repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilRegionMediaElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.dom.smil;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement;
import org.w3c.dom.smil.SMILRegionMediaElement;
public class SmilRegionMediaElementImpl extends SmilMediaElementImpl implements
SMILRegionMediaElement {
private SMILRegionElement mRegion;
SmilRegionMediaElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public SMILRegionElement getRegion() {
if (mRegion == null) {
SMILDocument doc = (SMILDocument)this.getOwnerDocument();
NodeList regions = doc.getLayout().getElementsByTagName("region");
SMILRegionElement region = null;
for (int i = 0; i < regions.getLength(); i++) {
region = (SMILRegionElement)regions.item(i);
if (region.getId().equals(this.getAttribute("region"))) {
mRegion = region;
}
}
}
return mRegion;
}
public void setRegion(SMILRegionElement region) {
this.setAttribute("region", region.getId());
mRegion = region;
}
}
| 1,830 | 32.907407 | 79 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/TimeListImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.dom.smil;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public class TimeListImpl implements TimeList {
private final ArrayList<Time> mTimes;
/*
* Internal Interface
*/
TimeListImpl(ArrayList<Time> times) {
mTimes = times;
}
/*
* TimeList Interface
*/
public int getLength() {
return mTimes.size();
}
public Time item(int index) {
Time time = null;
try {
time = mTimes.get(index);
} catch (IndexOutOfBoundsException e) {
// Do nothing and return null
}
return time;
}
}
| 1,340 | 23.833333 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.dom.smil;
import com.android.mms.dom.ElementImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILElement;
public class SmilElementImpl extends ElementImpl implements SMILElement {
/**
* This constructor is used by the factory methods of the SmilDocument.
*
* @param owner The SMIL document to which this element belongs to
* @param tagName The tag name of the element
*/
SmilElementImpl(SmilDocumentImpl owner, String tagName)
{
super(owner, tagName.toLowerCase());
}
public String getId() {
// TODO Auto-generated method stub
return null;
}
public void setId(String id) throws DOMException {
// TODO Auto-generated method stub
}
}
| 1,421 | 29.255319 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/ElementTimeContainerImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.dom.smil;
import org.w3c.dom.smil.ElementTimeContainer;
import org.w3c.dom.smil.SMILElement;
public abstract class ElementTimeContainerImpl extends ElementTimeImpl implements
ElementTimeContainer {
/*
* Internal Interface
*/
ElementTimeContainerImpl(SMILElement element) {
super(element);
}
}
| 1,015 | 28.882353 | 81 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/ElementParallelTimeContainerImpl.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* 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.mms.dom.smil;
import com.android.mms.dom.NodeListImpl;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import java.util.ArrayList;
public abstract class ElementParallelTimeContainerImpl extends ElementTimeContainerImpl
implements ElementParallelTimeContainer {
private final static String ENDSYNC_ATTRIBUTE_NAME = "endsync";
private final static String ENDSYNC_FIRST = "first";
private final static String ENDSYNC_LAST = "last";
private final static String ENDSYNC_ALL = "all";
private final static String ENDSYNC_MEDIA = "media";
/*
* Internal Interface
*/
ElementParallelTimeContainerImpl(SMILElement element) {
super(element);
}
public String getEndSync() {
String endsync = mSmilElement.getAttribute(ENDSYNC_ATTRIBUTE_NAME);
if ((endsync == null) || (endsync.length() == 0)) {
setEndSync(ENDSYNC_LAST);
return ENDSYNC_LAST;
}
if (ENDSYNC_FIRST.equals(endsync) || ENDSYNC_LAST.equals(endsync) ||
ENDSYNC_ALL.equals(endsync) || ENDSYNC_MEDIA.equals(endsync)) {
return endsync;
}
// FIXME add the checking for ID-Value and smil1.0-Id-value.
setEndSync(ENDSYNC_LAST);
return ENDSYNC_LAST;
}
public void setEndSync(String endSync) throws DOMException {
if (ENDSYNC_FIRST.equals(endSync) || ENDSYNC_LAST.equals(endSync) ||
ENDSYNC_ALL.equals(endSync) || ENDSYNC_MEDIA.equals(endSync)) {
mSmilElement.setAttribute(ENDSYNC_ATTRIBUTE_NAME, endSync);
} else { // FIXME add the support for ID-Value and smil1.0-Id-value.
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Unsupported endsync value" + endSync);
}
}
@Override
public float getDur() {
float dur = super.getDur();
if (dur == 0) {
dur = getImplicitDuration();
}
return dur;
}
public float getImplicitDuration() {
float dur = -1.0F;
if (ENDSYNC_LAST.equals(getEndSync())) {
NodeList children = getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
TimeList endTimeList = child.getEnd();
for (int j = 0; j < endTimeList.getLength(); ++j) {
Time endTime = endTimeList.item(j);
if (endTime.getTimeType() == Time.SMIL_TIME_INDEFINITE) {
// Return "indefinite" here.
return -1.0F;
}
if (endTime.getResolved()) {
float end = (float)endTime.getResolvedOffset();
dur = (end > dur) ? end : dur;
}
}
}
} // Other endsync types are not supported now.
return dur;
}
public NodeList getActiveChildrenAt(float instant) {
/*
* Find the closest Time of ElementTime before instant.
* Add ElementTime to list of active elements if the Time belongs to the begin-list,
* do not add it otherwise.
*/
ArrayList<Node> activeChildren = new ArrayList<Node>();
NodeList children = getTimeChildren();
int childrenLen = children.getLength();
for (int i = 0; i < childrenLen; ++i) {
double maxOffset = 0.0;
boolean active = false;
ElementTime child = (ElementTime) children.item(i);
TimeList beginList = child.getBegin();
int len = beginList.getLength();
for (int j = 0; j < len; ++j) {
Time begin = beginList.item(j);
if (begin.getResolved()) {
double resolvedOffset = begin.getResolvedOffset() * 1000.0;
if ((resolvedOffset <= instant) && (resolvedOffset >= maxOffset)) {
maxOffset = resolvedOffset;
active = true;
}
}
}
TimeList endList = child.getEnd();
len = endList.getLength();
for (int j = 0; j < len; ++j) {
Time end = endList.item(j);
if (end.getResolved()) {
double resolvedOffset = end.getResolvedOffset() * 1000.0;
if ((resolvedOffset <= instant) && (resolvedOffset >= maxOffset)) {
maxOffset = resolvedOffset;
active = false;
}
}
}
if (active) {
activeChildren.add((Node) child);
}
}
return new NodeListImpl(activeChildren);
}
}
| 5,725 | 35.941935 | 92 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilRefElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.dom.smil;
import org.w3c.dom.smil.SMILRefElement;
public class SmilRefElementImpl extends SmilRegionMediaElementImpl implements
SMILRefElement {
SmilRefElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
}
| 941 | 30.4 | 77 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilLayoutElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.dom.smil;
import com.android.mms.layout.LayoutManager;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.SMILRootLayoutElement;
public class SmilLayoutElementImpl extends SmilElementImpl implements
SMILLayoutElement {
SmilLayoutElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public boolean getResolved() {
// TODO Auto-generated method stub
return false;
}
public String getType() {
return this.getAttribute("type");
}
public NodeList getRegions() {
return this.getElementsByTagName("region");
}
public SMILRootLayoutElement getRootLayout() {
NodeList childNodes = this.getChildNodes();
SMILRootLayoutElement rootLayoutNode = null;
int childrenCount = childNodes.getLength();
for (int i = 0; i < childrenCount; i++) {
if (childNodes.item(i).getNodeName().equals("root-layout")) {
rootLayoutNode = (SMILRootLayoutElement)childNodes.item(i);
}
}
if (null == rootLayoutNode) {
// root-layout node is not set. Create a default one.
rootLayoutNode = (SMILRootLayoutElement) getOwnerDocument().createElement("root-layout");
rootLayoutNode.setWidth(LayoutManager.getInstance().getLayoutParameters().getWidth());
rootLayoutNode.setHeight(LayoutManager.getInstance().getLayoutParameters().getHeight());
appendChild(rootLayoutNode);
}
return rootLayoutNode;
}
}
| 2,269 | 34.46875 | 101 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/parser/SmilXmlSerializer.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.dom.smil.parser;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import timber.log.Timber;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class SmilXmlSerializer {
public static void serialize(SMILDocument smilDoc, OutputStream out) {
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 2048);
writeElement(writer, smilDoc.getDocumentElement());
writer.flush();
} catch (UnsupportedEncodingException e) {
Timber.e(e, "exception thrown");
} catch (IOException e) {
Timber.e(e, "exception thrown");
}
}
private static void writeElement(Writer writer, Element element)
throws IOException {
writer.write('<');
writer.write(element.getTagName());
if (element.hasAttributes()) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr)attributes.item(i);
writer.write(" " + attribute.getName());
writer.write("=\"" + attribute.getValue() + "\"");
}
}
// FIXME: Might throw ClassCastException
SMILElement childElement = (SMILElement) element.getFirstChild();
if (childElement != null) {
writer.write('>');
do {
writeElement(writer, childElement);
childElement = (SMILElement) childElement.getNextSibling();
} while (childElement != null);
writer.write("</");
writer.write(element.getTagName());
writer.write('>');
} else {
writer.write("/>");
}
}
}
| 2,628 | 31.060976 | 91 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/util/DownloadManager.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.util;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.widget.Toast;
import com.android.internal.telephony.TelephonyProperties;
import com.android.mms.service_alt.SystemPropertiesProxy;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.PduPersister;
import com.klinker.android.send_message.R;
import timber.log.Timber;
public class DownloadManager {
private static final boolean LOCAL_LOGV = false;
public static final int DEFERRED_MASK = 0x04;
public static final int STATE_UNKNOWN = 0x00;
public static final int STATE_UNSTARTED = 0x80;
public static final int STATE_DOWNLOADING = 0x81;
public static final int STATE_TRANSIENT_FAILURE = 0x82;
public static final int STATE_PERMANENT_FAILURE = 0x87;
public static final int STATE_PRE_DOWNLOADING = 0x88;
// TransactionService will skip downloading Mms if auto-download is off
public static final int STATE_SKIP_RETRYING = 0x89;
private final Context mContext;
private final Handler mHandler;
private final SharedPreferences mPreferences;
private boolean mAutoDownload;
private static DownloadManager sInstance;
private DownloadManager(Context context) {
mContext = context;
mHandler = new Handler(Looper.getMainLooper());
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
mAutoDownload = getAutoDownloadState(context, mPreferences);
if (LOCAL_LOGV) {
Timber.v("mAutoDownload ------> " + mAutoDownload);
}
}
public boolean isAuto() {
return mAutoDownload;
}
public static void init(Context context) {
if (LOCAL_LOGV) {
Timber.v("DownloadManager.init()");
}
if (sInstance != null) {
Timber.w("Already initialized.");
}
sInstance = new DownloadManager(context);
}
public static DownloadManager getInstance() {
if (sInstance == null) {
throw new IllegalStateException("Uninitialized.");
}
return sInstance;
}
static boolean getAutoDownloadState(Context context, SharedPreferences prefs) {
return getAutoDownloadState(prefs, isRoaming(context));
}
static boolean getAutoDownloadState(SharedPreferences prefs, boolean roaming) {
boolean autoDownload = prefs.getBoolean("auto_download_mms", true);
if (LOCAL_LOGV) {
Timber.v("auto download without roaming -> " + autoDownload);
}
if (autoDownload) {
boolean alwaysAuto = true;
if (LOCAL_LOGV) {
Timber.v("auto download during roaming -> " + alwaysAuto);
}
if (!roaming || alwaysAuto) {
return true;
}
}
return false;
}
static boolean isRoaming(Context context) {
// TODO: fix and put in Telephony layer
String roaming = SystemPropertiesProxy.get(context,
TelephonyProperties.PROPERTY_OPERATOR_ISROAMING, null);
if (LOCAL_LOGV) {
Timber.v("roaming ------> " + roaming);
}
return "true".equals(roaming);
}
public void markState(final Uri uri, int state) {
// Notify user if the message has expired.
try {
NotificationInd nInd = (NotificationInd) PduPersister.getPduPersister(mContext)
.load(uri);
if ((nInd.getExpiry() < System.currentTimeMillis() / 1000L)
&& (state == STATE_DOWNLOADING || state == STATE_PRE_DOWNLOADING)) {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(mContext, R.string.service_message_not_found,
Toast.LENGTH_LONG).show();
}
});
SqliteWrapper.delete(mContext, mContext.getContentResolver(), uri, null, null);
return;
}
} catch(MmsException e) {
Timber.e(e, e.getMessage());
return;
}
// Notify user if downloading permanently failed.
if (state == STATE_PERMANENT_FAILURE) {
mHandler.post(new Runnable() {
public void run() {
try {
Toast.makeText(mContext, getMessage(uri),
Toast.LENGTH_LONG).show();
} catch (MmsException e) {
Timber.e(e, e.getMessage());
}
}
});
} else if (!mAutoDownload) {
state |= DEFERRED_MASK;
}
// Use the STATUS field to store the state of downloading process
// because it's useless for M-Notification.ind.
ContentValues values = new ContentValues(1);
values.put(Mms.STATUS, state);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null);
}
public void showErrorCodeToast(int errorStr) {
final int errStr = errorStr;
mHandler.post(new Runnable() {
public void run() {
try {
Toast.makeText(mContext, errStr, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Timber.e("Caught an exception in showErrorCodeToast");
}
}
});
}
private String getMessage(Uri uri) throws MmsException {
NotificationInd ind = (NotificationInd) PduPersister
.getPduPersister(mContext).load(uri);
EncodedStringValue v = ind.getSubject();
String subject = (v != null) ? v.getString()
: mContext.getString(R.string.no_subject);
String from = mContext.getString(R.string.unknown_sender);
return mContext.getString(R.string.dl_failure_notification, subject, from);
}
public int getState(Uri uri) {
Cursor cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(),
uri, new String[] {Mms.STATUS}, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int state = cursor.getInt(0) & ~DEFERRED_MASK;
cursor.close();
return state;
}
} finally {
cursor.close();
}
}
return STATE_UNSTARTED;
}
}
| 7,605 | 34.050691 | 95 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/util/SendingProgressTokenManager.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.util;
import timber.log.Timber;
import java.util.HashMap;
public class SendingProgressTokenManager {
private static final boolean LOCAL_LOGV = false;
private static final HashMap<Object, Long> TOKEN_POOL;
public static final long NO_TOKEN = -1L;
static {
TOKEN_POOL = new HashMap<Object, Long>();
}
synchronized public static long get(Object key) {
Long token = TOKEN_POOL.get(key);
if (LOCAL_LOGV) {
Timber.v("TokenManager.get(" + key + ") -> " + token);
}
return token != null ? token : NO_TOKEN;
}
synchronized public static void put(Object key, long token) {
if (LOCAL_LOGV) {
Timber.v("TokenManager.put(" + key + ", " + token + ")");
}
TOKEN_POOL.put(key, token);
}
synchronized public static void remove(Object key) {
if (LOCAL_LOGV) {
Timber.v("TokenManager.remove(" + key + ")");
}
TOKEN_POOL.remove(key);
}
}
| 1,616 | 28.4 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/util/RateController.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.util;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.provider.Telephony.Mms.Rate;
import timber.log.Timber;
public class RateController {
private static final boolean LOCAL_LOGV = false;
private static final int RATE_LIMIT = 100;
private static final long ONE_HOUR = 1000 * 60 * 60;
private static final int NO_ANSWER = 0;
private static final int ANSWER_YES = 1;
private static final int ANSWER_NO = 2;
public static final int ANSWER_TIMEOUT = 20000;
public static final String RATE_LIMIT_SURPASSED_ACTION =
"com.android.mms.RATE_LIMIT_SURPASSED";
public static final String RATE_LIMIT_CONFIRMED_ACTION =
"com.android.mms.RATE_LIMIT_CONFIRMED";
private static RateController sInstance;
private static boolean sMutexLock;
private final Context mContext;
private int mAnswer;
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (LOCAL_LOGV) {
Timber.v("Intent received: " + intent);
}
if (RATE_LIMIT_CONFIRMED_ACTION.equals(intent.getAction())) {
synchronized (this) {
mAnswer = intent.getBooleanExtra("answer", false)
? ANSWER_YES : ANSWER_NO;
notifyAll();
}
}
}
};
private RateController(Context context) {
mContext = context;
}
public static void init(Context context) {
if (LOCAL_LOGV) {
Timber.v("RateController.init()");
}
if (sInstance != null) {
Timber.w("Already initialized.");
return;
}
sInstance = new RateController(context);
}
public static RateController getInstance() {
if (sInstance == null) {
throw new IllegalStateException("Uninitialized.");
}
return sInstance;
}
public final void update() {
ContentValues values = new ContentValues(1);
values.put(Rate.SENT_TIME, System.currentTimeMillis());
SqliteWrapper.insert(mContext, mContext.getContentResolver(),
Rate.CONTENT_URI, values);
}
public final boolean isLimitSurpassed() {
long oneHourAgo = System.currentTimeMillis() - ONE_HOUR;
Cursor c = SqliteWrapper.query(mContext, mContext.getContentResolver(),
Rate.CONTENT_URI, new String[] { "COUNT(*) AS rate" },
Rate.SENT_TIME + ">" + oneHourAgo, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
boolean limit = c.getInt(0) >= RATE_LIMIT;
c.close();
return limit;
}
} finally {
c.close();
}
}
return false;
}
synchronized public boolean isAllowedByUser() {
while (sMutexLock) {
try {
wait();
} catch (InterruptedException e) {
// Ignore it.
}
}
sMutexLock = true;
mContext.registerReceiver(mBroadcastReceiver,
new IntentFilter(RATE_LIMIT_CONFIRMED_ACTION));
mAnswer = NO_ANSWER;
try {
Intent intent = new Intent(RATE_LIMIT_SURPASSED_ACTION);
// Using NEW_TASK here is necessary because we're calling
// startActivity from outside an activity.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
return waitForAnswer() == ANSWER_YES;
} finally {
mContext.unregisterReceiver(mBroadcastReceiver);
sMutexLock = false;
notifyAll();
}
}
synchronized private int waitForAnswer() {
for (int t = 0; (mAnswer == NO_ANSWER) && (t < ANSWER_TIMEOUT); t += 1000) {
try {
if (LOCAL_LOGV) {
Timber.v("Waiting for answer..." + t / 1000);
}
wait(1000L);
} catch (InterruptedException e) {
// Ignore it.
}
}
return mAnswer;
}
}
| 5,157 | 31.440252 | 84 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/layout/HVGALayoutParameters.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.layout;
import android.content.Context;
import timber.log.Timber;
public class HVGALayoutParameters implements LayoutParameters {
private static final boolean LOCAL_LOGV = false;
private int mType = -1;
private static int mImageHeightLandscape;
private static int mTextHeightLandscape;
private static int mImageHeightPortrait;
private static int mTextHeightPortrait;
private static int mMaxHeight;
private static int mMaxWidth;
public HVGALayoutParameters(Context context, int type) {
if ((type != HVGA_LANDSCAPE) && (type != HVGA_PORTRAIT)) {
throw new IllegalArgumentException(
"Bad layout type detected: " + type);
}
if (LOCAL_LOGV) {
Timber.v("HVGALayoutParameters.<init>(" + type + ").");
}
mType = type;
float scale = context.getResources().getDisplayMetrics().density;
mMaxWidth = (int) (context.getResources().getConfiguration().screenWidthDp * scale + 0.5f);
mMaxHeight =
(int) (context.getResources().getConfiguration().screenHeightDp * scale + 0.5f);
mImageHeightLandscape = (int) (mMaxHeight * .90f);
mTextHeightLandscape = (int) (mMaxHeight * .10f);
mImageHeightPortrait = (int) (mMaxWidth * .90f);
mTextHeightPortrait = (int) (mMaxWidth * .10f);
if (LOCAL_LOGV) {
Timber.v("HVGALayoutParameters mMaxWidth: " + mMaxWidth +
" mMaxHeight: " + mMaxHeight +
" mImageHeightLandscape: " + mImageHeightLandscape +
" mTextHeightLandscape: " + mTextHeightLandscape +
" mImageHeightPortrait: " + mImageHeightPortrait +
" mTextHeightPortrait: " + mTextHeightPortrait);
}
}
public int getWidth() {
return mType == HVGA_LANDSCAPE ? mMaxWidth
: mMaxHeight;
}
public int getHeight() {
return mType == HVGA_LANDSCAPE ? mMaxHeight
: mMaxWidth;
}
public int getImageHeight() {
return mType == HVGA_LANDSCAPE ? mImageHeightLandscape
: mImageHeightPortrait;
}
public int getTextHeight() {
return mType == HVGA_LANDSCAPE ? mTextHeightLandscape
: mTextHeightPortrait;
}
public int getType() {
return mType;
}
public String getTypeDescription() {
return mType == HVGA_LANDSCAPE ? "HVGA-L" : "HVGA-P";
}
}
| 3,205 | 33.106383 | 99 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/layout/LayoutParameters.java | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* 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.mms.layout;
public interface LayoutParameters {
/* Layouts type definition */
public static final int UNKNOWN = -1;
public static final int HVGA_LANDSCAPE = 10;
public static final int HVGA_PORTRAIT = 11;
/* Parameters for known layouts */
public static final int HVGA_LANDSCAPE_WIDTH = 480;
public static final int HVGA_LANDSCAPE_HEIGHT = 320;
public static final int HVGA_PORTRAIT_WIDTH = 320;
public static final int HVGA_PORTRAIT_HEIGHT = 480;
/**
* Get the width of current layout.
*/
int getWidth();
/**
* Get the height of current layout.
*/
int getHeight();
/**
* Get the width of the image region of current layout.
*/
int getImageHeight();
/**
* Get the height of the text region of current layout.
*/
int getTextHeight();
/**
* Get the type of current layout.
*/
int getType();
/**
* Get the type description of current layout.
*/
String getTypeDescription();
}
| 1,708 | 28.982456 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/layout/LayoutManager.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.layout;
import android.content.Context;
import android.content.res.Configuration;
import timber.log.Timber;
/**
* MMS presentation layout management.
*/
public class LayoutManager {
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
private final Context mContext;
private LayoutParameters mLayoutParams;
private static LayoutManager sInstance;
private LayoutManager(Context context) {
mContext = context;
initLayoutParameters(context.getResources().getConfiguration());
}
private void initLayoutParameters(Configuration configuration) {
mLayoutParams = getLayoutParameters(
configuration.orientation == Configuration.ORIENTATION_PORTRAIT
? LayoutParameters.HVGA_PORTRAIT
: LayoutParameters.HVGA_LANDSCAPE);
if (LOCAL_LOGV) {
Timber.v("LayoutParameters: " + mLayoutParams.getTypeDescription()
+ ": " + mLayoutParams.getWidth() + "x" + mLayoutParams.getHeight());
}
}
private LayoutParameters getLayoutParameters(int displayType) {
switch (displayType) {
case LayoutParameters.HVGA_LANDSCAPE:
return new HVGALayoutParameters(mContext, LayoutParameters.HVGA_LANDSCAPE);
case LayoutParameters.HVGA_PORTRAIT:
return new HVGALayoutParameters(mContext, LayoutParameters.HVGA_PORTRAIT);
}
throw new IllegalArgumentException(
"Unsupported display type: " + displayType);
}
public static void init(Context context) {
if (LOCAL_LOGV) {
Timber.v("DefaultLayoutManager.init()");
}
if (sInstance != null) {
Timber.w("Already initialized.");
}
sInstance = new LayoutManager(context);
}
public static LayoutManager getInstance() {
if (sInstance == null) {
throw new IllegalStateException("Uninitialized.");
}
return sInstance;
}
public void onConfigurationChanged(Configuration newConfig) {
if (LOCAL_LOGV) {
Timber.v("-> LayoutManager.onConfigurationChanged().");
}
initLayoutParameters(newConfig);
}
public int getLayoutType() {
return mLayoutParams.getType();
}
public int getLayoutWidth() {
return mLayoutParams.getWidth();
}
public int getLayoutHeight() {
return mLayoutParams.getHeight();
}
public LayoutParameters getLayoutParameters() {
return mLayoutParams;
}
}
| 3,223 | 29.704762 | 91 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/MmsConfigManager.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.util.ArrayMap;
import timber.log.Timber;
import java.util.List;
import java.util.Map;
/**
* This class manages cached copies of all the MMS configuration for each subscription ID.
* A subscription ID loosely corresponds to a particular SIM. See the
* {@link SubscriptionManager} for more details.
*
*/
public class MmsConfigManager {
private static volatile MmsConfigManager sInstance = new MmsConfigManager();
public static MmsConfigManager getInstance() {
return sInstance;
}
// Map the various subIds to their corresponding MmsConfigs.
private final Map<Integer, MmsConfig> mSubIdConfigMap;
private Context mContext;
private SubscriptionManager mSubscriptionManager;
private MmsConfigManager() {
mSubIdConfigMap = new ArrayMap<Integer, MmsConfig>();
}
/**
* This receiver listens for changes made to SubInfoRecords and for a broadcast telling us
* the TelephonyManager has loaded the information needed in order to get the mcc/mnc's for
* each subscription Id. When either of these broadcasts are received, we rebuild the
* MmsConfig table.
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Timber.i("mReceiver action: " + action);
if (action.equals("LOADED")) {
loadInBackground();
}
}
};
public void init(final Context context) {
mContext = context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
mSubscriptionManager = SubscriptionManager.from(context);
// TODO: When this object "finishes" we should unregister.
IntentFilter intentFilterLoaded =
new IntentFilter("LOADED");
try {
context.registerReceiver(mReceiver, intentFilterLoaded);
} catch (Exception e) {
}
load(context);
} else {
load(context);
}
// TODO: When this object "finishes" we should unregister by invoking
// SubscriptionManager.getInstance(mContext).unregister(mOnSubscriptionsChangedListener);
// This is not strictly necessary because it will be unregistered if the
// notification fails but it is good form.
// Register for SubscriptionInfo list changes which is guaranteed
// to invoke onSubscriptionsChanged the first time.
// SubscriptionManager.from(mContext).addOnSubscriptionsChangedListener(
// new OnSubscriptionsChangedListener() {
// @Override
// public void onSubscriptionsChanged() {
// loadInBackground();
// }
// });
}
private void loadInBackground() {
// TODO (ywen) - AsyncTask to avoid creating a new thread?
new Thread() {
@Override
public void run() {
Configuration configuration = mContext.getResources().getConfiguration();
// Always put the mnc/mcc in the log so we can tell which mms_config.xml
// was loaded.
Timber.i("MmsConfigManager.loadInBackground(): mcc/mnc: " +
configuration.mcc + "/" + configuration.mnc);
load(mContext);
}
}.start();
}
/**
* Find and return the MmsConfig for a particular subscription id.
*
* @param subId Subscription id of the desired MmsConfig
* @return MmsConfig for the particular subscription id. This function can return null if
* the MmsConfig cannot be found or if this function is called before the
* TelephonyManager has setup the SIMs or if loadInBackground is still spawning a
* thread after a recent LISTEN_SUBSCRIPTION_INFO_LIST_CHANGED event.
*/
public MmsConfig getMmsConfigBySubId(int subId) {
MmsConfig mmsConfig;
synchronized(mSubIdConfigMap) {
mmsConfig = mSubIdConfigMap.get(subId);
}
Timber.i("getMmsConfigBySubId -- for sub: " + subId + " mmsConfig: " + mmsConfig);
return mmsConfig;
}
public MmsConfig getMmsConfig() {
return new MmsConfig(mContext);
}
/**
* This function goes through all the activated subscription ids (the actual SIMs in the
* device), builds a context with that SIM's mcc/mnc and loads the appropriate mms_config.xml
* file via the ResourceManager. With single-SIM devices, there will be a single subId.
*
*/
private void load(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
List<SubscriptionInfo> subs = mSubscriptionManager.getActiveSubscriptionInfoList();
if (subs == null || subs.size() < 1) {
Timber.e("MmsConfigManager.load -- empty getActiveSubInfoList");
return;
}
// Load all the mms_config.xml files in a separate map and then swap with the
// real map at the end so we don't block anyone sync'd on the real map.
final Map<Integer, MmsConfig> newConfigMap = new ArrayMap<Integer, MmsConfig>();
for (SubscriptionInfo sub : subs) {
Configuration configuration = new Configuration();
if (sub.getMcc() == 0 && sub.getMnc() == 0) {
Configuration config = mContext.getResources().getConfiguration();
configuration.mcc = config.mcc;
configuration.mnc = config.mnc;
Timber.i("MmsConfigManager.load -- no mcc/mnc for sub: " + sub +
" using mcc/mnc from main context: " + configuration.mcc + "/" +
configuration.mnc);
} else {
Timber.i("MmsConfigManager.load -- mcc/mnc for sub: " + sub);
configuration.mcc = sub.getMcc();
configuration.mnc = sub.getMnc();
}
Context subContext = context.createConfigurationContext(configuration);
int subId = sub.getSubscriptionId();
newConfigMap.put(subId, new MmsConfig(subContext, subId));
}
synchronized (mSubIdConfigMap) {
mSubIdConfigMap.clear();
mSubIdConfigMap.putAll(newConfigMap);
}
}
}
}
| 7,522 | 38.387435 | 97 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/MmsConfigXmlProcessor.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.content.ContentValues;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import timber.log.Timber;
import java.io.IOException;
/*
* XML processor for mms_config.xml
*/
public class MmsConfigXmlProcessor {
public interface MmsConfigHandler {
public void process(String key, String value, String type);
}
private static final String TAG_MMS_CONFIG = "mms_config";
// Handler to process one mms_config key/value pair
private MmsConfigHandler mMmsConfigHandler;
private final StringBuilder mLogStringBuilder = new StringBuilder();
private final XmlPullParser mInputParser;
private MmsConfigXmlProcessor(XmlPullParser parser) {
mInputParser = parser;
mMmsConfigHandler = null;
}
public static MmsConfigXmlProcessor get(XmlPullParser parser) {
return new MmsConfigXmlProcessor(parser);
}
public MmsConfigXmlProcessor setMmsConfigHandler(MmsConfigHandler handler) {
mMmsConfigHandler = handler;
return this;
}
/**
* Move XML parser forward to next event type or the end of doc
*
* @param eventType
* @return The final event type we meet
* @throws XmlPullParserException
* @throws IOException
*/
private int advanceToNextEvent(int eventType) throws XmlPullParserException, IOException {
for (;;) {
int nextEvent = mInputParser.next();
if (nextEvent == eventType
|| nextEvent == XmlPullParser.END_DOCUMENT) {
return nextEvent;
}
}
}
public void process() {
try {
// Find the first element
if (advanceToNextEvent(XmlPullParser.START_TAG) != XmlPullParser.START_TAG) {
throw new XmlPullParserException("MmsConfigXmlProcessor: expecting start tag @"
+ xmlParserDebugContext());
}
// A single ContentValues object for holding the parsing result of
// an apn element
final ContentValues values = new ContentValues();
String tagName = mInputParser.getName();
// Top level tag can be "apns" (apns.xml, or APN OTA XML)
// or "mms_config" (mms_config.xml)
if (TAG_MMS_CONFIG.equals(tagName)) {
// mms_config.xml resource
processMmsConfig();
}
} catch (IOException e) {
Timber.e(e, "MmsConfigXmlProcessor: I/O failure " + e);
} catch (XmlPullParserException e) {
Timber.e(e, "MmsConfigXmlProcessor: parsing failure " + e);
}
}
private static String xmlParserEventString(int event) {
switch (event) {
case XmlPullParser.START_DOCUMENT: return "START_DOCUMENT";
case XmlPullParser.END_DOCUMENT: return "END_DOCUMENT";
case XmlPullParser.START_TAG: return "START_TAG";
case XmlPullParser.END_TAG: return "END_TAG";
case XmlPullParser.TEXT: return "TEXT";
}
return Integer.toString(event);
}
/**
* @return The debugging information of the parser's current position
*/
private String xmlParserDebugContext() {
mLogStringBuilder.setLength(0);
if (mInputParser != null) {
try {
final int eventType = mInputParser.getEventType();
mLogStringBuilder.append(xmlParserEventString(eventType));
if (eventType == XmlPullParser.START_TAG
|| eventType == XmlPullParser.END_TAG
|| eventType == XmlPullParser.TEXT) {
mLogStringBuilder.append('<').append(mInputParser.getName());
for (int i = 0; i < mInputParser.getAttributeCount(); i++) {
mLogStringBuilder.append(' ')
.append(mInputParser.getAttributeName(i))
.append('=')
.append(mInputParser.getAttributeValue(i));
}
mLogStringBuilder.append("/>");
}
return mLogStringBuilder.toString();
} catch (XmlPullParserException e) {
Timber.e(e, "xmlParserDebugContext: " + e);
}
}
return "Unknown";
}
/**
* Process one mms_config.
*
* @throws IOException
* @throws XmlPullParserException
*/
private void processMmsConfig()
throws IOException, XmlPullParserException {
// We are at the start tag
for (;;) {
int nextEvent;
// Skipping spaces
while ((nextEvent = mInputParser.next()) == XmlPullParser.TEXT);
if (nextEvent == XmlPullParser.START_TAG) {
// Parse one mms config key/value
processMmsConfigKeyValue();
} else if (nextEvent == XmlPullParser.END_TAG) {
break;
} else {
throw new XmlPullParserException("MmsConfig: expecting start or end tag @"
+ xmlParserDebugContext());
}
}
}
/**
* Process one mms_config key/value pair
*
* @throws IOException
* @throws XmlPullParserException
*/
private void processMmsConfigKeyValue() throws IOException, XmlPullParserException {
final String key = mInputParser.getAttributeValue(null, "name");
// We are at the start tag, the name of the tag is the type
// e.g. <int name="key">value</int>
final String type = mInputParser.getName();
int nextEvent = mInputParser.next();
String value = null;
if (nextEvent == XmlPullParser.TEXT) {
value = mInputParser.getText();
nextEvent = mInputParser.next();
}
if (nextEvent != XmlPullParser.END_TAG) {
throw new XmlPullParserException("MmsConfigXmlProcessor: expecting end tag @"
+ xmlParserDebugContext());
}
if (MmsConfig.isValidKey(key, type)) {
// We are done parsing one mms_config key/value, call the handler
if (mMmsConfigHandler != null) {
mMmsConfigHandler.process(key, value, type);
}
} else {
Timber.w("MmsConfig: invalid key=" + key + " or type=" + type);
}
}
}
| 7,090 | 35.178571 | 95 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/DownloadRequest.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.provider.Telephony;
import android.text.TextUtils;
import com.android.mms.service_alt.exception.MmsHttpException;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.google.android.mms.util_alt.SqliteWrapper;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Transaction;
import timber.log.Timber;
/**
* Request to download an MMS
*/
public class DownloadRequest extends MmsRequest {
private static final String LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?";
static final String[] PROJECTION = new String[]{
Telephony.Mms.CONTENT_LOCATION
};
// The indexes of the columns which must be consistent with above PROJECTION.
static final int COLUMN_CONTENT_LOCATION = 0;
private final String mLocationUrl;
private final PendingIntent mDownloadedIntent;
private final Uri mContentUri;
public DownloadRequest(RequestManager manager, int subId, String locationUrl,
Uri contentUri, PendingIntent downloadedIntent, String creator,
Bundle configOverrides, Context context) throws MmsException {
super(manager, subId, creator, configOverrides);
if (locationUrl == null) {
mLocationUrl = getContentLocation(context, contentUri);
} else {
mLocationUrl = locationUrl;
}
mDownloadedIntent = downloadedIntent;
mContentUri = contentUri;
}
@Override
protected byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException {
final MmsHttpClient mmsHttpClient = netMgr.getOrCreateHttpClient();
if (mmsHttpClient == null) {
Timber.e("MMS network is not ready!");
throw new MmsHttpException(0/*statusCode*/, "MMS network is not ready");
}
return mmsHttpClient.execute(
mLocationUrl,
null/*pud*/,
MmsHttpClient.METHOD_GET,
apn.isProxySet(),
apn.getProxyAddress(),
apn.getProxyPort(),
mMmsConfig);
}
@Override
protected PendingIntent getPendingIntent() {
return mDownloadedIntent;
}
@Override
protected int getQueueType() {
return 1;
}
@Override
protected Uri persistIfRequired(Context context, int result, byte[] response) {
if (!mRequestManager.getAutoPersistingPref()) {
notifyOfDownload(context);
return null;
}
return persist(context, response, mMmsConfig, mLocationUrl, mSubId, mCreator);
}
public static Uri persist(Context context, byte[] response, MmsConfig.Overridden mmsConfig,
String locationUrl, int subId, String creator) {
// Let any mms apps running as secondary user know that a new mms has been downloaded.
notifyOfDownload(context);
Timber.d("DownloadRequest.persistIfRequired");
if (response == null || response.length < 1) {
Timber.e("DownloadRequest.persistIfRequired: empty response");
// Update the retrieve status of the NotificationInd
final ContentValues values = new ContentValues(1);
values.put(Telephony.Mms.RETRIEVE_STATUS, PduHeaders.RETRIEVE_STATUS_ERROR_END);
SqliteWrapper.update(
context,
context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
values,
LOCATION_SELECTION,
new String[]{
Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
locationUrl
});
return null;
}
final long identity = Binder.clearCallingIdentity();
try {
final GenericPdu pdu =
(new PduParser(response, mmsConfig.getSupportMmsContentDisposition())).parse();
if (pdu == null || !(pdu instanceof RetrieveConf)) {
Timber.e("DownloadRequest.persistIfRequired: invalid parsed PDU");
// Update the error type of the NotificationInd
setErrorType(context, locationUrl, Telephony.MmsSms.ERR_TYPE_MMS_PROTO_PERMANENT);
return null;
}
final RetrieveConf retrieveConf = (RetrieveConf) pdu;
final int status = retrieveConf.getRetrieveStatus();
// if (status != PduHeaders.RETRIEVE_STATUS_OK) {
// Timber.e("DownloadRequest.persistIfRequired: retrieve failed "
// + status);
// // Update the retrieve status of the NotificationInd
// final ContentValues values = new ContentValues(1);
// values.put(Telephony.Mms.RETRIEVE_STATUS, status);
// SqliteWrapper.update(
// context,
// context.getContentResolver(),
// Telephony.Mms.CONTENT_URI,
// values,
// LOCATION_SELECTION,
// new String[]{
// Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
// mLocationUrl
// });
// return null;
// }
// Store the downloaded message
final PduPersister persister = PduPersister.getPduPersister(context);
final Uri messageUri = persister.persist(pdu, Telephony.Mms.Inbox.CONTENT_URI, PduPersister.DUMMY_THREAD_ID, true, true, null);
if (messageUri == null) {
Timber.e("DownloadRequest.persistIfRequired: can not persist message");
return null;
}
// Update some of the properties of the message
final ContentValues values = new ContentValues();
values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
try {
values.put(Telephony.Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) {
}
values.put(Telephony.Mms.READ, 0);
values.put(Telephony.Mms.SEEN, 0);
if (!TextUtils.isEmpty(creator)) {
values.put(Telephony.Mms.CREATOR, creator);
}
if (SubscriptionIdChecker.getInstance(context).canUseSubscriptionId()) {
values.put(Telephony.Mms.SUBSCRIPTION_ID, subId);
}
try {
context.getContentResolver().update(messageUri, values, null, null);
} catch (SQLiteException e) {
// On MIUI and a couple other devices, the above call will fail and say `no such column: sub_id`
// If before making that call, we check to see if the sub_id column is available for messageUri, we will
// find that it is available, and yet the update call will still fail. So - there's no way we can know
// in advance that it will fail, and we have to just try again
if (values.containsKey(Telephony.Mms.SUBSCRIPTION_ID)) {
values.remove(Telephony.Mms.SUBSCRIPTION_ID);
context.getContentResolver().update(messageUri, values, null, null);
} else {
throw e;
}
}
// Delete the corresponding NotificationInd
SqliteWrapper.delete(context, context.getContentResolver(), Telephony.Mms.CONTENT_URI, LOCATION_SELECTION,
new String[]{Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND), locationUrl});
return messageUri;
} catch (MmsException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not persist message");
} catch (SQLiteException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not update message");
} catch (RuntimeException e) {
Timber.e(e, "DownloadRequest.persistIfRequired: can not parse response");
} finally {
Binder.restoreCallingIdentity(identity);
}
return null;
}
private static void notifyOfDownload(Context context) {
BroadcastUtils.sendExplicitBroadcast(context, new Intent(), Transaction.NOTIFY_OF_MMS);
// TODO, not sure what this is doing... sending a broadcast that
// the download has finished from a specific user account I believe.
// final Intent intent = new Intent("android.provider.Telephony.MMS_DOWNLOADED");
// intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
//
// // Get a list of currently started users.
// int[] users = null;
// try {
// users = ActivityManagerNative.getDefault().getRunningUserIds();
// } catch (RemoteException re) {
// }
// if (users == null) {
// users = new int[] {UserHandle.ALL.getIdentifier()};
// }
// final UserManager userManager =
// (UserManager) context.getSystemService(Context.USER_SERVICE);
//
// // Deliver the broadcast only to those running users that are permitted
// // by user policy.
// for (int i = users.length - 1; i >= 0; i--) {
// UserHandle targetUser = new UserHandle(users[i]);
// if (users[i] != UserHandle.USER_OWNER) {
// // Is the user not allowed to use SMS?
// if (userManager.hasUserRestriction(UserManager.DISALLOW_SMS, targetUser)) {
// continue;
// }
// // Skip unknown users and managed profiles as well
// UserInfo info = userManager.getUserInfo(users[i]);
// if (info == null || info.isManagedProfile()) {
// continue;
// }
// }
// context.sendOrderedBroadcastAsUser(intent, targetUser,
// android.Manifest.permission.RECEIVE_MMS,
// 18,
// null,
// null, Activity.RESULT_OK, null, null);
// }
}
/**
* Transfer the received response to the caller (for download requests write to content uri)
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
*/
@Override
protected boolean transferResponse(Intent fillIn, final byte[] response) {
return mRequestManager.writePduToContentUri(mContentUri, response);
}
@Override
protected boolean prepareForHttpRequest() {
return true;
}
/**
* Try downloading via the carrier app.
*
* @param context The context
* @param carrierMessagingServicePackage The carrier messaging service handling the download
*/
public void tryDownloadingByCarrierApp(Context context, String carrierMessagingServicePackage) {
// final CarrierDownloadManager carrierDownloadManger = new CarrierDownloadManager();
// final CarrierDownloadCompleteCallback downloadCallback =
// new CarrierDownloadCompleteCallback(context, carrierDownloadManger);
// carrierDownloadManger.downloadMms(context, carrierMessagingServicePackage,
// downloadCallback);
}
@Override
protected void revokeUriPermission(Context context) {
context.revokeUriPermission(mContentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
private String getContentLocation(Context context, Uri uri)
throws MmsException {
Cursor cursor = android.database.sqlite.SqliteWrapper.query(context, context.getContentResolver(),
uri, PROJECTION, null, null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
String location = cursor.getString(COLUMN_CONTENT_LOCATION);
cursor.close();
return location;
}
} finally {
cursor.close();
}
}
throw new MmsException("Cannot get X-Mms-Content-Location from: " + uri);
}
private static Long getId(Context context, String location) {
String selection = Telephony.Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[]{location};
Cursor c = android.database.sqlite.SqliteWrapper.query(
context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI, new String[]{Telephony.Mms._ID},
selection, selectionArgs, null);
if (c != null) {
try {
if (c.moveToFirst()) {
return c.getLong(c.getColumnIndex(Telephony.Mms._ID));
}
} finally {
c.close();
}
}
return null;
}
private static void setErrorType(Context context, String locationUrl, int errorType) {
Long msgId = getId(context, locationUrl);
if (msgId == null) {
return;
}
Uri.Builder uriBuilder = Telephony.MmsSms.PendingMessages.CONTENT_URI.buildUpon();
uriBuilder.appendQueryParameter("protocol", "mms");
uriBuilder.appendQueryParameter("message", String.valueOf(msgId));
Cursor cursor = android.database.sqlite.SqliteWrapper.query(context, context.getContentResolver(),
uriBuilder.build(), null, null, null, null);
if (cursor == null) {
return;
}
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
ContentValues values = new ContentValues();
values.put(Telephony.MmsSms.PendingMessages.ERROR_TYPE, errorType);
int columnIndex = cursor.getColumnIndexOrThrow(
Telephony.MmsSms.PendingMessages._ID);
long id = cursor.getLong(columnIndex);
android.database.sqlite.SqliteWrapper.update(context, context.getContentResolver(),
Telephony.MmsSms.PendingMessages.CONTENT_URI,
values, Telephony.MmsSms.PendingMessages._ID + "=" + id, null);
}
} finally {
cursor.close();
}
}
}
| 15,683 | 40.602122 | 139 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/ApnSettings.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.NetworkUtilsHelper;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.text.TextUtils;
import com.android.mms.service_alt.exception.ApnException;
import timber.log.Timber;
import java.net.URI;
import java.net.URISyntaxException;
/**
* APN settings used for MMS transactions
*/
public class ApnSettings {
// MMSC URL
private final String mServiceCenter;
// MMSC proxy address
private final String mProxyAddress;
// MMSC proxy port
private final int mProxyPort;
// Debug text for this APN: a concatenation of interesting columns of this APN
private final String mDebugText;
private static final String[] APN_PROJECTION = {
Telephony.Carriers.TYPE,
Telephony.Carriers.MMSC,
Telephony.Carriers.MMSPROXY,
Telephony.Carriers.MMSPORT,
Telephony.Carriers.NAME,
Telephony.Carriers.APN,
Telephony.Carriers.BEARER,
Telephony.Carriers.PROTOCOL,
Telephony.Carriers.ROAMING_PROTOCOL,
Telephony.Carriers.AUTH_TYPE,
Telephony.Carriers.MVNO_TYPE,
Telephony.Carriers.MVNO_MATCH_DATA,
Telephony.Carriers.PROXY,
Telephony.Carriers.PORT,
Telephony.Carriers.SERVER,
Telephony.Carriers.USER,
Telephony.Carriers.PASSWORD,
};
private static final int COLUMN_TYPE = 0;
private static final int COLUMN_MMSC = 1;
private static final int COLUMN_MMSPROXY = 2;
private static final int COLUMN_MMSPORT = 3;
private static final int COLUMN_NAME = 4;
private static final int COLUMN_APN = 5;
private static final int COLUMN_BEARER = 6;
private static final int COLUMN_PROTOCOL = 7;
private static final int COLUMN_ROAMING_PROTOCOL = 8;
private static final int COLUMN_AUTH_TYPE = 9;
private static final int COLUMN_MVNO_TYPE = 10;
private static final int COLUMN_MVNO_MATCH_DATA = 11;
private static final int COLUMN_PROXY = 12;
private static final int COLUMN_PORT = 13;
private static final int COLUMN_SERVER = 14;
private static final int COLUMN_USER = 15;
private static final int COLUMN_PASSWORD = 16;
/**
* Load APN settings from system
*
* @param context
* @param apnName the optional APN name to match
*/
public static ApnSettings load(Context context, String apnName, int subId)
throws ApnException {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String mmsc = sharedPrefs.getString("mmsc_url", "");
if (!TextUtils.isEmpty(mmsc)) {
String mmsProxy = sharedPrefs.getString("mms_proxy", "");
String mmsPort = sharedPrefs.getString("mms_port", "");
return new ApnSettings(mmsc, mmsProxy, parsePort(mmsPort), "Default from settings");
}
Timber.v("ApnSettings: apnName " + apnName);
// TODO: CURRENT semantics is currently broken in telephony. Revive this when it is fixed.
//String selection = Telephony.Carriers.CURRENT + " IS NOT NULL";
String selection = null;
String[] selectionArgs = null;
apnName = apnName != null ? apnName.trim() : null;
if (!TextUtils.isEmpty(apnName)) {
//selection += " AND " + Telephony.Carriers.APN + "=?";
selection = Telephony.Carriers.APN + "=?";
selectionArgs = new String[]{ apnName };
}
Cursor cursor = null;
try {
cursor = SqliteWrapper.query(
context,
context.getContentResolver(),
Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "/subId/" + subId),
APN_PROJECTION,
selection,
selectionArgs,
null/*sortOrder*/);
if (cursor != null) {
String mmscUrl = null;
String proxyAddress = null;
int proxyPort = -1;
while (cursor.moveToNext()) {
// Read values from APN settings
if (isValidApnType(
cursor.getString(COLUMN_TYPE), "mms")) {
mmscUrl = trimWithNullCheck(cursor.getString(COLUMN_MMSC));
if (TextUtils.isEmpty(mmscUrl)) {
continue;
}
mmscUrl = NetworkUtilsHelper.trimV4AddrZeros(mmscUrl);
try {
new URI(mmscUrl);
} catch (URISyntaxException e) {
throw new ApnException("Invalid MMSC url " + mmscUrl);
}
proxyAddress = trimWithNullCheck(cursor.getString(COLUMN_MMSPROXY));
if (!TextUtils.isEmpty(proxyAddress)) {
proxyAddress = NetworkUtilsHelper.trimV4AddrZeros(proxyAddress);
final String portString =
trimWithNullCheck(cursor.getString(COLUMN_MMSPORT));
if (portString != null) {
try {
proxyPort = Integer.parseInt(portString);
} catch (NumberFormatException e) {
Timber.e("Invalid port " + portString);
throw new ApnException("Invalid port " + portString);
}
}
}
return new ApnSettings(
mmscUrl, proxyAddress, proxyPort, getDebugText(cursor));
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return new ApnSettings("", "", 80, "Failed to find APNs :(");
}
private static String getDebugText(Cursor cursor) {
final StringBuilder sb = new StringBuilder();
sb.append("APN [");
for (int i = 0; i < cursor.getColumnCount(); i++) {
final String name = cursor.getColumnName(i);
final String value = cursor.getString(i);
if (TextUtils.isEmpty(value)) {
continue;
}
if (i > 0) {
sb.append(' ');
}
sb.append(name).append('=').append(value);
}
sb.append("]");
return sb.toString();
}
private static String trimWithNullCheck(String value) {
return value != null ? value.trim() : null;
}
public ApnSettings(String mmscUrl, String proxyAddr, int proxyPort, String debugText) {
mServiceCenter = mmscUrl;
mProxyAddress = proxyAddr;
mProxyPort = proxyPort;
mDebugText = debugText;
}
public String getMmscUrl() {
return mServiceCenter;
}
public String getProxyAddress() {
return mProxyAddress;
}
public int getProxyPort() {
return mProxyPort;
}
public boolean isProxySet() {
return !TextUtils.isEmpty(mProxyAddress);
}
private static boolean isValidApnType(String types, String requestType) {
// If APN type is unspecified, assume APN_TYPE_ALL.
if (TextUtils.isEmpty(types)) {
return true;
}
for (String type : types.split(",")) {
type = type.trim();
if (type.equals(requestType) || type.equals("*")) {
return true;
}
}
return false;
}
private static int parsePort(String port) {
if (TextUtils.isEmpty(port)) {
return 80;
} else {
return Integer.parseInt(port);
}
}
public String toString() {
return mDebugText;
}
}
| 8,926 | 36.041494 | 98 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/MmsConfig.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import com.klinker.android.send_message.R;
import timber.log.Timber;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* This class manages a cached copy of current MMS configuration key values
*
* The steps to add a key
* 1. Add a String constant for the key
* 2. Add a default value for the key by putting a typed value to DEFAULTS
* (null means String type only)
* 3. Add a getter for the key
* 4. Add key/value for relevant mms_config.xml of a specific carrier (mcc/mnc)
*/
public class MmsConfig {
private static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile";
private static final int MAX_IMAGE_HEIGHT = 480;
private static final int MAX_IMAGE_WIDTH = 640;
private static final int MAX_TEXT_LENGTH = 2000;
/*
* MmsConfig keys. These have to stay in sync with the MMS_CONFIG_* values defined in
* SmsManager.
*/
public static final String CONFIG_ENABLED_MMS = "enabledMMS";
// In case of single segment wap push message, this CONFIG_ENABLED_TRANS_ID indicates whether
// TransactionID should be appended to URI or not.
public static final String CONFIG_ENABLED_TRANS_ID = "enabledTransID";
public static final String CONFIG_ENABLED_NOTIFY_WAP_MMSC = "enabledNotifyWapMMSC";
public static final String CONFIG_ALIAS_ENABLED = "aliasEnabled";
public static final String CONFIG_ALLOW_ATTACH_AUDIO = "allowAttachAudio";
// If CONFIG_ENABLE_MULTIPART_SMS is true, long sms messages are always sent as multi-part sms
// messages, with no checked limit on the number of segments.
// If CONFIG_ENABLE_MULTIPART_SMS is false, then as soon as the user types a message longer
// than a single segment (i.e. 140 chars), then the message will turn into and be sent
// as an mms message or separate, independent SMS messages
// (which is dependent on CONFIG_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES flag).
// This feature exists for carriers that don't support multi-part sms's.
public static final String CONFIG_ENABLE_MULTIPART_SMS = "enableMultipartSMS";
public static final String CONFIG_ENABLE_SMS_DELIVERY_REPORTS = "enableSMSDeliveryReports";
// If CONFIG_ENABLE_GROUP_MMS is true, a message with multiple recipients,
// regardless of contents, will be sent as a single MMS message with multiple "TO" fields set
// for each recipient.
// If CONFIG_ENABLE_GROUP_MMS is false, the group MMS setting/preference will be hidden
// in the settings activity.
public static final String CONFIG_ENABLE_GROUP_MMS = "enableGroupMms";
// If this is true, then we should read the content_disposition field of an MMS part
// Check wap-230-wsp-20010705-a.pdf, chapter 8.4.2.21
// Most carriers support it except Sprint.
// There is a system resource defining it:
// com.android.internal.R.bool.config_mms_content_disposition_support.
// But Shem can not read it. Add here so that we can configure for different carriers.
public static final String CONFIG_SUPPORT_MMS_CONTENT_DISPOSITION =
"supportMmsContentDisposition";
// if true, show the cell broadcast (amber alert) in the SMS settings. Some carriers
// don't want this shown.
public static final String CONFIG_CELL_BROADCAST_APP_LINKS = "config_cellBroadcastAppLinks";
// If this is true, we will send multipart SMS as separate SMS messages
public static final String CONFIG_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES =
"sendMultipartSmsAsSeparateMessages";
// FLAG(ywen): the following two is not supported yet.
public static final String CONFIG_ENABLE_MMS_READ_REPORTS = "enableMMSReadReports";
public static final String CONFIG_ENABLE_MMS_DELIVERY_REPORTS = "enableMMSDeliveryReports";
// Bouygues Telecom (20820) MMSC does not support "charset" with "Content-Type" header
// It would fail and return 500. See b/18604507
// If this is false, then we don't add "charset" to "Content-Type"
public static final String CONFIG_SUPPORT_HTTP_CHARSET_HEADER = "supportHttpCharsetHeader";
public static final String CONFIG_MAX_MESSAGE_SIZE = "maxMessageSize"; // in bytes
public static final String CONFIG_MAX_IMAGE_HEIGHT = "maxImageHeight"; // in pixels
public static final String CONFIG_MAX_IMAGE_WIDTH = "maxImageWidth"; // in pixels
public static final String CONFIG_RECIPIENT_LIMIT = "recipientLimit";
public static final String CONFIG_HTTP_SOCKET_TIMEOUT = "httpSocketTimeout";
public static final String CONFIG_ALIAS_MIN_CHARS = "aliasMinChars";
public static final String CONFIG_ALIAS_MAX_CHARS = "aliasMaxChars";
// If CONFIG_ENABLE_MULTIPART_SMS is true and CONFIG_SMS_TO_MMS_TEXT_THRESHOLD > 1,
// then multi-part SMS messages will be converted into a single mms message.
// For example, if the mms_config.xml file specifies <int name="smsToMmsTextThreshold">4</int>,
// then on the 5th sms segment, the message will be converted to an mms.
public static final String CONFIG_SMS_TO_MMS_TEXT_THRESHOLD = "smsToMmsTextThreshold";
// LGU+ temporarily requires any SMS message longer than 80 bytes to be sent as MMS
// see b/12122333
public static final String CONFIG_SMS_TO_MMS_TEXT_LENGTH_THRESHOLD =
"smsToMmsTextLengthThreshold";
public static final String CONFIG_MAX_MESSAGE_TEXT_SIZE = "maxMessageTextSize";
// maximum number of characters allowed for mms subject
public static final String CONFIG_MAX_SUBJECT_LENGTH = "maxSubjectLength";
public static final String CONFIG_UA_PROF_TAG_NAME = "uaProfTagName";
public static final String CONFIG_USER_AGENT = "userAgent";
public static final String CONFIG_UA_PROF_URL = "uaProfUrl";
public static final String CONFIG_HTTP_PARAMS = "httpParams";
// Email gateway alias support, including the master switch and different rules
public static final String CONFIG_EMAIL_GATEWAY_NUMBER = "emailGatewayNumber";
// String to append to the NAI header, e.g. ":pcs"
public static final String CONFIG_NAI_SUFFIX = "naiSuffix";
/*
* Key types
*/
public static final String KEY_TYPE_INT = "int";
public static final String KEY_TYPE_BOOL = "bool";
public static final String KEY_TYPE_STRING = "string";
/*
* Macro names
*/
// The raw phone number from TelephonyManager.getLine1Number
public static final String MACRO_LINE1 = "LINE1";
// The phone number without country code
public static final String MACRO_LINE1NOCOUNTRYCODE = "LINE1NOCOUNTRYCODE";
// NAI (Network Access Identifier), used by Sprint for authentication
public static final String MACRO_NAI = "NAI";
// Default values. This is read-only. Don't write into it.
// This provides the info on valid keys, their types and default values
private static final Map<String, Object> DEFAULTS = new ConcurrentHashMap<String, Object>();
static {
DEFAULTS.put(CONFIG_ENABLED_MMS, Boolean.valueOf(true));
DEFAULTS.put(CONFIG_ENABLED_TRANS_ID, Boolean.valueOf(false));
DEFAULTS.put(CONFIG_ENABLED_NOTIFY_WAP_MMSC, Boolean.valueOf(false));
DEFAULTS.put(CONFIG_ALIAS_ENABLED, Boolean.valueOf(false));
DEFAULTS.put(CONFIG_ALLOW_ATTACH_AUDIO, Boolean.valueOf(true));
DEFAULTS.put(CONFIG_ENABLE_MULTIPART_SMS, Boolean.valueOf(true));
DEFAULTS.put(CONFIG_ENABLE_SMS_DELIVERY_REPORTS, Boolean.valueOf(true));
DEFAULTS.put(CONFIG_ENABLE_GROUP_MMS, Boolean.valueOf(true));
DEFAULTS.put(CONFIG_SUPPORT_MMS_CONTENT_DISPOSITION, Boolean.valueOf(true));
DEFAULTS.put(CONFIG_CELL_BROADCAST_APP_LINKS, Boolean.valueOf(true));
DEFAULTS.put(CONFIG_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES, Boolean.valueOf(false));
DEFAULTS.put(CONFIG_ENABLE_MMS_READ_REPORTS, Boolean.valueOf(false));
DEFAULTS.put(CONFIG_ENABLE_MMS_DELIVERY_REPORTS, Boolean.valueOf(false));
DEFAULTS.put(CONFIG_SUPPORT_HTTP_CHARSET_HEADER, Boolean.valueOf(false));
DEFAULTS.put(CONFIG_MAX_MESSAGE_SIZE, Integer.valueOf(300 * 1024));
DEFAULTS.put(CONFIG_MAX_IMAGE_HEIGHT, Integer.valueOf(MAX_IMAGE_HEIGHT));
DEFAULTS.put(CONFIG_MAX_IMAGE_WIDTH, Integer.valueOf(MAX_IMAGE_WIDTH));
DEFAULTS.put(CONFIG_RECIPIENT_LIMIT, Integer.valueOf(Integer.MAX_VALUE));
DEFAULTS.put(CONFIG_HTTP_SOCKET_TIMEOUT, Integer.valueOf(60 * 1000));
DEFAULTS.put(CONFIG_ALIAS_MIN_CHARS, Integer.valueOf(2));
DEFAULTS.put(CONFIG_ALIAS_MAX_CHARS, Integer.valueOf(48));
DEFAULTS.put(CONFIG_SMS_TO_MMS_TEXT_THRESHOLD, Integer.valueOf(-1));
DEFAULTS.put(CONFIG_SMS_TO_MMS_TEXT_LENGTH_THRESHOLD, Integer.valueOf(-1));
DEFAULTS.put(CONFIG_MAX_MESSAGE_TEXT_SIZE, Integer.valueOf(-1));
DEFAULTS.put(CONFIG_MAX_SUBJECT_LENGTH, Integer.valueOf(40));
DEFAULTS.put(CONFIG_UA_PROF_TAG_NAME, DEFAULT_HTTP_KEY_X_WAP_PROFILE);
DEFAULTS.put(CONFIG_USER_AGENT, "");
DEFAULTS.put(CONFIG_UA_PROF_URL, "");
DEFAULTS.put(CONFIG_HTTP_PARAMS, "");
DEFAULTS.put(CONFIG_EMAIL_GATEWAY_NUMBER, "");
DEFAULTS.put(CONFIG_NAI_SUFFIX, "");
}
private final int mSubId;
/**
* This class manages a cached copy of current MMS configuration key values for a particular
* subscription id. (See the {@link SubscriptionManager}).
*
* @param context Context of the particular subscription to load. The context's mcc/mnc
* should be set to that of the subscription id
* @param subId Subscription id of the mcc/mnc in the context
*/
public MmsConfig(Context context, int subId) {
mSubId = subId;
// Load defaults
mKeyValues.clear();
mKeyValues.putAll(DEFAULTS);
// Load User-Agent and UA profile URL settings
loadDeviceUaSettings(context);
Timber.v("MmsConfig: mUserAgent=" + mUserAgent + ", mUaProfUrl=" + mUaProfUrl);
// Load mms_config.xml resource overlays
loadFromResources(context);
Timber.v("MmsConfig: all settings -- " + mKeyValues);
}
/**
* This class manages a cached copy of current MMS configuration key values for a particular
* subscription id. (See the {@link SubscriptionManager}).
*
* @param context Context of the particular subscription to load. The context's mcc/mnc
* should be set to that of the subscription id\
*/
public MmsConfig(Context context) {
mSubId = -1;
// Load defaults
mKeyValues.clear();
mKeyValues.putAll(DEFAULTS);
// Load User-Agent and UA profile URL settings
loadDeviceUaSettings(context);
Timber.v("MmsConfig: mUserAgent=" + mUserAgent + ", mUaProfUrl=" + mUaProfUrl);
// Load mms_config.xml resource overlays
loadFromResources(context);
Timber.v("MmsConfig: all settings -- " + mKeyValues);
}
/**
* Return the subscription ID associated with this MmsConfig
*
* @return subId the subId associated with this MmsConfig
*/
public int getSubId() {
return mSubId;
}
/**
* Check a key and its type match the predefined keys and corresponding types
*
* @param key
* @param type Including "int" "bool" and "string"
* @return True if key and type both matches and false otherwise
*/
public static boolean isValidKey(String key, String type) {
if (!TextUtils.isEmpty(key) && DEFAULTS.containsKey(key)) {
Object defVal = DEFAULTS.get(key);
Class<?> valueType = defVal != null ? defVal.getClass() : String.class;
if (KEY_TYPE_INT.equals(type)) {
return valueType == Integer.class;
} else if (KEY_TYPE_BOOL.equals(type)) {
return valueType == Boolean.class;
} else if (KEY_TYPE_STRING.equals(type)) {
return valueType == String.class;
}
}
return false;
}
/**
* Check a key and its type match the predefined keys and corresponding types
*
* @param key The key of the config
* @param value The value of the config
* @return True if key and type both matches and false otherwise
*/
public static boolean isValidValue(String key, Object value) {
if (!TextUtils.isEmpty(key) && DEFAULTS.containsKey(key)) {
Object defVal = DEFAULTS.get(key);
Class<?> valueType = defVal != null ? defVal.getClass() : String.class;
return value.getClass().equals(valueType);
}
return false;
}
private String mUserAgent = null;
private String mUaProfUrl = null;
// The current values
private final Map<String, Object> mKeyValues = new ConcurrentHashMap<String, Object>();
/**
* Get a config value by its type
*
* @param key The key of the config
* @param type The type of the config value
* @return The expected typed value or null if no match
*/
public Object getValueAsType(String key, String type) {
if (isValidKey(key, type)) {
return mKeyValues.get(key);
}
return null;
}
public Bundle getCarrierConfigValues() {
final Bundle bundle = new Bundle();
final Iterator<Map.Entry<String, Object>> iter = mKeyValues.entrySet().iterator();
while(iter.hasNext()) {
final Map.Entry<String, Object> entry = iter.next();
final String key = entry.getKey();
final Object val = entry.getValue();
Class<?> valueType = val != null ? val.getClass() : String.class;
if (valueType == Integer.class) {
bundle.putInt(key, (Integer)val);
} else if (valueType == Boolean.class) {
bundle.putBoolean(key, (Boolean)val);
} else if (valueType == String.class) {
bundle.putString(key, (String)val);
}
}
return bundle;
}
private String getNullableStringValue(String key) {
final Object value = mKeyValues.get(key);
if (value != null) {
return (String) value;
}
return null;
}
private void update(String key, String value, String type) {
try {
if (KEY_TYPE_INT.equals(type)) {
mKeyValues.put(key, Integer.parseInt(value));
} else if (KEY_TYPE_BOOL.equals(type)) {
mKeyValues.put(key, Boolean.parseBoolean(value));
} else if (KEY_TYPE_STRING.equals(type)){
mKeyValues.put(key, value);
}
} catch (NumberFormatException e) {
Timber.e("MmsConfig.update: invalid " + key + "," + value + "," + type);
}
}
private void loadDeviceUaSettings(Context context) {
// load the MMS User agent and UaProfUrl from TelephonyManager APIs
final TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
mUserAgent = telephonyManager.getMmsUserAgent();
mUaProfUrl = telephonyManager.getMmsUAProfUrl();
// defaults for nexus 6, seems to work well.
//mUserAgent = "nexus6";
//mUaProfUrl = "http://uaprof.motorola.com/phoneconfig/nexus6/Profile/nexus6.rdf";
}
private void loadFromResources(Context context) {
Timber.d("MmsConfig.loadFromResources");
final XmlResourceParser parser = context.getResources().getXml(R.xml.mms_config);
final MmsConfigXmlProcessor processor = MmsConfigXmlProcessor.get(parser);
processor.setMmsConfigHandler(new MmsConfigXmlProcessor.MmsConfigHandler() {
@Override
public void process(String key, String value, String type) {
update(key, value, type);
}
});
try {
processor.process();
} finally {
parser.close();
}
}
/**
* This class returns corresponding MmsConfig values which can be overridden by
* externally provided values.
*/
public static class Overridden {
// The base MmsConfig
private final MmsConfig mBase;
// The overridden values
private final Bundle mOverrides;
public Overridden(MmsConfig base, Bundle overrides) {
mBase = base;
mOverrides = overrides;
}
private int getInt(String key) {
final Integer def = (Integer) mBase.mKeyValues.get(key);
return mOverrides != null ? mOverrides.getInt(key, def) : def;
}
private boolean getBoolean(String key) {
final Boolean def = (Boolean) mBase.mKeyValues.get(key);
return mOverrides != null ? mOverrides.getBoolean(key, def) : def;
}
private String getString(String key) {
if (mOverrides != null && mOverrides.containsKey(key)) {
return mOverrides.getString(key);
}
return mBase.getNullableStringValue(key);
}
public int getSmsToMmsTextThreshold() {
return getInt(CONFIG_SMS_TO_MMS_TEXT_THRESHOLD);
}
public int getSmsToMmsTextLengthThreshold() {
return getInt(CONFIG_SMS_TO_MMS_TEXT_LENGTH_THRESHOLD);
}
public boolean getMmsEnabled() {
return getBoolean(CONFIG_ENABLED_MMS);
}
public int getMaxMessageSize() {
return getInt(CONFIG_MAX_MESSAGE_SIZE);
}
public boolean getTransIdEnabled() {
return getBoolean(CONFIG_ENABLED_TRANS_ID);
}
public String getUserAgent() {
if (mOverrides != null && mOverrides.containsKey(CONFIG_USER_AGENT)) {
return mOverrides.getString(CONFIG_USER_AGENT);
}
return !TextUtils.isEmpty(mBase.mUserAgent) ?
mBase.mUserAgent : mBase.getNullableStringValue(CONFIG_USER_AGENT);
}
public String getUaProfTagName() {
return getString(CONFIG_UA_PROF_TAG_NAME);
}
public String getUaProfUrl() {
if (mOverrides != null && mOverrides.containsKey(CONFIG_UA_PROF_URL)) {
return mOverrides.getString(CONFIG_UA_PROF_URL);
}
return !TextUtils.isEmpty(mBase.mUaProfUrl) ?
mBase.mUaProfUrl : mBase.getNullableStringValue(CONFIG_UA_PROF_URL);
}
public String getHttpParams() {
return getString(CONFIG_HTTP_PARAMS);
}
public String getEmailGateway() {
return getString(CONFIG_EMAIL_GATEWAY_NUMBER);
}
public int getMaxImageHeight() {
return getInt(CONFIG_MAX_IMAGE_HEIGHT);
}
public int getMaxImageWidth() {
return getInt(CONFIG_MAX_IMAGE_WIDTH);
}
public int getRecipientLimit() {
final int limit = getInt(CONFIG_RECIPIENT_LIMIT);
return limit < 0 ? Integer.MAX_VALUE : limit;
}
public int getMaxTextLimit() {
final int max = getInt(CONFIG_MAX_MESSAGE_TEXT_SIZE);
return max > -1 ? max : MAX_TEXT_LENGTH;
}
public int getHttpSocketTimeout() {
return getInt(CONFIG_HTTP_SOCKET_TIMEOUT);
}
public boolean getMultipartSmsEnabled() {
return getBoolean(CONFIG_ENABLE_MULTIPART_SMS);
}
public boolean getSendMultipartSmsAsSeparateMessages() {
return getBoolean(CONFIG_SEND_MULTIPART_SMS_AS_SEPARATE_MESSAGES);
}
public boolean getSMSDeliveryReportsEnabled() {
return getBoolean(CONFIG_ENABLE_SMS_DELIVERY_REPORTS);
}
public boolean getNotifyWapMMSC() {
return getBoolean(CONFIG_ENABLED_NOTIFY_WAP_MMSC);
}
public boolean isAliasEnabled() {
return getBoolean(CONFIG_ALIAS_ENABLED);
}
public int getAliasMinChars() {
return getInt(CONFIG_ALIAS_MIN_CHARS);
}
public int getAliasMaxChars() {
return getInt(CONFIG_ALIAS_MAX_CHARS);
}
public boolean getAllowAttachAudio() {
return getBoolean(CONFIG_ALLOW_ATTACH_AUDIO);
}
public int getMaxSubjectLength() {
return getInt(CONFIG_MAX_SUBJECT_LENGTH);
}
public boolean getGroupMmsEnabled() {
return getBoolean(CONFIG_ENABLE_GROUP_MMS);
}
public boolean getSupportMmsContentDisposition() {
return getBoolean(CONFIG_SUPPORT_MMS_CONTENT_DISPOSITION);
}
public boolean getShowCellBroadcast() {
return getBoolean(CONFIG_CELL_BROADCAST_APP_LINKS);
}
public String getNaiSuffix() {
return getString(CONFIG_NAI_SUFFIX);
}
public boolean isMmsReadReportsEnabled() {
return getBoolean(CONFIG_ENABLE_MMS_READ_REPORTS);
}
public boolean isMmsDeliveryReportsEnabled() {
return getBoolean(CONFIG_ENABLE_MMS_DELIVERY_REPORTS);
}
public boolean getSupportHttpCharsetHeader() {
return getBoolean(CONFIG_SUPPORT_HTTP_CHARSET_HEADER);
}
/**
* Return the HTTP param macro value.
* Example: LINE1 returns the phone number, etc.
*
* @param macro The macro name
* @return The value of the defined macro
*/
public String getHttpParamMacro(Context context, String macro) {
if (MACRO_LINE1.equals(macro)) {
return getLine1(context, mBase.getSubId());
} else if (MACRO_LINE1NOCOUNTRYCODE.equals(macro)) {
return getLine1NoCountryCode(context, mBase.getSubId());
} else if (MACRO_NAI.equals(macro)) {
return getNai(context, mBase.getSubId());
}
return null;
}
/**
* @return the phone number
*/
private static String getLine1(Context context, int subId) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
return telephonyManager.getLine1Number();
} else {
try {
Method method = telephonyManager.getClass().getMethod("getLine1NumberForSubscriber", int.class);
return (String) method.invoke(telephonyManager, subId);
} catch (Exception e) {
return telephonyManager.getLine1Number();
}
}
}
private static String getLine1NoCountryCode(Context context, int subId) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
return PhoneUtils.getNationalNumber(
telephonyManager,
subId,
getLine1(context, subId));
}
/**
* @return the NAI (Network Access Identifier) from SystemProperties
*/
private String getNai(Context context, int subId) {
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
String nai = "";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
nai = SystemPropertiesProxy.get(context, "persist.radio.cdma.nai");
} else {
try {
Method method = telephonyManager.getClass().getMethod("getNai", int.class);
Method getSlotId = SubscriptionManager.class.getMethod("getSlotId", int.class);
nai = (String) method.invoke(telephonyManager, getSlotId.invoke(null, subId));
} catch (Exception e) {
nai = SystemPropertiesProxy.get(context, "persist.radio.cdma.nai");
}
}
Timber.v("MmsConfig.getNai: nai=" + nai);
if (!TextUtils.isEmpty(nai)) {
String naiSuffix = getNaiSuffix();
if (!TextUtils.isEmpty(naiSuffix)) {
nai = nai + naiSuffix;
}
byte[] encoded = null;
try {
encoded = Base64.encode(nai.getBytes("UTF-8"), Base64.NO_WRAP);
} catch (UnsupportedEncodingException e) {
encoded = Base64.encode(nai.getBytes(), Base64.NO_WRAP);
}
try {
nai = new String(encoded, "UTF-8");
} catch (UnsupportedEncodingException e) {
nai = new String(encoded);
}
}
return nai;
}
}
}
| 26,018 | 41.033926 | 116 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/MmsHttpClient.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.content.Context;
import android.text.TextUtils;
import com.android.mms.service_alt.exception.MmsHttpException;
import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.ConnectionSpec;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.Internal;
import com.squareup.okhttp.internal.huc.HttpURLConnectionImpl;
import com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl;
import timber.log.Timber;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* MMS HTTP client for sending and downloading MMS messages
*/
public class MmsHttpClient {
public static final String METHOD_POST = "POST";
public static final String METHOD_GET = "GET";
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final String HEADER_ACCEPT = "Accept";
private static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
private static final String HEADER_USER_AGENT = "User-Agent";
// The "Accept" header value
private static final String HEADER_VALUE_ACCEPT =
"*/*, application/vnd.wap.mms-message, application/vnd.wap.sic";
// The "Content-Type" header value
private static final String HEADER_VALUE_CONTENT_TYPE_WITH_CHARSET =
"application/vnd.wap.mms-message; charset=utf-8";
private static final String HEADER_VALUE_CONTENT_TYPE_WITHOUT_CHARSET =
"application/vnd.wap.mms-message";
private final Context mContext;
private final SocketFactory mSocketFactory;
private final MmsNetworkManager mHostResolver;
private final ConnectionPool mConnectionPool;
/**
* Constructor
*
* @param context The Context object
* @param socketFactory The socket factory for creating an OKHttp client
* @param hostResolver The host name resolver for creating an OKHttp client
* @param connectionPool The connection pool for creating an OKHttp client
*/
public MmsHttpClient(Context context, SocketFactory socketFactory, MmsNetworkManager hostResolver,
ConnectionPool connectionPool) {
mContext = context;
mSocketFactory = socketFactory;
mHostResolver = hostResolver;
mConnectionPool = connectionPool;
}
/**
* Execute an MMS HTTP request, either a POST (sending) or a GET (downloading)
*
* @param urlString The request URL, for sending it is usually the MMSC, and for downloading
* it is the message URL
* @param pdu For POST (sending) only, the PDU to send
* @param method HTTP method, POST for sending and GET for downloading
* @param isProxySet Is there a proxy for the MMSC
* @param proxyHost The proxy host
* @param proxyPort The proxy port
* @param mmsConfig The MMS config to use
* @return The HTTP response body
* @throws MmsHttpException For any failures
*/
public byte[] execute(String urlString, byte[] pdu, String method, boolean isProxySet,
String proxyHost, int proxyPort, MmsConfig.Overridden mmsConfig)
throws MmsHttpException {
Timber.d("HTTP: " + method + " " + urlString
+ (isProxySet ? (", proxy=" + proxyHost + ":" + proxyPort) : "")
+ ", PDU size=" + (pdu != null ? pdu.length : 0));
checkMethod(method);
HttpURLConnection connection = null;
try {
Proxy proxy = null;
if (isProxySet) {
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}
final URL url = new URL(urlString);
// Now get the connection
connection = openConnection(url, proxy);
connection.setDoInput(true);
connection.setConnectTimeout(mmsConfig.getHttpSocketTimeout());
// ------- COMMON HEADERS ---------
// Header: Accept
connection.setRequestProperty(HEADER_ACCEPT, HEADER_VALUE_ACCEPT);
// Header: Accept-Language
connection.setRequestProperty(
HEADER_ACCEPT_LANGUAGE, getCurrentAcceptLanguage(Locale.getDefault()));
// Header: User-Agent
final String userAgent = mmsConfig.getUserAgent();
Timber.i("HTTP: User-Agent=" + userAgent);
connection.setRequestProperty(HEADER_USER_AGENT, userAgent);
// Header: x-wap-profile
final String uaProfUrlTagName = mmsConfig.getUaProfTagName();
final String uaProfUrl = mmsConfig.getUaProfUrl();
if (uaProfUrl != null) {
Timber.i("HTTP: UaProfUrl=" + uaProfUrl);
connection.setRequestProperty(uaProfUrlTagName, uaProfUrl);
}
// Add extra headers specified by mms_config.xml's httpparams
addExtraHeaders(connection, mmsConfig);
// Different stuff for GET and POST
if (METHOD_POST.equals(method)) {
if (pdu == null || pdu.length < 1) {
Timber.e("HTTP: empty pdu");
throw new MmsHttpException(0/*statusCode*/, "Sending empty PDU");
}
connection.setDoOutput(true);
connection.setRequestMethod(METHOD_POST);
if (mmsConfig.getSupportHttpCharsetHeader()) {
connection.setRequestProperty(HEADER_CONTENT_TYPE,
HEADER_VALUE_CONTENT_TYPE_WITH_CHARSET);
} else {
connection.setRequestProperty(HEADER_CONTENT_TYPE,
HEADER_VALUE_CONTENT_TYPE_WITHOUT_CHARSET);
}
logHttpHeaders(connection.getRequestProperties());
connection.setFixedLengthStreamingMode(pdu.length);
// Sending request body
final OutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(pdu);
out.flush();
out.close();
} else if (METHOD_GET.equals(method)) {
logHttpHeaders(connection.getRequestProperties());
connection.setRequestMethod(METHOD_GET);
}
// Get response
final int responseCode = connection.getResponseCode();
final String responseMessage = connection.getResponseMessage();
Timber.d("HTTP: " + responseCode + " " + responseMessage);
logHttpHeaders(connection.getHeaderFields());
if (responseCode / 100 != 2) {
throw new MmsHttpException(responseCode, responseMessage);
}
final InputStream in = new BufferedInputStream(connection.getInputStream());
final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
final byte[] buf = new byte[4096];
int count = 0;
while ((count = in.read(buf)) > 0) {
byteOut.write(buf, 0, count);
}
in.close();
final byte[] responseBody = byteOut.toByteArray();
Timber.d("HTTP: response size="
+ (responseBody != null ? responseBody.length : 0));
return responseBody;
} catch (MalformedURLException e) {
Timber.e(e, "HTTP: invalid URL " + urlString);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL " + urlString, e);
} catch (ProtocolException e) {
Timber.e(e, "HTTP: invalid URL protocol " + urlString);
throw new MmsHttpException(0/*statusCode*/, "Invalid URL protocol " + urlString, e);
} catch (IOException e) {
Timber.e(e, "HTTP: IO failure");
throw new MmsHttpException(0/*statusCode*/, e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Open an HTTP connection
*
* TODO: The following code is borrowed from android.net.Network.openConnection
* Once that method supports proxy, we should use that instead
* Also we should remove the associated HostResolver and ConnectionPool from
* MmsNetworkManager
*
* @param url The URL to connect to
* @param proxy The proxy to use
* @return The opened HttpURLConnection
* @throws MalformedURLException If URL is malformed
*/
private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException {
final String protocol = url.getProtocol();
OkHttpClient okHttpClient;
if (protocol.equals("http")) {
okHttpClient = new OkHttpClient();
okHttpClient.setFollowRedirects(false);
okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
okHttpClient.setProxySelector(new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
if (proxy != null) {
return Arrays.asList(proxy);
} else {
return new ArrayList<Proxy>();
}
}
@Override
public void connectFailed(URI uri, SocketAddress address, IOException failure) {
}
});
okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
return null;
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
okHttpClient.setSocketFactory(SocketFactory.getDefault());
Internal.instance.setNetwork(okHttpClient, mHostResolver);
if (proxy != null) {
okHttpClient.setProxy(proxy);
}
return new HttpURLConnectionImpl(url, okHttpClient);
} else if (protocol.equals("https")) {
okHttpClient = new OkHttpClient();
okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
okHttpClient.setHostnameVerifier(verifier);
okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
okHttpClient.setProxySelector(new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
return Arrays.asList(proxy);
}
@Override
public void connectFailed(URI uri, SocketAddress address, IOException failure) {
}
});
okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
return null;
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
});
okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
Internal.instance.setNetwork(okHttpClient, mHostResolver);
return new HttpsURLConnectionImpl(url, okHttpClient);
} else {
throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
}
}
private static void logHttpHeaders(Map<String, List<String>> headers) {
final StringBuilder sb = new StringBuilder();
if (headers != null) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
final String key = entry.getKey();
final List<String> values = entry.getValue();
if (values != null) {
for (String value : values) {
sb.append(key).append('=').append(value).append('\n');
}
}
}
Timber.v("HTTP: headers\n" + sb.toString());
}
}
private static void checkMethod(String method) throws MmsHttpException {
if (!METHOD_GET.equals(method) && !METHOD_POST.equals(method)) {
throw new MmsHttpException(0/*statusCode*/, "Invalid method " + method);
}
}
private static final String ACCEPT_LANG_FOR_US_LOCALE = "en-US";
/**
* Return the Accept-Language header. Use the current locale plus
* US if we are in a different locale than US.
* This code copied from the browser's WebSettings.java
*
* @return Current AcceptLanguage String.
*/
public static String getCurrentAcceptLanguage(Locale locale) {
final StringBuilder buffer = new StringBuilder();
addLocaleToHttpAcceptLanguage(buffer, locale);
if (!Locale.US.equals(locale)) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(ACCEPT_LANG_FOR_US_LOCALE);
}
return buffer.toString();
}
/**
* Convert obsolete language codes, including Hebrew/Indonesian/Yiddish,
* to new standard.
*/
private static String convertObsoleteLanguageCodeToNew(String langCode) {
if (langCode == null) {
return null;
}
if ("iw".equals(langCode)) {
// Hebrew
return "he";
} else if ("in".equals(langCode)) {
// Indonesian
return "id";
} else if ("ji".equals(langCode)) {
// Yiddish
return "yi";
}
return langCode;
}
private static void addLocaleToHttpAcceptLanguage(StringBuilder builder, Locale locale) {
final String language = convertObsoleteLanguageCodeToNew(locale.getLanguage());
if (language != null) {
builder.append(language);
final String country = locale.getCountry();
if (country != null) {
builder.append("-");
builder.append(country);
}
}
}
private static final Pattern MACRO_P = Pattern.compile("##(\\S+)##");
/**
* Resolve the macro in HTTP param value text
* For example, "something##LINE1##something" is resolved to "something9139531419something"
*
* @param value The HTTP param value possibly containing macros
* @return The HTTP param with macro resolved to real value
*/
private static String resolveMacro(Context context, String value,
MmsConfig.Overridden mmsConfig) {
if (TextUtils.isEmpty(value)) {
return value;
}
final Matcher matcher = MACRO_P.matcher(value);
int nextStart = 0;
StringBuilder replaced = null;
while (matcher.find()) {
if (replaced == null) {
replaced = new StringBuilder();
}
final int matchedStart = matcher.start();
if (matchedStart > nextStart) {
replaced.append(value.substring(nextStart, matchedStart));
}
final String macro = matcher.group(1);
final String macroValue = mmsConfig.getHttpParamMacro(context, macro);
if (macroValue != null) {
replaced.append(macroValue);
} else {
Timber.w("HTTP: invalid macro " + macro);
}
nextStart = matcher.end();
}
if (replaced != null && nextStart < value.length()) {
replaced.append(value.substring(nextStart));
}
return replaced == null ? value : replaced.toString();
}
/**
* Add extra HTTP headers from mms_config.xml's httpParams, which is a list of key/value
* pairs separated by "|". Each key/value pair is separated by ":". Value may contain
* macros like "##LINE1##" or "##NAI##" which is resolved with methods in this class
*
* @param connection The HttpURLConnection that we add headers to
* @param mmsConfig The MmsConfig object
*/
private void addExtraHeaders(HttpURLConnection connection, MmsConfig.Overridden mmsConfig) {
final String extraHttpParams = mmsConfig.getHttpParams();
if (!TextUtils.isEmpty(extraHttpParams)) {
// Parse the parameter list
String paramList[] = extraHttpParams.split("\\|");
for (String paramPair : paramList) {
String splitPair[] = paramPair.split(":", 2);
if (splitPair.length == 2) {
final String name = splitPair[0].trim();
final String value = resolveMacro(mContext, splitPair[1].trim(), mmsConfig);
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
// Add the header if the param is valid
connection.setRequestProperty(name, value);
}
}
}
}
}
}
| 18,903 | 40.730684 | 103 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/SubscriptionIdChecker.java |
package com.android.mms.service_alt;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Build;
import android.provider.Telephony;
import com.google.android.mms.util_alt.SqliteWrapper;
import timber.log.Timber;
class SubscriptionIdChecker {
private static SubscriptionIdChecker sInstance;
private boolean mCanUseSubscriptionId = false;
// I met a device which does not have Telephony.Mms.SUBSCRIPTION_ID event if it's API Level is 22.
private void check(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
Cursor c = null;
try {
c = SqliteWrapper.query(context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
new String[]{Telephony.Mms.SUBSCRIPTION_ID}, null, null, null);
if (c != null) {
mCanUseSubscriptionId = true;
}
} catch (SQLiteException e) {
Timber.e("SubscriptionIdChecker.check() fail");
} finally {
if (c != null) {
c.close();
}
}
}
}
static synchronized SubscriptionIdChecker getInstance(Context context) {
if (sInstance == null) {
sInstance = new SubscriptionIdChecker();
sInstance.check(context);
}
return sInstance;
}
boolean canUseSubscriptionId() {
return mCanUseSubscriptionId;
}
}
| 1,581 | 30.64 | 102 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/MmsRequest.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.service.carrier.CarrierMessagingService;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import com.android.mms.service_alt.exception.ApnException;
import com.android.mms.service_alt.exception.MmsHttpException;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
/**
* Base class for MMS requests. This has the common logic of sending/downloading MMS.
*/
public abstract class MmsRequest {
private static final int RETRY_TIMES = 3;
/**
* Interface for certain functionalities from MmsService
*/
public static interface RequestManager {
/**
* Enqueue an MMS request
*
* @param request the request to enqueue
*/
public void addSimRequest(MmsRequest request);
/*
* @return Whether to auto persist received MMS
*/
public boolean getAutoPersistingPref();
/**
* Read pdu (up to maxSize bytes) from supplied content uri
* @param contentUri content uri from which to read
* @param maxSize maximum number of bytes to read
* @return read pdu (else null in case of error or too big)
*/
public byte[] readPduFromContentUri(final Uri contentUri, final int maxSize);
/**
* Write pdu to supplied content uri
* @param contentUri content uri to which bytes should be written
* @param pdu pdu bytes to write
* @return true in case of success (else false)
*/
public boolean writePduToContentUri(final Uri contentUri, final byte[] pdu);
}
// The reference to the pending requests manager (i.e. the MmsService)
protected RequestManager mRequestManager;
// The SIM id
protected int mSubId;
// The creator app
protected String mCreator;
// MMS config
protected MmsConfig.Overridden mMmsConfig;
// MMS config overrides
protected Bundle mMmsConfigOverrides;
private boolean mobileDataEnabled;
public MmsRequest(RequestManager requestManager, int subId, String creator,
Bundle configOverrides) {
mRequestManager = requestManager;
mSubId = subId;
mCreator = creator;
mMmsConfigOverrides = configOverrides;
mMmsConfig = null;
}
public int getSubId() {
return mSubId;
}
private boolean ensureMmsConfigLoaded() {
if (mMmsConfig == null) {
final MmsConfig config;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
// Not yet retrieved from mms config manager. Try getting it.
config = MmsConfigManager.getInstance().getMmsConfigBySubId(mSubId);
} else {
config = MmsConfigManager.getInstance().getMmsConfig();
}
if (config != null) {
mMmsConfig = new MmsConfig.Overridden(config, mMmsConfigOverrides);
}
}
return mMmsConfig != null;
}
private static boolean inAirplaneMode(final Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
private static boolean isMobileDataEnabled(final Context context, final int subId) {
final TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return Utils.isDataEnabled(telephonyManager, subId);
}
private static boolean isDataNetworkAvailable(final Context context, final int subId) {
return !inAirplaneMode(context) && isMobileDataEnabled(context, subId);
}
/**
* Execute the request
*
* @param context The context
* @param networkManager The network manager to use
*/
public void execute(Context context, MmsNetworkManager networkManager) {
int result = SmsManager.MMS_ERROR_UNSPECIFIED;
int httpStatusCode = 0;
byte[] response = null;
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
boolean isWifiEnabled = wifi.isWifiEnabled();
if (!useWifi(context)) {
wifi.setWifiEnabled(false);
}
mobileDataEnabled = Utils.isMobileDataEnabled(context);
Timber.v("mobile data enabled: " + mobileDataEnabled);
if (!mobileDataEnabled && !useWifi(context)) {
Timber.v("mobile data not enabled, so forcing it to enable");
Utils.setMobileDataEnabled(context, true);
}
if (!ensureMmsConfigLoaded()) { // Check mms config
Timber.e("MmsRequest: mms config is not loaded yet");
result = SmsManager.MMS_ERROR_CONFIGURATION_ERROR;
} else if (!prepareForHttpRequest()) { // Prepare request, like reading pdu data from user
Timber.e("MmsRequest: failed to prepare for request");
result = SmsManager.MMS_ERROR_IO_ERROR;
} else if (!isDataNetworkAvailable(context, mSubId)) {
Timber.e("MmsRequest: in airplane mode or mobile data disabled");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
result = SmsManager.MMS_ERROR_NO_DATA_NETWORK;
} else {
result = 8;
}
} else { // Execute
long retryDelaySecs = 2;
// Try multiple times of MMS HTTP request
for (int i = 0; i < RETRY_TIMES; i++) {
try {
try {
networkManager.acquireNetwork();
} catch (Exception e) {
Timber.e(e, "error acquiring network");
}
final String apnName = networkManager.getApnName();
try {
ApnSettings apn = null;
try {
apn = ApnSettings.load(context, apnName, mSubId);
} catch (ApnException e) {
// If no APN could be found, fall back to trying without the APN name
if (apnName == null) {
// If the APN name was already null then don't need to retry
throw (e);
}
Timber.i("MmsRequest: No match with APN name:"
+ apnName + ", try with no name");
apn = ApnSettings.load(context, null, mSubId);
}
Timber.i("MmsRequest: using " + apn.toString());
response = doHttp(context, networkManager, apn);
result = Activity.RESULT_OK;
// Success
break;
} finally {
networkManager.releaseNetwork();
}
} catch (ApnException e) {
Timber.e(e, "MmsRequest: APN failure");
result = SmsManager.MMS_ERROR_INVALID_APN;
break;
// } catch (MmsNetworkException e) {
// Timber.e(e, "MmsRequest: MMS network acquiring failure");
// result = SmsManager.MMS_ERROR_UNABLE_CONNECT_MMS;
// // Retry
} catch (MmsHttpException e) {
Timber.e(e, "MmsRequest: HTTP or network I/O failure");
result = SmsManager.MMS_ERROR_HTTP_FAILURE;
httpStatusCode = e.getStatusCode();
// Retry
} catch (Exception e) {
Timber.e(e, "MmsRequest: unexpected failure");
result = SmsManager.MMS_ERROR_UNSPECIFIED;
break;
}
try {
Thread.sleep(retryDelaySecs * 1000, 0/*nano*/);
} catch (InterruptedException e) {
}
retryDelaySecs <<= 1;
}
}
if (!mobileDataEnabled) {
Timber.v("setting mobile data back to disabled");
Utils.setMobileDataEnabled(context, false);
}
if (!useWifi(context)) {
wifi.setWifiEnabled(isWifiEnabled);
}
processResult(context, result, response, httpStatusCode);
}
/**
* Process the result of the completed request, including updating the message status
* in database and sending back the result via pending intents.
* @param context The context
* @param result The result code of execution
* @param response The response body
* @param httpStatusCode The optional http status code in case of http failure
*/
public void processResult(Context context, int result, byte[] response, int httpStatusCode) {
final Uri messageUri = persistIfRequired(context, result, response);
// Return MMS HTTP request result via PendingIntent
final PendingIntent pendingIntent = getPendingIntent();
if (pendingIntent != null) {
boolean succeeded = true;
// Extra information to send back with the pending intent
Intent fillIn = new Intent();
if (response != null) {
succeeded = transferResponse(fillIn, response);
}
if (messageUri != null) {
fillIn.putExtra("uri", messageUri.toString());
}
if (result == SmsManager.MMS_ERROR_HTTP_FAILURE && httpStatusCode != 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
fillIn.putExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, httpStatusCode);
} else {
fillIn.putExtra("android.telephony.extra.MMS_HTTP_STATUS", httpStatusCode);
}
}
try {
if (!succeeded) {
result = SmsManager.MMS_ERROR_IO_ERROR;
}
pendingIntent.send(context, result, fillIn);
} catch (PendingIntent.CanceledException e) {
Timber.e(e, "MmsRequest: sending pending intent canceled");
}
}
revokeUriPermission(context);
}
/**
* are we set up to use wifi? if so, send mms over it.
*/
public static boolean useWifi(Context context) {
if (Utils.isMmsOverWifiEnabled(context)) {
ConnectivityManager mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnMgr != null) {
NetworkInfo niWF = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if ((niWF != null) && (niWF.isConnected())) {
return true;
}
}
}
return false;
}
/**
* Returns true if sending / downloading using the carrier app has failed and completes the
* action using platform API's, otherwise false.
*/
protected boolean maybeFallbackToRegularDelivery(int carrierMessagingAppResult) {
if (carrierMessagingAppResult
== CarrierMessagingService.SEND_STATUS_RETRY_ON_CARRIER_NETWORK
|| carrierMessagingAppResult
== CarrierMessagingService.DOWNLOAD_STATUS_RETRY_ON_CARRIER_NETWORK) {
Timber.d("Sending/downloading MMS by IP failed.");
mRequestManager.addSimRequest(MmsRequest.this);
return true;
} else {
return false;
}
}
/**
* Converts from {@code carrierMessagingAppResult} to a platform result code.
*/
protected static int toSmsManagerResult(int carrierMessagingAppResult) {
switch (carrierMessagingAppResult) {
case CarrierMessagingService.SEND_STATUS_OK:
return Activity.RESULT_OK;
case CarrierMessagingService.SEND_STATUS_RETRY_ON_CARRIER_NETWORK:
return SmsManager.MMS_ERROR_RETRY;
default:
return SmsManager.MMS_ERROR_UNSPECIFIED;
}
}
/**
* Making the HTTP request to MMSC
*
* @param context The context
* @param netMgr The current {@link MmsNetworkManager}
* @param apn The APN setting
* @return The HTTP response data
* @throws MmsHttpException If any network error happens
*/
protected abstract byte[] doHttp(Context context, MmsNetworkManager netMgr, ApnSettings apn)
throws MmsHttpException;
/**
* @return The PendingIntent associate with the MMS sending invocation
*/
protected abstract PendingIntent getPendingIntent();
/**
* @return The queue should be used by this request, 0 is sending and 1 is downloading
*/
protected abstract int getQueueType();
/**
* Persist message into telephony if required (i.e. when auto-persisting is on or
* the calling app is non-default sms app for sending)
*
* @param context The context
* @param result The result code of execution
* @param response The response body
* @return The persisted URI of the message or null if we don't persist or fail
*/
protected abstract Uri persistIfRequired(Context context, int result, byte[] response);
/**
* Prepare to make the HTTP request - will download message for sending
* @return true if preparation succeeds (and request can proceed) else false
*/
protected abstract boolean prepareForHttpRequest();
/**
* Transfer the received response to the caller
*
* @param fillIn the intent that will be returned to the caller
* @param response the pdu to transfer
* @return true if response transfer succeeds else false
*/
protected abstract boolean transferResponse(Intent fillIn, byte[] response);
/**
* Revoke the content URI permission granted by the MMS app to the phone package.
*
* @param context The context
*/
protected abstract void revokeUriPermission(Context context);
}
| 15,169 | 37.600509 | 120 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/PhoneUtils.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.i18n.phonenumbers.NumberParseException;
import com.android.i18n.phonenumbers.PhoneNumberUtil;
import com.android.i18n.phonenumbers.Phonenumber;
import timber.log.Timber;
import java.lang.reflect.Method;
import java.util.Locale;
/**
* Utility to handle phone numbers.
*/
public class PhoneUtils {
/**
* Get a canonical national format phone number. If parsing fails, just return the
* original number.
*
* @param telephonyManager
* @param subId The SIM ID associated with this number
* @param phoneText The input phone number text
* @return The formatted number or the original phone number if failed to parse
*/
public static String getNationalNumber(TelephonyManager telephonyManager, int subId,
String phoneText) {
final String country = getSimOrDefaultLocaleCountry(telephonyManager, subId);
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
final Phonenumber.PhoneNumber parsed = getParsedNumber(phoneNumberUtil, phoneText, country);
if (parsed == null) {
return phoneText;
}
return phoneNumberUtil
.format(parsed, PhoneNumberUtil.PhoneNumberFormat.NATIONAL)
.replaceAll("\\D", "");
}
// Parse the input number into internal format
private static Phonenumber.PhoneNumber getParsedNumber(PhoneNumberUtil phoneNumberUtil,
String phoneText, String country) {
try {
final Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(phoneText, country);
if (phoneNumberUtil.isValidNumber(phoneNumber)) {
return phoneNumber;
} else {
Timber.e("getParsedNumber: not a valid phone number"
+ " for country " + country);
return null;
}
} catch (final NumberParseException e) {
Timber.e("getParsedNumber: Not able to parse phone number");
return null;
}
}
// Get the country/region either from the SIM ID or from locale
private static String getSimOrDefaultLocaleCountry(TelephonyManager telephonyManager,
int subId) {
String country = getSimCountry(telephonyManager, subId);
if (TextUtils.isEmpty(country)) {
country = Locale.getDefault().getCountry();
}
return country;
}
// Get country/region from SIM ID
private static String getSimCountry(TelephonyManager telephonyManager, int subId) {
String country = "";
try {
Method method = telephonyManager.getClass().getMethod("getSimCountryIso", int.class);
country = (String) method.invoke(telephonyManager, subId);
} catch (Exception e) {
country = telephonyManager.getSimCountryIso();
}
if (TextUtils.isEmpty(country)) {
return null;
}
return country.toUpperCase();
}
}
| 3,706 | 35.343137 | 100 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/SystemPropertiesProxy.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.content.Context;
import dalvik.system.DexFile;
import java.io.File;
import java.lang.reflect.Method;
public class SystemPropertiesProxy {
/**
* This class cannot be instantiated
*/
private SystemPropertiesProxy() {
}
/**
* Get the value for the given key.
*
* @return an empty string if the key isn't found
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(Context context, String key) throws IllegalArgumentException {
String ret = "";
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class;
Method get = SystemProperties.getMethod("get", paramTypes);
//Parameters
Object[] params = new Object[1];
params[0] = new String(key);
ret = (String) get.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = "";
//TODO
}
return ret;
}
/**
* Get the value for the given key.
*
* @return if the key isn't found, return def if it isn't null, or an empty string otherwise
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static String get(Context context, String key, String def) throws IllegalArgumentException {
String ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = String.class;
Method get = SystemProperties.getMethod("get", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new String(def);
ret = (String) get.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, and return as an integer.
*
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as an integer, or def if the key isn't found or
* cannot be parsed
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static Integer getInt(Context context, String key, int def) throws IllegalArgumentException {
Integer ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = int.class;
Method getInt = SystemProperties.getMethod("getInt", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Integer(def);
ret = (Integer) getInt.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, and return as a long.
*
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as a long, or def if the key isn't found or
* cannot be parsed
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static Long getLong(Context context, String key, long def) throws IllegalArgumentException {
Long ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = long.class;
Method getLong = SystemProperties.getMethod("getLong", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Long(def);
ret = (Long) getLong.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Get the value for the given key, returned as a boolean.
* Values 'n', 'no', '0', 'false' or 'off' are considered false.
* Values 'y', 'yes', '1', 'true' or 'on' are considered true.
* (case insensitive).
* If the key does not exist, or has any other value, then the default
* result is returned.
*
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as a boolean, or def if the key isn't found or is
* not able to be parsed as a boolean.
* @throws IllegalArgumentException if the key exceeds 32 characters
*/
public static Boolean getBoolean(Context context, String key, boolean def) throws IllegalArgumentException {
Boolean ret = def;
try {
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = cl.loadClass("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = boolean.class;
Method getBoolean = SystemProperties.getMethod("getBoolean", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new Boolean(def);
ret = (Boolean) getBoolean.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
ret = def;
//TODO
}
return ret;
}
/**
* Set the value for the given key.
*
* @throws IllegalArgumentException if the key exceeds 32 characters
* @throws IllegalArgumentException if the value exceeds 92 characters
*/
public static void set(Context context, String key, String val) throws IllegalArgumentException {
try {
@SuppressWarnings("unused")
DexFile df = new DexFile(new File("/system/app/Settings.apk"));
@SuppressWarnings("unused")
ClassLoader cl = context.getClassLoader();
@SuppressWarnings("rawtypes")
Class SystemProperties = Class.forName("android.os.SystemProperties");
//Parameters Types
@SuppressWarnings("rawtypes")
Class[] paramTypes = new Class[2];
paramTypes[0] = String.class;
paramTypes[1] = String.class;
Method set = SystemProperties.getMethod("set", paramTypes);
//Parameters
Object[] params = new Object[2];
params[0] = new String(key);
params[1] = new String(val);
set.invoke(SystemProperties, params);
} catch (IllegalArgumentException iAE) {
throw iAE;
} catch (Exception e) {
//TODO
}
}
}
| 8,911 | 29.108108 | 112 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/MmsNetworkManager.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.mms.service_alt;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.SSLCertificateSocketFactory;
import android.os.Build;
import android.os.SystemClock;
import com.android.mms.service_alt.exception.MmsNetworkException;
import com.squareup.okhttp.ConnectionPool;
import timber.log.Timber;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MmsNetworkManager implements com.squareup.okhttp.internal.Network {
// Timeout used to call ConnectivityManager.requestNetwork
private static final int NETWORK_REQUEST_TIMEOUT_MILLIS = 60 * 1000;
// Wait timeout for this class, a little bit longer than the above timeout
// to make sure we don't bail prematurely
private static final int NETWORK_ACQUIRE_TIMEOUT_MILLIS =
NETWORK_REQUEST_TIMEOUT_MILLIS + (5 * 1000);
// Borrowed from {@link android.net.Network}
private static final boolean httpKeepAlive =
Boolean.parseBoolean(System.getProperty("http.keepAlive", "true"));
private static final int httpMaxConnections =
httpKeepAlive ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0;
private static final long httpKeepAliveDurationMs =
Long.parseLong(System.getProperty("http.keepAliveDuration", "300000")); // 5 minutes.
private final Context mContext;
// The requested MMS {@link android.net.Network} we are holding
// We need this when we unbind from it. This is also used to indicate if the
// MMS network is available.
private Network mNetwork;
// The current count of MMS requests that require the MMS network
// If mMmsRequestCount is 0, we should release the MMS network.
private int mMmsRequestCount;
// This is really just for using the capability
private NetworkRequest mNetworkRequest;
// The callback to register when we request MMS network
private ConnectivityManager.NetworkCallback mNetworkCallback;
private volatile ConnectivityManager mConnectivityManager;
// The OkHttp's ConnectionPool used by the HTTP client associated with this network manager
private ConnectionPool mConnectionPool;
// The MMS HTTP client for this network
private MmsHttpClient mMmsHttpClient;
// The SIM ID which we use to connect
private final int mSubId;
private boolean permissionError = false;
public MmsNetworkManager(Context context, int subId) {
mContext = context;
mNetworkCallback = null;
mNetwork = null;
mMmsRequestCount = 0;
mConnectivityManager = null;
mConnectionPool = null;
mMmsHttpClient = null;
mSubId = subId;
if (!MmsRequest.useWifi(context)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
mNetworkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.setNetworkSpecifier(Integer.toString(mSubId))
.build();
} else {
mNetworkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_MMS)
.build();
}
} else {
mNetworkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build();
}
MmsConfigManager.getInstance().init(context);
}
/**
* Acquire the MMS network
*
* @throws MmsNetworkException if we fail to acquire it
*/
public Network acquireNetwork() throws MmsNetworkException {
synchronized (this) {
mMmsRequestCount += 1;
if (mNetwork != null) {
// Already available
Timber.d("MmsNetworkManager: already available");
return mNetwork;
}
Timber.d("MmsNetworkManager: start new network request");
// Not available, so start a new request
newRequest();
final long shouldEnd = SystemClock.elapsedRealtime() + NETWORK_ACQUIRE_TIMEOUT_MILLIS;
long waitTime = NETWORK_ACQUIRE_TIMEOUT_MILLIS;
while (waitTime > 0) {
try {
this.wait(waitTime);
} catch (InterruptedException e) {
Timber.w("MmsNetworkManager: acquire network wait interrupted");
}
if (mNetwork != null || permissionError) {
// Success
return mNetwork;
}
// Calculate remaining waiting time to make sure we wait the full timeout period
waitTime = shouldEnd - SystemClock.elapsedRealtime();
}
// Timed out, so release the request and fail
Timber.d("MmsNetworkManager: timed out");
releaseRequestLocked(mNetworkCallback);
throw new MmsNetworkException("Acquiring network timed out");
}
}
/**
* Release the MMS network when nobody is holding on to it.
*/
public void releaseNetwork() {
synchronized (this) {
if (mMmsRequestCount > 0) {
mMmsRequestCount -= 1;
Timber.d("MmsNetworkManager: release, count=" + mMmsRequestCount);
if (mMmsRequestCount < 1) {
releaseRequestLocked(mNetworkCallback);
}
}
}
}
/**
* Start a new {@link NetworkRequest} for MMS
*/
private void newRequest() {
final ConnectivityManager connectivityManager = getConnectivityManager();
mNetworkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
Timber.d("NetworkCallbackListener.onAvailable: network=" + network);
synchronized (MmsNetworkManager.this) {
mNetwork = network;
MmsNetworkManager.this.notifyAll();
}
}
@Override
public void onLost(Network network) {
super.onLost(network);
Timber.d("NetworkCallbackListener.onLost: network=" + network);
synchronized (MmsNetworkManager.this) {
releaseRequestLocked(this);
MmsNetworkManager.this.notifyAll();
}
}
// @Override
// public void onUnavailable() {
// super.onUnavailable();
// Timber.d("NetworkCallbackListener.onUnavailable");
// synchronized (MmsNetworkManager.this) {
// releaseRequestLocked(this);
// MmsNetworkManager.this.notifyAll();
// }
// }
};
try {
connectivityManager.requestNetwork(
mNetworkRequest, mNetworkCallback);
} catch (SecurityException e) {
Timber.e(e, "permission exception... skipping it for testing purposes");
permissionError = true;
}
}
/**
* Release the current {@link NetworkRequest} for MMS
*
* @param callback the {@link ConnectivityManager.NetworkCallback} to unregister
*/
private void releaseRequestLocked(ConnectivityManager.NetworkCallback callback) {
if (callback != null) {
final ConnectivityManager connectivityManager = getConnectivityManager();
try {
connectivityManager.unregisterNetworkCallback(callback);
} catch (Exception e) {
Timber.e(e, "couldn't unregister");
}
}
resetLocked();
}
/**
* Reset the state
*/
private void resetLocked() {
mNetworkCallback = null;
mNetwork = null;
mMmsRequestCount = 0;
// Currently we follow what android.net.Network does with ConnectionPool,
// which is per Network object. So if Network changes, we should clear
// out the ConnectionPool and thus the MmsHttpClient (since it is linked
// to a specific ConnectionPool).
mConnectionPool = null;
mMmsHttpClient = null;
}
private static final InetAddress[] EMPTY_ADDRESS_ARRAY = new InetAddress[0];
@Override
public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
Network network = null;
synchronized (this) {
if (mNetwork == null) {
return EMPTY_ADDRESS_ARRAY;
}
network = mNetwork;
}
return network.getAllByName(host);
}
private ConnectivityManager getConnectivityManager() {
if (mConnectivityManager == null) {
mConnectivityManager = (ConnectivityManager) mContext.getSystemService(
Context.CONNECTIVITY_SERVICE);
}
return mConnectivityManager;
}
private ConnectionPool getOrCreateConnectionPoolLocked() {
if (mConnectionPool == null) {
mConnectionPool = new ConnectionPool(httpMaxConnections, httpKeepAliveDurationMs);
}
return mConnectionPool;
}
/**
* Get an MmsHttpClient for the current network
*
* @return The MmsHttpClient instance
*/
public MmsHttpClient getOrCreateHttpClient() {
synchronized (this) {
if (mMmsHttpClient == null) {
if (mNetwork != null) {
// Create new MmsHttpClient for the current Network
mMmsHttpClient = new MmsHttpClient(
mContext,
mNetwork.getSocketFactory(),
MmsNetworkManager.this,
getOrCreateConnectionPoolLocked());
} else if (permissionError) {
mMmsHttpClient = new MmsHttpClient(
mContext,
new SSLCertificateSocketFactory(NETWORK_REQUEST_TIMEOUT_MILLIS),
MmsNetworkManager.this,
getOrCreateConnectionPoolLocked());
}
}
return mMmsHttpClient;
}
}
/**
* Get the APN name for the active network
*
* @return The APN name if available, otherwise null
*/
public String getApnName() {
Network network = null;
synchronized (this) {
if (mNetwork == null) {
Timber.d("MmsNetworkManager: getApnName: network not available");
mNetworkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build();
return null;
}
network = mNetwork;
}
String apnName = null;
final ConnectivityManager connectivityManager = getConnectivityManager();
NetworkInfo mmsNetworkInfo = connectivityManager.getNetworkInfo(network);
if (mmsNetworkInfo != null) {
apnName = mmsNetworkInfo.getExtraInfo();
}
Timber.d("MmsNetworkManager: getApnName: " + apnName);
return apnName;
}
}
| 12,337 | 36.615854 | 98 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/exception/ApnException.java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.mms.service_alt.exception;
/**
* APN exception
*/
public class ApnException extends Exception {
public ApnException() {
super();
}
public ApnException(String message) {
super(message);
}
public ApnException(Throwable cause) {
super(cause);
}
public ApnException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,036 | 24.925 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/exception/MmsNetworkException.java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.mms.service_alt.exception;
/**
* MMS network exception
*/
public class MmsNetworkException extends Exception {
public MmsNetworkException() {
super();
}
public MmsNetworkException(String message) {
super(message);
}
public MmsNetworkException(Throwable cause) {
super(cause);
}
public MmsNetworkException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,079 | 26 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/service_alt/exception/MmsHttpException.java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.mms.service_alt.exception;
/**
* HTTP exception
*/
public class MmsHttpException extends Exception {
// Optional HTTP status code. 0 means ignore. Otherwise this
// should be a valid HTTP status code.
private final int mStatusCode;
public MmsHttpException(int statusCode) {
super();
mStatusCode = statusCode;
}
public MmsHttpException(int statusCode, String message) {
super(message);
mStatusCode = statusCode;
}
public MmsHttpException(int statusCode, Throwable cause) {
super(cause);
mStatusCode = statusCode;
}
public MmsHttpException(int statusCode, String message, Throwable cause) {
super(message, cause);
mStatusCode = statusCode;
}
public int getStatusCode() {
return mStatusCode;
}
}
| 1,466 | 27.764706 | 78 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/MmsSystemEventReceiver.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Telephony.Mms;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
/**
* MmsSystemEventReceiver receives the
* and performs a series of operations which may include:
* <ul>
* <li>Show/hide the icon in notification area which is used to indicate
* whether there is new incoming message.</li>
* <li>Resend the MM's in the outbox.</li>
* </ul>
*/
public class MmsSystemEventReceiver extends BroadcastReceiver {
private static ConnectivityManager mConnMgr = null;
public static void wakeUpService(Context context) {
}
@Override
public void onReceive(Context context, Intent intent) {
Timber.v("Intent received: " + intent);
if (!Utils.isDefaultSmsApp(context)) {
Timber.v("not default sms app, cancelling");
return;
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (Utils.isMmsOverWifiEnabled(context)) {
NetworkInfo niWF = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if ((niWF != null) && (niWF.isConnected())) {
Timber.v("TYPE_WIFI connected");
wakeUpService(context);
}
} else {
boolean mobileDataEnabled = Utils.isMobileDataEnabled(context);
if (!mobileDataEnabled) {
Timber.v("mobile data turned off, bailing");
//Utils.setMobileDataEnabled(context, true);
return;
}
NetworkInfo mmsNetworkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
if (mmsNetworkInfo == null) {
return;
}
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
Timber.v("TYPE_MOBILE_MMS available = " + available + ", isConnected = " + isConnected);
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
}
| 3,918 | 38.19 | 106 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/HttpUtils.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Config;
import com.android.mms.MmsConfig;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import timber.log.Timber;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
public class HttpUtils {
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
public static final int HTTP_POST_METHOD = 1;
public static final int HTTP_GET_METHOD = 2;
private static final int MMS_READ_BUFFER = 4096;
// This is the value to use for the "Accept-Language" header.
// Once it becomes possible for the user to change the locale
// setting, this should no longer be static. We should call
// getHttpAcceptLanguage instead.
private static final String HDR_VALUE_ACCEPT_LANGUAGE;
static {
HDR_VALUE_ACCEPT_LANGUAGE = getCurrentAcceptLanguage(Locale.getDefault());
}
// Definition for necessary HTTP headers.
private static final String HDR_KEY_ACCEPT = "Accept";
private static final String HDR_KEY_ACCEPT_LANGUAGE = "Accept-Language";
private static final String HDR_VALUE_ACCEPT =
"*/*, application/vnd.wap.mms-message, application/vnd.wap.sic";
private HttpUtils() {
// To forbidden instantiate this class.
}
/**
* A helper method to send or retrieve data through HTTP protocol.
*
* @param token The token to identify the sending progress.
* @param url The URL used in a GET request. Null when the method is
* HTTP_POST_METHOD.
* @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
* @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
*/
public static byte[] httpConnection(Context context, long token,
String url, byte[] pdu, int method, boolean isProxySet,
String proxyHost, int proxyPort) throws IOException {
if (url == null) {
throw new IllegalArgumentException("URL must not be null.");
}
Timber.v("httpConnection: params list");
Timber.v("\ttoken\t\t= " + token);
Timber.v("\turl\t\t= " + url);
Timber.v("\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST"
: ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
Timber.v("\tisProxySet\t= " + isProxySet);
Timber.v("\tproxyHost\t= " + proxyHost);
Timber.v("\tproxyPort\t= " + proxyPort);
// TODO Print out binary data more readable.
//Timber.v("\tpdu\t\t= " + Arrays.toString(pdu));
AndroidHttpClient client = null;
try {
// Make sure to use a proxy which supports CONNECT.
URI hostUrl = new URI(url);
HttpHost target = new HttpHost(
hostUrl.getHost(), hostUrl.getPort(),
HttpHost.DEFAULT_SCHEME_NAME);
client = createHttpClient(context);
HttpRequest req = null;
switch(method) {
case HTTP_POST_METHOD:
ProgressCallbackEntity entity = new ProgressCallbackEntity(
context, token, pdu);
// Set request content type.
entity.setContentType("application/vnd.wap.mms-message");
HttpPost post = new HttpPost(url);
post.setEntity(entity);
req = post;
break;
case HTTP_GET_METHOD:
req = new HttpGet(url);
break;
default:
Timber.e("Unknown HTTP method: " + method
+ ". Must be one of POST[" + HTTP_POST_METHOD
+ "] or GET[" + HTTP_GET_METHOD + "].");
return null;
}
// Set route parameters for the request.
HttpParams params = client.getParams();
if (isProxySet) {
ConnRouteParams.setDefaultProxy(
params, new HttpHost(proxyHost, proxyPort));
}
req.setParams(params);
// Set necessary HTTP headers for MMS transmission.
req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
{
String xWapProfileTagName = MmsConfig.getUaProfTagName();
String xWapProfileUrl = MmsConfig.getUaProfUrl();
if (xWapProfileUrl != null) {
Timber.d("[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
req.addHeader(xWapProfileTagName, xWapProfileUrl);
}
}
// Extra http parameters. Split by '|' to get a list of value pairs.
// Separate each pair by the first occurrence of ':' to obtain a name and
// value. Replace the occurrence of the string returned by
// MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
// the value.
String extraHttpParams = MmsConfig.getHttpParams();
if (extraHttpParams != null) {
String line1Number = ((TelephonyManager)context
.getSystemService(Context.TELEPHONY_SERVICE))
.getLine1Number();
String line1Key = MmsConfig.getHttpParamsLine1Key();
String paramList[] = extraHttpParams.split("\\|");
for (String paramPair : paramList) {
String splitPair[] = paramPair.split(":", 2);
if (splitPair.length == 2) {
String name = splitPair[0].trim();
String value = splitPair[1].trim();
if (line1Key != null) {
value = value.replace(line1Key, line1Number);
}
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
req.addHeader(name, value);
}
}
}
}
req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);
HttpResponse response = client.execute(target, req);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) { // HTTP 200 is success.
throw new IOException("HTTP error: " + status.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
byte[] body = null;
if (entity != null) {
try {
if (entity.getContentLength() > 0) {
body = new byte[(int) entity.getContentLength()];
DataInputStream dis = new DataInputStream(entity.getContent());
try {
dis.readFully(body);
} finally {
try {
dis.close();
} catch (IOException e) {
Timber.e("Error closing input stream: " + e.getMessage());
}
}
}
if (entity.isChunked()) {
Timber.v("httpConnection: transfer encoding is chunked");
int bytesTobeRead = MmsConfig.getMaxMessageSize();
byte[] tempBody = new byte[bytesTobeRead];
DataInputStream dis = new DataInputStream(entity.getContent());
try {
int bytesRead = 0;
int offset = 0;
boolean readError = false;
do {
try {
bytesRead = dis.read(tempBody, offset, bytesTobeRead);
} catch (IOException e) {
readError = true;
Timber.e("httpConnection: error reading input stream" + e.getMessage());
break;
}
if (bytesRead > 0) {
bytesTobeRead -= bytesRead;
offset += bytesRead;
}
} while (bytesRead >= 0 && bytesTobeRead > 0);
if (bytesRead == -1 && offset > 0 && !readError) {
// offset is same as total number of bytes read
// bytesRead will be -1 if the data was read till the eof
body = new byte[offset];
System.arraycopy(tempBody, 0, body, 0, offset);
Timber.v("httpConnection: Chunked response length [" + Integer.toString(offset) + "]");
} else {
Timber.e("httpConnection: Response entity too large or empty");
}
} finally {
try {
dis.close();
} catch (IOException e) {
Timber.e("Error closing input stream: " + e.getMessage());
}
}
}
} finally {
if (entity != null) {
entity.consumeContent();
}
}
}
return body;
} catch (URISyntaxException e) {
handleHttpConnectionException(e, url);
} catch (IllegalStateException e) {
handleHttpConnectionException(e, url);
} catch (IllegalArgumentException e) {
handleHttpConnectionException(e, url);
} catch (SocketException e) {
handleHttpConnectionException(e, url);
} catch (Exception e) {
handleHttpConnectionException(e, url);
}
finally {
if (client != null) {
client.close();
}
}
return null;
}
private static void handleHttpConnectionException(Exception exception, String url)
throws IOException {
// Inner exception should be logged to make life easier.
Timber.e("Url: " + url + "\n" + exception.getMessage());
IOException e = new IOException(exception.getMessage());
e.initCause(exception);
throw e;
}
private static AndroidHttpClient createHttpClient(Context context) {
String userAgent = MmsConfig.getUserAgent();
AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent, context);
HttpParams params = client.getParams();
HttpProtocolParams.setContentCharset(params, "UTF-8");
// set the socket timeout
int soTimeout = MmsConfig.getHttpSocketTimeout();
Timber.d("[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, " + ", UA=" + userAgent);
HttpConnectionParams.setSoTimeout(params, soTimeout);
return client;
}
private static final String ACCEPT_LANG_FOR_US_LOCALE = "en-US";
/**
* Return the Accept-Language header. Use the current locale plus
* US if we are in a different locale than US.
* This code copied from the browser's WebSettings.java
* @return Current AcceptLanguage String.
*/
public static String getCurrentAcceptLanguage(Locale locale) {
StringBuilder buffer = new StringBuilder();
addLocaleToHttpAcceptLanguage(buffer, locale);
if (!Locale.US.equals(locale)) {
if (buffer.length() > 0) {
buffer.append(", ");
}
buffer.append(ACCEPT_LANG_FOR_US_LOCALE);
}
return buffer.toString();
}
/**
* Convert obsolete language codes, including Hebrew/Indonesian/Yiddish,
* to new standard.
*/
private static String convertObsoleteLanguageCodeToNew(String langCode) {
if (langCode == null) {
return null;
}
if ("iw".equals(langCode)) {
// Hebrew
return "he";
} else if ("in".equals(langCode)) {
// Indonesian
return "id";
} else if ("ji".equals(langCode)) {
// Yiddish
return "yi";
}
return langCode;
}
private static void addLocaleToHttpAcceptLanguage(StringBuilder builder,
Locale locale) {
String language = convertObsoleteLanguageCodeToNew(locale.getLanguage());
if (language != null) {
builder.append(language);
String country = locale.getCountry();
if (country != null) {
builder.append("-");
builder.append(country);
}
}
}
}
| 14,733 | 40.271709 | 119 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/TransactionBundle.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.os.Bundle;
/**
* A wrapper around the Bundle instances used to start the TransactionService.
* It provides high-level APIs to set the information required for the latter to
* instantiate transactions.
*/
public class TransactionBundle {
/**
* Key for the transaction-type.
* Allowed values for this key are: TYPE_PUSH_TRANSACTION, TYPE_RETRIEVE_TRANSACTION,
* TYPE_SEND_TRANSACTION, and TYPE_READREC_TRANSACTION.
*/
public static final String TRANSACTION_TYPE = "type";
/**
* Key of the push-data.
* Used when TRANSACTION_TYPE is TYPE_PUSH_TRANSACTION.
*/
private static final String PUSH_DATA = "mms-push-data";
public static final String LOLLIPOP_RECEIVING = "receive_with_new_method";
/**
* Key of the MMSC server URL.
*/
private static final String MMSC_URL = "mmsc-url";
/**
* Key of the HTTP Proxy address.
*/
private static final String PROXY_ADDRESS = "proxy-address";
/**
* Key of the HTTP Proxy port.
*/
private static final String PROXY_PORT = "proxy-port";
/**
* Key of the URI.
* Indicates the URL of the M-Retrieve.conf in TYPE_RETRIEVE_TRANSACTION, or the
* Uri of the M-Send.req/M-Read-Rec.ind in TYPE_SEND_TRANSACTION and
* TYPE_READREC_TRANSACTION, respectively.
*/
public static final String URI = "uri";
/**
* This is the real Bundle to be sent to the TransactionService upon calling
* startService.
*/
private final Bundle mBundle;
/**
* Private constructor.
*
* @param transactionType
*/
private TransactionBundle(int transactionType) {
mBundle = new Bundle();
mBundle.putInt(TRANSACTION_TYPE, transactionType);
}
/**
* Constructor of a bundle used for TransactionBundle instances of type
* TYPE_RETRIEVE_TRANSACTION, TYPE_SEND_TRANSACTION, and TYPE_READREC_TRANSACTION.
*
* @param transactionType
* @param uri The relevant URI for this transaction. Indicates the URL of the
* M-Retrieve.conf in TYPE_RETRIEVE_TRANSACTION, or the Uri of the
* M-Send.req/M-Read-Rec.ind in TYPE_SEND_TRANSACTION and
* TYPE_READREC_TRANSACTION, respectively.
*/
public TransactionBundle(int transactionType, String uri) {
this(transactionType);
mBundle.putString(URI, uri);
}
/**
* Constructor of a transaction bundle used for incoming bundle instances.
*
* @param bundle The incoming bundle
*/
public TransactionBundle(Bundle bundle) {
mBundle = bundle;
}
public void setConnectionSettings(String mmscUrl,
String proxyAddress,
int proxyPort) {
mBundle.putString(MMSC_URL, mmscUrl);
mBundle.putString(PROXY_ADDRESS, proxyAddress);
mBundle.putInt(PROXY_PORT, proxyPort);
}
public void setConnectionSettings(TransactionSettings settings) {
setConnectionSettings(
settings.getMmscUrl(),
settings.getProxyAddress(),
settings.getProxyPort());
}
public Bundle getBundle() {
return mBundle;
}
public int getTransactionType() {
return mBundle.getInt(TRANSACTION_TYPE);
}
public String getUri() {
return mBundle.getString(URI);
}
public byte[] getPushData() {
return mBundle.getByteArray(PUSH_DATA);
}
public String getMmscUrl() {
return mBundle.getString(MMSC_URL);
}
public String getProxyAddress() {
return mBundle.getString(PROXY_ADDRESS);
}
public int getProxyPort() {
return mBundle.getInt(PROXY_PORT);
}
@Override
public String toString() {
return "transactionType: " + getTransactionType() +
" uri: " + getUri() +
" mmscUrl: " + getMmscUrl() +
" proxyAddress: " + getProxyAddress() +
" proxyPort: " + getProxyPort();
}
}
| 4,625 | 28.464968 | 89 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/Observable.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* 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.mms.transaction;
import java.util.ArrayList;
import java.util.Iterator;
/**
* An interface to represent the state of an observable Transaction.
*/
public abstract class Observable {
private final ArrayList<Observer> mObservers;
private Iterator<Observer> mIterator;
public Observable() {
mObservers = new ArrayList<Observer>();
}
/**
* This method is implemented by the observable to represent its
* current state.
*
* @return A TransactionState object.
*/
abstract public TransactionState getState();
/**
* Attach an observer to this object.
*
* @param observer The observer object to be attached to.
*/
public void attach(Observer observer) {
mObservers.add(observer);
}
/**
* Detach an observer from this object.
*
* @param observer The observer object to be detached from.
*/
public void detach(Observer observer) {
if (mIterator != null) {
mIterator.remove();
} else {
mObservers.remove(observer);
}
}
/**
* Notify all observers that a status change has occurred.
*/
public void notifyObservers() {
mIterator = mObservers.iterator();
try {
while (mIterator.hasNext()) {
mIterator.next().update(this);
}
} finally {
mIterator = null;
}
}
}
| 2,123 | 25.886076 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/ProgressCallbackEntity.java | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* 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.mms.transaction;
import android.content.Context;
import android.content.Intent;
import com.klinker.android.send_message.BroadcastUtils;
import org.apache.http.entity.ByteArrayEntity;
import java.io.IOException;
import java.io.OutputStream;
public class ProgressCallbackEntity extends ByteArrayEntity {
private static final int DEFAULT_PIECE_SIZE = 4096;
public static final String PROGRESS_STATUS_ACTION = "com.android.mms.PROGRESS_STATUS";
public static final int PROGRESS_START = -1;
public static final int PROGRESS_ABORT = -2;
public static final int PROGRESS_COMPLETE = 100;
private final Context mContext;
private final byte[] mContent;
private final long mToken;
public ProgressCallbackEntity(Context context, long token, byte[] b) {
super(b);
mContext = context;
mContent = b;
mToken = token;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
boolean completed = false;
try {
broadcastProgressIfNeeded(PROGRESS_START);
int pos = 0, totalLen = mContent.length;
while (pos < totalLen) {
int len = totalLen - pos;
if (len > DEFAULT_PIECE_SIZE) {
len = DEFAULT_PIECE_SIZE;
}
outstream.write(mContent, pos, len);
outstream.flush();
pos += len;
broadcastProgressIfNeeded(100 * pos / totalLen);
}
broadcastProgressIfNeeded(PROGRESS_COMPLETE);
completed = true;
} finally {
if (!completed) {
broadcastProgressIfNeeded(PROGRESS_ABORT);
}
}
}
private void broadcastProgressIfNeeded(int progress) {
if (mToken > 0) {
Intent intent = new Intent(PROGRESS_STATUS_ACTION);
intent.putExtra("progress", progress);
intent.putExtra("token", mToken);
BroadcastUtils.sendExplicitBroadcast(mContext, intent, PROGRESS_STATUS_ACTION);
}
}
}
| 2,910 | 31.344444 | 91 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/TransactionState.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.transaction;
import android.net.Uri;
/**
* TransactionState intends to encapsulate all the informations which would
* be known by the observers of transactions. To encapsulate Transaction-
* State into an intent, it should implement Parcelable interface.
*/
public class TransactionState {
/**
* Result code indicates the Transaction has not started.
*/
public static final int INITIALIZED = 0;
/**
* Result code indicates the Transaction successfully complete.
*/
public static final int SUCCESS = 1;
/**
* Result code indicates the Transaction failed.
*/
public static final int FAILED = 2;
private Uri mContentUri;
private int mState;
public TransactionState() {
mState = INITIALIZED;
mContentUri = null;
}
/**
* To represent the current state(or the result of processing) to the
* ones who wants to know the state.
*
* @return Current state of the Transaction.
*/
public synchronized int getState() {
return mState;
}
/**
* To set the state of transaction. This method is only invoked by
* the transactions.
*
* @param state The current state of transaction.
*/
synchronized void setState(int state) {
if ((state < INITIALIZED) && (state > FAILED)) {
throw new IllegalArgumentException("Bad state: " + state);
}
mState = state;
}
/**
* To represent the result uri of transaction such as uri of MM.
*
* @return Result uri.
*/
public synchronized Uri getContentUri() {
return mContentUri;
}
/**
* To set the result uri. This method is only invoked by the transactions.
*
* @param uri The result uri.
*/
synchronized void setContentUri(Uri uri) {
mContentUri = uri;
}
}
| 2,548 | 27.322222 | 78 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/DownloadManager.java |
package com.android.mms.transaction;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.text.TextUtils;
import com.android.mms.MmsConfig;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.MmsReceivedReceiver;
import com.klinker.android.send_message.SmsManagerFactory;
import timber.log.Timber;
import java.io.File;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* In order to avoid downloading duplicate MMS.
* We should manage to call SMSManager.downloadMultimediaMessage().
*/
public class DownloadManager {
private static DownloadManager ourInstance = new DownloadManager();
private static final ConcurrentHashMap<String, MmsDownloadReceiver> mMap = new ConcurrentHashMap<>();
public static DownloadManager getInstance() {
return ourInstance;
}
private DownloadManager() {
}
public void downloadMultimediaMessage(final Context context, final String location, Uri uri, boolean byPush, int subscriptionId) {
if (location == null || mMap.get(location) != null) {
return;
}
// TransactionService can keep uri and location in memory while SmsManager download Mms.
if (!isNotificationExist(context, location)) {
return;
}
MmsDownloadReceiver receiver = new MmsDownloadReceiver();
mMap.put(location, receiver);
// Use unique action in order to avoid cancellation of notifying download result.
context.getApplicationContext().registerReceiver(receiver, new IntentFilter(receiver.mAction));
Timber.v("receiving with system method");
final String fileName = "download." + String.valueOf(Math.abs(new Random().nextLong())) + ".dat";
File mDownloadFile = new File(context.getCacheDir(), fileName);
Uri contentUri = (new Uri.Builder())
.authority(context.getPackageName() + ".MmsFileProvider")
.path(fileName)
.scheme(ContentResolver.SCHEME_CONTENT)
.build();
Intent download = new Intent(receiver.mAction);
download.putExtra(MmsReceivedReceiver.EXTRA_FILE_PATH, mDownloadFile.getPath());
download.putExtra(MmsReceivedReceiver.EXTRA_LOCATION_URL, location);
download.putExtra(MmsReceivedReceiver.EXTRA_TRIGGER_PUSH, byPush);
download.putExtra(MmsReceivedReceiver.EXTRA_URI, uri);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, download, PendingIntent.FLAG_CANCEL_CURRENT);
final SmsManager smsManager = SmsManagerFactory.INSTANCE.createSmsManager(subscriptionId);
Bundle configOverrides = new Bundle();
String httpParams = MmsConfig.getHttpParams();
if (!TextUtils.isEmpty(httpParams)) {
configOverrides.putString(SmsManager.MMS_CONFIG_HTTP_PARAMS, httpParams);
}
grantUriPermission(context, contentUri);
smsManager.downloadMultimediaMessage(context, location, contentUri, configOverrides, pendingIntent);
}
private void grantUriPermission(Context context, Uri contentUri) {
context.grantUriPermission(context.getPackageName() + ".MmsFileProvider",
contentUri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
private static class MmsDownloadReceiver extends BroadcastReceiver {
private static final String ACTION_PREFIX = "com.android.mms.transaction.DownloadManager$MmsDownloadReceiver.";
private final String mAction;
MmsDownloadReceiver() {
mAction = ACTION_PREFIX + UUID.randomUUID().toString();
}
@Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MMS DownloadReceiver");
wakeLock.acquire(60 * 1000);
Intent newIntent = (Intent) intent.clone();
newIntent.setAction(MmsReceivedReceiver.MMS_RECEIVED);
BroadcastUtils.sendExplicitBroadcast(context, newIntent, MmsReceivedReceiver.MMS_RECEIVED);
}
}
public static void finishDownload(String location) {
if (location != null) {
mMap.remove(location);
}
}
private static boolean isNotificationExist(Context context, String location) {
String selection = Telephony.Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[] { location };
Cursor c = SqliteWrapper.query(
context, context.getContentResolver(),
Telephony.Mms.CONTENT_URI, new String[] { Telephony.Mms._ID },
selection, selectionArgs, null);
if (c != null) {
try {
if (c.getCount() > 0) {
return true;
}
} finally {
c.close();
}
}
return false;
}
}
| 5,548 | 37.804196 | 134 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/AbstractRetryScheme.java | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* 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.mms.transaction;
public abstract class AbstractRetryScheme {
public static final int OUTGOING = 1;
public static final int INCOMING = 2;
protected int mRetriedTimes;
public AbstractRetryScheme(int retriedTimes) {
mRetriedTimes = retriedTimes;
}
abstract public int getRetryLimit();
abstract public long getWaitingInterval();
}
| 1,043 | 30.636364 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/SendTransaction.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Sent;
import android.text.TextUtils;
import com.android.mms.util.RateController;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.SendConf;
import com.google.android.mms.pdu_alt.SendReq;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
import java.util.Arrays;
/**
* The SendTransaction is responsible for sending multimedia messages
* (M-Send.req) to the MMSC server. It:
*
* <ul>
* <li>Loads the multimedia message from storage (Outbox).
* <li>Packs M-Send.req and sends it.
* <li>Retrieves confirmation data from the server (M-Send.conf).
* <li>Parses confirmation message and handles it.
* <li>Moves sent multimedia message from Outbox to Sent.
* <li>Notifies the TransactionService about successful completion.
* </ul>
*/
public class SendTransaction extends Transaction implements Runnable {
private Thread mThread;
public final Uri mSendReqURI;
public SendTransaction(Context context,
int transId, TransactionSettings connectionSettings, String uri) {
super(context, transId, connectionSettings);
mSendReqURI = Uri.parse(uri);
mId = uri;
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
/*
* (non-Javadoc)
* @see com.android.mms.Transaction#process()
*/
@Override
public void process() {
mThread = new Thread(this, "SendTransaction");
mThread.start();
}
public void run() {
StringBuilder builder = new StringBuilder();
try {
RateController.init(mContext);
RateController rateCtlr = RateController.getInstance();
if (rateCtlr.isLimitSurpassed() && !rateCtlr.isAllowedByUser()) {
Timber.e("Sending rate limit surpassed.");
return;
}
// Load M-Send.req from outbox
PduPersister persister = PduPersister.getPduPersister(mContext);
SendReq sendReq = (SendReq) persister.load(mSendReqURI);
// Update the 'date' field of the PDU right before sending it.
long date = System.currentTimeMillis() / 1000L;
sendReq.setDate(date);
// Persist the new date value into database.
ContentValues values = new ContentValues(1);
values.put(Mms.DATE, date);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
mSendReqURI, values, null, null);
// fix bug 2100169: insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
if (!TextUtils.isEmpty(lineNumber)) {
sendReq.setFrom(new EncodedStringValue(lineNumber));
}
// Pack M-Send.req, send it, retrieve confirmation data, and parse it
long tokenKey = ContentUris.parseId(mSendReqURI);
byte[] response = sendPdu(SendingProgressTokenManager.get(tokenKey),
new PduComposer(mContext, sendReq).make());
SendingProgressTokenManager.remove(tokenKey);
String respStr = new String(response);
builder.append("[SendTransaction] run: send mms msg (" + mId + "), resp=" + respStr);
Timber.d("[SendTransaction] run: send mms msg (" + mId + "), resp=" + respStr);
SendConf conf = (SendConf) new PduParser(response).parse();
if (conf == null) {
Timber.e("No M-Send.conf received.");
builder.append("No M-Send.conf received.\n");
}
// Check whether the responding Transaction-ID is consistent
// with the sent one.
byte[] reqId = sendReq.getTransactionId();
byte[] confId = conf.getTransactionId();
if (!Arrays.equals(reqId, confId)) {
Timber.e("Inconsistent Transaction-ID: req="
+ new String(reqId) + ", conf=" + new String(confId));
builder.append("Inconsistent Transaction-ID: req="
+ new String(reqId) + ", conf=" + new String(confId) + "\n");
return;
}
// From now on, we won't save the whole M-Send.conf into
// our database. Instead, we just save some interesting fields
// into the related M-Send.req.
values = new ContentValues(2);
int respStatus = conf.getResponseStatus();
values.put(Mms.RESPONSE_STATUS, respStatus);
if (respStatus != PduHeaders.RESPONSE_STATUS_OK) {
SqliteWrapper.update(mContext, mContext.getContentResolver(),
mSendReqURI, values, null, null);
Timber.e("Server returned an error code: " + respStatus);
builder.append("Server returned an error code: " + respStatus + "\n");
return;
}
String messageId = PduPersister.toIsoString(conf.getMessageId());
values.put(Mms.MESSAGE_ID, messageId);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
mSendReqURI, values, null, null);
// Move M-Send.req from Outbox into Sent.
Uri uri = persister.move(mSendReqURI, Sent.CONTENT_URI);
mTransactionState.setState(TransactionState.SUCCESS);
mTransactionState.setContentUri(uri);
} catch (Throwable t) {
Timber.e(t, "error");
} finally {
if (mTransactionState.getState() != TransactionState.SUCCESS) {
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mSendReqURI);
Timber.e("Delivery failed.");
builder.append("Delivery failed\n");
Intent intent = new Intent(com.klinker.android.send_message.Transaction.MMS_ERROR);
intent.putExtra("stack", builder.toString());
BroadcastUtils.sendExplicitBroadcast(
mContext, intent, com.klinker.android.send_message.Transaction.MMS_ERROR);
}
notifyObservers();
}
}
@Override
public int getType() {
return SEND_TRANSACTION;
}
}
| 7,621 | 39.978495 | 99 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/TransactionService.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.MmsSms.PendingMessages;
import android.text.TextUtils;
import android.widget.Toast;
import com.android.mms.util.RateController;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.R;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
import java.io.IOException;
import java.util.ArrayList;
/**
* The TransactionService of the MMS Client is responsible for handling requests
* to initiate client-transactions sent from:
* <ul>
* <li>The Proxy-Relay (Through Push messages)</li>
* <li>The composer/viewer activities of the MMS Client (Through intents)</li>
* </ul>
* The TransactionService runs locally in the same process as the application.
* It contains a HandlerThread to which messages are posted from the
* intent-receivers of this application.
* <p/>
* <b>IMPORTANT</b>: This is currently the only instance in the system in
* which simultaneous connectivity to both the mobile data network and
* a Wi-Fi network is allowed. This makes the code for handling network
* connectivity somewhat different than it is in other applications. In
* particular, we want to be able to send or receive MMS messages when
* a Wi-Fi connection is active (which implies that there is no connection
* to the mobile data network). This has two main consequences:
* <ul>
* <li>Testing for current network connectivity ({@link android.net.NetworkInfo#isConnected()} is
* not sufficient. Instead, the correct test is for network availability
* ({@link android.net.NetworkInfo#isAvailable()}).</li>
* <li>If the mobile data network is not in the connected state, but it is available,
* we must initiate setup of the mobile data connection, and defer handling
* the MMS transaction until the connection is established.</li>
* </ul>
*/
public class TransactionService extends Service implements Observer {
/**
* Used to identify notification intents broadcasted by the
* TransactionService when a Transaction is completed.
*/
public static final String TRANSACTION_COMPLETED_ACTION =
"android.intent.action.TRANSACTION_COMPLETED_ACTION";
/**
* Action for the Intent which is sent by Alarm service to launch
* TransactionService.
*/
public static final String ACTION_ONALARM = "android.intent.action.ACTION_ONALARM";
/**
* Action for the Intent which is sent when the user turns on the auto-retrieve setting.
* This service gets started to auto-retrieve any undownloaded messages.
*/
public static final String ACTION_ENABLE_AUTO_RETRIEVE
= "android.intent.action.ACTION_ENABLE_AUTO_RETRIEVE";
/**
* Used as extra key in notification intents broadcasted by the TransactionService
* when a Transaction is completed (TRANSACTION_COMPLETED_ACTION intents).
* Allowed values for this key are: TransactionState.INITIALIZED,
* TransactionState.SUCCESS, TransactionState.FAILED.
*/
public static final String STATE = "state";
/**
* Used as extra key in notification intents broadcasted by the TransactionService
* when a Transaction is completed (TRANSACTION_COMPLETED_ACTION intents).
* Allowed values for this key are any valid content uri.
*/
public static final String STATE_URI = "uri";
private static final int EVENT_TRANSACTION_REQUEST = 1;
private static final int EVENT_CONTINUE_MMS_CONNECTIVITY = 3;
private static final int EVENT_HANDLE_NEXT_PENDING_TRANSACTION = 4;
private static final int EVENT_NEW_INTENT = 5;
private static final int EVENT_QUIT = 100;
private static final int TOAST_MSG_QUEUED = 1;
private static final int TOAST_DOWNLOAD_LATER = 2;
private static final int TOAST_NO_APN = 3;
private static final int TOAST_NONE = -1;
// How often to extend the use of the MMS APN while a transaction
// is still being processed.
private static final int APN_EXTENSION_WAIT = 30 * 1000;
private ServiceHandler mServiceHandler;
private Looper mServiceLooper;
private final ArrayList<Transaction> mProcessing = new ArrayList<Transaction>();
private final ArrayList<Transaction> mPending = new ArrayList<Transaction>();
private ConnectivityManager mConnMgr;
private ConnectivityBroadcastReceiver mReceiver;
private boolean mobileDataEnabled;
private boolean lollipopReceiving = false;
private PowerManager.WakeLock mWakeLock;
public Handler mToastHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
String str = null;
if (msg.what == TOAST_MSG_QUEUED) {
str = getString(R.string.message_queued);
} else if (msg.what == TOAST_DOWNLOAD_LATER) {
str = getString(R.string.download_later);
} else if (msg.what == TOAST_NO_APN) {
str = getString(R.string.no_apn);
}
if (str != null) {
Toast.makeText(TransactionService.this, str,
Toast.LENGTH_LONG).show();
}
}
};
@Override
public void onCreate() {
Timber.v("Creating TransactionService");
if (!Utils.isDefaultSmsApp(this)) {
Timber.v("not default app, so exiting");
stopSelf();
return;
}
initServiceHandler();
mReceiver = new ConnectivityBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, intentFilter);
}
private void initServiceHandler() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
HandlerThread thread = new HandlerThread("TransactionService");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
if (intent != null) {
// if (intent.getBooleanExtra(TransactionBundle.LOLLIPOP_RECEIVING, false)) {
// lollipopReceiving = true;
// new Thread(new Runnable() {
// @Override
// public void run() {
// Timber.v("starting receiving with new lollipop method");
// try { Thread.sleep(60000); } catch (Exception e) { }
// Timber.v("done sleeping, lets try and grab the message");
// Uri contentUri = Uri.parse(intent.getStringExtra(TransactionBundle.URI));
// String downloadLocation = null;
// Cursor locationQuery = getContentResolver().query(contentUri, new String[]{Telephony.Mms.CONTENT_LOCATION, Telephony.Mms._ID}, null, null, "date desc");
//
// if (locationQuery != null && locationQuery.moveToFirst()) {
// Timber.v("grabbing content location url");
// downloadLocation = locationQuery.getString(locationQuery.getColumnIndex(Telephony.Mms.CONTENT_LOCATION));
// }
//
// Timber.v("creating request with url: " + downloadLocation);
// DownloadRequest request = new DownloadRequest(downloadLocation, contentUri, null, null, null);
// MmsNetworkManager manager = new MmsNetworkManager(TransactionService.this);
// request.execute(TransactionService.this, manager);
// stopSelf();
// }
// }).start();
// return START_NOT_STICKY;
// }
if (mServiceHandler == null) {
initServiceHandler();
}
Message msg = mServiceHandler.obtainMessage(EVENT_NEW_INTENT);
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
return Service.START_NOT_STICKY;
}
private boolean isNetworkAvailable() {
if (mConnMgr == null) {
return false;
} else if (Utils.isMmsOverWifiEnabled(this)) {
NetworkInfo niWF = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return (niWF == null ? false : niWF.isConnected());
} else {
NetworkInfo ni = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
return (ni == null ? false : ni.isAvailable());
}
}
public void onNewIntent(Intent intent, int serviceId) {
try {
mobileDataEnabled = Utils.isMobileDataEnabled(this);
} catch (Exception e) {
mobileDataEnabled = true;
}
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (!mobileDataEnabled) {
Utils.setMobileDataEnabled(this, true);
}
if (mConnMgr == null) {
endMmsConnectivity();
stopSelf(serviceId);
return;
}
boolean noNetwork = !isNetworkAvailable();
Timber.v("onNewIntent: serviceId: " + serviceId + ": " + intent.getExtras() + " intent=" + intent);
Timber.v(" networkAvailable=" + !noNetwork);
String action = intent.getAction();
if (ACTION_ONALARM.equals(action) || ACTION_ENABLE_AUTO_RETRIEVE.equals(action) ||
(intent.getExtras() == null)) {
// Scan database to find all pending operations.
Cursor cursor = PduPersister.getPduPersister(this).getPendingMessages(
System.currentTimeMillis());
if (cursor != null) {
try {
int count = cursor.getCount();
Timber.v("onNewIntent: cursor.count=" + count + " action=" + action);
if (count == 0) {
Timber.v("onNewIntent: no pending messages. Stopping service.");
RetryScheduler.setRetryAlarm(this);
stopSelfIfIdle(serviceId);
return;
}
int columnIndexOfMsgId = cursor.getColumnIndexOrThrow(PendingMessages.MSG_ID);
int columnIndexOfMsgType = cursor.getColumnIndexOrThrow(
PendingMessages.MSG_TYPE);
while (cursor.moveToNext()) {
int msgType = cursor.getInt(columnIndexOfMsgType);
int transactionType = getTransactionType(msgType);
try {
Uri uri = ContentUris.withAppendedId(Mms.CONTENT_URI,
cursor.getLong(columnIndexOfMsgId));
com.android.mms.transaction.DownloadManager.getInstance().
downloadMultimediaMessage(this, PushReceiver.getContentLocation(this, uri), uri, false, Utils.getDefaultSubscriptionId());
// can't handle many messages at once.
break;
} catch (MmsException e) {
e.printStackTrace();
}
}
} finally {
cursor.close();
}
} else {
Timber.v("onNewIntent: no pending messages. Stopping service.");
RetryScheduler.setRetryAlarm(this);
stopSelfIfIdle(serviceId);
}
} else {
Timber.v("onNewIntent: launch transaction...");
// For launching NotificationTransaction and test purpose.
TransactionBundle args = new TransactionBundle(intent.getExtras());
launchTransaction(serviceId, args, noNetwork);
}
}
private void stopSelfIfIdle(int startId) {
synchronized (mProcessing) {
if (mProcessing.isEmpty() && mPending.isEmpty()) {
Timber.v("stopSelfIfIdle: STOP!");
stopSelf(startId);
}
}
}
private static boolean isTransientFailure(int type) {
return type > MmsSms.NO_ERROR && type < MmsSms.ERR_TYPE_GENERIC_PERMANENT;
}
private int getTransactionType(int msgType) {
switch (msgType) {
case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
return Transaction.RETRIEVE_TRANSACTION;
case PduHeaders.MESSAGE_TYPE_READ_REC_IND:
return Transaction.READREC_TRANSACTION;
case PduHeaders.MESSAGE_TYPE_SEND_REQ:
return Transaction.SEND_TRANSACTION;
default:
Timber.w("Unrecognized MESSAGE_TYPE: " + msgType);
return -1;
}
}
private void launchTransaction(int serviceId, TransactionBundle txnBundle, boolean noNetwork) {
if (noNetwork) {
Timber.w("launchTransaction: no network error!");
onNetworkUnavailable(serviceId, txnBundle.getTransactionType());
return;
}
Message msg = mServiceHandler.obtainMessage(EVENT_TRANSACTION_REQUEST);
msg.arg1 = serviceId;
msg.obj = txnBundle;
Timber.v("launchTransaction: sending message " + msg);
mServiceHandler.sendMessage(msg);
}
private void onNetworkUnavailable(int serviceId, int transactionType) {
Timber.v("onNetworkUnavailable: sid=" + serviceId + ", type=" + transactionType);
int toastType = TOAST_NONE;
if (transactionType == Transaction.RETRIEVE_TRANSACTION) {
toastType = TOAST_DOWNLOAD_LATER;
} else if (transactionType == Transaction.SEND_TRANSACTION) {
toastType = TOAST_MSG_QUEUED;
}
if (toastType != TOAST_NONE) {
mToastHandler.sendEmptyMessage(toastType);
}
stopSelf(serviceId);
}
@Override
public void onDestroy() {
Timber.v("Destroying TransactionService");
if (!mPending.isEmpty()) {
Timber.w("TransactionService exiting with transaction still pending");
}
releaseWakeLock();
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
}
mServiceHandler.sendEmptyMessage(EVENT_QUIT);
if (!mobileDataEnabled && !lollipopReceiving) {
Timber.v("disabling mobile data");
Utils.setMobileDataEnabled(TransactionService.this, false);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* Handle status change of Transaction (The Observable).
*/
public void update(Observable observable) {
Transaction transaction = (Transaction) observable;
int serviceId = transaction.getServiceId();
Timber.v("update transaction " + serviceId);
try {
synchronized (mProcessing) {
mProcessing.remove(transaction);
if (mPending.size() > 0) {
Timber.v("update: handle next pending transaction...");
Message msg = mServiceHandler.obtainMessage(
EVENT_HANDLE_NEXT_PENDING_TRANSACTION,
transaction.getConnectionSettings());
mServiceHandler.sendMessage(msg);
}
else if (mProcessing.isEmpty()) {
Timber.v("update: endMmsConnectivity");
endMmsConnectivity();
} else {
Timber.v("update: mProcessing is not empty");
}
}
Intent intent = new Intent(TRANSACTION_COMPLETED_ACTION);
TransactionState state = transaction.getState();
int result = state.getState();
intent.putExtra(STATE, result);
switch (result) {
case TransactionState.SUCCESS:
Timber.v("Transaction complete: " + serviceId);
intent.putExtra(STATE_URI, state.getContentUri());
// Notify user in the system-wide notification area.
switch (transaction.getType()) {
case Transaction.NOTIFICATION_TRANSACTION:
case Transaction.RETRIEVE_TRANSACTION:
// We're already in a non-UI thread called from
// NotificationTransacation.run(), so ok to block here.
// long threadId = MessagingNotification.getThreadId(
// this, state.getContentUri());
// MessagingNotification.blockingUpdateNewMessageIndicator(this,
// threadId,
// false);
// MessagingNotification.updateDownloadFailedNotification(this);
break;
case Transaction.SEND_TRANSACTION:
RateController.init(getApplicationContext());
RateController.getInstance().update();
break;
}
break;
case TransactionState.FAILED:
Timber.v("Transaction failed: " + serviceId);
break;
default:
Timber.v("Transaction state unknown: " + serviceId + " " + result);
break;
}
Timber.v("update: broadcast transaction result " + result);
// Broadcast the result of the transaction.
BroadcastUtils.sendExplicitBroadcast(this, intent, TRANSACTION_COMPLETED_ACTION);
} finally {
transaction.detach(this);
stopSelfIfIdle(serviceId);
}
}
private synchronized void createWakeLock() {
// Create a new wake lock if we haven't made one yet.
if (mWakeLock == null) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MMS Connectivity");
mWakeLock.setReferenceCounted(false);
}
}
private void acquireWakeLock() {
// It's okay to double-acquire this because we are not using it
// in reference-counted mode.
Timber.v("mms acquireWakeLock");
mWakeLock.acquire();
}
private void releaseWakeLock() {
// Don't release the wake lock if it hasn't been created and acquired.
if (mWakeLock != null && mWakeLock.isHeld()) {
Timber.v("mms releaseWakeLock");
mWakeLock.release();
}
}
protected int beginMmsConnectivity() throws IOException {
Timber.v("beginMmsConnectivity");
// Take a wake lock so we don't fall asleep before the message is downloaded.
createWakeLock();
if (Utils.isMmsOverWifiEnabled(this)) {
NetworkInfo niWF = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if ((niWF != null) && (niWF.isConnected())) {
Timber.v("beginMmsConnectivity: Wifi active");
return 0;
}
}
int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");
Timber.v("beginMmsConnectivity: result=" + result);
switch (result) {
case 0:
case 1:
acquireWakeLock();
return result;
}
throw new IOException("Cannot establish MMS connectivity");
}
protected void endMmsConnectivity() {
try {
Timber.v("endMmsConnectivity");
// cancel timer for renewal of lease
mServiceHandler.removeMessages(EVENT_CONTINUE_MMS_CONNECTIVITY);
if (mConnMgr != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mConnMgr.stopUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE,
"enableMMS");
}
} finally {
releaseWakeLock();
}
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
private String decodeMessage(Message msg) {
if (msg.what == EVENT_QUIT) {
return "EVENT_QUIT";
} else if (msg.what == EVENT_CONTINUE_MMS_CONNECTIVITY) {
return "EVENT_CONTINUE_MMS_CONNECTIVITY";
} else if (msg.what == EVENT_TRANSACTION_REQUEST) {
return "EVENT_TRANSACTION_REQUEST";
} else if (msg.what == EVENT_HANDLE_NEXT_PENDING_TRANSACTION) {
return "EVENT_HANDLE_NEXT_PENDING_TRANSACTION";
} else if (msg.what == EVENT_NEW_INTENT) {
return "EVENT_NEW_INTENT";
}
return "unknown message.what";
}
private String decodeTransactionType(int transactionType) {
if (transactionType == Transaction.NOTIFICATION_TRANSACTION) {
return "NOTIFICATION_TRANSACTION";
} else if (transactionType == Transaction.RETRIEVE_TRANSACTION) {
return "RETRIEVE_TRANSACTION";
} else if (transactionType == Transaction.SEND_TRANSACTION) {
return "SEND_TRANSACTION";
} else if (transactionType == Transaction.READREC_TRANSACTION) {
return "READREC_TRANSACTION";
}
return "invalid transaction type";
}
/**
* Handle incoming transaction requests.
* The incoming requests are initiated by the MMSC Server or by the
* MMS Client itself.
*/
@Override
public void handleMessage(Message msg) {
Timber.v("Handling incoming message: " + msg + " = " + decodeMessage(msg));
Transaction transaction = null;
switch (msg.what) {
case EVENT_NEW_INTENT:
onNewIntent((Intent)msg.obj, msg.arg1);
break;
case EVENT_QUIT:
getLooper().quit();
return;
case EVENT_CONTINUE_MMS_CONNECTIVITY:
synchronized (mProcessing) {
if (mProcessing.isEmpty()) {
return;
}
}
Timber.v("handle EVENT_CONTINUE_MMS_CONNECTIVITY event...");
try {
int result = beginMmsConnectivity();
if (result != 0) {
Timber.v("Extending MMS connectivity returned " + result +
" instead of APN_ALREADY_ACTIVE");
// Just wait for connectivity startup without
// any new request of APN switch.
return;
}
} catch (IOException e) {
Timber.w("Attempt to extend use of MMS connectivity failed");
return;
}
// Restart timer
renewMmsConnectivity();
return;
case EVENT_TRANSACTION_REQUEST:
int serviceId = msg.arg1;
try {
TransactionBundle args = (TransactionBundle) msg.obj;
TransactionSettings transactionSettings;
Timber.v("EVENT_TRANSACTION_REQUEST MmscUrl=" +
args.getMmscUrl() + " proxy port: " + args.getProxyAddress());
// Set the connection settings for this transaction.
// If these have not been set in args, load the default settings.
String mmsc = args.getMmscUrl();
if (mmsc != null) {
transactionSettings = new TransactionSettings(
mmsc, args.getProxyAddress(), args.getProxyPort());
} else {
transactionSettings = new TransactionSettings(
TransactionService.this, null);
}
int transactionType = args.getTransactionType();
Timber.v("handle EVENT_TRANSACTION_REQUEST: transactionType=" +
transactionType + " " + decodeTransactionType(transactionType));
// Create appropriate transaction
switch (transactionType) {
case Transaction.NOTIFICATION_TRANSACTION:
String uri = args.getUri();
if (uri != null) {
transaction = new NotificationTransaction(
TransactionService.this, serviceId,
transactionSettings, uri);
} else {
// Now it's only used for test purpose.
byte[] pushData = args.getPushData();
PduParser parser = new PduParser(pushData);
GenericPdu ind = parser.parse();
int type = PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND;
if ((ind != null) && (ind.getMessageType() == type)) {
transaction = new NotificationTransaction(
TransactionService.this, serviceId,
transactionSettings, (NotificationInd) ind);
} else {
Timber.e("Invalid PUSH data.");
transaction = null;
return;
}
}
break;
case Transaction.RETRIEVE_TRANSACTION:
transaction = new RetrieveTransaction(
TransactionService.this, serviceId,
transactionSettings, args.getUri());
Uri u = Uri.parse(args.getUri());
com.android.mms.transaction.DownloadManager.getInstance().
downloadMultimediaMessage(TransactionService.this,
((RetrieveTransaction) transaction).getContentLocation(TransactionService.this, u), u, false, Utils.getDefaultSubscriptionId());
return;
}
if (!processTransaction(transaction)) {
transaction = null;
return;
}
Timber.v("Started processing of incoming message: " + msg);
} catch (Exception ex) {
Timber.w(ex, "Exception occurred while handling message: " + msg);
if (transaction != null) {
try {
transaction.detach(TransactionService.this);
if (mProcessing.contains(transaction)) {
synchronized (mProcessing) {
mProcessing.remove(transaction);
}
}
} catch (Throwable t) {
Timber.e(t, "Unexpected Throwable.");
} finally {
// Set transaction to null to allow stopping the
// transaction service.
transaction = null;
}
}
} finally {
if (transaction == null) {
Timber.v("Transaction was null. Stopping self: " + serviceId);
endMmsConnectivity();
stopSelf(serviceId);
}
}
return;
case EVENT_HANDLE_NEXT_PENDING_TRANSACTION:
processPendingTransaction(transaction, (TransactionSettings) msg.obj);
return;
default:
Timber.w("what=" + msg.what);
return;
}
}
public void markAllPendingTransactionsAsFailed() {
synchronized (mProcessing) {
while (mPending.size() != 0) {
Transaction transaction = mPending.remove(0);
transaction.mTransactionState.setState(TransactionState.FAILED);
if (transaction instanceof SendTransaction) {
Uri uri = ((SendTransaction)transaction).mSendReqURI;
transaction.mTransactionState.setContentUri(uri);
int respStatus = PduHeaders.RESPONSE_STATUS_ERROR_NETWORK_PROBLEM;
ContentValues values = new ContentValues(1);
values.put(Mms.RESPONSE_STATUS, respStatus);
SqliteWrapper.update(TransactionService.this,
TransactionService.this.getContentResolver(),
uri, values, null, null);
}
transaction.notifyObservers();
}
}
}
public void processPendingTransaction(Transaction transaction,
TransactionSettings settings) {
Timber.v("processPendingTxn: transaction=" + transaction);
int numProcessTransaction = 0;
synchronized (mProcessing) {
if (mPending.size() != 0) {
transaction = mPending.remove(0);
}
numProcessTransaction = mProcessing.size();
}
if (transaction != null) {
if (settings != null) {
transaction.setConnectionSettings(settings);
}
/*
* Process deferred transaction
*/
try {
int serviceId = transaction.getServiceId();
Timber.v("processPendingTxn: process " + serviceId);
if (processTransaction(transaction)) {
Timber.v("Started deferred processing of transaction " + transaction);
} else {
transaction = null;
stopSelf(serviceId);
}
} catch (IOException e) {
Timber.w(e, e.getMessage());
}
} else {
if (numProcessTransaction == 0) {
Timber.v("processPendingTxn: no more transaction, endMmsConnectivity");
endMmsConnectivity();
}
}
}
/**
* Internal method to begin processing a transaction.
* @param transaction the transaction. Must not be {@code null}.
* @return {@code true} if process has begun or will begin. {@code false}
* if the transaction should be discarded.
* @throws java.io.IOException if connectivity for MMS traffic could not be
* established.
*/
private boolean processTransaction(Transaction transaction) throws IOException {
// Check if transaction already processing
synchronized (mProcessing) {
for (Transaction t : mPending) {
if (t.isEquivalent(transaction)) {
Timber.v("Transaction already pending: " + transaction.getServiceId());
return true;
}
}
for (Transaction t : mProcessing) {
if (t.isEquivalent(transaction)) {
Timber.v("Duplicated transaction: " + transaction.getServiceId());
return true;
}
}
/*
* Make sure that the network connectivity necessary
* for MMS traffic is enabled. If it is not, we need
* to defer processing the transaction until
* connectivity is established.
*/
Timber.v("processTransaction: call beginMmsConnectivity...");
int connectivityResult = beginMmsConnectivity();
if (connectivityResult == 1) {
mPending.add(transaction);
Timber.v("processTransaction: connResult=APN_REQUEST_STARTED, " +
"defer transaction pending MMS connectivity");
return true;
}
// If there is already a transaction in processing list, because of the previous
// beginMmsConnectivity call and there is another transaction just at a time,
// when the pdp is connected, there will be a case of adding the new transaction
// to the Processing list. But Processing list is never traversed to
// resend, resulting in transaction not completed/sent.
if (mProcessing.size() > 0) {
Timber.v("Adding transaction to 'mPending' list: " + transaction);
mPending.add(transaction);
return true;
} else {
Timber.v("Adding transaction to 'mProcessing' list: " + transaction);
mProcessing.add(transaction);
}
}
// Set a timer to keep renewing our "lease" on the MMS connection
sendMessageDelayed(obtainMessage(EVENT_CONTINUE_MMS_CONNECTIVITY), APN_EXTENSION_WAIT);
Timber.v("processTransaction: starting transaction " + transaction);
// Attach to transaction and process it
transaction.attach(TransactionService.this);
transaction.process();
return true;
}
}
private void renewMmsConnectivity() {
// Set a timer to keep renewing our "lease" on the MMS connection
mServiceHandler.sendMessageDelayed(
mServiceHandler.obtainMessage(EVENT_CONTINUE_MMS_CONNECTIVITY),
APN_EXTENSION_WAIT);
}
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Timber.w("ConnectivityBroadcastReceiver.onReceive() action: " + action);
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
return;
}
NetworkInfo mmsNetworkInfo = null;
if (mConnMgr != null && Utils.isMobileDataEnabled(context)) {
mmsNetworkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
} else {
Timber.v("mConnMgr is null, bail");
}
/*
* If we are being informed that connectivity has been established
* to allow MMS traffic, then proceed with processing the pending
* transaction, if any.
*/
Timber.v("Handle ConnectivityBroadcastReceiver.onReceive(): " + mmsNetworkInfo);
// Check availability of the mobile network.
if (mmsNetworkInfo == null) {
Timber.v("mms type is null or mobile data is turned off, bail");
} else {
// This is a very specific fix to handle the case where the phone receives an
// incoming call during the time we're trying to setup the mms connection.
// When the call ends, restart the process of mms connectivity.
if ("2GVoiceCallEnded".equals(mmsNetworkInfo.getReason())) {
Timber.v(" reason is " + "2GVoiceCallEnded" + ", retrying mms connectivity");
renewMmsConnectivity();
return;
}
if (mmsNetworkInfo.isConnected()) {
TransactionSettings settings = new TransactionSettings(
TransactionService.this, mmsNetworkInfo.getExtraInfo());
// If this APN doesn't have an MMSC, mark everything as failed and bail.
if (TextUtils.isEmpty(settings.getMmscUrl())) {
Timber.v(" empty MMSC url, bail");
BroadcastUtils.sendExplicitBroadcast(
TransactionService.this,
new Intent(),
com.klinker.android.send_message.Transaction.MMS_ERROR);
mServiceHandler.markAllPendingTransactionsAsFailed();
endMmsConnectivity();
stopSelf();
return;
}
mServiceHandler.processPendingTransaction(null, settings);
} else {
Timber.v(" TYPE_MOBILE_MMS not connected, bail");
// Retry mms connectivity once it's possible to connect
if (mmsNetworkInfo.isAvailable()) {
Timber.v(" retrying mms connectivity for it's available");
renewMmsConnectivity();
}
}
}
}
}
}
| 40,268 | 41.703075 | 178 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/DefaultRetryScheme.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.Context;
import android.util.Config;
import timber.log.Timber;
/**
* Default retry scheme, based on specs.
*/
public class DefaultRetryScheme extends AbstractRetryScheme {
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
private static final int[] sDefaultRetryScheme = {
0, 1 * 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000};
public DefaultRetryScheme(Context context, int retriedTimes) {
super(retriedTimes);
mRetriedTimes = mRetriedTimes < 0 ? 0 : mRetriedTimes;
mRetriedTimes = mRetriedTimes >= sDefaultRetryScheme.length
? sDefaultRetryScheme.length - 1 : mRetriedTimes;
// TODO Get retry scheme from preference.
}
@Override
public int getRetryLimit() {
return sDefaultRetryScheme.length;
}
@Override
public long getWaitingInterval() {
if (LOCAL_LOGV) {
Timber.v("Next int: " + sDefaultRetryScheme[mRetriedTimes]);
}
return sDefaultRetryScheme[mRetriedTimes];
}
}
| 1,764 | 30.517857 | 80 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/MessageStatusService.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.app.IntentService;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.provider.Telephony.Sms;
import android.provider.Telephony.Sms.Inbox;
import android.telephony.SmsMessage;
import timber.log.Timber;
/**
* Service that gets started by the MessageStatusReceiver when a message status report is
* received.
*/
public class MessageStatusService extends IntentService {
private static final String[] ID_PROJECTION = new String[] { Sms._ID };
private static final Uri STATUS_URI = Uri.parse("content://sms/status");
public MessageStatusService() {
// Class name will be the thread name.
super(MessageStatusService.class.getName());
// Intent should be redelivered if the process gets killed before completing the job.
setIntentRedelivery(true);
}
@Override
protected void onHandleIntent(Intent intent) {
// This method is called on a worker thread.
String messageUri = intent.getDataString();
if (messageUri == null) {
messageUri = intent.getStringExtra("message_uri");
if (messageUri == null) {
return;
}
}
byte[] pdu = intent.getByteArrayExtra("pdu");
String format = intent.getStringExtra("format");
SmsMessage message = updateMessageStatus(this, Uri.parse(messageUri), pdu, format);
}
private SmsMessage updateMessageStatus(Context context, Uri messageUri, byte[] pdu,
String format) {
SmsMessage message = SmsMessage.createFromPdu(pdu);
if (message == null) {
return null;
}
// Create a "status/#" URL and use it to update the
// message's status in the database.
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
messageUri, ID_PROJECTION, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
int messageId = cursor.getInt(0);
Uri updateUri = ContentUris.withAppendedId(STATUS_URI, messageId);
int status = message.getStatus();
boolean isStatusReport = message.isStatusReportMessage();
ContentValues contentValues = new ContentValues(2);
log("updateMessageStatus: msgUrl=" + messageUri + ", status=" + status
+ ", isStatusReport=" + isStatusReport);
contentValues.put(Sms.STATUS, status);
contentValues.put(Inbox.DATE_SENT, System.currentTimeMillis());
SqliteWrapper.update(context, context.getContentResolver(),
updateUri, contentValues, null, null);
} else {
error("Can't find message for status update: " + messageUri);
}
} finally {
cursor.close();
}
return message;
}
private void error(String message) {
Timber.e("[MessageStatusReceiver] " + message);
}
private void log(String message) {
Timber.d("[MessageStatusReceiver] " + message);
}
}
| 4,019 | 34.575221 | 93 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/NotificationTransaction.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Inbox;
import android.provider.Telephony.Threads;
import android.telephony.TelephonyManager;
import com.android.mms.MmsConfig;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.NotifyRespInd;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.klinker.android.send_message.BroadcastUtils;
import java.io.IOException;
import timber.log.Timber;
import static com.android.mms.transaction.TransactionState.FAILED;
import static com.android.mms.transaction.TransactionState.INITIALIZED;
import static com.android.mms.transaction.TransactionState.SUCCESS;
import static com.google.android.mms.pdu_alt.PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_DEFERRED;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_RETRIEVED;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_UNRECOGNIZED;
/**
* The NotificationTransaction is responsible for handling multimedia
* message notifications (M-Notification.ind). It:
*
* <ul>
* <li>Composes the notification response (M-NotifyResp.ind).
* <li>Sends the notification response to the MMSC server.
* <li>Stores the notification indication.
* <li>Notifies the TransactionService about succesful completion.
* </ul>
*
* NOTE: This MMS client handles all notifications with a <b>deferred
* retrieval</b> response. The transaction service, upon succesful
* completion of this transaction, will trigger a retrieve transaction
* in case the client is in immediate retrieve mode.
*/
public class NotificationTransaction extends Transaction implements Runnable {
private static final boolean LOCAL_LOGV = false;
private Uri mUri;
private NotificationInd mNotificationInd;
private String mContentLocation;
public NotificationTransaction(
Context context, int serviceId,
TransactionSettings connectionSettings, String uriString) {
super(context, serviceId, connectionSettings);
mUri = Uri.parse(uriString);
try {
mNotificationInd = (NotificationInd)
PduPersister.getPduPersister(context).load(mUri);
} catch (MmsException e) {
Timber.e(e, "Failed to load NotificationInd from: " + uriString);
throw new IllegalArgumentException();
}
mContentLocation = new String(mNotificationInd.getContentLocation());
mId = mContentLocation;
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
/**
* This constructor is only used for test purposes.
*/
public NotificationTransaction(
Context context, int serviceId,
TransactionSettings connectionSettings, NotificationInd ind) {
super(context, serviceId, connectionSettings);
try {
// Save the pdu. If we can start downloading the real pdu immediately, don't allow
// persist() to create a thread for the notificationInd because it causes UI jank.
mUri = PduPersister.getPduPersister(context).persist(ind, Inbox.CONTENT_URI,
PduPersister.DUMMY_THREAD_ID, !allowAutoDownload(mContext), true, null);
} catch (MmsException e) {
Timber.e(e, "Failed to save NotificationInd in constructor.");
throw new IllegalArgumentException();
}
mNotificationInd = ind;
mId = new String(mNotificationInd.getContentLocation());
}
/*
* (non-Javadoc)
* @see com.google.android.mms.pdu.Transaction#process()
*/
@Override
public void process() {
new Thread(this, "NotificationTransaction").start();
}
public static boolean allowAutoDownload(Context context) {
try { Looper.prepare(); } catch (Exception e) { }
boolean autoDownload = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("auto_download_mms", true);
boolean dataSuspended = (((TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE)).getDataState() ==
TelephonyManager.DATA_SUSPENDED);
return autoDownload && !dataSuspended;
}
public void run() {
try { Looper.prepare(); } catch (Exception e) {}
DownloadManager.init(mContext);
DownloadManager downloadManager = DownloadManager.getInstance();
boolean autoDownload = allowAutoDownload(mContext);
try {
if (LOCAL_LOGV) {
Timber.v("Notification transaction launched: " + this);
}
// By default, we set status to STATUS_DEFERRED because we
// should response MMSC with STATUS_DEFERRED when we cannot
// download a MM immediately.
int status = STATUS_DEFERRED;
// Don't try to download when data is suspended, as it will fail, so defer download
if (!autoDownload) {
downloadManager.markState(mUri, DownloadManager.STATE_UNSTARTED);
sendNotifyRespInd(status);
return;
}
downloadManager.markState(mUri, DownloadManager.STATE_DOWNLOADING);
if (LOCAL_LOGV) {
Timber.v("Content-Location: " + mContentLocation);
}
byte[] retrieveConfData = null;
// We should catch exceptions here to response MMSC
// with STATUS_DEFERRED.
try {
retrieveConfData = getPdu(mContentLocation);
} catch (IOException e) {
mTransactionState.setState(FAILED);
}
if (retrieveConfData != null) {
GenericPdu pdu = new PduParser(retrieveConfData).parse();
if ((pdu == null) || (pdu.getMessageType() != MESSAGE_TYPE_RETRIEVE_CONF)) {
Timber.e("Invalid M-RETRIEVE.CONF PDU. " +
(pdu != null ? "message type: " + pdu.getMessageType() : "null pdu"));
mTransactionState.setState(FAILED);
status = STATUS_UNRECOGNIZED;
} else {
// Save the received PDU (must be a M-RETRIEVE.CONF).
PduPersister p = PduPersister.getPduPersister(mContext);
Uri uri = p.persist(pdu, Inbox.CONTENT_URI, PduPersister.DUMMY_THREAD_ID,
true, true, null);
RetrieveConf retrieveConf = (RetrieveConf) pdu;
// Use local time instead of PDU time
ContentValues values = new ContentValues(2);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
try {
values.put(Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) {
}
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, values, null, null);
// We have successfully downloaded the new MM. Delete the
// M-NotifyResp.ind from Inbox.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
Timber.v("NotificationTransaction received new mms message: " + uri);
// Delete obsolete threads
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
Threads.OBSOLETE_THREADS_URI, null, null);
// Notify observers with newly received MM.
mUri = uri;
status = STATUS_RETRIEVED;
BroadcastUtils.sendExplicitBroadcast(
mContext,
new Intent(),
com.klinker.android.send_message.Transaction.NOTIFY_OF_MMS);
}
}
if (LOCAL_LOGV) {
Timber.v("status=0x" + Integer.toHexString(status));
}
// Check the status and update the result state of this Transaction.
switch (status) {
case STATUS_RETRIEVED:
mTransactionState.setState(SUCCESS);
break;
case STATUS_DEFERRED:
// STATUS_DEFERRED, may be a failed immediate retrieval.
if (mTransactionState.getState() == INITIALIZED) {
mTransactionState.setState(SUCCESS);
}
break;
}
sendNotifyRespInd(status);
} catch (Throwable t) {
Timber.e(t, "error");
} finally {
mTransactionState.setContentUri(mUri);
if (!autoDownload) {
// Always mark the transaction successful for deferred
// download since any error here doesn't make sense.
mTransactionState.setState(SUCCESS);
}
if (mTransactionState.getState() != SUCCESS) {
mTransactionState.setState(FAILED);
Timber.e("NotificationTransaction failed.");
}
notifyObservers();
}
}
private void sendNotifyRespInd(int status) throws MmsException, IOException {
// Create the M-NotifyResp.ind
NotifyRespInd notifyRespInd = new NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
mNotificationInd.getTransactionId(),
status);
// Pack M-NotifyResp.ind and send it
if(MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, notifyRespInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, notifyRespInd).make());
}
}
@Override
public int getType() {
return NOTIFICATION_TRANSACTION;
}
}
| 11,298 | 39.938406 | 124 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/PushReceiver.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Inbox;
import com.android.mms.MmsConfig;
import com.google.android.mms.ContentType;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.DeliveryInd;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.ReadOrigInd;
import com.klinker.android.send_message.Utils;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import timber.log.Timber;
import static android.provider.Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION;
import static android.provider.Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION;
import static com.google.android.mms.pdu_alt.PduHeaders.MESSAGE_TYPE_DELIVERY_IND;
import static com.google.android.mms.pdu_alt.PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND;
import static com.google.android.mms.pdu_alt.PduHeaders.MESSAGE_TYPE_READ_ORIG_IND;
/**
* Receives Intent.WAP_PUSH_RECEIVED_ACTION intents and starts the
* TransactionService by passing the push-data to it.
*/
public class PushReceiver extends BroadcastReceiver {
static final String[] PROJECTION = new String[]{Mms.CONTENT_LOCATION, Mms.LOCKED};
static final int COLUMN_CONTENT_LOCATION = 0;
private static Set<String> downloadedUrls = new HashSet<String>();
private static final ExecutorService PUSH_RECEIVER_EXECUTOR = Executors.newSingleThreadExecutor();
private class ReceivePushTask extends AsyncTask<Intent, Void, Void> {
private Context mContext;
private PendingResult pendingResult;
private ReceivePushTask(Context context, PendingResult pendingResult) {
mContext = context;
this.pendingResult = pendingResult;
}
@Override
protected Void doInBackground(Intent... intents) {
Timber.v("receiving a new mms message");
Intent intent = intents[0];
// Get raw PDU push-data from the message and parse it
byte[] pushData = intent.getByteArrayExtra("data");
PduParser parser = new PduParser(pushData);
GenericPdu pdu = parser.parse();
if (pdu == null) {
Timber.e("Invalid PUSH data");
return null;
}
PduPersister p = PduPersister.getPduPersister(mContext);
ContentResolver cr = mContext.getContentResolver();
int type = pdu.getMessageType();
long threadId;
try {
switch (type) {
case MESSAGE_TYPE_DELIVERY_IND:
case MESSAGE_TYPE_READ_ORIG_IND: {
threadId = findThreadId(mContext, pdu, type);
if (threadId == -1) {
// The associated SendReq isn't found, therefore skip
// processing this PDU.
break;
}
Uri uri = p.persist(pdu, Uri.parse("content://mms/inbox"),
PduPersister.DUMMY_THREAD_ID, true, true, null);
// Update thread ID for ReadOrigInd & DeliveryInd.
ContentValues values = new ContentValues(1);
values.put(Mms.THREAD_ID, threadId);
SqliteWrapper.update(mContext, cr, uri, values, null, null);
break;
}
case MESSAGE_TYPE_NOTIFICATION_IND: {
NotificationInd nInd = (NotificationInd) pdu;
if (MmsConfig.getTransIdEnabled()) {
byte[] contentLocation = nInd.getContentLocation();
if ('=' == contentLocation[contentLocation.length - 1]) {
byte[] transactionId = nInd.getTransactionId();
byte[] contentLocationWithId = new byte[contentLocation.length
+ transactionId.length];
System.arraycopy(contentLocation, 0, contentLocationWithId,
0, contentLocation.length);
System.arraycopy(transactionId, 0, contentLocationWithId,
contentLocation.length, transactionId.length);
nInd.setContentLocation(contentLocationWithId);
}
}
if (!isDuplicateNotification(mContext, nInd)) {
// Save the pdu. If we can start downloading the real pdu immediately,
// don't allow persist() to create a thread for the notificationInd
// because it causes UI jank.
Uri uri = p.persist(pdu, Inbox.CONTENT_URI,
PduPersister.DUMMY_THREAD_ID, true, true, null);
String location = getContentLocation(mContext, uri);
if (downloadedUrls.contains(location)) {
Timber.v("already added this download, don't download again");
return null;
} else {
downloadedUrls.add(location);
}
int subId = intent.getIntExtra("subscription", Utils.getDefaultSubscriptionId());
DownloadManager.getInstance().downloadMultimediaMessage(mContext, location, uri, true, subId);
} else {
Timber.v("Skip downloading duplicate message: " + new String(nInd.getContentLocation()));
}
break;
}
default:
Timber.e("Received unrecognized PDU.");
}
} catch (MmsException e) {
Timber.e(e, "Failed to save the data from PUSH: type=" + type);
} catch (RuntimeException e) {
Timber.e(e, "Unexpected RuntimeException.");
}
Timber.v("PUSH Intent processed.");
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
pendingResult.finish();
}
}
@Override
public void onReceive(Context context, Intent intent) {
Timber.v(intent.getAction() + " " + intent.getType());
if ((intent.getAction().equals(WAP_PUSH_DELIVER_ACTION) || intent.getAction().equals(WAP_PUSH_RECEIVED_ACTION))
&& ContentType.MMS_MESSAGE.equals(intent.getType())) {
Timber.v("Received PUSH Intent: " + intent);
MmsConfig.init(context);
new ReceivePushTask(context, goAsync()).executeOnExecutor(PUSH_RECEIVER_EXECUTOR, intent);
Timber.v(context.getPackageName() + " received and aborted");
}
}
public static String getContentLocation(Context context, Uri uri) throws MmsException {
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
uri, PROJECTION, null, null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
String location = cursor.getString(COLUMN_CONTENT_LOCATION);
cursor.close();
return location;
}
} finally {
cursor.close();
}
}
throw new MmsException("Cannot get X-Mms-Content-Location from: " + uri);
}
private static long findThreadId(Context context, GenericPdu pdu, int type) {
String messageId;
if (type == MESSAGE_TYPE_DELIVERY_IND) {
messageId = new String(((DeliveryInd) pdu).getMessageId());
} else {
messageId = new String(((ReadOrigInd) pdu).getMessageId());
}
StringBuilder sb = new StringBuilder('(');
sb.append(Mms.MESSAGE_ID);
sb.append('=');
sb.append(DatabaseUtils.sqlEscapeString(messageId));
sb.append(" AND ");
sb.append(Mms.MESSAGE_TYPE);
sb.append('=');
sb.append(PduHeaders.MESSAGE_TYPE_SEND_REQ);
// TODO ContentResolver.query() appends closing ')' to the selection argument
// sb.append(')');
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
Mms.CONTENT_URI, new String[]{Mms.THREAD_ID},
sb.toString(), null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
long id = cursor.getLong(0);
cursor.close();
return id;
}
} finally {
cursor.close();
}
}
return -1;
}
private static boolean isDuplicateNotification(Context context, NotificationInd nInd) {
byte[] rawLocation = nInd.getContentLocation();
if (rawLocation != null) {
String location = new String(rawLocation);
String selection = Mms.CONTENT_LOCATION + " = ?";
String[] selectionArgs = new String[]{location};
Cursor cursor = SqliteWrapper.query(
context, context.getContentResolver(),
Mms.CONTENT_URI, new String[]{Mms._ID},
selection, selectionArgs, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
// We already received the same notification before.
cursor.close();
//return true;
}
} finally {
cursor.close();
}
}
}
return false;
}
}
| 11,312 | 40.43956 | 122 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/Observer.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.transaction;
/**
* An interface for observing the state of a Transaction.
*/
public interface Observer {
/**
* Update the state of the observable.
*
* @param observable An observable object.
*/
void update(Observable observable);
}
| 945 | 27.666667 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/MessageStatusReceiver.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* 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.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MessageStatusReceiver extends BroadcastReceiver {
public static final String MESSAGE_STATUS_RECEIVED_ACTION =
"com.android.mms.transaction.MessageStatusReceiver.MESSAGE_STATUS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (MESSAGE_STATUS_RECEIVED_ACTION.equals(intent.getAction())) {
intent.setClass(context, MessageStatusService.class);
context.startService(intent);
}
}
}
| 1,289 | 34.833333 | 88 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/RetryScheduler.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.provider.Telephony.MmsSms;
import android.provider.Telephony.MmsSms.PendingMessages;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduPersister;
import com.klinker.android.send_message.BroadcastUtils;
import com.klinker.android.send_message.R;
import timber.log.Timber;
public class RetryScheduler implements Observer {
private static final boolean LOCAL_LOGV = false;
private final Context mContext;
private final ContentResolver mContentResolver;
private RetryScheduler(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
}
private static RetryScheduler sInstance;
public static RetryScheduler getInstance(Context context) {
if (sInstance == null) {
sInstance = new RetryScheduler(context);
}
return sInstance;
}
private boolean isConnected() {
ConnectivityManager mConnMgr = (ConnectivityManager)
mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
return (ni == null ? false : ni.isConnected());
}
public void update(Observable observable) {
try {
Transaction t = (Transaction) observable;
Timber.v("[RetryScheduler] update " + observable);
// We are only supposed to handle M-Notification.ind, M-Send.req
// and M-ReadRec.ind.
if ((t instanceof NotificationTransaction)
|| (t instanceof RetrieveTransaction)
|| (t instanceof ReadRecTransaction)
|| (t instanceof SendTransaction)) {
try {
TransactionState state = t.getState();
if (state.getState() == TransactionState.FAILED) {
Uri uri = state.getContentUri();
if (uri != null) {
scheduleRetry(uri);
}
}
} finally {
t.detach(this);
}
}
} finally {
if (isConnected()) {
setRetryAlarm(mContext);
}
}
}
private void scheduleRetry(Uri uri) {
long msgId = ContentUris.parseId(uri);
Uri.Builder uriBuilder = PendingMessages.CONTENT_URI.buildUpon();
uriBuilder.appendQueryParameter("protocol", "mms");
uriBuilder.appendQueryParameter("message", String.valueOf(msgId));
Cursor cursor = SqliteWrapper.query(mContext, mContentResolver,
uriBuilder.build(), null, null, null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
int msgType = cursor.getInt(cursor.getColumnIndexOrThrow(
PendingMessages.MSG_TYPE));
int retryIndex = cursor.getInt(cursor.getColumnIndexOrThrow(
PendingMessages.RETRY_INDEX)) + 1; // Count this time.
// TODO Should exactly understand what was happened.
int errorType = MmsSms.ERR_TYPE_GENERIC;
DefaultRetryScheme scheme = new DefaultRetryScheme(mContext, retryIndex);
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
boolean isRetryDownloading =
(msgType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND);
boolean retry = true;
int respStatus = getResponseStatus(msgId);
int errorString = 0;
if (!isRetryDownloading) {
// Send Transaction case
switch (respStatus) {
case PduHeaders.RESPONSE_STATUS_ERROR_SENDING_ADDRESS_UNRESOLVED:
errorString = R.string.invalid_destination;
break;
case PduHeaders.RESPONSE_STATUS_ERROR_SERVICE_DENIED:
case PduHeaders.RESPONSE_STATUS_ERROR_PERMANENT_SERVICE_DENIED:
errorString = R.string.service_not_activated;
break;
case PduHeaders.RESPONSE_STATUS_ERROR_NETWORK_PROBLEM:
errorString = R.string.service_network_problem;
break;
case PduHeaders.RESPONSE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND:
case PduHeaders.RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND:
errorString = R.string.service_message_not_found;
break;
}
if (errorString != 0) {
DownloadManager.init(mContext.getApplicationContext());
DownloadManager.getInstance().showErrorCodeToast(errorString);
retry = false;
}
} else {
// apply R880 IOT issue (Conformance 11.6 Retrieve Invalid Message)
// Notification Transaction case
respStatus = getRetrieveStatus(msgId);
if (respStatus ==
PduHeaders.RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND) {
DownloadManager.init(mContext.getApplicationContext());
DownloadManager.getInstance().showErrorCodeToast(
R.string.service_message_not_found);
SqliteWrapper.delete(mContext, mContext.getContentResolver(), uri,
null, null);
retry = false;
return;
}
}
if ((retryIndex < scheme.getRetryLimit()) && retry) {
long retryAt = current + scheme.getWaitingInterval();
Timber.v("scheduleRetry: retry for " + uri + " is scheduled at "
+ (retryAt - System.currentTimeMillis()) + "ms from now");
values.put(PendingMessages.DUE_TIME, retryAt);
if (isRetryDownloading) {
// Downloading process is transiently failed.
DownloadManager.init(mContext.getApplicationContext());
DownloadManager.getInstance().markState(
uri, DownloadManager.STATE_TRANSIENT_FAILURE);
}
} else {
errorType = MmsSms.ERR_TYPE_GENERIC_PERMANENT;
if (isRetryDownloading) {
Cursor c = SqliteWrapper.query(mContext, mContext.getContentResolver(), uri,
new String[] { Mms.THREAD_ID }, null, null, null);
long threadId = -1;
if (c != null) {
try {
if (c.moveToFirst()) {
threadId = c.getLong(0);
}
} finally {
c.close();
}
}
if (threadId != -1) {
// Downloading process is permanently failed.
markMmsFailed(mContext);
}
DownloadManager.init(mContext.getApplicationContext());
DownloadManager.getInstance().markState(
uri, DownloadManager.STATE_PERMANENT_FAILURE);
} else {
// Mark the failed message as unread.
ContentValues readValues = new ContentValues(1);
readValues.put(Mms.READ, 0);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
uri, readValues, null, null);
markMmsFailed(mContext);
}
}
values.put(PendingMessages.ERROR_TYPE, errorType);
values.put(PendingMessages.RETRY_INDEX, retryIndex);
values.put(PendingMessages.LAST_TRY, current);
int columnIndex = cursor.getColumnIndexOrThrow(
PendingMessages._ID);
long id = cursor.getLong(columnIndex);
SqliteWrapper.update(mContext, mContentResolver,
PendingMessages.CONTENT_URI,
values, PendingMessages._ID + "=" + id, null);
} else if (LOCAL_LOGV) {
Timber.v("Cannot found correct pending status for: " + msgId);
}
} finally {
cursor.close();
}
}
}
private void markMmsFailed(final Context context) {
Cursor query = context.getContentResolver().query(Mms.CONTENT_URI, new String[]{Mms._ID}, null, null, "date desc");
try {
query.moveToFirst();
String id = query.getString(query.getColumnIndex(Mms._ID));
query.close();
// mark message as failed
ContentValues values = new ContentValues();
values.put(Mms.MESSAGE_BOX, Mms.MESSAGE_BOX_FAILED);
String where = Mms._ID + " = '" + id + "'";
context.getContentResolver().update(Mms.CONTENT_URI, values, where, null);
BroadcastUtils.sendExplicitBroadcast(
mContext, new Intent(), com.klinker.android.send_message.Transaction.REFRESH);
BroadcastUtils.sendExplicitBroadcast(
mContext,
new Intent(),
com.klinker.android.send_message.Transaction.NOTIFY_SMS_FAILURE);
// broadcast that mms has failed and you can notify user from there if you would like
BroadcastUtils.sendExplicitBroadcast(
mContext, new Intent(), com.klinker.android.send_message.Transaction.MMS_ERROR);
} catch (Exception e) {
}
}
private int getResponseStatus(long msgID) {
int respStatus = 0;
Cursor cursor = SqliteWrapper.query(mContext, mContentResolver,
Mms.Outbox.CONTENT_URI, null, Mms._ID + "=" + msgID, null, null);
try {
if (cursor.moveToFirst()) {
respStatus = cursor.getInt(cursor.getColumnIndexOrThrow(Mms.RESPONSE_STATUS));
}
} finally {
cursor.close();
}
if (respStatus != 0) {
Timber.e("Response status is: " + respStatus);
}
return respStatus;
}
// apply R880 IOT issue (Conformance 11.6 Retrieve Invalid Message)
private int getRetrieveStatus(long msgID) {
int retrieveStatus = 0;
Cursor cursor = SqliteWrapper.query(mContext, mContentResolver,
Mms.Inbox.CONTENT_URI, null, Mms._ID + "=" + msgID, null, null);
try {
if (cursor.moveToFirst()) {
retrieveStatus = cursor.getInt(cursor.getColumnIndexOrThrow(
Mms.RESPONSE_STATUS));
}
} finally {
cursor.close();
}
if (retrieveStatus != 0) {
Timber.v("Retrieve status is: " + retrieveStatus);
}
return retrieveStatus;
}
public static void setRetryAlarm(Context context) {
Cursor cursor = PduPersister.getPduPersister(context).getPendingMessages(
Long.MAX_VALUE);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
// The result of getPendingMessages() is order by due time.
long retryAt = cursor.getLong(cursor.getColumnIndexOrThrow(
PendingMessages.DUE_TIME));
Intent service = new Intent(TransactionService.ACTION_ONALARM,
null, context, TransactionService.class);
PendingIntent operation = PendingIntent.getService(
context, 0, service, PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
am.set(AlarmManager.RTC, retryAt, operation);
Timber.v("Next retry is scheduled at" + (retryAt - System.currentTimeMillis()) + "ms from now");
}
} finally {
cursor.close();
}
}
}
}
| 14,423 | 43.381538 | 123 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/ReadRecTransaction.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.Context;
import android.net.Uri;
import android.provider.Telephony.Mms.Sent;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.ReadRecInd;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
import java.io.IOException;
/**
* The ReadRecTransaction is responsible for sending read report
* notifications (M-read-rec.ind) to clients that have requested them.
* It:
*
* <ul>
* <li>Loads the read report indication from storage (Outbox).
* <li>Packs M-read-rec.ind and sends it.
* <li>Notifies the TransactionService about succesful completion.
* </ul>
*/
public class ReadRecTransaction extends Transaction implements Runnable{
private static final boolean LOCAL_LOGV = false;
private Thread mThread;
private final Uri mReadReportURI;
public ReadRecTransaction(Context context,
int transId,
TransactionSettings connectionSettings,
String uri) {
super(context, transId, connectionSettings);
mReadReportURI = Uri.parse(uri);
mId = uri;
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
/*
* (non-Javadoc)
* @see com.android.mms.Transaction#process()
*/
@Override
public void process() {
mThread = new Thread(this, "ReadRecTransaction");
mThread.start();
}
public void run() {
PduPersister persister = PduPersister.getPduPersister(mContext);
try {
// Load M-read-rec.ind from outbox
ReadRecInd readRecInd = (ReadRecInd) persister.load(mReadReportURI);
// insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
readRecInd.setFrom(new EncodedStringValue(lineNumber));
// Pack M-read-rec.ind and send it
byte[] postingData = new PduComposer(mContext, readRecInd).make();
sendPdu(postingData);
Uri uri = persister.move(mReadReportURI, Sent.CONTENT_URI);
mTransactionState.setState(TransactionState.SUCCESS);
mTransactionState.setContentUri(uri);
} catch (IOException e) {
if (LOCAL_LOGV) {
Timber.v(e, "Failed to send M-Read-Rec.Ind.");
}
} catch (MmsException e) {
if (LOCAL_LOGV) {
Timber.v(e, "Failed to load message from Outbox.");
}
} catch (RuntimeException e) {
if (LOCAL_LOGV) {
Timber.e(e, "Unexpected RuntimeException.");
}
} finally {
if (mTransactionState.getState() != TransactionState.SUCCESS) {
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mReadReportURI);
}
notifyObservers();
}
}
@Override
public int getType() {
return READREC_TRANSACTION;
}
}
| 3,826 | 32.278261 | 80 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/Transaction.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.MmsException;
import com.klinker.android.send_message.Utils;
import java.io.IOException;
/**
* Transaction is an abstract class for notification transaction, send transaction
* and other transactions described in MMS spec.
* It provides the interfaces of them and some common methods for them.
*/
public abstract class Transaction extends Observable {
private final int mServiceId;
protected Context mContext;
protected String mId;
protected TransactionState mTransactionState;
protected TransactionSettings mTransactionSettings;
/**
* Identifies push requests.
*/
public static final int NOTIFICATION_TRANSACTION = 0;
/**
* Identifies deferred retrieve requests.
*/
public static final int RETRIEVE_TRANSACTION = 1;
/**
* Identifies send multimedia message requests.
*/
public static final int SEND_TRANSACTION = 2;
/**
* Identifies send read report requests.
*/
public static final int READREC_TRANSACTION = 3;
public Transaction(Context context, int serviceId,
TransactionSettings settings) {
mContext = context;
mTransactionState = new TransactionState();
mServiceId = serviceId;
mTransactionSettings = settings;
}
/**
* Returns the transaction state of this transaction.
*
* @return Current state of the Transaction.
*/
@Override
public TransactionState getState() {
return mTransactionState;
}
/**
* An instance of Transaction encapsulates the actions required
* during a MMS Client transaction.
*/
public abstract void process();
/**
* Used to determine whether a transaction is equivalent to this instance.
*
* @param transaction the transaction which is compared to this instance.
* @return true if transaction is equivalent to this instance, false otherwise.
*/
public boolean isEquivalent(Transaction transaction) {
return mId.equals(transaction.mId);
}
/**
* Get the service-id of this transaction which was assigned by the framework.
* @return the service-id of the transaction
*/
public int getServiceId() {
return mServiceId;
}
public TransactionSettings getConnectionSettings() {
return mTransactionSettings;
}
public void setConnectionSettings(TransactionSettings settings) {
mTransactionSettings = settings;
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
protected byte[] sendPdu(byte[] pdu) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu,
mTransactionSettings.getMmscUrl());
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
protected byte[] sendPdu(byte[] pdu, String mmscUrl) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu, mmscUrl);
}
/**
* A common method to send a PDU to MMSC.
*
* @param token The token to identify the sending progress.
* @param pdu A byte array which contains the data of the PDU.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
protected byte[] sendPdu(long token, byte[] pdu) throws IOException, MmsException {
return sendPdu(token, pdu, mTransactionSettings.getMmscUrl());
}
/**
* A common method to send a PDU to MMSC.
*
* @param token The token to identify the sending progress.
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
protected byte[] sendPdu(final long token, final byte[] pdu,
final String mmscUrl) throws IOException, MmsException {
if (pdu == null) {
throw new MmsException();
}
if (mmscUrl == null) {
throw new IOException("Cannot establish route: mmscUrl is null");
}
if (useWifi(mContext)) {
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
false, null, 0);
}
return Utils.ensureRouteToMmsNetwork(mContext, mmscUrl, mTransactionSettings.getProxyAddress(), new Utils.Task<byte[]>() {
@Override
public byte[] run() throws IOException {
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
mTransactionSettings.isProxySet(),
mTransactionSettings.getProxyAddress(),
mTransactionSettings.getProxyPort());
}
});
}
/**
* A common method to retrieve a PDU from MMSC.
*
* @param url The URL of the message which we are going to retrieve.
* @return A byte array which contains the data of the PDU.
* If the status code is not correct, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
*/
protected byte[] getPdu(final String url) throws IOException {
if (url == null) {
throw new IOException("Cannot establish route: url is null");
}
if (useWifi(mContext)) {
return HttpUtils.httpConnection(
mContext,
SendingProgressTokenManager.NO_TOKEN,
url,
null,
HttpUtils.HTTP_GET_METHOD,
false,
null,
0);
}
return Utils.ensureRouteToMmsNetwork(mContext, url, mTransactionSettings.getProxyAddress(), new Utils.Task<byte[]>() {
@Override
public byte[] run() throws IOException {
return HttpUtils.httpConnection(
mContext,
SendingProgressTokenManager.NO_TOKEN,
url,
null,
HttpUtils.HTTP_GET_METHOD,
mTransactionSettings.isProxySet(),
mTransactionSettings.getProxyAddress(),
mTransactionSettings.getProxyPort());
}
});
}
public static boolean useWifi(Context context) {
if (Utils.isMmsOverWifiEnabled(context)) {
ConnectivityManager mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnMgr != null) {
NetworkInfo niWF = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if ((niWF != null) && (niWF.isConnected())) {
return true;
}
}
}
return false;
}
@Override
public String toString() {
return getClass().getName() + ": serviceId=" + mServiceId;
}
/**
* Get the type of the transaction.
*
* @return Transaction type in integer.
*/
abstract public int getType();
}
| 9,678 | 35.802281 | 130 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/RetrieveTransaction.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SqliteWrapper;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Mms.Inbox;
import android.text.TextUtils;
import com.android.mms.MmsConfig;
import com.android.mms.util.DownloadManager;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.AcknowledgeInd;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.klinker.android.send_message.Utils;
import java.io.IOException;
import timber.log.Timber;
/**
* The RetrieveTransaction is responsible for retrieving multimedia
* messages (M-Retrieve.conf) from the MMSC server. It:
*
* <ul>
* <li>Sends a GET request to the MMSC server.
* <li>Retrieves the binary M-Retrieve.conf data and parses it.
* <li>Persists the retrieve multimedia message.
* <li>Determines whether an acknowledgement is required.
* <li>Creates appropriate M-Acknowledge.ind and sends it to MMSC server.
* <li>Notifies the TransactionService about succesful completion.
* </ul>
*/
public class RetrieveTransaction extends Transaction implements Runnable {
private static final boolean LOCAL_LOGV = false;
private final Uri mUri;
private final String mContentLocation;
private boolean mLocked;
static final String[] PROJECTION = new String[] {
Mms.CONTENT_LOCATION,
Mms.LOCKED
};
// The indexes of the columns which must be consistent with above PROJECTION.
static final int COLUMN_CONTENT_LOCATION = 0;
static final int COLUMN_LOCKED = 1;
public RetrieveTransaction(Context context, int serviceId,
TransactionSettings connectionSettings, String uri)
throws MmsException {
super(context, serviceId, connectionSettings);
if (uri.startsWith("content://")) {
mUri = Uri.parse(uri); // The Uri of the M-Notification.ind
mId = mContentLocation = getContentLocation(context, mUri);
if (LOCAL_LOGV) {
Timber.v("X-Mms-Content-Location: " + mContentLocation);
}
} else {
throw new IllegalArgumentException(
"Initializing from X-Mms-Content-Location is abandoned!");
}
// Attach the transaction to the instance of RetryScheduler.
attach(RetryScheduler.getInstance(context));
}
public String getContentLocation(Context context, Uri uri)
throws MmsException {
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
uri, PROJECTION, null, null, null);
mLocked = false;
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
// Get the locked flag from the M-Notification.ind so it can be transferred
// to the real message after the download.
mLocked = cursor.getInt(COLUMN_LOCKED) == 1;
String location = cursor.getString(COLUMN_CONTENT_LOCATION);
cursor.close();
return location;
}
} finally {
cursor.close();
}
}
throw new MmsException("Cannot get X-Mms-Content-Location from: " + uri);
}
/*
* (non-Javadoc)
* @see com.android.mms.transaction.Transaction#process()
*/
@Override
public void process() {
new Thread(this, "RetrieveTransaction").start();
}
public void run() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// DownloadRequest request = new DownloadRequest(mContentLocation, mUri, null, null, null);
// MmsNetworkManager manager = new MmsNetworkManager(mContext);
// request.execute(mContext, manager);
// } else {
try {
// Change the downloading state of the M-Notification.ind.
DownloadManager.init(mContext.getApplicationContext());
DownloadManager.getInstance().markState(
mUri, DownloadManager.STATE_DOWNLOADING);
// Send GET request to MMSC and retrieve the response data.
byte[] resp = getPdu(mContentLocation);
// Parse M-Retrieve.conf
RetrieveConf retrieveConf = (RetrieveConf) new PduParser(resp).parse();
if (null == retrieveConf) {
throw new MmsException("Invalid M-Retrieve.conf PDU.");
}
Uri msgUri = null;
if (isDuplicateMessage(mContext, retrieveConf)) {
// Mark this transaction as failed to prevent duplicate
// notification to user.
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mUri);
} else {
// Store M-Retrieve.conf into Inbox
PduPersister persister = PduPersister.getPduPersister(mContext);
msgUri = persister.persist(retrieveConf, Inbox.CONTENT_URI,
PduPersister.DUMMY_THREAD_ID, true, true, null);
// Use local time instead of PDU time
ContentValues values = new ContentValues(3);
values.put(Mms.DATE, System.currentTimeMillis() / 1000L);
try {
values.put(Mms.DATE_SENT, retrieveConf.getDate());
} catch (Exception ignored) {
}
values.put(Mms.MESSAGE_SIZE, resp.length);
SqliteWrapper.update(mContext, mContext.getContentResolver(),
msgUri, values, null, null);
// The M-Retrieve.conf has been successfully downloaded.
mTransactionState.setState(TransactionState.SUCCESS);
mTransactionState.setContentUri(msgUri);
// Remember the location the message was downloaded from.
// Since it's not critical, it won't fail the transaction.
// Copy over the locked flag from the M-Notification.ind in case
// the user locked the message before activating the download.
updateContentLocation(mContext, msgUri, mContentLocation, mLocked);
}
// Delete the corresponding M-Notification.ind.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
// Send ACK to the Proxy-Relay to indicate we have fetched the
// MM successfully.
// Don't mark the transaction as failed if we failed to send it.
sendAcknowledgeInd(retrieveConf);
} catch (Throwable t) {
Timber.e(t, "error");
if ("HTTP error: Not Found".equals(t.getMessage())) {
// Delete the expired M-Notification.ind.
SqliteWrapper.delete(mContext, mContext.getContentResolver(),
mUri, null, null);
}
} finally {
if (mTransactionState.getState() != TransactionState.SUCCESS) {
mTransactionState.setState(TransactionState.FAILED);
mTransactionState.setContentUri(mUri);
Timber.e("Retrieval failed.");
}
notifyObservers();
}
// }
}
private static boolean isDuplicateMessage(Context context, RetrieveConf rc) {
byte[] rawMessageId = rc.getMessageId();
if (rawMessageId != null) {
String messageId = new String(rawMessageId);
String selection = "(" + Mms.MESSAGE_ID + " = ? AND "
+ Mms.MESSAGE_TYPE + " = ?)";
String[] selectionArgs = new String[] { messageId,
String.valueOf(PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF) };
Cursor cursor = SqliteWrapper.query(
context, context.getContentResolver(),
Mms.CONTENT_URI, new String[] { Mms._ID, Mms.SUBJECT, Mms.SUBJECT_CHARSET },
selection, selectionArgs, null);
if (cursor != null) {
try {
if (cursor.getCount() > 0) {
// A message with identical message ID and type found.
// Do some additional checks to be sure it's a duplicate.
boolean dup = isDuplicateMessageExtra(cursor, rc);
if (!cursor.isClosed()) {
cursor.close();
}
return dup;
}
} finally {
cursor.close();
}
}
}
return false;
}
private static boolean isDuplicateMessageExtra(Cursor cursor, RetrieveConf rc) {
// Compare message subjects, taking encoding into account
EncodedStringValue encodedSubjectReceived = null;
EncodedStringValue encodedSubjectStored = null;
String subjectReceived = null;
String subjectStored = null;
String subject = null;
encodedSubjectReceived = rc.getSubject();
if (encodedSubjectReceived != null) {
subjectReceived = encodedSubjectReceived.getString();
}
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int subjectIdx = cursor.getColumnIndex(Mms.SUBJECT);
int charsetIdx = cursor.getColumnIndex(Mms.SUBJECT_CHARSET);
subject = cursor.getString(subjectIdx);
int charset = cursor.getInt(charsetIdx);
if (subject != null) {
encodedSubjectStored = new EncodedStringValue(charset, PduPersister
.getBytes(subject));
}
if (encodedSubjectStored == null && encodedSubjectReceived == null) {
// Both encoded subjects are null - return true
return true;
} else if (encodedSubjectStored != null && encodedSubjectReceived != null) {
subjectStored = encodedSubjectStored.getString();
if (!TextUtils.isEmpty(subjectStored) && !TextUtils.isEmpty(subjectReceived)) {
// Both decoded subjects are non-empty - compare them
return subjectStored.equals(subjectReceived);
} else if (TextUtils.isEmpty(subjectStored) && TextUtils.isEmpty(subjectReceived)) {
// Both decoded subjects are "" - return true
return true;
}
}
}
return false;
}
private void sendAcknowledgeInd(RetrieveConf rc) throws MmsException, IOException {
// Send M-Acknowledge.ind to MMSC if required.
// If the Transaction-ID isn't set in the M-Retrieve.conf, it means
// the MMS proxy-relay doesn't require an ACK.
byte[] tranId = rc.getTransactionId();
if (tranId != null) {
// Create M-Acknowledge.ind
AcknowledgeInd acknowledgeInd = new AcknowledgeInd(
PduHeaders.CURRENT_MMS_VERSION, tranId);
// insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
acknowledgeInd.setFrom(new EncodedStringValue(lineNumber));
// Pack M-Acknowledge.ind and send it
if(MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, acknowledgeInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, acknowledgeInd).make());
}
}
}
private static void updateContentLocation(Context context, Uri uri,
String contentLocation,
boolean locked) {
ContentValues values = new ContentValues(2);
values.put(Mms.CONTENT_LOCATION, contentLocation);
values.put(Mms.LOCKED, locked); // preserve the state of the M-Notification.ind lock.
SqliteWrapper.update(context, context.getContentResolver(),
uri, values, null, null);
}
@Override
public int getType() {
return RETRIEVE_TRANSACTION;
}
}
| 13,569 | 41.672956 | 102 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/MmsPushOutboxMessages.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import timber.log.Timber;
/**
* MmsPushOutboxMessages listens for MMS_SEND_OUTBOX_MSG intent .
* {@link android.intent.action.MMS_SEND_OUTBOX_MSG},
* and wakes up the mms service when it receives it.
* This will tricker the mms service to send any messages stored
* in the outbox.
*/
public class MmsPushOutboxMessages extends BroadcastReceiver {
private static final String INTENT_MMS_SEND_OUTBOX_MSG = "android.intent.action.MMS_SEND_OUTBOX_MSG";
@Override
public void onReceive(Context context, Intent intent) {
Timber.v("Received the MMS_SEND_OUTBOX_MSG intent: " + intent);
String action = intent.getAction();
if(action.equalsIgnoreCase(INTENT_MMS_SEND_OUTBOX_MSG)){
Timber.d("Now waking up the MMS service");
context.startService(new Intent(context, TransactionService.class));
}
}
}
| 1,611 | 35.636364 | 105 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/mms/transaction/TransactionSettings.java | /*
* Copyright 2014 Jacob Klinker
*
* 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.mms.transaction;
import android.content.Context;
import android.net.NetworkUtilsHelper;
import android.provider.Telephony;
import android.text.TextUtils;
import com.android.mms.MmsConfig;
import com.klinker.android.send_message.Transaction;
import com.klinker.android.send_message.Utils;
import timber.log.Timber;
/**
* Container of transaction settings. Instances of this class are contained
* within Transaction instances to allow overriding of the default APN
* settings or of the MMS Client.
*/
public class TransactionSettings {
private String mServiceCenter;
private String mProxyAddress;
private int mProxyPort = -1;
private static final String[] APN_PROJECTION = {
Telephony.Carriers.TYPE, // 0
Telephony.Carriers.MMSC, // 1
Telephony.Carriers.MMSPROXY, // 2
Telephony.Carriers.MMSPORT // 3
};
private static final int COLUMN_TYPE = 0;
private static final int COLUMN_MMSC = 1;
private static final int COLUMN_MMSPROXY = 2;
private static final int COLUMN_MMSPORT = 3;
/**
* Constructor that uses the default settings of the MMS Client.
*
* @param context The context of the MMS Client
*/
public TransactionSettings(Context context, String apnName) {
Timber.v("TransactionSettings: apnName: " + apnName);
// String selection = "current" + " IS NOT NULL";
// String[] selectionArgs = null;
// if (!TextUtils.isEmpty(apnName)) {
// selection += " AND " + "apn" + "=?";
// selectionArgs = new String[]{ apnName.trim() };
// }
//
// Cursor cursor;
//
// try {
// cursor = SqliteWrapper.query(context, context.getContentResolver(),
// Telephony.Carriers.CONTENT_URI,
// APN_PROJECTION, selection, selectionArgs, null);
//
// Timber.v("TransactionSettings looking for apn: " + selection + " returned: " +
// (cursor == null ? "null cursor" : (cursor.getCount() + " hits")));
// } catch (SecurityException e) {
// Timber.e(e, "exception thrown");
// cursor = null;
// }
//
// if (cursor == null) {
// Timber.e("Apn is not found in Database!");
if (Transaction.Companion.getSettings() == null) {
Transaction.Companion.setSettings(Utils.getDefaultSendSettings(context));
}
mServiceCenter = NetworkUtilsHelper.trimV4AddrZeros(Transaction.Companion.getSettings().getMmsc());
mProxyAddress = NetworkUtilsHelper.trimV4AddrZeros(Transaction.Companion.getSettings().getProxy());
// Set up the agent, profile url and tag name to be used in the mms request if they are attached in settings
String agent = Transaction.Companion.getSettings().getAgent();
if (agent != null && !agent.trim().equals("")) {
MmsConfig.setUserAgent(agent);
Timber.v("set user agent");
}
String uaProfUrl = Transaction.Companion.getSettings().getUserProfileUrl();
if (uaProfUrl != null && !uaProfUrl.trim().equals("")) {
MmsConfig.setUaProfUrl(uaProfUrl);
Timber.v("set user agent profile url");
}
String uaProfTagName = Transaction.Companion.getSettings().getUaProfTagName();
if (uaProfTagName != null && !uaProfTagName.trim().equals("")) {
MmsConfig.setUaProfTagName(uaProfTagName);
Timber.v("set user agent profile tag name");
}
if (isProxySet()) {
try {
mProxyPort = Integer.parseInt(Transaction.Companion.getSettings().getPort());
} catch (NumberFormatException e) {
Timber.e(e, "could not get proxy: " + Transaction.Companion.getSettings().getPort());
}
}
// }
// boolean sawValidApn = false;
// try {
// while (cursor.moveToNext() && TextUtils.isEmpty(mServiceCenter)) {
// // Read values from APN settings
// if (isValidApnType(cursor.getString(COLUMN_TYPE), "mms")) {
// sawValidApn = true;
//
// String mmsc = cursor.getString(COLUMN_MMSC);
// if (mmsc == null) {
// continue;
// }
//
// mServiceCenter = NetworkUtils.trimV4AddrZeros(mmsc.trim());
// mProxyAddress = NetworkUtils.trimV4AddrZeros(
// cursor.getString(COLUMN_MMSPROXY));
// if (isProxySet()) {
// String portString = cursor.getString(COLUMN_MMSPORT);
// try {
// mProxyPort = Integer.parseInt(portString);
// } catch (NumberFormatException e) {
// if (TextUtils.isEmpty(portString)) {
// Timber.w("mms port not set!");
// } else {
// Timber.e(e, "Bad port number format: " + portString);
// }
// }
// }
// }
// }
// } finally {
// cursor.close();
// }
//
// Timber.v("APN setting: MMSC: " + mServiceCenter + " looked for: " + selection);
//
// if (sawValidApn && TextUtils.isEmpty(mServiceCenter)) {
// Timber.e("Invalid APN setting: MMSC is empty");
// }
}
/**
* Constructor that overrides the default settings of the MMS Client.
*
* @param mmscUrl The MMSC URL
* @param proxyAddr The proxy address
* @param proxyPort The port used by the proxy address
* immediately start a SendTransaction upon completion of a NotificationTransaction,
* false otherwise.
*/
public TransactionSettings(String mmscUrl, String proxyAddr, int proxyPort) {
mServiceCenter = mmscUrl != null ? mmscUrl.trim() : null;
mProxyAddress = proxyAddr;
mProxyPort = proxyPort;
Timber.v("TransactionSettings: " + mServiceCenter
+ " proxyAddress: " + mProxyAddress
+ " proxyPort: " + mProxyPort);
}
public String getMmscUrl() {
return mServiceCenter;
}
public String getProxyAddress() {
return mProxyAddress;
}
public int getProxyPort() {
return mProxyPort;
}
public boolean isProxySet() {
return (mProxyAddress != null) && (mProxyAddress.trim().length() != 0);
}
static private boolean isValidApnType(String types, String requestType) {
// If APN type is unspecified, assume APN_TYPE_ALL.
if (TextUtils.isEmpty(types)) {
return true;
}
for (String t : types.split(",")) {
if (t.equals(requestType) || t.equals("*")) {
return true;
}
}
return false;
}
}
| 7,707 | 36.970443 | 116 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/i18n/phonenumbers/Phonenumber.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.i18n.phonenumbers;
public class Phonenumber {
public static class PhoneNumber {
}
}
| 711 | 29.956522 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/i18n/phonenumbers/PhoneNumberUtil.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.i18n.phonenumbers;
public class PhoneNumberUtil {
private static PhoneNumberUtil instance;
public static PhoneNumberUtil getInstance() {
return instance;
}
public String format(Phonenumber.PhoneNumber parsed, PhoneNumberFormat format) {
return null;
}
public Phonenumber.PhoneNumber parse(String s, String s2) throws NumberParseException {
return new Phonenumber.PhoneNumber();
}
public boolean isValidNumber(Phonenumber.PhoneNumber phoneNumber) {
return true;
}
public enum PhoneNumberFormat {
E164,
INTERNATIONAL,
NATIONAL,
RFC3966
}
}
| 1,270 | 27.244444 | 91 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/i18n/phonenumbers/NumberParseException.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.i18n.phonenumbers;
public class NumberParseException extends Exception {
}
| 694 | 32.095238 | 75 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/android/internal/telephony/TelephonyProperties.java | /*
* Copyright (C) 2006 The Android Open Source Project
*
* 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.internal.telephony;
/**
* Contains a list of string constants used to get or set telephone properties
* in the system. You can use {@link android.os.SystemProperties os.SystemProperties}
* to get and set these values.
*
* @hide
*/
public interface TelephonyProperties {
//****** Baseband and Radio Interface version
//TODO T: property strings do not have to be gsm specific
// change gsm.*operator.*" properties to "operator.*" properties
/**
* Baseband version
* Availability: property is available any time radio is on
*/
static final String PROPERTY_BASEBAND_VERSION = "gsm.version.baseband";
/**
* Radio Interface Layer (RIL) library implementation.
*/
static final String PROPERTY_RIL_IMPL = "gsm.version.ril-impl";
//****** Current Network
/**
* Alpha name of current registered operator.<p>
* Availability: when registered to a network. Result may be unreliable on
* CDMA networks.
*/
static final String PROPERTY_OPERATOR_ALPHA = "gsm.operator.alpha";
//TODO: most of these properties are generic, substitute gsm. with phone. bug 1856959
/**
* Numeric name (MCC+MNC) of current registered operator.<p>
* Availability: when registered to a network. Result may be unreliable on
* CDMA networks.
*/
static final String PROPERTY_OPERATOR_NUMERIC = "gsm.operator.numeric";
/**
* 'true' if the device is on a manually selected network
* <p/>
* Availability: when registered to a network
*/
static final String PROPERTY_OPERATOR_ISMANUAL = "operator.ismanual";
/**
* 'true' if the device is considered roaming on this network for GSM
* purposes.
* Availability: when registered to a network
*/
static final String PROPERTY_OPERATOR_ISROAMING = "gsm.operator.isroaming";
/**
* The ISO country code equivalent of the current registered operator's
* MCC (Mobile Country Code)<p>
* Availability: when registered to a network. Result may be unreliable on
* CDMA networks.
*/
static final String PROPERTY_OPERATOR_ISO_COUNTRY = "gsm.operator.iso-country";
/**
* The contents of this property is the value of the kernel command line
* product_type variable that corresponds to a product that supports LTE on CDMA.
* {@see BaseCommands#getLteOnCdmaMode()}
*/
static final String PROPERTY_LTE_ON_CDMA_PRODUCT_TYPE = "telephony.lteOnCdmaProductType";
/**
* The contents of this property is the one of {@link Phone#LTE_ON_CDMA_TRUE} or
* {@link Phone#LTE_ON_CDMA_FALSE}. If absent the value will assumed to be false
* and the {@see #PROPERTY_LTE_ON_CDMA_PRODUCT_TYPE} will be used to determine its
* final value which could also be {@link Phone#LTE_ON_CDMA_FALSE}.
* {@see BaseCommands#getLteOnCdmaMode()}
*/
static final String PROPERTY_LTE_ON_CDMA_DEVICE = "telephony.lteOnCdmaDevice";
static final String CURRENT_ACTIVE_PHONE = "gsm.current.phone-type";
//****** SIM Card
/**
* One of <code>"UNKNOWN"</code> <code>"ABSENT"</code> <code>"PIN_REQUIRED"</code>
* <code>"PUK_REQUIRED"</code> <code>"NETWORK_LOCKED"</code> or <code>"READY"</code>
*/
static String PROPERTY_SIM_STATE = "gsm.sim.state";
/**
* The MCC+MNC (mobile country code+mobile network code) of the
* provider of the SIM. 5 or 6 decimal digits.
* Availability: SIM state must be "READY"
*/
static String PROPERTY_ICC_OPERATOR_NUMERIC = "gsm.sim.operator.numeric";
/**
* PROPERTY_ICC_OPERATOR_ALPHA is also known as the SPN, or Service Provider Name.
* Availability: SIM state must be "READY"
*/
static String PROPERTY_ICC_OPERATOR_ALPHA = "gsm.sim.operator.alpha";
/**
* ISO country code equivalent for the SIM provider's country code
*/
static String PROPERTY_ICC_OPERATOR_ISO_COUNTRY = "gsm.sim.operator.iso-country";
/**
* Indicates the available radio technology. Values include: <code>"unknown"</code>,
* <code>"GPRS"</code>, <code>"EDGE"</code> and <code>"UMTS"</code>.
*/
static String PROPERTY_DATA_NETWORK_TYPE = "gsm.network.type";
/**
* Indicate if phone is in emergency callback mode
*/
static final String PROPERTY_INECM_MODE = "ril.cdma.inecmmode";
/**
* Indicate the timer value for exiting emergency callback mode
*/
static final String PROPERTY_ECM_EXIT_TIMER = "ro.cdma.ecmexittimer";
/**
* The international dialing prefix conversion string
*/
static final String PROPERTY_IDP_STRING = "ro.cdma.idpstring";
/**
* Defines the schema for the carrier specified OTASP number
*/
static final String PROPERTY_OTASP_NUM_SCHEMA = "ro.cdma.otaspnumschema";
/**
* Disable all calls including Emergency call when it set to true.
*/
static final String PROPERTY_DISABLE_CALL = "ro.telephony.disable-call";
/**
* Set to true for vendor RIL's that send multiple UNSOL_CALL_RING notifications.
*/
static final String PROPERTY_RIL_SENDS_MULTIPLE_CALL_RING =
"ro.telephony.call_ring.multiple";
/**
* The number of milliseconds between CALL_RING notifications.
*/
static final String PROPERTY_CALL_RING_DELAY = "ro.telephony.call_ring.delay";
/**
* Track CDMA SMS message id numbers to ensure they increment
* monotonically, regardless of reboots.
*/
static final String PROPERTY_CDMA_MSG_ID = "persist.radio.cdma.msgid";
/**
* Property to override DEFAULT_WAKE_LOCK_TIMEOUT
*/
static final String PROPERTY_WAKE_LOCK_TIMEOUT = "ro.ril.wake_lock_timeout";
/**
* Set to true to indicate that the modem needs to be reset
* when there is a radio technology change.
*/
static final String PROPERTY_RESET_ON_RADIO_TECH_CHANGE = "persist.radio.reset_on_switch";
/**
* Set to false to disable SMS receiving, default is
* the value of config_sms_capable
*/
static final String PROPERTY_SMS_RECEIVE = "telephony.sms.receive";
/**
* Set to false to disable SMS sending, default is
* the value of config_sms_capable
*/
static final String PROPERTY_SMS_SEND = "telephony.sms.send";
/**
* Set to true to indicate a test CSIM card is used in the device.
* This property is for testing purpose only. This should not be defined
* in commercial configuration.
*/
static final String PROPERTY_TEST_CSIM = "persist.radio.test-csim";
/**
* Ignore RIL_UNSOL_NITZ_TIME_RECEIVED completely, used for debugging/testing.
*/
static final String PROPERTY_IGNORE_NITZ = "telephony.test.ignore.nitz";
}
| 7,408 | 34.620192 | 94 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/klinker/android/send_message/MmsFileProvider.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.klinker.android.send_message;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import java.io.File;
import java.io.FileNotFoundException;
public class MmsFileProvider extends ContentProvider {
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// Don't support queries.
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// Don't support inserts.
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Don't support deletes.
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// Don't support updates.
return 0;
}
@Override
public String getType(Uri uri) {
// For this sample, assume all files have no type.
return null;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String fileMode) throws FileNotFoundException {
File file = new File(getContext().getCacheDir(), uri.getPath());
int mode = (TextUtils.equals(fileMode, "r") ? ParcelFileDescriptor.MODE_READ_ONLY :
ParcelFileDescriptor.MODE_WRITE_ONLY
|ParcelFileDescriptor.MODE_TRUNCATE
|ParcelFileDescriptor.MODE_CREATE);
return ParcelFileDescriptor.open(file, mode);
}
} | 2,326 | 30.445946 | 115 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/klinker/android/send_message/MmsReceivedReceiver.java | /*
* Copyright (C) 2015 Jacob Klinker
*
* 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.klinker.android.send_message;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.Telephony;
import android.telephony.SmsManager;
import com.android.mms.service_alt.DownloadRequest;
import com.android.mms.service_alt.MmsConfig;
import com.android.mms.transaction.DownloadManager;
import com.android.mms.transaction.HttpUtils;
import com.android.mms.transaction.TransactionSettings;
import com.android.mms.util.SendingProgressTokenManager;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.android.mms.pdu_alt.GenericPdu;
import com.google.android.mms.pdu_alt.NotificationInd;
import com.google.android.mms.pdu_alt.NotifyRespInd;
import com.google.android.mms.pdu_alt.PduComposer;
import com.google.android.mms.pdu_alt.PduHeaders;
import com.google.android.mms.pdu_alt.PduParser;
import com.google.android.mms.pdu_alt.PduPersister;
import com.google.android.mms.pdu_alt.RetrieveConf;
import com.google.android.mms.util_alt.SqliteWrapper;
import timber.log.Timber;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.google.android.mms.pdu_alt.PduHeaders.STATUS_RETRIEVED;
public class MmsReceivedReceiver extends BroadcastReceiver {
public static final String MMS_RECEIVED = "com.klinker.android.messaging.MMS_RECEIVED";
public static final String EXTRA_FILE_PATH = "file_path";
public static final String EXTRA_LOCATION_URL = "location_url";
public static final String EXTRA_TRIGGER_PUSH = "trigger_push";
public static final String EXTRA_URI = "notification_ind_uri";
private static final String LOCATION_SELECTION =
Telephony.Mms.MESSAGE_TYPE + "=? AND " + Telephony.Mms.CONTENT_LOCATION + " =?";
private static final ExecutorService RECEIVE_NOTIFICATION_EXECUTOR = Executors.newSingleThreadExecutor();
public MmscInformation getMmscInfoForReceptionAck() {
// Override this and provide the MMSC to send the ACK to.
// some carriers will download duplicate MMS messages without this ACK. When using the
// system sending method, apparently Google does not do this for us. Not sure why.
// You might have to have users manually enter their APN settings if you cannot get them
// from the system somehow.
return null;
}
@Override
public void onReceive(Context context, Intent intent) {
Timber.v("MMS has finished downloading, persisting it to the database");
String path = intent.getStringExtra(EXTRA_FILE_PATH);
Timber.v(path);
FileInputStream reader = null;
Uri messageUri = null;
String errorMessage = null;
try {
File mDownloadFile = new File(path);
final int nBytes = (int) mDownloadFile.length();
reader = new FileInputStream(mDownloadFile);
final byte[] response = new byte[nBytes];
reader.read(response, 0, nBytes);
List<CommonAsyncTask> tasks = getNotificationTask(context, intent, response);
messageUri = DownloadRequest.persist(context, response,
new MmsConfig.Overridden(new MmsConfig(context), null),
intent.getStringExtra(EXTRA_LOCATION_URL),
Utils.getDefaultSubscriptionId(), null);
Timber.v("response saved successfully");
Timber.v("response length: " + response.length);
mDownloadFile.delete();
if (tasks != null) {
Timber.v("running the common async notifier for download");
for (CommonAsyncTask task : tasks)
task.executeOnExecutor(RECEIVE_NOTIFICATION_EXECUTOR);
}
} catch (FileNotFoundException e) {
errorMessage = "MMS received, file not found exception";
Timber.e(e, errorMessage);
} catch (IOException e) {
errorMessage = "MMS received, io exception";
Timber.e(e, errorMessage);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
errorMessage = "MMS received, io exception";
Timber.e(e, "MMS received, io exception");
}
}
}
handleHttpError(context, intent);
DownloadManager.finishDownload(intent.getStringExtra(EXTRA_LOCATION_URL));
if (messageUri != null) {
onMessageReceived(messageUri);
}
if (errorMessage != null) {
onError(errorMessage);
}
}
protected void onMessageReceived(Uri messageUri) {
// Override this in a custom receiver, if you want access to the message, outside of the
// internal SMS/MMS database
}
protected void onError(String error) {
}
private void handleHttpError(Context context, Intent intent) {
final int httpError = intent.getIntExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, 0);
if (httpError == 404 ||
httpError == 400) {
// Delete the corresponding NotificationInd
SqliteWrapper.delete(context,
context.getContentResolver(),
Telephony.Mms.CONTENT_URI,
LOCATION_SELECTION,
new String[]{
Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND),
intent.getStringExtra(EXTRA_LOCATION_URL)
});
}
}
private static NotificationInd getNotificationInd(Context context, Intent intent) throws MmsException {
return (NotificationInd) PduPersister.getPduPersister(context).load((Uri) intent.getParcelableExtra(EXTRA_URI));
}
private static abstract class CommonAsyncTask extends AsyncTask<Void, Void, Void> {
protected final Context mContext;
protected final TransactionSettings mTransactionSettings;
final NotificationInd mNotificationInd;
final String mContentLocation;
CommonAsyncTask(Context context, TransactionSettings settings, NotificationInd ind) {
mContext = context;
mTransactionSettings = settings;
mNotificationInd = ind;
mContentLocation = new String(ind.getContentLocation());
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
byte[] sendPdu(byte[] pdu, String mmscUrl) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu, mmscUrl);
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
byte[] sendPdu(byte[] pdu) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu,
mTransactionSettings.getMmscUrl());
}
/**
* A common method to send a PDU to MMSC.
*
* @param token The token to identify the sending progress.
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws java.io.IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws com.google.android.mms.MmsException if pdu is null.
*/
private byte[] sendPdu(long token, byte[] pdu,
String mmscUrl) throws IOException, MmsException {
if (pdu == null) {
throw new MmsException();
}
if (mmscUrl == null) {
throw new IOException("Cannot establish route: mmscUrl is null");
}
if (com.android.mms.transaction.Transaction.useWifi(mContext)) {
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
false, null, 0);
}
Utils.ensureRouteToHost(mContext, mmscUrl, mTransactionSettings.getProxyAddress());
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
mTransactionSettings.isProxySet(),
mTransactionSettings.getProxyAddress(),
mTransactionSettings.getProxyPort());
}
}
private static class NotifyRespTask extends CommonAsyncTask {
NotifyRespTask(Context context, NotificationInd ind, TransactionSettings settings) {
super(context, settings, ind);
}
@Override
protected Void doInBackground(Void... params) {
// Create the M-NotifyResp.ind
NotifyRespInd notifyRespInd;
try {
notifyRespInd = new NotifyRespInd(
PduHeaders.CURRENT_MMS_VERSION,
mNotificationInd.getTransactionId(),
STATUS_RETRIEVED);
// Pack M-NotifyResp.ind and send it
if(com.android.mms.MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, notifyRespInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, notifyRespInd).make());
}
} catch (MmsException | IOException e) {
Timber.e(e, "error");
}
return null;
}
}
private static class AcknowledgeIndTask extends CommonAsyncTask {
private final RetrieveConf mRetrieveConf;
AcknowledgeIndTask(Context context, NotificationInd ind, TransactionSettings settings, RetrieveConf rc) {
super(context, settings, ind);
mRetrieveConf = rc;
}
@Override
protected Void doInBackground(Void... params) {
// Send M-Acknowledge.ind to MMSC if required.
// If the Transaction-ID isn't set in the M-Retrieve.conf, it means
// the MMS proxy-relay doesn't require an ACK.
byte[] tranId = mRetrieveConf.getTransactionId();
if (tranId != null) {
Timber.v("sending ACK to MMSC: " + mTransactionSettings.getMmscUrl());
// Create M-Acknowledge.ind
com.google.android.mms.pdu_alt.AcknowledgeInd acknowledgeInd;
try {
acknowledgeInd = new com.google.android.mms.pdu_alt.AcknowledgeInd(
PduHeaders.CURRENT_MMS_VERSION, tranId);
// insert the 'from' address per spec
String lineNumber = Utils.getMyPhoneNumber(mContext);
acknowledgeInd.setFrom(new EncodedStringValue(lineNumber));
// Pack M-Acknowledge.ind and send it
if(com.android.mms.MmsConfig.getNotifyWapMMSC()) {
sendPdu(new PduComposer(mContext, acknowledgeInd).make(), mContentLocation);
} else {
sendPdu(new PduComposer(mContext, acknowledgeInd).make());
}
} catch (IOException | MmsException e) {
Timber.e(e, "error");
}
}
return null;
}
}
private List<CommonAsyncTask> getNotificationTask(Context context, Intent intent, byte[] response) {
if (response.length == 0) {
Timber.v("MmsReceivedReceiver.sendNotification blank response");
return null;
}
if (getMmscInfoForReceptionAck() == null) {
Timber.v("No MMSC information set, so no notification tasks will be able to complete");
return null;
}
final GenericPdu pdu =
(new PduParser(response, new MmsConfig.Overridden(new MmsConfig(context), null).
getSupportMmsContentDisposition())).parse();
if (pdu == null || !(pdu instanceof RetrieveConf)) {
Timber.e("MmsReceivedReceiver.sendNotification failed to parse pdu");
return null;
}
try {
final NotificationInd ind = getNotificationInd(context, intent);
final MmscInformation mmsc = getMmscInfoForReceptionAck();
final TransactionSettings transactionSettings = new TransactionSettings(mmsc.mmscUrl, mmsc.mmsProxy, mmsc.proxyPort);
final List<CommonAsyncTask> responseTasks = new ArrayList<>();
responseTasks.add(new AcknowledgeIndTask(context, ind, transactionSettings, (RetrieveConf) pdu));
responseTasks.add(new NotifyRespTask(context, ind, transactionSettings));
return responseTasks;
} catch (MmsException e) {
Timber.e(e, "error");
return null;
}
}
public static class MmscInformation {
String mmscUrl;
String mmsProxy;
int proxyPort;
public MmscInformation(String mmscUrl, String mmsProxy, int proxyPort) {
this.mmscUrl = mmscUrl;
this.mmsProxy = mmsProxy;
this.proxyPort = proxyPort;
}
}
}
| 15,341 | 40.464865 | 129 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/klinker/android/send_message/BroadcastUtils.java | package com.klinker.android.send_message;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
/**
* Utility for helping with Android O changes. This means that we need to explicitly send broadcasts
* to the correct receiver instead of implicitly. This is done by attaching the class and package
* name to the intent based on the provided action.
*/
public class BroadcastUtils {
public static void sendExplicitBroadcast(Context context, Intent intent, String action) {
addClassName(context, intent, action);
intent.setAction(action);
context.sendBroadcast(intent);
}
public static void addClassName(Context context, Intent intent, String action) {
PackageManager pm = context.getPackageManager();
try {
PackageInfo packageInfo =
pm.getPackageInfo(context.getPackageName(), PackageManager.GET_RECEIVERS);
ActivityInfo[] receivers = packageInfo.receivers;
for (ActivityInfo receiver : receivers) {
if (receiver.taskAffinity.equals(action)) {
intent.setClassName(receiver.packageName, receiver.name);
}
}
} catch (Exception e) {
e.printStackTrace();
}
intent.setPackage(context.getPackageName());
}
}
| 1,453 | 33.619048 | 100 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/klinker/android/send_message/Utils.java | package com.klinker.android.send_message;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.mms.service_alt.MmsNetworkManager;
import com.android.mms.service_alt.exception.MmsNetworkException;
import com.google.android.mms.util_alt.SqliteWrapper;
import timber.log.Timber;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Common methods to be used for data connectivity/sending messages ect
*
* @author Jake Klinker
*/
public class Utils {
/**
* characters to compare against when checking for 160 character sending compatibility
*/
public static final String GSM_CHARACTERS_REGEX = "^[A-Za-z0-9 \\r\\n@Ł$ĽčéůěňÇŘřĹĺ\u0394_\u03A6\u0393\u039B\u03A9\u03A0\u03A8\u03A3\u0398\u039EĆćßÉ!\"#$%&'()*+,\\-./:;<=>?ĄÄÖŃܧżäöńüŕ^{}\\\\\\[~\\]|\u20AC]*$";
public static final int DEFAULT_SUBSCRIPTION_ID = 1;
/**
* Gets the current users phone number
*
* @param context is the context of the activity or service
* @return a string of the phone number on the device
*/
public static String getMyPhoneNumber(Context context) {
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
public interface Task<T> {
T run() throws IOException;
}
public static <T> T ensureRouteToMmsNetwork(Context context, String url, String proxy, Task<T> task) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return ensureRouteToMmsNetworkMarshmallow(context, task);
} else {
return ensureRouteToMmsNetworkLollipop(context, task);
}
}
@TargetApi(Build.VERSION_CODES.M)
private static <T> T ensureRouteToMmsNetworkMarshmallow(Context context, Task<T> task) throws IOException {
final MmsNetworkManager networkManager = new MmsNetworkManager(context.getApplicationContext(), Utils.getDefaultSubscriptionId());
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = null;
try {
network = networkManager.acquireNetwork();
connectivityManager.bindProcessToNetwork(network);
return task.run();
} catch (MmsNetworkException e) {
throw new IOException(e);
} finally {
if (network != null) {
connectivityManager.bindProcessToNetwork(null);
}
networkManager.releaseNetwork();
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static <T> T ensureRouteToMmsNetworkLollipop(Context context, Task<T> task) throws IOException {
final MmsNetworkManager networkManager = new MmsNetworkManager(context.getApplicationContext(), Utils.getDefaultSubscriptionId());
Network network = null;
try {
network = networkManager.acquireNetwork();
ConnectivityManager.setProcessDefaultNetwork(network);
return task.run();
} catch (MmsNetworkException e) {
throw new IOException(e);
} finally {
if (network != null) {
ConnectivityManager.setProcessDefaultNetwork(null);
}
networkManager.releaseNetwork();
}
}
/**
* Ensures that the host MMSC is reachable
*
* @param context is the context of the activity or service
* @param url is the MMSC to check
* @param proxy is the proxy of the APN to check
* @throws java.io.IOException when route cannot be established
*/
public static void ensureRouteToHost(Context context, String url, String proxy) throws IOException {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
InetAddress inetAddr;
if (proxy != null && proxy.trim().length() != 0) {
try {
inetAddr = InetAddress.getByName(proxy);
} catch (UnknownHostException e) {
throw new IOException("Cannot establish route for " + url +
": Unknown proxy " + proxy);
}
try {
Method requestRoute = ConnectivityManager.class.getMethod("requestRouteToHostAddress", Integer.TYPE, InetAddress.class);
if (!((Boolean) requestRoute.invoke(connMgr, ConnectivityManager.TYPE_MOBILE_MMS, inetAddr))) {
throw new IOException("Cannot establish route to proxy " + inetAddr);
}
} catch (Exception e) {
Timber.e(e, "Cannot establishh route to proxy " + inetAddr);
}
} else {
Uri uri = Uri.parse(url);
try {
inetAddr = InetAddress.getByName(uri.getHost());
} catch (UnknownHostException e) {
throw new IOException("Cannot establish route for " + url + ": Unknown host");
}
try {
Method requestRoute = ConnectivityManager.class.getMethod("requestRouteToHostAddress", Integer.TYPE, InetAddress.class);
if (!((Boolean) requestRoute.invoke(connMgr, ConnectivityManager.TYPE_MOBILE_MMS, inetAddr))) {
throw new IOException("Cannot establish route to proxy " + inetAddr);
}
} catch (Exception e) {
Timber.e(e, "Cannot establishh route to proxy " + inetAddr + " for " + url);
}
}
}
/**
* Checks whether or not mobile data is enabled and returns the result
*
* @param context is the context of the activity or service
* @return true if data is enabled or false if disabled
*/
public static Boolean isMobileDataEnabled(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class<?> c = Class.forName(cm.getClass().getName());
Method m = c.getDeclaredMethod("getMobileDataEnabled");
m.setAccessible(true);
return (Boolean) m.invoke(cm);
} catch (Exception e) {
Timber.e(e, "exception thrown");
return null;
}
}
/**
* Checks mobile data enabled based on telephonymanager
*
* @param telephonyManager the telephony manager
*/
public static boolean isDataEnabled(TelephonyManager telephonyManager) {
try {
Class<?> c = telephonyManager.getClass();
Method m = c.getMethod("getDataEnabled");
return (boolean) m.invoke(telephonyManager);
} catch (Exception e) {
Timber.e(e, "exception thrown");
return true;
}
}
/**
* Checks mobile data enabled based on telephonymanager and sim card
*
* @param telephonyManager the telephony manager
* @param subId the sim card id
*/
public static boolean isDataEnabled(TelephonyManager telephonyManager, int subId) {
try {
Class<?> c = telephonyManager.getClass();
Method m = c.getMethod("getDataEnabled", int.class);
return (boolean) m.invoke(telephonyManager, subId);
} catch (Exception e) {
Timber.e(e, "exception thrown");
return isDataEnabled(telephonyManager);
}
}
/**
* Toggles mobile data
*
* @param context is the context of the activity or service
* @param enabled is whether to enable or disable data
*/
public static void setMobileDataEnabled(Context context, boolean enabled) {
// TODO find a better way to do this on lollipop!
// This will actually not work due to no permission for android.permission.MODIFY_PHONE_STATE, which
// is a system level permission and cannot be accessed for third party apps.
try {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
Object telephonyService = m.invoke(tm);
c = Class.forName(telephonyService.getClass().getName());
m = c.getDeclaredMethod("setDataEnabled", Boolean.TYPE);
m.setAccessible(true);
m.invoke(telephonyService, enabled);
} catch (Exception e) {
Timber.e(e, "error enabling data on lollipop");
}
}
/**
* Gets the number of pages in the SMS based on settings and the length of string
*
* @param settings is the settings object to check against
* @param text is the text from the message object to be sent
* @return the number of pages required to hold message
*/
public static int getNumPages(Settings settings, String text) {
if (settings.getStripUnicode()) {
text = StripAccents.stripAccents(text);
}
int[] data = SmsMessage.calculateLength(text, false);
return data[0];
}
/**
* Gets the current thread_id or creates a new one for the given recipient
* @param context is the context of the activity or service
* @param recipient is the person message is being sent to
* @return the thread_id to use in the database
*/
public static long getOrCreateThreadId(Context context, String recipient) {
Set<String> recipients = new HashSet<String>();
recipients.add(recipient);
return getOrCreateThreadId(context, recipients);
}
/**
* Gets the current thread_id or creates a new one for the given recipient
* @param context is the context of the activity or service
* @param recipients is the set of people message is being sent to
* @return the thread_id to use in the database
*/
public static long getOrCreateThreadId(
Context context, Set<String> recipients) {
Uri.Builder uriBuilder = Uri.parse("content://mms-sms/threadID").buildUpon();
for (String recipient : recipients) {
if (isEmailAddress(recipient)) {
recipient = extractAddrSpec(recipient);
}
uriBuilder.appendQueryParameter("recipient", recipient);
}
Uri uri = uriBuilder.build();
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
uri, new String[]{"_id"}, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
long id = cursor.getLong(0);
cursor.close();
return id;
}
} finally {
cursor.close();
}
}
Random random = new Random();
return random.nextLong();
//throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
}
public static boolean doesThreadIdExist(Context context, long threadId) {
Uri uri = Uri.parse("content://mms-sms/conversations/" + threadId + "/");
Cursor cursor = context.getContentResolver().query(uri, new String[] {"_id"}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
cursor.close();
return true;
} else {
return false;
}
}
private static boolean isEmailAddress(String address) {
if (TextUtils.isEmpty(address)) {
return false;
}
String s = extractAddrSpec(address);
Matcher match = EMAIL_ADDRESS_PATTERN.matcher(s);
return match.matches();
}
private static final Pattern EMAIL_ADDRESS_PATTERN
= Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
);
private static final Pattern NAME_ADDR_EMAIL_PATTERN =
Pattern.compile("\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*");
private static String extractAddrSpec(String address) {
Matcher match = NAME_ADDR_EMAIL_PATTERN.matcher(address);
if (match.matches()) {
return match.group(2);
}
return address;
}
/**
* Gets the default settings from a shared preferences file associated with your app
* @param context is the context of the activity or service
* @return the settings object to send with
*/
public static Settings getDefaultSendSettings(Context context) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Settings sendSettings = new Settings();
sendSettings.setMmsc(sharedPrefs.getString("mmsc_url", ""));
sendSettings.setProxy(sharedPrefs.getString("mms_proxy", ""));
sendSettings.setPort(sharedPrefs.getString("mms_port", ""));
sendSettings.setAgent(sharedPrefs.getString("mms_agent", ""));
sendSettings.setUserProfileUrl(sharedPrefs.getString("mms_user_agent_profile_url", ""));
sendSettings.setUaProfTagName(sharedPrefs.getString("mms_user_agent_tag_name", ""));
sendSettings.setStripUnicode(sharedPrefs.getBoolean("strip_unicode", false));
return sendSettings;
}
/**
* Determines whether or not the app is the default SMS app on a device
* @param context
* @return true if app is default
*/
public static boolean isDefaultSmsApp(Context context) {
return context.getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(context));
}
/**
* Determins whether or not the app has enabled MMS over WiFi
* @param context
* @return true if enabled
*/
public static boolean isMmsOverWifiEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("mms_over_wifi", false);
}
public static int getDefaultSubscriptionId() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
return SmsManager.getDefaultSmsSubscriptionId();
} else {
return DEFAULT_SUBSCRIPTION_ID;
}
}
}
| 15,148 | 37.744246 | 214 | java |
qksms | qksms-master/android-smsmms/src/main/java/com/klinker/android/send_message/StripAccents.java | /*
* Copyright 2013 Jacob Klinker
*
* 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.klinker.android.send_message;
import android.telephony.SmsMessage;
public class StripAccents {
public static String characters = "\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD" +
"\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03AC\u03AD" +
"\u03AE\u03AF\u03CC\u03CD\u03CE\u03CA\u03CB\u0390\u03B0\u0391\u0392\u0395\u0396\u0397\u0399" +
"\u039A\u039C\u039D\u039F\u03A1\u03A4\u03A5\u03A7\u0386\u0388\u0389\u038A\u038C\u038F\u03AA" +
"\u03AB\u0170\u0171\u0150\u0151\u0105\u0107\u0119\u0142\u0144\u015B\u017A\u017C\u0104\u0106" +
"\u0118\u0141\u0143\u015A\u0179\u017B\u00C0\u00C2\u00C3\u00C8\u00CA\u00CC\u00CE\u00D2\u00D5" +
"\u00D9\u00DB\u00E2\u00E3\u00EA\u00EE\u00F5\u00FA\u00FB\u00E7\u011B\u0161\u010D\u0159\u017E\u010F" +
"\u0165\u0148\u00E1\u00ED\u00E9\u00F3\u00FD\u016F\u011A\u0160\u010C\u0158\u017D\u010E\u0164\u0147" +
"\u00C1\u00C9\u00CD\u00D3\u00DD\u00DA\u016E\u0155\u013A\u013E\u00F4\u0154\u0139\u013D\u00D4\u00CF\u00EF\u00EB\u00CB";
public static String gsm = "AB\u0393\u0394EZH\u0398IK\u039BMN\u039EO\u03A0P\u03A3\u03A3TY\u03A6X\u03A8\u03A9AEHIOY" +
"\u03A9IYIYABEZHIKMNOPTYXAEHIO\u03A9IY\u00DC\u00FC\u00D6\u00F6acelnszzACELNSZZAAAEEIIOOUU" +
"aaeiouucescrzdtnaieoyuESCRZDTNAEIOYUUrlloRLLOIIee";
public static String stripAccents(String s) {
int[] messageData = SmsMessage.calculateLength(s, false);
if (messageData[0] != 1) {
for (int i = 0; i < characters.length(); i++) {
s = s.replaceAll(characters.substring(i, i + 1), gsm.substring(i, i + 1));
}
}
return s;
}
}
| 2,363 | 47.244898 | 129 | java |
null | NearPMSW-main/baseline/logging/YCSB/scylla/src/test/java/site/ycsb/db/scylla/ScyllaCQLClientTest.java | /*
* Copyright (c) 2020 YCSB contributors. All rights reserved.
*
* 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. See accompanying LICENSE file.
*/
package site.ycsb.db.scylla;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import com.google.common.collect.Sets;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.Insert;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import site.ycsb.ByteIterator;
import site.ycsb.Status;
import site.ycsb.StringByteIterator;
import site.ycsb.measurements.Measurements;
import site.ycsb.workloads.CoreWorkload;
import org.cassandraunit.CassandraCQLUnit;
import org.cassandraunit.dataset.cql.ClassPathCQLDataSet;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Integration tests for the Scylla client
*/
public class ScyllaCQLClientTest {
// Change the default Scylla timeout from 10s to 120s for slow CI machines
private final static long timeout = 120000L;
private final static String TABLE = "usertable";
private final static String HOST = "localhost";
private final static int PORT = 9142;
private final static String DEFAULT_ROW_KEY = "user1";
private ScyllaCQLClient client;
private Session session;
@ClassRule
public static CassandraCQLUnit unit = new CassandraCQLUnit(
new ClassPathCQLDataSet("ycsb.cql", "ycsb"), null, timeout);
@Before
public void setUp() throws Exception {
session = unit.getSession();
Properties p = new Properties();
p.setProperty("scylla.hosts", HOST);
p.setProperty("scylla.port", Integer.toString(PORT));
p.setProperty("scylla.table", TABLE);
Measurements.setProperties(p);
final CoreWorkload workload = new CoreWorkload();
workload.init(p);
client = new ScyllaCQLClient();
client.setProperties(p);
client.init();
}
@After
public void tearDownClient() throws Exception {
if (client != null) {
client.cleanup();
}
client = null;
}
@After
public void clearTable() {
// Clear the table so that each test starts fresh.
final Statement truncate = QueryBuilder.truncate(TABLE);
if (unit != null) {
unit.getSession().execute(truncate);
}
}
@Test
public void testReadMissingRow() {
final HashMap<String, ByteIterator> result = new HashMap<>();
final Status status = client.read(TABLE, "Missing row", null, result);
assertThat(result.size(), is(0));
assertThat(status, is(Status.NOT_FOUND));
}
private void insertRow() {
Insert insertStmt = QueryBuilder.insertInto(TABLE);
insertStmt.value(ScyllaCQLClient.YCSB_KEY, DEFAULT_ROW_KEY);
insertStmt.value("field0", "value1");
insertStmt.value("field1", "value2");
session.execute(insertStmt);
}
@Test
public void testRead() {
insertRow();
final HashMap<String, ByteIterator> result = new HashMap<>();
final Status status = client.read(TABLE, DEFAULT_ROW_KEY, null, result);
assertThat(status, is(Status.OK));
assertThat(result.entrySet(), hasSize(11));
assertThat(result, hasEntry("field2", null));
final HashMap<String, String> strResult = new HashMap<>();
for (final Map.Entry<String, ByteIterator> e : result.entrySet()) {
if (e.getValue() != null) {
strResult.put(e.getKey(), e.getValue().toString());
}
}
assertThat(strResult, hasEntry(ScyllaCQLClient.YCSB_KEY, DEFAULT_ROW_KEY));
assertThat(strResult, hasEntry("field0", "value1"));
assertThat(strResult, hasEntry("field1", "value2"));
}
@Test
public void testReadSingleColumn() {
insertRow();
final HashMap<String, ByteIterator> result = new HashMap<>();
final Set<String> fields = Sets.newHashSet("field1");
final Status status = client.read(TABLE, DEFAULT_ROW_KEY, fields, result);
assertThat(status, is(Status.OK));
assertThat(result.entrySet(), hasSize(1));
final Map<String, String> strResult = StringByteIterator.getStringMap(result);
assertThat(strResult, hasEntry("field1", "value2"));
}
@Test
public void testInsert() {
final String key = "key";
final Map<String, String> input = new HashMap<>();
input.put("field0", "value1");
input.put("field1", "value2");
final Status status = client.insert(TABLE, key, StringByteIterator.getByteIteratorMap(input));
assertThat(status, is(Status.OK));
// Verify result
final Select selectStmt =
QueryBuilder.select("field0", "field1")
.from(TABLE)
.where(QueryBuilder.eq(ScyllaCQLClient.YCSB_KEY, key))
.limit(1);
final ResultSet rs = session.execute(selectStmt);
final Row row = rs.one();
assertThat(row, notNullValue());
assertThat(rs.isExhausted(), is(true));
assertThat(row.getString("field0"), is("value1"));
assertThat(row.getString("field1"), is("value2"));
}
@Test
public void testUpdate() {
insertRow();
final Map<String, String> input = new HashMap<>();
input.put("field0", "new-value1");
input.put("field1", "new-value2");
final Status status = client.update(TABLE,
DEFAULT_ROW_KEY,
StringByteIterator.getByteIteratorMap(input));
assertThat(status, is(Status.OK));
// Verify result
final Select selectStmt =
QueryBuilder.select("field0", "field1")
.from(TABLE)
.where(QueryBuilder.eq(ScyllaCQLClient.YCSB_KEY, DEFAULT_ROW_KEY))
.limit(1);
final ResultSet rs = session.execute(selectStmt);
final Row row = rs.one();
assertThat(row, notNullValue());
assertThat(rs.isExhausted(), is(true));
assertThat(row.getString("field0"), is("new-value1"));
assertThat(row.getString("field1"), is("new-value2"));
}
@Test
public void testDelete() {
insertRow();
final Status status = client.delete(TABLE, DEFAULT_ROW_KEY);
assertThat(status, is(Status.OK));
// Verify result
final Select selectStmt =
QueryBuilder.select("field0", "field1")
.from(TABLE)
.where(QueryBuilder.eq(ScyllaCQLClient.YCSB_KEY, DEFAULT_ROW_KEY))
.limit(1);
final ResultSet rs = session.execute(selectStmt);
final Row row = rs.one();
assertThat(row, nullValue());
}
@Test
public void testPreparedStatements() {
final int LOOP_COUNT = 3;
for (int i = 0; i < LOOP_COUNT; i++) {
testInsert();
testUpdate();
testRead();
testReadSingleColumn();
testReadMissingRow();
testDelete();
}
}
}
| 7,630 | 30.533058 | 98 | java |
null | NearPMSW-main/baseline/logging/YCSB/scylla/src/main/java/site/ycsb/db/scylla/package-info.java | /*
* Copyright (c) 2020 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
/**
* The YCSB binding for <a href="https://www.scylladb.com/">scylla</a>
* via CQL.
*/
package site.ycsb.db.scylla;
| 779 | 31.5 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/scylla/src/main/java/site/ycsb/db/scylla/ScyllaCQLClient.java | /*
* Copyright (c) 2020 YCSB contributors. All rights reserved.
*
* 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. See accompanying LICENSE file.
*/
package site.ycsb.db.scylla;
import com.datastax.driver.core.*;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.datastax.driver.core.querybuilder.*;
import site.ycsb.ByteArrayByteIterator;
import site.ycsb.ByteIterator;
import site.ycsb.DB;
import site.ycsb.DBException;
import site.ycsb.Status;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.MessageFormatter;
/**
* Scylla DB implementation.
*/
public class ScyllaCQLClient extends DB {
private static final Logger LOGGER = LoggerFactory.getLogger(ScyllaCQLClient.class);
private static Cluster cluster = null;
private static Session session = null;
private static final ConcurrentMap<Set<String>, PreparedStatement> READ_STMTS = new ConcurrentHashMap<>();
private static final ConcurrentMap<Set<String>, PreparedStatement> SCAN_STMTS = new ConcurrentHashMap<>();
private static final ConcurrentMap<Set<String>, PreparedStatement> INSERT_STMTS = new ConcurrentHashMap<>();
private static final ConcurrentMap<Set<String>, PreparedStatement> UPDATE_STMTS = new ConcurrentHashMap<>();
private static final AtomicReference<PreparedStatement> READ_ALL_STMT = new AtomicReference<>();
private static final AtomicReference<PreparedStatement> SCAN_ALL_STMT = new AtomicReference<>();
private static final AtomicReference<PreparedStatement> DELETE_STMT = new AtomicReference<>();
private static ConsistencyLevel readConsistencyLevel = ConsistencyLevel.QUORUM;
private static ConsistencyLevel writeConsistencyLevel = ConsistencyLevel.QUORUM;
private static boolean lwt = false;
public static final String YCSB_KEY = "y_id";
public static final String KEYSPACE_PROPERTY = "scylla.keyspace";
public static final String KEYSPACE_PROPERTY_DEFAULT = "ycsb";
public static final String USERNAME_PROPERTY = "scylla.username";
public static final String PASSWORD_PROPERTY = "scylla.password";
public static final String HOSTS_PROPERTY = "scylla.hosts";
public static final String PORT_PROPERTY = "scylla.port";
public static final String PORT_PROPERTY_DEFAULT = "9042";
public static final String READ_CONSISTENCY_LEVEL_PROPERTY = "scylla.readconsistencylevel";
public static final String READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = readConsistencyLevel.name();
public static final String WRITE_CONSISTENCY_LEVEL_PROPERTY = "scylla.writeconsistencylevel";
public static final String WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = writeConsistencyLevel.name();
public static final String MAX_CONNECTIONS_PROPERTY = "scylla.maxconnections";
public static final String CORE_CONNECTIONS_PROPERTY = "scylla.coreconnections";
public static final String CONNECT_TIMEOUT_MILLIS_PROPERTY = "scylla.connecttimeoutmillis";
public static final String READ_TIMEOUT_MILLIS_PROPERTY = "scylla.readtimeoutmillis";
public static final String SCYLLA_LWT = "scylla.lwt";
public static final String TOKEN_AWARE_LOCAL_DC = "scylla.local_dc";
public static final String TRACING_PROPERTY = "scylla.tracing";
public static final String TRACING_PROPERTY_DEFAULT = "false";
public static final String USE_SSL_CONNECTION = "scylla.useSSL";
private static final String DEFAULT_USE_SSL_CONNECTION = "false";
/**
* Count the number of times initialized to teardown on the last
* {@link #cleanup()}.
*/
private static final AtomicInteger INIT_COUNT = new AtomicInteger(0);
private static boolean debug = false;
private static boolean trace = false;
/**
* Initialize any state for this DB. Called once per DB instance; there is one
* DB instance per client thread.
*/
@Override
public void init() throws DBException {
// Keep track of number of calls to init (for later cleanup)
INIT_COUNT.incrementAndGet();
// Synchronized so that we only have a single
// cluster/session instance for all the threads.
synchronized (INIT_COUNT) {
// Check if the cluster has already been initialized
if (cluster != null) {
return;
}
try {
debug = Boolean.parseBoolean(getProperties().getProperty("debug", "false"));
trace = Boolean.parseBoolean(getProperties().getProperty(TRACING_PROPERTY, TRACING_PROPERTY_DEFAULT));
String host = getProperties().getProperty(HOSTS_PROPERTY);
if (host == null) {
throw new DBException(String.format("Required property \"%s\" missing for scyllaCQLClient", HOSTS_PROPERTY));
}
String[] hosts = host.split(",");
String port = getProperties().getProperty(PORT_PROPERTY, PORT_PROPERTY_DEFAULT);
String username = getProperties().getProperty(USERNAME_PROPERTY);
String password = getProperties().getProperty(PASSWORD_PROPERTY);
String keyspace = getProperties().getProperty(KEYSPACE_PROPERTY, KEYSPACE_PROPERTY_DEFAULT);
readConsistencyLevel = ConsistencyLevel.valueOf(
getProperties().getProperty(READ_CONSISTENCY_LEVEL_PROPERTY, READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));
writeConsistencyLevel = ConsistencyLevel.valueOf(
getProperties().getProperty(WRITE_CONSISTENCY_LEVEL_PROPERTY, WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));
boolean useSSL = Boolean.parseBoolean(
getProperties().getProperty(USE_SSL_CONNECTION, DEFAULT_USE_SSL_CONNECTION));
Cluster.Builder builder;
if ((username != null) && !username.isEmpty()) {
builder = Cluster.builder().withCredentials(username, password)
.addContactPoints(hosts).withPort(Integer.parseInt(port));
if (useSSL) {
builder = builder.withSSL();
}
} else {
builder = Cluster.builder().withPort(Integer.parseInt(port))
.addContactPoints(hosts);
}
final String localDC = getProperties().getProperty(TOKEN_AWARE_LOCAL_DC);
if (localDC != null && !localDC.isEmpty()) {
final LoadBalancingPolicy local = DCAwareRoundRobinPolicy.builder().withLocalDc(localDC).build();
final TokenAwarePolicy tokenAware = new TokenAwarePolicy(local);
builder = builder.withLoadBalancingPolicy(tokenAware);
LOGGER.info("Using local datacenter with token awareness: {}\n", localDC);
// If was not overridden explicitly, set LOCAL_QUORUM
if (getProperties().getProperty(READ_CONSISTENCY_LEVEL_PROPERTY) == null) {
readConsistencyLevel = ConsistencyLevel.LOCAL_QUORUM;
}
if (getProperties().getProperty(WRITE_CONSISTENCY_LEVEL_PROPERTY) == null) {
writeConsistencyLevel = ConsistencyLevel.LOCAL_QUORUM;
}
}
cluster = builder.build();
String maxConnections = getProperties().getProperty(
MAX_CONNECTIONS_PROPERTY);
if (maxConnections != null) {
cluster.getConfiguration().getPoolingOptions()
.setMaxConnectionsPerHost(HostDistance.LOCAL, Integer.parseInt(maxConnections));
}
String coreConnections = getProperties().getProperty(
CORE_CONNECTIONS_PROPERTY);
if (coreConnections != null) {
cluster.getConfiguration().getPoolingOptions()
.setCoreConnectionsPerHost(HostDistance.LOCAL, Integer.parseInt(coreConnections));
}
String connectTimeoutMillis = getProperties().getProperty(
CONNECT_TIMEOUT_MILLIS_PROPERTY);
if (connectTimeoutMillis != null) {
cluster.getConfiguration().getSocketOptions()
.setConnectTimeoutMillis(Integer.parseInt(connectTimeoutMillis));
}
String readTimeoutMillis = getProperties().getProperty(
READ_TIMEOUT_MILLIS_PROPERTY);
if (readTimeoutMillis != null) {
cluster.getConfiguration().getSocketOptions()
.setReadTimeoutMillis(Integer.parseInt(readTimeoutMillis));
}
Metadata metadata = cluster.getMetadata();
LOGGER.info("Connected to cluster: {}\n", metadata.getClusterName());
for (Host discoveredHost : metadata.getAllHosts()) {
LOGGER.info("Datacenter: {}; Host: {}; Rack: {}\n",
discoveredHost.getDatacenter(), discoveredHost.getEndPoint().resolve().getAddress(),
discoveredHost.getRack());
}
session = cluster.connect(keyspace);
if (Boolean.parseBoolean(getProperties().getProperty(SCYLLA_LWT, Boolean.toString(lwt)))) {
LOGGER.info("Using LWT\n");
lwt = true;
readConsistencyLevel = ConsistencyLevel.SERIAL;
writeConsistencyLevel = ConsistencyLevel.ANY;
} else {
LOGGER.info("Not using LWT\n");
}
LOGGER.info("Read consistency: {}, Write consistency: {}\n",
readConsistencyLevel.name(),
writeConsistencyLevel.name());
} catch (Exception e) {
throw new DBException(e);
}
} // synchronized
}
/**
* Cleanup any state for this DB. Called once per DB instance; there is one DB
* instance per client thread.
*/
@Override
public void cleanup() throws DBException {
synchronized (INIT_COUNT) {
final int curInitCount = INIT_COUNT.decrementAndGet();
if (curInitCount <= 0) {
READ_STMTS.clear();
SCAN_STMTS.clear();
INSERT_STMTS.clear();
UPDATE_STMTS.clear();
READ_ALL_STMT.set(null);
SCAN_ALL_STMT.set(null);
DELETE_STMT.set(null);
if (session != null) {
session.close();
session = null;
}
if (cluster != null) {
cluster.close();
cluster = null;
}
}
if (curInitCount < 0) {
// This should never happen.
throw new DBException(String.format("initCount is negative: %d", curInitCount));
}
}
}
/**
* Read a record from the database. Each field/value pair from the result will
* be stored in a HashMap.
*
* @param table
* The name of the table
* @param key
* The record key of the record to read.
* @param fields
* The list of fields to read, or null for all of them
* @param result
* A HashMap of field/value pairs for the result
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
PreparedStatement stmt = (fields == null) ? READ_ALL_STMT.get() : READ_STMTS.get(fields);
// Prepare statement on demand
if (stmt == null) {
Select.Builder selectBuilder;
if (fields == null) {
selectBuilder = QueryBuilder.select().all();
} else {
selectBuilder = QueryBuilder.select();
for (String col : fields) {
((Select.Selection) selectBuilder).column(col);
}
}
stmt = session.prepare(selectBuilder.from(table)
.where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker()))
.limit(1));
stmt.setConsistencyLevel(readConsistencyLevel);
if (trace) {
stmt.enableTracing();
}
PreparedStatement prevStmt = (fields == null) ?
READ_ALL_STMT.getAndSet(stmt) :
READ_STMTS.putIfAbsent(new HashSet<>(fields), stmt);
if (prevStmt != null) {
stmt = prevStmt;
}
}
LOGGER.debug(stmt.getQueryString());
LOGGER.debug("key = {}", key);
ResultSet rs = session.execute(stmt.bind(key));
if (rs.isExhausted()) {
return Status.NOT_FOUND;
}
// Should be only 1 row
Row row = rs.one();
ColumnDefinitions cd = row.getColumnDefinitions();
for (ColumnDefinitions.Definition def : cd) {
ByteBuffer val = row.getBytesUnsafe(def.getName());
if (val != null) {
result.put(def.getName(), new ByteArrayByteIterator(val.array()));
} else {
result.put(def.getName(), null);
}
}
return Status.OK;
} catch (Exception e) {
LOGGER.error(MessageFormatter.format("Error reading key: {}", key).getMessage(), e);
return Status.ERROR;
}
}
/**
* Perform a range scan for a set of records in the database. Each field/value
* pair from the result will be stored in a HashMap.
*
* scylla CQL uses "token" method for range scan which doesn't always yield
* intuitive results.
*
* @param table
* The name of the table
* @param startkey
* The record key of the first record to read.
* @param recordcount
* The number of records to read
* @param fields
* The list of fields to read, or null for all of them
* @param result
* A Vector of HashMaps, where each HashMap is a set field/value
* pairs for one record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
try {
PreparedStatement stmt = (fields == null) ? SCAN_ALL_STMT.get() : SCAN_STMTS.get(fields);
// Prepare statement on demand
if (stmt == null) {
Select.Builder selectBuilder;
if (fields == null) {
selectBuilder = QueryBuilder.select().all();
} else {
selectBuilder = QueryBuilder.select();
for (String col : fields) {
((Select.Selection) selectBuilder).column(col);
}
}
Select selectStmt = selectBuilder.from(table);
// The statement builder is not setup right for tokens.
// So, we need to build it manually.
String initialStmt = selectStmt.toString();
String scanStmt = initialStmt.substring(0, initialStmt.length() - 1) +
" WHERE " + QueryBuilder.token(YCSB_KEY) +
" >= token(" + QueryBuilder.bindMarker() + ")" +
" LIMIT " + QueryBuilder.bindMarker();
stmt = session.prepare(scanStmt);
stmt.setConsistencyLevel(readConsistencyLevel);
if (trace) {
stmt.enableTracing();
}
PreparedStatement prevStmt = (fields == null) ?
SCAN_ALL_STMT.getAndSet(stmt) :
SCAN_STMTS.putIfAbsent(new HashSet<>(fields), stmt);
if (prevStmt != null) {
stmt = prevStmt;
}
}
LOGGER.debug(stmt.getQueryString());
LOGGER.debug("startKey = {}, recordcount = {}", startkey, recordcount);
ResultSet rs = session.execute(stmt.bind(startkey, recordcount));
HashMap<String, ByteIterator> tuple;
while (!rs.isExhausted()) {
Row row = rs.one();
tuple = new HashMap<>();
ColumnDefinitions cd = row.getColumnDefinitions();
for (ColumnDefinitions.Definition def : cd) {
ByteBuffer val = row.getBytesUnsafe(def.getName());
if (val != null) {
tuple.put(def.getName(), new ByteArrayByteIterator(val.array()));
} else {
tuple.put(def.getName(), null);
}
}
result.add(tuple);
}
return Status.OK;
} catch (Exception e) {
LOGGER.error(
MessageFormatter.format("Error scanning with startkey: {}", startkey).getMessage(), e);
return Status.ERROR;
}
}
/**
* Update a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key, overwriting any existing values with the same field name.
*
* @param table
* The name of the table
* @param key
* The record key of the record to write.
* @param values
* A HashMap of field/value pairs to update in the record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
try {
Set<String> fields = values.keySet();
PreparedStatement stmt = UPDATE_STMTS.get(fields);
// Prepare statement on demand
if (stmt == null) {
Update updateStmt = QueryBuilder.update(table);
// Add fields
for (String field : fields) {
updateStmt.with(QueryBuilder.set(field, QueryBuilder.bindMarker()));
}
// Add key
updateStmt.where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker()));
if (lwt) {
updateStmt.where().ifExists();
}
stmt = session.prepare(updateStmt);
stmt.setConsistencyLevel(writeConsistencyLevel);
if (trace) {
stmt.enableTracing();
}
PreparedStatement prevStmt = UPDATE_STMTS.putIfAbsent(new HashSet<>(fields), stmt);
if (prevStmt != null) {
stmt = prevStmt;
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(stmt.getQueryString());
LOGGER.debug("key = {}", key);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
LOGGER.debug("{} = {}", entry.getKey(), entry.getValue());
}
}
// Add fields
ColumnDefinitions vars = stmt.getVariables();
BoundStatement boundStmt = stmt.bind();
for (int i = 0; i < vars.size() - 1; i++) {
boundStmt.setString(i, values.get(vars.getName(i)).toString());
}
// Add key
boundStmt.setString(vars.size() - 1, key);
session.execute(boundStmt);
return Status.OK;
} catch (Exception e) {
LOGGER.error(MessageFormatter.format("Error updating key: {}", key).getMessage(), e);
}
return Status.ERROR;
}
/**
* Insert a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key.
*
* @param table
* The name of the table
* @param key
* The record key of the record to insert.
* @param values
* A HashMap of field/value pairs to insert in the record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
try {
Set<String> fields = values.keySet();
PreparedStatement stmt = INSERT_STMTS.get(fields);
// Prepare statement on demand
if (stmt == null) {
Insert insertStmt = QueryBuilder.insertInto(table);
// Add key
insertStmt.value(YCSB_KEY, QueryBuilder.bindMarker());
// Add fields
for (String field : fields) {
insertStmt.value(field, QueryBuilder.bindMarker());
}
if (lwt) {
insertStmt.ifNotExists();
}
stmt = session.prepare(insertStmt);
stmt.setConsistencyLevel(writeConsistencyLevel);
if (trace) {
stmt.enableTracing();
}
PreparedStatement prevStmt = INSERT_STMTS.putIfAbsent(new HashSet<>(fields), stmt);
if (prevStmt != null) {
stmt = prevStmt;
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(stmt.getQueryString());
LOGGER.debug("key = {}", key);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
LOGGER.debug("{} = {}", entry.getKey(), entry.getValue());
}
}
// Add key
BoundStatement boundStmt = stmt.bind().setString(0, key);
// Add fields
ColumnDefinitions vars = stmt.getVariables();
for (int i = 1; i < vars.size(); i++) {
boundStmt.setString(i, values.get(vars.getName(i)).toString());
}
session.execute(boundStmt);
return Status.OK;
} catch (Exception e) {
LOGGER.error(MessageFormatter.format("Error inserting key: {}", key).getMessage(), e);
}
return Status.ERROR;
}
/**
* Delete a record from the database.
*
* @param table
* The name of the table
* @param key
* The record key of the record to delete.
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status delete(String table, String key) {
try {
PreparedStatement stmt = DELETE_STMT.get();
// Prepare statement on demand
if (stmt == null) {
Delete s = QueryBuilder.delete().from(table);
s.where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker()));
if (lwt) {
s.ifExists();
}
stmt = session.prepare(s);
stmt.setConsistencyLevel(writeConsistencyLevel);
if (trace) {
stmt.enableTracing();
}
PreparedStatement prevStmt = DELETE_STMT.getAndSet(stmt);
if (prevStmt != null) {
stmt = prevStmt;
}
}
LOGGER.debug(stmt.getQueryString());
LOGGER.debug("key = {}", key);
session.execute(stmt.bind(key));
return Status.OK;
} catch (Exception e) {
LOGGER.error(MessageFormatter.format("Error deleting key: {}", key).getMessage(), e);
}
return Status.ERROR;
}
}
| 22,304 | 33.315385 | 119 | java |
null | NearPMSW-main/baseline/logging/YCSB/zookeeper/src/test/java/site/ycsb/db/zookeeper/ZKClientTest.java | /**
* Copyright (c) 2020 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.db.zookeeper;
import org.apache.curator.test.TestingServer;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import site.ycsb.ByteIterator;
import site.ycsb.Status;
import site.ycsb.StringByteIterator;
import site.ycsb.measurements.Measurements;
import site.ycsb.workloads.CoreWorkload;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.fail;
import static site.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY;
import static site.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY_DEFAULT;
/**
* Integration tests for the YCSB ZooKeeper client.
*/
public class ZKClientTest {
private static TestingServer zkTestServer;
private ZKClient client;
private String tableName;
private final static String path = "benchmark";
private static final int PORT = 2181;
@BeforeClass
public static void setUpClass() throws Exception {
zkTestServer = new TestingServer(PORT);
zkTestServer.start();
}
@AfterClass
public static void tearDownClass() throws Exception {
zkTestServer.stop();
}
@Before
public void setUp() throws Exception {
client = new ZKClient();
Properties p = new Properties();
p.setProperty("zookeeper.connectString", "127.0.0.1:" + String.valueOf(PORT));
Measurements.setProperties(p);
final CoreWorkload workload = new CoreWorkload();
workload.init(p);
tableName = p.getProperty(TABLENAME_PROPERTY, TABLENAME_PROPERTY_DEFAULT);
client.setProperties(p);
client.init();
}
@After
public void tearDown() throws Exception {
client.cleanup();
}
@Test
public void testZKClient() {
// insert
Map<String, String> m = new HashMap<>();
String field1 = "field_1";
String value1 = "value_1";
m.put(field1, value1);
Map<String, ByteIterator> result = StringByteIterator.getByteIteratorMap(m);
client.insert(tableName, path, result);
// read
result.clear();
Status status = client.read(tableName, path, null, result);
assertEquals(Status.OK, status);
assertEquals(1, result.size());
assertEquals(value1, result.get(field1).toString());
// update(the same field)
m.clear();
result.clear();
String newVal = "value_new";
m.put(field1, newVal);
result = StringByteIterator.getByteIteratorMap(m);
client.update(tableName, path, result);
assertEquals(1, result.size());
// Verify result
result.clear();
status = client.read(tableName, path, null, result);
assertEquals(Status.OK, status);
// here we only have one field: field_1
assertEquals(1, result.size());
assertEquals(newVal, result.get(field1).toString());
// update(two different field)
m.clear();
result.clear();
String field2 = "field_2";
String value2 = "value_2";
m.put(field2, value2);
result = StringByteIterator.getByteIteratorMap(m);
client.update(tableName, path, result);
assertEquals(1, result.size());
// Verify result
result.clear();
status = client.read(tableName, path, null, result);
assertEquals(Status.OK, status);
// here we have two field: field_1 and field_2
assertEquals(2, result.size());
assertEquals(value2, result.get(field2).toString());
assertEquals(newVal, result.get(field1).toString());
// delete
status = client.delete(tableName, path);
assertEquals(Status.OK, status);
// Verify result
result.clear();
status = client.read(tableName, path, null, result);
// NoNode return ERROR
assertEquals(Status.ERROR, status);
assertEquals(0, result.size());
}
@Test
@Ignore("Not yet implemented")
public void testScan() {
fail("Not yet implemented");
}
}
| 4,549 | 27.797468 | 82 | java |
null | NearPMSW-main/baseline/logging/YCSB/zookeeper/src/main/java/site/ycsb/db/zookeeper/package-info.java | /*
* Copyright (c) 2020 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
/**
* The YCSB binding for <a href="https://zookeeper.apache.org/">ZooKeeper</a>.
*/
package site.ycsb.db.zookeeper;
| 778 | 32.869565 | 78 | java |
null | NearPMSW-main/baseline/logging/YCSB/zookeeper/src/main/java/site/ycsb/db/zookeeper/ZKClient.java | /**
* Copyright (c) 2020 YCSB contributors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
* <p>
* ZooKeeper client binding for YCSB.
* <p>
*/
package site.ycsb.db.zookeeper;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import site.ycsb.ByteIterator;
import site.ycsb.DB;
import site.ycsb.DBException;
import site.ycsb.Status;
import site.ycsb.StringByteIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* YCSB binding for <a href="https://zookeeper.apache.org/">ZooKeeper</a>.
*
* See {@code zookeeper/README.md} for details.
*/
public class ZKClient extends DB {
private ZooKeeper zk;
private Watcher watcher;
private static final String CONNECT_STRING = "zookeeper.connectString";
private static final String DEFAULT_CONNECT_STRING = "127.0.0.1:2181";
private static final String SESSION_TIMEOUT_PROPERTY = "zookeeper.sessionTimeout";
private static final long DEFAULT_SESSION_TIMEOUT = TimeUnit.SECONDS.toMillis(30L);
private static final String WATCH_FLAG = "zookeeper.watchFlag";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Logger LOG = LoggerFactory.getLogger(ZKClient.class);
public void init() throws DBException {
Properties props = getProperties();
String connectString = props.getProperty(CONNECT_STRING);
if (connectString == null || connectString.length() == 0) {
connectString = DEFAULT_CONNECT_STRING;
}
if(Boolean.parseBoolean(props.getProperty(WATCH_FLAG))) {
watcher = new SimpleWatcher();
} else {
watcher = null;
}
long sessionTimeout;
String sessionTimeoutString = props.getProperty(SESSION_TIMEOUT_PROPERTY);
if (sessionTimeoutString != null) {
sessionTimeout = Integer.parseInt(sessionTimeoutString);
} else {
sessionTimeout = DEFAULT_SESSION_TIMEOUT;
}
try {
zk = new ZooKeeper(connectString, (int) sessionTimeout, new SimpleWatcher());
} catch (IOException e) {
throw new DBException("Creating connection failed.");
}
}
public void cleanup() throws DBException {
try {
zk.close();
} catch (InterruptedException e) {
throw new DBException("Closing connection failed.");
}
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
String path = getPath(key);
try {
byte[] data = zk.getData(path, watcher, null);
if (data == null || data.length == 0) {
return Status.NOT_FOUND;
}
deserializeValues(data, fields, result);
return Status.OK;
} catch (KeeperException | InterruptedException e) {
LOG.error("Error when reading a path:{},tableName:{}", path, table, e);
return Status.ERROR;
}
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
String path = getPath(key);
String data = getJsonStrFromByteMap(values);
try {
zk.create(path, data.getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
return Status.OK;
} catch (KeeperException.NodeExistsException e1) {
return Status.OK;
} catch (KeeperException | InterruptedException e2) {
LOG.error("Error when inserting a path:{},tableName:{}", path, table, e2);
return Status.ERROR;
}
}
@Override
public Status delete(String table, String key) {
String path = getPath(key);
try {
zk.delete(path, -1);
return Status.OK;
} catch (InterruptedException | KeeperException e) {
LOG.error("Error when deleting a path:{},tableName:{}", path, table, e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
String path = getPath(key);
try {
// we have to do a read operation here before setData to meet the YCSB's update semantics:
// update a single record in the database, adding or replacing the specified fields.
byte[] data = zk.getData(path, watcher, null);
if (data == null || data.length == 0) {
return Status.NOT_FOUND;
}
final Map<String, ByteIterator> result = new HashMap<>();
deserializeValues(data, null, result);
result.putAll(values);
// update
zk.setData(path, getJsonStrFromByteMap(result).getBytes(UTF_8), -1);
return Status.OK;
} catch (KeeperException | InterruptedException e) {
LOG.error("Error when updating a path:{},tableName:{}", path, table, e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
return Status.NOT_IMPLEMENTED;
}
private String getPath(String key) {
return key.startsWith("/") ? key : "/" + key;
}
/**
* converting the key:values map to JSON Strings.
*/
private static String getJsonStrFromByteMap(Map<String, ByteIterator> map) {
Map<String, String> stringMap = StringByteIterator.getStringMap(map);
return JSONValue.toJSONString(stringMap);
}
private Map<String, ByteIterator> deserializeValues(final byte[] data, final Set<String> fields,
final Map<String, ByteIterator> result) {
JSONObject jsonObject = (JSONObject)JSONValue.parse(new String(data, UTF_8));
Iterator<String> iterator = jsonObject.keySet().iterator();
while(iterator.hasNext()) {
String field = iterator.next();
String value = jsonObject.get(field).toString();
if(fields == null || fields.contains(field)) {
result.put(field, new StringByteIterator(value));
}
}
return result;
}
private static class SimpleWatcher implements Watcher {
public void process(WatchedEvent e) {
if (e.getType() == Event.EventType.None) {
return;
}
if (e.getState() == Event.KeeperState.SyncConnected) {
//do nothing
}
}
}
}
| 7,198 | 31.282511 | 98 | java |
null | NearPMSW-main/baseline/logging/YCSB/couchbase/src/main/java/site/ycsb/db/package-info.java | /*
* Copyright (c) 2015 - 2016 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
/**
* The YCSB binding for <a href="http://www.couchbase.com/">Couchbase</a>.
*/
package site.ycsb.db;
| 771 | 32.565217 | 74 | java |
null | NearPMSW-main/baseline/logging/YCSB/couchbase/src/main/java/site/ycsb/db/CouchbaseClient.java | /**
* Copyright (c) 2013 - 2016 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.db;
import com.couchbase.client.protocol.views.*;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import site.ycsb.ByteIterator;
import site.ycsb.DB;
import site.ycsb.DBException;
import site.ycsb.Status;
import site.ycsb.StringByteIterator;
import net.spy.memcached.PersistTo;
import net.spy.memcached.ReplicateTo;
import net.spy.memcached.internal.OperationFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
/**
* A class that wraps the CouchbaseClient to allow it to be interfaced with YCSB.
* This class extends {@link DB} and implements the database interface used by YCSB client.
*/
public class CouchbaseClient extends DB {
public static final String URL_PROPERTY = "couchbase.url";
public static final String BUCKET_PROPERTY = "couchbase.bucket";
public static final String PASSWORD_PROPERTY = "couchbase.password";
public static final String CHECKF_PROPERTY = "couchbase.checkFutures";
public static final String PERSIST_PROPERTY = "couchbase.persistTo";
public static final String REPLICATE_PROPERTY = "couchbase.replicateTo";
public static final String JSON_PROPERTY = "couchbase.json";
public static final String DESIGN_DOC_PROPERTY = "couchbase.ddoc";
public static final String VIEW_PROPERTY = "couchbase.view";
public static final String STALE_PROPERTY = "couchbase.stale";
public static final String SCAN_PROPERTY = "scanproportion";
public static final String STALE_PROPERTY_DEFAULT = Stale.OK.name();
public static final String SCAN_PROPERTY_DEFAULT = "0.0";
protected static final ObjectMapper JSON_MAPPER = new ObjectMapper();
private com.couchbase.client.CouchbaseClient client;
private PersistTo persistTo;
private ReplicateTo replicateTo;
private boolean checkFutures;
private boolean useJson;
private String designDoc;
private String viewName;
private Stale stale;
private View view;
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
public void init() throws DBException {
Properties props = getProperties();
String url = props.getProperty(URL_PROPERTY, "http://127.0.0.1:8091/pools");
String bucket = props.getProperty(BUCKET_PROPERTY, "default");
String password = props.getProperty(PASSWORD_PROPERTY, "");
checkFutures = props.getProperty(CHECKF_PROPERTY, "true").equals("true");
useJson = props.getProperty(JSON_PROPERTY, "true").equals("true");
persistTo = parsePersistTo(props.getProperty(PERSIST_PROPERTY, "0"));
replicateTo = parseReplicateTo(props.getProperty(REPLICATE_PROPERTY, "0"));
designDoc = getProperties().getProperty(DESIGN_DOC_PROPERTY);
viewName = getProperties().getProperty(VIEW_PROPERTY);
stale = Stale.valueOf(getProperties().getProperty(STALE_PROPERTY, STALE_PROPERTY_DEFAULT).toUpperCase());
Double scanproportion = Double.valueOf(props.getProperty(SCAN_PROPERTY, SCAN_PROPERTY_DEFAULT));
Properties systemProperties = System.getProperties();
systemProperties.put("net.spy.log.LoggerImpl", "net.spy.memcached.compat.log.SLF4JLogger");
System.setProperties(systemProperties);
try {
client = new com.couchbase.client.CouchbaseClient(Arrays.asList(new URI(url)), bucket, password);
} catch (Exception e) {
throw new DBException("Could not create CouchbaseClient object.", e);
}
if (scanproportion > 0) {
try {
view = client.getView(designDoc, viewName);
} catch (Exception e) {
throw new DBException(String.format("%s=%s and %s=%s provided, unable to connect to view.",
DESIGN_DOC_PROPERTY, designDoc, VIEW_PROPERTY, viewName), e.getCause());
}
}
}
/**
* Parse the replicate property into the correct enum.
*
* @param property the stringified property value.
* @throws DBException if parsing the property did fail.
* @return the correct enum.
*/
private ReplicateTo parseReplicateTo(final String property) throws DBException {
int value = Integer.parseInt(property);
switch (value) {
case 0:
return ReplicateTo.ZERO;
case 1:
return ReplicateTo.ONE;
case 2:
return ReplicateTo.TWO;
case 3:
return ReplicateTo.THREE;
default:
throw new DBException(REPLICATE_PROPERTY + " must be between 0 and 3");
}
}
/**
* Parse the persist property into the correct enum.
*
* @param property the stringified property value.
* @throws DBException if parsing the property did fail.
* @return the correct enum.
*/
private PersistTo parsePersistTo(final String property) throws DBException {
int value = Integer.parseInt(property);
switch (value) {
case 0:
return PersistTo.ZERO;
case 1:
return PersistTo.ONE;
case 2:
return PersistTo.TWO;
case 3:
return PersistTo.THREE;
case 4:
return PersistTo.FOUR;
default:
throw new DBException(PERSIST_PROPERTY + " must be between 0 and 4");
}
}
/**
* Shutdown the client.
*/
@Override
public void cleanup() {
client.shutdown();
}
@Override
public Status read(final String table, final String key, final Set<String> fields,
final Map<String, ByteIterator> result) {
String formattedKey = formatKey(table, key);
try {
Object loaded = client.get(formattedKey);
if (loaded == null) {
return Status.ERROR;
}
decode(loaded, fields, result);
return Status.OK;
} catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("Could not read value for key " + formattedKey, e);
}
return Status.ERROR;
}
}
@Override
public Status scan(final String table, final String startkey, final int recordcount, final Set<String> fields,
final Vector<HashMap<String, ByteIterator>> result) {
try {
Query query = new Query().setRangeStart(startkey)
.setLimit(recordcount)
.setIncludeDocs(true)
.setStale(stale);
ViewResponse response = client.query(view, query);
for (ViewRow row : response) {
HashMap<String, ByteIterator> rowMap = new HashMap();
decode(row.getDocument(), fields, rowMap);
result.add(rowMap);
}
return Status.OK;
} catch (Exception e) {
log.error(e.getMessage());
}
return Status.ERROR;
}
@Override
public Status update(final String table, final String key, final Map<String, ByteIterator> values) {
String formattedKey = formatKey(table, key);
try {
final OperationFuture<Boolean> future = client.replace(formattedKey, encode(values), persistTo, replicateTo);
return checkFutureStatus(future);
} catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("Could not update value for key " + formattedKey, e);
}
return Status.ERROR;
}
}
@Override
public Status insert(final String table, final String key, final Map<String, ByteIterator> values) {
String formattedKey = formatKey(table, key);
try {
final OperationFuture<Boolean> future = client.add(formattedKey, encode(values), persistTo, replicateTo);
return checkFutureStatus(future);
} catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("Could not insert value for key " + formattedKey, e);
}
return Status.ERROR;
}
}
@Override
public Status delete(final String table, final String key) {
String formattedKey = formatKey(table, key);
try {
final OperationFuture<Boolean> future = client.delete(formattedKey, persistTo, replicateTo);
return checkFutureStatus(future);
} catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("Could not delete value for key " + formattedKey, e);
}
return Status.ERROR;
}
}
/**
* Prefix the key with the given prefix, to establish a unique namespace.
*
* @param prefix the prefix to use.
* @param key the actual key.
* @return the formatted and prefixed key.
*/
private String formatKey(final String prefix, final String key) {
return prefix + ":" + key;
}
/**
* Wrapper method that either inspects the future or not.
*
* @param future the future to potentially verify.
* @return the status of the future result.
*/
private Status checkFutureStatus(final OperationFuture<?> future) {
if (checkFutures) {
return future.getStatus().isSuccess() ? Status.OK : Status.ERROR;
} else {
return Status.OK;
}
}
/**
* Decode the object from server into the storable result.
*
* @param source the loaded object.
* @param fields the fields to check.
* @param dest the result passed back to the ycsb core.
*/
private void decode(final Object source, final Set<String> fields, final Map<String, ByteIterator> dest) {
if (useJson) {
try {
JsonNode json = JSON_MAPPER.readTree((String) source);
boolean checkFields = fields != null && !fields.isEmpty();
for (Iterator<Map.Entry<String, JsonNode>> jsonFields = json.fields(); jsonFields.hasNext();) {
Map.Entry<String, JsonNode> jsonField = jsonFields.next();
String name = jsonField.getKey();
if (checkFields && fields.contains(name)) {
continue;
}
JsonNode jsonValue = jsonField.getValue();
if (jsonValue != null && !jsonValue.isNull()) {
dest.put(name, new StringByteIterator(jsonValue.asText()));
}
}
} catch (Exception e) {
throw new RuntimeException("Could not decode JSON");
}
} else {
Map<String, String> converted = (HashMap<String, String>) source;
for (Map.Entry<String, String> entry : converted.entrySet()) {
dest.put(entry.getKey(), new StringByteIterator(entry.getValue()));
}
}
}
/**
* Encode the object for couchbase storage.
*
* @param source the source value.
* @return the storable object.
*/
private Object encode(final Map<String, ByteIterator> source) {
Map<String, String> stringMap = StringByteIterator.getStringMap(source);
if (!useJson) {
return stringMap;
}
ObjectNode node = JSON_MAPPER.createObjectNode();
for (Map.Entry<String, String> pair : stringMap.entrySet()) {
node.put(pair.getKey(), pair.getValue());
}
JsonFactory jsonFactory = new JsonFactory();
Writer writer = new StringWriter();
try {
JsonGenerator jsonGenerator = jsonFactory.createGenerator(writer);
JSON_MAPPER.writeTree(jsonGenerator, node);
} catch (Exception e) {
throw new RuntimeException("Could not encode JSON value");
}
return writer.toString();
}
}
| 11,866 | 32.148045 | 115 | java |
null | NearPMSW-main/baseline/logging/YCSB/hbase2/src/test/java/site/ycsb/db/hbase2/HBaseClient2Test.java | /**
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.db.hbase2;
import static org.junit.Assert.assertArrayEquals;
import static site.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY;
import static site.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY_DEFAULT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import site.ycsb.ByteIterator;
import site.ycsb.Status;
import site.ycsb.StringByteIterator;
import site.ycsb.measurements.Measurements;
import site.ycsb.workloads.CoreWorkload;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
/**
* Integration tests for the YCSB HBase 2 client using an HBase minicluster.
*/
public class HBaseClient2Test {
private final static String COLUMN_FAMILY = "cf";
private static HBaseTestingUtility testingUtil;
private HBaseClient2 client;
private Table table = null;
private String tableName;
private static boolean isWindows() {
final String os = System.getProperty("os.name");
return os.startsWith("Windows");
}
/**
* Creates a mini-cluster for use in these tests.
* This is a heavy-weight operation, so invoked only once for the test class.
*/
@BeforeClass
public static void setUpClass() throws Exception {
// Minicluster setup fails on Windows with an UnsatisfiedLinkError.
// Skip if windows.
assumeTrue(!isWindows());
testingUtil = HBaseTestingUtility.createLocalHTU();
testingUtil.startMiniCluster();
}
/**
* Tears down mini-cluster.
*/
@AfterClass
public static void tearDownClass() throws Exception {
if (testingUtil != null) {
testingUtil.shutdownMiniCluster();
}
}
/**
* Re-create the table for each test. Using default properties.
*/
public void setUp() throws Exception {
setUp(new Properties());
}
/**
* Re-create the table for each test. Using custom properties.
*/
public void setUp(Properties p) throws Exception {
client = new HBaseClient2();
client.setConfiguration(new Configuration(testingUtil.getConfiguration()));
p.setProperty("columnfamily", COLUMN_FAMILY);
Measurements.setProperties(p);
final CoreWorkload workload = new CoreWorkload();
workload.init(p);
tableName = p.getProperty(TABLENAME_PROPERTY, TABLENAME_PROPERTY_DEFAULT);
table = testingUtil.createTable(TableName.valueOf(tableName), Bytes.toBytes(COLUMN_FAMILY));
client.setProperties(p);
client.init();
}
@After
public void tearDown() throws Exception {
table.close();
testingUtil.deleteTable(TableName.valueOf(tableName));
}
@Test
public void testRead() throws Exception {
setUp();
final String rowKey = "row1";
final Put p = new Put(Bytes.toBytes(rowKey));
p.addColumn(Bytes.toBytes(COLUMN_FAMILY),
Bytes.toBytes("column1"), Bytes.toBytes("value1"));
p.addColumn(Bytes.toBytes(COLUMN_FAMILY),
Bytes.toBytes("column2"), Bytes.toBytes("value2"));
table.put(p);
final HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();
final Status status = client.read(tableName, rowKey, null, result);
assertEquals(Status.OK, status);
assertEquals(2, result.size());
assertEquals("value1", result.get("column1").toString());
assertEquals("value2", result.get("column2").toString());
}
@Test
public void testReadMissingRow() throws Exception {
setUp();
final HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();
final Status status = client.read(tableName, "Missing row", null, result);
assertEquals(Status.NOT_FOUND, status);
assertEquals(0, result.size());
}
@Test
public void testScan() throws Exception {
setUp();
// Fill with data
final String colStr = "row_number";
final byte[] col = Bytes.toBytes(colStr);
final int n = 10;
final List<Put> puts = new ArrayList<Put>(n);
for(int i = 0; i < n; i++) {
final byte[] key = Bytes.toBytes(String.format("%05d", i));
final byte[] value = java.nio.ByteBuffer.allocate(4).putInt(i).array();
final Put p = new Put(key);
p.addColumn(Bytes.toBytes(COLUMN_FAMILY), col, value);
puts.add(p);
}
table.put(puts);
// Test
final Vector<HashMap<String, ByteIterator>> result =
new Vector<HashMap<String, ByteIterator>>();
// Scan 5 records, skipping the first
client.scan(tableName, "00001", 5, null, result);
assertEquals(5, result.size());
for(int i = 0; i < 5; i++) {
final HashMap<String, ByteIterator> row = result.get(i);
assertEquals(1, row.size());
assertTrue(row.containsKey(colStr));
final byte[] bytes = row.get(colStr).toArray();
final ByteBuffer buf = ByteBuffer.wrap(bytes);
final int rowNum = buf.getInt();
assertEquals(i + 1, rowNum);
}
}
@Test
public void testScanWithValueFilteringUsingDefaultProperties() throws Exception {
testScanWithValueFiltering(null, null, 100, new byte[][] {
Bytes.fromHex("0000"), Bytes.fromHex("1111"), Bytes.fromHex("2222"), Bytes.fromHex("3333"),
Bytes.fromHex("4444"), Bytes.fromHex("5555"), Bytes.fromHex("6666"), Bytes.fromHex("7777"),
});
}
@Test
public void testScanWithValueFilteringOperationLessOrEqual() throws Exception {
testScanWithValueFiltering("less_or_equal", "3333", 100, new byte[][] {
Bytes.fromHex("0000"), Bytes.fromHex("1111"), Bytes.fromHex("2222"), Bytes.fromHex("3333"),
});
}
@Test
public void testScanWithValueFilteringOperationEqual() throws Exception {
testScanWithValueFiltering("equal", "AAAA", 100, new byte[][]{
Bytes.fromHex("AAAA")
});
}
@Test
public void testScanWithValueFilteringOperationNotEqual() throws Exception {
testScanWithValueFiltering("not_equal", "AAAA", 100 , new byte[][]{
Bytes.fromHex("0000"), Bytes.fromHex("1111"), Bytes.fromHex("2222"), Bytes.fromHex("3333"),
Bytes.fromHex("4444"), Bytes.fromHex("5555"), Bytes.fromHex("6666"), Bytes.fromHex("7777"),
Bytes.fromHex("8888"), Bytes.fromHex("9999"), Bytes.fromHex("BBBB"),
Bytes.fromHex("CCCC"), Bytes.fromHex("DDDD"), Bytes.fromHex("EEEE"), Bytes.fromHex("FFFF")
});
}
@Test
public void testScanWithValueFilteringAndRowLimit() throws Exception {
testScanWithValueFiltering("greater", "8887", 3, new byte[][] {
Bytes.fromHex("8888"), Bytes.fromHex("9999"), Bytes.fromHex("AAAA")
});
}
@Test
public void testUpdate() throws Exception{
setUp();
final String key = "key";
final HashMap<String, String> input = new HashMap<String, String>();
input.put("column1", "value1");
input.put("column2", "value2");
final Status status = client.insert(tableName, key, StringByteIterator.getByteIteratorMap(input));
assertEquals(Status.OK, status);
// Verify result
final Get get = new Get(Bytes.toBytes(key));
final Result result = this.table.get(get);
assertFalse(result.isEmpty());
assertEquals(2, result.size());
for(final java.util.Map.Entry<String, String> entry : input.entrySet()) {
assertEquals(entry.getValue(),
new String(result.getValue(Bytes.toBytes(COLUMN_FAMILY),
Bytes.toBytes(entry.getKey()))));
}
}
@Test
@Ignore("Not yet implemented")
public void testDelete() {
fail("Not yet implemented");
}
private void testScanWithValueFiltering(String operation, String filterValue, int scanRowLimit,
byte[][] expectedValuesReturned) throws Exception {
Properties properties = new Properties();
properties.setProperty("hbase.usescanvaluefiltering", String.valueOf(true));
if(operation != null) {
properties.setProperty("hbase.scanfilteroperator", operation);
}
if(filterValue != null) {
properties.setProperty("hbase.scanfiltervalue", filterValue);
}
// setup the client and fill two columns with data
setUp(properties);
setupTableColumnWithHexValues("col_1");
setupTableColumnWithHexValues("col_2");
Vector<HashMap<String, ByteIterator>> result = new Vector<>();
// first scan the whole table (both columns)
client.scan(tableName, "00000", scanRowLimit, null, result);
assertEquals(expectedValuesReturned.length, result.size());
for(int i = 0; i < expectedValuesReturned.length; i++) {
final HashMap<String, ByteIterator> row = result.get(i);
assertEquals(2, row.size());
assertTrue(row.containsKey("col_1") && row.containsKey("col_2"));
assertArrayEquals(expectedValuesReturned[i], row.get("col_1").toArray());
assertArrayEquals(expectedValuesReturned[i], row.get("col_2").toArray());
}
// now scan only a single column (the filter should work here too)
result = new Vector<>();
client.scan(tableName, "00000", scanRowLimit, Collections.singleton("col_1"), result);
assertEquals(expectedValuesReturned.length, result.size());
for(int i = 0; i < expectedValuesReturned.length; i++) {
final HashMap<String, ByteIterator> row = result.get(i);
assertEquals(1, row.size());
assertTrue(row.containsKey("col_1"));
assertArrayEquals(expectedValuesReturned[i], row.get("col_1").toArray());
}
}
private void setupTableColumnWithHexValues(String colStr) throws Exception {
final byte[] col = Bytes.toBytes(colStr);
final byte[][] values = {
Bytes.fromHex("0000"), Bytes.fromHex("1111"), Bytes.fromHex("2222"), Bytes.fromHex("3333"),
Bytes.fromHex("4444"), Bytes.fromHex("5555"), Bytes.fromHex("6666"), Bytes.fromHex("7777"),
Bytes.fromHex("8888"), Bytes.fromHex("9999"), Bytes.fromHex("AAAA"), Bytes.fromHex("BBBB"),
Bytes.fromHex("CCCC"), Bytes.fromHex("DDDD"), Bytes.fromHex("EEEE"), Bytes.fromHex("FFFF")
};
final List<Put> puts = new ArrayList<>(16);
for(int i = 0; i < 16; i++) {
final byte[] key = Bytes.toBytes(String.format("%05d", i));
final byte[] value = values[i];
final Put p = new Put(key);
p.addColumn(Bytes.toBytes(COLUMN_FAMILY), col, value);
puts.add(p);
}
table.put(puts);
}
}
| 11,470 | 34.513932 | 102 | java |
null | NearPMSW-main/baseline/logging/YCSB/hbase2/src/main/java/site/ycsb/db/hbase2/package-info.java | /*
* Copyright (c) 2014, Yahoo!, Inc. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
/**
* The YCSB binding for <a href="https://hbase.apache.org/">HBase</a>
* using the HBase 2 shaded API.
*/
package site.ycsb.db.hbase2;
| 795 | 32.166667 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/hbase2/src/main/java/site/ycsb/db/hbase2/HBaseClient2.java | /**
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.db.hbase2;
import org.apache.hadoop.hbase.CompareOperator;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.ByteArrayComparable;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.ValueFilter;
import site.ycsb.ByteArrayByteIterator;
import site.ycsb.ByteIterator;
import site.ycsb.DBException;
import site.ycsb.Status;
import site.ycsb.measurements.Measurements;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.BufferedMutator;
import org.apache.hadoop.hbase.client.BufferedMutatorParams;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import static site.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY;
import static site.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY_DEFAULT;
/**
* HBase 2 client for YCSB framework.
*
* Intended for use with HBase's shaded client.
*/
public class HBaseClient2 extends site.ycsb.DB {
private static final AtomicInteger THREAD_COUNT = new AtomicInteger(0);
private Configuration config = HBaseConfiguration.create();
private boolean debug = false;
private String tableName = "";
/**
* A Cluster Connection instance that is shared by all running ycsb threads.
* Needs to be initialized late so we pick up command-line configs if any.
* To ensure one instance only in a multi-threaded context, guard access
* with a 'lock' object.
* @See #CONNECTION_LOCK.
*/
private static Connection connection = null;
// Depending on the value of clientSideBuffering, either bufferedMutator
// (clientSideBuffering) or currentTable (!clientSideBuffering) will be used.
private Table currentTable = null;
private BufferedMutator bufferedMutator = null;
private String columnFamily = "";
private byte[] columnFamilyBytes;
/**
* Durability to use for puts and deletes.
*/
private Durability durability = Durability.USE_DEFAULT;
/** Whether or not a page filter should be used to limit scan length. */
private boolean usePageFilter = true;
/**
* If true, buffer mutations on the client. This is the default behavior for
* HBaseClient. For measuring insert/update/delete latencies, client side
* buffering should be disabled.
*/
private boolean clientSideBuffering = false;
private long writeBufferSize = 1024 * 1024 * 12;
/**
* If true, we will configure server-side value filtering during scans.
*/
private boolean useScanValueFiltering = false;
private CompareOperator scanFilterOperator;
private static final String DEFAULT_SCAN_FILTER_OPERATOR = "less_or_equal";
private ByteArrayComparable scanFilterValue;
private static final String DEFAULT_SCAN_FILTER_VALUE = // 200 hexadecimal chars translated into 100 bytes
"7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
/**
* Initialize any state for this DB. Called once per DB instance; there is one
* DB instance per client thread.
*/
@Override
public void init() throws DBException {
if ("true"
.equals(getProperties().getProperty("clientbuffering", "false"))) {
this.clientSideBuffering = true;
}
if (getProperties().containsKey("writebuffersize")) {
writeBufferSize =
Long.parseLong(getProperties().getProperty("writebuffersize"));
}
if (getProperties().getProperty("durability") != null) {
this.durability =
Durability.valueOf(getProperties().getProperty("durability"));
}
if ("kerberos".equalsIgnoreCase(config.get("hbase.security.authentication"))) {
config.set("hadoop.security.authentication", "Kerberos");
UserGroupInformation.setConfiguration(config);
}
if ((getProperties().getProperty("principal") != null)
&& (getProperties().getProperty("keytab") != null)) {
try {
UserGroupInformation.loginUserFromKeytab(getProperties().getProperty("principal"),
getProperties().getProperty("keytab"));
} catch (IOException e) {
System.err.println("Keytab file is not readable or not found");
throw new DBException(e);
}
}
String table = getProperties().getProperty(TABLENAME_PROPERTY, TABLENAME_PROPERTY_DEFAULT);
try {
THREAD_COUNT.getAndIncrement();
synchronized (THREAD_COUNT) {
if (connection == null) {
// Initialize if not set up already.
connection = ConnectionFactory.createConnection(config);
// Terminate right now if table does not exist, since the client
// will not propagate this error upstream once the workload
// starts.
final TableName tName = TableName.valueOf(table);
try (Admin admin = connection.getAdmin()) {
if (!admin.tableExists(tName)) {
throw new DBException("Table " + tName + " does not exists");
}
}
}
}
} catch (java.io.IOException e) {
throw new DBException(e);
}
if ((getProperties().getProperty("debug") != null)
&& (getProperties().getProperty("debug").compareTo("true") == 0)) {
debug = true;
}
usePageFilter = isBooleanParamSet("hbase.usepagefilter", usePageFilter);
if (isBooleanParamSet("hbase.usescanvaluefiltering", false)) {
useScanValueFiltering=true;
String operator = getProperties().getProperty("hbase.scanfilteroperator");
operator = operator == null || operator.trim().isEmpty() ? DEFAULT_SCAN_FILTER_OPERATOR : operator;
scanFilterOperator = CompareOperator.valueOf(operator.toUpperCase());
String filterValue = getProperties().getProperty("hbase.scanfiltervalue");
filterValue = filterValue == null || filterValue.trim().isEmpty() ? DEFAULT_SCAN_FILTER_VALUE : filterValue;
scanFilterValue = new BinaryComparator(Bytes.fromHex(filterValue));
}
columnFamily = getProperties().getProperty("columnfamily");
if (columnFamily == null) {
System.err.println("Error, must specify a columnfamily for HBase table");
throw new DBException("No columnfamily specified");
}
columnFamilyBytes = Bytes.toBytes(columnFamily);
}
/**
* Cleanup any state for this DB. Called once per DB instance; there is one DB
* instance per client thread.
*/
@Override
public void cleanup() throws DBException {
// Get the measurements instance as this is the only client that should
// count clean up time like an update if client-side buffering is
// enabled.
Measurements measurements = Measurements.getMeasurements();
try {
long st = System.nanoTime();
if (bufferedMutator != null) {
bufferedMutator.close();
}
if (currentTable != null) {
currentTable.close();
}
long en = System.nanoTime();
final String type = clientSideBuffering ? "UPDATE" : "CLEANUP";
measurements.measure(type, (int) ((en - st) / 1000));
int threadCount = THREAD_COUNT.decrementAndGet();
if (threadCount <= 0) {
// Means we are done so ok to shut down the Connection.
synchronized (THREAD_COUNT) {
if (connection != null) {
connection.close();
connection = null;
}
}
}
} catch (IOException e) {
throw new DBException(e);
}
}
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p = new BufferedMutatorParams(tName);
p.writeBufferSize(writeBufferSize);
this.bufferedMutator = connection.getBufferedMutator(p);
}
}
/**
* Read a record from the database. Each field/value pair from the result will
* be stored in a HashMap.
*
* @param table
* The name of the table
* @param key
* The record key of the record to read.
* @param fields
* The list of fields to read, or null for all of them
* @param result
* A HashMap of field/value pairs for the result
* @return Zero on success, a non-zero error code on error
*/
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
// if this is a "new" table, init HTable object. Else, use existing one
if (!tableName.equals(table)) {
currentTable = null;
try {
getHTable(table);
tableName = table;
} catch (IOException e) {
System.err.println("Error accessing HBase table: " + e);
return Status.ERROR;
}
}
Result r = null;
try {
if (debug) {
System.out
.println("Doing read from HBase columnfamily " + columnFamily);
System.out.println("Doing read for key: " + key);
}
Get g = new Get(Bytes.toBytes(key));
if (fields == null) {
g.addFamily(columnFamilyBytes);
} else {
for (String field : fields) {
g.addColumn(columnFamilyBytes, Bytes.toBytes(field));
}
}
r = currentTable.get(g);
} catch (IOException e) {
if (debug) {
System.err.println("Error doing get: " + e);
}
return Status.ERROR;
} catch (ConcurrentModificationException e) {
// do nothing for now...need to understand HBase concurrency model better
return Status.ERROR;
}
if (r.isEmpty()) {
return Status.NOT_FOUND;
}
while (r.advance()) {
final Cell c = r.current();
result.put(Bytes.toString(CellUtil.cloneQualifier(c)),
new ByteArrayByteIterator(CellUtil.cloneValue(c)));
if (debug) {
System.out.println(
"Result for field: " + Bytes.toString(CellUtil.cloneQualifier(c))
+ " is: " + Bytes.toString(CellUtil.cloneValue(c)));
}
}
return Status.OK;
}
/**
* Perform a range scan for a set of records in the database. Each field/value
* pair from the result will be stored in a HashMap.
*
* @param table
* The name of the table
* @param startkey
* The record key of the first record to read.
* @param recordcount
* The number of records to read
* @param fields
* The list of fields to read, or null for all of them
* @param result
* A Vector of HashMaps, where each HashMap is a set field/value
* pairs for one record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// if this is a "new" table, init HTable object. Else, use existing one
if (!tableName.equals(table)) {
currentTable = null;
try {
getHTable(table);
tableName = table;
} catch (IOException e) {
System.err.println("Error accessing HBase table: " + e);
return Status.ERROR;
}
}
Scan s = new Scan(Bytes.toBytes(startkey));
// HBase has no record limit. Here, assume recordcount is small enough to
// bring back in one call.
// We get back recordcount records
FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL);
s.setCaching(recordcount);
if (this.usePageFilter) {
filterList.addFilter(new PageFilter(recordcount));
}
// add specified fields or else all fields
if (fields == null) {
s.addFamily(columnFamilyBytes);
} else {
for (String field : fields) {
s.addColumn(columnFamilyBytes, Bytes.toBytes(field));
}
}
// define value filter if needed
if (useScanValueFiltering){
filterList.addFilter(new ValueFilter(scanFilterOperator, scanFilterValue));
}
s.setFilter(filterList);
// get results
ResultScanner scanner = null;
try {
scanner = currentTable.getScanner(s);
int numResults = 0;
for (Result rr = scanner.next(); rr != null; rr = scanner.next()) {
// get row key
String key = Bytes.toString(rr.getRow());
if (debug) {
System.out.println("Got scan result for key: " + key);
}
HashMap<String, ByteIterator> rowResult =
new HashMap<String, ByteIterator>();
while (rr.advance()) {
final Cell cell = rr.current();
rowResult.put(Bytes.toString(CellUtil.cloneQualifier(cell)),
new ByteArrayByteIterator(CellUtil.cloneValue(cell)));
}
// add rowResult to result vector
result.add(rowResult);
numResults++;
// PageFilter does not guarantee that the number of results is <=
// pageSize, so this
// break is required.
if (numResults >= recordcount) {// if hit recordcount, bail out
break;
}
} // done with row
} catch (IOException e) {
if (debug) {
System.out.println("Error in getting/parsing scan result: " + e);
}
return Status.ERROR;
} finally {
if (scanner != null) {
scanner.close();
}
}
return Status.OK;
}
/**
* Update a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key, overwriting any existing values with the same field name.
*
* @param table
* The name of the table
* @param key
* The record key of the record to write
* @param values
* A HashMap of field/value pairs to update in the record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
// if this is a "new" table, init HTable object. Else, use existing one
if (!tableName.equals(table)) {
currentTable = null;
try {
getHTable(table);
tableName = table;
} catch (IOException e) {
System.err.println("Error accessing HBase table: " + e);
return Status.ERROR;
}
}
if (debug) {
System.out.println("Setting up put for key: " + key);
}
Put p = new Put(Bytes.toBytes(key));
p.setDurability(durability);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
byte[] value = entry.getValue().toArray();
if (debug) {
System.out.println("Adding field/value " + entry.getKey() + "/"
+ Bytes.toStringBinary(value) + " to put request");
}
p.addColumn(columnFamilyBytes, Bytes.toBytes(entry.getKey()), value);
}
try {
if (clientSideBuffering) {
// removed Preconditions.checkNotNull, which throws NPE, in favor of NPE on next line
bufferedMutator.mutate(p);
} else {
currentTable.put(p);
}
} catch (IOException e) {
if (debug) {
System.err.println("Error doing put: " + e);
}
return Status.ERROR;
} catch (ConcurrentModificationException e) {
// do nothing for now...hope this is rare
return Status.ERROR;
}
return Status.OK;
}
/**
* Insert a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key.
*
* @param table
* The name of the table
* @param key
* The record key of the record to insert.
* @param values
* A HashMap of field/value pairs to insert in the record
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return update(table, key, values);
}
/**
* Delete a record from the database.
*
* @param table
* The name of the table
* @param key
* The record key of the record to delete.
* @return Zero on success, a non-zero error code on error
*/
@Override
public Status delete(String table, String key) {
// if this is a "new" table, init HTable object. Else, use existing one
if (!tableName.equals(table)) {
currentTable = null;
try {
getHTable(table);
tableName = table;
} catch (IOException e) {
System.err.println("Error accessing HBase table: " + e);
return Status.ERROR;
}
}
if (debug) {
System.out.println("Doing delete for key: " + key);
}
final Delete d = new Delete(Bytes.toBytes(key));
d.setDurability(durability);
try {
if (clientSideBuffering) {
// removed Preconditions.checkNotNull, which throws NPE, in favor of NPE on next line
bufferedMutator.mutate(d);
} else {
currentTable.delete(d);
}
} catch (IOException e) {
if (debug) {
System.err.println("Error doing delete: " + e);
}
return Status.ERROR;
}
return Status.OK;
}
// Only non-private for testing.
void setConfiguration(final Configuration newConfig) {
this.config = newConfig;
}
private boolean isBooleanParamSet(String param, boolean defaultValue){
return Boolean.parseBoolean(getProperties().getProperty(param, Boolean.toString(defaultValue)));
}
}
/*
* For customized vim control set autoindent set si set shiftwidth=4
*/
| 19,193 | 32.732865 | 114 | java |
null | NearPMSW-main/baseline/logging/YCSB/dynamodb/src/main/java/site/ycsb/db/package-info.java | /*
* Copyright 2015-2016 YCSB Contributors. All Rights Reserved.
*
* 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. See accompanying
* LICENSE file.
*/
/**
* The YCSB binding for <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a>.
*/
package site.ycsb.db;
| 771 | 32.565217 | 80 | java |
null | NearPMSW-main/baseline/logging/YCSB/dynamodb/src/main/java/site/ycsb/db/DynamoDBClient.java | /*
* Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Copyright 2015-2016 YCSB Contributors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 site.ycsb.db;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import site.ycsb.*;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;
/**
* DynamoDB client for YCSB.
*/
public class DynamoDBClient extends DB {
/**
* Defines the primary key type used in this particular DB instance.
* <p>
* By default, the primary key type is "HASH". Optionally, the user can
* choose to use hash_and_range key type. See documentation in the
* DynamoDB.Properties file for more details.
*/
private enum PrimaryKeyType {
HASH,
HASH_AND_RANGE
}
private AmazonDynamoDB dynamoDB;
private String primaryKeyName;
private PrimaryKeyType primaryKeyType = PrimaryKeyType.HASH;
// If the user choose to use HASH_AND_RANGE as primary key type, then
// the following two variables become relevant. See documentation in the
// DynamoDB.Properties file for more details.
private String hashKeyValue;
private String hashKeyName;
private boolean consistentRead = false;
private String region = "us-east-1";
private String endpoint = null;
private int maxConnects = 50;
private static final Logger LOGGER = Logger.getLogger(DynamoDBClient.class);
private static final Status CLIENT_ERROR = new Status("CLIENT_ERROR", "An error occurred on the client.");
private static final String DEFAULT_HASH_KEY_VALUE = "YCSB_0";
@Override
public void init() throws DBException {
String debug = getProperties().getProperty("dynamodb.debug", null);
if (null != debug && "true".equalsIgnoreCase(debug)) {
LOGGER.setLevel(Level.DEBUG);
}
String configuredEndpoint = getProperties().getProperty("dynamodb.endpoint", null);
String credentialsFile = getProperties().getProperty("dynamodb.awsCredentialsFile", null);
String primaryKey = getProperties().getProperty("dynamodb.primaryKey", null);
String primaryKeyTypeString = getProperties().getProperty("dynamodb.primaryKeyType", null);
String consistentReads = getProperties().getProperty("dynamodb.consistentReads", null);
String connectMax = getProperties().getProperty("dynamodb.connectMax", null);
String configuredRegion = getProperties().getProperty("dynamodb.region", null);
if (null != connectMax) {
this.maxConnects = Integer.parseInt(connectMax);
}
if (null != consistentReads && "true".equalsIgnoreCase(consistentReads)) {
this.consistentRead = true;
}
if (null != configuredEndpoint) {
this.endpoint = configuredEndpoint;
}
if (null == primaryKey || primaryKey.length() < 1) {
throw new DBException("Missing primary key attribute name, cannot continue");
}
if (null != primaryKeyTypeString) {
try {
this.primaryKeyType = PrimaryKeyType.valueOf(primaryKeyTypeString.trim().toUpperCase());
} catch (IllegalArgumentException e) {
throw new DBException("Invalid primary key mode specified: " + primaryKeyTypeString +
". Expecting HASH or HASH_AND_RANGE.");
}
}
if (this.primaryKeyType == PrimaryKeyType.HASH_AND_RANGE) {
// When the primary key type is HASH_AND_RANGE, keys used by YCSB
// are range keys so we can benchmark performance of individual hash
// partitions. In this case, the user must specify the hash key's name
// and optionally can designate a value for the hash key.
String configuredHashKeyName = getProperties().getProperty("dynamodb.hashKeyName", null);
if (null == configuredHashKeyName || configuredHashKeyName.isEmpty()) {
throw new DBException("Must specify a non-empty hash key name when the primary key type is HASH_AND_RANGE.");
}
this.hashKeyName = configuredHashKeyName;
this.hashKeyValue = getProperties().getProperty("dynamodb.hashKeyValue", DEFAULT_HASH_KEY_VALUE);
}
if (null != configuredRegion && configuredRegion.length() > 0) {
region = configuredRegion;
}
try {
AmazonDynamoDBClientBuilder dynamoDBBuilder = AmazonDynamoDBClientBuilder.standard();
dynamoDBBuilder = null == endpoint ?
dynamoDBBuilder.withRegion(this.region) :
dynamoDBBuilder.withEndpointConfiguration(
new AwsClientBuilder.EndpointConfiguration(this.endpoint, this.region)
);
dynamoDB = dynamoDBBuilder
.withClientConfiguration(
new ClientConfiguration()
.withTcpKeepAlive(true)
.withMaxConnections(this.maxConnects)
)
.withCredentials(new AWSStaticCredentialsProvider(new PropertiesCredentials(new File(credentialsFile))))
.build();
primaryKeyName = primaryKey;
LOGGER.info("dynamodb connection created with " + this.endpoint);
} catch (Exception e1) {
LOGGER.error("DynamoDBClient.init(): Could not initialize DynamoDB client.", e1);
}
}
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("readkey: " + key + " from table: " + table);
}
GetItemRequest req = new GetItemRequest(table, createPrimaryKey(key));
req.setAttributesToGet(fields);
req.setConsistentRead(consistentRead);
GetItemResult res;
try {
res = dynamoDB.getItem(req);
} catch (AmazonServiceException ex) {
LOGGER.error(ex);
return Status.ERROR;
} catch (AmazonClientException ex) {
LOGGER.error(ex);
return CLIENT_ERROR;
}
if (null != res.getItem()) {
result.putAll(extractResult(res.getItem()));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Result: " + res.toString());
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("scan " + recordcount + " records from key: " + startkey + " on table: " + table);
}
/*
* on DynamoDB's scan, startkey is *exclusive* so we need to
* getItem(startKey) and then use scan for the res
*/
GetItemRequest greq = new GetItemRequest(table, createPrimaryKey(startkey));
greq.setAttributesToGet(fields);
GetItemResult gres;
try {
gres = dynamoDB.getItem(greq);
} catch (AmazonServiceException ex) {
LOGGER.error(ex);
return Status.ERROR;
} catch (AmazonClientException ex) {
LOGGER.error(ex);
return CLIENT_ERROR;
}
if (null != gres.getItem()) {
result.add(extractResult(gres.getItem()));
}
int count = 1; // startKey is done, rest to go.
Map<String, AttributeValue> startKey = createPrimaryKey(startkey);
ScanRequest req = new ScanRequest(table);
req.setAttributesToGet(fields);
while (count < recordcount) {
req.setExclusiveStartKey(startKey);
req.setLimit(recordcount - count);
ScanResult res;
try {
res = dynamoDB.scan(req);
} catch (AmazonServiceException ex) {
LOGGER.error(ex);
return Status.ERROR;
} catch (AmazonClientException ex) {
LOGGER.error(ex);
return CLIENT_ERROR;
}
count += res.getCount();
for (Map<String, AttributeValue> items : res.getItems()) {
result.add(extractResult(items));
}
startKey = res.getLastEvaluatedKey();
}
return Status.OK;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("updatekey: " + key + " from table: " + table);
}
Map<String, AttributeValueUpdate> attributes = new HashMap<>(values.size());
for (Entry<String, ByteIterator> val : values.entrySet()) {
AttributeValue v = new AttributeValue(val.getValue().toString());
attributes.put(val.getKey(), new AttributeValueUpdate().withValue(v).withAction("PUT"));
}
UpdateItemRequest req = new UpdateItemRequest(table, createPrimaryKey(key), attributes);
try {
dynamoDB.updateItem(req);
} catch (AmazonServiceException ex) {
LOGGER.error(ex);
return Status.ERROR;
} catch (AmazonClientException ex) {
LOGGER.error(ex);
return CLIENT_ERROR;
}
return Status.OK;
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("insertkey: " + primaryKeyName + "-" + key + " from table: " + table);
}
Map<String, AttributeValue> attributes = createAttributes(values);
// adding primary key
attributes.put(primaryKeyName, new AttributeValue(key));
if (primaryKeyType == PrimaryKeyType.HASH_AND_RANGE) {
// If the primary key type is HASH_AND_RANGE, then what has been put
// into the attributes map above is the range key part of the primary
// key, we still need to put in the hash key part here.
attributes.put(hashKeyName, new AttributeValue(hashKeyValue));
}
PutItemRequest putItemRequest = new PutItemRequest(table, attributes);
try {
dynamoDB.putItem(putItemRequest);
} catch (AmazonServiceException ex) {
LOGGER.error(ex);
return Status.ERROR;
} catch (AmazonClientException ex) {
LOGGER.error(ex);
return CLIENT_ERROR;
}
return Status.OK;
}
@Override
public Status delete(String table, String key) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("deletekey: " + key + " from table: " + table);
}
DeleteItemRequest req = new DeleteItemRequest(table, createPrimaryKey(key));
try {
dynamoDB.deleteItem(req);
} catch (AmazonServiceException ex) {
LOGGER.error(ex);
return Status.ERROR;
} catch (AmazonClientException ex) {
LOGGER.error(ex);
return CLIENT_ERROR;
}
return Status.OK;
}
private static Map<String, AttributeValue> createAttributes(Map<String, ByteIterator> values) {
Map<String, AttributeValue> attributes = new HashMap<>(values.size() + 1);
for (Entry<String, ByteIterator> val : values.entrySet()) {
attributes.put(val.getKey(), new AttributeValue(val.getValue().toString()));
}
return attributes;
}
private HashMap<String, ByteIterator> extractResult(Map<String, AttributeValue> item) {
if (null == item) {
return null;
}
HashMap<String, ByteIterator> rItems = new HashMap<>(item.size());
for (Entry<String, AttributeValue> attr : item.entrySet()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Result- key: %s, value: %s", attr.getKey(), attr.getValue()));
}
rItems.put(attr.getKey(), new StringByteIterator(attr.getValue().getS()));
}
return rItems;
}
private Map<String, AttributeValue> createPrimaryKey(String key) {
Map<String, AttributeValue> k = new HashMap<>();
if (primaryKeyType == PrimaryKeyType.HASH) {
k.put(primaryKeyName, new AttributeValue().withS(key));
} else if (primaryKeyType == PrimaryKeyType.HASH_AND_RANGE) {
k.put(hashKeyName, new AttributeValue().withS(hashKeyValue));
k.put(primaryKeyName, new AttributeValue().withS(key));
} else {
throw new RuntimeException("Assertion Error: impossible primary key type");
}
return k;
}
}
| 12,595 | 34.184358 | 117 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/TestNumericByteIterator.java | /**
* Copyright (c) 2017 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.*;
public class TestNumericByteIterator {
@Test
public void testLong() throws Exception {
NumericByteIterator it = new NumericByteIterator(42L);
assertFalse(it.isFloatingPoint());
assertEquals(42L, it.getLong());
try {
it.getDouble();
fail("Expected IllegalStateException.");
} catch (IllegalStateException e) { }
try {
it.next();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) { }
assertEquals(8, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(7, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(6, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(5, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(4, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(3, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(2, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(1, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 42, (byte) it.nextByte());
assertEquals(0, it.bytesLeft());
assertFalse(it.hasNext());
it.reset();
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
}
@Test
public void testDouble() throws Exception {
NumericByteIterator it = new NumericByteIterator(42.75);
assertTrue(it.isFloatingPoint());
assertEquals(42.75, it.getDouble(), 0.001);
try {
it.getLong();
fail("Expected IllegalStateException.");
} catch (IllegalStateException e) { }
try {
it.next();
fail("Expected UnsupportedOperationException.");
} catch (UnsupportedOperationException e) { }
assertEquals(8, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 64, (byte) it.nextByte());
assertEquals(7, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 69, (byte) it.nextByte());
assertEquals(6, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 96, (byte) it.nextByte());
assertEquals(5, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(4, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(3, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(2, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(1, it.bytesLeft());
assertTrue(it.hasNext());
assertEquals((byte) 0, (byte) it.nextByte());
assertEquals(0, it.bytesLeft());
assertFalse(it.hasNext());
it.reset();
assertTrue(it.hasNext());
assertEquals((byte) 64, (byte) it.nextByte());
}
}
| 3,935 | 32.355932 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/TestStatus.java | /**
* Copyright (c) 2016 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import org.testng.annotations.Test;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
/**
* Test class for {@link Status}.
*/
public class TestStatus {
@Test
public void testAcceptableStatus() {
assertTrue(Status.OK.isOk());
assertTrue(Status.BATCHED_OK.isOk());
assertFalse(Status.BAD_REQUEST.isOk());
assertFalse(Status.ERROR.isOk());
assertFalse(Status.FORBIDDEN.isOk());
assertFalse(Status.NOT_FOUND.isOk());
assertFalse(Status.NOT_IMPLEMENTED.isOk());
assertFalse(Status.SERVICE_UNAVAILABLE.isOk());
assertFalse(Status.UNEXPECTED_STATE.isOk());
}
}
| 1,318 | 30.404762 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/TestUtils.java | /**
* Copyright (c) 2016 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.Arrays;
import org.testng.annotations.Test;
public class TestUtils {
@Test
public void bytesToFromLong() throws Exception {
byte[] bytes = new byte[8];
assertEquals(Utils.bytesToLong(bytes), 0L);
assertArrayEquals(Utils.longToBytes(0), bytes);
bytes[7] = 1;
assertEquals(Utils.bytesToLong(bytes), 1L);
assertArrayEquals(Utils.longToBytes(1L), bytes);
bytes = new byte[] { 127, -1, -1, -1, -1, -1, -1, -1 };
assertEquals(Utils.bytesToLong(bytes), Long.MAX_VALUE);
assertArrayEquals(Utils.longToBytes(Long.MAX_VALUE), bytes);
bytes = new byte[] { -128, 0, 0, 0, 0, 0, 0, 0 };
assertEquals(Utils.bytesToLong(bytes), Long.MIN_VALUE);
assertArrayEquals(Utils.longToBytes(Long.MIN_VALUE), bytes);
bytes = new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF };
assertEquals(Utils.bytesToLong(bytes), -1L);
assertArrayEquals(Utils.longToBytes(-1L), bytes);
// if the array is too long we just skip the remainder
bytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 42, 42, 42 };
assertEquals(Utils.bytesToLong(bytes), 1L);
}
@Test
public void bytesToFromDouble() throws Exception {
byte[] bytes = new byte[8];
assertEquals(Utils.bytesToDouble(bytes), 0, 0.0001);
assertArrayEquals(Utils.doubleToBytes(0), bytes);
bytes = new byte[] { 63, -16, 0, 0, 0, 0, 0, 0 };
assertEquals(Utils.bytesToDouble(bytes), 1, 0.0001);
assertArrayEquals(Utils.doubleToBytes(1), bytes);
bytes = new byte[] { -65, -16, 0, 0, 0, 0, 0, 0 };
assertEquals(Utils.bytesToDouble(bytes), -1, 0.0001);
assertArrayEquals(Utils.doubleToBytes(-1), bytes);
bytes = new byte[] { 127, -17, -1, -1, -1, -1, -1, -1 };
assertEquals(Utils.bytesToDouble(bytes), Double.MAX_VALUE, 0.0001);
assertArrayEquals(Utils.doubleToBytes(Double.MAX_VALUE), bytes);
bytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1 };
assertEquals(Utils.bytesToDouble(bytes), Double.MIN_VALUE, 0.0001);
assertArrayEquals(Utils.doubleToBytes(Double.MIN_VALUE), bytes);
bytes = new byte[] { 127, -8, 0, 0, 0, 0, 0, 0 };
assertTrue(Double.isNaN(Utils.bytesToDouble(bytes)));
assertArrayEquals(Utils.doubleToBytes(Double.NaN), bytes);
bytes = new byte[] { 63, -16, 0, 0, 0, 0, 0, 0, 42, 42, 42 };
assertEquals(Utils.bytesToDouble(bytes), 1, 0.0001);
}
@Test (expectedExceptions = NullPointerException.class)
public void bytesToLongNull() throws Exception {
Utils.bytesToLong(null);
}
@Test (expectedExceptions = IndexOutOfBoundsException.class)
public void bytesToLongTooShort() throws Exception {
Utils.bytesToLong(new byte[] { 0, 0, 0, 0, 0, 0, 0 });
}
@Test (expectedExceptions = IllegalArgumentException.class)
public void bytesToDoubleTooShort() throws Exception {
Utils.bytesToDouble(new byte[] { 0, 0, 0, 0, 0, 0, 0 });
}
@Test
public void jvmUtils() throws Exception {
// This should ALWAYS return at least one thread.
assertTrue(Utils.getActiveThreadCount() > 0);
// This should always be greater than 0 or something is goofed up in the JVM.
assertTrue(Utils.getUsedMemoryBytes() > 0);
// Some operating systems may not implement this so we don't have a good
// test. Just make sure it doesn't throw an exception.
Utils.getSystemLoadAverage();
// This will probably be zero but should never be negative.
assertTrue(Utils.getGCTotalCollectionCount() >= 0);
// Could be zero similar to GC total collection count
assertTrue(Utils.getGCTotalTime() >= 0);
// Could be empty
assertTrue(Utils.getGCStatst().size() >= 0);
}
/**
* Since this version of TestNG doesn't appear to have an assertArrayEquals,
* this will compare the two to make sure they're the same.
* @param actual Actual array to validate
* @param expected What the array should contain
* @throws AssertionError if the test fails.
*/
public void assertArrayEquals(final byte[] actual, final byte[] expected) {
if (actual == null && expected != null) {
throw new AssertionError("Expected " + Arrays.toString(expected) +
" but found [null]");
}
if (actual != null && expected == null) {
throw new AssertionError("Expected [null] but found " +
Arrays.toString(actual));
}
if (actual.length != expected.length) {
throw new AssertionError("Expected length " + expected.length +
" but found " + actual.length);
}
for (int i = 0; i < expected.length; i++) {
if (actual[i] != expected[i]) {
throw new AssertionError("Expected byte [" + expected[i] +
"] at index " + i + " but found [" + actual[i] + "]");
}
}
}
} | 5,606 | 37.40411 | 81 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/TestByteIterator.java | /**
* Copyright (c) 2012 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.*;
public class TestByteIterator {
@Test
public void testRandomByteIterator() {
int size = 100;
ByteIterator itor = new RandomByteIterator(size);
assertTrue(itor.hasNext());
assertEquals(size, itor.bytesLeft());
assertEquals(size, itor.toString().getBytes().length);
assertFalse(itor.hasNext());
assertEquals(0, itor.bytesLeft());
itor = new RandomByteIterator(size);
assertEquals(size, itor.toArray().length);
assertFalse(itor.hasNext());
assertEquals(0, itor.bytesLeft());
}
}
| 1,283 | 31.1 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/measurements/exporter/TestMeasurementsExporter.java | /**
* Copyright (c) 2015 Yahoo! Inc. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.measurements.exporter;
import site.ycsb.generator.ZipfianGenerator;
import site.ycsb.measurements.Measurements;
import site.ycsb.measurements.OneMeasurementHistogram;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.testng.annotations.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
public class TestMeasurementsExporter {
@Test
public void testJSONArrayMeasurementsExporter() throws IOException {
Properties props = new Properties();
props.put(Measurements.MEASUREMENT_TYPE_PROPERTY, "histogram");
props.put(OneMeasurementHistogram.VERBOSE_PROPERTY, "true");
Measurements mm = new Measurements(props);
ByteArrayOutputStream out = new ByteArrayOutputStream();
JSONArrayMeasurementsExporter export = new JSONArrayMeasurementsExporter(out);
long min = 5000;
long max = 100000;
ZipfianGenerator zipfian = new ZipfianGenerator(min, max);
for (int i = 0; i < 1000; i++) {
int rnd = zipfian.nextValue().intValue();
mm.measure("UPDATE", rnd);
}
mm.exportMeasurements(export);
export.close();
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(out.toString("UTF-8"));
assertTrue(json.isArray());
assertEquals(json.get(0).get("measurement").asText(), "Operations");
assertEquals(json.get(4).get("measurement").asText(), "MaxLatency(us)");
assertEquals(json.get(11).get("measurement").asText(), "4");
}
}
| 2,394 | 37.629032 | 86 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/workloads/TestCoreWorkload.java | /**
* Copyright (c) 2016 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.workloads;
import static org.testng.Assert.assertTrue;
import java.util.Properties;
import org.testng.annotations.Test;
import site.ycsb.generator.DiscreteGenerator;
public class TestCoreWorkload {
@Test
public void createOperationChooser() {
final Properties p = new Properties();
p.setProperty(CoreWorkload.READ_PROPORTION_PROPERTY, "0.20");
p.setProperty(CoreWorkload.UPDATE_PROPORTION_PROPERTY, "0.20");
p.setProperty(CoreWorkload.INSERT_PROPORTION_PROPERTY, "0.20");
p.setProperty(CoreWorkload.SCAN_PROPORTION_PROPERTY, "0.20");
p.setProperty(CoreWorkload.READMODIFYWRITE_PROPORTION_PROPERTY, "0.20");
final DiscreteGenerator generator = CoreWorkload.createOperationGenerator(p);
final int[] counts = new int[5];
for (int i = 0; i < 100; ++i) {
switch (generator.nextString()) {
case "READ":
++counts[0];
break;
case "UPDATE":
++counts[1];
break;
case "INSERT":
++counts[2];
break;
case "SCAN":
++counts[3];
break;
default:
++counts[4];
}
}
for (int i : counts) {
// Doesn't do a wonderful job of equal distribution, but in a hundred, if we
// don't see at least one of each operation then the generator is really broke.
assertTrue(i > 1);
}
}
@Test (expectedExceptions = IllegalArgumentException.class)
public void createOperationChooserNullProperties() {
CoreWorkload.createOperationGenerator(null);
}
} | 4,257 | 59.828571 | 186 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/workloads/TestTimeSeriesWorkload.java | /**
* Copyright (c) 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.workloads;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import site.ycsb.ByteIterator;
import site.ycsb.Client;
import site.ycsb.DB;
import site.ycsb.NumericByteIterator;
import site.ycsb.Status;
import site.ycsb.StringByteIterator;
import site.ycsb.Utils;
import site.ycsb.WorkloadException;
import site.ycsb.measurements.Measurements;
import org.testng.annotations.Test;
public class TestTimeSeriesWorkload {
@Test
public void twoThreads() throws Exception {
final Properties p = getUTProperties();
Measurements.setProperties(p);
final TimeSeriesWorkload wl = new TimeSeriesWorkload();
wl.init(p);
Object threadState = wl.initThread(p, 0, 2);
MockDB db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
long timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAA");
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertNotNull(db.values.get(i).get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT));
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
timestamp += 60;
}
}
threadState = wl.initThread(p, 1, 2);
db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAB");
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertNotNull(db.values.get(i).get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT));
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
timestamp += 60;
}
}
}
@Test (expectedExceptions = WorkloadException.class)
public void badTimeUnit() throws Exception {
final Properties p = new Properties();
p.put(TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, "foobar");
getWorkload(p, true);
}
@Test (expectedExceptions = WorkloadException.class)
public void failedToInitWorkloadBeforeThreadInit() throws Exception {
final Properties p = getUTProperties();
final TimeSeriesWorkload wl = getWorkload(p, false);
//wl.init(p); // <-- we NEED this :(
final Object threadState = wl.initThread(p, 0, 2);
final MockDB db = new MockDB();
wl.doInsert(db, threadState);
}
@Test (expectedExceptions = IllegalStateException.class)
public void failedToInitThread() throws Exception {
final Properties p = getUTProperties();
final TimeSeriesWorkload wl = getWorkload(p, true);
final MockDB db = new MockDB();
wl.doInsert(db, null);
}
@Test
public void insertOneKeyOneTagCardinalityOne() throws Exception {
final Properties p = getUTProperties();
p.put(CoreWorkload.FIELD_COUNT_PROPERTY, "1");
p.put(TimeSeriesWorkload.TAG_COUNT_PROPERTY, "1");
p.put(TimeSeriesWorkload.TAG_CARDINALITY_PROPERTY, "1");
final TimeSeriesWorkload wl = getWorkload(p, true);
final Object threadState = wl.initThread(p, 0, 1);
final MockDB db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
long timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAA");
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertTrue(((NumericByteIterator) db.values.get(i)
.get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT)).isFloatingPoint());
timestamp += 60;
}
}
@Test
public void insertOneKeyTwoTagsLowCardinality() throws Exception {
final Properties p = getUTProperties();
p.put(CoreWorkload.FIELD_COUNT_PROPERTY, "1");
final TimeSeriesWorkload wl = getWorkload(p, true);
final Object threadState = wl.initThread(p, 0, 1);
final MockDB db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
long timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAA");
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertTrue(((NumericByteIterator) db.values.get(i)
.get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT)).isFloatingPoint());
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
timestamp += 60;
}
}
}
@Test
public void insertTwoKeysTwoTagsLowCardinality() throws Exception {
final Properties p = getUTProperties();
final TimeSeriesWorkload wl = getWorkload(p, true);
final Object threadState = wl.initThread(p, 0, 1);
final MockDB db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
long timestamp = 1451606400;
int metricCtr = 0;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertTrue(((NumericByteIterator) db.values.get(i)
.get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT)).isFloatingPoint());
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
}
if (metricCtr++ > 1) {
assertEquals(db.keys.get(i), "AAAB");
if (metricCtr >= 4) {
metricCtr = 0;
timestamp += 60;
}
} else {
assertEquals(db.keys.get(i), "AAAA");
}
}
}
@Test
public void insertTwoKeysTwoThreads() throws Exception {
final Properties p = getUTProperties();
final TimeSeriesWorkload wl = getWorkload(p, true);
Object threadState = wl.initThread(p, 0, 2);
MockDB db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
long timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAA"); // <-- key 1
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertTrue(((NumericByteIterator) db.values.get(i)
.get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT)).isFloatingPoint());
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
timestamp += 60;
}
}
threadState = wl.initThread(p, 1, 2);
db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAB"); // <-- key 2
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertNotNull(db.values.get(i).get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT));
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
timestamp += 60;
}
}
}
@Test
public void insertThreeKeysTwoThreads() throws Exception {
// To make sure the distribution doesn't miss any metrics
final Properties p = getUTProperties();
p.put(CoreWorkload.FIELD_COUNT_PROPERTY, "3");
final TimeSeriesWorkload wl = getWorkload(p, true);
Object threadState = wl.initThread(p, 0, 2);
MockDB db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
long timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAA");
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertTrue(((NumericByteIterator) db.values.get(i)
.get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT)).isFloatingPoint());
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
timestamp += 60;
}
}
threadState = wl.initThread(p, 1, 2);
db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
timestamp = 1451606400;
int metricCtr = 0;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertNotNull(db.values.get(i).get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT));
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
}
if (metricCtr++ > 1) {
assertEquals(db.keys.get(i), "AAAC");
if (metricCtr >= 4) {
metricCtr = 0;
timestamp += 60;
}
} else {
assertEquals(db.keys.get(i), "AAAB");
}
}
}
@Test
public void insertWithValidation() throws Exception {
final Properties p = getUTProperties();
p.put(CoreWorkload.FIELD_COUNT_PROPERTY, "1");
p.put(CoreWorkload.DATA_INTEGRITY_PROPERTY, "true");
p.put(TimeSeriesWorkload.VALUE_TYPE_PROPERTY, "integers");
final TimeSeriesWorkload wl = getWorkload(p, true);
final Object threadState = wl.initThread(p, 0, 1);
final MockDB db = new MockDB();
for (int i = 0; i < 74; i++) {
assertTrue(wl.doInsert(db, threadState));
}
assertEquals(db.keys.size(), 74);
assertEquals(db.values.size(), 74);
long timestamp = 1451606400;
for (int i = 0; i < db.keys.size(); i++) {
assertEquals(db.keys.get(i), "AAAA");
assertEquals(db.values.get(i).get("AA").toString(), "AAAA");
assertEquals(Utils.bytesToLong(db.values.get(i).get(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT).toArray()), timestamp);
assertFalse(((NumericByteIterator) db.values.get(i)
.get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT)).isFloatingPoint());
// validation check
final TreeMap<String, String> validationTags = new TreeMap<String, String>();
for (final Entry<String, ByteIterator> entry : db.values.get(i).entrySet()) {
if (entry.getKey().equals(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT) ||
entry.getKey().equals(TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT)) {
continue;
}
validationTags.put(entry.getKey(), entry.getValue().toString());
}
assertEquals(wl.validationFunction(db.keys.get(i), timestamp, validationTags),
((NumericByteIterator) db.values.get(i).get(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT)).getLong());
if (i % 2 == 0) {
assertEquals(db.values.get(i).get("AB").toString(), "AAAA");
} else {
assertEquals(db.values.get(i).get("AB").toString(), "AAAB");
timestamp += 60;
}
}
}
@Test
public void read() throws Exception {
final Properties p = getUTProperties();
final TimeSeriesWorkload wl = getWorkload(p, true);
final Object threadState = wl.initThread(p, 0, 1);
final MockDB db = new MockDB();
for (int i = 0; i < 20; i++) {
wl.doTransactionRead(db, threadState);
}
}
@Test
public void verifyRow() throws Exception {
final Properties p = getUTProperties();
final TimeSeriesWorkload wl = getWorkload(p, true);
final TreeMap<String, String> validationTags = new TreeMap<String, String>();
final HashMap<String, ByteIterator> cells = new HashMap<String, ByteIterator>();
validationTags.put("AA", "AAAA");
cells.put("AA", new StringByteIterator("AAAA"));
validationTags.put("AB", "AAAB");
cells.put("AB", new StringByteIterator("AAAB"));
long hash = wl.validationFunction("AAAA", 1451606400L, validationTags);
cells.put(TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT, new NumericByteIterator(1451606400L));
cells.put(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT, new NumericByteIterator(hash));
assertEquals(wl.verifyRow("AAAA", cells), Status.OK);
// tweak the last value a bit
for (final ByteIterator it : cells.values()) {
it.reset();
}
cells.put(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT, new NumericByteIterator(hash + 1));
assertEquals(wl.verifyRow("AAAA", cells), Status.UNEXPECTED_STATE);
// no value cell, returns an unexpected state
for (final ByteIterator it : cells.values()) {
it.reset();
}
cells.remove(TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT);
assertEquals(wl.verifyRow("AAAA", cells), Status.UNEXPECTED_STATE);
}
@Test
public void validateSettingsDataIntegrity() throws Exception {
Properties p = getUTProperties();
// data validation incompatibilities
p.setProperty(CoreWorkload.DATA_INTEGRITY_PROPERTY, "true");
try {
getWorkload(p, true);
fail("Expected WorkloadException");
} catch (WorkloadException e) { }
p.setProperty(TimeSeriesWorkload.VALUE_TYPE_PROPERTY, "integers"); // now it's ok
p.setProperty(TimeSeriesWorkload.GROUPBY_PROPERTY, "sum"); // now it's not
try {
getWorkload(p, true);
fail("Expected WorkloadException");
} catch (WorkloadException e) { }
p.setProperty(TimeSeriesWorkload.GROUPBY_PROPERTY, "");
p.setProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, "sum");
p.setProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, "60");
try {
getWorkload(p, true);
fail("Expected WorkloadException");
} catch (WorkloadException e) { }
p.setProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, "");
p.setProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, "");
p.setProperty(TimeSeriesWorkload.QUERY_TIMESPAN_PROPERTY, "60");
try {
getWorkload(p, true);
fail("Expected WorkloadException");
} catch (WorkloadException e) { }
p = getUTProperties();
p.setProperty(CoreWorkload.DATA_INTEGRITY_PROPERTY, "true");
p.setProperty(TimeSeriesWorkload.VALUE_TYPE_PROPERTY, "integers");
p.setProperty(TimeSeriesWorkload.RANDOMIZE_TIMESERIES_ORDER_PROPERTY, "true");
try {
getWorkload(p, true);
fail("Expected WorkloadException");
} catch (WorkloadException e) { }
p.setProperty(TimeSeriesWorkload.RANDOMIZE_TIMESERIES_ORDER_PROPERTY, "false");
p.setProperty(TimeSeriesWorkload.INSERT_START_PROPERTY, "");
try {
getWorkload(p, true);
fail("Expected WorkloadException");
} catch (WorkloadException e) { }
}
/** Helper method that generates unit testing defaults for the properties map */
private Properties getUTProperties() {
final Properties p = new Properties();
p.put(Client.RECORD_COUNT_PROPERTY, "10");
p.put(CoreWorkload.FIELD_COUNT_PROPERTY, "2");
p.put(CoreWorkload.FIELD_LENGTH_PROPERTY, "4");
p.put(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, "2");
p.put(TimeSeriesWorkload.TAG_VALUE_LENGTH_PROPERTY, "4");
p.put(TimeSeriesWorkload.TAG_COUNT_PROPERTY, "2");
p.put(TimeSeriesWorkload.TAG_CARDINALITY_PROPERTY, "1,2");
p.put(CoreWorkload.INSERT_START_PROPERTY, "1451606400");
p.put(TimeSeriesWorkload.DELAYED_SERIES_PROPERTY, "0");
p.put(TimeSeriesWorkload.RANDOMIZE_TIMESERIES_ORDER_PROPERTY, "false");
return p;
}
/** Helper to setup the workload for testing. */
private TimeSeriesWorkload getWorkload(final Properties p, final boolean init)
throws WorkloadException {
Measurements.setProperties(p);
if (!init) {
return new TimeSeriesWorkload();
} else {
final TimeSeriesWorkload workload = new TimeSeriesWorkload();
workload.init(p);
return workload;
}
}
static class MockDB extends DB {
final List<String> keys = new ArrayList<String>();
final List<Map<String, ByteIterator>> values =
new ArrayList<Map<String, ByteIterator>>();
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// TODO Auto-generated method stub
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
// TODO Auto-generated method stub
return Status.OK;
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
keys.add(key);
this.values.add(values);
return Status.OK;
}
@Override
public Status delete(String table, String key) {
// TODO Auto-generated method stub
return Status.OK;
}
public void dumpStdout() {
for (int i = 0; i < keys.size(); i++) {
System.out.print("[" + i + "] Key: " + keys.get(i) + " Values: {");
int x = 0;
for (final Entry<String, ByteIterator> entry : values.get(i).entrySet()) {
if (x++ > 0) {
System.out.print(", ");
}
System.out.print("{" + entry.getKey() + " => ");
if (entry.getKey().equals("YCSBV")) {
System.out.print(new String(Utils.bytesToDouble(entry.getValue().toArray()) + "}"));
} else if (entry.getKey().equals("YCSBTS")) {
System.out.print(new String(Utils.bytesToLong(entry.getValue().toArray()) + "}"));
} else {
System.out.print(new String(entry.getValue().toArray()) + "}");
}
}
System.out.println("}");
}
}
}
} | 21,195 | 35.734835 | 113 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/generator/TestUnixEpochTimestampGenerator.java | /**
* Copyright (c) 2016 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.generator;
import static org.testng.Assert.assertEquals;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
public class TestUnixEpochTimestampGenerator {
@Test
public void defaultCtor() throws Exception {
final UnixEpochTimestampGenerator generator =
new UnixEpochTimestampGenerator();
final long startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + 60);
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + 120);
assertEquals((long) generator.lastValue(), startTime + 60);
assertEquals((long) generator.nextValue(), startTime + 180);
}
@Test
public void ctorWithIntervalAndUnits() throws Exception {
final UnixEpochTimestampGenerator generator =
new UnixEpochTimestampGenerator(120, TimeUnit.SECONDS);
final long startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + 120);
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + 240);
assertEquals((long) generator.lastValue(), startTime + 120);
}
@Test
public void ctorWithIntervalAndUnitsAndStart() throws Exception {
final UnixEpochTimestampGenerator generator =
new UnixEpochTimestampGenerator(120, TimeUnit.SECONDS, 1072915200L);
assertEquals((long) generator.nextValue(), 1072915200L);
assertEquals((long) generator.lastValue(), 1072915200L - 120);
assertEquals((long) generator.nextValue(), 1072915200L + 120);
assertEquals((long) generator.lastValue(), 1072915200L);
}
@Test
public void variousIntervalsAndUnits() throws Exception {
// negatives could happen, just start and roll back in time
UnixEpochTimestampGenerator generator =
new UnixEpochTimestampGenerator(-60, TimeUnit.SECONDS);
long startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime - 60);
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime - 120);
assertEquals((long) generator.lastValue(), startTime - 60);
generator = new UnixEpochTimestampGenerator(100, TimeUnit.NANOSECONDS);
startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + 100);
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + 200);
assertEquals((long) generator.lastValue(), startTime + 100);
generator = new UnixEpochTimestampGenerator(100, TimeUnit.MICROSECONDS);
startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + 100);
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + 200);
assertEquals((long) generator.lastValue(), startTime + 100);
generator = new UnixEpochTimestampGenerator(100, TimeUnit.MILLISECONDS);
startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + 100);
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + 200);
assertEquals((long) generator.lastValue(), startTime + 100);
generator = new UnixEpochTimestampGenerator(100, TimeUnit.SECONDS);
startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + 100);
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + 200);
assertEquals((long) generator.lastValue(), startTime + 100);
generator = new UnixEpochTimestampGenerator(1, TimeUnit.MINUTES);
startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + (1 * 60));
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + (2 * 60));
assertEquals((long) generator.lastValue(), startTime + (1 * 60));
generator = new UnixEpochTimestampGenerator(1, TimeUnit.HOURS);
startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + (1 * 60 * 60));
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + (2 * 60 * 60));
assertEquals((long) generator.lastValue(), startTime + (1 * 60 * 60));
generator = new UnixEpochTimestampGenerator(1, TimeUnit.DAYS);
startTime = generator.currentValue();
assertEquals((long) generator.nextValue(), startTime + (1 * 60 * 60 * 24));
assertEquals((long) generator.lastValue(), startTime);
assertEquals((long) generator.nextValue(), startTime + (2 * 60 * 60 * 24));
assertEquals((long) generator.lastValue(), startTime + (1 * 60 * 60 * 24));
}
// TODO - With PowerMockito we could UT the initializeTimestamp(long) call.
// Otherwise it would involve creating more functions and that would get ugly.
}
| 7,813 | 62.528455 | 186 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/generator/TestZipfianGenerator.java | /**
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.generator;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertFalse;
public class TestZipfianGenerator {
@Test
public void testMinAndMaxParameter() {
long min = 5;
long max = 10;
ZipfianGenerator zipfian = new ZipfianGenerator(min, max);
for (int i = 0; i < 10000; i++) {
long rnd = zipfian.nextValue();
assertFalse(rnd < min);
assertFalse(rnd > max);
}
}
}
| 1,150 | 27.775 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/generator/AcknowledgedCounterGeneratorTest.java | /**
* Copyright (c) 2015-2017 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.generator;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.testng.annotations.Test;
/**
* Tests for the AcknowledgedCounterGenerator class.
*/
public class AcknowledgedCounterGeneratorTest {
/**
* Test that advancing past {@link Integer#MAX_VALUE} works.
*/
@Test
public void testIncrementPastIntegerMaxValue() {
final long toTry = AcknowledgedCounterGenerator.WINDOW_SIZE * 3;
AcknowledgedCounterGenerator generator =
new AcknowledgedCounterGenerator(Integer.MAX_VALUE - 1000);
Random rand = new Random(System.currentTimeMillis());
BlockingQueue<Long> pending = new ArrayBlockingQueue<Long>(1000);
for (long i = 0; i < toTry; ++i) {
long value = generator.nextValue();
while (!pending.offer(value)) {
Long first = pending.poll();
// Don't always advance by one.
if (rand.nextBoolean()) {
generator.acknowledge(first);
} else {
Long second = pending.poll();
pending.add(first);
generator.acknowledge(second);
}
}
}
}
}
| 1,835 | 28.612903 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/generator/TestIncrementingPrintableStringGenerator.java | /**
* Copyright (c) 2016 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.generator;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
import java.util.NoSuchElementException;
import org.testng.annotations.Test;
public class TestIncrementingPrintableStringGenerator {
private final static int[] ATOC = new int[] { 65, 66, 67 };
@Test
public void rolloverOK() throws Exception {
final IncrementingPrintableStringGenerator gen =
new IncrementingPrintableStringGenerator(2, ATOC);
assertNull(gen.lastValue());
assertEquals(gen.nextValue(), "AA");
assertEquals(gen.lastValue(), "AA");
assertEquals(gen.nextValue(), "AB");
assertEquals(gen.lastValue(), "AB");
assertEquals(gen.nextValue(), "AC");
assertEquals(gen.lastValue(), "AC");
assertEquals(gen.nextValue(), "BA");
assertEquals(gen.lastValue(), "BA");
assertEquals(gen.nextValue(), "BB");
assertEquals(gen.lastValue(), "BB");
assertEquals(gen.nextValue(), "BC");
assertEquals(gen.lastValue(), "BC");
assertEquals(gen.nextValue(), "CA");
assertEquals(gen.lastValue(), "CA");
assertEquals(gen.nextValue(), "CB");
assertEquals(gen.lastValue(), "CB");
assertEquals(gen.nextValue(), "CC");
assertEquals(gen.lastValue(), "CC");
assertEquals(gen.nextValue(), "AA"); // <-- rollover
assertEquals(gen.lastValue(), "AA");
}
@Test
public void rolloverOneCharacterOK() throws Exception {
// It would be silly to create a generator with one character.
final IncrementingPrintableStringGenerator gen =
new IncrementingPrintableStringGenerator(2, new int[] { 65 });
for (int i = 0; i < 5; i++) {
assertEquals(gen.nextValue(), "AA");
}
}
@Test
public void rolloverException() throws Exception {
final IncrementingPrintableStringGenerator gen =
new IncrementingPrintableStringGenerator(2, ATOC);
gen.setThrowExceptionOnRollover(true);
int i = 0;
try {
while(i < 11) {
++i;
gen.nextValue();
}
fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
assertEquals(i, 10);
}
}
@Test
public void rolloverOneCharacterException() throws Exception {
// It would be silly to create a generator with one character.
final IncrementingPrintableStringGenerator gen =
new IncrementingPrintableStringGenerator(2, new int[] { 65 });
gen.setThrowExceptionOnRollover(true);
int i = 0;
try {
while(i < 3) {
++i;
gen.nextValue();
}
fail("Expected NoSuchElementException");
} catch (NoSuchElementException e) {
assertEquals(i, 2);
}
}
@Test
public void invalidLengths() throws Exception {
try {
new IncrementingPrintableStringGenerator(0, ATOC);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
try {
new IncrementingPrintableStringGenerator(-42, ATOC);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
}
@Test
public void invalidCharacterSets() throws Exception {
try {
new IncrementingPrintableStringGenerator(2, null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
try {
new IncrementingPrintableStringGenerator(2, new int[] {});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) { }
}
}
| 4,188 | 30.977099 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/test/java/site/ycsb/generator/TestRandomDiscreteTimestampGenerator.java | /**
* Copyright (c) 2017 YCSB contributors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb.generator;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
public class TestRandomDiscreteTimestampGenerator {
@Test
public void systemTime() throws Exception {
final RandomDiscreteTimestampGenerator generator =
new RandomDiscreteTimestampGenerator(60, TimeUnit.SECONDS, 60);
List<Long> generated = Lists.newArrayList();
for (int i = 0; i < 60; i++) {
generated.add(generator.nextValue());
}
assertEquals(generated.size(), 60);
try {
generator.nextValue();
fail("Expected IllegalStateException");
} catch (IllegalStateException e) { }
}
@Test
public void withStartTime() throws Exception {
final RandomDiscreteTimestampGenerator generator =
new RandomDiscreteTimestampGenerator(60, TimeUnit.SECONDS, 1072915200L, 60);
List<Long> generated = Lists.newArrayList();
for (int i = 0; i < 60; i++) {
generated.add(generator.nextValue());
}
assertEquals(generated.size(), 60);
Collections.sort(generated);
long ts = 1072915200L - 60; // starts 1 interval in the past
for (final long t : generated) {
assertEquals(t, ts);
ts += 60;
}
try {
generator.nextValue();
fail("Expected IllegalStateException");
} catch (IllegalStateException e) { }
}
@Test (expectedExceptions = IllegalArgumentException.class)
public void tooLarge() throws Exception {
new RandomDiscreteTimestampGenerator(60, TimeUnit.SECONDS,
RandomDiscreteTimestampGenerator.MAX_INTERVALS + 1);
}
//TODO - With PowerMockito we could UT the initializeTimestamp(long) call.
// Otherwise it would involve creating more functions and that would get ugly.
}
| 2,582 | 32.986842 | 84 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/UnknownDBException.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
/**
* Could not create the specified DB.
*/
public class UnknownDBException extends Exception {
/**
*
*/
private static final long serialVersionUID = 459099842269616836L;
public UnknownDBException(String message) {
super(message);
}
public UnknownDBException() {
super();
}
public UnknownDBException(String message, Throwable cause) {
super(message, cause);
}
public UnknownDBException(Throwable cause) {
super(cause);
}
}
| 1,185 | 24.782609 | 83 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/DBFactory.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import org.apache.htrace.core.Tracer;
import java.util.Properties;
/**
* Creates a DB layer by dynamically classloading the specified DB class.
*/
public final class DBFactory {
private DBFactory() {
// not used
}
public static DB newDB(String dbname, Properties properties, final Tracer tracer) throws UnknownDBException {
ClassLoader classLoader = DBFactory.class.getClassLoader();
DB ret;
try {
Class dbclass = classLoader.loadClass(dbname);
ret = (DB) dbclass.newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
ret.setProperties(properties);
return new DBWrapper(ret, tracer);
}
}
| 1,397 | 25.884615 | 111 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/TerminatorThread.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import java.util.Collection;
/**
* A thread that waits for the maximum specified time and then interrupts all the client
* threads passed at initialization of this thread.
*
* The maximum execution time passed is assumed to be in seconds.
*
*/
public class TerminatorThread extends Thread {
private final Collection<? extends Thread> threads;
private long maxExecutionTime;
private Workload workload;
private long waitTimeOutInMS;
public TerminatorThread(long maxExecutionTime, Collection<? extends Thread> threads,
Workload workload) {
this.maxExecutionTime = maxExecutionTime;
this.threads = threads;
this.workload = workload;
waitTimeOutInMS = 2000;
System.err.println("Maximum execution time specified as: " + maxExecutionTime + " secs");
}
public void run() {
try {
Thread.sleep(maxExecutionTime * 1000);
} catch (InterruptedException e) {
System.err.println("Could not wait until max specified time, TerminatorThread interrupted.");
return;
}
System.err.println("Maximum time elapsed. Requesting stop for the workload.");
workload.requestStop();
System.err.println("Stop requested for workload. Now Joining!");
for (Thread t : threads) {
while (t.isAlive()) {
try {
t.join(waitTimeOutInMS);
if (t.isAlive()) {
System.out.println("Still waiting for thread " + t.getName() + " to complete. " +
"Workload status: " + workload.isStopRequested());
}
} catch (InterruptedException e) {
// Do nothing. Don't know why I was interrupted.
}
}
}
}
}
| 2,383 | 33.550725 | 99 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/package-info.java | /*
* Copyright (c) 2015 - 2017 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
/**
* The YCSB core package.
*/
package site.ycsb;
| 719 | 30.304348 | 70 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/ByteArrayByteIterator.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
/**
* A ByteIterator that iterates through a byte array.
*/
public class ByteArrayByteIterator extends ByteIterator {
private final int originalOffset;
private final byte[] str;
private int off;
private final int len;
public ByteArrayByteIterator(byte[] s) {
this.str = s;
this.off = 0;
this.len = s.length;
originalOffset = 0;
}
public ByteArrayByteIterator(byte[] s, int off, int len) {
this.str = s;
this.off = off;
this.len = off + len;
originalOffset = off;
}
@Override
public boolean hasNext() {
return off < len;
}
@Override
public byte nextByte() {
byte ret = str[off];
off++;
return ret;
}
@Override
public long bytesLeft() {
return len - off;
}
@Override
public void reset() {
off = originalOffset;
}
@Override
public byte[] toArray() {
int size = (int) bytesLeft();
byte[] bytes = new byte[size];
System.arraycopy(str, off, bytes, 0, size);
off = len;
return bytes;
}
}
| 1,726 | 22.337838 | 83 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/GoodBadUglyDB.java | /**
* Copyright (c) 2010 Yahoo! Inc. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
/**
* Basic DB that just prints out the requested operations, instead of doing them against a database.
*/
public class GoodBadUglyDB extends DB {
public static final String SIMULATE_DELAY = "gbudb.delays";
public static final String SIMULATE_DELAY_DEFAULT = "200,1000,10000,50000,100000";
private static final ReadWriteLock DB_ACCESS = new ReentrantReadWriteLock();
private long[] delays;
public GoodBadUglyDB() {
delays = new long[]{200, 1000, 10000, 50000, 200000};
}
private void delay() {
final Random random = ThreadLocalRandom.current();
double p = random.nextDouble();
int mod;
if (p < 0.9) {
mod = 0;
} else if (p < 0.99) {
mod = 1;
} else if (p < 0.9999) {
mod = 2;
} else {
mod = 3;
}
// this will make mod 3 pauses global
Lock lock = mod == 3 ? DB_ACCESS.writeLock() : DB_ACCESS.readLock();
if (mod == 3) {
System.out.println("OUCH");
}
lock.lock();
try {
final long baseDelayNs = MICROSECONDS.toNanos(delays[mod]);
final int delayRangeNs = (int) (MICROSECONDS.toNanos(delays[mod + 1]) - baseDelayNs);
final long delayNs = baseDelayNs + random.nextInt(delayRangeNs);
final long deadline = System.nanoTime() + delayNs;
do {
LockSupport.parkNanos(deadline - System.nanoTime());
} while (System.nanoTime() < deadline && !Thread.interrupted());
} finally {
lock.unlock();
}
}
/**
* Initialize any state for this DB. Called once per DB instance; there is one DB instance per client thread.
*/
public void init() {
int i = 0;
for (String delay : getProperties().getProperty(SIMULATE_DELAY, SIMULATE_DELAY_DEFAULT).split(",")) {
delays[i++] = Long.parseLong(delay);
}
}
/**
* Read a record from the database. Each field/value pair from the result will be stored in a HashMap.
*
* @param table The name of the table
* @param key The record key of the record to read.
* @param fields The list of fields to read, or null for all of them
* @param result A HashMap of field/value pairs for the result
* @return Zero on success, a non-zero error code on error
*/
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
delay();
return Status.OK;
}
/**
* Perform a range scan for a set of records in the database. Each field/value pair from the result will be stored
* in a HashMap.
*
* @param table The name of the table
* @param startkey The record key of the first record to read.
* @param recordcount The number of records to read
* @param fields The list of fields to read, or null for all of them
* @param result A Vector of HashMaps, where each HashMap is a set field/value pairs for one record
* @return Zero on success, a non-zero error code on error
*/
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
delay();
return Status.OK;
}
/**
* Update a record in the database. Any field/value pairs in the specified values HashMap will be written into the
* record with the specified record key, overwriting any existing values with the same field name.
*
* @param table The name of the table
* @param key The record key of the record to write.
* @param values A HashMap of field/value pairs to update in the record
* @return Zero on success, a non-zero error code on error
*/
public Status update(String table, String key, Map<String, ByteIterator> values) {
delay();
return Status.OK;
}
/**
* Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the
* record with the specified record key.
*
* @param table The name of the table
* @param key The record key of the record to insert.
* @param values A HashMap of field/value pairs to insert in the record
* @return Zero on success, a non-zero error code on error
*/
public Status insert(String table, String key, Map<String, ByteIterator> values) {
delay();
return Status.OK;
}
/**
* Delete a record from the database.
*
* @param table The name of the table
* @param key The record key of the record to delete.
* @return Zero on success, a non-zero error code on error
*/
public Status delete(String table, String key) {
delay();
return Status.OK;
}
}
| 5,612 | 33.648148 | 116 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/NumericByteIterator.java | /**
* Copyright (c) 2017 YCSB contributors. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
/**
* A byte iterator that handles encoding and decoding numeric values.
* Currently this iterator can handle 64 bit signed values and double precision
* floating point values.
*/
public class NumericByteIterator extends ByteIterator {
private final byte[] payload;
private final boolean floatingPoint;
private int off;
public NumericByteIterator(final long value) {
floatingPoint = false;
payload = Utils.longToBytes(value);
off = 0;
}
public NumericByteIterator(final double value) {
floatingPoint = true;
payload = Utils.doubleToBytes(value);
off = 0;
}
@Override
public boolean hasNext() {
return off < payload.length;
}
@Override
public byte nextByte() {
return payload[off++];
}
@Override
public long bytesLeft() {
return payload.length - off;
}
@Override
public void reset() {
off = 0;
}
public long getLong() {
if (floatingPoint) {
throw new IllegalStateException("Byte iterator is of the type double");
}
return Utils.bytesToLong(payload);
}
public double getDouble() {
if (!floatingPoint) {
throw new IllegalStateException("Byte iterator is of the type long");
}
return Utils.bytesToDouble(payload);
}
public boolean isFloatingPoint() {
return floatingPoint;
}
} | 2,002 | 24.35443 | 79 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/Status.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
/**
* The result of an operation.
*/
public class Status {
private final String name;
private final String description;
/**
* @param name A short name for the status.
* @param description A description of the status.
*/
public Status(String name, String description) {
super();
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Status [name=" + name + ", description=" + description + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Status other = (Status) obj;
if (description == null) {
if (other.description != null) {
return false;
}
} else if (!description.equals(other.description)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
/**
* Is {@code this} a passing state for the operation: {@link Status#OK} or {@link Status#BATCHED_OK}.
* @return true if the operation is successful, false otherwise
*/
public boolean isOk() {
return this == OK || this == BATCHED_OK;
}
public static final Status OK = new Status("OK", "The operation completed successfully.");
public static final Status ERROR = new Status("ERROR", "The operation failed.");
public static final Status NOT_FOUND = new Status("NOT_FOUND", "The requested record was not found.");
public static final Status NOT_IMPLEMENTED = new Status("NOT_IMPLEMENTED", "The operation is not " +
"implemented for the current binding.");
public static final Status UNEXPECTED_STATE = new Status("UNEXPECTED_STATE", "The operation reported" +
" success, but the result was not as expected.");
public static final Status BAD_REQUEST = new Status("BAD_REQUEST", "The request was not valid.");
public static final Status FORBIDDEN = new Status("FORBIDDEN", "The operation is forbidden.");
public static final Status SERVICE_UNAVAILABLE = new Status("SERVICE_UNAVAILABLE", "Dependant " +
"service for the current binding is not available.");
public static final Status BATCHED_OK = new Status("BATCHED_OK", "The operation has been batched by " +
"the binding to be executed later.");
}
| 3,541 | 30.90991 | 105 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/ByteIterator.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Iterator;
/**
* YCSB-specific buffer class. ByteIterators are designed to support
* efficient field generation, and to allow backend drivers that can stream
* fields (instead of materializing them in RAM) to do so.
* <p>
* YCSB originially used String objects to represent field values. This led to
* two performance issues.
* </p><p>
* First, it leads to unnecessary conversions between UTF-16 and UTF-8, both
* during field generation, and when passing data to byte-based backend
* drivers.
* </p><p>
* Second, Java strings are represented internally using UTF-16, and are
* built by appending to a growable array type (StringBuilder or
* StringBuffer), then calling a toString() method. This leads to a 4x memory
* overhead as field values are being built, which prevented YCSB from
* driving large object stores.
* </p>
* The StringByteIterator class contains a number of convenience methods for
* backend drivers that convert between Map<String,String> and
* Map<String,ByteBuffer>.
*
*/
public abstract class ByteIterator implements Iterator<Byte> {
@Override
public abstract boolean hasNext();
@Override
public Byte next() {
throw new UnsupportedOperationException();
}
public abstract byte nextByte();
/** @return byte offset immediately after the last valid byte */
public int nextBuf(byte[] buf, int bufOff) {
int sz = bufOff;
while (sz < buf.length && hasNext()) {
buf[sz] = nextByte();
sz++;
}
return sz;
}
public abstract long bytesLeft();
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/** Resets the iterator so that it can be consumed again. Not all
* implementations support this call.
* @throws UnsupportedOperationException if the implementation hasn't implemented
* the method.
*/
public void reset() {
throw new UnsupportedOperationException();
}
/** Consumes remaining contents of this object, and returns them as a string. */
public String toString() {
Charset cset = Charset.forName("UTF-8");
CharBuffer cb = cset.decode(ByteBuffer.wrap(this.toArray()));
return cb.toString();
}
/** Consumes remaining contents of this object, and returns them as a byte array. */
public byte[] toArray() {
long left = bytesLeft();
if (left != (int) left) {
throw new ArrayIndexOutOfBoundsException("Too much data to fit in one array!");
}
byte[] ret = new byte[(int) left];
for (int i = 0; i < ret.length; i++) {
ret[i] = nextByte();
}
return ret;
}
}
| 3,407 | 31.150943 | 86 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/Utils.java | /**
* Copyright (c) 2010 Yahoo! Inc., 2016 YCSB contributors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
/**
* Utility functions.
*/
public final class Utils {
private Utils() {
// not used
}
/**
* Hash an integer value.
*/
public static long hash(long val) {
return fnvhash64(val);
}
public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L;
public static final long FNV_PRIME_64 = 1099511628211L;
/**
* 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode().
*
* @param val The value to hash.
* @return The hash value
*/
public static long fnvhash64(long val) {
//from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash
long hashval = FNV_OFFSET_BASIS_64;
for (int i = 0; i < 8; i++) {
long octet = val & 0x00ff;
val = val >> 8;
hashval = hashval ^ octet;
hashval = hashval * FNV_PRIME_64;
//hashval = hashval ^ octet;
}
return Math.abs(hashval);
}
/**
* Reads a big-endian 8-byte long from an offset in the given array.
* @param bytes The array to read from.
* @return A long integer.
* @throws IndexOutOfBoundsException if the byte array is too small.
* @throws NullPointerException if the byte array is null.
*/
public static long bytesToLong(final byte[] bytes) {
return (bytes[0] & 0xFFL) << 56
| (bytes[1] & 0xFFL) << 48
| (bytes[2] & 0xFFL) << 40
| (bytes[3] & 0xFFL) << 32
| (bytes[4] & 0xFFL) << 24
| (bytes[5] & 0xFFL) << 16
| (bytes[6] & 0xFFL) << 8
| (bytes[7] & 0xFFL) << 0;
}
/**
* Writes a big-endian 8-byte long at an offset in the given array.
* @param val The value to encode.
* @throws IndexOutOfBoundsException if the byte array is too small.
*/
public static byte[] longToBytes(final long val) {
final byte[] bytes = new byte[8];
bytes[0] = (byte) (val >>> 56);
bytes[1] = (byte) (val >>> 48);
bytes[2] = (byte) (val >>> 40);
bytes[3] = (byte) (val >>> 32);
bytes[4] = (byte) (val >>> 24);
bytes[5] = (byte) (val >>> 16);
bytes[6] = (byte) (val >>> 8);
bytes[7] = (byte) (val >>> 0);
return bytes;
}
/**
* Parses the byte array into a double.
* The byte array must be at least 8 bytes long and have been encoded using
* {@link #doubleToBytes}. If the array is longer than 8 bytes, only the
* first 8 bytes are parsed.
* @param bytes The byte array to parse, at least 8 bytes.
* @return A double value read from the byte array.
* @throws IllegalArgumentException if the byte array is not 8 bytes wide.
*/
public static double bytesToDouble(final byte[] bytes) {
if (bytes.length < 8) {
throw new IllegalArgumentException("Byte array must be 8 bytes wide.");
}
return Double.longBitsToDouble(bytesToLong(bytes));
}
/**
* Encodes the double value as an 8 byte array.
* @param val The double value to encode.
* @return A byte array of length 8.
*/
public static byte[] doubleToBytes(final double val) {
return longToBytes(Double.doubleToRawLongBits(val));
}
/**
* Measure the estimated active thread count in the current thread group.
* Since this calls {@link Thread.activeCount} it should be called from the
* main thread or one started by the main thread. Threads included in the
* count can be in any state.
* For a more accurate count we could use {@link Thread.getAllStackTraces().size()}
* but that freezes the JVM and incurs a high overhead.
* @return An estimated thread count, good for showing the thread count
* over time.
*/
public static int getActiveThreadCount() {
return Thread.activeCount();
}
/** @return The currently used memory in bytes */
public static long getUsedMemoryBytes() {
final Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
/** @return The currently used memory in megabytes. */
public static int getUsedMemoryMegaBytes() {
return (int) (getUsedMemoryBytes() / 1024 / 1024);
}
/** @return The current system load average if supported by the JDK.
* If it's not supported, the value will be negative. */
public static double getSystemLoadAverage() {
final OperatingSystemMXBean osBean =
ManagementFactory.getOperatingSystemMXBean();
return osBean.getSystemLoadAverage();
}
/** @return The total number of garbage collections executed for all
* memory pools. */
public static long getGCTotalCollectionCount() {
final List<GarbageCollectorMXBean> gcBeans =
ManagementFactory.getGarbageCollectorMXBeans();
long count = 0;
for (final GarbageCollectorMXBean bean : gcBeans) {
if (bean.getCollectionCount() < 0) {
continue;
}
count += bean.getCollectionCount();
}
return count;
}
/** @return The total time, in milliseconds, spent in GC. */
public static long getGCTotalTime() {
final List<GarbageCollectorMXBean> gcBeans =
ManagementFactory.getGarbageCollectorMXBeans();
long time = 0;
for (final GarbageCollectorMXBean bean : gcBeans) {
if (bean.getCollectionTime() < 0) {
continue;
}
time += bean.getCollectionTime();
}
return time;
}
/**
* Returns a map of garbage collectors and their stats.
* The first object in the array is the total count since JVM start and the
* second is the total time (ms) since JVM start.
* If a garbage collectors does not support the collector MXBean, then it
* will not be represented in the map.
* @return A non-null map of garbage collectors and their metrics. The map
* may be empty.
*/
public static Map<String, Long[]> getGCStatst() {
final List<GarbageCollectorMXBean> gcBeans =
ManagementFactory.getGarbageCollectorMXBeans();
final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size());
for (final GarbageCollectorMXBean bean : gcBeans) {
if (!bean.isValid() || bean.getCollectionCount() < 0 ||
bean.getCollectionTime() < 0) {
continue;
}
final Long[] measurements = new Long[]{
bean.getCollectionCount(),
bean.getCollectionTime()
};
map.put(bean.getName().replace(" ", "_"), measurements);
}
return map;
}
/**
* Simple Fisher-Yates array shuffle to randomize discrete sets.
* @param array The array to randomly shuffle.
* @return The shuffled array.
*/
public static <T> T [] shuffleArray(final T[] array) {
for (int i = array.length -1; i > 0; i--) {
final int idx = ThreadLocalRandom.current().nextInt(i + 1);
final T temp = array[idx];
array[idx] = array[i];
array[i] = temp;
}
return array;
}
}
| 7,671 | 31.927039 | 85 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/Workload.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.Properties;
/**
* One experiment scenario. One object of this type will
* be instantiated and shared among all client threads. This class
* should be constructed using a no-argument constructor, so we can
* load it dynamically. Any argument-based initialization should be
* done by init().
*
* If you extend this class, you should support the "insertstart" property. This
* allows the Client to proceed from multiple clients on different machines, in case
* the client is the bottleneck. For example, if we want to load 1 million records from
* 2 machines, the first machine should have insertstart=0 and the second insertstart=500000. Additionally,
* the "insertcount" property, which is interpreted by Client, can be used to tell each instance of the
* client how many inserts to do. In the example above, both clients should have insertcount=500000.
*/
public abstract class Workload {
public static final String INSERT_START_PROPERTY = "insertstart";
public static final String INSERT_COUNT_PROPERTY = "insertcount";
public static final String INSERT_START_PROPERTY_DEFAULT = "0";
private volatile AtomicBoolean stopRequested = new AtomicBoolean(false);
/** Operations available for a database. */
public enum Operation {
READ,
UPDATE,
INSERT,
SCAN,
DELETE
}
/**
* Initialize the scenario. Create any generators and other shared objects here.
* Called once, in the main client thread, before any operations are started.
*/
public void init(Properties p) throws WorkloadException {
}
/**
* Initialize any state for a particular client thread. Since the scenario object
* will be shared among all threads, this is the place to create any state that is specific
* to one thread. To be clear, this means the returned object should be created anew on each
* call to initThread(); do not return the same object multiple times.
* The returned object will be passed to invocations of doInsert() and doTransaction()
* for this thread. There should be no side effects from this call; all state should be encapsulated
* in the returned object. If you have no state to retain for this thread, return null. (But if you have
* no state to retain for this thread, probably you don't need to override initThread().)
*
* @return false if the workload knows it is done for this thread. Client will terminate the thread.
* Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read
* traces from a file, return true when there are more to do, false when you are done.
*/
public Object initThread(Properties p, int mythreadid, int threadcount) throws WorkloadException {
return null;
}
/**
* Cleanup the scenario. Called once, in the main client thread, after all operations have completed.
*/
public void cleanup() throws WorkloadException {
}
/**
* Do one insert operation. Because it will be called concurrently from multiple client threads, this
* function must be thread safe. However, avoid synchronized, or the threads will block waiting for each
* other, and it will be difficult to reach the target throughput. Ideally, this function would have no side
* effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be
* synchronized, since each thread has its own threadstate instance.
*/
public abstract boolean doInsert(DB db, Object threadstate);
/**
* Do one transaction operation. Because it will be called concurrently from multiple client threads, this
* function must be thread safe. However, avoid synchronized, or the threads will block waiting for each
* other, and it will be difficult to reach the target throughput. Ideally, this function would have no side
* effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be
* synchronized, since each thread has its own threadstate instance.
*
* @return false if the workload knows it is done for this thread. Client will terminate the thread.
* Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read
* traces from a file, return true when there are more to do, false when you are done.
*/
public abstract boolean doTransaction(DB db, Object threadstate);
/**
* Allows scheduling a request to stop the workload.
*/
public void requestStop() {
stopRequested.set(true);
}
/**
* Check the status of the stop request flag.
* @return true if stop was requested, false otherwise.
*/
public boolean isStopRequested() {
return stopRequested.get();
}
}
| 5,488 | 43.626016 | 110 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/StatusThread.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import site.ycsb.measurements.Measurements;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* A thread to periodically show the status of the experiment to reassure you that progress is being made.
*/
public class StatusThread extends Thread {
// Counts down each of the clients completing
private final CountDownLatch completeLatch;
// Stores the measurements for the run
private final Measurements measurements;
// Whether or not to track the JVM stats per run
private final boolean trackJVMStats;
// The clients that are running.
private final List<ClientThread> clients;
private final String label;
private final boolean standardstatus;
// The interval for reporting status.
private long sleeptimeNs;
// JVM max/mins
private int maxThreads;
private int minThreads = Integer.MAX_VALUE;
private long maxUsedMem;
private long minUsedMem = Long.MAX_VALUE;
private double maxLoadAvg;
private double minLoadAvg = Double.MAX_VALUE;
private long lastGCCount = 0;
private long lastGCTime = 0;
/**
* Creates a new StatusThread without JVM stat tracking.
*
* @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()}
* as they complete.
* @param clients The clients to collect metrics from.
* @param label The label for the status.
* @param standardstatus If true the status is printed to stdout in addition to stderr.
* @param statusIntervalSeconds The number of seconds between status updates.
*/
public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients,
String label, boolean standardstatus, int statusIntervalSeconds) {
this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false);
}
/**
* Creates a new StatusThread.
*
* @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()}
* as they complete.
* @param clients The clients to collect metrics from.
* @param label The label for the status.
* @param standardstatus If true the status is printed to stdout in addition to stderr.
* @param statusIntervalSeconds The number of seconds between status updates.
* @param trackJVMStats Whether or not to track JVM stats.
*/
public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients,
String label, boolean standardstatus, int statusIntervalSeconds,
boolean trackJVMStats) {
this.completeLatch = completeLatch;
this.clients = clients;
this.label = label;
this.standardstatus = standardstatus;
sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds);
measurements = Measurements.getMeasurements();
this.trackJVMStats = trackJVMStats;
}
/**
* Run and periodically report status.
*/
@Override
public void run() {
final long startTimeMs = System.currentTimeMillis();
final long startTimeNanos = System.nanoTime();
long deadline = startTimeNanos + sleeptimeNs;
long startIntervalMs = startTimeMs;
long lastTotalOps = 0;
boolean alldone;
do {
long nowMs = System.currentTimeMillis();
lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps);
if (trackJVMStats) {
measureJVM();
}
alldone = waitForClientsUntil(deadline);
startIntervalMs = nowMs;
deadline += sleeptimeNs;
}
while (!alldone);
if (trackJVMStats) {
measureJVM();
}
// Print the final stats.
computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps);
}
/**
* Computes and prints the stats.
*
* @param startTimeMs The start time of the test.
* @param startIntervalMs The start time of this interval.
* @param endIntervalMs The end time (now) for the interval.
* @param lastTotalOps The last total operations count.
* @return The current operation count.
*/
private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs,
long lastTotalOps) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
long totalops = 0;
long todoops = 0;
// Calculate the total number of operations completed.
for (ClientThread t : clients) {
totalops += t.getOpsDone();
todoops += t.getOpsTodo();
}
long interval = endIntervalMs - startTimeMs;
double throughput = 1000.0 * (((double) totalops) / (double) interval);
double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) /
((double) (endIntervalMs - startIntervalMs)));
long estremaining = (long) Math.ceil(todoops / throughput);
DecimalFormat d = new DecimalFormat("#.##");
String labelString = this.label + format.format(new Date());
StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: ");
msg.append(totalops).append(" operations; ");
if (totalops != 0) {
msg.append(d.format(curthroughput)).append(" current ops/sec; ");
}
if (todoops != 0) {
msg.append("est completion in ").append(RemainingFormatter.format(estremaining));
}
msg.append(Measurements.getMeasurements().getSummary());
System.err.println(msg);
if (standardstatus) {
System.out.println(msg);
}
return totalops;
}
/**
* Waits for all of the client to finish or the deadline to expire.
*
* @param deadline The current deadline.
* @return True if all of the clients completed.
*/
private boolean waitForClientsUntil(long deadline) {
boolean alldone = false;
long now = System.nanoTime();
while (!alldone && now < deadline) {
try {
alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS);
} catch (InterruptedException ie) {
// If we are interrupted the thread is being asked to shutdown.
// Return true to indicate that and reset the interrupt state
// of the thread.
Thread.currentThread().interrupt();
alldone = true;
}
now = System.nanoTime();
}
return alldone;
}
/**
* Executes the JVM measurements.
*/
private void measureJVM() {
final int threads = Utils.getActiveThreadCount();
if (threads < minThreads) {
minThreads = threads;
}
if (threads > maxThreads) {
maxThreads = threads;
}
measurements.measure("THREAD_COUNT", threads);
// TODO - once measurements allow for other number types, switch to using
// the raw bytes. Otherwise we can track in MB to avoid negative values
// when faced with huge heaps.
final int usedMem = Utils.getUsedMemoryMegaBytes();
if (usedMem < minUsedMem) {
minUsedMem = usedMem;
}
if (usedMem > maxUsedMem) {
maxUsedMem = usedMem;
}
measurements.measure("USED_MEM_MB", usedMem);
// Some JVMs may not implement this feature so if the value is less than
// zero, just ommit it.
final double systemLoad = Utils.getSystemLoadAverage();
if (systemLoad >= 0) {
// TODO - store the double if measurements allows for them
measurements.measure("SYS_LOAD_AVG", (int) systemLoad);
if (systemLoad > maxLoadAvg) {
maxLoadAvg = systemLoad;
}
if (systemLoad < minLoadAvg) {
minLoadAvg = systemLoad;
}
}
final long gcs = Utils.getGCTotalCollectionCount();
measurements.measure("GCS", (int) (gcs - lastGCCount));
final long gcTime = Utils.getGCTotalTime();
measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime));
lastGCCount = gcs;
lastGCTime = gcTime;
}
/**
* @return The maximum threads running during the test.
*/
public int getMaxThreads() {
return maxThreads;
}
/**
* @return The minimum threads running during the test.
*/
public int getMinThreads() {
return minThreads;
}
/**
* @return The maximum memory used during the test.
*/
public long getMaxUsedMem() {
return maxUsedMem;
}
/**
* @return The minimum memory used during the test.
*/
public long getMinUsedMem() {
return minUsedMem;
}
/**
* @return The maximum load average during the test.
*/
public double getMaxLoadAvg() {
return maxLoadAvg;
}
/**
* @return The minimum load average during the test.
*/
public double getMinLoadAvg() {
return minLoadAvg;
}
/**
* @return Whether or not the thread is tracking JVM stats.
*/
public boolean trackJVMStats() {
return trackJVMStats;
}
}
| 9,635 | 30.184466 | 108 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/BasicTSDB.java | /**
* Copyright (c) 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import site.ycsb.workloads.TimeSeriesWorkload;
/**
* Basic DB for printing out time series workloads and/or tracking the distribution
* of keys and fields.
*/
public class BasicTSDB extends BasicDB {
/** Time series workload specific counters. */
protected static Map<Long, Integer> timestamps;
protected static Map<Integer, Integer> floats;
protected static Map<Integer, Integer> integers;
private String timestampKey;
private String valueKey;
private String tagPairDelimiter;
private String queryTimeSpanDelimiter;
private long lastTimestamp;
@Override
public void init() {
super.init();
synchronized (MUTEX) {
if (timestamps == null) {
timestamps = new HashMap<Long, Integer>();
floats = new HashMap<Integer, Integer>();
integers = new HashMap<Integer, Integer>();
}
}
timestampKey = getProperties().getProperty(
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY,
TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT);
valueKey = getProperties().getProperty(
TimeSeriesWorkload.VALUE_KEY_PROPERTY,
TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT);
tagPairDelimiter = getProperties().getProperty(
TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY,
TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT);
queryTimeSpanDelimiter = getProperties().getProperty(
TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY,
TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT);
}
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
delay();
if (verbose) {
StringBuilder sb = getStringBuilder();
sb.append("READ ").append(table).append(" ").append(key).append(" [ ");
if (fields != null) {
for (String f : fields) {
sb.append(f).append(" ");
}
} else {
sb.append("<all fields>");
}
sb.append("]");
System.out.println(sb);
}
if (count) {
Set<String> filtered = null;
if (fields != null) {
filtered = new HashSet<String>();
for (final String field : fields) {
if (field.startsWith(timestampKey)) {
String[] parts = field.split(tagPairDelimiter);
if (parts[1].contains(queryTimeSpanDelimiter)) {
parts = parts[1].split(queryTimeSpanDelimiter);
lastTimestamp = Long.parseLong(parts[0]);
} else {
lastTimestamp = Long.parseLong(parts[1]);
}
synchronized(timestamps) {
Integer ctr = timestamps.get(lastTimestamp);
if (ctr == null) {
timestamps.put(lastTimestamp, 1);
} else {
timestamps.put(lastTimestamp, ctr + 1);
}
}
} else {
filtered.add(field);
}
}
}
incCounter(reads, hash(table, key, filtered));
}
return Status.OK;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
delay();
boolean isFloat = false;
if (verbose) {
StringBuilder sb = getStringBuilder();
sb.append("UPDATE ").append(table).append(" ").append(key).append(" [ ");
if (values != null) {
final TreeMap<String, ByteIterator> tree = new TreeMap<String, ByteIterator>(values);
for (Map.Entry<String, ByteIterator> entry : tree.entrySet()) {
if (entry.getKey().equals(timestampKey)) {
sb.append(entry.getKey()).append("=")
.append(Utils.bytesToLong(entry.getValue().toArray())).append(" ");
} else if (entry.getKey().equals(valueKey)) {
final NumericByteIterator it = (NumericByteIterator) entry.getValue();
isFloat = it.isFloatingPoint();
sb.append(entry.getKey()).append("=")
.append(isFloat ? it.getDouble() : it.getLong()).append(" ");
} else {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append(" ");
}
}
}
sb.append("]");
System.out.println(sb);
}
if (count) {
if (!verbose) {
isFloat = ((NumericByteIterator) values.get(valueKey)).isFloatingPoint();
}
int hash = hash(table, key, values);
incCounter(updates, hash);
synchronized(timestamps) {
Integer ctr = timestamps.get(lastTimestamp);
if (ctr == null) {
timestamps.put(lastTimestamp, 1);
} else {
timestamps.put(lastTimestamp, ctr + 1);
}
}
if (isFloat) {
incCounter(floats, hash);
} else {
incCounter(integers, hash);
}
}
return Status.OK;
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
delay();
boolean isFloat = false;
if (verbose) {
StringBuilder sb = getStringBuilder();
sb.append("INSERT ").append(table).append(" ").append(key).append(" [ ");
if (values != null) {
final TreeMap<String, ByteIterator> tree = new TreeMap<String, ByteIterator>(values);
for (Map.Entry<String, ByteIterator> entry : tree.entrySet()) {
if (entry.getKey().equals(timestampKey)) {
sb.append(entry.getKey()).append("=")
.append(Utils.bytesToLong(entry.getValue().toArray())).append(" ");
} else if (entry.getKey().equals(valueKey)) {
final NumericByteIterator it = (NumericByteIterator) entry.getValue();
isFloat = it.isFloatingPoint();
sb.append(entry.getKey()).append("=")
.append(isFloat ? it.getDouble() : it.getLong()).append(" ");
} else {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append(" ");
}
}
}
sb.append("]");
System.out.println(sb);
}
if (count) {
if (!verbose) {
isFloat = ((NumericByteIterator) values.get(valueKey)).isFloatingPoint();
}
int hash = hash(table, key, values);
incCounter(inserts, hash);
synchronized(timestamps) {
Integer ctr = timestamps.get(lastTimestamp);
if (ctr == null) {
timestamps.put(lastTimestamp, 1);
} else {
timestamps.put(lastTimestamp, ctr + 1);
}
}
if (isFloat) {
incCounter(floats, hash);
} else {
incCounter(integers, hash);
}
}
return Status.OK;
}
@Override
public void cleanup() {
super.cleanup();
if (count && counter < 1) {
System.out.println("[TIMESTAMPS], Unique, " + timestamps.size());
System.out.println("[FLOATS], Unique series, " + floats.size());
System.out.println("[INTEGERS], Unique series, " + integers.size());
long minTs = Long.MAX_VALUE;
long maxTs = Long.MIN_VALUE;
for (final long ts : timestamps.keySet()) {
if (ts > maxTs) {
maxTs = ts;
}
if (ts < minTs) {
minTs = ts;
}
}
System.out.println("[TIMESTAMPS], Min, " + minTs);
System.out.println("[TIMESTAMPS], Max, " + maxTs);
}
}
@Override
protected int hash(final String table, final String key, final Map<String, ByteIterator> values) {
final TreeMap<String, ByteIterator> sorted = new TreeMap<String, ByteIterator>();
for (final Entry<String, ByteIterator> entry : values.entrySet()) {
if (entry.getKey().equals(valueKey)) {
continue;
} else if (entry.getKey().equals(timestampKey)) {
lastTimestamp = ((NumericByteIterator) entry.getValue()).getLong();
entry.getValue().reset();
continue;
}
sorted.put(entry.getKey(), entry.getValue());
}
// yeah it's ugly but gives us a unique hash without having to add hashers
// to all of the ByteIterators.
StringBuilder buf = new StringBuilder().append(table).append(key);
for (final Entry<String, ByteIterator> entry : sorted.entrySet()) {
entry.getValue().reset();
buf.append(entry.getKey())
.append(entry.getValue().toString());
}
return buf.toString().hashCode();
}
} | 9,106 | 32.358974 | 102 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/RandomByteIterator.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import java.util.concurrent.ThreadLocalRandom;
/**
* A ByteIterator that generates a random sequence of bytes.
*/
public class RandomByteIterator extends ByteIterator {
private final long len;
private long off;
private int bufOff;
private final byte[] buf;
@Override
public boolean hasNext() {
return (off + bufOff) < len;
}
private void fillBytesImpl(byte[] buffer, int base) {
int bytes = ThreadLocalRandom.current().nextInt();
switch (buffer.length - base) {
default:
buffer[base + 5] = (byte) (((bytes >> 25) & 95) + ' ');
case 5:
buffer[base + 4] = (byte) (((bytes >> 20) & 63) + ' ');
case 4:
buffer[base + 3] = (byte) (((bytes >> 15) & 31) + ' ');
case 3:
buffer[base + 2] = (byte) (((bytes >> 10) & 95) + ' ');
case 2:
buffer[base + 1] = (byte) (((bytes >> 5) & 63) + ' ');
case 1:
buffer[base + 0] = (byte) (((bytes) & 31) + ' ');
case 0:
break;
}
}
private void fillBytes() {
if (bufOff == buf.length) {
fillBytesImpl(buf, 0);
bufOff = 0;
off += buf.length;
}
}
public RandomByteIterator(long len) {
this.len = len;
this.buf = new byte[6];
this.bufOff = buf.length;
fillBytes();
this.off = 0;
}
public byte nextByte() {
fillBytes();
bufOff++;
return buf[bufOff - 1];
}
@Override
public int nextBuf(byte[] buffer, int bufOffset) {
int ret;
if (len - off < buffer.length - bufOffset) {
ret = (int) (len - off);
} else {
ret = buffer.length - bufOffset;
}
int i;
for (i = 0; i < ret; i += 6) {
fillBytesImpl(buffer, i + bufOffset);
}
off += ret;
return ret + bufOffset;
}
@Override
public long bytesLeft() {
return len - off - bufOff;
}
@Override
public void reset() {
off = 0;
}
/** Consumes remaining contents of this object, and returns them as a byte array. */
public byte[] toArray() {
long left = bytesLeft();
if (left != (int) left) {
throw new ArrayIndexOutOfBoundsException("Too much data to fit in one array!");
}
byte[] ret = new byte[(int) left];
int bufOffset = 0;
while (bufOffset < ret.length) {
bufOffset = nextBuf(ret, bufOffset);
}
return ret;
}
}
| 3,004 | 24.252101 | 86 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/Client.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import site.ycsb.measurements.Measurements;
import site.ycsb.measurements.exporter.MeasurementsExporter;
import site.ycsb.measurements.exporter.TextMeasurementsExporter;
import org.apache.htrace.core.HTraceConfiguration;
import org.apache.htrace.core.TraceScope;
import org.apache.htrace.core.Tracer;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Turn seconds remaining into more useful units.
* i.e. if there are hours or days worth of seconds, use them.
*/
final class RemainingFormatter {
private RemainingFormatter() {
// not used
}
public static StringBuilder format(long seconds) {
StringBuilder time = new StringBuilder();
long days = TimeUnit.SECONDS.toDays(seconds);
if (days > 0) {
time.append(days).append(days == 1 ? " day " : " days ");
seconds -= TimeUnit.DAYS.toSeconds(days);
}
long hours = TimeUnit.SECONDS.toHours(seconds);
if (hours > 0) {
time.append(hours).append(hours == 1 ? " hour " : " hours ");
seconds -= TimeUnit.HOURS.toSeconds(hours);
}
/* Only include minute granularity if we're < 1 day. */
if (days < 1) {
long minutes = TimeUnit.SECONDS.toMinutes(seconds);
if (minutes > 0) {
time.append(minutes).append(minutes == 1 ? " minute " : " minutes ");
seconds -= TimeUnit.MINUTES.toSeconds(seconds);
}
}
/* Only bother to include seconds if we're < 1 minute */
if (time.length() == 0) {
time.append(seconds).append(time.length() == 1 ? " second " : " seconds ");
}
return time;
}
}
/**
* Main class for executing YCSB.
*/
public final class Client {
private Client() {
//not used
}
public static final String DEFAULT_RECORD_COUNT = "0";
/**
* The target number of operations to perform.
*/
public static final String OPERATION_COUNT_PROPERTY = "operationcount";
/**
* The number of records to load into the database initially.
*/
public static final String RECORD_COUNT_PROPERTY = "recordcount";
/**
* The workload class to be loaded.
*/
public static final String WORKLOAD_PROPERTY = "workload";
/**
* The database class to be used.
*/
public static final String DB_PROPERTY = "db";
/**
* The exporter class to be used. The default is
* site.ycsb.measurements.exporter.TextMeasurementsExporter.
*/
public static final String EXPORTER_PROPERTY = "exporter";
/**
* If set to the path of a file, YCSB will write all output to this file
* instead of STDOUT.
*/
public static final String EXPORT_FILE_PROPERTY = "exportfile";
/**
* The number of YCSB client threads to run.
*/
public static final String THREAD_COUNT_PROPERTY = "threadcount";
/**
* Indicates how many inserts to do if less than recordcount.
* Useful for partitioning the load among multiple servers if the client is the bottleneck.
* Additionally workloads should support the "insertstart" property which tells them which record to start at.
*/
public static final String INSERT_COUNT_PROPERTY = "insertcount";
/**
* Target number of operations per second.
*/
public static final String TARGET_PROPERTY = "target";
/**
* The maximum amount of time (in seconds) for which the benchmark will be run.
*/
public static final String MAX_EXECUTION_TIME = "maxexecutiontime";
/**
* Whether or not this is the transaction phase (run) or not (load).
*/
public static final String DO_TRANSACTIONS_PROPERTY = "dotransactions";
/**
* Whether or not to show status during run.
*/
public static final String STATUS_PROPERTY = "status";
/**
* Use label for status (e.g. to label one experiment out of a whole batch).
*/
public static final String LABEL_PROPERTY = "label";
/**
* An optional thread used to track progress and measure JVM stats.
*/
private static StatusThread statusthread = null;
// HTrace integration related constants.
/**
* All keys for configuring the tracing system start with this prefix.
*/
private static final String HTRACE_KEY_PREFIX = "htrace.";
private static final String CLIENT_WORKLOAD_INIT_SPAN = "Client#workload_init";
private static final String CLIENT_INIT_SPAN = "Client#init";
private static final String CLIENT_WORKLOAD_SPAN = "Client#workload";
private static final String CLIENT_CLEANUP_SPAN = "Client#cleanup";
private static final String CLIENT_EXPORT_MEASUREMENTS_SPAN = "Client#export_measurements";
public static void usageMessage() {
System.out.println("Usage: java site.ycsb.Client [options]");
System.out.println("Options:");
System.out.println(" -threads n: execute using n threads (default: 1) - can also be specified as the \n" +
" \"threadcount\" property using -p");
System.out.println(" -target n: attempt to do n operations per second (default: unlimited) - can also\n" +
" be specified as the \"target\" property using -p");
System.out.println(" -load: run the loading phase of the workload");
System.out.println(" -t: run the transactions phase of the workload (default)");
System.out.println(" -db dbname: specify the name of the DB to use (default: site.ycsb.BasicDB) - \n" +
" can also be specified as the \"db\" property using -p");
System.out.println(" -P propertyfile: load properties from the given file. Multiple files can");
System.out.println(" be specified, and will be processed in the order specified");
System.out.println(" -p name=value: specify a property to be passed to the DB and workloads;");
System.out.println(" multiple properties can be specified, and override any");
System.out.println(" values in the propertyfile");
System.out.println(" -s: show status during run (default: no status)");
System.out.println(" -l label: use label for status (e.g. to label one experiment out of a whole batch)");
System.out.println("");
System.out.println("Required properties:");
System.out.println(" " + WORKLOAD_PROPERTY + ": the name of the workload class to use (e.g. " +
"site.ycsb.workloads.CoreWorkload)");
System.out.println("");
System.out.println("To run the transaction phase from multiple servers, start a separate client on each.");
System.out.println("To run the load phase from multiple servers, start a separate client on each; additionally,");
System.out.println("use the \"insertcount\" and \"insertstart\" properties to divide up the records " +
"to be inserted");
}
public static boolean checkRequiredProperties(Properties props) {
if (props.getProperty(WORKLOAD_PROPERTY) == null) {
System.out.println("Missing property: " + WORKLOAD_PROPERTY);
return false;
}
return true;
}
/**
* Exports the measurements to either sysout or a file using the exporter
* loaded from conf.
*
* @throws IOException Either failed to write to output stream or failed to close it.
*/
private static void exportMeasurements(Properties props, int opcount, long runtime)
throws IOException {
MeasurementsExporter exporter = null;
try {
// if no destination file is provided the results will be written to stdout
OutputStream out;
String exportFile = props.getProperty(EXPORT_FILE_PROPERTY);
if (exportFile == null) {
out = System.out;
} else {
out = new FileOutputStream(exportFile);
}
// if no exporter is provided the default text one will be used
String exporterStr = props.getProperty(EXPORTER_PROPERTY,
"site.ycsb.measurements.exporter.TextMeasurementsExporter");
try {
exporter = (MeasurementsExporter) Class.forName(exporterStr).getConstructor(OutputStream.class)
.newInstance(out);
} catch (Exception e) {
System.err.println("Could not find exporter " + exporterStr
+ ", will use default text reporter.");
e.printStackTrace();
exporter = new TextMeasurementsExporter(out);
}
exporter.write("OVERALL", "RunTime(ms)", runtime);
double throughput = 1000.0 * (opcount) / (runtime);
exporter.write("OVERALL", "Throughput(ops/sec)", throughput);
final Map<String, Long[]> gcs = Utils.getGCStatst();
long totalGCCount = 0;
long totalGCTime = 0;
for (final Entry<String, Long[]> entry : gcs.entrySet()) {
exporter.write("TOTAL_GCS_" + entry.getKey(), "Count", entry.getValue()[0]);
exporter.write("TOTAL_GC_TIME_" + entry.getKey(), "Time(ms)", entry.getValue()[1]);
exporter.write("TOTAL_GC_TIME_%_" + entry.getKey(), "Time(%)",
((double) entry.getValue()[1] / runtime) * (double) 100);
totalGCCount += entry.getValue()[0];
totalGCTime += entry.getValue()[1];
}
exporter.write("TOTAL_GCs", "Count", totalGCCount);
exporter.write("TOTAL_GC_TIME", "Time(ms)", totalGCTime);
exporter.write("TOTAL_GC_TIME_%", "Time(%)", ((double) totalGCTime / runtime) * (double) 100);
if (statusthread != null && statusthread.trackJVMStats()) {
exporter.write("MAX_MEM_USED", "MBs", statusthread.getMaxUsedMem());
exporter.write("MIN_MEM_USED", "MBs", statusthread.getMinUsedMem());
exporter.write("MAX_THREADS", "Count", statusthread.getMaxThreads());
exporter.write("MIN_THREADS", "Count", statusthread.getMinThreads());
exporter.write("MAX_SYS_LOAD_AVG", "Load", statusthread.getMaxLoadAvg());
exporter.write("MIN_SYS_LOAD_AVG", "Load", statusthread.getMinLoadAvg());
}
Measurements.getMeasurements().exportMeasurements(exporter);
} finally {
if (exporter != null) {
exporter.close();
}
}
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Properties props = parseArguments(args);
boolean status = Boolean.valueOf(props.getProperty(STATUS_PROPERTY, String.valueOf(false)));
String label = props.getProperty(LABEL_PROPERTY, "");
long maxExecutionTime = Integer.parseInt(props.getProperty(MAX_EXECUTION_TIME, "0"));
//get number of threads, target and db
int threadcount = Integer.parseInt(props.getProperty(THREAD_COUNT_PROPERTY, "1"));
String dbname = props.getProperty(DB_PROPERTY, "site.ycsb.BasicDB");
int target = Integer.parseInt(props.getProperty(TARGET_PROPERTY, "0"));
//compute the target throughput
double targetperthreadperms = -1;
if (target > 0) {
double targetperthread = ((double) target) / ((double) threadcount);
targetperthreadperms = targetperthread / 1000.0;
}
Thread warningthread = setupWarningThread();
warningthread.start();
Measurements.setProperties(props);
Workload workload = getWorkload(props);
final Tracer tracer = getTracer(props, workload);
initWorkload(props, warningthread, workload, tracer);
System.err.println("Starting test.");
final CountDownLatch completeLatch = new CountDownLatch(threadcount);
final List<ClientThread> clients = initDb(dbname, props, threadcount, targetperthreadperms,
workload, tracer, completeLatch);
if (status) {
boolean standardstatus = false;
if (props.getProperty(Measurements.MEASUREMENT_TYPE_PROPERTY, "").compareTo("timeseries") == 0) {
standardstatus = true;
}
int statusIntervalSeconds = Integer.parseInt(props.getProperty("status.interval", "10"));
boolean trackJVMStats = props.getProperty(Measurements.MEASUREMENT_TRACK_JVM_PROPERTY,
Measurements.MEASUREMENT_TRACK_JVM_PROPERTY_DEFAULT).equals("true");
statusthread = new StatusThread(completeLatch, clients, label, standardstatus, statusIntervalSeconds,
trackJVMStats);
statusthread.start();
}
Thread terminator = null;
long st;
long en;
int opsDone;
try (final TraceScope span = tracer.newScope(CLIENT_WORKLOAD_SPAN)) {
final Map<Thread, ClientThread> threads = new HashMap<>(threadcount);
for (ClientThread client : clients) {
threads.put(new Thread(tracer.wrap(client, "ClientThread")), client);
}
st = System.currentTimeMillis();
for (Thread t : threads.keySet()) {
t.start();
}
if (maxExecutionTime > 0) {
terminator = new TerminatorThread(maxExecutionTime, threads.keySet(), workload);
terminator.start();
}
opsDone = 0;
for (Map.Entry<Thread, ClientThread> entry : threads.entrySet()) {
try {
entry.getKey().join();
opsDone += entry.getValue().getOpsDone();
} catch (InterruptedException ignored) {
// ignored
}
}
en = System.currentTimeMillis();
}
try {
try (final TraceScope span = tracer.newScope(CLIENT_CLEANUP_SPAN)) {
if (terminator != null && !terminator.isInterrupted()) {
terminator.interrupt();
}
if (status) {
// wake up status thread if it's asleep
statusthread.interrupt();
// at this point we assume all the monitored threads are already gone as per above join loop.
try {
statusthread.join();
} catch (InterruptedException ignored) {
// ignored
}
}
workload.cleanup();
}
} catch (WorkloadException e) {
e.printStackTrace();
e.printStackTrace(System.out);
System.exit(0);
}
try {
try (final TraceScope span = tracer.newScope(CLIENT_EXPORT_MEASUREMENTS_SPAN)) {
exportMeasurements(props, opsDone, en - st);
}
} catch (IOException e) {
System.err.println("Could not export measurements, error: " + e.getMessage());
e.printStackTrace();
System.exit(-1);
}
System.exit(0);
}
private static List<ClientThread> initDb(String dbname, Properties props, int threadcount,
double targetperthreadperms, Workload workload, Tracer tracer,
CountDownLatch completeLatch) {
boolean initFailed = false;
boolean dotransactions = Boolean.valueOf(props.getProperty(DO_TRANSACTIONS_PROPERTY, String.valueOf(true)));
final List<ClientThread> clients = new ArrayList<>(threadcount);
try (final TraceScope span = tracer.newScope(CLIENT_INIT_SPAN)) {
int opcount;
if (dotransactions) {
opcount = Integer.parseInt(props.getProperty(OPERATION_COUNT_PROPERTY, "0"));
} else {
if (props.containsKey(INSERT_COUNT_PROPERTY)) {
opcount = Integer.parseInt(props.getProperty(INSERT_COUNT_PROPERTY, "0"));
} else {
opcount = Integer.parseInt(props.getProperty(RECORD_COUNT_PROPERTY, DEFAULT_RECORD_COUNT));
}
}
if (threadcount > opcount && opcount > 0){
threadcount = opcount;
System.out.println("Warning: the threadcount is bigger than recordcount, the threadcount will be recordcount!");
}
for (int threadid = 0; threadid < threadcount; threadid++) {
DB db;
try {
db = DBFactory.newDB(dbname, props, tracer);
} catch (UnknownDBException e) {
System.out.println("Unknown DB " + dbname);
initFailed = true;
break;
}
int threadopcount = opcount / threadcount;
// ensure correct number of operations, in case opcount is not a multiple of threadcount
if (threadid < opcount % threadcount) {
++threadopcount;
}
ClientThread t = new ClientThread(db, dotransactions, workload, props, threadopcount, targetperthreadperms,
completeLatch);
t.setThreadId(threadid);
t.setThreadCount(threadcount);
clients.add(t);
}
if (initFailed) {
System.err.println("Error initializing datastore bindings.");
System.exit(0);
}
}
return clients;
}
private static Tracer getTracer(Properties props, Workload workload) {
return new Tracer.Builder("YCSB " + workload.getClass().getSimpleName())
.conf(getHTraceConfiguration(props))
.build();
}
private static void initWorkload(Properties props, Thread warningthread, Workload workload, Tracer tracer) {
try {
try (final TraceScope span = tracer.newScope(CLIENT_WORKLOAD_INIT_SPAN)) {
workload.init(props);
warningthread.interrupt();
}
} catch (WorkloadException e) {
e.printStackTrace();
e.printStackTrace(System.out);
System.exit(0);
}
}
private static HTraceConfiguration getHTraceConfiguration(Properties props) {
final Map<String, String> filteredProperties = new HashMap<>();
for (String key : props.stringPropertyNames()) {
if (key.startsWith(HTRACE_KEY_PREFIX)) {
filteredProperties.put(key.substring(HTRACE_KEY_PREFIX.length()), props.getProperty(key));
}
}
return HTraceConfiguration.fromMap(filteredProperties);
}
private static Thread setupWarningThread() {
//show a warning message that creating the workload is taking a while
//but only do so if it is taking longer than 2 seconds
//(showing the message right away if the setup wasn't taking very long was confusing people)
return new Thread() {
@Override
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
return;
}
System.err.println(" (might take a few minutes for large data sets)");
}
};
}
private static Workload getWorkload(Properties props) {
ClassLoader classLoader = Client.class.getClassLoader();
try {
Properties projectProp = new Properties();
projectProp.load(classLoader.getResourceAsStream("project.properties"));
System.err.println("YCSB Client " + projectProp.getProperty("version"));
} catch (IOException e) {
System.err.println("Unable to retrieve client version.");
}
System.err.println();
System.err.println("Loading workload...");
try {
Class workloadclass = classLoader.loadClass(props.getProperty(WORKLOAD_PROPERTY));
return (Workload) workloadclass.newInstance();
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace(System.out);
System.exit(0);
}
return null;
}
private static Properties parseArguments(String[] args) {
Properties props = new Properties();
System.err.print("Command line:");
for (String arg : args) {
System.err.print(" " + arg);
}
System.err.println();
Properties fileprops = new Properties();
int argindex = 0;
if (args.length == 0) {
usageMessage();
System.out.println("At least one argument specifying a workload is required.");
System.exit(0);
}
while (args[argindex].startsWith("-")) {
if (args[argindex].compareTo("-threads") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.out.println("Missing argument value for -threads.");
System.exit(0);
}
int tcount = Integer.parseInt(args[argindex]);
props.setProperty(THREAD_COUNT_PROPERTY, String.valueOf(tcount));
argindex++;
} else if (args[argindex].compareTo("-target") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.out.println("Missing argument value for -target.");
System.exit(0);
}
int ttarget = Integer.parseInt(args[argindex]);
props.setProperty(TARGET_PROPERTY, String.valueOf(ttarget));
argindex++;
} else if (args[argindex].compareTo("-load") == 0) {
props.setProperty(DO_TRANSACTIONS_PROPERTY, String.valueOf(false));
argindex++;
} else if (args[argindex].compareTo("-t") == 0) {
props.setProperty(DO_TRANSACTIONS_PROPERTY, String.valueOf(true));
argindex++;
} else if (args[argindex].compareTo("-s") == 0) {
props.setProperty(STATUS_PROPERTY, String.valueOf(true));
argindex++;
} else if (args[argindex].compareTo("-db") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.out.println("Missing argument value for -db.");
System.exit(0);
}
props.setProperty(DB_PROPERTY, args[argindex]);
argindex++;
} else if (args[argindex].compareTo("-l") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.out.println("Missing argument value for -l.");
System.exit(0);
}
props.setProperty(LABEL_PROPERTY, args[argindex]);
argindex++;
} else if (args[argindex].compareTo("-P") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.out.println("Missing argument value for -P.");
System.exit(0);
}
String propfile = args[argindex];
argindex++;
Properties myfileprops = new Properties();
try {
myfileprops.load(new FileInputStream(propfile));
} catch (IOException e) {
System.out.println("Unable to open the properties file " + propfile);
System.out.println(e.getMessage());
System.exit(0);
}
//Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5
for (Enumeration e = myfileprops.propertyNames(); e.hasMoreElements();) {
String prop = (String) e.nextElement();
fileprops.setProperty(prop, myfileprops.getProperty(prop));
}
} else if (args[argindex].compareTo("-p") == 0) {
argindex++;
if (argindex >= args.length) {
usageMessage();
System.out.println("Missing argument value for -p");
System.exit(0);
}
int eq = args[argindex].indexOf('=');
if (eq < 0) {
usageMessage();
System.out.println("Argument '-p' expected to be in key=value format (e.g., -p operationcount=99999)");
System.exit(0);
}
String name = args[argindex].substring(0, eq);
String value = args[argindex].substring(eq + 1);
props.put(name, value);
argindex++;
} else {
usageMessage();
System.out.println("Unknown option " + args[argindex]);
System.exit(0);
}
if (argindex >= args.length) {
break;
}
}
if (argindex != args.length) {
usageMessage();
if (argindex < args.length) {
System.out.println("An argument value without corresponding argument specifier (e.g., -p, -s) was found. "
+ "We expected an argument specifier and instead found " + args[argindex]);
} else {
System.out.println("An argument specifier without corresponding value was found at the end of the supplied " +
"command line arguments.");
}
System.exit(0);
}
//overwrite file properties with properties from the command line
//Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5
for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
String prop = (String) e.nextElement();
fileprops.setProperty(prop, props.getProperty(prop));
}
props = fileprops;
if (!checkRequiredProperties(props)) {
System.out.println("Failed check required properties.");
System.exit(0);
}
return props;
}
}
| 24,543 | 35.094118 | 120 | java |
null | NearPMSW-main/baseline/logging/YCSB/core/src/main/java/site/ycsb/ClientThread.java | /**
* Copyright (c) 2010-2016 Yahoo! Inc., 2017 YCSB contributors All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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. See accompanying
* LICENSE file.
*/
package site.ycsb;
import site.ycsb.measurements.Measurements;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.LockSupport;
/**
* A thread for executing transactions or data inserts to the database.
*/
public class ClientThread implements Runnable {
// Counts down each of the clients completing.
private final CountDownLatch completeLatch;
private static boolean spinSleep;
private DB db;
private boolean dotransactions;
private Workload workload;
private int opcount;
private double targetOpsPerMs;
private int opsdone;
private int threadid;
private int threadcount;
private Object workloadstate;
private Properties props;
private long targetOpsTickNs;
private final Measurements measurements;
/**
* Constructor.
*
* @param db the DB implementation to use
* @param dotransactions true to do transactions, false to insert data
* @param workload the workload to use
* @param props the properties defining the experiment
* @param opcount the number of operations (transactions or inserts) to do
* @param targetperthreadperms target number of operations per thread per ms
* @param completeLatch The latch tracking the completion of all clients.
*/
public ClientThread(DB db, boolean dotransactions, Workload workload, Properties props, int opcount,
double targetperthreadperms, CountDownLatch completeLatch) {
this.db = db;
this.dotransactions = dotransactions;
this.workload = workload;
this.opcount = opcount;
opsdone = 0;
if (targetperthreadperms > 0) {
targetOpsPerMs = targetperthreadperms;
targetOpsTickNs = (long) (1000000 / targetOpsPerMs);
}
this.props = props;
measurements = Measurements.getMeasurements();
spinSleep = Boolean.valueOf(this.props.getProperty("spin.sleep", "false"));
this.completeLatch = completeLatch;
}
public void setThreadId(final int threadId) {
threadid = threadId;
}
public void setThreadCount(final int threadCount) {
threadcount = threadCount;
}
public int getOpsDone() {
return opsdone;
}
@Override
public void run() {
try {
db.init();
} catch (DBException e) {
e.printStackTrace();
e.printStackTrace(System.out);
return;
}
try {
workloadstate = workload.initThread(props, threadid, threadcount);
} catch (WorkloadException e) {
e.printStackTrace();
e.printStackTrace(System.out);
return;
}
//NOTE: Switching to using nanoTime and parkNanos for time management here such that the measurements
// and the client thread have the same view on time.
//spread the thread operations out so they don't all hit the DB at the same time
// GH issue 4 - throws exception if _target>1 because random.nextInt argument must be >0
// and the sleep() doesn't make sense for granularities < 1 ms anyway
if ((targetOpsPerMs > 0) && (targetOpsPerMs <= 1.0)) {
long randomMinorDelay = ThreadLocalRandom.current().nextInt((int) targetOpsTickNs);
sleepUntil(System.nanoTime() + randomMinorDelay);
}
try {
if (dotransactions) {
long startTimeNanos = System.nanoTime();
while (((opcount == 0) || (opsdone < opcount)) && !workload.isStopRequested()) {
if (!workload.doTransaction(db, workloadstate)) {
break;
}
opsdone++;
throttleNanos(startTimeNanos);
}
} else {
long startTimeNanos = System.nanoTime();
while (((opcount == 0) || (opsdone < opcount)) && !workload.isStopRequested()) {
if (!workload.doInsert(db, workloadstate)) {
break;
}
opsdone++;
throttleNanos(startTimeNanos);
}
}
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace(System.out);
System.exit(0);
}
try {
measurements.setIntendedStartTimeNs(0);
db.cleanup();
} catch (DBException e) {
e.printStackTrace();
e.printStackTrace(System.out);
} finally {
completeLatch.countDown();
}
}
private static void sleepUntil(long deadline) {
while (System.nanoTime() < deadline) {
if (!spinSleep) {
LockSupport.parkNanos(deadline - System.nanoTime());
}
}
}
private void throttleNanos(long startTimeNanos) {
//throttle the operations
if (targetOpsPerMs > 0) {
// delay until next tick
long deadline = startTimeNanos + opsdone * targetOpsTickNs;
sleepUntil(deadline);
measurements.setIntendedStartTimeNs(deadline);
}
}
/**
* The total amount of work this thread is still expected to do.
*/
int getOpsTodo() {
int todo = opcount - opsdone;
return todo < 0 ? 0 : todo;
}
}
| 5,667 | 29.31016 | 105 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.