lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 07f2d4e72d57313473316edf8a1ec11eec4f0434 | 0 | xlongtang/cordova-plugin-image-resizer,protonet/cordova-plugin-image-resizer,JoschkaSchulz/cordova-plugin-image-resizer,xlongtang/cordova-plugin-image-resizer,JoschkaSchulz/cordova-plugin-image-resizer,protonet/cordova-plugin-image-resizer | package info.protonet.imageresizer;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.FileHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.util.Log;
import android.content.Context;
import android.provider.MediaStore.Images.Media;
import android.net.Uri;
import android.os.Environment;
public class ImageResizer extends CordovaPlugin {
private static final int ARGUMENT_NUMBER = 1;
public CallbackContext callbackContext;
private String uri;
private String folderName;
private int quality;
private int width;
private int height;
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
this.callbackContext = callbackContext;
if (action.equals("resize")) {
checkParameters(args);
// get the arguments
JSONObject jsonObject = args.getJSONObject(0);
uri = jsonObject.getString("uri");
folderName = jsonObject.getString("folderName");
quality = jsonObject.getInt("quality");
width = jsonObject.getInt("width");
height = jsonObject.getInt("height");
// load the image from uri
Bitmap bitmap = loadScaledBitmapFromUri(uri, width, height);
// save the image as jpeg on the device
Uri scaledFile = saveFile(bitmap);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, scaledFile.toString()));
return true;
} else {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
return false;
}
} catch(JSONException e) {
Log.e("Protonet", "JSON Exception during the Image Resizer Plugin... :(");
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
return false;
}
/**
* Loads a Bitmap of the given android uri path
*
* @params uri the URI who points to the image
**/
private Bitmap loadScaledBitmapFromUri(String uriString, int width, int height) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(uriString, cordova), null, options);
//calc aspect ratio
int[] retval = calculateAspectRatio(options.outWidth, options.outHeight);
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, width, height);
Bitmap unscaledBitmap = BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(uriString, cordova), null, options);
return Bitmap.createScaledBitmap(unscaledBitmap, retval[0], retval[1], true);
} catch (FileNotFoundException e) {
Log.e("Protonet", "File not found. :(");
} catch (IOException e) {
Log.e("Protonet", "IO Exception :(");
}catch(Exception e) {
Log.e("Protonet", e.toString());
}
return null;
}
private Uri saveFile(Bitmap bitmap) {
File folder = new File(Environment.getExternalStorageDirectory() + "/" + folderName);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if(success) {
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(folder, fileName);
if(file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
out.flush();
out.close();
} catch(Exception e) {
Log.e("Protonet", e.toString());
}
return Uri.fromFile(file);
}
return null;
}
/**
* Figure out what ratio we can load our image into memory at while still being bigger than
* our desired width and height
*
* @param srcWidth
* @param srcHeight
* @param dstWidth
* @param dstHeight
* @return
*/
private int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)dstWidth / (float)dstHeight;
if (srcAspect > dstAspect) {
return srcWidth / dstWidth;
} else {
return srcHeight / dstHeight;
}
}
/**
* Maintain the aspect ratio so the resulting image does not look smooshed
*
* @param origWidth
* @param origHeight
* @return
*/
private int[] calculateAspectRatio(int origWidth, int origHeight) {
int newWidth = width;
int newHeight = height;
// If no new width or height were specified return the original bitmap
if (newWidth <= 0 && newHeight <= 0) {
newWidth = origWidth;
newHeight = origHeight;
}
// Only the width was specified
else if (newWidth > 0 && newHeight <= 0) {
newHeight = (newWidth * origHeight) / origWidth;
}
// only the height was specified
else if (newWidth <= 0 && newHeight > 0) {
newWidth = (newHeight * origWidth) / origHeight;
}
// If the user specified both a positive width and height
// (potentially different aspect ratio) then the width or height is
// scaled so that the image fits while maintaining aspect ratio.
// Alternatively, the specified width and height could have been
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
// would result in whitespace in the new image.
else {
double newRatio = newWidth / (double) newHeight;
double origRatio = origWidth / (double) origHeight;
if (origRatio > newRatio) {
newHeight = (newWidth * origHeight) / origWidth;
} else if (origRatio < newRatio) {
newWidth = (newHeight * origWidth) / origHeight;
}
}
int[] retval = new int[2];
retval[0] = newWidth;
retval[1] = newHeight;
return retval;
}
private boolean checkParameters(JSONArray args) {
if (args.length() != ARGUMENT_NUMBER) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
return false;
}
return true;
}
}
| src/android/ImageResizer.java | package info.protonet.imageresizer;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.apache.cordova.FileHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.util.Log;
import android.content.Context;
import android.provider.MediaStore.Images.Media;
import android.net.Uri;
import android.os.Environment;
public class ImageResizer extends CordovaPlugin {
private static final int ARGUMENT_NUMBER = 1;
public CallbackContext callbackContext;
private String uri;
private String folderName;
private int quality;
private int width;
private int height;
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
this.callbackContext = callbackContext;
if (action.equals("resize")) {
checkParameters(args);
// get the arguments
JSONObject jsonObject = args.getJSONObject(0);
uri = jsonObject.getString("uri");
folderName = jsonObject.getString("folderName");
quality = jsonObject.getInt("quality");
width = jsonObject.getInt("width");
height = jsonObject.getInt("height");
// load the image from uri
Bitmap bitmap = loadScaledBitmapFromUri(uri, width, height);
// save the image as jpeg on the device
Uri scaledFile = saveFile(bitmap);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, scaledFile.toString()));
return true;
} else {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
return false;
}
} catch(JSONException e) {
Log.e("Protonet", "JSON Exception during the Image Resizer Plugin... :(");
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
return false;
}
/**
* Loads a Bitmap of the given android uri path
*
* @params uri the URI who points to the image
**/
private Bitmap loadScaledBitmapFromUri(String uriString, int width, int height) {
Log.i("Protonet", "width: " + width + " height: " + height);
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(uriString, cordova), null, options);
Log.i("Protonet", "owidth: " + options.outWidth + " oheight: " + options.outHeight);
//calc aspect ratio
Log.i("Protonet", "Options: " + options);
int[] retval = calculateAspectRatio(options.outWidth, options.outHeight);
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, width, height);
Log.i("Protonet", "inSampleSize: " + options.inSampleSize);
Bitmap unscaledBitmap = BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(uriString, cordova), null, options);
return Bitmap.createScaledBitmap(unscaledBitmap, retval[0], retval[1], true);
} catch (FileNotFoundException e) {
Log.e("Protonet", "File not found. :(");
} catch (IOException e) {
Log.e("Protonet", "IO Exception :(");
}catch(Exception e) {
Log.e("Protonet", e.toString());
}
return null;
}
private Uri saveFile(Bitmap bitmap) {
File folder = new File(Environment.getExternalStorageDirectory() + "/" + folderName);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if(success) {
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(folder, fileName);
if(file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
out.flush();
out.close();
} catch(Exception e) {
Log.e("Protonet", e.toString());
}
return Uri.fromFile(file);
}
return null;
}
/**
* Figure out what ratio we can load our image into memory at while still being bigger than
* our desired width and height
*
* @param srcWidth
* @param srcHeight
* @param dstWidth
* @param dstHeight
* @return
*/
private int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)dstWidth / (float)dstHeight;
if (srcAspect > dstAspect) {
return srcWidth / dstWidth;
} else {
return srcHeight / dstHeight;
}
}
/**
* Maintain the aspect ratio so the resulting image does not look smooshed
*
* @param origWidth
* @param origHeight
* @return
*/
private int[] calculateAspectRatio(int origWidth, int origHeight) {
int newWidth = width;
int newHeight = height;
// If no new width or height were specified return the original bitmap
if (newWidth <= 0 && newHeight <= 0) {
newWidth = origWidth;
newHeight = origHeight;
}
// Only the width was specified
else if (newWidth > 0 && newHeight <= 0) {
newHeight = (newWidth * origHeight) / origWidth;
}
// only the height was specified
else if (newWidth <= 0 && newHeight > 0) {
newWidth = (newHeight * origWidth) / origHeight;
}
// If the user specified both a positive width and height
// (potentially different aspect ratio) then the width or height is
// scaled so that the image fits while maintaining aspect ratio.
// Alternatively, the specified width and height could have been
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
// would result in whitespace in the new image.
else {
double newRatio = newWidth / (double) newHeight;
double origRatio = origWidth / (double) origHeight;
if (origRatio > newRatio) {
newHeight = (newWidth * origHeight) / origWidth;
} else if (origRatio < newRatio) {
newWidth = (newHeight * origWidth) / origHeight;
}
}
int[] retval = new int[2];
retval[0] = newWidth;
retval[1] = newHeight;
return retval;
}
private boolean checkParameters(JSONArray args) {
if (args.length() != ARGUMENT_NUMBER) {
Log.e("Protonet", "Invalid Number of Arguments (" + args.length() + " of " + ARGUMENT_NUMBER + ")");
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
return false;
}
return true;
}
}
| removed Logs
| src/android/ImageResizer.java | removed Logs | <ide><path>rc/android/ImageResizer.java
<ide> * @params uri the URI who points to the image
<ide> **/
<ide> private Bitmap loadScaledBitmapFromUri(String uriString, int width, int height) {
<del> Log.i("Protonet", "width: " + width + " height: " + height);
<ide> try {
<ide> BitmapFactory.Options options = new BitmapFactory.Options();
<ide> options.inJustDecodeBounds = true;
<ide> BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(uriString, cordova), null, options);
<del> Log.i("Protonet", "owidth: " + options.outWidth + " oheight: " + options.outHeight);
<ide>
<ide> //calc aspect ratio
<del> Log.i("Protonet", "Options: " + options);
<ide> int[] retval = calculateAspectRatio(options.outWidth, options.outHeight);
<ide>
<ide> options.inJustDecodeBounds = false;
<ide> options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, width, height);
<del> Log.i("Protonet", "inSampleSize: " + options.inSampleSize);
<ide> Bitmap unscaledBitmap = BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(uriString, cordova), null, options);
<ide> return Bitmap.createScaledBitmap(unscaledBitmap, retval[0], retval[1], true);
<ide> } catch (FileNotFoundException e) {
<ide>
<ide> private boolean checkParameters(JSONArray args) {
<ide> if (args.length() != ARGUMENT_NUMBER) {
<del> Log.e("Protonet", "Invalid Number of Arguments (" + args.length() + " of " + ARGUMENT_NUMBER + ")");
<ide> callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
<ide> return false;
<ide> } |
|
Java | apache-2.0 | f63bf2cd87cc5845fca7b271e1e6e94def779743 | 0 | weexteam/incubator-weex,alibaba/weex,leoward/incubator-weex,cxfeng1/incubator-weex,weexteam/incubator-weex,alibaba/weex,miomin/incubator-weex,MrRaindrop/incubator-weex,miomin/incubator-weex,leoward/incubator-weex,yuguitao/incubator-weex,cxfeng1/incubator-weex,Hanks10100/incubator-weex,erha19/incubator-weex,MrRaindrop/incubator-weex,yuguitao/incubator-weex,miomin/incubator-weex,alibaba/weex,alibaba/weex,alibaba/weex,leoward/incubator-weex,xiayun200825/weex,erha19/incubator-weex,xiayun200825/weex,xiayun200825/weex,Hanks10100/incubator-weex,erha19/incubator-weex,acton393/incubator-weex,miomin/incubator-weex,KalicyZhou/incubator-weex,KalicyZhou/incubator-weex,MrRaindrop/incubator-weex,cxfeng1/incubator-weex,alibaba/weex,KalicyZhou/incubator-weex,weexteam/incubator-weex,leoward/incubator-weex,acton393/incubator-weex,yuguitao/incubator-weex,Hanks10100/incubator-weex,xiayun200825/weex,weexteam/incubator-weex,Hanks10100/incubator-weex,leoward/incubator-weex,acton393/incubator-weex,Hanks10100/incubator-weex,KalicyZhou/incubator-weex,xiayun200825/weex,cxfeng1/incubator-weex,erha19/incubator-weex,acton393/incubator-weex,yuguitao/incubator-weex,acton393/incubator-weex,cxfeng1/incubator-weex,erha19/incubator-weex,MrRaindrop/incubator-weex,acton393/incubator-weex,erha19/incubator-weex,erha19/incubator-weex,Hanks10100/incubator-weex,MrRaindrop/incubator-weex,yuguitao/incubator-weex,alibaba/weex,miomin/incubator-weex,miomin/incubator-weex,erha19/incubator-weex,miomin/incubator-weex,Hanks10100/incubator-weex,miomin/incubator-weex,KalicyZhou/incubator-weex,leoward/incubator-weex,cxfeng1/incubator-weex,acton393/incubator-weex,xiayun200825/weex,yuguitao/incubator-weex,acton393/incubator-weex,KalicyZhou/incubator-weex,MrRaindrop/incubator-weex,weexteam/incubator-weex,weexteam/incubator-weex,Hanks10100/incubator-weex | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.taobao.weex.ui.component.list;
import android.content.Context;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.annotation.Component;
import com.taobao.weex.common.Constants;
import com.taobao.weex.dom.WXDomObject;
import com.taobao.weex.dom.WXRecyclerDomObject;
import com.taobao.weex.dom.flex.Spacing;
import com.taobao.weex.ui.component.WXBaseRefresh;
import com.taobao.weex.ui.component.WXBasicComponentType;
import com.taobao.weex.ui.component.WXComponent;
import com.taobao.weex.ui.component.WXComponentProp;
import com.taobao.weex.ui.component.WXLoading;
import com.taobao.weex.ui.component.WXRefresh;
import com.taobao.weex.ui.component.WXVContainer;
import com.taobao.weex.ui.view.listview.WXRecyclerView;
import com.taobao.weex.ui.view.listview.adapter.ListBaseViewHolder;
import com.taobao.weex.ui.view.refresh.wrapper.BounceRecyclerView;
import com.taobao.weex.utils.WXLogUtils;
import java.util.Map;
/**
* Unlike other components, there is immutable bi-directional association between View and
* ViewHolder, while only mutable and temporal uni-directional association between view and
* components. The association only exist from {@link #onBindViewHolder(ListBaseViewHolder, int)} to
* {@link #onViewRecycled(ListBaseViewHolder)}. In other situations, the association may not valid
* or not even exist.
*/
@Component(lazyload = false)
public class WXListComponent extends BasicListComponent<BounceRecyclerView> {
private String TAG = "WXListComponent";
private WXRecyclerDomObject mDomObject;
private float mPaddingLeft;
private float mPaddingRight;
@Deprecated
public WXListComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy) {
this(instance, dom, parent, isLazy);
}
public WXListComponent(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy) {
super(instance, node, parent);
if (node != null && node instanceof WXRecyclerDomObject) {
mDomObject = (WXRecyclerDomObject) node;
mDomObject.preCalculateCellWidth();
if(WXBasicComponentType.WATERFALL.equals(node.getType())){
mLayoutType = WXRecyclerView.TYPE_STAGGERED_GRID_LAYOUT;
}else{
mLayoutType = mDomObject.getLayoutType();
}
updateRecyclerAttr();
}
}
@Override
protected BounceRecyclerView generateListView(Context context, int orientation) {
return new BounceRecyclerView(context,mLayoutType,mColumnCount,mColumnGap,orientation);
}
@Override
public void addChild(WXComponent child, int index) {
super.addChild(child, index);
if (child == null || index < -1) {
return;
}
setRefreshOrLoading(child);
// Synchronize DomObject's attr to Component and Native View
if(mDomObject != null && getHostView() != null && (mColumnWidth != mDomObject.getColumnWidth() ||
mColumnCount != mDomObject.getColumnCount() ||
mColumnGap != mDomObject.getColumnGap())) {
updateRecyclerAttr();
getHostView().getInnerView().initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation());
}
}
/**
* Setting refresh view and loading view
*
* @param child the refresh_view or loading_view
*/
private boolean setRefreshOrLoading(final WXComponent child) {
if (getHostView() == null) {
WXLogUtils.e(TAG, "setRefreshOrLoading: HostView == null !!!!!! check list attr has append =tree");
return true;
}
if (child instanceof WXRefresh) {
getHostView().setOnRefreshListener((WXRefresh) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setHeaderView(child);
}
}, 100);
return true;
}
if (child instanceof WXLoading) {
getHostView().setOnLoadingListener((WXLoading) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setFooterView(child);
}
}, 100);
return true;
}
return false;
}
private void updateRecyclerAttr(){
mColumnCount = mDomObject.getColumnCount();
mColumnGap = mDomObject.getColumnGap();
mColumnWidth = mDomObject.getColumnWidth();
mPaddingLeft =mDomObject.getPadding().get(Spacing.LEFT);
mPaddingRight =mDomObject.getPadding().get(Spacing.RIGHT);
}
@WXComponentProp(name = Constants.Name.COLUMN_WIDTH)
public void setColumnWidth(int columnCount) {
if(mDomObject.getColumnWidth() != mColumnWidth){
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation());
}
}
@WXComponentProp(name = Constants.Name.COLUMN_COUNT)
public void setColumnCount(int columnCount){
if(mDomObject.getColumnCount() != mColumnCount){
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation());
}
}
@WXComponentProp(name = Constants.Name.COLUMN_GAP)
public void setColumnGap(float columnGap) throws InterruptedException {
if(mDomObject.getColumnGap() != mColumnGap) {
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType, mColumnCount, mColumnGap, getOrientation());
}
}
@WXComponentProp(name = Constants.Name.SCROLLABLE)
public void setScrollable(boolean scrollable) {
WXRecyclerView inner = getHostView().getInnerView();
inner.setScrollable(scrollable);
}
@Override
public void updateProperties(Map<String, Object> props) {
super.updateProperties(props);
if(props.containsKey(Constants.Name.PADDING)
||props.containsKey(Constants.Name.PADDING_LEFT)
|| props.containsKey(Constants.Name.PADDING_RIGHT)){
if(mPaddingLeft !=mDomObject.getPadding().get(Spacing.LEFT)
|| mPaddingRight !=mDomObject.getPadding().get(Spacing.RIGHT)) {
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType, mColumnCount, mColumnGap, getOrientation());
}
}
}
@Override
public void createChildViewAt(int index) {
int indexToCreate = index;
if (indexToCreate < 0) {
indexToCreate = childCount() - 1;
if (indexToCreate < 0) {
return;
}
}
final WXComponent child = getChild(indexToCreate);
if (child instanceof WXBaseRefresh) {
child.createView();
if (child instanceof WXRefresh) {
getHostView().setOnRefreshListener((WXRefresh) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setHeaderView(child);
}
}, 100);
} else if (child instanceof WXLoading) {
getHostView().setOnLoadingListener((WXLoading) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setFooterView(child);
}
}, 100);
}
} else {
super.createChildViewAt(indexToCreate);
}
}
public void remove(WXComponent child, boolean destroy) {
super.remove(child, destroy);
removeFooterOrHeader(child);
}
private void removeFooterOrHeader(WXComponent child) {
if (child instanceof WXLoading) {
getHostView().removeFooterView(child);
} else if (child instanceof WXRefresh) {
getHostView().removeHeaderView(child);
}
}
}
| android/sdk/src/main/java/com/taobao/weex/ui/component/list/WXListComponent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.taobao.weex.ui.component.list;
import android.content.Context;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.annotation.Component;
import com.taobao.weex.common.Constants;
import com.taobao.weex.dom.WXDomObject;
import com.taobao.weex.dom.WXRecyclerDomObject;
import com.taobao.weex.dom.flex.Spacing;
import com.taobao.weex.ui.component.WXBaseRefresh;
import com.taobao.weex.ui.component.WXBasicComponentType;
import com.taobao.weex.ui.component.WXComponent;
import com.taobao.weex.ui.component.WXComponentProp;
import com.taobao.weex.ui.component.WXLoading;
import com.taobao.weex.ui.component.WXRefresh;
import com.taobao.weex.ui.component.WXVContainer;
import com.taobao.weex.ui.view.listview.WXRecyclerView;
import com.taobao.weex.ui.view.listview.adapter.ListBaseViewHolder;
import com.taobao.weex.ui.view.refresh.wrapper.BounceRecyclerView;
import com.taobao.weex.utils.WXLogUtils;
import java.util.Map;
/**
* Unlike other components, there is immutable bi-directional association between View and
* ViewHolder, while only mutable and temporal uni-directional association between view and
* components. The association only exist from {@link #onBindViewHolder(ListBaseViewHolder, int)} to
* {@link #onViewRecycled(ListBaseViewHolder)}. In other situations, the association may not valid
* or not even exist.
*/
@Component(lazyload = false)
public class WXListComponent extends BasicListComponent<BounceRecyclerView> {
private String TAG = "WXListComponent";
private WXRecyclerDomObject mDomObject;
private float mPaddingLeft;
private float mPaddingRight;
@Deprecated
public WXListComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy) {
this(instance, dom, parent, isLazy);
}
public WXListComponent(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy) {
super(instance, node, parent);
if (node != null && node instanceof WXRecyclerDomObject) {
mDomObject = (WXRecyclerDomObject) node;
mDomObject.preCalculateCellWidth();
if(WXBasicComponentType.WATERFALL.equals(node.getType())){
mLayoutType = WXRecyclerView.TYPE_STAGGERED_GRID_LAYOUT;
}else{
mLayoutType = mDomObject.getLayoutType();
}
updateRecyclerAttr();
}
}
@Override
protected BounceRecyclerView generateListView(Context context, int orientation) {
return new BounceRecyclerView(context,mLayoutType,mColumnCount,mColumnGap,orientation);
}
@Override
public void addChild(WXComponent child, int index) {
super.addChild(child, index);
if (child == null || index < -1) {
return;
}
setRefreshOrLoading(child);
// Synchronize DomObject's attr to Component and Native View
if(mDomObject.getColumnWidth() != mColumnWidth ||
mDomObject.getColumnCount() != mColumnCount ||
mDomObject.getColumnGap() != mColumnGap) {
updateRecyclerAttr();
getHostView().getInnerView().initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation());
}
}
/**
* Setting refresh view and loading view
*
* @param child the refresh_view or loading_view
*/
private boolean setRefreshOrLoading(final WXComponent child) {
if (getHostView() == null) {
WXLogUtils.e(TAG, "setRefreshOrLoading: HostView == null !!!!!! check list attr has append =tree");
return true;
}
if (child instanceof WXRefresh) {
getHostView().setOnRefreshListener((WXRefresh) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setHeaderView(child);
}
}, 100);
return true;
}
if (child instanceof WXLoading) {
getHostView().setOnLoadingListener((WXLoading) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setFooterView(child);
}
}, 100);
return true;
}
return false;
}
private void updateRecyclerAttr(){
mColumnCount = mDomObject.getColumnCount();
mColumnGap = mDomObject.getColumnGap();
mColumnWidth = mDomObject.getColumnWidth();
mPaddingLeft =mDomObject.getPadding().get(Spacing.LEFT);
mPaddingRight =mDomObject.getPadding().get(Spacing.RIGHT);
}
@WXComponentProp(name = Constants.Name.COLUMN_WIDTH)
public void setColumnWidth(int columnCount) {
if(mDomObject.getColumnWidth() != mColumnWidth){
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation());
}
}
@WXComponentProp(name = Constants.Name.COLUMN_COUNT)
public void setColumnCount(int columnCount){
if(mDomObject.getColumnCount() != mColumnCount){
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation());
}
}
@WXComponentProp(name = Constants.Name.COLUMN_GAP)
public void setColumnGap(float columnGap) throws InterruptedException {
if(mDomObject.getColumnGap() != mColumnGap) {
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType, mColumnCount, mColumnGap, getOrientation());
}
}
@WXComponentProp(name = Constants.Name.SCROLLABLE)
public void setScrollable(boolean scrollable) {
WXRecyclerView inner = getHostView().getInnerView();
inner.setScrollable(scrollable);
}
@Override
public void updateProperties(Map<String, Object> props) {
super.updateProperties(props);
if(props.containsKey(Constants.Name.PADDING)
||props.containsKey(Constants.Name.PADDING_LEFT)
|| props.containsKey(Constants.Name.PADDING_RIGHT)){
if(mPaddingLeft !=mDomObject.getPadding().get(Spacing.LEFT)
|| mPaddingRight !=mDomObject.getPadding().get(Spacing.RIGHT)) {
markComponentUsable();
updateRecyclerAttr();
WXRecyclerView wxRecyclerView = getHostView().getInnerView();
wxRecyclerView.initView(getContext(), mLayoutType, mColumnCount, mColumnGap, getOrientation());
}
}
}
@Override
public void createChildViewAt(int index) {
int indexToCreate = index;
if (indexToCreate < 0) {
indexToCreate = childCount() - 1;
if (indexToCreate < 0) {
return;
}
}
final WXComponent child = getChild(indexToCreate);
if (child instanceof WXBaseRefresh) {
child.createView();
if (child instanceof WXRefresh) {
getHostView().setOnRefreshListener((WXRefresh) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setHeaderView(child);
}
}, 100);
} else if (child instanceof WXLoading) {
getHostView().setOnLoadingListener((WXLoading) child);
getHostView().postDelayed(new Runnable() {
@Override
public void run() {
getHostView().setFooterView(child);
}
}, 100);
}
} else {
super.createChildViewAt(indexToCreate);
}
}
public void remove(WXComponent child, boolean destroy) {
super.remove(child, destroy);
removeFooterOrHeader(child);
}
private void removeFooterOrHeader(WXComponent child) {
if (child instanceof WXLoading) {
getHostView().removeFooterView(child);
} else if (child instanceof WXRefresh) {
getHostView().removeHeaderView(child);
}
}
}
| * [android] fix NPE
| android/sdk/src/main/java/com/taobao/weex/ui/component/list/WXListComponent.java | * [android] fix NPE | <ide><path>ndroid/sdk/src/main/java/com/taobao/weex/ui/component/list/WXListComponent.java
<ide> setRefreshOrLoading(child);
<ide>
<ide> // Synchronize DomObject's attr to Component and Native View
<del> if(mDomObject.getColumnWidth() != mColumnWidth ||
<del> mDomObject.getColumnCount() != mColumnCount ||
<del> mDomObject.getColumnGap() != mColumnGap) {
<add> if(mDomObject != null && getHostView() != null && (mColumnWidth != mDomObject.getColumnWidth() ||
<add> mColumnCount != mDomObject.getColumnCount() ||
<add> mColumnGap != mDomObject.getColumnGap())) {
<ide> updateRecyclerAttr();
<ide> getHostView().getInnerView().initView(getContext(), mLayoutType,mColumnCount,mColumnGap,getOrientation());
<ide> }
<ide> }
<del>
<ide>
<ide> /**
<ide> * Setting refresh view and loading view |
|
Java | apache-2.0 | 49b7e02fb4e237281bd6bb300cdbe0b5add58e2b | 0 | oasisfeng/deagle | package com.oasisfeng.android.os;
import android.os.Parcel;
import android.os.Process;
import android.os.UserHandle;
import android.util.Pair;
import com.oasisfeng.android.annotation.AppIdInt;
import com.oasisfeng.android.annotation.UserIdInt;
import androidx.annotation.VisibleForTesting;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.N;
/**
* Created by Oasis on 2018-9-6.
*/
public class UserHandles {
public static final UserHandle MY_USER_HANDLE = Process.myUserHandle();
public static final int MY_USER_ID = getIdentifier(Process.myUserHandle());
@VisibleForTesting static Pair<Integer, UserHandle> sCache = null; // Must before SYSTEM. TODO: Support multiple profiles.
/**
* Enable multi-user related side effects. Set this to false if
* there are problems with single user use-cases.
*/
private static final boolean MU_ENABLED = true;
/**
* Range of uids allocated for a user.
*/
private static final int PER_USER_RANGE = 100000;
/** A user id constant to indicate the "system" user of the device */
public static final @UserIdInt int USER_SYSTEM = 0;
/** A user handle to indicate the "system" user of the device */
public static final UserHandle SYSTEM = from(USER_SYSTEM);
public static UserHandle getUserHandleForUid(final int uid) {
return SDK_INT >= N ? UserHandle.getUserHandleForUid(uid) : of(getUserId(uid));
}
public static UserHandle of(final @UserIdInt int user_id) {
if (user_id == USER_SYSTEM) return SYSTEM;
final Pair<Integer, UserHandle> cache = sCache;
if (cache != null && cache.first == user_id) return cache.second;
final UserHandle user = from(user_id);
sCache = new Pair<>(user_id, user);
return user;
}
private static UserHandle from(final @UserIdInt int user_id) {
if (MY_USER_HANDLE.hashCode() == user_id) return MY_USER_HANDLE;
final Parcel parcel = Parcel.obtain();
try {
final int begin = parcel.dataPosition();
parcel.writeInt(user_id);
parcel.setDataPosition(begin);
return UserHandle.CREATOR.createFromParcel(parcel);
} finally {
parcel.recycle();
}
}
/**
* Returns the user id for a given uid.
*/
public static @UserIdInt int getUserId(final int uid) {
if (MU_ENABLED) {
return uid / PER_USER_RANGE;
} else {
return USER_SYSTEM;
}
}
/**
* Returns the app id (or base uid) for a given uid, stripping out the user id from it.
*/
public static @AppIdInt int getAppId(final int uid) {
return uid % PER_USER_RANGE;
}
/**
* Returns the uid that is composed from the userId and the appId.
*/
public static int getUid(final @UserIdInt int userId, final @AppIdInt int appId) {
if (MU_ENABLED) {
return userId * PER_USER_RANGE + (appId % PER_USER_RANGE);
} else {
return appId;
}
}
/**
* Returns the userId stored in this UserHandle. (same as UserHandle.getIdentifier())
*/
public static int getIdentifier(final UserHandle handle) {
return handle.hashCode(); // So far so good
}
}
| library/src/main/java/com/oasisfeng/android/os/UserHandles.java | package com.oasisfeng.android.os;
import android.os.Parcel;
import android.os.Process;
import android.os.UserHandle;
import android.util.Pair;
import com.oasisfeng.android.annotation.AppIdInt;
import com.oasisfeng.android.annotation.UserIdInt;
import androidx.annotation.VisibleForTesting;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.N;
/**
* Created by Oasis on 2018-9-6.
*/
public class UserHandles {
private static final UserHandle MY_USER_HANDLE = Process.myUserHandle();
@VisibleForTesting static Pair<Integer, UserHandle> sCache = null; // Must before SYSTEM
/**
* Enable multi-user related side effects. Set this to false if
* there are problems with single user use-cases.
*/
private static final boolean MU_ENABLED = true;
/**
* Range of uids allocated for a user.
*/
private static final int PER_USER_RANGE = 100000;
/** A user id constant to indicate the "system" user of the device */
public static final @UserIdInt int USER_SYSTEM = 0;
/** A user handle to indicate the "system" user of the device */
public static final UserHandle SYSTEM = from(USER_SYSTEM);
public static UserHandle getUserHandleForUid(final int uid) {
return SDK_INT >= N ? UserHandle.getUserHandleForUid(uid) : of(getUserId(uid));
}
public static UserHandle of(final @UserIdInt int user_id) {
if (user_id == USER_SYSTEM) return SYSTEM;
final Pair<Integer, UserHandle> cache = sCache;
if (cache != null && cache.first == user_id) return cache.second;
final UserHandle user = from(user_id);
sCache = new Pair<>(user_id, user);
return user;
}
private static UserHandle from(final @UserIdInt int user_id) {
if (MY_USER_HANDLE.hashCode() == user_id) return MY_USER_HANDLE;
final Parcel parcel = Parcel.obtain();
try {
final int begin = parcel.dataPosition();
parcel.writeInt(user_id);
parcel.setDataPosition(begin);
return UserHandle.CREATOR.createFromParcel(parcel);
} finally {
parcel.recycle();
}
}
/**
* Returns the user id for a given uid.
*/
public static @UserIdInt int getUserId(final int uid) {
if (MU_ENABLED) {
return uid / PER_USER_RANGE;
} else {
return USER_SYSTEM;
}
}
/**
* Returns the app id (or base uid) for a given uid, stripping out the user id from it.
*/
public static @AppIdInt int getAppId(final int uid) {
return uid % PER_USER_RANGE;
}
}
| UPDATE: Make UserHandles.MY_USER_HANDLE public, together with new MY_USER_ID.
| library/src/main/java/com/oasisfeng/android/os/UserHandles.java | UPDATE: Make UserHandles.MY_USER_HANDLE public, together with new MY_USER_ID. | <ide><path>ibrary/src/main/java/com/oasisfeng/android/os/UserHandles.java
<ide> */
<ide> public class UserHandles {
<ide>
<del> private static final UserHandle MY_USER_HANDLE = Process.myUserHandle();
<del> @VisibleForTesting static Pair<Integer, UserHandle> sCache = null; // Must before SYSTEM
<add> public static final UserHandle MY_USER_HANDLE = Process.myUserHandle();
<add> public static final int MY_USER_ID = getIdentifier(Process.myUserHandle());
<add>
<add> @VisibleForTesting static Pair<Integer, UserHandle> sCache = null; // Must before SYSTEM. TODO: Support multiple profiles.
<ide>
<ide> /**
<ide> * Enable multi-user related side effects. Set this to false if
<ide> public static @AppIdInt int getAppId(final int uid) {
<ide> return uid % PER_USER_RANGE;
<ide> }
<add>
<add> /**
<add> * Returns the uid that is composed from the userId and the appId.
<add> */
<add> public static int getUid(final @UserIdInt int userId, final @AppIdInt int appId) {
<add> if (MU_ENABLED) {
<add> return userId * PER_USER_RANGE + (appId % PER_USER_RANGE);
<add> } else {
<add> return appId;
<add> }
<add> }
<add>
<add> /**
<add> * Returns the userId stored in this UserHandle. (same as UserHandle.getIdentifier())
<add> */
<add> public static int getIdentifier(final UserHandle handle) {
<add> return handle.hashCode(); // So far so good
<add> }
<ide> } |
|
JavaScript | mit | fbeb415ad4c11dbe9c88e446890f5d677a1e110b | 0 | NekR/webpack,NekR/webpack,webpack/webpack,webpack/webpack,SimenB/webpack,webpack/webpack,EliteScientist/webpack,EliteScientist/webpack,SimenB/webpack,SimenB/webpack,SimenB/webpack,webpack/webpack | module.exports = {
env: {
mocha: true
}
};
| test/.eslintrc.js | module.exports = {
"env": {
"mocha": true,
}
};
| Prettify
| test/.eslintrc.js | Prettify | <ide><path>est/.eslintrc.js
<ide> module.exports = {
<del> "env": {
<del> "mocha": true,
<add> env: {
<add> mocha: true
<ide> }
<ide> }; |
|
JavaScript | mit | 1512ae1d30f3aed2075b205cb1367898c789b755 | 0 | HoeenCoder/SpacialGaze,HoeenCoder/SpacialGaze,HoeenCoder/SpacialGaze,HoeenCoder/SpacialGaze | 'use strict';
exports.BattleMovedex = {
"acidbubble": {
id: "acidbubble",
name: "Acid Bubble",
basePower: 30,
category: "Special",
secondary: false,
priority: 0,
target: "any",
pp: 40,
shortDesc: "No additional effects.",
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Bubble');
},
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Bubble", target);
},
accuracy: 100,
type: "Ice",
},
"firetower": {
id: "firetower",
name: "Fire Tower",
basePower: 65,
category: "Physical",
secondary: {
chance: 25,
volatileStatus: "flinch",
},
priority: 0,
target: "any",
pp: 20,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Inferno", target);
this.add('-anim', source, "Precipice Blades", target);
},
shortDesc: "25% chance to flinch.",
accuracy: 100,
type: "Fire",
},
"prominencebeam": {
id: "prominencebeam",
name: "Prominence Beam",
basePower: 105,
category: "Special",
secondary: {
self: {
chance: 20,
boosts: {
spa: -2,
atk: -2,
},
},
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flamethrower", target);
},
priority: 0,
target: "any",
pp: 5,
desc: "Has a 20% chance to lower the user's Attack and Special Attack by two stages.",
shortDesc: "20% chance to lower user's Atk & SpA by 2.",
flags: {protect: 1, distance: 1},
accuracy: 100,
type: "Fire",
},
"spitfire": {
id: "spitfire",
name: "Spit Fire",
basePower: 45,
category: "Special",
secondary: false,
priority: 0,
target: "any",
pp: 25,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flamethrower", target);
},
shortDesc: "No additional effects.",
accuracy: 100,
type: "Fire",
},
"redinferno": {
id: "redinferno",
name: "Red Inferno",
basePower: 75,
category: "Special",
secondary: false,
priority: 0,
target: "allAdjacentFoes",
pp: 15,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fire Blast", target);
},
shortDesc: "No additional effects.",
accuracy: 100,
type: "Fire",
},
"magmabomb": {
id: "magmabomb",
name: "Magma Bomb",
basePower: 85,
category: "Physical",
secondary: {
chance: 25,
volatileStatus: "panic",
},
priority: 0,
target: "any",
pp: 15,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Egg Bomb", target);
this.add('-anim', source, "Sunny Day", target);
},
shortDesc: "25% chance to cause the target to panic.",
accuracy: 100,
type: "Fire",
},
"heatlaser": {
id: "heatlaser",
name: "Heat Laser",
basePower: 55,
category: "Special",
secondary: {
chance: 50,
boosts: {
spa: -3,
atk: -3,
},
},
priority: 0,
target: "allAdjacent",
pp: 30,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Roar", target);
this.add('-anim', source, "Sunny Day", target);
},
desc: "Has a 50% chance to lower the target's Attack and Special Attack by three stages.",
shortDesc: "50% chance to lower Atk & SpA by 3.",
accuracy: 100,
type: "Fire",
},
"infinityburn": {
id: "infinityburn",
name: "Infinity Burn",
basePower: 110,
accuracy: 100,
pp: 5,
target: "any",
priority: 0,
secondary: {
chance: 5,
volatileStatus: "flinch",
},
category: "Physical",
flags: {protect: 1, mirror: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Inferno", target);
this.add('-anim', source, "Precipice Blades", target);
},
desc: "5% chance to flinch.",
type: "Fire",
},
"meltdown": {
id: "meltdown",
name: "Meltdown",
basePower: 95,
accuracy: 100,
pp: 5,
target: "allAdjacent",
priority: 0,
secondary: {
chance: 10,
volatileStatus: "flinch",
},
category: "Special",
flags: {protect: 1, mirror: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sunny Day", target);
this.add('-anim', source, "Lava Plume", target);
},
desc: "10% chance to flinch.",
type: "Fire",
},
"tremar": {
id: "tremar",
name: "Tremar",
basePower: 75,
accuracy: 85,
pp: 20,
target: "allAdjacent",
priority: 0,
secondary: false,
category: "Physical",
flags: {protect: 1, mirror: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ancient Power", target);
},
shortDesc: "No additional effects.",
type: "Battle",
},
"musclecharge": {
id: "musclecharge",
name: "Muscle Charge",
basePower: 0,
accuracy: 100,
pp: 25,
boosts: {
atk: 2,
spa: 2,
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
},
target: "self",
priority: 0,
secondary: false,
category: "Status",
flags: {snatch: 1},
shortDesc: "Raises the user's Atk & SpA by 2.",
type: "Battle",
},
"warcry": {
id: "warcry",
name: "War Cry",
basePower: 0,
secondary: false,
category: "Status",
pp: 30,
accuracy: 100,
boosts: {
atk: 1,
def: 1,
spa: 1,
spd: 1,
spe: 1,
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Dragon Dance", source);
},
shortDesc: "Raises all user's stats by 1 (except eva & acc).",
priority: 0,
flags: {snatch: 1},
target: "self",
type: "Battle",
},
"sonicjab": {
id: "sonicjab",
name: "Sonic Jab",
basePower: 65,
category: "Physical",
accuracy: 100,
secondary: false,
priority: 0,
flags: {protect: 1, contact: 1, punch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Dizzy Punch", target);
},
shortDesc: "No additional effects.",
pp: 40,
target: "normal",
type: "Battle",
},
"dynamitekick": {
id: "dynamitekick",
name: "Dynamite Kick",
basePower: 85,
accuracy: 100,
pp: 5,
category: "Special",
secondary: {
chance: 20,
volatileStatus: "flinch",
},
priority: 0,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Mega Kick", target);
},
shortDesc: "20% chance to flinch.",
target: "normal",
type: "Battle",
},
"reboundstrike": {
id: "reboundstrike",
name: "Rebound Strike",
basePower: 95,
secondary: {
chance: 30,
volatileStatus: "panic",
},
damageCallback: function (pokemon) {
if (!pokemon.volatiles['counter']) return 0;
return pokemon.volatiles['counter'].damage || 1;
},
category: "Physical",
pp: 20,
priority: -5,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Headbutt", target);
},
beforeTurnCallback: function (pokemon) {
pokemon.addVolatile('counter');
},
onTryHit: function (target, source, move) {
if (!source.volatiles['counter']) return false;
if (source.volatiles['counter'].position === null) return false;
},
effect: {
duration: 1,
noCopy: true,
onStart: function (target, source, source2, move) {
this.effectData.position = null;
this.effectData.damage = 0;
},
onRedirectTargetPriority: -1,
onRedirectTarget: function (target, source, source2) {
if (source !== this.effectData.target) return;
return source.side.foe.active[this.effectData.position];
},
onDamagePriority: -101,
onDamage: function (damage, target, source, effect) {
if (effect && effect.effectType === 'Move' && source.side !== target.side && this.getCategory(effect) === 'Physical') {
this.effectData.position = source.position;
this.effectData.damage = 2 * damage;
}
},
},
desc: "Deals damage to the last foe to hit the user with a physical attack this turn equal to twice the HP lost by the user from that attack. If the user did not lose HP from the attack, this move deals damage with a Base Power of 1 instead. If that foe's position is no longer in use, the damage is done to a random foe in range. Only the last hit of a multi-hit attack is counted. Fails if the user was not hit by a foe's physical attack this turn. 30% chance to make the target panic.",
shortDesc: "If hit by physical attack, returns double damage. 30% chance to panic.",
target: "normal",
type: "Battle",
},
"megatonpunch": {
id: "megatonpunch",
name: "Megaton Punch",
basePower: 105,
category: "Physical",
accuracy: 100,
pp: 10,
secondary: {
chance: 15,
volatileStatus: "flinch",
},
flags: {protect: 1, contact: 1, punch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Dizzy Punch", target);
},
shortDesc: "15% chance to flinch.",
priority: 0,
target: "normal",
type: "Battle",
},
"busterdrive": {
id: "busterdrive",
name: "Buster Drive",
basePower: 110,
secondary: {
chance: 5,
volatileStatus: "panic",
},
category: "Physical",
pp: 5,
accuracy: 100,
flags: {protect: 1, contact: 1, distance: 1, punch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fire Punch", target);
},
shortDesc: "5% chance to make the target panic.",
priority: 0,
target: "any",
type: "Battle",
},
"thunderjustice": {
id: "thunderjustice",
name: "Thunder Justice",
basePower: 105,
accuracy: true,
pp: 5,
category: "Special",
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thunder", target);
},
secondary: {
chance: 5,
volatileStatus: "flinch",
},
shortDesc: "5% chance to flinch.",
type: "Air",
target: "any",
},
"spinningshot": {
id: "spinningshot",
name: "Spinning Shot",
basePower: 110,
pp: 10,
accuracy: 100,
secondary: false,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Air Cutter", target);
},
category: "Special",
type: "Air",
shortDesc: "No additional effects.",
target: "allAdjacent",
},
"electriccloud": {
id: "electriccloud",
name: "Electric Cloud",
basePower: 55,
category: "Special",
secondary: {
chance: 40,
volatileStatus: "flinch",
},
shortDesc: "40% chance to flinch.",
accuracy: true,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thundershock", target);
},
priority: 0,
pp: 20,
type: "Air",
target: "any",
},
"megalospark": {
id: "megalospark",
name: "Megalo Spark",
basePower: 95,
secondary: {
chance: 15,
volatileStatus: "flinch",
},
accuracy: 100,
pp: 15,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Shock Wave", target);
},
shortDesc: "15% chance to flinch.",
category: "Physical",
target: "any",
type: "Air",
},
"staticelect": {
id: "staticelect",
name: "Static Elect",
basePower: 45,
accuracy: 100,
pp: 40,
secondary: {
chance: 50,
volatileStatus: "flinch",
},
priority: 0,
flags: {protect: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thunder Punch", target);
},
shortDesc: "50% chance to flinch.",
category: "Physical",
target: "normal",
type: "Air",
},
"windcutter": {
id: "windcutter",
name: "Wind Cutter",
basePower: 65,
accuracy: 100,
category: "Special",
secondary: false,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Gust", target);
},
shortDesc: "No additional effects.",
pp: 15,
target: "any",
type: "Air",
},
"confusedstorm": {
id: "confusedstorm",
name: "Confused Storm",
basePower: 75,
secondary: {
self: {
volatileStatus: "confusion",
},
chance: 20,
volatileStatus: "panic",
},
accuracy: 100,
category: "Special",
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Prismatic Laser", target);
},
shortDesc: "20% chance to make target panic; confuses the user.",
pp: 10,
target: "allAdjacent",
type: "Air",
},
"typhoon": {
id: "typhoon",
name: "Typhoon",
basePower: 85,
secondary: {
chance: 15,
volatileStatus: "panic",
},
category: "Special",
pp: 10,
accuracy: 100,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hurricane", target);
},
shortDesc: "15% chance to make the target panic.",
target: "allAdjacent",
type: "Air",
},
"toxicpowder": {
id: "toxicpowder",
name: "Toxic Powder",
basePower: 65,
pp: 15,
category: "Special",
secondary: {
chance: 50,
status: "psn",
},
accuracy: 100,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Powder", target);
},
desc: "50% chance to poison the target.",
target: "allAdjacent",
type: "Earth",
},
"bug": {
id: "bug",
name: "Bug",
basePower: 110,
accuracy: 100,
secondary: {
chance: 5,
boosts: {
atk: -3,
spa: -3,
},
},
category: "Physical",
pp: 5,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Magnet Bomb", target);
},
shortDesc: "5% chance to lower target's Atk & SpA by 1.",
target: "any",
type: "Earth",
},
"massmorph": {
id: "massmorph",
name: "Mass Morph",
basePower: 0,
category: "Status",
boosts: {
atk: 1,
def: 2,
spa: 1,
spd: 1,
spe: 1,
accuracy: 1,
},
desc: "Boosts all stats by 1 (except evasion); Def by 2.",
accuracy: 100,
pp: 40,
priority: 0,
secondary: false,
flags: {snatch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Cotton Guard", source);
},
target: "self",
type: "Earth",
},
"insectplague": {
id: "insectplague",
name: "Insect Plague",
basePower: 95,
accuracy: 100,
category: "Special",
pp: 10,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Toxic", target);
},
secondary: {
chance: 40,
status: "psn",
},
shortDesc: "40% chance to poison.",
target: "any",
type: "Earth",
},
"charmperfume": {
id: "charmperfume",
name: "Charm Perfume",
basePower: 95,
secondary: {
chance: 40,
volatileStatus: "panic",
},
category: "Special",
pp: 15,
accuracy: 100,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Gas", target);
},
shortDesc: "40% chance to make the target panic.",
target: "allAdjacent",
type: "Earth",
},
"poisonclaw": {
id: "poisonclaw",
name: "Poison Claw",
basePower: 55,
category: "Physical",
secondary: {
chance: 50,
status: "psn",
},
pp: 40,
accuracy: 100,
priority: 0,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Jab", target);
},
shortDesc: "50% chance to poison.",
target: "normal",
type: "Earth",
},
"dangersting": {
id: "dangersting",
name: "Danger Sting",
basePower: 75,
accuracy: 100,
category: "Physical",
pp: 15,
secondary: {
chance: 35,
boosts: {
atk: -3,
spa: -3,
},
},
priority: 0,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Sting", target);
},
shortDesc: "35% chance to lower Atk & SpA by 3.",
target: "normal",
type: "Earth",
},
"greentrap": {
id: "greentrap",
name: "Green Trap",
basePower: 105,
accuracy: 100,
pp: 10,
secondary: {
chance: 15,
volatileStatus: "flinch",
},
category: "Physical",
flags: {protect: 1, contact: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Grass Knot", target);
},
shortDesc: "15% chance to flinch.",
priority: 0,
target: "any",
type: "Earth",
},
"gigafreeze": {
id: "gigafreeze",
name: "Giga Freeze",
basePower: 95,
category: "Physical",
pp: 10,
secondary: {
chance: 20,
volatileStatus: "flinch",
},
accuracy: 100,
flags: {protect: 1, contact: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Frost Breath", target);
},
shortDesc: "20% chance to flinch.",
priority: 0,
target: "allAdjacentFoes",
type: "Ice",
},
"icestatue": {
id: "icestatue",
name: "Ice Statue",
basePower: 105,
accuracy: 100,
pp: 10,
secondary: {
chance: 10,
volatileStatus: "flinch",
},
category: "Physical",
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Avalanche", target);
},
shortDesc: "10% chance to flinch.",
priority: 0,
target: "any",
type: "Ice",
},
"winterblast": {
id: "winterblast",
name: "Winter Blast",
basePower: 65,
accuracy: 100,
secondary: {
chance: 30,
volatileStatus: "flinch",
},
category: "Special",
pp: 10,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Blizzard", target);
},
shortDesc: "30% chance to flinch.",
target: "allAdjacent",
type: "Ice",
},
"iceneedle": {
id: "iceneedle",
name: "Ice Needle",
basePower: 75,
accuracy: 50,
secondary: {
chance: 35,
volatileStatus: "flinch",
},
category: "Physical",
pp: 20,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ice Shard", target);
},
shortDesc: "35% chance to flinch.",
priority: 0,
target: "any",
type: "Ice",
},
"waterblit": {
id: "waterblit",
name: "Water Blit",
basePower: 85,
accuracy: 100,
category: "Special",
pp: 20,
secondary: false,
priority: 0,
flags: {protect: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Aqua Ring", target);
},
shortDesc: "No additional effects.",
target: "normal",
type: "Ice",
},
"aquamagic": {
id: "aquamagic",
name: "Aqua Magic",
basePower: 0,
accuracy: 100,
boosts: {
atk: 1,
def: 1,
spa: 1,
spd: 1,
spe: 1,
},
pp: 20,
secondary: false,
priority: 0,
flags: {snatch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Bubble", source);
},
shortDesc: "Raises all stats by 1 (except acc and eva).",
target: "self",
type: "Ice",
},
"aurorafreeze": {
id: "aurorafreeze",
name: "Aurora Freeze",
basePower: 110,
accuracy: 100,
category: "Special",
secondary: {
chance: 10,
boosts: {
atk: -3,
spa: -3,
},
},
pp: 10,
onTry: function (attacker, defender, move) {
if (attacker.removeVolatile(move.id)) {
return;
}
this.add('-prepare', attacker, move.name, defender);
if (!this.runEvent('ChargeMove', attacker, defender, move)) {
this.add('-anim', attacker, move.name, defender);
return;
}
attacker.addVolatile('twoturnmove', defender);
return null;
},
priority: 0,
flags: {protect: 1, charge: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Moonlight", target);
this.add('-anim', source, "Power Gem", target);
},
shortdesc: "10% chance to lower Atk & SpA by 3.",
target: "allAdjacent",
type: "Ice",
},
"teardrop": {
id: "teardrop",
name: "Tear Drop",
basePower: 55,
accuracy: 90,
secondary: {
chance: 50,
boosts: {
atk: -3,
spa: -3,
},
},
pp: 40,
category: "Special",
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Water Pulse", target);
},
shortdesc: "50% chance to lower Atk & SpA by 3.",
target: "any",
type: "Ice",
},
"powercrane": {
id: "powercrane",
name: "Power Crane",
basePower: 65,
accuracy: 100,
secondary: false,
category: "Physical",
pp: 15,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Metal Claw", target);
},
shortDesc: "No additional effects.",
target: "any",
type: "Mech",
},
"allrangebeam": {
id: "allrangebeam",
name: "All-Range Beam",
basePower: 105,
pp: 5,
accuracy: 100,
category: "Special",
priority: 0,
secondary: false,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Gear Up", target);
this.add('-anim', source, "Hyper Beam", target);
},
shortDesc: "No additional effects.",
target: "allAdjacent",
type: "Mech",
},
"metalsprinter": {
id: "metalsprinter",
name: "Metal Sprinter",
basePower: 55,
accuracy: 100,
category: "Physical",
secondary: false,
pp: 10,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Metal Burst", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "allAdjacent",
type: "Mech",
},
"pulselazer": {
id: "pulselazer",
name: "Pulse Lazer",
basePower: 85,
accuracy: 100,
category: "Special",
pp: 10,
secondary: false,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flash Cannon", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"deleteprogram": {
id: "deleteprogram",
name: "Delete Program",
basePower: 95,
accuracy: 100,
category: "Special",
pp: 10,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flash Cannon", target);
},
secondary: {
chance: 10,
boosts: {
atk: -3,
spa: -3,
},
},
shortDesc: "10% chance to lower Atk & SpA by 3.",
priority: 0,
target: "any",
type: "Mech",
},
"dgdimension": {
id: "dgdimension",
name: "DG Dimension",
basePower: 110,
category: "Special",
pp: 5,
accuracy: 100,
secondary: false,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Moonlight", target);
this.add('-anim', source, "Sonic Boom", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"fullpotential": {
id: "fullpotential",
name: "Full Potential",
basePower: 0,
accuracy: 0,
category: "Status",
pp: 20,
boosts: {
atk: 2,
def: 2,
spa: 2,
spd: 2,
spe: 2,
},
secondary: false,
flags: {snatch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Gear Grind", target);
},
priority: 0,
shortDesc: "Raises all stats by 2 (except acc and eva).",
target: "self",
type: "Mech",
},
"reverseprogram": {
id: "reverseprogram",
name: "Reverse Program",
basePower: 75,
accuracy: 100,
category: "Special",
pp: 5,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Lock-On", target);
this.add('-anim', source, "Wake-Up Slap", target);
},
secondary: {
chance: 20,
boosts: {
atk: -3,
spa: -3,
},
},
shortDesc: "20% chance to lower Atk & SpA by 3.",
priority: 0,
target: "any",
type: "Mech",
},
"orderspray": {
id: "orderspray",
name: "Order Spray",
basePower: 65,
category: "Special",
pp: 40,
secondary: {
chance: 50,
volatileStatus: "flinch",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Gas", target);
},
shortDesc: "50% chance to flinch.",
priority: 0,
target: "any",
type: "Filth",
},
"poopspdtoss": {
id: "poopspdtoss",
name: "Poop Spd Toss",
basePower: 75,
category: "Physical",
pp: 20,
secondary: {
chance: 30,
status: "psn",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Throw", target);
},
shortDesc: "30% chance to poison.",
priority: 0,
target: "any",
type: "Filth",
},
"bigpooptoss": {
id: "bigpooptoss",
name: "Big Poop Toss",
basePower: 95,
category: "Physical",
pp: 15,
secondary: {
chance: 30,
volatileStatus: "panic",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Wrecker", target);
},
shortDesc: "30% chance to make the target to panic.",
priority: 0,
target: "any",
type: "Filth",
},
"bigrndtoss": {
id: "bigrndtoss",
name: "Big Rnd Toss",
basePower: 105,
category: "Physical",
pp: 5,
secondary: {
chance: 30,
volatileStatus: "panic",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Tomb", target);
},
shortDesc: "30% chance to make the target panic.",
priority: 0,
target: "allAdjacentFoes",
type: "Filth",
},
"pooprndtoss": {
id: "pooprndtoss",
name: "Poop RND Toss",
basePower: 55,
category: "Physical",
pp: 15,
secondary: {
chance: 40,
status: "psn",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Slide", target);
},
shortDesc: "40% chance to poison.",
priority: 0,
target: "allAdjacent",
type: "Filth",
},
"rndspdtoss": {
id: "rndspdtoss",
name: "Rnd Spd Toss",
basePower: 75,
category: "Physical",
pp: 10,
secondary: {
chance: 30,
status: "psn",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Blast", target);
},
shortDesc: "30% chance to poison.",
priority: 0,
target: "allAdjacent",
type: "Filth",
},
"horizontalkick": {
id: "horizontalkick",
name: "Horizontal Kick",
basePower: 45,
category: "Special",
pp: 5,
accuracy: 100,
secondary: false,
flags: {protect: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Gas", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "normal",
type: "Filth",
},
"ultpoophell": {
id: "ultpoophell",
name: "Ult Poop Hell",
basePower: 110,
category: "Physical",
pp: 5,
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Stone Edge", target);
},
secondary: {
chance: 10,
boosts: {
atk: -3,
spa: -3,
},
},
shortDesc: "10% chance to lower Atk & SpA by 3.",
priority: 0,
target: "allAdjacent",
type: "Filth",
},
//Health Items
//Small Recovery
smallrecovery: {
accuracy: true,
basePower: 0,
category: "Status",
id: "smallrecovery",
isNonstandard: true,
name: "Small Recovery",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 4],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals 1/4 of max HP.",
},
//Medium Recovery
mediumrecovery: {
accuracy: true,
basePower: 0,
category: "Status",
id: "mediumrecovery",
isNonstandard: true,
name: "Medium Recovery",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 3],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals 1/3 of max HP.",
},
//Large Recovery
largerecovery: {
accuracy: true,
basePower: 0,
category: "Status",
id: "largerecovery",
isNonstandard: true,
name: "Large Recovery",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 2],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals 1/2 of max HP.",
},
//Super Recovery Floppy
superrecoveryfloppy: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superrecoveryfloppy",
isNonstandard: true,
name: "Super Recovery Floppy",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 1],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals all of user's HP.",
},
//Various
various: {
accuracy: true,
basePower: 0,
category: "Status",
id: "various",
isNonstandard: true,
name: "Various",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
onPrepareHit: function (pokemon, source) {
this.add('-activate', source, 'move: Various');
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
let side = pokemon.side;
for (let i = 0; i < side.pokemon.length; i++) {
side.pokemon[i].cureStatus();
}
},
desc: "Cures user of status conditions.",
secondary: false,
target: "adjacentAllyOrSelf",
},
//Protection
protection: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "For 5 turns, the user and its party members cannot have major status conditions or confusion inflicted on them by other Pokemon. It is removed from the user's side if the user or an ally is successfully hit by Defog.",
shortDesc: "For 5 turns, protects user's party from status.",
pp: 0.625,
priority: 0,
flags: {snatch: 1},
//safeguard effects = same effect for the Protection "item" in Digimon
sideCondition: 'safeguard',
effect: {
duration: 5,
durationCallback: function (target, source, effect) {
if (source && source.hasAbility('persistent')) {
return 7;
}
return 5;
},
onSetStatus: function (status, target, source, effect) {
if (source && target !== source && effect && (!effect.infiltrates || target.side === source.side)) {
this.debug('interrupting setStatus');
if (effect.id === 'synchronize' || (effect.effectType === 'Move' && !effect.secondaries)) {
this.add('-activate', target, 'move: Protection');
}
return null;
}
},
onTryAddVolatile: function (status, target, source, effect) {
if ((status.id === 'confusion' || status.id === 'yawn') && source && target !== source && effect && (!effect.infiltrates || target.side === source.side)) {
if (!effect.secondaries) this.add('-activate', target, 'move: Protection');
return null;
}
},
onStart: function (side) {
this.add('-sidestart', side, 'Protection');
},
onResidualOrder: 21,
onResidualSubOrder: 2,
onEnd: function (side) {
this.add('-sideend', side, 'Protection');
},
},
secondary: false,
target: "adjacentAllyOrSelf",
type: "Battle",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Safeguard", source);
},
},
//Omnipotent
omnipotent: {
accuracy: true,
basePower: 0,
category: "Status",
id: "omnipotent",
isNonstandard: true,
name: "Omnipotent",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
onPrepareHit: function (pokemon, source) {
pokemon.cureStatus();
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
secondary: false,
heal: [1, 1],
desc: "Heals all of the user's HP.",
target: "adjacentAllyOrSelf",
},
//Restore Floppy
restorefloppy: {
accuracy: true,
basePower: 0,
category: "Status",
id: "restorefloppy",
isNonstandard: true,
name: "Restore Floppy",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 2],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Restores 1/2 of the user's max HP.",
},
//Super Restore Floppy
superrestorefloppy: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superrestorefloppy",
isNonstandard: true,
name: "Super Restore Floppy",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 1],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Restores all of the user's max HP.",
},
//Stat Boosting Items
//Offense Disk
offensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "offensedisk",
isNonstandard: true,
name: "Offense Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
atk: 1,
spa: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Atk & SpA by 1.",
},
//Defense Disk
defensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "defensedisk",
isNonstandard: true,
name: "Defense Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spd: 1,
def: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Def & SpD by 1.",
},
//Hi Speed Disk
hispeeddisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "hispeeddisk",
isNonstandard: true,
name: "Hi Speed Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spe: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Spe by 1.",
},
//Super Defense Disk
superdefensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superdefensedisk",
isNonstandard: true,
name: "Super Defense Disk",
pp: 0.625,
priority: 0,
boosts: {
def: 2,
spd: 2,
},
flags: {snatch: 1, distance: 1},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Def & SpD by 2.",
},
//Super Offense Disk
superoffensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superoffensedisk",
isNonstandard: true,
name: "Super Offense Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spa: 2,
atk: 2,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Atk & SpA by 2.",
},
//Super Speed Disk
superspeeddisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superspeeddisk",
isNonstandard: true,
name: "Super Speed Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spe: 2,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Spe by 2.",
},
//Omnipotent Disk
omnipotentdisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "omnipotentdisk",
isNonstandard: true,
name: "Omnipotent Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
atk: 1,
def: 1,
spa: 1,
spd: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Atk, Def, SpA & SpD by 1.",
},
//Finishers
"pepperbreath": {
id: "pepperbreath",
name: "Pepper Breath",
basePower: 89,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Pepper Breath');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Inferno Overdrive", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"blueblaster": {
id: "blueblaster",
name: "Blue Blaster",
basePower: 90,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Blue Blaster');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Blue Flare", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"boombubble": {
id: "boombubble",
name: "Boom Bubble",
basePower: 85,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Boom Bubble');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Aeroblast", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"superthunderstrike": {
id: "superthunderstrike",
name: "Super Thunder Strike",
basePower: 100,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Super Thunder Strike');
},
shortDesc: "No additional effects.",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Gigavolt Havoc", target);
},
priority: 0,
target: "any",
type: "Air",
},
"spiraltwister": {
id: "spiraltwister",
name: "Spiral Twister",
basePower: 91,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Spiral Twister');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fire Spin", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"electricthread": {
id: "electricthread",
name: "Electric Thread",
basePower: 94,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Electric Thread');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Electroweb", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"poisonivy": {
id: "poisonivy",
name: "Poison Ivy",
basePower: 101,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Poison Ivy');
},
shortDesc: "No additional effects.",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Toxic", target);
},
priority: 0,
target: "any",
type: "Earth",
},
"electricshock": {
id: "electricshock",
name: "Electric Shock",
basePower: 92,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Electric Shock');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thunderbolt", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"superslap": {
id: "superslap",
name: "Super Slap",
basePower: 91,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1, contact: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Super Slap');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ice Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
// Champions
"megaflame": {
id: "megaflame",
name: "Mega Flame",
basePower: 196,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Mega Flame');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Overheat", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"volcanicstrike": {
id: "volcanicstrike",
name: "Volcanic Strike",
basePower: 160,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Volcanic Strike');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Eruption", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Fire",
},
"pummelwhack": {
id: "pummelwhack",
name: "Pummel Whack",
basePower: 170,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Pummel Whack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Wood Hammer", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"spinningneedle": {
id: "spinningneedle",
name: "Spinning Needle",
basePower: 152,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Spinning Needle');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Whirlwind", target);
this.add('-anim', source, "Ice Shard", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"scissorclaw": {
id: "scissorclaw",
name: "Scissor Claw",
basePower: 172,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Scissor Claw');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Smart Strike", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"blastingspout": {
id: "blastingspout",
name: "Blasting Spout",
basePower: 150,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Blastin Spout');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Water Spout", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"subzeroicepunch": {
id: "subzeroicepunch",
name: "Sub Zero Ice Punch",
basePower: 157,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Sub Zero Ice Punch');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Ice Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"partytime": {
id: "partytime",
name: "Party Time",
basePower: 100,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Party Time');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Continental Crush", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"fireball": {
id: "fireball",
name: "Fireball",
basePower: 155,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Fireball');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", source);
this.add('-anim', source, "Fire Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"drillspin": {
id: "drillspin",
name: "Drill Spin",
basePower: 150,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Drill Spin');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Drill Run", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"fistofthebeastking": {
id: "fistofthebeastking",
name: "Fist Of The Beast King",
basePower: 170,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Fist Of The Beast King');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Roar", target);
this.add('-anim', source, "Fire Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"frozenfireshot": {
id: "frozenfireshot",
name: "Frozen Fire Shot",
basePower: 159,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1, defrost: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Frozen Fire Shot');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Frost Breath", target);
this.add('-anim', source, "Stone Edge", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"sweetbreath": {
id: "sweetbreath",
name: "Sweet Breath",
basePower: 130,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Sweet Breath');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sweet Kiss", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"hydropressure": {
id: "hydropressure",
name: "Hydro Pressure",
basePower: 155,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Hydro Pressure');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hydro Pump", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"boneboomerang": {
id: "boneboomerang",
name: "Bone Boomerang",
basePower: 148,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Bone Boomerang');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Bonemerang", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"meteorwing": {
id: "meteorwing",
name: "Meteor Wing",
basePower: 158,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Meteor Wing');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Heat Wave", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"blazeblast": {
id: "blazeblast",
name: "Blaze Blast",
basePower: 174,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Blaze Blast');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Overheat", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"handoffate": {
id: "handoffate",
name: "Hand Of Fate",
basePower: 166,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Hand Of Fate');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Zap Cannon", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"aerialattack": {
id: "aerialattack",
name: "Aerial Attack",
basePower: 153,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Aerial Attack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Supersonic Skystrike", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"igaschoolthrowingknife": {
id: "igaschoolthrowingknife",
name: "Iga School Throwing Knife",
basePower: 150,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Iga School Throwing Knife');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Power Gem", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"variabledarts": {
id: "variabledarts",
name: "Variable Darts",
basePower: 153,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Variable Darts');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ice Hammer", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"solarray": {
id: "solarray",
name: "Solar Ray",
basePower: 167,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Solar Ray');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Electro Ball", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Earth",
},
"deathclaw": {
id: "deathclaw",
name: "Death Claw",
basePower: 180,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Death Claw');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hone Claws", target);
this.add('-anim', source, "Night Slash", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"darkclaw": {
id: "darkclaw",
name: "Dark Claw",
basePower: 143,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Dark Claw');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hone Claws", target);
this.add('-anim', source, "Shadow Claw", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"electroshocker": {
id: "electroshocker",
name: "Electro Shocker",
basePower: 170,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Electro Shocker');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Discharge", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"iceblast": {
id: "iceblast",
name: "Ice Blast",
basePower: 162,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Ice Blast');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Subzero Slammer", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"howlingblaster": {
id: "howlingblaster",
name: "Howling Blaster",
basePower: 183,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Howling Blaster');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sacred Fire", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Battle",
},
//Ultimates
"gigablaster": {
id: "gigablaster",
name: "Giga Blaster",
basePower: 215,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Giga Blaster');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sunsteel Strike", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"darkshot": {
id: "darkshot",
name: "Dark Shot",
basePower: 200,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Dark Shot');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Flare Blitz", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"deadlybomb": {
id: "deadlybomb",
name: "Deadly Bomb",
basePower: 260,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Deadly Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Egg Bomb", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"highelectricshocker": {
id: "highelectricshocker",
name: "High Electric Shocker",
basePower: 218,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: High Electric Shocker');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Discharge", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"smileybomb": {
id: "smileybomb",
name: "Smiley Bomb",
basePower: 255,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Smiley Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Inferno Overdrive", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"mailstorm": {
id: "mailstorm",
name: "Mail Storm",
basePower: 211,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Mail Storm');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Subzero Slammer", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"abductionbeam": {
id: "abductionbeam",
name: "Abduction Beam",
basePower: 222,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Abduction Beam');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Signal Beam", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Mech",
},
"darknetwork": {
id: "darknetwork",
name: "Dark Network",
basePower: 202,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Dark Network');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sing", target);
this.add('-anim', source, "Nightmare", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Filth",
},
"spiralsword": {
id: "spiralsword",
name: "Spiral Sword",
basePower: 210,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Spiral Sword');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Smart Strike", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"genocideattack": {
id: "genocideattack",
name: "Genocide Attack",
basePower: 215,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Genocide Attack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Never-Ending Nightmare", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"crimsonflare": {
id: "crimsonflare",
name: "Crimson Flare",
basePower: 213,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Crimson Flare');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Roar", target);
this.add('-anim', source, "Fire Blast", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Fire",
},
"bitbomb": {
id: "bitbomb",
name: "Bit Bomb",
basePower: 232,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Bit Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Nightmare", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"energybomb": {
id: "energybomb",
name: "Energy Bomb",
basePower: 214,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Energy Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Mach Punch", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Earth",
},
"lovelyattack": {
id: "lovelyattack",
name: "Lovely Attack",
basePower: 230,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Lovely Attack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Lovely Kiss", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Ice",
},
"nightmaresyndrome": {
id: "nightmaresyndrome",
name: "Nightmare Syndrome",
basePower: 222,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Nightmare Syndrome');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Black Hole Eclipse", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
//mega digimon
"infinitycannon": {
id: "infinitycannon",
name: "Infinity Cannon",
basePower: 777,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Infinity Cannon');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fleur Cannon", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
//Status Attacks
"panicattack": {
accuracy: true,
basePower: 40,
category: "Physical",
desc: "No additional effects.",
shortDesc: "No additional effects.",
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
if (this.random(2) === 1) {
move.target = 'self';
}
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-message', 'A panic is going on!');
this.add('-anim', source, "Tackle", target);
},
id: "panicattack",
name: "Panic Attack",
pp: 35,
priority: 0,
flags: {protect: 1},
target: "random",
type: "Battle",
},
};
| mods/digimon/moves.js | 'use strict';
exports.BattleMovedex = {
"acidbubble": {
id: "acidbubble",
name: "Acid Bubble",
basePower: 30,
category: "Special",
secondary: false,
priority: 0,
target: "any",
pp: 40,
shortDesc: "No additional effects.",
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Bubble');
},
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Bubble", target);
},
accuracy: 100,
type: "Ice",
},
"firetower": {
id: "firetower",
name: "Fire Tower",
basePower: 65,
category: "Physical",
secondary: {
chance: 25,
volatileStatus: "flinch",
},
priority: 0,
target: "any",
pp: 20,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Inferno", target);
this.add('-anim', source, "Precipice Blades", target);
},
shortDesc: "25% chance to flinch.",
accuracy: 100,
type: "Fire",
},
"prominencebeam": {
id: "prominencebeam",
name: "Prominence Beam",
basePower: 105,
category: "Special",
secondary: {
self: {
chance: 20,
boosts: {
spa: -2,
atk: -2,
},
},
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flamethrower", target);
},
priority: 0,
target: "any",
pp: 5,
desc: "Has a 20% chance to lower the user's Attack and Special Attack by two stages.",
shortDesc: "20% chance to lower user's Atk & SpA by 2.",
flags: {protect: 1, distance: 1},
accuracy: 100,
type: "Fire",
},
"spitfire": {
id: "spitfire",
name: "Spit Fire",
basePower: 45,
category: "Special",
secondary: false,
priority: 0,
target: "any",
pp: 25,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flamethrower", target);
},
shortDesc: "No additional effects.",
accuracy: 100,
type: "Fire",
},
"redinferno": {
id: "redinferno",
name: "Red Inferno",
basePower: 75,
category: "Special",
secondary: false,
priority: 0,
target: "allAdjacentFoes",
pp: 15,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fire Blast", target);
},
shortDesc: "No additional effects.",
accuracy: 100,
type: "Fire",
},
"magmabomb": {
id: "magmabomb",
name: "Magma Bomb",
basePower: 85,
category: "Physical",
secondary: {
chance: 25,
volatileStatus: "panic",
},
priority: 0,
target: "any",
pp: 15,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Egg Bomb", target);
this.add('-anim', source, "Sunny Day", target);
},
shortDesc: "25% chance to cause the target to panic.",
accuracy: 100,
type: "Fire",
},
"heatlaser": {
id: "heatlaser",
name: "Heat Laser",
basePower: 55,
category: "Special",
secondary: {
chance: 50,
boosts: {
spa: -3,
atk: -3,
},
},
priority: 0,
target: "allAdjacent",
pp: 30,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Roar", target);
this.add('-anim', source, "Sunny Day", target);
},
desc: "Has a 50% chance to lower the target's Attack and Special Attack by three stages.",
shortDesc: "50% chance to lower Atk & SpA by 3.",
accuracy: 100,
type: "Fire",
},
"infinityburn": {
id: "infinityburn",
name: "Infinity Burn",
basePower: 110,
accuracy: 100,
pp: 5,
target: "any",
priority: 0,
secondary: {
chance: 5,
volatileStatus: "flinch",
},
category: "Physical",
flags: {protect: 1, mirror: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Inferno", target);
this.add('-anim', source, "Precipice Blades", target);
},
desc: "5% chance to flinch.",
type: "Fire",
},
"meltdown": {
id: "meltdown",
name: "Meltdown",
basePower: 95,
accuracy: 100,
pp: 5,
target: "allAdjacent",
priority: 0,
secondary: {
chance: 10,
volatileStatus: "flinch",
},
category: "Special",
flags: {protect: 1, mirror: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sunny Day", target);
this.add('-anim', source, "Lava Plume", target);
},
desc: "10% chance to flinch.",
type: "Fire",
},
"tremar": {
id: "tremar",
name: "Tremar",
basePower: 75,
accuracy: 85,
pp: 20,
target: "allAdjacent",
priority: 0,
secondary: false,
category: "Physical",
flags: {protect: 1, mirror: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ancient Power", target);
},
shortDesc: "No additional effects.",
type: "Battle",
},
"musclecharge": {
id: "musclecharge",
name: "Muscle Charge",
basePower: 0,
accuracy: 100,
pp: 25,
boosts: {
atk: 2,
spa: 2,
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
},
target: "self",
priority: 0,
secondary: false,
category: "Status",
flags: {snatch: 1},
shortDesc: "Raises the user's Atk & SpA by 2.",
type: "Battle",
},
"warcry": {
id: "warcry",
name: "War Cry",
basePower: 0,
secondary: false,
category: "Status",
pp: 30,
accuracy: 100,
boosts: {
atk: 1,
def: 1,
spa: 1,
spd: 1,
spe: 1,
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Dragon Dance", source);
},
shortDesc: "Raises all user's stats by 1 (except eva & acc).",
priority: 0,
flags: {snatch: 1},
target: "self",
type: "Battle",
},
"sonicjab": {
id: "sonicjab",
name: "Sonic Jab",
basePower: 65,
category: "Physical",
accuracy: 100,
secondary: false,
priority: 0,
flags: {protect: 1, contact: 1, punch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Dizzy Punch", target);
},
shortDesc: "No additional effects.",
pp: 40,
target: "normal",
type: "Battle",
},
"dynamitekick": {
id: "dynamitekick",
name: "Dynamite Kick",
basePower: 85,
accuracy: 100,
pp: 5,
category: "Special",
secondary: {
chance: 20,
volatileStatus: "flinch",
},
priority: 0,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Mega Kick", target);
},
shortDesc: "20% chance to flinch.",
target: "normal",
type: "Battle",
},
"reboundstrike": {
id: "reboundstrike",
name: "Rebound Strike",
basePower: 95,
secondary: {
chance: 30,
volatileStatus: "panic",
},
damageCallback: function (pokemon) {
if (!pokemon.volatiles['counter']) return 0;
return pokemon.volatiles['counter'].damage || 1;
},
category: "Physical",
pp: 20,
priority: -5,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Headbutt", target);
},
beforeTurnCallback: function (pokemon) {
pokemon.addVolatile('counter');
},
onTryHit: function (target, source, move) {
if (!source.volatiles['counter']) return false;
if (source.volatiles['counter'].position === null) return false;
},
effect: {
duration: 1,
noCopy: true,
onStart: function (target, source, source2, move) {
this.effectData.position = null;
this.effectData.damage = 0;
},
onRedirectTargetPriority: -1,
onRedirectTarget: function (target, source, source2) {
if (source !== this.effectData.target) return;
return source.side.foe.active[this.effectData.position];
},
onDamagePriority: -101,
onDamage: function (damage, target, source, effect) {
if (effect && effect.effectType === 'Move' && source.side !== target.side && this.getCategory(effect) === 'Physical') {
this.effectData.position = source.position;
this.effectData.damage = 2 * damage;
}
},
},
desc: "Deals damage to the last foe to hit the user with a physical attack this turn equal to twice the HP lost by the user from that attack. If the user did not lose HP from the attack, this move deals damage with a Base Power of 1 instead. If that foe's position is no longer in use, the damage is done to a random foe in range. Only the last hit of a multi-hit attack is counted. Fails if the user was not hit by a foe's physical attack this turn. 30% chance to make the target panic.",
shortDesc: "If hit by physical attack, returns double damage. 30% chance to panic.",
target: "normal",
type: "Battle",
},
"megatonpunch": {
id: "megatonpunch",
name: "Megaton Punch",
basePower: 105,
category: "Physical",
accuracy: 100,
pp: 10,
secondary: {
chance: 15,
volatileStatus: "flinch",
},
flags: {protect: 1, contact: 1, punch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Dizzy Punch", target);
},
shortDesc: "15% chance to flinch.",
priority: 0,
target: "normal",
type: "Battle",
},
"busterdrive": {
id: "busterdrive",
name: "Buster Drive",
basePower: 110,
secondary: {
chance: 5,
volatileStatus: "panic",
},
category: "Physical",
pp: 5,
accuracy: 100,
flags: {protect: 1, contact: 1, distance: 1, punch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fire Punch", target);
},
shortDesc: "5% chance to make the target panic.",
priority: 0,
target: "any",
type: "Battle",
},
"thunderjustice": {
id: "thunderjustice",
name: "Thunder Justice",
basePower: 105,
accuracy: true,
pp: 5,
category: "Special",
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thunder", target);
},
secondary: {
chance: 5,
volatileStatus: "flinch",
},
shortDesc: "5% chance to flinch.",
type: "Air",
target: "any",
},
"spinningshot": {
id: "spinningshot",
name: "Spinning Shot",
basePower: 110,
pp: 10,
accuracy: 100,
secondary: false,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Air Cutter", target);
},
category: "Special",
type: "Air",
shortDesc: "No additional effects.",
target: "allAdjacent",
},
"electriccloud": {
id: "electriccloud",
name: "Electric Cloud",
basePower: 55,
category: "Special",
secondary: {
chance: 40,
volatileStatus: "flinch",
},
shortDesc: "40% chance to flinch.",
accuracy: true,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thundershock", target);
},
priority: 0,
pp: 20,
type: "Air",
target: "any",
},
"megalospark": {
id: "megalospark",
name: "Megalo Spark",
basePower: 95,
secondary: {
chance: 15,
volatileStatus: "flinch",
},
accuracy: 100,
pp: 15,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Shock Wave", target);
},
shortDesc: "15% chance to flinch.",
category: "Physical",
target: "any",
type: "Air",
},
"staticelect": {
id: "staticelect",
name: "Static Elect",
basePower: 45,
accuracy: 100,
pp: 40,
secondary: {
chance: 50,
volatileStatus: "flinch",
},
priority: 0,
flags: {protect: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thunder Punch", target);
},
shortDesc: "50% chance to flinch.",
category: "Physical",
target: "normal",
type: "Air",
},
"windcutter": {
id: "windcutter",
name: "Wind Cutter",
basePower: 65,
accuracy: 100,
category: "Special",
secondary: false,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Gust", target);
},
shortDesc: "No additional effects.",
pp: 15,
target: "any",
type: "Air",
},
"confusedstorm": {
id: "confusedstorm",
name: "Confused Storm",
basePower: 75,
secondary: {
self: {
volatileStatus: "confusion",
},
chance: 20,
volatileStatus: "panic",
},
accuracy: 100,
category: "Special",
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Prismatic Laser", target);
},
shortDesc: "20% chance to make target panic; confuses the user.",
pp: 10,
target: "allAdjacent",
type: "Air",
},
"typhoon": {
id: "typhoon",
name: "Typhoon",
basePower: 85,
secondary: {
chance: 15,
volatileStatus: "panic",
},
category: "Special",
pp: 10,
accuracy: 100,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hurricane", target);
},
shortDesc: "15% chance to make the target panic.",
target: "allAdjacent",
type: "Air",
},
"toxicpowder": {
id: "toxicpowder",
name: "Toxic Powder",
basePower: 65,
pp: 15,
category: "Special",
secondary: {
chance: 50,
status: "psn",
},
accuracy: 100,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Powder", target);
},
desc: "50% chance to poison the target.",
target: "allAdjacent",
type: "Earth",
},
"bug": {
id: "bug",
name: "Bug",
basePower: 110,
accuracy: 100,
secondary: {
chance: 5,
boosts: {
atk: -3,
spa: -3,
},
},
category: "Physical",
pp: 5,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Magnet Bomb", target);
},
shortDesc: "5% chance to lower target's Atk & SpA by 1.",
target: "any",
type: "Earth",
},
"massmorph": {
id: "massmorph",
name: "Mass Morph",
basePower: 0,
category: "Status",
boosts: {
atk: 1,
def: 2,
spa: 1,
spd: 1,
spe: 1,
accuracy: 1,
},
desc: "Boosts all stats by 1 (except evasion); Def by 2.",
accuracy: 100,
pp: 40,
priority: 0,
secondary: false,
flags: {snatch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Cotton Guard", source);
},
target: "self",
type: "Earth",
},
"insectplague": {
id: "insectplague",
name: "Insect Plague",
basePower: 95,
accuracy: 100,
category: "Special",
pp: 10,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Toxic", target);
},
secondary: {
chance: 40,
status: "psn",
},
shortDesc: "40% chance to poison.",
target: "any",
type: "Earth",
},
"charmperfume": {
id: "charmperfume",
name: "Charm Perfume",
basePower: 95,
secondary: {
chance: 40,
volatileStatus: "panic",
},
category: "Special",
pp: 15,
accuracy: 100,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Gas", target);
},
shortDesc: "40% chance to make the target panic.",
target: "allAdjacent",
type: "Earth",
},
"poisonclaw": {
id: "poisonclaw",
name: "Poison Claw",
basePower: 55,
category: "Physical",
secondary: {
chance: 50,
status: "psn",
},
pp: 40,
accuracy: 100,
priority: 0,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Jab", target);
},
shortDesc: "50% chance to poison.",
target: "normal",
type: "Earth",
},
"dangersting": {
id: "dangersting",
name: "Danger Sting",
basePower: 75,
accuracy: 100,
category: "Physical",
pp: 15,
secondary: {
chance: 35,
boosts: {
atk: -3,
spa: -3,
},
},
priority: 0,
flags: {protect: 1, contact: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Sting", target);
},
shortDesc: "35% chance to lower Atk & SpA by 3.",
target: "normal",
type: "Earth",
},
"greentrap": {
id: "greentrap",
name: "Green Trap",
basePower: 105,
accuracy: 100,
pp: 10,
secondary: {
chance: 15,
volatileStatus: "flinch",
},
category: "Physical",
flags: {protect: 1, contact: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Grass Knot", target);
},
shortDesc: "15% chance to flinch.",
priority: 0,
target: "any",
type: "Earth",
},
"gigafreeze": {
id: "gigafreeze",
name: "Giga Freeze",
basePower: 95,
category: "Physical",
pp: 10,
secondary: {
chance: 20,
volatileStatus: "flinch",
},
accuracy: 100,
flags: {protect: 1, contact: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Frost Breath", target);
},
shortDesc: "20% chance to flinch.",
priority: 0,
target: "allAdjacentFoes",
type: "Ice",
},
"icestatue": {
id: "icestatue",
name: "Ice Statue",
basePower: 105,
accuracy: 100,
pp: 10,
secondary: {
chance: 10,
volatileStatus: "flinch",
},
category: "Physical",
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Avalanche", target);
},
shortDesc: "10% chance to flinch.",
priority: 0,
target: "any",
type: "Ice",
},
"winterblast": {
id: "winterblast",
name: "Winter Blast",
basePower: 65,
accuracy: 100,
secondary: {
chance: 30,
volatileStatus: "flinch",
},
category: "Special",
pp: 10,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Blizzard", target);
},
shortDesc: "30% chance to flinch.",
target: "allAdjacent",
type: "Ice",
},
"iceneedle": {
id: "iceneedle",
name: "Ice Needle",
basePower: 75,
accuracy: 50,
secondary: {
chance: 35,
volatileStatus: "flinch",
},
category: "Physical",
pp: 20,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ice Shard", target);
},
shortDesc: "35% chance to flinch.",
priority: 0,
target: "any",
type: "Ice",
},
"waterblit": {
id: "waterblit",
name: "Water Blit",
basePower: 85,
accuracy: 100,
category: "Special",
pp: 20,
secondary: false,
priority: 0,
flags: {protect: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Aqua Ring", target);
},
shortDesc: "No additional effects.",
target: "normal",
type: "Ice",
},
"aquamagic": {
id: "aquamagic",
name: "Aqua Magic",
basePower: 0,
accuracy: 100,
boosts: {
atk: 1,
def: 1,
spa: 1,
spd: 1,
spe: 1,
},
pp: 20,
secondary: false,
priority: 0,
flags: {snatch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Bubble", source);
},
shortDesc: "Raises all stats by 1 (except acc and eva).",
target: "self",
type: "Ice",
},
"aurorafreeze": {
id: "aurorafreeze",
name: "Aurora Freeze",
basePower: 110,
accuracy: 100,
category: "Special",
secondary: {
chance: 10,
boosts: {
atk: -3,
spa: -3,
},
},
pp: 10,
onTry: function (attacker, defender, move) {
if (attacker.removeVolatile(move.id)) {
return;
}
this.add('-prepare', attacker, move.name, defender);
if (!this.runEvent('ChargeMove', attacker, defender, move)) {
this.add('-anim', attacker, move.name, defender);
return;
}
attacker.addVolatile('twoturnmove', defender);
return null;
},
priority: 0,
flags: {protect: 1, charge: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Moonlight", target);
this.add('-anim', source, "Power Gem", target);
},
shortdesc: "10% chance to lower Atk & SpA by 3.",
target: "allAdjacent",
type: "Ice",
},
"teardrop": {
id: "teardrop",
name: "Tear Drop",
basePower: 55,
accuracy: 90,
secondary: {
chance: 50,
boosts: {
atk: -3,
spa: -3,
},
},
pp: 40,
category: "Special",
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Water Pulse", target);
},
shortdesc: "50% chance to lower Atk & SpA by 3.",
target: "any",
type: "Ice",
},
"powercrane": {
id: "powercrane",
name: "Power Crane",
basePower: 65,
accuracy: 100,
secondary: false,
category: "Physical",
pp: 15,
priority: 0,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Metal Claw", target);
},
shortDesc: "No additional effects.",
target: "any",
type: "Mech",
},
"allrangebeam": {
id: "allrangebeam",
name: "All-Range Beam",
basePower: 105,
pp: 5,
accuracy: 100,
category: "Special",
priority: 0,
secondary: false,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Gear Up", target);
this.add('-anim', source, "Hyper Beam", target);
},
shortDesc: "No additional effects.",
target: "allAdjacent",
type: "Mech",
},
"metalsprinter": {
id: "metalsprinter",
name: "Metal Sprinter",
basePower: 55,
accuracy: 100,
category: "Physical",
secondary: false,
pp: 10,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Metal Burst", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "allAdjacent",
type: "Mech",
},
"pulselaser": {
id: "pulselaser",
name: "Pulse Laser",
basePower: 85,
accuracy: 100,
category: "Special",
pp: 10,
secondary: false,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flash Cannon", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"deleteprogram": {
id: "deleteprogram",
name: "Delete Program",
basePower: 95,
accuracy: 100,
category: "Special",
pp: 10,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Flash Cannon", target);
},
secondary: {
chance: 10,
boosts: {
atk: -3,
spa: -3,
},
},
shortDesc: "10% chance to lower Atk & SpA by 3.",
priority: 0,
target: "any",
type: "Mech",
},
"dgdimension": {
id: "dgdimension",
name: "DG Dimension",
basePower: 110,
category: "Special",
pp: 5,
accuracy: 100,
secondary: false,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Moonlight", target);
this.add('-anim', source, "Sonic Boom", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"fullpotential": {
id: "fullpotential",
name: "Full Potential",
basePower: 0,
accuracy: 0,
category: "Status",
pp: 20,
boosts: {
atk: 2,
def: 2,
spa: 2,
spd: 2,
spe: 2,
},
secondary: false,
flags: {snatch: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Gear Grind", target);
},
priority: 0,
shortDesc: "Raises all stats by 2 (except acc and eva).",
target: "self",
type: "Mech",
},
"reverseprogram": {
id: "reverseprogram",
name: "Reverse Program",
basePower: 75,
accuracy: 100,
category: "Special",
pp: 5,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Lock-On", target);
this.add('-anim', source, "Wake-Up Slap", target);
},
secondary: {
chance: 20,
boosts: {
atk: -3,
spa: -3,
},
},
shortDesc: "20% chance to lower Atk & SpA by 3.",
priority: 0,
target: "any",
type: "Mech",
},
"orderspray": {
id: "orderspray",
name: "Order Spray",
basePower: 65,
category: "Special",
pp: 40,
secondary: {
chance: 50,
volatileStatus: "flinch",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Gas", target);
},
shortDesc: "50% chance to flinch.",
priority: 0,
target: "any",
type: "Filth",
},
"poopspdtoss": {
id: "poopspdtoss",
name: "Poop Spd Toss",
basePower: 75,
category: "Physical",
pp: 20,
secondary: {
chance: 30,
status: "psn",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Throw", target);
},
shortDesc: "30% chance to poison.",
priority: 0,
target: "any",
type: "Filth",
},
"bigpooptoss": {
id: "bigpooptoss",
name: "Big Poop Toss",
basePower: 95,
category: "Physical",
pp: 15,
secondary: {
chance: 30,
volatileStatus: "panic",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Wrecker", target);
},
shortDesc: "30% chance to make the target to panic.",
priority: 0,
target: "any",
type: "Filth",
},
"bigrndtoss": {
id: "bigrndtoss",
name: "Big Rnd Toss",
basePower: 105,
category: "Physical",
pp: 5,
secondary: {
chance: 30,
volatileStatus: "panic",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Tomb", target);
},
shortDesc: "30% chance to make the target panic.",
priority: 0,
target: "allAdjacentFoes",
type: "Filth",
},
"pooprndtoss": {
id: "pooprndtoss",
name: "Poop RND Toss",
basePower: 55,
category: "Physical",
pp: 15,
secondary: {
chance: 40,
status: "psn",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Slide", target);
},
shortDesc: "40% chance to poison.",
priority: 0,
target: "allAdjacent",
type: "Filth",
},
"rndspdtoss": {
id: "rndspdtoss",
name: "Rnd Spd Toss",
basePower: 75,
category: "Physical",
pp: 10,
secondary: {
chance: 30,
status: "psn",
},
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Rock Blast", target);
},
shortDesc: "30% chance to poison.",
priority: 0,
target: "allAdjacent",
type: "Filth",
},
"horizontalkick": {
id: "horizontalkick",
name: "Horizontal Kick",
basePower: 45,
category: "Special",
pp: 5,
accuracy: 100,
secondary: false,
flags: {protect: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Poison Gas", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "normal",
type: "Filth",
},
"ultpoophell": {
id: "ultpoophell",
name: "Ult Poop Hell",
basePower: 110,
category: "Physical",
pp: 5,
accuracy: 100,
flags: {protect: 1, distance: 1},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Stone Edge", target);
},
secondary: {
chance: 10,
boosts: {
atk: -3,
spa: -3,
},
},
shortDesc: "10% chance to lower Atk & SpA by 3.",
priority: 0,
target: "allAdjacent",
type: "Filth",
},
//Health Items
//Small Recovery
smallrecovery: {
accuracy: true,
basePower: 0,
category: "Status",
id: "smallrecovery",
isNonstandard: true,
name: "Small Recovery",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 4],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals 1/4 of max HP.",
},
//Medium Recovery
mediumrecovery: {
accuracy: true,
basePower: 0,
category: "Status",
id: "mediumrecovery",
isNonstandard: true,
name: "Medium Recovery",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 3],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals 1/3 of max HP.",
},
//Large Recovery
largerecovery: {
accuracy: true,
basePower: 0,
category: "Status",
id: "largerecovery",
isNonstandard: true,
name: "Large Recovery",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 2],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals 1/2 of max HP.",
},
//Super Recovery Floppy
superrecoveryfloppy: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superrecoveryfloppy",
isNonstandard: true,
name: "Super Recovery Floppy",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 1],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Heals all of user's HP.",
},
//Various
various: {
accuracy: true,
basePower: 0,
category: "Status",
id: "various",
isNonstandard: true,
name: "Various",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
onPrepareHit: function (pokemon, source) {
this.add('-activate', source, 'move: Various');
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
let side = pokemon.side;
for (let i = 0; i < side.pokemon.length; i++) {
side.pokemon[i].cureStatus();
}
},
desc: "Cures user of status conditions.",
secondary: false,
target: "adjacentAllyOrSelf",
},
//Protection
protection: {
accuracy: true,
basePower: 0,
category: "Status",
desc: "For 5 turns, the user and its party members cannot have major status conditions or confusion inflicted on them by other Pokemon. It is removed from the user's side if the user or an ally is successfully hit by Defog.",
shortDesc: "For 5 turns, protects user's party from status.",
pp: 0.625,
priority: 0,
flags: {snatch: 1},
//safeguard effects = same effect for the Protection "item" in Digimon
sideCondition: 'safeguard',
effect: {
duration: 5,
durationCallback: function (target, source, effect) {
if (source && source.hasAbility('persistent')) {
return 7;
}
return 5;
},
onSetStatus: function (status, target, source, effect) {
if (source && target !== source && effect && (!effect.infiltrates || target.side === source.side)) {
this.debug('interrupting setStatus');
if (effect.id === 'synchronize' || (effect.effectType === 'Move' && !effect.secondaries)) {
this.add('-activate', target, 'move: Protection');
}
return null;
}
},
onTryAddVolatile: function (status, target, source, effect) {
if ((status.id === 'confusion' || status.id === 'yawn') && source && target !== source && effect && (!effect.infiltrates || target.side === source.side)) {
if (!effect.secondaries) this.add('-activate', target, 'move: Protection');
return null;
}
},
onStart: function (side) {
this.add('-sidestart', side, 'Protection');
},
onResidualOrder: 21,
onResidualSubOrder: 2,
onEnd: function (side) {
this.add('-sideend', side, 'Protection');
},
},
secondary: false,
target: "adjacentAllyOrSelf",
type: "Battle",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Safeguard", source);
},
},
//Omnipotent
omnipotent: {
accuracy: true,
basePower: 0,
category: "Status",
id: "omnipotent",
isNonstandard: true,
name: "Omnipotent",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
onPrepareHit: function (pokemon, source) {
pokemon.cureStatus();
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
secondary: false,
heal: [1, 1],
desc: "Heals all of the user's HP.",
target: "adjacentAllyOrSelf",
},
//Restore Floppy
restorefloppy: {
accuracy: true,
basePower: 0,
category: "Status",
id: "restorefloppy",
isNonstandard: true,
name: "Restore Floppy",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 2],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Restores 1/2 of the user's max HP.",
},
//Super Restore Floppy
superrestorefloppy: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superrestorefloppy",
isNonstandard: true,
name: "Super Restore Floppy",
pp: 0.625,
priority: 0,
flags: {heal: 1, snatch: 1, distance: 1},
secondary: false,
heal: [1, 1],
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
desc: "Restores all of the user's max HP.",
},
//Stat Boosting Items
//Offense Disk
offensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "offensedisk",
isNonstandard: true,
name: "Offense Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
atk: 1,
spa: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Atk & SpA by 1.",
},
//Defense Disk
defensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "defensedisk",
isNonstandard: true,
name: "Defense Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spd: 1,
def: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Def & SpD by 1.",
},
//Hi Speed Disk
hispeeddisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "hispeeddisk",
isNonstandard: true,
name: "Hi Speed Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spe: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Spe by 1.",
},
//Super Defense Disk
superdefensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superdefensedisk",
isNonstandard: true,
name: "Super Defense Disk",
pp: 0.625,
priority: 0,
boosts: {
def: 2,
spd: 2,
},
flags: {snatch: 1, distance: 1},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Def & SpD by 2.",
},
//Super Offense Disk
superoffensedisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superoffensedisk",
isNonstandard: true,
name: "Super Offense Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spa: 2,
atk: 2,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Atk & SpA by 2.",
},
//Super Speed Disk
superspeeddisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "superspeeddisk",
isNonstandard: true,
name: "Super Speed Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
spe: 2,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Spe by 2.",
},
//Omnipotent Disk
omnipotentdisk: {
accuracy: true,
basePower: 0,
category: "Status",
id: "omnipotentdisk",
isNonstandard: true,
name: "Omnipotent Disk",
pp: 0.625,
priority: 0,
flags: {snatch: 1, distance: 1},
boosts: {
atk: 1,
def: 1,
spa: 1,
spd: 1,
},
secondary: false,
target: "adjacentAllyOrSelf",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Recover", source);
},
shortDesc: "Raises the user's Atk, Def, SpA & SpD by 1.",
},
//Finishers
"pepperbreath": {
id: "pepperbreath",
name: "Pepper Breath",
basePower: 89,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Pepper Breath');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Inferno Overdrive", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"blueblaster": {
id: "blueblaster",
name: "Blue Blaster",
basePower: 90,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Blue Blaster');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Blue Flare", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"boombubble": {
id: "boombubble",
name: "Boom Bubble",
basePower: 85,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Boom Bubble');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Aeroblast", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"superthunderstrike": {
id: "superthunderstrike",
name: "Super Thunder Strike",
basePower: 100,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Super Thunder Strike');
},
shortDesc: "No additional effects.",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Gigavolt Havoc", target);
},
priority: 0,
target: "any",
type: "Air",
},
"spiraltwister": {
id: "spiraltwister",
name: "Spiral Twister",
basePower: 91,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Spiral Twister');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fire Spin", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"electricthread": {
id: "electricthread",
name: "Electric Thread",
basePower: 94,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Electric Thread');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Electroweb", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"poisonivy": {
id: "poisonivy",
name: "Poison Ivy",
basePower: 101,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Poison Ivy');
},
shortDesc: "No additional effects.",
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Toxic", target);
},
priority: 0,
target: "any",
type: "Earth",
},
"electricshock": {
id: "electricshock",
name: "Electric Shock",
basePower: 92,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Electric Shock');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Thunderbolt", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"superslap": {
id: "superslap",
name: "Super Slap",
basePower: 91,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1, contact: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Super Slap');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ice Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
// Champions
"megaflame": {
id: "megaflame",
name: "Mega Flame",
basePower: 196,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Mega Flame');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Overheat", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"volcanicstrike": {
id: "volcanicstrike",
name: "Volcanic Strike",
basePower: 160,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Volcanic Strike');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Eruption", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Fire",
},
"pummelwhack": {
id: "pummelwhack",
name: "Pummel Whack",
basePower: 170,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Pummel Whack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Wood Hammer", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"spinningneedle": {
id: "spinningneedle",
name: "Spinning Needle",
basePower: 152,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Spinning Needle');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Whirlwind", target);
this.add('-anim', source, "Ice Shard", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"scissorclaw": {
id: "scissorclaw",
name: "Scissor Claw",
basePower: 172,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Scissor Claw');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Smart Strike", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"blastingspout": {
id: "blastingspout",
name: "Blasting Spout",
basePower: 150,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Blastin Spout');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Water Spout", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"subzeroicepunch": {
id: "subzeroicepunch",
name: "Sub Zero Ice Punch",
basePower: 157,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Sub Zero Ice Punch');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Ice Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"partytime": {
id: "partytime",
name: "Party Time",
basePower: 100,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Party Time');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Continental Crush", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"fireball": {
id: "fireball",
name: "Fireball",
basePower: 155,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Fireball');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", source);
this.add('-anim', source, "Fire Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"drillspin": {
id: "drillspin",
name: "Drill Spin",
basePower: 150,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Drill Spin');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Drill Run", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"fistofthebeastking": {
id: "fistofthebeastking",
name: "Fist Of The Beast King",
basePower: 170,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Fist Of The Beast King');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Roar", target);
this.add('-anim', source, "Fire Punch", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"frozenfireshot": {
id: "frozenfireshot",
name: "Frozen Fire Shot",
basePower: 159,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1, defrost: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Frozen Fire Shot');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Frost Breath", target);
this.add('-anim', source, "Stone Edge", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"sweetbreath": {
id: "sweetbreath",
name: "Sweet Breath",
basePower: 130,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Sweet Breath');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sweet Kiss", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"hydropressure": {
id: "hydropressure",
name: "Hydro Pressure",
basePower: 155,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Hydro Pressure');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hydro Pump", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"boneboomerang": {
id: "boneboomerang",
name: "Bone Boomerang",
basePower: 148,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Bone Boomerang');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Bonemerang", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"meteorwing": {
id: "meteorwing",
name: "Meteor Wing",
basePower: 158,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Meteor Wing');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Heat Wave", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"blazeblast": {
id: "blazeblast",
name: "Blaze Blast",
basePower: 174,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Blaze Blast');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Overheat", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Fire",
},
"handoffate": {
id: "handoffate",
name: "Hand Of Fate",
basePower: 166,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Hand Of Fate');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Zap Cannon", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"aerialattack": {
id: "aerialattack",
name: "Aerial Attack",
basePower: 153,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Aerial Attack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Supersonic Skystrike", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"igaschoolthrowingknife": {
id: "igaschoolthrowingknife",
name: "Iga School Throwing Knife",
basePower: 150,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Iga School Throwing Knife');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Power Gem", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
"variabledarts": {
id: "variabledarts",
name: "Variable Darts",
basePower: 153,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Variable Darts');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Ice Hammer", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"solarray": {
id: "solarray",
name: "Solar Ray",
basePower: 167,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Solar Ray');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Electro Ball", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Earth",
},
"deathclaw": {
id: "deathclaw",
name: "Death Claw",
basePower: 180,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Death Claw');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hone Claws", target);
this.add('-anim', source, "Night Slash", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"darkclaw": {
id: "darkclaw",
name: "Dark Claw",
basePower: 143,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Dark Claw');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Hone Claws", target);
this.add('-anim', source, "Shadow Claw", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"electroshocker": {
id: "electroshocker",
name: "Electro Shocker",
basePower: 170,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Electro Shocker');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Discharge", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"iceblast": {
id: "iceblast",
name: "Ice Blast",
basePower: 162,
accuracy: 100,
category: "Physical",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Ice Blast');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Subzero Slammer", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Ice",
},
"howlingblaster": {
id: "howlingblaster",
name: "Howling Blaster",
basePower: 183,
accuracy: 100,
category: "Special",
pp: 0.625,
flags: {protect: 1, distance: 1},
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Howling Blaster');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sacred Fire", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Battle",
},
//Ultimates
"gigablaster": {
id: "gigablaster",
name: "Giga Blaster",
basePower: 215,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Giga Blaster');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sunsteel Strike", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"darkshot": {
id: "darkshot",
name: "Dark Shot",
basePower: 200,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Dark Shot');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Flare Blitz", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"deadlybomb": {
id: "deadlybomb",
name: "Deadly Bomb",
basePower: 260,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Deadly Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Egg Bomb", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
"highelectricshocker": {
id: "highelectricshocker",
name: "High Electric Shocker",
basePower: 218,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: High Electric Shocker');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Discharge", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Air",
},
"smileybomb": {
id: "smileybomb",
name: "Smiley Bomb",
basePower: 255,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Smiley Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Inferno Overdrive", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"mailstorm": {
id: "mailstorm",
name: "Mail Storm",
basePower: 211,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Mail Storm');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Subzero Slammer", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Battle",
},
"abductionbeam": {
id: "abductionbeam",
name: "Abduction Beam",
basePower: 222,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Abduction Beam');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Signal Beam", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Mech",
},
"darknetwork": {
id: "darknetwork",
name: "Dark Network",
basePower: 202,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Dark Network');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Sing", target);
this.add('-anim', source, "Nightmare", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Filth",
},
"spiralsword": {
id: "spiralsword",
name: "Spiral Sword",
basePower: 210,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Spiral Sword');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Smart Strike", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"genocideattack": {
id: "genocideattack",
name: "Genocide Attack",
basePower: 215,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Genocide Attack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Never-Ending Nightmare", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"crimsonflare": {
id: "crimsonflare",
name: "Crimson Flare",
basePower: 213,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Crimson Flare');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Roar", target);
this.add('-anim', source, "Fire Blast", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Fire",
},
"bitbomb": {
id: "bitbomb",
name: "Bit Bomb",
basePower: 232,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Bit Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Charge", target);
this.add('-anim', source, "Nightmare", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Battle",
},
"energybomb": {
id: "energybomb",
name: "Energy Bomb",
basePower: 214,
accuracy: 100,
category: "Physical",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Energy Bomb');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Autotomize", target);
this.add('-anim', source, "Mach Punch", target);
},
priority: 0,
target: "any",
shortDesc: "No additional effects.",
type: "Earth",
},
"lovelyattack": {
id: "lovelyattack",
name: "Lovely Attack",
basePower: 230,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Lovely Attack');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Lovely Kiss", target);
},
priority: 0,
shortDesc: "No additional effects.",
target: "any",
type: "Ice",
},
"nightmaresyndrome": {
id: "nightmaresyndrome",
name: "Nightmare Syndrome",
basePower: 222,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Nightmare Syndrome');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Black Hole Eclipse", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Filth",
},
//mega digimon
"infinitycannon": {
id: "infinitycannon",
name: "Infinity Cannon",
basePower: 777,
accuracy: 100,
category: "Special",
pp: 0.625,
secondary: false,
flags: {protect: 1, distance: 1},
onModifyMove: function (move, pokemon, target) {
move.type = '???';
this.add('-activate', pokemon, 'move: Infinity Cannon');
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-anim', source, "Fleur Cannon", target);
},
shortDesc: "No additional effects.",
priority: 0,
target: "any",
type: "Mech",
},
//Status Attacks
"panicattack": {
accuracy: true,
basePower: 40,
category: "Physical",
desc: "No additional effects.",
shortDesc: "No additional effects.",
secondary: false,
onModifyMove: function (move, pokemon, target) {
move.type = '???';
if (this.random(2) === 1) {
move.target = 'self';
}
},
onPrepareHit: function (target, source) {
this.attrLastMove('[still]');
this.add('-message', 'A panic is going on!');
this.add('-anim', source, "Tackle", target);
},
id: "panicattack",
name: "Panic Attack",
pp: 35,
priority: 0,
flags: {protect: 1},
target: "random",
type: "Battle",
},
};
| Digimon Showdown: Fix Pulse Lazer Bug (#336)
| mods/digimon/moves.js | Digimon Showdown: Fix Pulse Lazer Bug (#336) | <ide><path>ods/digimon/moves.js
<ide> target: "allAdjacent",
<ide> type: "Mech",
<ide> },
<del> "pulselaser": {
<del> id: "pulselaser",
<del> name: "Pulse Laser",
<add> "pulselazer": {
<add> id: "pulselazer",
<add> name: "Pulse Lazer",
<ide> basePower: 85,
<ide> accuracy: 100,
<ide> category: "Special", |
|
JavaScript | mit | fb0bd02f5ea98cfbe37f222efdf31d45bc27ef60 | 0 | li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,li-ang/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb | import React, {Component, PropTypes} from 'react'
import SourceIndicator from 'shared/components/SourceIndicator'
import AllUsersTable from 'src/admin/components/chronograf/AllUsersTable'
import FancyScrollbar from 'shared/components/FancyScrollbar'
import {DUMMY_USERS} from 'src/admin/constants/dummyUsers'
class AdminChronografPage extends Component {
constructor(props) {
super(props)
this.state = {
organizationName: null,
selectedUsers: [],
filteredUsers: this.props.users,
}
}
isSameUser = (userA, userB) => {
return (
userA.name === userB.name &&
userA.provider === userB.provider &&
userA.scheme === userB.scheme
)
}
handleFilterUsers = organizationName => () => {
const {users} = this.props
const filteredUsers = organizationName
? users.filter(user => {
return user.roles.find(
role => role.organizationName === organizationName
)
})
: users
this.setState({filteredUsers})
}
handleToggleUserSelected = user => e => {
e.preventDefault()
const {selectedUsers} = this.state
const isUserSelected = selectedUsers.find(u => this.isSameUser(user, u))
const newSelectedUsers = isUserSelected
? selectedUsers.filter(u => !this.isSameUser(user, u))
: [...selectedUsers, user]
this.setState({selectedUsers: newSelectedUsers})
}
handleToggleAllUsersSelected = areAllSelected => () => {
const {filteredUsers} = this.state
if (areAllSelected) {
this.setState({selectedUsers: []})
} else {
this.setState({selectedUsers: filteredUsers})
}
}
render() {
const {users} = this.props
const {organizationName, selectedUsers, filteredUsers} = this.state
const numUsersSelected = Object.keys(selectedUsers).length
return (
<div className="page">
<div className="page-header">
<div className="page-header__container">
<div className="page-header__left">
<h1 className="page-header__title">Chronograf Admin</h1>
</div>
<div className="page-header__right">
<SourceIndicator />
<button className="btn btn-primary btn-sm">
<span className="icon plus" />
Create Organization
</button>
</div>
</div>
</div>
<FancyScrollbar className="page-contents">
{users
? <div className="container-fluid">
<div className="row">
<div className="col-xs-12">
<div className="panel panel-minimal">
{numUsersSelected
? <div className="panel-heading">
<h2 className="panel-title">
{numUsersSelected} User{numUsersSelected > 1 ? 's' : ''}{' '}
Selected
</h2>
</div>
: <div className="panel-heading">
<h2 className="panel-title">
{organizationName
? `Users in ${organizationName}`
: 'Users'}
</h2>
</div>}
<div className="panel-body">
<AllUsersTable
filteredUsers={filteredUsers}
organizationName={organizationName}
onFilterUsers={this.handleFilterUsers}
onToggleUserSelected={this.handleToggleUserSelected}
selectedUsers={selectedUsers}
isSameUser={this.isSameUser}
onToggleAllUsersSelected={
this.handleToggleAllUsersSelected
}
/>
</div>
</div>
</div>
</div>
</div>
: <div className="page-spinner" />}
</FancyScrollbar>
</div>
)
}
}
const {arrayOf, shape} = PropTypes
AdminChronografPage.propTypes = {
users: arrayOf(shape()),
}
AdminChronografPage.defaultProps = {
users: DUMMY_USERS,
}
export default AdminChronografPage
| ui/src/admin/containers/AdminChronografPage.js | import React, {Component, PropTypes} from 'react'
import SourceIndicator from 'shared/components/SourceIndicator'
import AllUsersTable from 'src/admin/components/chronograf/AllUsersTable'
import FancyScrollbar from 'shared/components/FancyScrollbar'
import {DUMMY_USERS} from 'src/admin/constants/dummyUsers'
class AdminChronografPage extends Component {
constructor(props) {
super(props)
this.state = {
organizationName: null,
selectedUsers: [],
filteredUsers: this.props.users,
}
}
isSameUser = (userA, userB) => {
return (
userA.name === userB.name &&
userA.provider === userB.provider &&
userA.scheme === userB.scheme
)
}
handleFilterUsers = organizationName => () => {
const {users} = this.props
const filteredUsers = organizationName
? users.filter(user => {
return user.roles.find(
role => role.organizationName === organizationName
)
})
: users
this.setState({filteredUsers})
}
handleToggleUserSelected = user => e => {
e.preventDefault()
const {selectedUsers} = this.state
const isUserSelected = selectedUsers.find(u => this.isSameUser(user, u))
const newSelectedUsers = isUserSelected
? selectedUsers.filter(u => !this.isSameUser(user, u))
: [...selectedUsers, user]
this.setState({selectedUsers: newSelectedUsers})
}
handleToggleAllUsersSelected = areAllSelected => () => {
const {filteredUsers} = this.state
if (areAllSelected) {
this.setState({selectedUsers: []})
} else {
this.setState({selectedUsers: filteredUsers})
}
}
render() {
const {users} = this.props
const {organizationName, selectedUsers, filteredUsers} = this.state
return (
<div className="page">
<div className="page-header">
<div className="page-header__container">
<div className="page-header__left">
<h1 className="page-header__title">Chronograf Admin</h1>
</div>
<div className="page-header__right">
<SourceIndicator />
<button className="btn btn-primary btn-sm">
<span className="icon plus" />
Create Organization
</button>
</div>
</div>
</div>
<FancyScrollbar className="page-contents">
{users
? <div className="container-fluid">
<div className="row">
<div className="col-xs-12">
<div className="panel panel-minimal">
{Object.keys(selectedUsers).length
? <div className="panel-heading">
<h2 className="panel-title">Batch actions</h2>
</div>
: <div className="panel-heading">
<h2 className="panel-title">
{organizationName
? `Users in ${organizationName}`
: 'Users'}
</h2>
</div>}
<div className="panel-body">
<AllUsersTable
filteredUsers={filteredUsers}
organizationName={organizationName}
onFilterUsers={this.handleFilterUsers}
onToggleUserSelected={this.handleToggleUserSelected}
selectedUsers={selectedUsers}
isSameUser={this.isSameUser}
onToggleAllUsersSelected={
this.handleToggleAllUsersSelected
}
/>
</div>
</div>
</div>
</div>
</div>
: <div className="page-spinner" />}
</FancyScrollbar>
</div>
)
}
}
const {arrayOf, shape} = PropTypes
AdminChronografPage.propTypes = {
users: arrayOf(shape()),
}
AdminChronografPage.defaultProps = {
users: DUMMY_USERS,
}
export default AdminChronografPage
| Show number of users selected on Chronograf admin page
Signed-off-by: Alex Paxton <[email protected]>
| ui/src/admin/containers/AdminChronografPage.js | Show number of users selected on Chronograf admin page | <ide><path>i/src/admin/containers/AdminChronografPage.js
<ide> render() {
<ide> const {users} = this.props
<ide> const {organizationName, selectedUsers, filteredUsers} = this.state
<del>
<add> const numUsersSelected = Object.keys(selectedUsers).length
<ide> return (
<ide> <div className="page">
<ide> <div className="page-header">
<ide> <div className="row">
<ide> <div className="col-xs-12">
<ide> <div className="panel panel-minimal">
<del> {Object.keys(selectedUsers).length
<add> {numUsersSelected
<ide> ? <div className="panel-heading">
<del> <h2 className="panel-title">Batch actions</h2>
<add> <h2 className="panel-title">
<add> {numUsersSelected} User{numUsersSelected > 1 ? 's' : ''}{' '}
<add> Selected
<add> </h2>
<ide> </div>
<ide> : <div className="panel-heading">
<ide> <h2 className="panel-title"> |
|
JavaScript | mpl-2.0 | 5c9f9eecb32fae065f50834fd4c98d027d22f8f1 | 0 | gladly-team/tab,gladly-team/tab,gladly-team/tab | import React from 'react'
import PropTypes from 'prop-types'
class WidgetSharedSpace extends React.Component {
render () {
const main = {
position: 'absolute',
top: 40,
left: 5,
backgroundColor: 'transparent',
width: 300,
height: '80vh',
overflowX: 'hidden',
overflowY: 'scroll'
}
return (
<div style={Object.assign({}, main, this.props.containerStyle)}>
{this.props.children}
</div>
)
}
}
WidgetSharedSpace.propTypes = {
containerStyle: PropTypes.object
}
WidgetSharedSpace.defaultProps = {
containerStyle: {}
}
export default WidgetSharedSpace
| web/src/js/components/General/WidgetSharedSpace.js | import React from 'react'
import PropTypes from 'prop-types'
class WidgetSharedSpace extends React.Component {
render () {
const main = {
position: 'absolute',
top: 50,
left: 5,
backgroundColor: 'transparent',
width: 300,
height: '80vh',
overflowX: 'hidden',
overflowY: 'scroll'
}
return (
<div style={Object.assign({}, main, this.props.containerStyle)}>
{this.props.children}
</div>
)
}
}
WidgetSharedSpace.propTypes = {
containerStyle: PropTypes.object
}
WidgetSharedSpace.defaultProps = {
containerStyle: {}
}
export default WidgetSharedSpace
| Less space above widget.
| web/src/js/components/General/WidgetSharedSpace.js | Less space above widget. | <ide><path>eb/src/js/components/General/WidgetSharedSpace.js
<ide> render () {
<ide> const main = {
<ide> position: 'absolute',
<del> top: 50,
<add> top: 40,
<ide> left: 5,
<ide> backgroundColor: 'transparent',
<ide> width: 300, |
|
Java | bsd-3-clause | 44a146c03d773841e1ba404f1050040271b27dc0 | 0 | dspinellis/UMLGraph,dspinellis/UMLGraph,dspinellis/UMLGraph | package org.umlgraph.doclet;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Comparator;
import java.util.Set;
import java.util.regex.Pattern;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.LanguageVersion;
import com.sun.javadoc.PackageDoc;
import com.sun.javadoc.RootDoc;
import com.sun.tools.doclets.standard.Standard;
/**
* Chaining doclet that runs the standart Javadoc doclet first, and on success,
* runs the generation of dot files by UMLGraph
* @author wolf
*
* @depend - - - WrappedClassDoc
* @depend - - - WrappedRootDoc
*/
public class UmlGraphDoc {
/**
* Option check, forwards options to the standard doclet, if that one refuses them,
* they are sent to UmlGraph
*/
public static int optionLength(String option) {
int result = Standard.optionLength(option);
if (result != 0)
return result;
else
return UmlGraph.optionLength(option);
}
/**
* Standard doclet entry point
* @param root
* @return
*/
public static boolean start(RootDoc root) {
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", running the standard doclet");
Standard.start(root);
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", altering javadocs");
try {
String outputFolder = findOutputPath(root.options());
Options opt = UmlGraph.buildOptions(root);
opt.setOptions(root.options());
// in javadoc enumerations are always printed
opt.showEnumerations = true;
opt.relativeLinksForSourcePackages = true;
// enable strict matching for hide expressions
opt.strictMatching = true;
// root.printNotice(opt.toString());
root = new WrappedRootDoc(root);
generatePackageDiagrams(root, opt, outputFolder);
generateContextDiagrams(root, opt, outputFolder);
} catch(Throwable t) {
root.printWarning("Error!");
root.printWarning(t.toString());
t.printStackTrace();
return false;
}
return true;
}
/**
* Standand doclet entry
* @return
*/
public static LanguageVersion languageVersion() {
return Standard.languageVersion();
}
/**
* Generates the package diagrams for all of the packages that contain classes among those
* returned by RootDoc.class()
*/
private static void generatePackageDiagrams(RootDoc root, Options opt, String outputFolder)
throws IOException {
Set<String> packages = new HashSet<String>();
for (ClassDoc classDoc : root.classes()) {
PackageDoc packageDoc = classDoc.containingPackage();
if(!packages.contains(packageDoc.name())) {
packages.add(packageDoc.name());
OptionProvider view = new PackageView(outputFolder, packageDoc, root, opt);
UmlGraph.buildGraph(root, view, packageDoc);
runGraphviz(opt.dotExecutable, outputFolder, packageDoc.name(), packageDoc.name(), root);
alterHtmlDocs(opt, outputFolder, packageDoc.name(), packageDoc.name(),
"package-summary.html", Pattern.compile("(</[Hh]2>)|(<h1 title=\"Package\").*"), root);
}
}
}
/**
* Generates the context diagram for a single class
*/
private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)
throws IOException {
Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {
public int compare(ClassDoc cd1, ClassDoc cd2) {
return cd1.name().compareTo(cd2.name());
}
});
for (ClassDoc classDoc : root.classes())
classDocs.add(classDoc);
ContextView view = null;
for (ClassDoc classDoc : classDocs) {
if(view == null)
view = new ContextView(outputFolder, classDoc, root, opt);
else
view.setContextCenter(classDoc);
UmlGraph.buildGraph(root, view, classDoc);
runGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);
alterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),
classDoc.name() + ".html", Pattern.compile(".*(Class|Interface|Enum) " + classDoc.name() + ".*") , root);
}
}
/**
* Runs Graphviz dot building both a diagram (in png format) and a client side map for it.
*/
private static void runGraphviz(String dotExecutable, String outputFolder, String packageName, String name, RootDoc root) {
if (dotExecutable == null) {
dotExecutable = "dot";
}
File dotFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".dot");
File svgFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".svg");
try {
Process p = Runtime.getRuntime().exec(new String [] {
dotExecutable,
"-Tsvg",
"-o",
svgFile.getAbsolutePath(),
dotFile.getAbsolutePath()
});
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = null;
while((line = reader.readLine()) != null)
root.printWarning(line);
int result = p.waitFor();
if (result != 0)
root.printWarning("Errors running Graphviz on " + dotFile);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Ensure that dot is in your path and that its path does not contain spaces");
}
}
//Format string for the uml image div tag.
private static final String UML_DIV_TAG =
"<div align=\"center\">" +
"<object width=\"100%\" height=\"100%\" type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>" +
"</div>";
private static final String EXPANDABLE_UML_STYLE = "font-family: Arial,Helvetica,sans-serif;font-size: 1.5em; display: block; width: 250px; height: 20px; background: #009933; padding: 5px; text-align: center; border-radius: 8px; color: white; font-weight: bold;";
//Format string for the java script tag.
private static final String EXPANDABLE_UML =
"<script type=\"text/javascript\">\n" +
"function show() {\n" +
" document.getElementById(\"uml\").innerHTML = \n" +
" \'<a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:hide()\">%3$s</a>\' +\n" +
" \'%1$s\';\n" +
"}\n" +
"function hide() {\n" +
" document.getElementById(\"uml\").innerHTML = \n" +
" \'<a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:show()\">%2$s</a>\' ;\n" +
"}\n" +
"</script>\n" +
"<div id=\"uml\" >\n" +
" <a href=\"javascript:show()\">\n" +
" <a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:show()\">%2$s</a> \n" +
"</div>";
/**
* Takes an HTML file, looks for the first instance of the specified insertion point, and
* inserts the diagram image reference and a client side map in that point.
*/
private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,
String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {
// setup files
File output = new File(outputFolder, packageName.replace(".", "/"));
File htmlFile = new File(output, htmlFileName);
File alteredFile = new File(htmlFile.getAbsolutePath() + ".uml");
if (!htmlFile.exists()) {
System.err.println("Expected file not found: " + htmlFile.getAbsolutePath());
return;
}
// parse & rewrite
BufferedWriter writer = null;
BufferedReader reader = null;
boolean matched = false;
try {
writer = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(alteredFile), opt.outputEncoding));
reader = new BufferedReader(new InputStreamReader(new
FileInputStream(htmlFile), opt.outputEncoding));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
if (!matched && insertPointPattern.matcher(line).matches()) {
matched = true;
String tag = String.format(UML_DIV_TAG, className);
if (opt.collapsibleDiagrams)
tag = String.format(EXPANDABLE_UML, tag, "Show UML class diagram", "Hide UML class diagram");
writer.write("<!-- UML diagram added by UMLGraph version " +
Version.VERSION +
" (http://www.umlgraph.org/) -->");
writer.newLine();
writer.write(tag);
writer.newLine();
}
}
} finally {
if (writer != null)
writer.close();
if (reader != null)
reader.close();
}
// if altered, delete old file and rename new one to the old file name
if (matched) {
htmlFile.delete();
alteredFile.renameTo(htmlFile);
} else {
root.printNotice("Warning, could not find a line that matches the pattern '" + insertPointPattern.pattern()
+ "'.\n Class diagram reference not inserted");
alteredFile.delete();
}
}
/**
* Returns the output path specified on the javadoc options
*/
private static String findOutputPath(String[][] options) {
for (int i = 0; i < options.length; i++) {
if (options[i][0].equals("-d"))
return options[i][1];
}
return ".";
}
}
| src/main/java/org/umlgraph/doclet/UmlGraphDoc.java | package org.umlgraph.doclet;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Comparator;
import java.util.Set;
import java.util.regex.Pattern;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.LanguageVersion;
import com.sun.javadoc.PackageDoc;
import com.sun.javadoc.RootDoc;
import com.sun.tools.doclets.standard.Standard;
/**
* Chaining doclet that runs the standart Javadoc doclet first, and on success,
* runs the generation of dot files by UMLGraph
* @author wolf
*
* @depend - - - WrappedClassDoc
* @depend - - - WrappedRootDoc
*/
public class UmlGraphDoc {
/**
* Option check, forwards options to the standard doclet, if that one refuses them,
* they are sent to UmlGraph
*/
public static int optionLength(String option) {
int result = Standard.optionLength(option);
if (result != 0)
return result;
else
return UmlGraph.optionLength(option);
}
/**
* Standard doclet entry point
* @param root
* @return
*/
public static boolean start(RootDoc root) {
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", running the standard doclet");
Standard.start(root);
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", altering javadocs");
try {
String outputFolder = findOutputPath(root.options());
Options opt = UmlGraph.buildOptions(root);
opt.setOptions(root.options());
// in javadoc enumerations are always printed
opt.showEnumerations = true;
opt.relativeLinksForSourcePackages = true;
// enable strict matching for hide expressions
opt.strictMatching = true;
// root.printNotice(opt.toString());
root = new WrappedRootDoc(root);
generatePackageDiagrams(root, opt, outputFolder);
generateContextDiagrams(root, opt, outputFolder);
} catch(Throwable t) {
root.printWarning("Error!");
root.printWarning(t.toString());
t.printStackTrace();
return false;
}
return true;
}
/**
* Standand doclet entry
* @return
*/
public static LanguageVersion languageVersion() {
return Standard.languageVersion();
}
/**
* Generates the package diagrams for all of the packages that contain classes among those
* returned by RootDoc.class()
*/
private static void generatePackageDiagrams(RootDoc root, Options opt, String outputFolder)
throws IOException {
Set<String> packages = new HashSet<String>();
for (ClassDoc classDoc : root.classes()) {
PackageDoc packageDoc = classDoc.containingPackage();
if(!packages.contains(packageDoc.name())) {
packages.add(packageDoc.name());
OptionProvider view = new PackageView(outputFolder, packageDoc, root, opt);
UmlGraph.buildGraph(root, view, packageDoc);
runGraphviz(opt.dotExecutable, outputFolder, packageDoc.name(), packageDoc.name(), root);
alterHtmlDocs(opt, outputFolder, packageDoc.name(), packageDoc.name(),
"package-summary.html", Pattern.compile("(</[Hh]2>)|(<h1 title=\"Package\").*"), root);
}
}
}
/**
* Generates the context diagram for a single class
*/
private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder)
throws IOException {
Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {
public int compare(ClassDoc cd1, ClassDoc cd2) {
return cd1.name().compareTo(cd2.name());
}
});
for (ClassDoc classDoc : root.classes())
classDocs.add(classDoc);
ContextView view = null;
for (ClassDoc classDoc : classDocs) {
if(view == null)
view = new ContextView(outputFolder, classDoc, root, opt);
else
view.setContextCenter(classDoc);
UmlGraph.buildGraph(root, view, classDoc);
runGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);
alterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),
classDoc.name() + ".html", Pattern.compile(".*(Class|Interface|Enum) " + classDoc.name() + ".*") , root);
}
}
/**
* Runs Graphviz dot building both a diagram (in png format) and a client side map for it.
*/
private static void runGraphviz(String dotExecutable, String outputFolder, String packageName, String name, RootDoc root) {
if (dotExecutable == null) {
dotExecutable = "dot";
}
File dotFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".dot");
File svgFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".svg");
try {
Process p = Runtime.getRuntime().exec(new String [] {
dotExecutable,
"-Tsvg",
"-o",
svgFile.getAbsolutePath(),
dotFile.getAbsolutePath()
});
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = null;
while((line = reader.readLine()) != null)
root.printWarning(line);
int result = p.waitFor();
if (result != 0)
root.printWarning("Errors running Graphviz on " + dotFile);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Ensure that dot is in your path and that its path does not contain spaces");
}
}
//Format string for the uml image div tag.
private static final String UML_DIV_TAG =
"<div align=\"center\">" +
"<object type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>" +
"</div>";
private static final String EXPANDABLE_UML_STYLE = "font-family: Arial,Helvetica,sans-serif;font-size: 1.5em; display: block; width: 250px; height: 20px; background: #009933; padding: 5px; text-align: center; border-radius: 8px; color: white; font-weight: bold;";
//Format string for the java script tag.
private static final String EXPANDABLE_UML =
"<script type=\"text/javascript\">\n" +
"function show() {\n" +
" document.getElementById(\"uml\").innerHTML = \n" +
" \'<a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:hide()\">%3$s</a>\' +\n" +
" \'%1$s\';\n" +
"}\n" +
"function hide() {\n" +
" document.getElementById(\"uml\").innerHTML = \n" +
" \'<a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:show()\">%2$s</a>\' ;\n" +
"}\n" +
"</script>\n" +
"<div id=\"uml\" >\n" +
" <a href=\"javascript:show()\">\n" +
" <a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:show()\">%2$s</a> \n" +
"</div>";
/**
* Takes an HTML file, looks for the first instance of the specified insertion point, and
* inserts the diagram image reference and a client side map in that point.
*/
private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,
String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {
// setup files
File output = new File(outputFolder, packageName.replace(".", "/"));
File htmlFile = new File(output, htmlFileName);
File alteredFile = new File(htmlFile.getAbsolutePath() + ".uml");
if (!htmlFile.exists()) {
System.err.println("Expected file not found: " + htmlFile.getAbsolutePath());
return;
}
// parse & rewrite
BufferedWriter writer = null;
BufferedReader reader = null;
boolean matched = false;
try {
writer = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(alteredFile), opt.outputEncoding));
reader = new BufferedReader(new InputStreamReader(new
FileInputStream(htmlFile), opt.outputEncoding));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
if (!matched && insertPointPattern.matcher(line).matches()) {
matched = true;
String tag = String.format(UML_DIV_TAG, className);
if (opt.collapsibleDiagrams)
tag = String.format(EXPANDABLE_UML, tag, "Show UML class diagram", "Hide UML class diagram");
writer.write("<!-- UML diagram added by UMLGraph version " +
Version.VERSION +
" (http://www.umlgraph.org/) -->");
writer.newLine();
writer.write(tag);
writer.newLine();
}
}
} finally {
if (writer != null)
writer.close();
if (reader != null)
reader.close();
}
// if altered, delete old file and rename new one to the old file name
if (matched) {
htmlFile.delete();
alteredFile.renameTo(htmlFile);
} else {
root.printNotice("Warning, could not find a line that matches the pattern '" + insertPointPattern.pattern()
+ "'.\n Class diagram reference not inserted");
alteredFile.delete();
}
}
/**
* Returns the output path specified on the javadoc options
*/
private static String findOutputPath(String[][] options) {
for (int i = 0; i < options.length; i++) {
if (options[i][0].equals("-d"))
return options[i][1];
}
return ".";
}
}
| Added width and height to svg object tag
| src/main/java/org/umlgraph/doclet/UmlGraphDoc.java | Added width and height to svg object tag | <ide><path>rc/main/java/org/umlgraph/doclet/UmlGraphDoc.java
<ide> //Format string for the uml image div tag.
<ide> private static final String UML_DIV_TAG =
<ide> "<div align=\"center\">" +
<del> "<object type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>" +
<add> "<object width=\"100%\" height=\"100%\" type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>" +
<ide> "</div>";
<ide>
<ide> private static final String EXPANDABLE_UML_STYLE = "font-family: Arial,Helvetica,sans-serif;font-size: 1.5em; display: block; width: 250px; height: 20px; background: #009933; padding: 5px; text-align: center; border-radius: 8px; color: white; font-weight: bold;"; |
|
Java | mit | 4422fe7caf3b33eb70fdc36b2145dea8d05b0d5a | 0 | stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main,stefanbrausch/hudson-main | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import hudson.Util;
import hudson.XmlFile;
import hudson.BulkChange;
import hudson.util.HexBinaryConverter;
import hudson.util.Iterators;
import hudson.util.XStream2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A file being tracked by Hudson.
*
* <p>
* Lifecycle is managed by {@link FingerprintMap}.
*
* @author Kohsuke Kawaguchi
* @see FingerprintMap
*/
@ExportedBean
public class Fingerprint implements ModelObject, Saveable {
/**
* Pointer to a {@link Build}.
*/
@ExportedBean(defaultVisibility=2)
public static class BuildPtr {
final String name;
final int number;
public BuildPtr(String name, int number) {
this.name = name;
this.number = number;
}
public BuildPtr(Run run) {
this( run.getParent().getFullName(), run.getNumber() );
}
/**
* Gets {@link Job#getFullName() the full name of the job}.
* <p>
* Such job could be since then removed,
* so there might not be a corresponding
* {@link Job}.
*/
@Exported
public String getName() {
return name;
}
/**
* Gets the {@link Job} that this pointer points to,
* or null if such a job no longer exists.
*/
public AbstractProject getJob() {
return Hudson.getInstance().getItemByFullName(name,AbstractProject.class);
}
/**
* Gets the project build number.
* <p>
* Such {@link Run} could be since then
* discarded.
*/
@Exported
public int getNumber() {
return number;
}
/**
* Gets the {@link Job} that this pointer points to,
* or null if such a job no longer exists.
*/
public Run getRun() {
Job j = getJob();
if(j==null) return null;
return j.getBuildByNumber(number);
}
private boolean isAlive() {
return getRun()!=null;
}
/**
* Returns true if {@link BuildPtr} points to the given run.
*/
public boolean is(Run r) {
return r.getNumber()==number && r.getParent().getFullName().equals(name);
}
/**
* Returns true if {@link BuildPtr} points to the given job.
*/
public boolean is(Job job) {
return job.getFullName().equals(name);
}
/**
* Returns true if {@link BuildPtr} points to the given job
* or one of its subordinates.
*
* <p>
* This is useful to check if an artifact in MavenModule
* belongs to MavenModuleSet.
*/
public boolean belongsTo(Job job) {
Item p = Hudson.getInstance().getItemByFullName(name);
while(p!=null) {
if(p==job)
return true;
// go up the chain while we
ItemGroup<? extends Item> parent = p.getParent();
if (!(parent instanceof Item)) {
return false;
}
p = (Item) parent;
}
return false;
}
}
/**
* Range of build numbers [start,end). Immutable.
*/
@ExportedBean(defaultVisibility=4)
public static final class Range {
final int start;
final int end;
public Range(int start, int end) {
assert start<end;
this.start = start;
this.end = end;
}
@Exported
public int getStart() {
return start;
}
@Exported
public int getEnd() {
return end;
}
public boolean isSmallerThan(int i) {
return end<=i;
}
public boolean isBiggerThan(int i) {
return i<start;
}
public boolean includes(int i) {
return start<=i && i<end;
}
public Range expandRight() {
return new Range(start,end+1);
}
public Range expandLeft() {
return new Range(start-1,end);
}
public boolean isAdjacentTo(Range that) {
return this.end==that.start;
}
@Override
public String toString() {
return "["+start+","+end+")";
}
/**
* Returns true if two {@link Range}s can't be combined into a single range.
*/
public boolean isIndependent(Range that) {
return this.end<that.start ||that.end<this.start;
}
/**
* Returns true if this range only represents a single number.
*/
public boolean isSingle() {
return end-1==start;
}
/**
* Returns the {@link Range} that combines two ranges.
*/
public Range combine(Range that) {
assert !isIndependent(that);
return new Range(
Math.min(this.start,that.start),
Math.max(this.end ,that.end ));
}
}
/**
* Set of {@link Range}s.
*/
@ExportedBean(defaultVisibility=3)
public static final class RangeSet {
// sorted
private final List<Range> ranges;
public RangeSet() {
this(new ArrayList<Range>());
}
private RangeSet(List<Range> data) {
this.ranges = data;
}
/**
* List all numbers in this range set, in the ascending order.
*/
public Iterable<Integer> listNumbers() {
final List<Range> ranges = getRanges();
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterators.FlattenIterator<Integer,Range>(ranges) {
protected Iterator<Integer> expand(Range range) {
return Iterators.sequence(range.start,range.end).iterator();
}
};
}
};
}
// /**
// * List up builds.
// */
// public <J extends Job<J,R>,R extends Run<J,R>> Iterable<R> listBuilds(final J job) {
// return new Iterable<R>() {
// public Iterator<R> iterator() {
// return new Iterators.FilterIterator<R>(new AdaptedIterator<Integer,R>(listNumbers().iterator()) {
// protected R adapt(Integer n) {
// return job.getBuildByNumber(n);
// }
// }) {
// protected boolean filter(R r) {
// return r!=null;
// }
// };
// }
// };
// }
/**
* List all numbers in this range set in the descending order.
*/
public Iterable<Integer> listNumbersReverse() {
final List<Range> ranges = getRanges();
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterators.FlattenIterator<Integer,Range>(Iterators.reverse(ranges)) {
protected Iterator<Integer> expand(Range range) {
return Iterators.reverseSequence(range.start,range.end).iterator();
}
};
}
};
}
/**
* Gets all the ranges.
*/
@Exported
public synchronized List<Range> getRanges() {
return new ArrayList<Range>(ranges);
}
/**
* Expands the range set to include the given value.
* If the set already includes this number, this will be a no-op.
*/
public synchronized void add(int n) {
for( int i=0; i<ranges.size(); i++ ) {
Range r = ranges.get(i);
if(r.includes(n)) return; // already included
if(r.end==n) {
ranges.set(i,r.expandRight());
checkCollapse(i);
return;
}
if(r.start==n+1) {
ranges.set(i,r.expandLeft());
checkCollapse(i-1);
return;
}
if(r.isBiggerThan(n)) {
// needs to insert a single-value Range
ranges.add(i,new Range(n,n+1));
return;
}
}
ranges.add(new Range(n,n+1));
}
private void checkCollapse(int i) {
if(i<0 || i==ranges.size()-1) return;
Range lhs = ranges.get(i);
Range rhs = ranges.get(i+1);
if(lhs.isAdjacentTo(rhs)) {
// collapsed
Range r = new Range(lhs.start,rhs.end);
ranges.set(i,r);
ranges.remove(i+1);
}
}
public synchronized boolean includes(int i) {
for (Range r : ranges) {
if(r.includes(i))
return true;
}
return false;
}
public synchronized void add(RangeSet that) {
int lhs=0,rhs=0;
while(lhs<this.ranges.size() && rhs<that.ranges.size()) {
Range lr = this.ranges.get(lhs);
Range rr = that.ranges.get(rhs);
// no overlap
if(lr.end<rr.start) {
lhs++;
continue;
}
if(rr.end<lr.start) {
ranges.add(lhs,rr);
lhs++;
rhs++;
continue;
}
// overlap. merge two
Range m = lr.combine(rr);
rhs++;
// since ranges[lhs] is expanded, it might overlap with others in this.ranges
while(lhs+1<this.ranges.size() && !m.isIndependent(this.ranges.get(lhs+1))) {
m = m.combine(this.ranges.get(lhs+1));
this.ranges.remove(lhs+1);
}
this.ranges.set(lhs,m);
}
// if anything is left in that.ranges, add them all
this.ranges.addAll(that.ranges.subList(rhs,that.ranges.size()));
}
@Override
public synchronized String toString() {
StringBuilder buf = new StringBuilder();
for (Range r : ranges) {
if(buf.length()>0) buf.append(',');
buf.append(r);
}
return buf.toString();
}
public synchronized boolean isEmpty() {
return ranges.isEmpty();
}
/**
* Returns the smallest value in this range.
* <p>
* If this range is empty, this method throws an exception.
*/
public synchronized int min() {
return ranges.get(0).start;
}
/**
* Returns the largest value in this range.
* <p>
* If this range is empty, this method throws an exception.
*/
public synchronized int max() {
return ranges.get(ranges.size()-1).end;
}
/**
* Returns true if all the integers logically in this {@link RangeSet}
* is smaller than the given integer. For example, {[1,3)} is smaller than 3,
* but {[1,3),[100,105)} is not smaller than anything less than 105.
*
* Note that {} is smaller than any n.
*/
public synchronized boolean isSmallerThan(int n) {
if(ranges.isEmpty()) return true;
return ranges.get(ranges.size() - 1).isSmallerThan(n);
}
/**
* Parses a {@link RangeSet} from a string like "1-3,5,7-9"
*/
public static RangeSet fromString(String list, boolean skipError) {
RangeSet rs = new RangeSet();
for (String s : Util.tokenize(list,",")) {
s = s.trim();
// s is either single number or range "x-y".
// note that the end range is inclusive in this notation, but not in the Range class
try {
if(s.contains("-")) {
String[] tokens = Util.tokenize(s,"-");
rs.ranges.add(new Range(Integer.parseInt(tokens[0]),Integer.parseInt(tokens[1])+1));
} else {
int n = Integer.parseInt(s);
rs.ranges.add(new Range(n,n+1));
}
} catch (NumberFormatException e) {
if (!skipError)
throw new IllegalArgumentException("Unable to parse "+list);
// ignore malformed text
}
}
return rs;
}
static final class ConverterImpl implements Converter {
private final Converter collectionConv; // used to convert ArrayList in it
public ConverterImpl(Converter collectionConv) {
this.collectionConv = collectionConv;
}
public boolean canConvert(Class type) {
return type==RangeSet.class;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
RangeSet src = (RangeSet) source;
StringBuilder buf = new StringBuilder(src.ranges.size()*10);
for (Range r : src.ranges) {
if(buf.length()>0) buf.append(',');
if(r.isSingle())
buf.append(r.start);
else
buf.append(r.start).append('-').append(r.end-1);
}
writer.setValue(buf.toString());
}
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
if(reader.hasMoreChildren()) {
/* old format where <range> elements are nested like
<range>
<start>1337</start>
<end>1479</end>
</range>
*/
return new RangeSet((List<Range>)(collectionConv.unmarshal(reader,context)));
} else {
return RangeSet.fromString(reader.getValue(),true);
}
}
}
}
private final Date timestamp;
/**
* Null if this fingerprint is for a file that's
* apparently produced outside.
*/
private final BuildPtr original;
private final byte[] md5sum;
private final String fileName;
/**
* Range of builds that use this file keyed by a job full name.
*/
private final Hashtable<String,RangeSet> usages = new Hashtable<String,RangeSet>();
public Fingerprint(Run build, String fileName, byte[] md5sum) throws IOException {
this.original = build==null ? null : new BuildPtr(build);
this.md5sum = md5sum;
this.fileName = fileName;
this.timestamp = new Date();
save();
}
/**
* The first build in which this file showed up,
* if the file looked like it's created there.
* <p>
* This is considered as the "source" of this file,
* or the owner, in the sense that this project "owns"
* this file.
*
* @return null
* if the file is apparently created outside Hudson.
*/
@Exported
public BuildPtr getOriginal() {
return original;
}
public String getDisplayName() {
return fileName;
}
/**
* The file name (like "foo.jar" without path).
*/
@Exported
public String getFileName() {
return fileName;
}
/**
* Gets the MD5 hash string.
*/
@Exported(name="hash")
public String getHashString() {
return Util.toHexString(md5sum);
}
/**
* Gets the timestamp when this record is created.
*/
@Exported
public Date getTimestamp() {
return timestamp;
}
/**
* Gets the string that says how long since this build has scheduled.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public String getTimestampString() {
long duration = System.currentTimeMillis()-timestamp.getTime();
return Util.getPastTimeString(duration);
}
/**
* Gets the build range set for the given job name.
*
* <p>
* These builds of this job has used this file.
*/
public RangeSet getRangeSet(String jobFullName) {
RangeSet r = usages.get(jobFullName);
if(r==null) r = new RangeSet();
return r;
}
public RangeSet getRangeSet(Job job) {
return getRangeSet(job.getFullName());
}
/**
* Gets the sorted list of job names where this jar is used.
*/
public List<String> getJobs() {
List<String> r = new ArrayList<String>();
r.addAll(usages.keySet());
Collections.sort(r);
return r;
}
public Hashtable<String,RangeSet> getUsages() {
return usages;
}
@ExportedBean(defaultVisibility=2)
public static final class RangeItem {
@Exported
public final String name;
@Exported
public final RangeSet ranges;
public RangeItem(String name, RangeSet ranges) {
this.name = name;
this.ranges = ranges;
}
}
// this is for remote API
@Exported(name="usage")
public List<RangeItem> _getUsages() {
List<RangeItem> r = new ArrayList<RangeItem>();
for (Entry<String, RangeSet> e : usages.entrySet())
r.add(new RangeItem(e.getKey(),e.getValue()));
return r;
}
public synchronized void add(AbstractBuild b) throws IOException {
add(b.getParent().getFullName(),b.getNumber());
}
/**
* Records that a build of a job has used this file.
*/
public synchronized void add(String jobFullName, int n) throws IOException {
synchronized(usages) {
RangeSet r = usages.get(jobFullName);
if(r==null) {
r = new RangeSet();
usages.put(jobFullName,r);
}
r.add(n);
}
save();
}
/**
* Returns true if any of the builds recorded in this fingerprint
* is still retained.
*
* <p>
* This is used to find out old fingerprint records that can be removed
* without losing too much information.
*/
public synchronized boolean isAlive() {
if(original!=null && original.isAlive())
return true;
for (Entry<String,RangeSet> e : usages.entrySet()) {
Job j = Hudson.getInstance().getItemByFullName(e.getKey(),Job.class);
if(j==null)
continue;
int oldest = j.getFirstBuild().getNumber();
if(!e.getValue().isSmallerThan(oldest))
return true;
}
return false;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
long start=0;
if(logger.isLoggable(Level.FINE))
start = System.currentTimeMillis();
File file = getFingerprintFile(md5sum);
getConfigFile(file).write(this);
if(logger.isLoggable(Level.FINE))
logger.fine("Saving fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms");
}
public Api getApi() {
return new Api(this);
}
/**
* The file we save our configuration.
*/
private static XmlFile getConfigFile(File file) {
return new XmlFile(XSTREAM,file);
}
/**
* Determines the file name from md5sum.
*/
private static File getFingerprintFile(byte[] md5sum) {
assert md5sum.length==16;
return new File( Hudson.getInstance().getRootDir(),
"fingerprints/"+ Util.toHexString(md5sum,0,1)+'/'+Util.toHexString(md5sum,1,1)+'/'+Util.toHexString(md5sum,2,md5sum.length-2)+".xml");
}
/**
* Loads a {@link Fingerprint} from a file in the image.
*/
/*package*/ static Fingerprint load(byte[] md5sum) throws IOException {
return load(getFingerprintFile(md5sum));
}
/*package*/ static Fingerprint load(File file) throws IOException {
XmlFile configFile = getConfigFile(file);
if(!configFile.exists())
return null;
long start=0;
if(logger.isLoggable(Level.FINE))
start = System.currentTimeMillis();
try {
Fingerprint f = (Fingerprint) configFile.read();
if(logger.isLoggable(Level.FINE))
logger.fine("Loading fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms");
return f;
} catch (IOException e) {
if(file.exists() && file.length()==0) {
// Despite the use of AtomicFile, there are reports indicating that people often see
// empty XML file, presumably either due to file system corruption (perhaps by sudden
// power loss, etc.) or abnormal program termination.
// generally we don't want to wipe out user data just because we can't load it,
// but if the file size is 0, which is what's reported in HUDSON-2012, then it seems
// like recovering it silently by deleting the file is not a bad idea.
logger.log(Level.WARNING, "Size zero fingerprint. Disk corruption? "+configFile,e);
file.delete();
return null;
}
logger.log(Level.WARNING, "Failed to load "+configFile,e);
throw e;
}
}
private static final XStream XSTREAM = new XStream2();
static {
XSTREAM.alias("fingerprint",Fingerprint.class);
XSTREAM.alias("range",Range.class);
XSTREAM.alias("ranges",RangeSet.class);
XSTREAM.registerConverter(new HexBinaryConverter(),10);
XSTREAM.registerConverter(new RangeSet.ConverterImpl(
new CollectionConverter(XSTREAM.getMapper()) {
@Override
protected Object createCollection(Class type) {
return new ArrayList();
}
}
),10);
}
private static final Logger logger = Logger.getLogger(Fingerprint.class.getName());
}
| core/src/main/java/hudson/model/Fingerprint.java | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import hudson.Util;
import hudson.XmlFile;
import hudson.BulkChange;
import hudson.util.HexBinaryConverter;
import hudson.util.Iterators;
import hudson.util.XStream2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A file being tracked by Hudson.
*
* <p>
* Lifecycle is managed by {@link FingerprintMap}.
*
* @author Kohsuke Kawaguchi
* @see FingerprintMap
*/
@ExportedBean
public class Fingerprint implements ModelObject, Saveable {
/**
* Pointer to a {@link Build}.
*/
@ExportedBean(defaultVisibility=2)
public static class BuildPtr {
final String name;
final int number;
public BuildPtr(String name, int number) {
this.name = name;
this.number = number;
}
public BuildPtr(Run run) {
this( run.getParent().getFullName(), run.getNumber() );
}
/**
* Gets {@link Job#getFullName() the full name of the job}.
* <p>
* Such job could be since then removed,
* so there might not be a corresponding
* {@link Job}.
*/
@Exported
public String getName() {
return name;
}
/**
* Gets the {@link Job} that this pointer points to,
* or null if such a job no longer exists.
*/
public AbstractProject getJob() {
return Hudson.getInstance().getItemByFullName(name,AbstractProject.class);
}
/**
* Gets the project build number.
* <p>
* Such {@link Run} could be since then
* discarded.
*/
@Exported
public int getNumber() {
return number;
}
/**
* Gets the {@link Job} that this pointer points to,
* or null if such a job no longer exists.
*/
public Run getRun() {
Job j = getJob();
if(j==null) return null;
return j.getBuildByNumber(number);
}
private boolean isAlive() {
return getRun()!=null;
}
/**
* Returns true if {@link BuildPtr} points to the given run.
*/
public boolean is(Run r) {
return r.getNumber()==number && r.getParent().getFullName().equals(name);
}
/**
* Returns true if {@link BuildPtr} points to the given job.
*/
public boolean is(Job job) {
return job.getFullName().equals(name);
}
/**
* Returns true if {@link BuildPtr} points to the given job
* or one of its subordinates.
*
* <p>
* This is useful to check if an artifact in MavenModule
* belongs to MavenModuleSet.
*/
public boolean belongsTo(Job job) {
Item p = Hudson.getInstance().getItemByFullName(name);
while(p!=null) {
if(p==job)
return true;
// go up the chain while we
ItemGroup<? extends Item> parent = p.getParent();
if (!(parent instanceof Item)) {
return false;
}
p = (Item) parent;
}
return false;
}
}
/**
* Range of build numbers [start,end). Immutable.
*/
@ExportedBean(defaultVisibility=4)
public static final class Range {
final int start;
final int end;
public Range(int start, int end) {
assert start<end;
this.start = start;
this.end = end;
}
@Exported
public int getStart() {
return start;
}
@Exported
public int getEnd() {
return end;
}
public boolean isSmallerThan(int i) {
return end<=i;
}
public boolean isBiggerThan(int i) {
return i<start;
}
public boolean includes(int i) {
return start<=i && i<end;
}
public Range expandRight() {
return new Range(start,end+1);
}
public Range expandLeft() {
return new Range(start-1,end);
}
public boolean isAdjacentTo(Range that) {
return this.end==that.start;
}
@Override
public String toString() {
return "["+start+","+end+")";
}
/**
* Returns true if two {@link Range}s can't be combined into a single range.
*/
public boolean isIndependent(Range that) {
return this.end<that.start ||that.end<this.start;
}
/**
* Returns true if this range only represents a single number.
*/
public boolean isSingle() {
return end-1==start;
}
/**
* Returns the {@link Range} that combines two ranges.
*/
public Range combine(Range that) {
assert !isIndependent(that);
return new Range(
Math.min(this.start,that.start),
Math.max(this.end ,that.end ));
}
}
/**
* Set of {@link Range}s.
*/
@ExportedBean(defaultVisibility=3)
public static final class RangeSet {
// sorted
private final List<Range> ranges;
public RangeSet() {
this(new ArrayList<Range>());
}
private RangeSet(List<Range> data) {
this.ranges = data;
}
/**
* List all numbers in this range set, in the ascending order.
*/
public Iterable<Integer> listNumbers() {
final List<Range> ranges = getRanges();
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterators.FlattenIterator<Integer,Range>(ranges) {
protected Iterator<Integer> expand(Range range) {
return Iterators.sequence(range.start,range.end).iterator();
}
};
}
};
}
// /**
// * List up builds.
// */
// public <J extends Job<J,R>,R extends Run<J,R>> Iterable<R> listBuilds(final J job) {
// return new Iterable<R>() {
// public Iterator<R> iterator() {
// return new Iterators.FilterIterator<R>(new AdaptedIterator<Integer,R>(listNumbers().iterator()) {
// protected R adapt(Integer n) {
// return job.getBuildByNumber(n);
// }
// }) {
// protected boolean filter(R r) {
// return r!=null;
// }
// };
// }
// };
// }
/**
* List all numbers in this range set in the descending order.
*/
public Iterable<Integer> listNumbersReverse() {
final List<Range> ranges = getRanges();
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterators.FlattenIterator<Integer,Range>(Iterators.reverse(ranges)) {
protected Iterator<Integer> expand(Range range) {
return Iterators.reverseSequence(range.start,range.end).iterator();
}
};
}
};
}
/**
* Gets all the ranges.
*/
@Exported
public synchronized List<Range> getRanges() {
return new ArrayList<Range>(ranges);
}
/**
* Expands the range set to include the given value.
* If the set already includes this number, this will be a no-op.
*/
public synchronized void add(int n) {
for( int i=0; i<ranges.size(); i++ ) {
Range r = ranges.get(i);
if(r.includes(n)) return; // already included
if(r.end==n) {
ranges.set(i,r.expandRight());
checkCollapse(i);
return;
}
if(r.start==n+1) {
ranges.set(i,r.expandLeft());
checkCollapse(i-1);
return;
}
if(r.isBiggerThan(n)) {
// needs to insert a single-value Range
ranges.add(i,new Range(n,n+1));
return;
}
}
ranges.add(new Range(n,n+1));
}
private void checkCollapse(int i) {
if(i<0 || i==ranges.size()-1) return;
Range lhs = ranges.get(i);
Range rhs = ranges.get(i+1);
if(lhs.isAdjacentTo(rhs)) {
// collapsed
Range r = new Range(lhs.start,rhs.end);
ranges.set(i,r);
ranges.remove(i+1);
}
}
public synchronized boolean includes(int i) {
for (Range r : ranges) {
if(r.includes(i))
return true;
}
return false;
}
public synchronized void add(RangeSet that) {
int lhs=0,rhs=0;
while(lhs<this.ranges.size() && rhs<that.ranges.size()) {
Range lr = this.ranges.get(lhs);
Range rr = that.ranges.get(rhs);
// no overlap
if(lr.end<rr.start) {
lhs++;
continue;
}
if(rr.end<lr.start) {
ranges.add(lhs,rr);
lhs++;
rhs++;
continue;
}
// overlap. merge two
Range m = lr.combine(rr);
rhs++;
// since ranges[lhs] is expanded, it might overlap with others in this.ranges
while(lhs+1<this.ranges.size() && !m.isIndependent(this.ranges.get(lhs+1))) {
m = m.combine(this.ranges.get(lhs+1));
this.ranges.remove(lhs+1);
}
this.ranges.set(lhs,m);
}
// if anything is left in that.ranges, add them all
this.ranges.addAll(that.ranges.subList(rhs,that.ranges.size()));
}
@Override
public synchronized String toString() {
StringBuffer buf = new StringBuffer();
for (Range r : ranges) {
if(buf.length()>0) buf.append(',');
buf.append(r);
}
return buf.toString();
}
public synchronized boolean isEmpty() {
return ranges.isEmpty();
}
/**
* Returns the smallest value in this range.
* <p>
* If this range is empty, this method throws an exception.
*/
public synchronized int min() {
return ranges.get(0).start;
}
/**
* Returns the largest value in this range.
* <p>
* If this range is empty, this method throws an exception.
*/
public synchronized int max() {
return ranges.get(ranges.size()-1).end;
}
/**
* Returns true if all the integers logically in this {@link RangeSet}
* is smaller than the given integer. For example, {[1,3)} is smaller than 3,
* but {[1,3),[100,105)} is not smaller than anything less than 105.
*
* Note that {} is smaller than any n.
*/
public synchronized boolean isSmallerThan(int n) {
if(ranges.isEmpty()) return true;
return ranges.get(ranges.size() - 1).isSmallerThan(n);
}
/**
* Parses a {@link RangeSet} from a string like "1-3,5,7-9"
*/
public static RangeSet fromString(String list) {
RangeSet rs = new RangeSet();
for (String s : Util.tokenize(list,",")) {
s = s.trim();
// s is either single number or range "x-y".
// note that the end range is inclusive in this notation, but not in the Range class
try {
if(s.contains("-")) {
String[] tokens = Util.tokenize(s,"-");
rs.ranges.add(new Range(Integer.parseInt(tokens[0]),Integer.parseInt(tokens[1])+1));
} else {
int n = Integer.parseInt(s);
rs.ranges.add(new Range(n,n+1));
}
} catch (NumberFormatException e) {
// ignore malformed text
}
}
return rs;
}
static final class ConverterImpl implements Converter {
private final Converter collectionConv; // used to convert ArrayList in it
public ConverterImpl(Converter collectionConv) {
this.collectionConv = collectionConv;
}
public boolean canConvert(Class type) {
return type==RangeSet.class;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
RangeSet src = (RangeSet) source;
StringBuilder buf = new StringBuilder(src.ranges.size()*10);
for (Range r : src.ranges) {
if(buf.length()>0) buf.append(',');
if(r.isSingle())
buf.append(r.start);
else
buf.append(r.start).append('-').append(r.end-1);
}
writer.setValue(buf.toString());
}
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
if(reader.hasMoreChildren()) {
/* old format where <range> elements are nested like
<range>
<start>1337</start>
<end>1479</end>
</range>
*/
return new RangeSet((List<Range>)(collectionConv.unmarshal(reader,context)));
} else {
return RangeSet.fromString(reader.getValue());
}
}
}
}
private final Date timestamp;
/**
* Null if this fingerprint is for a file that's
* apparently produced outside.
*/
private final BuildPtr original;
private final byte[] md5sum;
private final String fileName;
/**
* Range of builds that use this file keyed by a job full name.
*/
private final Hashtable<String,RangeSet> usages = new Hashtable<String,RangeSet>();
public Fingerprint(Run build, String fileName, byte[] md5sum) throws IOException {
this.original = build==null ? null : new BuildPtr(build);
this.md5sum = md5sum;
this.fileName = fileName;
this.timestamp = new Date();
save();
}
/**
* The first build in which this file showed up,
* if the file looked like it's created there.
* <p>
* This is considered as the "source" of this file,
* or the owner, in the sense that this project "owns"
* this file.
*
* @return null
* if the file is apparently created outside Hudson.
*/
@Exported
public BuildPtr getOriginal() {
return original;
}
public String getDisplayName() {
return fileName;
}
/**
* The file name (like "foo.jar" without path).
*/
@Exported
public String getFileName() {
return fileName;
}
/**
* Gets the MD5 hash string.
*/
@Exported(name="hash")
public String getHashString() {
return Util.toHexString(md5sum);
}
/**
* Gets the timestamp when this record is created.
*/
@Exported
public Date getTimestamp() {
return timestamp;
}
/**
* Gets the string that says how long since this build has scheduled.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public String getTimestampString() {
long duration = System.currentTimeMillis()-timestamp.getTime();
return Util.getPastTimeString(duration);
}
/**
* Gets the build range set for the given job name.
*
* <p>
* These builds of this job has used this file.
*/
public RangeSet getRangeSet(String jobFullName) {
RangeSet r = usages.get(jobFullName);
if(r==null) r = new RangeSet();
return r;
}
public RangeSet getRangeSet(Job job) {
return getRangeSet(job.getFullName());
}
/**
* Gets the sorted list of job names where this jar is used.
*/
public List<String> getJobs() {
List<String> r = new ArrayList<String>();
r.addAll(usages.keySet());
Collections.sort(r);
return r;
}
public Hashtable<String,RangeSet> getUsages() {
return usages;
}
@ExportedBean(defaultVisibility=2)
public static final class RangeItem {
@Exported
public final String name;
@Exported
public final RangeSet ranges;
public RangeItem(String name, RangeSet ranges) {
this.name = name;
this.ranges = ranges;
}
}
// this is for remote API
@Exported(name="usage")
public List<RangeItem> _getUsages() {
List<RangeItem> r = new ArrayList<RangeItem>();
for (Entry<String, RangeSet> e : usages.entrySet())
r.add(new RangeItem(e.getKey(),e.getValue()));
return r;
}
public synchronized void add(AbstractBuild b) throws IOException {
add(b.getParent().getFullName(),b.getNumber());
}
/**
* Records that a build of a job has used this file.
*/
public synchronized void add(String jobFullName, int n) throws IOException {
synchronized(usages) {
RangeSet r = usages.get(jobFullName);
if(r==null) {
r = new RangeSet();
usages.put(jobFullName,r);
}
r.add(n);
}
save();
}
/**
* Returns true if any of the builds recorded in this fingerprint
* is still retained.
*
* <p>
* This is used to find out old fingerprint records that can be removed
* without losing too much information.
*/
public synchronized boolean isAlive() {
if(original!=null && original.isAlive())
return true;
for (Entry<String,RangeSet> e : usages.entrySet()) {
Job j = Hudson.getInstance().getItemByFullName(e.getKey(),Job.class);
if(j==null)
continue;
int oldest = j.getFirstBuild().getNumber();
if(!e.getValue().isSmallerThan(oldest))
return true;
}
return false;
}
/**
* Save the settings to a file.
*/
public synchronized void save() throws IOException {
if(BulkChange.contains(this)) return;
long start=0;
if(logger.isLoggable(Level.FINE))
start = System.currentTimeMillis();
File file = getFingerprintFile(md5sum);
getConfigFile(file).write(this);
if(logger.isLoggable(Level.FINE))
logger.fine("Saving fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms");
}
public Api getApi() {
return new Api(this);
}
/**
* The file we save our configuration.
*/
private static XmlFile getConfigFile(File file) {
return new XmlFile(XSTREAM,file);
}
/**
* Determines the file name from md5sum.
*/
private static File getFingerprintFile(byte[] md5sum) {
assert md5sum.length==16;
return new File( Hudson.getInstance().getRootDir(),
"fingerprints/"+ Util.toHexString(md5sum,0,1)+'/'+Util.toHexString(md5sum,1,1)+'/'+Util.toHexString(md5sum,2,md5sum.length-2)+".xml");
}
/**
* Loads a {@link Fingerprint} from a file in the image.
*/
/*package*/ static Fingerprint load(byte[] md5sum) throws IOException {
return load(getFingerprintFile(md5sum));
}
/*package*/ static Fingerprint load(File file) throws IOException {
XmlFile configFile = getConfigFile(file);
if(!configFile.exists())
return null;
long start=0;
if(logger.isLoggable(Level.FINE))
start = System.currentTimeMillis();
try {
Fingerprint f = (Fingerprint) configFile.read();
if(logger.isLoggable(Level.FINE))
logger.fine("Loading fingerprint "+file+" took "+(System.currentTimeMillis()-start)+"ms");
return f;
} catch (IOException e) {
if(file.exists() && file.length()==0) {
// Despite the use of AtomicFile, there are reports indicating that people often see
// empty XML file, presumably either due to file system corruption (perhaps by sudden
// power loss, etc.) or abnormal program termination.
// generally we don't want to wipe out user data just because we can't load it,
// but if the file size is 0, which is what's reported in HUDSON-2012, then it seems
// like recovering it silently by deleting the file is not a bad idea.
logger.log(Level.WARNING, "Size zero fingerprint. Disk corruption? "+configFile,e);
file.delete();
return null;
}
logger.log(Level.WARNING, "Failed to load "+configFile,e);
throw e;
}
}
private static final XStream XSTREAM = new XStream2();
static {
XSTREAM.alias("fingerprint",Fingerprint.class);
XSTREAM.alias("range",Range.class);
XSTREAM.alias("ranges",RangeSet.class);
XSTREAM.registerConverter(new HexBinaryConverter(),10);
XSTREAM.registerConverter(new RangeSet.ConverterImpl(
new CollectionConverter(XSTREAM.getMapper()) {
@Override
protected Object createCollection(Class type) {
return new ArrayList();
}
}
),10);
}
private static final Logger logger = Logger.getLogger(Fingerprint.class.getName());
}
| define a mode that doesn't report an error.
git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@23431 71c3de6d-444a-0410-be80-ed276b4c234a
| core/src/main/java/hudson/model/Fingerprint.java | define a mode that doesn't report an error. | <ide><path>ore/src/main/java/hudson/model/Fingerprint.java
<ide>
<ide> @Override
<ide> public synchronized String toString() {
<del> StringBuffer buf = new StringBuffer();
<add> StringBuilder buf = new StringBuilder();
<ide> for (Range r : ranges) {
<ide> if(buf.length()>0) buf.append(',');
<ide> buf.append(r);
<ide> /**
<ide> * Parses a {@link RangeSet} from a string like "1-3,5,7-9"
<ide> */
<del> public static RangeSet fromString(String list) {
<add> public static RangeSet fromString(String list, boolean skipError) {
<ide> RangeSet rs = new RangeSet();
<ide> for (String s : Util.tokenize(list,",")) {
<ide> s = s.trim();
<ide> rs.ranges.add(new Range(n,n+1));
<ide> }
<ide> } catch (NumberFormatException e) {
<add> if (!skipError)
<add> throw new IllegalArgumentException("Unable to parse "+list);
<ide> // ignore malformed text
<add>
<ide> }
<ide> }
<ide> return rs;
<ide> */
<ide> return new RangeSet((List<Range>)(collectionConv.unmarshal(reader,context)));
<ide> } else {
<del> return RangeSet.fromString(reader.getValue());
<add> return RangeSet.fromString(reader.getValue(),true);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 832e3e3533034082696fb5208dcbe56e43916580 | 0 | jdbi/jdbi,stevenschlansker/jdbi,voidifremoved/jdbi,zanebenefits/jdbi,stevenschlansker/jdbi,11xor6/jdbi,fengshao0907/jdbi,kentyeh/jdbi,zanebenefits/jdbi,john9x/jdbi,pennello/jdbi,christophercurrie/jdbi,omidp/jdbi,BernhardBln/jdbi,hgschmie/jdbi,john9x/jdbi,christophercurrie/jdbi,hgschmie/jdbi,11xor6/jdbi,HubSpot/jdbi,HubSpot/jdbi,fengshao0907/jdbi,hgschmie/jdbi,voidifremoved/jdbi,pennello/jdbi,BernhardBln/jdbi,kentyeh/jdbi,jdbi/jdbi,jdbi/jdbi,omidp/jdbi | package org.skife.jdbi.v2;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.SQLLog;
import org.skife.jdbi.v2.tweak.StatementBuilder;
import org.skife.jdbi.v2.tweak.StatementLocator;
import org.skife.jdbi.v2.tweak.StatementRewriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
/**
* Used for invoking stored procedures.
*/
public class Call extends SQLStatement<Call>
{
private final List<OutParamArgument> params = new ArrayList<OutParamArgument>();
Call(Connection connection,
StatementLocator locator,
StatementRewriter statementRewriter,
StatementBuilder cache,
String sql,
StatementContext ctx,
SQLLog log)
{
super(new Binding(), locator, statementRewriter, connection, cache, sql, ctx, log);
}
/**
* Register output parameter
* @param position
* @param sqlType
* @return
*/
public Call registerOutParameter(int position, int sqlType)
{
return registerOutParameter(position, sqlType, null);
}
public Call registerOutParameter(int position, int sqlType, CallableStatementMapper mapper)
{
getParams().addPositional(position, new OutParamArgument(sqlType, mapper, null));
return this;
}
/**
* Register output parameter
* @param name
* @param sqlType
* @return
*/
public Call registerOutParameter(String name, int sqlType)
{
return registerOutParameter(name, sqlType, null);
}
public Call registerOutParameter(String name, int sqlType, CallableStatementMapper mapper)
{
getParams().addNamed(name, new OutParamArgument(sqlType, mapper, name));
return this;
}
/**
* Invoke the callable statement
* @return
*/
public OutParameters invoke()
{
return this.internalExecute(QueryPreperator.NO_OP, new QueryResultMunger<OutParameters>(){
public OutParameters munge(Statement results) throws SQLException
{
OutParameters out = new OutParameters();
for ( OutParamArgument param : params ) {
Object obj = param.map((CallableStatement)results);
out.getMap().put(param.position, obj);
if ( param.name != null ) {
out.getMap().put(param.name, obj);
}
}
return out;
}
}, QueryPostMungeCleanup.CLOSE_RESOURCES_QUIETLY);
}
private class OutParamArgument implements Argument
{
private final int sqlType;
private final CallableStatementMapper mapper;
private final String name;
private int position ;
public OutParamArgument(int sqlType, CallableStatementMapper mapper, String name)
{
this.sqlType = sqlType;
this.mapper = mapper;
this.name = name;
params.add(this);
}
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException
{
((CallableStatement)statement).registerOutParameter(position, sqlType);
this.position = position ;
}
public Object map(CallableStatement stmt) throws SQLException
{
if ( mapper != null ) {
return mapper.map(position, stmt);
}
switch ( sqlType ) {
case Types.CLOB : case Types.VARCHAR :
case Types.LONGNVARCHAR :
case Types.LONGVARCHAR :
case Types.NCLOB :
case Types.NVARCHAR :
return stmt.getString(position) ;
case Types.BLOB :
case Types.VARBINARY :
return stmt.getBytes(position) ;
case Types.SMALLINT :
return stmt.getShort(position);
case Types.INTEGER :
return stmt.getInt(position);
case Types.BIGINT :
return stmt.getLong(position);
case Types.TIMESTAMP : case Types.TIME :
return stmt.getTimestamp(position) ;
case Types.DATE :
return stmt.getDate(position) ;
case Types.FLOAT :
return stmt.getFloat(position);
case Types.DECIMAL : case Types.DOUBLE :
return stmt.getDouble(position);
default :
return stmt.getObject(position);
}
}
}
}
| src/main/java/org/skife/jdbi/v2/Call.java | package org.skife.jdbi.v2;
import org.skife.jdbi.v2.tweak.Argument;
import org.skife.jdbi.v2.tweak.SQLLog;
import org.skife.jdbi.v2.tweak.StatementBuilder;
import org.skife.jdbi.v2.tweak.StatementLocator;
import org.skife.jdbi.v2.tweak.StatementRewriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
/**
* Used for invoking stored procedures.
*/
public class Call extends SQLStatement<Call>
{
private final List<OutParamArgument> params = new ArrayList<OutParamArgument>();
Call(Connection connection,
StatementLocator locator,
StatementRewriter statementRewriter,
StatementBuilder cache,
String sql,
StatementContext ctx,
SQLLog log)
{
super(new Binding(), locator, statementRewriter, connection, cache, sql, ctx, log);
}
/**
* Register output parameter
* @param position
* @param sqlType
* @return
*/
public Call registerOutParameter(int position, int sqlType)
{
return registerOutParameter(position, sqlType, null);
}
public Call registerOutParameter(int position, int sqlType, CallableStatementMapper mapper)
{
getParams().addPositional(position, new OutParamArgument(sqlType, mapper, null));
return this;
}
/**
* Register output parameter
* @param name
* @param sqlType
* @return
*/
public Call registerOutParameter(String name, int sqlType)
{
return registerOutParameter(name, sqlType, null);
}
public Call registerOutParameter(String name, int sqlType, CallableStatementMapper mapper)
{
getParams().addNamed(name, new OutParamArgument(sqlType, mapper, name));
return this;
}
/**
* Invoke the callable statement
* @return
*/
public OutParameters invoke()
{
return this.internalExecute(QueryPreperator.NO_OP, new QueryResultMunger<OutParameters>(){
public OutParameters munge(Statement results) throws SQLException
{
OutParameters out = new OutParameters();
for ( OutParamArgument param : params ) {
Object obj = param.map((CallableStatement)results);
out.getMap().put(param.position, obj);
if ( param.name != null ) {
out.getMap().put(param.name, obj);
}
}
return out;
}
}, QueryPostMungeCleanup.CLOSE_RESOURCES_QUIETLY);
}
private class OutParamArgument implements Argument
{
private final int sqlType;
private final CallableStatementMapper mapper;
private final String name;
private int position ;
public OutParamArgument(int sqlType, CallableStatementMapper mapper, String name)
{
this.sqlType = sqlType;
this.mapper = mapper;
this.name = name;
params.add(this);
}
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException
{
((CallableStatement)statement).registerOutParameter(position, sqlType);
this.position = position ;
}
public Object map(CallableStatement stmt) throws SQLException
{
if ( mapper != null ) {
return mapper.map(position, stmt);
}
switch ( sqlType ) {
case Types.CLOB : case Types.VARCHAR : case Types.LONGNVARCHAR : case Types.LONGVARCHAR : case Types.NCLOB : case Types.NVARCHAR :
return stmt.getString(position) ;
case Types.BLOB : case Types.VARBINARY :
return stmt.getBytes(position) ;
case Types.SMALLINT :
return stmt.getShort(position);
case Types.INTEGER :
return stmt.getInt(position);
case Types.BIGINT :
return stmt.getLong(position);
case Types.TIMESTAMP : case Types.TIME :
return stmt.getTimestamp(position) ;
case Types.DATE :
return stmt.getDate(position) ;
case Types.FLOAT :
return stmt.getFloat(position);
case Types.DECIMAL : case Types.DOUBLE :
return stmt.getDouble(position);
default :
return stmt.getObject(position);
}
}
}
}
| fix strange formatting.
| src/main/java/org/skife/jdbi/v2/Call.java | fix strange formatting. | <ide><path>rc/main/java/org/skife/jdbi/v2/Call.java
<ide> return mapper.map(position, stmt);
<ide> }
<ide> switch ( sqlType ) {
<del> case Types.CLOB : case Types.VARCHAR : case Types.LONGNVARCHAR : case Types.LONGVARCHAR : case Types.NCLOB : case Types.NVARCHAR :
<add> case Types.CLOB : case Types.VARCHAR :
<add> case Types.LONGNVARCHAR :
<add> case Types.LONGVARCHAR :
<add> case Types.NCLOB :
<add> case Types.NVARCHAR :
<ide> return stmt.getString(position) ;
<del> case Types.BLOB : case Types.VARBINARY :
<add> case Types.BLOB :
<add> case Types.VARBINARY :
<ide> return stmt.getBytes(position) ;
<ide> case Types.SMALLINT :
<ide> return stmt.getShort(position); |
|
JavaScript | mit | 7530d8edbab9da7e261f44d2bad30ec06855df65 | 0 | mercysmart/cepatsembuh,cepatsembuh/cordova,cepatsembuh/cordova,cepatsembuh/cordova,mercysmart/cepatsembuh,mercysmart/cepatsembuh,cepatsembuh/cordova,cepatsembuh/cordova,mercysmart/cepatsembuh,mercysmart/cepatsembuh | /*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/
// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
Firebase.goOnline();
});
// Not available faskes
$('#not-available').on('click', function() {
alert("Faskes is not available")
})
// Get no antrian function
function getNoAntri(tipe, username, name) {
// Define firebase URL
var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Log firebase URL
console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Warn user that this fiture need internet
alert('Fitur ini membutuhkan internet untuk mengambil data');
// Confirmation
alert("Mohon konfirmasi ulang");
var nama = prompt("Masukan nama"),
nik = prompt("Masukan NIK:");
if (nama != "" || nik.length != 16) {
// Firebase
var pasien = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/pasien/');
// Get data
faskesRef.on("value", function(snapshot) {
// Print data
alert('No antrian: ' + snapshot.val().antrian);
// Push data to firebase
pasien.push().set({
nama: nama,
nomor_antrian: snapshot.val().antrian
})
});
} else {
// Error message
swal("Input anda tidak valid. ", "Anda tidak bisa mendapatkan nomor antrian", "error");
}
}
function tempatTidur(tipe, username) {
// Firebase
brea = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + '/faskes/' + username + '/tempat_tidur');
// Log
wait = 'Getting data..';
console.log(wait);
alert(wait);
// Get data
brea.on("value", function(snapshot) {
satu = snapshot.val().satu;
dua = snapshot.val().dua;
tiga = snapshot.val().tiga;
alert("Satu: " + satu + "\n" + "Dua: " + dua + "\n" + "Tiga: " + tiga);
/* swal({
title: "Jumlah Tempat Tidur",
text: text,
type: "success",
html: true
}) */
})
}
function doctorProfile(nama, gambar, lulusan, tahun) {
// Text
giant = "Lulusan: " + lulusan + "<br>" + "Tahun: " + tahun;
name = "dr. " + nama;
image = "../../img/" + gambar;
// Pop-up
alert(name + "\n" + giant);
/* swal({
title: name,
imageUrl: image,
text: giant,
html: true
}) */
}
| www/js/profile.js | /*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/
// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
Firebase.goOnline();
});
// Not available faskes
$('#not-available').on('click', function() {
alert("Faskes is not available")
})
// Get no antrian function
function getNoAntri(tipe, username, name) {
// Define firebase URL
var faskesRef = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Log firebase URL
console.log('Url :' + "https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username);
// Warn user that this fiture need internet
alert('Fitur ini membutuhkan internet untuk mengambil data');
// Confirmation
alert("Mohon konfirmasi ulang");
var nama = prompt("Masukan nama"),
nik = prompt("Masukan NIK:");
if (nama != "" || nik.length != 16) {
// Firebase
var pasien = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + "/faskes/" + username + '/pasien/');
// Get data
faskesRef.on("value", function(snapshot) {
// Print data
alert('No antrian: ' + snapshot.val().antrian);
// Push data to firebase
pasien.push().set({
nama: nama,
nomor_antrian: snapshot.val().antrian
})
});
} else {
// Error message
swal("Input anda tidak valid. ", "Anda tidak bisa mendapatkan nomor antrian", "error");
}
}
function tempatTidur(tipe, username) {
// Firebase
brea = new Firebase("https://cepatsembuh.firebaseio.com/" + tipe + '/faskes/' + username + '/tempat_tidur');
// Log
wait = 'Getting data..';
console.log(wait);
alert(wait);
// Get data
brea.on("value", function(snapshot) {
satu = snapshot.val().satu;
dua = snapshot.val().dua;
tiga = snapshot.val().tiga;
alert("Satu: " + satu + "\n" + "Dua: " + dua + "\n" + "Tiga: " + tiga);
/* swal({
title: "Jumlah Tempat Tidur",
text: text,
type: "success",
html: true
}) */
})
}
function doctorProfile(nama, gambar, lulusan, tahun) {
// Text
giant = "Lulusan: " + lulusan + "<br>" + "Tahun: " + tahun;
name = "dr. " + nama;
image = "../../img/" + gambar;
// Pop-up
swal({
title: name,
imageUrl: image,
text: giant,
html: true
})
}
| Replace swal with basic alert
| www/js/profile.js | Replace swal with basic alert | <ide><path>ww/js/profile.js
<ide> image = "../../img/" + gambar;
<ide>
<ide> // Pop-up
<del> swal({
<add> alert(name + "\n" + giant);
<add> /* swal({
<ide> title: name,
<ide> imageUrl: image,
<ide> text: giant,
<ide> html: true
<del> })
<add> }) */
<ide> } |
|
Java | epl-1.0 | e116ffbffe3eeefe52a39da3419316f37cc8b408 | 0 | gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime | /*******************************************************************************
* Copyright (c) 1998, 2009 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.history;
import java.util.*;
import org.eclipse.persistence.history.*;
import org.eclipse.persistence.internal.helper.*;
import org.eclipse.persistence.internal.history.*;
import org.eclipse.persistence.mappings.*;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.queries.*;
import org.eclipse.persistence.sessions.broker.*;
import org.eclipse.persistence.tools.schemaframework.*;
import org.eclipse.persistence.sessions.server.*;
/**
* <b>Purpose:</b>One stop shopping for all your history needs.
* <p>
* @author Stephen McRitchie
* @since Oracle 10g AS
*/
public class HistoryFacade {
private static Map timeOffsetsMap = new IdentityHashMap();
protected HistoryFacade() {
}
protected static void buildHistoricalTableDefinition(HistoryPolicy policy,
String name,
TableDefinition def,
TableCreator creator) {
if (def == null) {
return;
}
TableDefinition histDef = (TableDefinition)def.clone();
histDef.setName(name);
FieldDefinition fieldDef = new FieldDefinition();
fieldDef.setName(policy.getStartFieldName());
fieldDef.setType(ClassConstants.TIMESTAMP);
histDef.addField(fieldDef);
fieldDef = new FieldDefinition();
fieldDef.setName(policy.getEndFieldName());
fieldDef.setType(ClassConstants.TIMESTAMP);
histDef.addField(fieldDef);
histDef.setForeignKeys(new Vector());
for (Enumeration enumtr = histDef.getFields().elements();
enumtr.hasMoreElements(); ) {
FieldDefinition fieldDef2 = (FieldDefinition)enumtr.nextElement();
// For now foreign key constraints are not supported, because shallow inserts are not...
fieldDef2.setForeignKeyFieldName(null);
if (fieldDef2.getName().equals("ROW_START") &&
(!histDef.getPrimaryKeyFieldNames().isEmpty())) {
fieldDef2.setIsPrimaryKey(true);
}
if (fieldDef2.getName().equals("VERSION") &&
(!histDef.getPrimaryKeyFieldNames().isEmpty())) {
fieldDef2.setIsPrimaryKey(true);
}
}
creator.addTableDefinition(histDef);
}
public static long currentDatabaseTimeMillis(org.eclipse.persistence.sessions.Session session) {
return currentDatabaseTimeMillis(session, null);
}
/**
* PUBLIC:
*/
public static long currentDatabaseTimeMillis(org.eclipse.persistence.sessions.Session session,
Class domainClass) {
Session rootSession = session;
while (rootSession.isUnitOfWork() || rootSession.isClientSession() ||
rootSession instanceof HistoricalSession ||
rootSession.isSessionBroker()) {
if (rootSession.isUnitOfWork()) {
rootSession = ((UnitOfWork)rootSession).getParent();
} else if (rootSession.isClientSession()) {
rootSession = ((ClientSession)rootSession).getParent();
} else if (rootSession instanceof HistoricalSession) {
rootSession = ((HistoricalSession)rootSession).getParent();
} else {
SessionBroker broker = (SessionBroker)rootSession;
rootSession = broker.getSessionForClass(domainClass);
if (rootSession == broker) {
break;
}
}
}
if (timeOffsetsMap.containsKey(rootSession)) {
Long offset = (Long)timeOffsetsMap.get(rootSession);
return System.currentTimeMillis() + offset.longValue();
} else {
DatabaseQuery query =
rootSession.getPlatform().getTimestampQuery();
long startTime = System.currentTimeMillis();
java.sql.Timestamp databaseTime =
(java.sql.Timestamp)rootSession.executeQuery(query);
long endTime = System.currentTimeMillis();
long jvmTime = (endTime - startTime) / 2 + startTime;
long offset = databaseTime.getTime() - jvmTime;
timeOffsetsMap.put(rootSession, new Long(offset));
return jvmTime + offset;
}
}
/**
* PUBLIC:
* Generates a mirroring historical schema given a
* conventional schema and a session with HistoryPolicies set on
* the descriptors.
*/
public static void generateHistoricalTableDefinitions(TableCreator creator,
org.eclipse.persistence.sessions.Session session) {
// First add all table definitions to a hashtable.
Hashtable tableDefinitions =
new Hashtable(creator.getTableDefinitions().size());
for (Enumeration enumtr = creator.getTableDefinitions().elements();
enumtr.hasMoreElements(); ) {
DatabaseObjectDefinition def =
(DatabaseObjectDefinition)enumtr.nextElement();
tableDefinitions.put(def.getFullName(), def);
}
for (Iterator iterator = session.getDescriptors().values().iterator();
iterator.hasNext(); ) {
ClassDescriptor descriptor = (ClassDescriptor)iterator.next();
HistoryPolicy policy = descriptor.getHistoryPolicy();
if (policy != null) {
Vector names = policy.getHistoryTableNames();
for (int i = 0; i < descriptor.getTableNames().size(); i++) {
String name =
(String)descriptor.getTableNames().elementAt(i);
String histName = (String)names.elementAt(i);
TableDefinition def =
(TableDefinition)tableDefinitions.get(name);
buildHistoricalTableDefinition(policy, histName, def,
creator);
}
}
for (Enumeration mappings = descriptor.getMappings().elements();
mappings.hasMoreElements(); ) {
DatabaseMapping mapping =
(DatabaseMapping)mappings.nextElement();
if (mapping.isManyToManyMapping()) {
ManyToManyMapping m2mMapping = (ManyToManyMapping)mapping;
policy = m2mMapping.getHistoryPolicy();
if (policy != null) {
String name = m2mMapping.getRelationTableName();
String histName =
(String)policy.getHistoryTableNames().elementAt(0);
TableDefinition def =
(TableDefinition)tableDefinitions.get(name);
buildHistoricalTableDefinition(policy, histName, def,
creator);
}
} else if (mapping.isDirectCollectionMapping()) {
DirectCollectionMapping dcMapping =
(DirectCollectionMapping)mapping;
policy = dcMapping.getHistoryPolicy();
if (policy != null) {
String name = dcMapping.getReferenceTableName();
String histName =
(String)policy.getHistoryTableNames().elementAt(0);
TableDefinition def =
(TableDefinition)tableDefinitions.get(name);
buildHistoricalTableDefinition(policy, histName, def,
creator);
}
}
}
}
}
/**
* PUBLIC:
* Generates HistoryPolicies for a given object model. The policies
* are of the recommended form, with START/END, and the history table name
* being the current table name with a _HIST suffix. Hence Employee would
* become Employee_Hist.
*/
public static void generateHistoryPolicies(Iterator descriptors) {
HistoryPolicy basePolicy = new HistoryPolicy();
basePolicy.addStartFieldName("ROW_START");
basePolicy.addEndFieldName("ROW_END");
HistoryPolicy policy = null;
while (descriptors.hasNext()) {
ClassDescriptor descriptor = (ClassDescriptor)descriptors.next();
policy = (HistoryPolicy)basePolicy.clone();
List<DatabaseTable> tables = descriptor.getTables();
int size = tables.size();
if (size == 0) {
continue;
}
for (int i = 0; i < size; i++) {
DatabaseTable table = tables.get(i);
String name = table.getQualifiedNameDelimited();
String historicalName;
if(table.shouldUseDelimiters()) {
historicalName = name.substring(0, name.length() - 1) + "_HIST" + Helper.getEndDatabaseDelimiter();
} else {
historicalName = name + "_HIST";
}
policy.addHistoryTableName(name, historicalName);
}
descriptor.setHistoryPolicy(policy);
for (Enumeration mappings = descriptor.getMappings().elements();
mappings.hasMoreElements(); ) {
DatabaseMapping mapping =
(DatabaseMapping)mappings.nextElement();
if (mapping instanceof ManyToManyMapping) {
ManyToManyMapping m2mMapping = (ManyToManyMapping)mapping;
policy = (HistoryPolicy)basePolicy.clone();
policy.addHistoryTableName(m2mMapping.getRelationTableName() +
"_HIST");
m2mMapping.setHistoryPolicy(policy);
} else if (mapping instanceof DirectCollectionMapping) {
DirectCollectionMapping dcMapping =
(DirectCollectionMapping)mapping;
policy = (HistoryPolicy)basePolicy.clone();
policy.addHistoryTableName(dcMapping.getReferenceTableName() +
"_HIST");
dcMapping.setHistoryPolicy(policy);
}
}
}
}
public static void generateHistoryPolicies(org.eclipse.persistence.sessions.Project project) {
generateHistoryPolicies(project.getDescriptors().values().iterator());
}
public static void generateHistoryPolicies(org.eclipse.persistence.sessions.Session session) {
generateHistoryPolicies(session.getDescriptors().values().iterator());
}
}
| foundation/eclipselink.core.test/src/org/eclipse/persistence/tools/history/HistoryFacade.java | /*******************************************************************************
* Copyright (c) 1998, 2009 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.history;
import java.util.*;
import org.eclipse.persistence.history.*;
import org.eclipse.persistence.internal.helper.*;
import org.eclipse.persistence.internal.history.*;
import org.eclipse.persistence.mappings.*;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.queries.*;
import org.eclipse.persistence.sessions.broker.*;
import org.eclipse.persistence.tools.schemaframework.*;
import org.eclipse.persistence.sessions.server.*;
/**
* <b>Purpose:</b>One stop shopping for all your history needs.
* <p>
* @author Stephen McRitchie
* @since Oracle 10g AS
*/
public class HistoryFacade {
private static Map timeOffsetsMap = new IdentityHashMap();
protected HistoryFacade() {
}
protected static void buildHistoricalTableDefinition(HistoryPolicy policy,
String name,
TableDefinition def,
TableCreator creator) {
if (def == null) {
return;
}
TableDefinition histDef = (TableDefinition)def.clone();
histDef.setName(name);
FieldDefinition fieldDef = new FieldDefinition();
fieldDef.setName(policy.getStartFieldName());
fieldDef.setType(ClassConstants.TIMESTAMP);
histDef.addField(fieldDef);
fieldDef = new FieldDefinition();
fieldDef.setName(policy.getEndFieldName());
fieldDef.setType(ClassConstants.TIMESTAMP);
histDef.addField(fieldDef);
histDef.setForeignKeys(new Vector());
for (Enumeration enumtr = histDef.getFields().elements();
enumtr.hasMoreElements(); ) {
FieldDefinition fieldDef2 = (FieldDefinition)enumtr.nextElement();
// For now foreign key constraints are not supported, because shallow inserts are not...
fieldDef2.setForeignKeyFieldName(null);
if (fieldDef2.getName().equals("ROW_START") &&
(!histDef.getPrimaryKeyFieldNames().isEmpty())) {
fieldDef2.setIsPrimaryKey(true);
}
if (fieldDef2.getName().equals("VERSION") &&
(!histDef.getPrimaryKeyFieldNames().isEmpty())) {
fieldDef2.setIsPrimaryKey(true);
}
}
creator.addTableDefinition(histDef);
}
public static long currentDatabaseTimeMillis(org.eclipse.persistence.sessions.Session session) {
return currentDatabaseTimeMillis(session, null);
}
/**
* PUBLIC:
*/
public static long currentDatabaseTimeMillis(org.eclipse.persistence.sessions.Session session,
Class domainClass) {
Session rootSession = session;
while (rootSession.isUnitOfWork() || rootSession.isClientSession() ||
rootSession instanceof HistoricalSession ||
rootSession.isSessionBroker()) {
if (rootSession.isUnitOfWork()) {
rootSession = ((UnitOfWork)rootSession).getParent();
} else if (rootSession.isClientSession()) {
rootSession = ((ClientSession)rootSession).getParent();
} else if (rootSession instanceof HistoricalSession) {
rootSession = ((HistoricalSession)rootSession).getParent();
} else {
SessionBroker broker = (SessionBroker)rootSession;
rootSession = broker.getSessionForClass(domainClass);
if (rootSession == broker) {
break;
}
}
}
if (timeOffsetsMap.containsKey(rootSession)) {
Long offset = (Long)timeOffsetsMap.get(rootSession);
return System.currentTimeMillis() + offset.longValue();
} else {
DatabaseQuery query =
rootSession.getPlatform().getTimestampQuery();
long startTime = System.currentTimeMillis();
java.sql.Timestamp databaseTime =
(java.sql.Timestamp)rootSession.executeQuery(query);
long endTime = System.currentTimeMillis();
long jvmTime = (endTime - startTime) / 2 + startTime;
long offset = databaseTime.getTime() - jvmTime;
timeOffsetsMap.put(rootSession, new Long(offset));
return jvmTime + offset;
}
}
/**
* PUBLIC:
* Generates a mirroring historical schema given a
* conventional schema and a session with HistoryPolicies set on
* the descriptors.
*/
public static void generateHistoricalTableDefinitions(TableCreator creator,
org.eclipse.persistence.sessions.Session session) {
// First add all table definitions to a hashtable.
Hashtable tableDefinitions =
new Hashtable(creator.getTableDefinitions().size());
for (Enumeration enumtr = creator.getTableDefinitions().elements();
enumtr.hasMoreElements(); ) {
DatabaseObjectDefinition def =
(DatabaseObjectDefinition)enumtr.nextElement();
tableDefinitions.put(def.getFullName(), def);
}
for (Iterator iterator = session.getDescriptors().values().iterator();
iterator.hasNext(); ) {
ClassDescriptor descriptor = (ClassDescriptor)iterator.next();
HistoryPolicy policy = descriptor.getHistoryPolicy();
if (policy != null) {
Vector names = policy.getHistoryTableNames();
for (int i = 0; i < descriptor.getTableNames().size(); i++) {
String name =
(String)descriptor.getTableNames().elementAt(i);
String histName = (String)names.elementAt(i);
TableDefinition def =
(TableDefinition)tableDefinitions.get(name);
buildHistoricalTableDefinition(policy, histName, def,
creator);
}
}
for (Enumeration mappings = descriptor.getMappings().elements();
mappings.hasMoreElements(); ) {
DatabaseMapping mapping =
(DatabaseMapping)mappings.nextElement();
if (mapping.isManyToManyMapping()) {
ManyToManyMapping m2mMapping = (ManyToManyMapping)mapping;
policy = m2mMapping.getHistoryPolicy();
if (policy != null) {
String name = m2mMapping.getRelationTableName();
String histName =
(String)policy.getHistoryTableNames().elementAt(0);
TableDefinition def =
(TableDefinition)tableDefinitions.get(name);
buildHistoricalTableDefinition(policy, histName, def,
creator);
}
} else if (mapping.isDirectCollectionMapping()) {
DirectCollectionMapping dcMapping =
(DirectCollectionMapping)mapping;
policy = dcMapping.getHistoryPolicy();
if (policy != null) {
String name = dcMapping.getReferenceTableName();
String histName =
(String)policy.getHistoryTableNames().elementAt(0);
TableDefinition def =
(TableDefinition)tableDefinitions.get(name);
buildHistoricalTableDefinition(policy, histName, def,
creator);
}
}
}
}
}
/**
* PUBLIC:
* Generates HistoryPolicies for a given object model. The policies
* are of the recommended form, with START/END, and the history table name
* being the current table name with a _HIST suffix. Hence Employee would
* become Employee_Hist.
*/
public static void generateHistoryPolicies(Iterator descriptors) {
HistoryPolicy basePolicy = new HistoryPolicy();
basePolicy.addStartFieldName("ROW_START");
basePolicy.addEndFieldName("ROW_END");
HistoryPolicy policy = null;
while (descriptors.hasNext()) {
ClassDescriptor descriptor = (ClassDescriptor)descriptors.next();
policy = (HistoryPolicy)basePolicy.clone();
Vector tableNames = descriptor.getTableNames();
if (tableNames.size() == 0) {
continue;
}
for (int i = 0; i < tableNames.size(); i++) {
String name = (String)tableNames.elementAt(i);
policy.addHistoryTableName(name, name + "_HIST");
}
descriptor.setHistoryPolicy(policy);
for (Enumeration mappings = descriptor.getMappings().elements();
mappings.hasMoreElements(); ) {
DatabaseMapping mapping =
(DatabaseMapping)mappings.nextElement();
if (mapping instanceof ManyToManyMapping) {
ManyToManyMapping m2mMapping = (ManyToManyMapping)mapping;
policy = (HistoryPolicy)basePolicy.clone();
policy.addHistoryTableName(m2mMapping.getRelationTableName() +
"_HIST");
m2mMapping.setHistoryPolicy(policy);
} else if (mapping instanceof DirectCollectionMapping) {
DirectCollectionMapping dcMapping =
(DirectCollectionMapping)mapping;
policy = (HistoryPolicy)basePolicy.clone();
policy.addHistoryTableName(dcMapping.getReferenceTableName() +
"_HIST");
dcMapping.setHistoryPolicy(policy);
}
}
}
}
public static void generateHistoryPolicies(org.eclipse.persistence.sessions.Project project) {
generateHistoryPolicies(project.getDescriptors().values().iterator());
}
public static void generateHistoryPolicies(org.eclipse.persistence.sessions.Session session) {
generateHistoryPolicies(session.getDescriptors().values().iterator());
}
}
| Fixed historical name to accommodate delimiters.
| foundation/eclipselink.core.test/src/org/eclipse/persistence/tools/history/HistoryFacade.java | Fixed historical name to accommodate delimiters. | <ide><path>oundation/eclipselink.core.test/src/org/eclipse/persistence/tools/history/HistoryFacade.java
<ide> while (descriptors.hasNext()) {
<ide> ClassDescriptor descriptor = (ClassDescriptor)descriptors.next();
<ide> policy = (HistoryPolicy)basePolicy.clone();
<del> Vector tableNames = descriptor.getTableNames();
<del> if (tableNames.size() == 0) {
<add> List<DatabaseTable> tables = descriptor.getTables();
<add> int size = tables.size();
<add> if (size == 0) {
<ide> continue;
<ide> }
<del> for (int i = 0; i < tableNames.size(); i++) {
<del> String name = (String)tableNames.elementAt(i);
<del> policy.addHistoryTableName(name, name + "_HIST");
<add> for (int i = 0; i < size; i++) {
<add> DatabaseTable table = tables.get(i);
<add> String name = table.getQualifiedNameDelimited();
<add> String historicalName;
<add> if(table.shouldUseDelimiters()) {
<add> historicalName = name.substring(0, name.length() - 1) + "_HIST" + Helper.getEndDatabaseDelimiter();
<add> } else {
<add> historicalName = name + "_HIST";
<add> }
<add> policy.addHistoryTableName(name, historicalName);
<ide> }
<ide> descriptor.setHistoryPolicy(policy);
<ide> |
|
Java | apache-2.0 | 34c1e190bd031b20915ddd63af36ba6bba8f6ace | 0 | Transcordia/ringojs,ashwinrayaprolu1984/ringojs,oberhamsi/ringojs,oberhamsi/ringojs,ringo/ringojs,ringo/ringojs,oberhamsi/ringojs,Transcordia/ringojs,ashwinrayaprolu1984/ringojs,ringo/ringojs,Transcordia/ringojs,Transcordia/ringojs,ashwinrayaprolu1984/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs | /*
* Copyright 2008 Hannes Wallnoefer <[email protected]>
*
* 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 org.ringojs.tools;
import jline.Completor;
import jline.ConsoleReader;
import jline.History;
import org.ringojs.engine.ModuleScope;
import org.ringojs.engine.RhinoEngine;
import org.ringojs.repository.Repository;
import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.ToolErrorReporter;
import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.security.CodeSource;
import java.security.CodeSigner;
/**
* RingoShell is a simple interactive shell that provides the
* additional global functions implemented by Ringo.
*/
public class RingoShell {
RingoConfiguration config;
RhinoEngine engine;
Scriptable scope;
boolean silent;
File history;
CodeSource codeSource = null;
public RingoShell() throws IOException {
this(RhinoEngine.getEngine(), null, false);
}
public RingoShell(RhinoEngine engine) throws IOException {
this(engine, null, false);
}
public RingoShell(RhinoEngine engine, File history, boolean silent)
throws IOException {
this.config = engine.getConfiguration();
this.engine = engine;
this.history = history;
this.scope = engine.getShellScope();
this.silent = silent;
// FIXME give shell code a trusted code source in case security is on
if (config.isPolicyEnabled()) {
Repository modules = config.getRingoHome().getChildRepository("modules");
codeSource = new CodeSource(modules.getUrl(), (CodeSigner[])null);
}
}
public void run() throws IOException {
if (silent) {
// bypass console if running with redirected stdin or stout
runSilently();
return;
}
ConsoleReader reader = new ConsoleReader();
reader.setBellEnabled(false);
// reader.setDebug(new PrintWriter(new FileWriter("jline.debug")));
reader.addCompletor(new JSCompletor());
if (history == null) {
history = new File(System.getProperty("user.home"), ".ringo-history");
}
reader.setHistory(new History(history));
PrintStream out = System.out;
int lineno = 0;
repl: while (true) {
Context cx = engine.getContextFactory().enterContext();
cx.setErrorReporter(new ToolErrorReporter(false, System.err));
String source = "";
String prompt = getPrompt();
while (true) {
String newline = reader.readLine(prompt);
if (newline == null) {
// NULL input, if e.g. Ctrl-D was pressed
out.println();
out.flush();
break repl;
}
source = source + newline + "\n";
lineno++;
if (cx.stringIsCompilableUnit(source)) {
break;
}
prompt = getSecondaryPrompt();
}
try {
Script script = cx.compileString(source, "<stdin>", lineno, codeSource);
Object result = script.exec(cx, scope);
printResult(result, out);
lineno++;
// trigger GC once in a while - if we run in non-interpreter mode
// we generate a lot of classes to unload
if (lineno % 10 == 0) {
System.gc();
}
} catch (Exception ex) {
// TODO: shouldn't this print to System.err?
printError(ex, System.out, config.isVerbose());
} finally {
Context.exit();
}
}
System.exit(0);
}
protected String getPrompt() {
return ">> ";
}
protected String getSecondaryPrompt() {
return ".. ";
}
protected void printResult(Object result, PrintStream out) {
// Avoid printing out undefined or function definitions.
if (result != Context.getUndefinedValue()) {
out.println(Context.toString(result));
}
out.flush();
}
protected void printError(Exception ex, PrintStream out, boolean verbose) {
// default implementation forwards to RingoRunner.reportError()
RingoRunner.reportError(ex, out, verbose);
}
private void runSilently() throws IOException {
int lineno = 0;
outer: while (true) {
Context cx = engine.getContextFactory().enterContext();
cx.setErrorReporter(new ToolErrorReporter(false, System.err));
cx.setOptimizationLevel(-1);
String source = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line == null) {
// reached EOF
break outer;
}
source = source + line + "\n";
lineno++;
if (cx.stringIsCompilableUnit(source))
break;
}
try {
cx.evaluateString(scope, source, "<stdin>", lineno, codeSource);
lineno++;
} catch (Exception ex) {
printError(ex, System.err, config.isVerbose());
} finally {
Context.exit();
}
}
System.exit(0);
}
class JSCompletor implements Completor {
Pattern variables = Pattern.compile(
"(^|\\s|[^\\w\\.'\"])([\\w\\.]+)$");
Pattern keywords = Pattern.compile(
"(^|\\s)([\\w]+)$");
public int complete(String s, int i, List list) {
int start = i;
try {
Matcher match = keywords.matcher(s);
if (match.find() && s.length() == i) {
String word = match.group(2);
for(String str: jsKeywords) {
if (str.startsWith(word)) {
list.add(str);
}
}
}
match = variables.matcher(s);
if (match.find() && s.length() == i) {
String word = match.group(2);
Scriptable obj = scope;
String[] parts = word.split("\\.", -1);
for (int k = 0; k < parts.length - 1; k++) {
Object o = ScriptableObject.getProperty(obj, parts[k]);
if (o == null || o == ScriptableObject.NOT_FOUND) {
return start;
}
obj = ScriptRuntime.toObject(scope, o);
}
String lastpart = parts[parts.length - 1];
// set return value to beginning of word we're replacing
start = i - lastpart.length();
while (obj != null) {
// System.err.println(word + " -- " + obj);
Object[] ids = obj.getIds();
collectIds(ids, obj, word, lastpart, list);
if (list.isEmpty() && obj instanceof ScriptableObject) {
ids = ((ScriptableObject) obj).getAllIds();
collectIds(ids, obj, word, lastpart, list);
}
if (word.endsWith(".") && obj instanceof ModuleScope) {
// don't walk scope prototype chain if nothing to compare yet -
// the list is just too long.
break;
}
obj = obj.getPrototype();
}
}
} catch (Exception ignore) {
// ignore.printStackTrace();
}
Collections.sort(list);
return start;
}
private void collectIds(Object[] ids, Scriptable obj, String word, String lastpart, List list) {
for(Object id: ids) {
if (!(id instanceof String)) {
continue;
}
String str = (String) id;
if (str.startsWith(lastpart) || word.endsWith(".")) {
if (ScriptableObject.getProperty(obj, str) instanceof Callable) {
list.add(str + "(");
} else {
list.add(str);
}
}
}
}
}
static String[] jsKeywords =
new String[] {
"break",
"case",
"catch",
"continue",
"default",
"delete",
"do",
"else",
"finally",
"for",
"function",
"if",
"in",
"instanceof",
"new",
"return",
"switch",
"this",
"throw",
"try",
"typeof",
"var",
"void",
"while",
"with"
};
}
| src/org/ringojs/tools/RingoShell.java | /*
* Copyright 2008 Hannes Wallnoefer <[email protected]>
*
* 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 org.ringojs.tools;
import jline.Completor;
import jline.ConsoleReader;
import jline.History;
import org.ringojs.engine.ModuleScope;
import org.ringojs.engine.RhinoEngine;
import org.ringojs.repository.Repository;
import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.ToolErrorReporter;
import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.security.CodeSource;
import java.security.CodeSigner;
/**
* RingoShell is a simple interactive shell that provides the
* additional global functions implemented by Ringo.
*/
public class RingoShell {
RingoConfiguration config;
RhinoEngine engine;
Scriptable scope;
boolean silent;
File history;
CodeSource codeSource = null;
public RingoShell(RhinoEngine engine) throws IOException {
this(engine, null, false);
}
public RingoShell(RhinoEngine engine, File history, boolean silent)
throws IOException {
this.config = engine.getConfiguration();
this.engine = engine;
this.history = history;
this.scope = engine.getShellScope();
this.silent = silent;
// FIXME give shell code a trusted code source in case security is on
if (config.isPolicyEnabled()) {
Repository modules = config.getRingoHome().getChildRepository("modules");
codeSource = new CodeSource(modules.getUrl(), (CodeSigner[])null);
}
}
public void run() throws IOException {
if (silent) {
// bypass console if running with redirected stdin or stout
runSilently();
return;
}
ConsoleReader reader = new ConsoleReader();
reader.setBellEnabled(false);
// reader.setDebug(new PrintWriter(new FileWriter("jline.debug")));
reader.addCompletor(new JSCompletor());
if (history == null) {
history = new File(System.getProperty("user.home"), ".ringo-history");
}
reader.setHistory(new History(history));
PrintWriter out = new PrintWriter(System.out);
int lineno = 0;
repl: while (true) {
Context cx = engine.getContextFactory().enterContext();
cx.setErrorReporter(new ToolErrorReporter(false, System.err));
String source = "";
String prompt = ">> ";
while (true) {
String newline = reader.readLine(prompt);
if (newline == null) {
// NULL input, if e.g. Ctrl-D was pressed
out.println();
out.flush();
break repl;
}
source = source + newline + "\n";
lineno++;
if (cx.stringIsCompilableUnit(source)) {
break;
}
prompt = ".. ";
}
try {
Script script = cx.compileString(source, "<stdin>", lineno, codeSource);
Object result = script.exec(cx, scope);
// Avoid printing out undefined or function definitions.
if (result != Context.getUndefinedValue()) {
out.println(Context.toString(result));
}
out.flush();
lineno++;
// trigger GC once in a while - if we run in non-interpreter mode
// we generate a lot of classes to unload
if (lineno % 10 == 0) {
System.gc();
}
} catch (Exception ex) {
RingoRunner.reportError(ex, System.out, config.isVerbose());
} finally {
Context.exit();
}
}
System.exit(0);
}
private void runSilently() throws IOException {
int lineno = 0;
outer: while (true) {
Context cx = engine.getContextFactory().enterContext();
cx.setErrorReporter(new ToolErrorReporter(false, System.err));
cx.setOptimizationLevel(-1);
String source = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line == null) {
// reached EOF
break outer;
}
source = source + line + "\n";
lineno++;
if (cx.stringIsCompilableUnit(source))
break;
}
try {
cx.evaluateString(scope, source, "<stdin>", lineno, codeSource);
lineno++;
} catch (Exception ex) {
RingoRunner.reportError(ex, System.err, config.isVerbose());
} finally {
Context.exit();
}
}
System.exit(0);
}
class JSCompletor implements Completor {
Pattern variables = Pattern.compile(
"(^|\\s|[^\\w\\.'\"])([\\w\\.]+)$");
Pattern keywords = Pattern.compile(
"(^|\\s)([\\w]+)$");
public int complete(String s, int i, List list) {
int start = i;
try {
Matcher match = keywords.matcher(s);
if (match.find() && s.length() == i) {
String word = match.group(2);
for(String str: jsKeywords) {
if (str.startsWith(word)) {
list.add(str);
}
}
}
match = variables.matcher(s);
if (match.find() && s.length() == i) {
String word = match.group(2);
Scriptable obj = scope;
String[] parts = word.split("\\.", -1);
for (int k = 0; k < parts.length - 1; k++) {
Object o = ScriptableObject.getProperty(obj, parts[k]);
if (o == null || o == ScriptableObject.NOT_FOUND) {
return start;
}
obj = ScriptRuntime.toObject(scope, o);
}
String lastpart = parts[parts.length - 1];
// set return value to beginning of word we're replacing
start = i - lastpart.length();
while (obj != null) {
// System.err.println(word + " -- " + obj);
Object[] ids = obj.getIds();
collectIds(ids, obj, word, lastpart, list);
if (list.isEmpty() && obj instanceof ScriptableObject) {
ids = ((ScriptableObject) obj).getAllIds();
collectIds(ids, obj, word, lastpart, list);
}
if (word.endsWith(".") && obj instanceof ModuleScope) {
// don't walk scope prototype chain if nothing to compare yet -
// the list is just too long.
break;
}
obj = obj.getPrototype();
}
}
} catch (Exception ignore) {
// ignore.printStackTrace();
}
Collections.sort(list);
return start;
}
private void collectIds(Object[] ids, Scriptable obj, String word, String lastpart, List list) {
for(Object id: ids) {
if (!(id instanceof String)) {
continue;
}
String str = (String) id;
if (str.startsWith(lastpart) || word.endsWith(".")) {
if (ScriptableObject.getProperty(obj, str) instanceof Callable) {
list.add(str + "(");
} else {
list.add(str);
}
}
}
}
}
static String[] jsKeywords =
new String[] {
"break",
"case",
"catch",
"continue",
"default",
"delete",
"do",
"else",
"finally",
"for",
"function",
"if",
"in",
"instanceof",
"new",
"return",
"switch",
"this",
"throw",
"try",
"typeof",
"var",
"void",
"while",
"with"
};
}
| Make RingoShell more subclassable.
This allows to subclass RingoShell via JavaAdapter and to override
its prompts and result and error printing methods. E.g. it could
be used to print a different string representation of results and
errors, apply ANSI coloring, etc.
| src/org/ringojs/tools/RingoShell.java | Make RingoShell more subclassable. | <ide><path>rc/org/ringojs/tools/RingoShell.java
<ide> File history;
<ide> CodeSource codeSource = null;
<ide>
<add> public RingoShell() throws IOException {
<add> this(RhinoEngine.getEngine(), null, false);
<add> }
<add>
<ide> public RingoShell(RhinoEngine engine) throws IOException {
<ide> this(engine, null, false);
<ide> }
<ide> history = new File(System.getProperty("user.home"), ".ringo-history");
<ide> }
<ide> reader.setHistory(new History(history));
<del> PrintWriter out = new PrintWriter(System.out);
<add> PrintStream out = System.out;
<ide> int lineno = 0;
<ide> repl: while (true) {
<ide> Context cx = engine.getContextFactory().enterContext();
<ide> cx.setErrorReporter(new ToolErrorReporter(false, System.err));
<ide> String source = "";
<del> String prompt = ">> ";
<add> String prompt = getPrompt();
<ide> while (true) {
<ide> String newline = reader.readLine(prompt);
<ide> if (newline == null) {
<ide> if (cx.stringIsCompilableUnit(source)) {
<ide> break;
<ide> }
<del> prompt = ".. ";
<add> prompt = getSecondaryPrompt();
<ide> }
<ide> try {
<ide> Script script = cx.compileString(source, "<stdin>", lineno, codeSource);
<ide> Object result = script.exec(cx, scope);
<del> // Avoid printing out undefined or function definitions.
<del> if (result != Context.getUndefinedValue()) {
<del> out.println(Context.toString(result));
<del> }
<del> out.flush();
<add> printResult(result, out);
<ide> lineno++;
<ide> // trigger GC once in a while - if we run in non-interpreter mode
<ide> // we generate a lot of classes to unload
<ide> System.gc();
<ide> }
<ide> } catch (Exception ex) {
<del> RingoRunner.reportError(ex, System.out, config.isVerbose());
<add> // TODO: shouldn't this print to System.err?
<add> printError(ex, System.out, config.isVerbose());
<ide> } finally {
<ide> Context.exit();
<ide> }
<ide> }
<ide> System.exit(0);
<add> }
<add>
<add> protected String getPrompt() {
<add> return ">> ";
<add> }
<add>
<add> protected String getSecondaryPrompt() {
<add> return ".. ";
<add> }
<add>
<add> protected void printResult(Object result, PrintStream out) {
<add> // Avoid printing out undefined or function definitions.
<add> if (result != Context.getUndefinedValue()) {
<add> out.println(Context.toString(result));
<add> }
<add> out.flush();
<add> }
<add>
<add> protected void printError(Exception ex, PrintStream out, boolean verbose) {
<add> // default implementation forwards to RingoRunner.reportError()
<add> RingoRunner.reportError(ex, out, verbose);
<ide> }
<ide>
<ide> private void runSilently() throws IOException {
<ide> cx.evaluateString(scope, source, "<stdin>", lineno, codeSource);
<ide> lineno++;
<ide> } catch (Exception ex) {
<del> RingoRunner.reportError(ex, System.err, config.isVerbose());
<add> printError(ex, System.err, config.isVerbose());
<ide> } finally {
<ide> Context.exit();
<ide> } |
|
Java | mpl-2.0 | e41e5b27b695afd5cbe809465ef8506d2b1107ec | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.gl3d.model.image;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import javax.media.opengl.GL;
import org.helioviewer.base.logging.Log;
import org.helioviewer.base.physics.Constants;
import org.helioviewer.gl3d.camera.GL3DCamera;
import org.helioviewer.gl3d.camera.GL3DCameraListener;
import org.helioviewer.gl3d.model.GL3DHitReferenceShape;
import org.helioviewer.gl3d.scenegraph.GL3DNode;
import org.helioviewer.gl3d.scenegraph.GL3DOrientedGroup;
import org.helioviewer.gl3d.scenegraph.GL3DState;
import org.helioviewer.gl3d.scenegraph.math.GL3DMat4d;
import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d;
import org.helioviewer.gl3d.scenegraph.math.GL3DVec4d;
import org.helioviewer.gl3d.scenegraph.rt.GL3DRay;
import org.helioviewer.gl3d.scenegraph.rt.GL3DRayTracer;
import org.helioviewer.gl3d.shader.GL3DImageFragmentShaderProgram;
import org.helioviewer.gl3d.view.GL3DCoordinateSystemView;
import org.helioviewer.gl3d.view.GL3DImageTextureView;
import org.helioviewer.gl3d.view.GL3DView;
import org.helioviewer.gl3d.wcs.CoordinateSystem;
import org.helioviewer.gl3d.wcs.CoordinateVector;
import org.helioviewer.viewmodel.changeevent.ChangeEvent;
import org.helioviewer.viewmodel.metadata.MetaData;
import org.helioviewer.viewmodel.region.Region;
import org.helioviewer.viewmodel.region.StaticRegion;
import org.helioviewer.viewmodel.view.MetaDataView;
import org.helioviewer.viewmodel.view.RegionView;
/**
* This is the scene graph equivalent of an image layer sub view chain attached
* to the GL3DLayeredView. It represents exactly one image layer in the view
* chain
*
* @author Simon Spoerri ([email protected])
*
*/
public abstract class GL3DImageLayer extends GL3DOrientedGroup implements GL3DCameraListener {
private static int nextLayerId = 0;
private final int layerId;
private GL3DVec4d direction = new GL3DVec4d(0, 0, 1, 0);
public int getLayerId() {
return layerId;
}
protected GL3DView mainLayerView;
protected GL3DImageTextureView imageTextureView;
protected GL3DCoordinateSystemView coordinateSystemView;
protected MetaDataView metaDataView;
protected RegionView regionView;
protected GL3DImageLayers layerGroup;
public double minZ = -Constants.SunRadius;
public double maxZ = Constants.SunRadius;
protected GL3DNode accellerationShape;
protected boolean doUpdateROI = true;
private final ArrayList<Point> points = new ArrayList<Point>();
private double lastViewAngle = 0.0;
protected GL gl;
protected GL3DImageFragmentShaderProgram coronaFragmentShader = null;
protected GL3DImageFragmentShaderProgram sphereFragmentShader = null;
public GL3DImageLayer(String name, GL3DView mainLayerView) {
super(name);
layerId = nextLayerId++;
this.mainLayerView = mainLayerView;
if (this.mainLayerView == null) {
throw new NullPointerException("Cannot create GL3DImageLayer from null Layer");
}
this.imageTextureView = this.mainLayerView.getAdapter(GL3DImageTextureView.class);
if (this.imageTextureView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no GL3DImageTextureView is present in Layer");
}
this.coordinateSystemView = this.mainLayerView.getAdapter(GL3DCoordinateSystemView.class);
if (this.coordinateSystemView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no GL3DCoordinateSystemView is present in Layer");
}
this.metaDataView = this.mainLayerView.getAdapter(MetaDataView.class);
if (this.metaDataView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no MetaDataView is present in Layer");
}
this.regionView = this.mainLayerView.getAdapter(RegionView.class);
if (this.regionView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no RegionView is present in Layer");
}
getCoordinateSystem().addListener(this);
this.doUpdateROI = true;
this.markAsChanged();
}
@Override
public void shapeDraw(GL3DState state) {
super.shapeDraw(state);
}
@Override
public void shapeInit(GL3DState state) {
this.createImageMeshNodes(state.gl);
this.accellerationShape = new GL3DHitReferenceShape(true, 0.);
this.addNode(this.accellerationShape);
super.shapeInit(state);
this.doUpdateROI = true;
this.markAsChanged();
updateROI(state.getActiveCamera());
}
protected abstract void createImageMeshNodes(GL gl);
protected abstract GL3DImageMesh getImageSphere();
@Override
public void shapeUpdate(GL3DState state) {
super.shapeUpdate(state);
if (doUpdateROI) {
this.updateROI(state.getActiveCamera());
doUpdateROI = false;
this.accellerationShape.setUnchanged();
}
}
@Override
public void cameraMoved(GL3DCamera camera) {
doUpdateROI = true;
if (this.accellerationShape != null)
this.accellerationShape.markAsChanged();
cameraMoving(camera);
}
public double getLastViewAngle() {
return lastViewAngle;
}
public void paint(Graphics g) {
for (Point p : points) {
g.fillRect(p.x - 1, p.y - 1, 2, 2);
}
}
@Override
public void cameraMoving(GL3DCamera camera) {
GL3DMat4d camTrans = camera.getRotation().toMatrix().inverse();
GL3DVec4d camDirection = new GL3DVec4d(0, 0, 1, 1);
camDirection = camTrans.multiply(camDirection);
camDirection.w = 0;
camDirection.normalize();
double angle = Math.acos(camDirection.dot(direction)) / Math.PI * 180.0;
double maxAngle = 60;
double minAngle = 30;
if (angle != lastViewAngle) {
lastViewAngle = angle;
float alpha = (float) ((Math.abs(90 - lastViewAngle) - minAngle) / (maxAngle - minAngle));
}
}
public GL3DVec4d getLayerDirection() {
// Convert layer orientation to heliocentric coordinate system
/*
* CoordinateVector orientation = coordinateSystemView.getOrientation();
* CoordinateSystem targetSystem = new
* HeliocentricCartesianCoordinateSystem(); CoordinateConversion
* converter =
* orientation.getCoordinateSystem().getConversion(targetSystem);
* orientation = converter.convert(orientation);
*
* GL3DVec3d layerDirection = new GL3DVec3d(orientation.getValue(0),
* orientation.getValue(1), orientation.getValue(2));
*/
// GL3DVec4d n = new GL3DVec4d(0, 0, 1, 1);
// n = modelView().multiply(n);
// GL3DVec3d layerDirection = new GL3DVec3d(n.x, n.y, n.z);
// layerDirection.normalize();
return direction;
}
public void setLayerDirection(GL3DVec4d direction) {
this.direction = direction;
}
@Override
public CoordinateSystem getCoordinateSystem() {
return this.coordinateSystemView.getCoordinateSystem();
}
@Override
public CoordinateVector getOrientation() {
return this.coordinateSystemView.getOrientation();
}
private void updateROI(GL3DCamera activeCamera) {
MetaData metaData = metaDataView.getMetaData();
GL3DRayTracer rayTracer = new GL3DRayTracer(this.accellerationShape, activeCamera);
// Shoot Rays in the corners of the viewport
int width = (int) activeCamera.getWidth();
int height = (int) activeCamera.getHeight();
List<GL3DRay> regionTestRays = new ArrayList<GL3DRay>();
// frame.setVisible(true);
// frame1.setVisible(true);
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= 10; j++) {
regionTestRays.add(rayTracer.cast(i * (width / 10), j * (height / 10)));
}
}
double minPhysicalX = Double.MAX_VALUE;
double minPhysicalY = Double.MAX_VALUE;
double minPhysicalZ = Double.MAX_VALUE;
double maxPhysicalX = -Double.MAX_VALUE;
double maxPhysicalY = -Double.MAX_VALUE;
double maxPhysicalZ = -Double.MAX_VALUE;
GL3DMat4d phiRotation = GL3DMat4d.rotation(this.imageTextureView.phi, new GL3DVec3d(0, 1, 0));
for (GL3DRay ray : regionTestRays) {
GL3DVec3d hitPoint = ray.getHitPoint();
if (hitPoint != null) {
hitPoint = this.wmI.multiply(hitPoint);
// double coordx = (hitPoint.x -
// metaData.getPhysicalLowerLeft().getX())/metaData.getPhysicalImageWidth();
// double coordy = ((1-hitPoint.y) -
// metaData.getPhysicalLowerLeft().getY())/metaData.getPhysicalImageHeight();
double x = phiRotation.m[0] * hitPoint.x + phiRotation.m[4] * hitPoint.y + phiRotation.m[8] * hitPoint.z + phiRotation.m[12];
double y = phiRotation.m[1] * hitPoint.x + phiRotation.m[5] * hitPoint.y + phiRotation.m[9] * hitPoint.z + phiRotation.m[13];
double z = phiRotation.m[2] * hitPoint.x + phiRotation.m[6] * hitPoint.y + phiRotation.m[10] * hitPoint.z + phiRotation.m[14];
// coordx = (x -
// metaData.getPhysicalLowerLeft().getX())/metaData.getPhysicalImageWidth();
// coordy = ((1-y) -
// metaData.getPhysicalLowerLeft().getY())/metaData.getPhysicalImageHeight();
minPhysicalX = Math.min(minPhysicalX, x);
minPhysicalY = Math.min(minPhysicalY, y);
minPhysicalZ = Math.min(minPhysicalZ, z);
maxPhysicalX = Math.max(maxPhysicalX, x);
maxPhysicalY = Math.max(maxPhysicalY, y);
maxPhysicalZ = Math.max(maxPhysicalZ, z);
// Log.debug("GL3DImageLayer: Hitpoint: "+hitPoint+" - "+ray.isOnSun);
}
}
minPhysicalX = Math.max(minPhysicalX, metaData.getPhysicalLowerLeft().getX());
minPhysicalY = Math.max(minPhysicalY, metaData.getPhysicalLowerLeft().getY());
maxPhysicalX = Math.min(maxPhysicalX, metaData.getPhysicalUpperRight().getX());
maxPhysicalY = Math.min(maxPhysicalY, metaData.getPhysicalUpperRight().getY());
minPhysicalX -= Math.abs(minPhysicalX) * 0.5;
minPhysicalY -= Math.abs(minPhysicalY) * 0.5;
maxPhysicalX += Math.abs(maxPhysicalX) * 0.5;
maxPhysicalY += Math.abs(maxPhysicalY) * 0.5;
if (minPhysicalX < metaData.getPhysicalLowerLeft().getX())
minPhysicalX = metaData.getPhysicalLowerLeft().getX();
if (minPhysicalY < metaData.getPhysicalLowerLeft().getY())
minPhysicalY = metaData.getPhysicalLowerLeft().getX();
if (maxPhysicalX > metaData.getPhysicalUpperRight().getX())
maxPhysicalX = metaData.getPhysicalUpperRight().getX();
if (maxPhysicalY > metaData.getPhysicalUpperRight().getY())
maxPhysicalY = metaData.getPhysicalUpperRight().getY();
double regionWidth = maxPhysicalX - minPhysicalX;
double regionHeight = maxPhysicalY - minPhysicalY;
if (regionWidth > 0 && regionHeight > 0) {
Region newRegion = StaticRegion.createAdaptedRegion(minPhysicalX, minPhysicalY, regionWidth, regionHeight);
this.regionView.setRegion(newRegion, new ChangeEvent());
} else {
Log.error("Illegal Region calculated! " + regionWidth + ":" + regionHeight + ". x = " + minPhysicalX + " - " + maxPhysicalX + ", y = " + minPhysicalY + " - " + maxPhysicalY);
}
}
public void setCoronaVisibility(boolean visible) {
}
protected GL3DImageTextureView getImageTextureView() {
return this.imageTextureView;
}
public void setLayerGroup(GL3DImageLayers layers) {
layerGroup = layers;
}
public GL3DImageLayers getLayerGroup() {
return layerGroup;
}
}
| src/jhv-3d/src/org/helioviewer/gl3d/model/image/GL3DImageLayer.java | package org.helioviewer.gl3d.model.image;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import javax.media.opengl.GL;
import org.helioviewer.base.logging.Log;
import org.helioviewer.base.physics.Constants;
import org.helioviewer.gl3d.GL3DHelper;
import org.helioviewer.gl3d.camera.GL3DCamera;
import org.helioviewer.gl3d.camera.GL3DCameraListener;
import org.helioviewer.gl3d.model.GL3DHitReferenceShape;
import org.helioviewer.gl3d.scenegraph.GL3DNode;
import org.helioviewer.gl3d.scenegraph.GL3DOrientedGroup;
import org.helioviewer.gl3d.scenegraph.GL3DState;
import org.helioviewer.gl3d.scenegraph.math.GL3DMat4d;
import org.helioviewer.gl3d.scenegraph.math.GL3DQuatd;
import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d;
import org.helioviewer.gl3d.scenegraph.math.GL3DVec4d;
import org.helioviewer.gl3d.scenegraph.rt.GL3DRay;
import org.helioviewer.gl3d.scenegraph.rt.GL3DRayTracer;
import org.helioviewer.gl3d.shader.GL3DImageFragmentShaderProgram;
import org.helioviewer.gl3d.view.GL3DCoordinateSystemView;
import org.helioviewer.gl3d.view.GL3DImageTextureView;
import org.helioviewer.gl3d.view.GL3DView;
import org.helioviewer.gl3d.wcs.CoordinateConversion;
import org.helioviewer.gl3d.wcs.CoordinateSystem;
import org.helioviewer.gl3d.wcs.CoordinateVector;
import org.helioviewer.viewmodel.changeevent.ChangeEvent;
import org.helioviewer.viewmodel.metadata.MetaData;
import org.helioviewer.viewmodel.region.Region;
import org.helioviewer.viewmodel.region.StaticRegion;
import org.helioviewer.viewmodel.view.MetaDataView;
import org.helioviewer.viewmodel.view.RegionView;
/**
* This is the scene graph equivalent of an image layer sub view chain attached
* to the GL3DLayeredView. It represents exactly one image layer in the view
* chain
*
* @author Simon Spoerri ([email protected])
*
*/
public abstract class GL3DImageLayer extends GL3DOrientedGroup implements GL3DCameraListener {
private static int nextLayerId = 0;
private final int layerId;
private GL3DVec4d direction = new GL3DVec4d(0, 0, 1, 0);
public int getLayerId() {
return layerId;
}
protected GL3DView mainLayerView;
protected GL3DImageTextureView imageTextureView;
protected GL3DCoordinateSystemView coordinateSystemView;
protected MetaDataView metaDataView;
protected RegionView regionView;
protected GL3DImageLayers layerGroup;
public double minZ = -Constants.SunRadius;
public double maxZ = Constants.SunRadius;
protected GL3DNode accellerationShape;
protected boolean doUpdateROI = true;
private final ArrayList<Point> points = new ArrayList<Point>();
private double lastViewAngle = 0.0;
protected GL gl;
protected GL3DImageFragmentShaderProgram coronaFragmentShader = null;
protected GL3DImageFragmentShaderProgram sphereFragmentShader = null;
public GL3DImageLayer(String name, GL3DView mainLayerView) {
super(name);
layerId = nextLayerId++;
this.mainLayerView = mainLayerView;
if (this.mainLayerView == null) {
throw new NullPointerException("Cannot create GL3DImageLayer from null Layer");
}
this.imageTextureView = this.mainLayerView.getAdapter(GL3DImageTextureView.class);
if (this.imageTextureView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no GL3DImageTextureView is present in Layer");
}
this.coordinateSystemView = this.mainLayerView.getAdapter(GL3DCoordinateSystemView.class);
if (this.coordinateSystemView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no GL3DCoordinateSystemView is present in Layer");
}
this.metaDataView = this.mainLayerView.getAdapter(MetaDataView.class);
if (this.metaDataView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no MetaDataView is present in Layer");
}
this.regionView = this.mainLayerView.getAdapter(RegionView.class);
if (this.regionView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no RegionView is present in Layer");
}
getCoordinateSystem().addListener(this);
this.doUpdateROI = true;
this.markAsChanged();
}
@Override
public void shapeDraw(GL3DState state) {
super.shapeDraw(state);
}
@Override
public void shapeInit(GL3DState state) {
this.createImageMeshNodes(state.gl);
CoordinateVector orientationVector = this.getOrientation();
CoordinateConversion toViewSpace = this.getCoordinateSystem().getConversion(state.getActiveCamera().getViewSpaceCoordinateSystem());
GL3DVec3d orientation = GL3DHelper.toVec(toViewSpace.convert(orientationVector)); // .normalize();
// -
// not
// needed
// for
// atan2
double phi = Math.atan2(orientation.x, orientation.z);
this.accellerationShape = new GL3DHitReferenceShape(true, phi);
this.addNode(this.accellerationShape);
super.shapeInit(state);
this.doUpdateROI = true;
this.markAsChanged();
updateROI(state.getActiveCamera());
GL3DQuatd phiRotation = GL3DQuatd.createRotation(phi, new GL3DVec3d(0, 1, 0));
state.getActiveCamera().getRotation().set(phiRotation);
state.getActiveCamera().updateCameraTransformation();
}
protected abstract void createImageMeshNodes(GL gl);
protected abstract GL3DImageMesh getImageSphere();
@Override
public void shapeUpdate(GL3DState state) {
super.shapeUpdate(state);
if (doUpdateROI) {
this.updateROI(state.getActiveCamera());
doUpdateROI = false;
this.accellerationShape.setUnchanged();
}
}
@Override
public void cameraMoved(GL3DCamera camera) {
doUpdateROI = true;
if (this.accellerationShape != null)
this.accellerationShape.markAsChanged();
cameraMoving(camera);
}
public double getLastViewAngle() {
return lastViewAngle;
}
public void paint(Graphics g) {
for (Point p : points) {
g.fillRect(p.x - 1, p.y - 1, 2, 2);
}
}
@Override
public void cameraMoving(GL3DCamera camera) {
GL3DMat4d camTrans = camera.getRotation().toMatrix().inverse();
GL3DVec4d camDirection = new GL3DVec4d(0, 0, 1, 1);
camDirection = camTrans.multiply(camDirection);
camDirection.w = 0;
camDirection.normalize();
double angle = Math.acos(camDirection.dot(direction)) / Math.PI * 180.0;
double maxAngle = 60;
double minAngle = 30;
if (angle != lastViewAngle) {
lastViewAngle = angle;
float alpha = (float) ((Math.abs(90 - lastViewAngle) - minAngle) / (maxAngle - minAngle));
}
}
public GL3DVec4d getLayerDirection() {
// Convert layer orientation to heliocentric coordinate system
/*
* CoordinateVector orientation = coordinateSystemView.getOrientation();
* CoordinateSystem targetSystem = new
* HeliocentricCartesianCoordinateSystem(); CoordinateConversion
* converter =
* orientation.getCoordinateSystem().getConversion(targetSystem);
* orientation = converter.convert(orientation);
*
* GL3DVec3d layerDirection = new GL3DVec3d(orientation.getValue(0),
* orientation.getValue(1), orientation.getValue(2));
*/
// GL3DVec4d n = new GL3DVec4d(0, 0, 1, 1);
// n = modelView().multiply(n);
// GL3DVec3d layerDirection = new GL3DVec3d(n.x, n.y, n.z);
// layerDirection.normalize();
return direction;
}
public void setLayerDirection(GL3DVec4d direction) {
this.direction = direction;
}
@Override
public CoordinateSystem getCoordinateSystem() {
return this.coordinateSystemView.getCoordinateSystem();
}
@Override
public CoordinateVector getOrientation() {
return this.coordinateSystemView.getOrientation();
}
private void updateROI(GL3DCamera activeCamera) {
MetaData metaData = metaDataView.getMetaData();
GL3DRayTracer rayTracer = new GL3DRayTracer(this.accellerationShape, activeCamera);
// Shoot Rays in the corners of the viewport
int width = (int) activeCamera.getWidth();
int height = (int) activeCamera.getHeight();
List<GL3DRay> regionTestRays = new ArrayList<GL3DRay>();
// frame.setVisible(true);
// frame1.setVisible(true);
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= 10; j++) {
regionTestRays.add(rayTracer.cast(i * (width / 10), j * (height / 10)));
}
}
double minPhysicalX = Double.MAX_VALUE;
double minPhysicalY = Double.MAX_VALUE;
double minPhysicalZ = Double.MAX_VALUE;
double maxPhysicalX = -Double.MAX_VALUE;
double maxPhysicalY = -Double.MAX_VALUE;
double maxPhysicalZ = -Double.MAX_VALUE;
GL3DMat4d phiRotation = GL3DMat4d.rotation(this.imageTextureView.phi, new GL3DVec3d(0, 1, 0));
for (GL3DRay ray : regionTestRays) {
GL3DVec3d hitPoint = ray.getHitPoint();
if (hitPoint != null) {
hitPoint = this.wmI.multiply(hitPoint);
// double coordx = (hitPoint.x -
// metaData.getPhysicalLowerLeft().getX())/metaData.getPhysicalImageWidth();
// double coordy = ((1-hitPoint.y) -
// metaData.getPhysicalLowerLeft().getY())/metaData.getPhysicalImageHeight();
double x = phiRotation.m[0] * hitPoint.x + phiRotation.m[4] * hitPoint.y + phiRotation.m[8] * hitPoint.z + phiRotation.m[12];
double y = phiRotation.m[1] * hitPoint.x + phiRotation.m[5] * hitPoint.y + phiRotation.m[9] * hitPoint.z + phiRotation.m[13];
double z = phiRotation.m[2] * hitPoint.x + phiRotation.m[6] * hitPoint.y + phiRotation.m[10] * hitPoint.z + phiRotation.m[14];
// coordx = (x -
// metaData.getPhysicalLowerLeft().getX())/metaData.getPhysicalImageWidth();
// coordy = ((1-y) -
// metaData.getPhysicalLowerLeft().getY())/metaData.getPhysicalImageHeight();
minPhysicalX = Math.min(minPhysicalX, x);
minPhysicalY = Math.min(minPhysicalY, y);
minPhysicalZ = Math.min(minPhysicalZ, z);
maxPhysicalX = Math.max(maxPhysicalX, x);
maxPhysicalY = Math.max(maxPhysicalY, y);
maxPhysicalZ = Math.max(maxPhysicalZ, z);
// Log.debug("GL3DImageLayer: Hitpoint: "+hitPoint+" - "+ray.isOnSun);
}
}
minPhysicalX = Math.max(minPhysicalX, metaData.getPhysicalLowerLeft().getX());
minPhysicalY = Math.max(minPhysicalY, metaData.getPhysicalLowerLeft().getY());
maxPhysicalX = Math.min(maxPhysicalX, metaData.getPhysicalUpperRight().getX());
maxPhysicalY = Math.min(maxPhysicalY, metaData.getPhysicalUpperRight().getY());
minPhysicalX -= Math.abs(minPhysicalX) * 0.5;
minPhysicalY -= Math.abs(minPhysicalY) * 0.5;
maxPhysicalX += Math.abs(maxPhysicalX) * 0.5;
maxPhysicalY += Math.abs(maxPhysicalY) * 0.5;
if (minPhysicalX < metaData.getPhysicalLowerLeft().getX())
minPhysicalX = metaData.getPhysicalLowerLeft().getX();
if (minPhysicalY < metaData.getPhysicalLowerLeft().getY())
minPhysicalY = metaData.getPhysicalLowerLeft().getX();
if (maxPhysicalX > metaData.getPhysicalUpperRight().getX())
maxPhysicalX = metaData.getPhysicalUpperRight().getX();
if (maxPhysicalY > metaData.getPhysicalUpperRight().getY())
maxPhysicalY = metaData.getPhysicalUpperRight().getY();
double regionWidth = maxPhysicalX - minPhysicalX;
double regionHeight = maxPhysicalY - minPhysicalY;
if (regionWidth > 0 && regionHeight > 0) {
Region newRegion = StaticRegion.createAdaptedRegion(minPhysicalX, minPhysicalY, regionWidth, regionHeight);
this.regionView.setRegion(newRegion, new ChangeEvent());
} else {
Log.error("Illegal Region calculated! " + regionWidth + ":" + regionHeight + ". x = " + minPhysicalX + " - " + maxPhysicalX + ", y = " + minPhysicalY + " - " + maxPhysicalY);
}
}
public void setCoronaVisibility(boolean visible) {
}
protected GL3DImageTextureView getImageTextureView() {
return this.imageTextureView;
}
public void setLayerGroup(GL3DImageLayers layers) {
layerGroup = layers;
}
public GL3DImageLayers getLayerGroup() {
return layerGroup;
}
}
| Remove overhead
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@1116 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/jhv-3d/src/org/helioviewer/gl3d/model/image/GL3DImageLayer.java | Remove overhead | <ide><path>rc/jhv-3d/src/org/helioviewer/gl3d/model/image/GL3DImageLayer.java
<ide>
<ide> import org.helioviewer.base.logging.Log;
<ide> import org.helioviewer.base.physics.Constants;
<del>import org.helioviewer.gl3d.GL3DHelper;
<ide> import org.helioviewer.gl3d.camera.GL3DCamera;
<ide> import org.helioviewer.gl3d.camera.GL3DCameraListener;
<ide> import org.helioviewer.gl3d.model.GL3DHitReferenceShape;
<ide> import org.helioviewer.gl3d.scenegraph.GL3DOrientedGroup;
<ide> import org.helioviewer.gl3d.scenegraph.GL3DState;
<ide> import org.helioviewer.gl3d.scenegraph.math.GL3DMat4d;
<del>import org.helioviewer.gl3d.scenegraph.math.GL3DQuatd;
<ide> import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d;
<ide> import org.helioviewer.gl3d.scenegraph.math.GL3DVec4d;
<ide> import org.helioviewer.gl3d.scenegraph.rt.GL3DRay;
<ide> import org.helioviewer.gl3d.view.GL3DCoordinateSystemView;
<ide> import org.helioviewer.gl3d.view.GL3DImageTextureView;
<ide> import org.helioviewer.gl3d.view.GL3DView;
<del>import org.helioviewer.gl3d.wcs.CoordinateConversion;
<ide> import org.helioviewer.gl3d.wcs.CoordinateSystem;
<ide> import org.helioviewer.gl3d.wcs.CoordinateVector;
<ide> import org.helioviewer.viewmodel.changeevent.ChangeEvent;
<ide> * This is the scene graph equivalent of an image layer sub view chain attached
<ide> * to the GL3DLayeredView. It represents exactly one image layer in the view
<ide> * chain
<del> *
<add> *
<ide> * @author Simon Spoerri ([email protected])
<del> *
<add> *
<ide> */
<ide> public abstract class GL3DImageLayer extends GL3DOrientedGroup implements GL3DCameraListener {
<ide> private static int nextLayerId = 0;
<ide> public void shapeInit(GL3DState state) {
<ide> this.createImageMeshNodes(state.gl);
<ide>
<del> CoordinateVector orientationVector = this.getOrientation();
<del> CoordinateConversion toViewSpace = this.getCoordinateSystem().getConversion(state.getActiveCamera().getViewSpaceCoordinateSystem());
<del>
<del> GL3DVec3d orientation = GL3DHelper.toVec(toViewSpace.convert(orientationVector)); // .normalize();
<del> // -
<del> // not
<del> // needed
<del> // for
<del> // atan2
<del> double phi = Math.atan2(orientation.x, orientation.z);
<del>
<del> this.accellerationShape = new GL3DHitReferenceShape(true, phi);
<add> this.accellerationShape = new GL3DHitReferenceShape(true, 0.);
<ide> this.addNode(this.accellerationShape);
<ide>
<ide> super.shapeInit(state);
<del>
<ide> this.doUpdateROI = true;
<ide> this.markAsChanged();
<ide> updateROI(state.getActiveCamera());
<ide>
<del> GL3DQuatd phiRotation = GL3DQuatd.createRotation(phi, new GL3DVec3d(0, 1, 0));
<del> state.getActiveCamera().getRotation().set(phiRotation);
<del> state.getActiveCamera().updateCameraTransformation();
<ide> }
<ide>
<ide> protected abstract void createImageMeshNodes(GL gl);
<ide> * converter =
<ide> * orientation.getCoordinateSystem().getConversion(targetSystem);
<ide> * orientation = converter.convert(orientation);
<del> *
<add> *
<ide> * GL3DVec3d layerDirection = new GL3DVec3d(orientation.getValue(0),
<ide> * orientation.getValue(1), orientation.getValue(2));
<ide> */ |
|
Java | bsd-2-clause | dae5781610430c5e3cedc9ebae9110050499a364 | 0 | TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.ui.swing.display;
import imagej.ImageJ;
import imagej.data.display.DataView;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageCanvas;
import imagej.data.display.ImageDisplay;
import imagej.data.display.OverlayView;
import imagej.data.display.event.DataViewDeselectedEvent;
import imagej.data.display.event.DataViewSelectedEvent;
import imagej.data.display.event.MouseCursorEvent;
import imagej.data.display.event.ZoomEvent;
import imagej.event.EventHandler;
import imagej.event.EventService;
import imagej.event.EventSubscriber;
import imagej.ext.display.event.DisplayDeletedEvent;
import imagej.ext.tool.Tool;
import imagej.ext.tool.ToolService;
import imagej.ext.tool.event.ToolActivatedEvent;
import imagej.ui.common.awt.AWTCursors;
import imagej.ui.common.awt.AWTInputEventDispatcher;
import imagej.ui.swing.StaticSwingUtils;
import imagej.ui.swing.overlay.FigureCreatedEvent;
import imagej.ui.swing.overlay.IJHotDrawOverlayAdapter;
import imagej.ui.swing.overlay.JHotDrawTool;
import imagej.ui.swing.overlay.OverlayCreatedListener;
import imagej.ui.swing.overlay.ToolDelegator;
import imagej.util.IntCoords;
import imagej.util.Log;
import imagej.util.RealCoords;
import imagej.util.RealRect;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.Border;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import org.jhotdraw.draw.DefaultDrawing;
import org.jhotdraw.draw.DefaultDrawingEditor;
import org.jhotdraw.draw.DefaultDrawingView;
import org.jhotdraw.draw.Drawing;
import org.jhotdraw.draw.DrawingEditor;
import org.jhotdraw.draw.Figure;
import org.jhotdraw.draw.event.FigureSelectionEvent;
import org.jhotdraw.draw.event.FigureSelectionListener;
/**
* A renderer of an {@link ImageCanvas}, which uses JHotDraw's
* {@link DefaultDrawingView} component to do most of the work.
*
* @author Curtis Rueden
* @author Lee Kamentsky
*/
public class JHotDrawImageCanvas extends JPanel implements AdjustmentListener {
private static final long serialVersionUID = 1L;
private final SwingImageDisplayViewer displayViewer;
private final Drawing drawing;
private final DefaultDrawingView drawingView;
private final DrawingEditor drawingEditor;
private final ToolDelegator toolDelegator;
private final JScrollPane scrollPane;
private boolean insideSynch = false;
private boolean initialized = false;
private final List<FigureView> figureViews = new ArrayList<FigureView>();
private final List<EventSubscriber<?>> subscribers;
public JHotDrawImageCanvas(final SwingImageDisplayViewer displayViewer) {
this.displayViewer = displayViewer;
drawing = new DefaultDrawing(); // or QuadTreeDrawing?
drawingView = new DefaultDrawingView();
drawingView.setDrawing(drawing);
drawingEditor = new DefaultDrawingEditor();
drawingEditor.add(drawingView);
toolDelegator = new ToolDelegator();
drawingEditor.setTool(toolDelegator);
scrollPane = new JScrollPane(drawingView);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
scrollPane.getHorizontalScrollBar().addAdjustmentListener(this);
scrollPane.getVerticalScrollBar().addAdjustmentListener(this);
final ImageJ context = displayViewer.getDisplay().getContext();
final ToolService toolService = context.getService(ToolService.class);
final Tool activeTool = toolService.getActiveTool();
activateTool(activeTool);
final EventService eventService = context.getService(EventService.class);
subscribers = eventService.subscribe(this);
drawingView.addFigureSelectionListener(new FigureSelectionListener() {
@Override
public void selectionChanged(final FigureSelectionEvent event) {
onFigureSelectionChanged(event);
}
});
drawingView.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
onSizeChanged(e);
}
});
}
protected FigureView getFigureView(final DataView dataView) {
for (final FigureView figureView : figureViews) {
if (figureView.getDataView() == dataView) return figureView;
}
return null;
}
/**
* Respond to the JHotDraw figure selection event by selecting and deselecting
* views whose state has changed
*
* @param event - event indicating that the figure selections have changed
*/
protected void onFigureSelectionChanged(final FigureSelectionEvent event) {
final Set<Figure> newSelection = event.getNewSelection();
final Set<Figure> oldSelection = event.getOldSelection();
for (final DataView view : displayViewer.getDisplay()) {
final FigureView figureView = getFigureView(view);
if (figureView != null) {
final Figure figure = figureView.getFigure();
if (newSelection.contains(figure)) {
// BDZ removed next line 10-12-11
// Fixes drawing of multiple overlays (#817). Lee had this code
// here in anticipation of avoiding infinite event loops.
// Inspection seems to bear out that this possibility doesn't
// happen.
// if (!oldSelection.contains(figure))
view.setSelected(true);
}
else if (oldSelection.contains(figure)) {
view.setSelected(false);
}
}
}
}
/**
* Tell the display's canvas that its viewport's size changed
*
* @param e
*/
protected void onSizeChanged(final ComponentEvent e) {
final ImageCanvas canvas = getDisplay().getCanvas();
final Rectangle viewRect = scrollPane.getViewport().getViewRect();
canvas.setViewportSize(viewRect.width, viewRect.height);
}
@EventHandler
protected void onViewSelected(final DataViewSelectedEvent event) {
final DataView view = event.getView();
final FigureView figureView = getFigureView(view);
if (figureView != null) {
final Figure figure = figureView.getFigure();
if (!drawingView.getSelectedFigures().contains(figure)) {
drawingView.addToSelection(figure);
}
}
}
@EventHandler
protected void onViewDeselected(final DataViewDeselectedEvent event) {
final DataView view = event.getView();
final FigureView figureView = getFigureView(view);
if (figureView != null) {
final Figure figure = figureView.getFigure();
if (drawingView.getSelectedFigures().contains(figure)) {
drawingView.removeFromSelection(figure);
}
}
}
@EventHandler
protected void onToolActivatedEvent(final ToolActivatedEvent event) {
final Tool iTool = event.getTool();
activateTool(iTool);
}
@EventHandler
protected void onEvent(final DisplayDeletedEvent event) {
if (event.getObject() == getDisplay()) {
final EventService eventService =
event.getContext().getService(EventService.class);
eventService.unsubscribe(subscribers);
}
}
@EventHandler
protected void onEvent(final ZoomEvent event) {
if (event.getCanvas() != getDisplay().getCanvas()) return;
syncPanAndZoom();
}
@EventHandler
protected void onEvent(
@SuppressWarnings("unused") final MouseCursorEvent event)
{
drawingView.setCursor(AWTCursors.getCursor(getDisplay().getCanvas()
.getCursor()));
}
void rebuild() {
for (final DataView dataView : getDisplay()) {
FigureView figureView = getFigureView(dataView);
if (figureView == null) {
if (dataView instanceof DatasetView) {
figureView =
new DatasetFigureView(this.displayViewer, (DatasetView) dataView);
}
else if (dataView instanceof OverlayView) {
figureView =
new OverlayFigureView(this.displayViewer, (OverlayView) dataView);
}
else {
Log.error("Don't know how to make a figure view for " +
dataView.getClass().getName());
continue;
}
figureViews.add(figureView);
}
}
int idx = 0;
while (idx < figureViews.size()) {
final FigureView figureView = figureViews.get(idx);
if (!getDisplay().contains(figureView.getDataView())) {
figureViews.remove(idx);
figureView.dispose();
}
else {
idx++;
}
}
}
void update() {
for (final FigureView figureView : figureViews) {
figureView.update();
}
}
protected void activateTool(final Tool iTool) {
if (iTool instanceof IJHotDrawOverlayAdapter) {
final IJHotDrawOverlayAdapter adapter = (IJHotDrawOverlayAdapter) iTool;
// When the tool creates an overlay, add the
// overlay/figure combo to a SwingOverlayView.
final OverlayCreatedListener listener = new OverlayCreatedListener() {
@SuppressWarnings("synthetic-access")
@Override
public void overlayCreated(final FigureCreatedEvent e) {
final OverlayView overlay = e.getOverlay();
final ImageDisplay display = displayViewer.getDisplay();
for (int i = 0; i < display.numDimensions(); i++) {
final AxisType axis = display.axis(i);
if (Axes.isXY(axis)) continue;
if (overlay.getData().getAxisIndex(axis) < 0) {
overlay.setPosition(display.getLongPosition(axis), axis);
}
}
if (drawingView.getSelectedFigures().contains(e.getFigure())) {
overlay.setSelected(true);
}
final OverlayFigureView figureView =
new OverlayFigureView(displayViewer, overlay, e.getFigure());
figureViews.add(figureView);
display.add(overlay);
display.update();
}
};
final JHotDrawTool creationTool =
adapter.getCreationTool(getDisplay(), listener);
toolDelegator.setCreationTool(creationTool);
}
else {
toolDelegator.setCreationTool(null);
}
}
// -- JHotDrawImageCanvas methods --
public Drawing getDrawing() {
return drawing;
}
public DefaultDrawingView getDrawingView() {
return drawingView;
}
public DrawingEditor getDrawingEditor() {
return drawingEditor;
}
public void addEventDispatcher(final AWTInputEventDispatcher dispatcher) {
dispatcher.register(drawingView);
}
// -- JComponent methods --
@Override
public Dimension getPreferredSize() {
// NB Johannes
// HACK: Size the canvas one pixel larger. This is a workaround to an
// apparent bug in JHotDraw, where an ImageFigure is initially drawn as a
// large X until it is finished being rendered. Unfortunately, the X is
// slightly smaller than the image after being rendered.
final int w = scrollPane.getPreferredSize().width + 1;
final int h = scrollPane.getPreferredSize().height + 1;
// NB BDZ - Avoid space left around for nonexistent scroll bars
// This code works (except rare cases). Not sure why 4 is key. 3 and lower
// and sizing failures happen. We used to have a fudge factor of 5 in place
// elsewhere. Can no longer find it. But it is apparent from debugging
// statements that there is an off by 5(?). Notice we test versus 4 but add
// 5. If both 4 then initial zoom has scrollbars when not needed. If both 5
// then some zoom ins can leave empty scroll bar space. (I may have these
// conditions reversed). Anyhow printing in here can show getPreferredSize()
// starts out at w,h and before/during 1st redraw goes to w+1,h+1. Its this
// off by one that makes initial view have scroll bars unnecessarily. Look
// into this further.
final Dimension drawViewSize = drawingView.getPreferredSize();
final Border border = scrollPane.getBorder();
Dimension slop = new Dimension(0, 0);
if (border != null) {
final Insets insets = border.getBorderInsets(scrollPane);
slop =
new Dimension(insets.left + insets.right, insets.top + insets.bottom);
}
final Dimension bigDrawViewSize =
new Dimension(drawViewSize.width + slop.width + 1, drawViewSize.height +
slop.height + 1);
if (drawViewSize.height == 0 || drawViewSize.width == 0) {
// The image figure hasn't been placed yet. Calculate the projected size.
final Rectangle bounds = StaticSwingUtils.getWorkSpaceBounds();
final RealRect imageBounds = getDisplay().getImageExtents();
final double zoomFactor = getDisplay().getCanvas().getZoomFactor();
return new Dimension(Math.min((int) (imageBounds.width * zoomFactor) +
slop.width + 1, bounds.width), Math
.min((int) (imageBounds.height * zoomFactor) + slop.width + 1,
bounds.height));
}
if (bigDrawViewSize.width <= scrollPane.getPreferredSize().width &&
bigDrawViewSize.height <= scrollPane.getPreferredSize().height)
{
return bigDrawViewSize;
}
return new Dimension(w, h);
}
// -- Helper methods --
private ImageDisplay getDisplay() {
return displayViewer.getDisplay();
}
// -- AdjustmentListener methods --
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
if (insideSynch) return;
final ImageCanvas canvas = getDisplay().getCanvas();
final Point viewPos = scrollPane.getViewport().getViewPosition();
final Rectangle viewRect = scrollPane.getViewport().getViewRect();
if (viewRect.width != canvas.getViewportWidth() ||
viewRect.height != canvas.getViewportHeight())
{
canvas.setViewportSize(viewRect.width, viewRect.height);
}
final RealCoords center =
new RealCoords((viewPos.x + viewRect.width / 2) /
drawingView.getScaleFactor(), (viewPos.y + viewRect.height / 2) /
drawingView.getScaleFactor());
if (!initialized) return;
final RealCoords oldCenter = canvas.getPanCenter();
if (oldCenter.x == center.x && oldCenter.y == center.y) return;
canvas.setPan(center);
}
private void syncPanAndZoom() {
if (insideSynch) return;
insideSynch = true;
try {
final ImageCanvas canvas = getDisplay().getCanvas();
boolean considerResize = !initialized;
final double zoomFactor = canvas.getZoomFactor();
if (drawingView.getScaleFactor() != zoomFactor) {
drawingView.setScaleFactor(zoomFactor);
scrollPane.validate();
considerResize = true;
}
final Point viewPos = scrollPane.getViewport().getViewPosition();
final Rectangle viewRect = scrollPane.getViewport().getViewRect();
final RealCoords center = canvas.getPanCenter();
final int originX =
(int) Math.round(center.x * zoomFactor - viewRect.width / 2.0);
final int originY =
(int) Math.round(center.y * zoomFactor - viewRect.height / 2.0);
final IntCoords origin = new IntCoords(originX, originY);
if (constrainOrigin(origin)) {
// Back-compute the center if origin was changed.
canvas.setPan(new RealCoords((origin.x + viewRect.width / 2.0) /
zoomFactor, (origin.y + viewRect.height / 2.0) / zoomFactor));
}
if (viewPos.x != origin.x || viewPos.y != origin.y) {
scrollPane.getViewport().setViewPosition(new Point(origin.x, origin.y));
}
if (considerResize) maybeResizeWindow();
}
finally {
insideSynch = false;
initialized = true;
}
}
/**
* Constrain the origin to within the image.
*
* @param origin
* @return true if origin was changed.
*/
private boolean constrainOrigin(final IntCoords origin) {
boolean originChanged = false;
if (origin.x < 0) {
origin.x = 0;
originChanged = true;
}
if (origin.y < 0) {
origin.y = 0;
originChanged = true;
}
final Dimension viewportSize = scrollPane.getViewport().getSize();
final Dimension canvasSize = drawingView.getSize();
final int xMax = canvasSize.width - viewportSize.width;
final int yMax = canvasSize.height - viewportSize.height;
if (origin.x > xMax) {
origin.x = xMax;
originChanged = true;
}
if (origin.y > yMax) {
origin.y = yMax;
originChanged = true;
}
return originChanged;
}
private void maybeResizeWindow() {
final Rectangle bounds = StaticSwingUtils.getWorkSpaceBounds();
final RealRect imageBounds = getDisplay().getImageExtents();
final ImageCanvas canvas = getDisplay().getCanvas();
final IntCoords topLeft =
canvas.imageToPanelCoords(new RealCoords(imageBounds.x, imageBounds.y));
final IntCoords bottomRight =
canvas.imageToPanelCoords(new RealCoords(imageBounds.x +
imageBounds.width, imageBounds.y + imageBounds.height));
if (bottomRight.x - topLeft.x > bounds.width) return;
if (bottomRight.y - topLeft.y > bounds.height) return;
// FIXME TEMP
// NB BDZ - there is an issue where zoom out does not always pack()
// correctly. There seems like there is a race condition. I have tried a
// number of approaches to a fix but nothing has fallen out yet. Approaches
// included:
// - generating a "INeedARepackEvent" and trying to handle elsewhere
// - calling redoLayout() on the panel (infinite loop)
// - call pack() after a slight delay
// Current approach:
// Update on a different thread after a slight delay.
// Note this always resizes correctly (except for off by a fixed
// scrollbar size which I have handled in getPreferredSize())
if (false) {
new Thread() {
@Override
public void run() {
// NB: Not enough to be in separate thread - it must sleep a little.
try {
Thread.sleep(30);
}
catch (final Exception e) {
// no action needed
}
displayViewer.getPanel().getWindow().pack();
}
}.start();
}
else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
displayViewer.getPanel().getWindow().pack();
}
});
}
}
}
| ui/awt-swing/swing/ui-base/src/main/java/imagej/ui/swing/display/JHotDrawImageCanvas.java | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2012 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.ui.swing.display;
import imagej.ImageJ;
import imagej.data.display.DataView;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageCanvas;
import imagej.data.display.ImageDisplay;
import imagej.data.display.OverlayView;
import imagej.data.display.event.DataViewDeselectedEvent;
import imagej.data.display.event.DataViewSelectedEvent;
import imagej.data.display.event.MouseCursorEvent;
import imagej.data.display.event.ZoomEvent;
import imagej.event.EventHandler;
import imagej.event.EventService;
import imagej.event.EventSubscriber;
import imagej.ext.display.event.DisplayDeletedEvent;
import imagej.ext.tool.Tool;
import imagej.ext.tool.ToolService;
import imagej.ext.tool.event.ToolActivatedEvent;
import imagej.ui.common.awt.AWTCursors;
import imagej.ui.common.awt.AWTInputEventDispatcher;
import imagej.ui.swing.StaticSwingUtils;
import imagej.ui.swing.overlay.FigureCreatedEvent;
import imagej.ui.swing.overlay.IJHotDrawOverlayAdapter;
import imagej.ui.swing.overlay.JHotDrawTool;
import imagej.ui.swing.overlay.OverlayCreatedListener;
import imagej.ui.swing.overlay.ToolDelegator;
import imagej.util.IntCoords;
import imagej.util.Log;
import imagej.util.RealCoords;
import imagej.util.RealRect;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.Border;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import org.jhotdraw.draw.DefaultDrawing;
import org.jhotdraw.draw.DefaultDrawingEditor;
import org.jhotdraw.draw.DefaultDrawingView;
import org.jhotdraw.draw.Drawing;
import org.jhotdraw.draw.DrawingEditor;
import org.jhotdraw.draw.Figure;
import org.jhotdraw.draw.event.FigureSelectionEvent;
import org.jhotdraw.draw.event.FigureSelectionListener;
/**
* A renderer of an {@link ImageCanvas}, which uses JHotDraw's
* {@link DefaultDrawingView} component to do most of the work.
*
* @author Curtis Rueden
* @author Lee Kamentsky
*/
public class JHotDrawImageCanvas extends JPanel implements AdjustmentListener {
private static final long serialVersionUID = 1L;
private final SwingImageDisplayViewer displayViewer;
private final Drawing drawing;
private final DefaultDrawingView drawingView;
private final DrawingEditor drawingEditor;
private final ToolDelegator toolDelegator;
private final JScrollPane scrollPane;
private boolean insideSynch = false;
private boolean initialized = false;
private final List<FigureView> figureViews = new ArrayList<FigureView>();
private final List<EventSubscriber<?>> subscribers;
public JHotDrawImageCanvas(final SwingImageDisplayViewer displayViewer) {
this.displayViewer = displayViewer;
drawing = new DefaultDrawing(); // or QuadTreeDrawing?
drawingView = new DefaultDrawingView();
drawingView.setDrawing(drawing);
drawingEditor = new DefaultDrawingEditor();
drawingEditor.add(drawingView);
toolDelegator = new ToolDelegator();
drawingEditor.setTool(toolDelegator);
scrollPane = new JScrollPane(drawingView);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
scrollPane.getHorizontalScrollBar().addAdjustmentListener(this);
scrollPane.getVerticalScrollBar().addAdjustmentListener(this);
final ImageJ context = displayViewer.getDisplay().getContext();
final ToolService toolService = context.getService(ToolService.class);
final Tool activeTool = toolService.getActiveTool();
activateTool(activeTool);
final EventService eventService = context.getService(EventService.class);
subscribers = eventService.subscribe(this);
drawingView.addFigureSelectionListener(new FigureSelectionListener() {
@Override
public void selectionChanged(final FigureSelectionEvent event) {
onFigureSelectionChanged(event);
}
});
drawingView.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
onSizeChanged(e);
}
});
}
protected FigureView getFigureView(final DataView dataView) {
for (final FigureView figureView : figureViews) {
if (figureView.getDataView() == dataView) return figureView;
}
return null;
}
/**
* Respond to the JHotDraw figure selection event by selecting and deselecting
* views whose state has changed
*
* @param event - event indicating that the figure selections have changed
*/
protected void onFigureSelectionChanged(final FigureSelectionEvent event) {
final Set<Figure> newSelection = event.getNewSelection();
final Set<Figure> oldSelection = event.getOldSelection();
for (final DataView view : displayViewer.getDisplay()) {
final FigureView figureView = getFigureView(view);
if (figureView != null) {
final Figure figure = figureView.getFigure();
if (newSelection.contains(figure)) {
// BDZ removed next line 10-12-11
// Fixes drawing of multiple overlays (#817). Lee had this code
// here in anticipation of avoiding infinite event loops.
// Inspection seems to bear out that this possibility doesn't
// happen.
// if (!oldSelection.contains(figure))
view.setSelected(true);
}
else if (oldSelection.contains(figure)) {
view.setSelected(false);
}
}
}
}
/**
* Tell the display's canvas that its viewport's size changed
*
* @param e
*/
protected void onSizeChanged(final ComponentEvent e) {
final ImageCanvas canvas = getDisplay().getCanvas();
final Rectangle viewRect = scrollPane.getViewport().getViewRect();
canvas.setViewportSize(viewRect.width, viewRect.height);
}
@EventHandler
protected void onViewSelected(final DataViewSelectedEvent event) {
final DataView view = event.getView();
final FigureView figureView = getFigureView(view);
if (figureView != null) {
final Figure figure = figureView.getFigure();
if (!drawingView.getSelectedFigures().contains(figure)) {
drawingView.addToSelection(figure);
}
}
}
@EventHandler
protected void onViewDeselected(final DataViewDeselectedEvent event) {
final DataView view = event.getView();
final FigureView figureView = getFigureView(view);
if (figureView != null) {
final Figure figure = figureView.getFigure();
if (drawingView.getSelectedFigures().contains(figure)) {
drawingView.removeFromSelection(figure);
}
}
}
@EventHandler
protected void onToolActivatedEvent(final ToolActivatedEvent event) {
final Tool iTool = event.getTool();
activateTool(iTool);
}
@EventHandler
protected void onEvent(final DisplayDeletedEvent event) {
if (event.getObject() == getDisplay()) {
final EventService eventService =
event.getContext().getService(EventService.class);
eventService.unsubscribe(subscribers);
}
}
@EventHandler
protected void onEvent(final ZoomEvent event) {
if (event.getCanvas() != getDisplay().getCanvas()) return;
syncPanAndZoom();
}
@EventHandler
protected void onEvent(final MouseCursorEvent event) {
drawingView.setCursor(AWTCursors.getCursor(getDisplay().getCanvas()
.getCursor()));
}
void rebuild() {
for (final DataView dataView : getDisplay()) {
FigureView figureView = getFigureView(dataView);
if (figureView == null) {
if (dataView instanceof DatasetView) {
figureView =
new DatasetFigureView(this.displayViewer, (DatasetView) dataView);
}
else if (dataView instanceof OverlayView) {
figureView =
new OverlayFigureView(this.displayViewer, (OverlayView) dataView);
}
else {
Log.error("Don't know how to make a figure view for " +
dataView.getClass().getName());
continue;
}
figureViews.add(figureView);
}
}
int idx = 0;
while (idx < figureViews.size()) {
final FigureView figureView = figureViews.get(idx);
if (!getDisplay().contains(figureView.getDataView())) {
figureViews.remove(idx);
figureView.dispose();
}
else {
idx++;
}
}
}
void update() {
for (final FigureView figureView : figureViews) {
figureView.update();
}
}
protected void activateTool(final Tool iTool) {
if (iTool instanceof IJHotDrawOverlayAdapter) {
final IJHotDrawOverlayAdapter adapter = (IJHotDrawOverlayAdapter) iTool;
// When the tool creates an overlay, add the
// overlay/figure combo to a SwingOverlayView.
final OverlayCreatedListener listener = new OverlayCreatedListener() {
@SuppressWarnings("synthetic-access")
@Override
public void overlayCreated(final FigureCreatedEvent e) {
final OverlayView overlay = e.getOverlay();
final ImageDisplay display = displayViewer.getDisplay();
for (int i = 0; i < display.numDimensions(); i++) {
final AxisType axis = display.axis(i);
if (Axes.isXY(axis)) continue;
if (overlay.getData().getAxisIndex(axis) < 0) {
overlay.setPosition(display.getLongPosition(axis), axis);
}
}
if (drawingView.getSelectedFigures().contains(e.getFigure())) {
overlay.setSelected(true);
}
final OverlayFigureView figureView =
new OverlayFigureView(displayViewer, overlay, e.getFigure());
figureViews.add(figureView);
display.add(overlay);
display.update();
}
};
final JHotDrawTool creationTool =
adapter.getCreationTool(getDisplay(), listener);
toolDelegator.setCreationTool(creationTool);
}
else {
toolDelegator.setCreationTool(null);
}
}
// -- JHotDrawImageCanvas methods --
public Drawing getDrawing() {
return drawing;
}
public DefaultDrawingView getDrawingView() {
return drawingView;
}
public DrawingEditor getDrawingEditor() {
return drawingEditor;
}
public void addEventDispatcher(final AWTInputEventDispatcher dispatcher) {
dispatcher.register(drawingView);
}
// -- JComponent methods --
@Override
public Dimension getPreferredSize() {
// NB Johannes
// HACK: Size the canvas one pixel larger. This is a workaround to an
// apparent bug in JHotDraw, where an ImageFigure is initially drawn as a
// large X until it is finished being rendered. Unfortunately, the X is
// slightly smaller than the image after being rendered.
final int w = scrollPane.getPreferredSize().width + 1;
final int h = scrollPane.getPreferredSize().height + 1;
// NB BDZ - Avoid space left around for nonexistent scroll bars
// This code works (except rare cases). Not sure why 4 is key. 3 and lower
// and sizing failures happen. We used to have a fudge factor of 5 in place
// elsewhere. Can no longer find it. But it is apparent from debugging
// statements that there is an off by 5(?). Notice we test versus 4 but add
// 5. If both 4 then initial zoom has scrollbars when not needed. If both 5
// then some zoom ins can leave empty scroll bar space. (I may have these
// conditions reversed). Anyhow printing in here can show getPreferredSize()
// starts out at w,h and before/during 1st redraw goes to w+1,h+1. Its this
// off by one that makes initial view have scroll bars unnecessarily. Look
// into this further.
final Dimension drawViewSize = drawingView.getPreferredSize();
final Border border = scrollPane.getBorder();
Dimension slop = new Dimension(0, 0);
if (border != null) {
final Insets insets = border.getBorderInsets(scrollPane);
slop =
new Dimension(insets.left + insets.right, insets.top + insets.bottom);
}
final Dimension bigDrawViewSize =
new Dimension(drawViewSize.width + slop.width + 1, drawViewSize.height +
slop.height + 1);
if (drawViewSize.height == 0 || drawViewSize.width == 0) {
// The image figure hasn't been placed yet. Calculate the projected size.
final Rectangle bounds = StaticSwingUtils.getWorkSpaceBounds();
final RealRect imageBounds = getDisplay().getImageExtents();
final double zoomFactor = getDisplay().getCanvas().getZoomFactor();
return new Dimension(Math.min((int) (imageBounds.width * zoomFactor) +
slop.width + 1, bounds.width), Math
.min((int) (imageBounds.height * zoomFactor) + slop.width + 1,
bounds.height));
}
if (bigDrawViewSize.width <= scrollPane.getPreferredSize().width &&
bigDrawViewSize.height <= scrollPane.getPreferredSize().height)
{
return bigDrawViewSize;
}
return new Dimension(w, h);
}
// -- Helper methods --
private ImageDisplay getDisplay() {
return displayViewer.getDisplay();
}
// -- AdjustmentListener methods --
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
if (insideSynch) return;
final ImageCanvas canvas = getDisplay().getCanvas();
final Point viewPos = scrollPane.getViewport().getViewPosition();
final Rectangle viewRect = scrollPane.getViewport().getViewRect();
if (viewRect.width != canvas.getViewportWidth() ||
viewRect.height != canvas.getViewportHeight())
{
canvas.setViewportSize(viewRect.width, viewRect.height);
}
final RealCoords center =
new RealCoords((viewPos.x + viewRect.width / 2) /
drawingView.getScaleFactor(), (viewPos.y + viewRect.height / 2) /
drawingView.getScaleFactor());
if (!initialized) return;
final RealCoords oldCenter = canvas.getPanCenter();
if (oldCenter.x == center.x && oldCenter.y == center.y) return;
canvas.setPan(center);
}
private void syncPanAndZoom() {
if (insideSynch) return;
insideSynch = true;
try {
final ImageCanvas canvas = getDisplay().getCanvas();
boolean considerResize = !initialized;
final double zoomFactor = canvas.getZoomFactor();
if (drawingView.getScaleFactor() != zoomFactor) {
drawingView.setScaleFactor(zoomFactor);
scrollPane.validate();
considerResize = true;
}
final Point viewPos = scrollPane.getViewport().getViewPosition();
final Rectangle viewRect = scrollPane.getViewport().getViewRect();
final RealCoords center = canvas.getPanCenter();
final int originX =
(int) Math.round(center.x * zoomFactor - viewRect.width / 2.0);
final int originY =
(int) Math.round(center.y * zoomFactor - viewRect.height / 2.0);
final IntCoords origin = new IntCoords(originX, originY);
if (constrainOrigin(origin)) {
// Back-compute the center if origin was changed.
canvas.setPan(new RealCoords((origin.x + viewRect.width / 2.0) /
zoomFactor, (origin.y + viewRect.height / 2.0) / zoomFactor));
}
if (viewPos.x != origin.x || viewPos.y != origin.y) {
scrollPane.getViewport().setViewPosition(new Point(origin.x, origin.y));
}
if (considerResize) maybeResizeWindow();
}
finally {
insideSynch = false;
initialized = true;
}
}
/**
* Constrain the origin to within the image.
*
* @param origin
* @return true if origin was changed.
*/
private boolean constrainOrigin(final IntCoords origin) {
boolean originChanged = false;
if (origin.x < 0) {
origin.x = 0;
originChanged = true;
}
if (origin.y < 0) {
origin.y = 0;
originChanged = true;
}
final Dimension viewportSize = scrollPane.getViewport().getSize();
final Dimension canvasSize = drawingView.getSize();
final int xMax = canvasSize.width - viewportSize.width;
final int yMax = canvasSize.height - viewportSize.height;
if (origin.x > xMax) {
origin.x = xMax;
originChanged = true;
}
if (origin.y > yMax) {
origin.y = yMax;
originChanged = true;
}
return originChanged;
}
private void maybeResizeWindow() {
final Rectangle bounds = StaticSwingUtils.getWorkSpaceBounds();
final RealRect imageBounds = getDisplay().getImageExtents();
final ImageCanvas canvas = getDisplay().getCanvas();
final IntCoords topLeft =
canvas.imageToPanelCoords(new RealCoords(imageBounds.x, imageBounds.y));
final IntCoords bottomRight =
canvas.imageToPanelCoords(new RealCoords(imageBounds.x +
imageBounds.width, imageBounds.y + imageBounds.height));
if (bottomRight.x - topLeft.x > bounds.width) return;
if (bottomRight.y - topLeft.y > bounds.height) return;
// FIXME TEMP
// NB BDZ - there is an issue where zoom out does not always pack()
// correctly. There seems like there is a race condition. I have tried a
// number of approaches to a fix but nothing has fallen out yet. Approaches
// included:
// - generating a "INeedARepackEvent" and trying to handle elsewhere
// - calling redoLayout() on the panel (infinite loop)
// - call pack() after a slight delay
// Current approach:
// Update on a different thread after a slight delay.
// Note this always resizes correctly (except for off by a fixed
// scrollbar size which I have handled in getPreferredSize())
if (false) {
new Thread() {
@Override
public void run() {
// NB: Not enough to be in separate thread - it must sleep a little.
try {
Thread.sleep(30);
}
catch (final Exception e) {
// no action needed
}
displayViewer.getPanel().getWindow().pack();
}
}.start();
}
else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
displayViewer.getPanel().getWindow().pack();
}
});
}
}
}
| Fix Eclipse warning
This used to be revision r5521.
| ui/awt-swing/swing/ui-base/src/main/java/imagej/ui/swing/display/JHotDrawImageCanvas.java | Fix Eclipse warning | <ide><path>i/awt-swing/swing/ui-base/src/main/java/imagej/ui/swing/display/JHotDrawImageCanvas.java
<ide> }
<ide>
<ide> @EventHandler
<del> protected void onEvent(final MouseCursorEvent event) {
<add> protected void onEvent(
<add> @SuppressWarnings("unused") final MouseCursorEvent event)
<add> {
<ide> drawingView.setCursor(AWTCursors.getCursor(getDisplay().getCanvas()
<ide> .getCursor()));
<ide> } |
|
Java | mit | 4c1bc46ec948b9e8b97113ee3ca5b50b8473d80a | 0 | evilband7/web-thumbnailer | package io.prime.web.thumbnailator.core.filter;
import org.apache.commons.lang3.BooleanUtils;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
public class CropFilter implements ThumbnailatorFilter
{
private int width;
private int height;
private Position position;
@Override
public <T> void filter( final Builder<T> builder )
{
if ( BooleanUtils.isFalse( ( width > 0 ) || ( height > 0 ) ) ) {
}
if ( ( width > 0 ) && ( height > 0 ) ) {
builder.size( width, height );
}
else {
if ( width > 0 ) {
builder.width( width );
}
else {
builder.height( height );
}
}
if ( null == position ) {
position = Positions.CENTER;
}
builder.crop( position );
}
public int getWidth()
{
return width;
}
public void setWidth( final int width )
{
this.width = width;
}
public int getHeight()
{
return height;
}
public void setHeight( final int height )
{
this.height = height;
}
public Position getPosition()
{
return position;
}
public void setPosition( final Position position )
{
this.position = position;
}
}
| core/src/main/java/io/prime/web/thumbnailator/core/filter/CropFilter.java | package io.prime.web.thumbnailator.core.filter;
import org.apache.commons.lang3.BooleanUtils;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
public class CropFilter implements ThumbnailatorFilter
{
private int width;
private int height;
private Position position;
@Override
public <T> void filter(final Builder<T> builder)
{
if (BooleanUtils.isFalse((width > 0) || (height > 0))) {
}
if ((width > 0) && (height > 0)) {
builder.size(width, height);
} else {
if (width > 0) {
builder.width(width);
} else {
builder.height(height);
}
}
if (null == position) {
position = Positions.CENTER;
}
builder.crop(position);
}
public int getWidth()
{
return width;
}
public void setWidth(final int width)
{
this.width = width;
}
public int getHeight()
{
return height;
}
public void setHeight(final int height)
{
this.height = height;
}
}
| fix position | core/src/main/java/io/prime/web/thumbnailator/core/filter/CropFilter.java | fix position | <ide><path>ore/src/main/java/io/prime/web/thumbnailator/core/filter/CropFilter.java
<ide> private Position position;
<ide>
<ide> @Override
<del> public <T> void filter(final Builder<T> builder)
<add> public <T> void filter( final Builder<T> builder )
<ide> {
<del> if (BooleanUtils.isFalse((width > 0) || (height > 0))) {
<add> if ( BooleanUtils.isFalse( ( width > 0 ) || ( height > 0 ) ) ) {
<ide>
<ide> }
<del> if ((width > 0) && (height > 0)) {
<del> builder.size(width, height);
<del> } else {
<del> if (width > 0) {
<del> builder.width(width);
<del> } else {
<del> builder.height(height);
<add> if ( ( width > 0 ) && ( height > 0 ) ) {
<add> builder.size( width, height );
<add> }
<add> else {
<add> if ( width > 0 ) {
<add> builder.width( width );
<add> }
<add> else {
<add> builder.height( height );
<ide> }
<ide> }
<ide>
<del> if (null == position) {
<add> if ( null == position ) {
<ide> position = Positions.CENTER;
<ide> }
<ide>
<del> builder.crop(position);
<add> builder.crop( position );
<ide> }
<ide>
<ide> public int getWidth()
<ide> return width;
<ide> }
<ide>
<del> public void setWidth(final int width)
<add> public void setWidth( final int width )
<ide> {
<ide> this.width = width;
<ide> }
<ide> return height;
<ide> }
<ide>
<del> public void setHeight(final int height)
<add> public void setHeight( final int height )
<ide> {
<ide> this.height = height;
<ide> }
<ide>
<add> public Position getPosition()
<add> {
<add> return position;
<add> }
<add>
<add> public void setPosition( final Position position )
<add> {
<add> this.position = position;
<add> }
<add>
<ide> } |
|
Java | mit | 7ee9f7f8438200686245ecc9d9395825e735f3cd | 0 | PCLuddite/baxshops | /*
* Copyright (C) Timothy Baxendale
* Portions derived from Shops Copyright (c) 2012 Nathan Dinsmore and Sam Lazarus.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.tbax.baxshops;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.tbax.baxshops.items.EnchantMap;
import org.tbax.baxshops.items.ItemUtil;
import org.tbax.baxshops.serialization.SafeMap;
import org.tbax.baxshops.serialization.UpgradeableSerializable;
import org.tbax.baxshops.serialization.UpgradeableSerialization;
import java.util.Map;
import java.util.Objects;
@SuppressWarnings("unused")
public final class BaxEntry implements UpgradeableSerializable
{
private static final int CAN_BUY = 1;
private static final int CAN_SELL = 2;
private ItemStack stack = new ItemStack(Material.AIR);
private double retailPrice = Integer.MAX_VALUE;
private double refundPrice = 0;
private int buySell = CAN_BUY;
private int quantity = 0;
public BaxEntry()
{
}
public BaxEntry(@NotNull BaxEntry other)
{
quantity = other.quantity;
refundPrice = other.refundPrice;
retailPrice = other.retailPrice;
buySell = other.buySell;
stack = other.stack.clone();
}
public BaxEntry(@NotNull ItemStack item)
{
setItem(item);
quantity = item.getAmount();
}
public BaxEntry(Map<String, Object> args)
{
UpgradeableSerialization.upgrade(this, args);
}
@Override @SuppressWarnings("unchecked")
public void upgrade00300(@NotNull SafeMap map)
{
retailPrice = map.getDouble("retailPrice", 10000);
refundPrice = map.getDouble("refundPrice", 0);
if (map.get("stack") instanceof Map) {
stack = ItemStack.deserialize((Map) map.get("stack"));
}
quantity = map.getInteger("quantity");
buySell = CAN_BUY;
}
@Override @SuppressWarnings("unchecked")
public void upgrade00421(@NotNull SafeMap map)
{
retailPrice = map.getDouble("retailPrice", retailPrice);
refundPrice = map.getDouble("refundPrice", 0);
quantity = map.getInteger("quantity", 0);
if (map.get("stack") instanceof Map) {
stack = ItemStack.deserialize((Map) map.get("stack"));
}
buySell = CAN_BUY;
}
@Override
public void upgrade00450(@NotNull SafeMap map)
{
stack = map.getItemStack("stack", stack);
retailPrice = map.getDouble("retailPrice", retailPrice);
refundPrice = map.getDouble("refundPrice", 0);
quantity = map.getInteger("quantity", 0);
buySell = CAN_BUY | (refundPrice >= 0 ? CAN_SELL : 0);
}
@Override
public void upgrade00451(@NotNull SafeMap map)
{
stack = map.getItemStack("stack", stack);
retailPrice = map.getDouble("retailPrice", retailPrice);
refundPrice = Math.max(map.getDouble("refundPrice", refundPrice), 0);
quantity = map.getInteger("quantity", 0);
buySell = map.getBoolean("canBuy", true) ? CAN_BUY : 0;
buySell = buySell | (map.getBoolean("canSell", false) ? CAN_SELL : 0);
}
public boolean canBuy()
{
return (buySell & CAN_BUY) == CAN_BUY;
}
public void canBuy(boolean value)
{
if (value) {
buySell = buySell | CAN_BUY;
}
else {
buySell = buySell & ~CAN_BUY;
}
}
public boolean canSell()
{
return (buySell & CAN_SELL) == CAN_SELL;
}
public void canSell(boolean value)
{
if (value) {
buySell = buySell | CAN_SELL;
}
else {
buySell = buySell & ~CAN_SELL;
}
}
public double getRetailPrice()
{
return retailPrice;
}
public void setRetailPrice(double price)
{
retailPrice = price;
}
public double getRefundPrice()
{
return refundPrice;
}
public void setRefundPrice(double price)
{
refundPrice = price;
}
public Material getType()
{
return stack.getType();
}
public void add(int amt)
{
setAmount(getAmount() + amt);
}
public void subtract(int amt)
{
setAmount(getAmount() - amt);
}
public void setItem(@NotNull ItemStack item)
{
stack = item.clone();
}
public void setItem(@NotNull ItemStack item, int qty)
{
setItem(item);
quantity = qty;
}
public void setItem(Material type)
{
stack = new ItemStack(type, getAmount());
}
public void setItem(Material type, int damage)
{
stack = new ItemStack(type, getAmount());
setDurability(damage);
}
/**
* clones this entry's item stack and sets its amount to this entry's quantity
* If the entry quantity is equal to zero, the material type may be AIR
* @return an ItemStack
*/
public @NotNull ItemStack toItemStack()
{
ItemStack stack = this.stack.clone();
stack.setAmount(quantity);
if (quantity == 0)
stack.setType(this.stack.getType());
return stack;
}
/**
* gets a reference to the ItemStack that this entry points to. the amount is not guaranteed to be the entry
* quantity
* @return the ItemStack
*/
public @NotNull ItemStack getItemStack()
{
return stack;
}
public Map<Enchantment, Integer> getEnchantments()
{
return EnchantMap.getEnchants(stack);
}
public boolean hasItemMeta()
{
return stack.hasItemMeta();
}
public ItemMeta getItemMeta()
{
return stack.getItemMeta();
}
public void setAmount(int amt)
{
quantity = amt;
}
public int getAmount()
{
return quantity;
}
public int getDurability()
{
return ItemUtil.getDurability(stack);
}
public void setDurability(int durability)
{
ItemUtil.setDurability(stack, durability);
}
public int getDamagePercent()
{
return (int)Math.round((getDurability() * 100d) / ItemUtil.getMaxDamage(stack.getType()));
}
public void setDamagePercent(int pct)
{
double damage = (pct / 100d) * ItemUtil.getMaxDamage(stack.getType());
setDurability((int)damage);
}
public @NotNull String getName()
{
return ItemUtil.getName(this);
}
public @NotNull String getFormattedName()
{
return Format.itemName(getAmount(), getName());
}
public @NotNull String getFormattedSellPrice()
{
return Format.money(MathUtil.multiply(refundPrice, getAmount()));
}
public @NotNull String getFormattedSellPrice2()
{
return Format.money2(MathUtil.multiply(refundPrice, getAmount()));
}
public @NotNull String getFormattedBuyPrice()
{
return Format.money(MathUtil.multiply(retailPrice, getAmount()));
}
public @NotNull String getFormattedBuyPrice2()
{
return Format.money2(MathUtil.multiply(retailPrice, getAmount()));
}
@Override
public String toString()
{
StringBuilder info = new StringBuilder();
info.append(Format.header("BaxEntry Information"));
info.append('\n');
info.append("Name: ").append(Format.itemName(ItemUtil.getName(this))).append('\n');
info.append("Material: ").append(Format.command(stack.getType().toString())).append('\n');
if (ItemUtil.isDamageable(stack.getType())) {
info.append("Damage: ").append(ChatColor.YELLOW).append(getDamagePercent()).append('%').append(ChatColor.RESET).append('\n');
}
if (stack.hasItemMeta()) {
ItemMeta meta = stack.getItemMeta();
if (meta.hasDisplayName()) {
info.append("Display Name: ").append(ChatColor.YELLOW).append(stack.getItemMeta().getDisplayName()).append(ChatColor.RESET).append('\n');
}
if (meta.hasLore()) {
info.append("Description: ").append(ChatColor.BLUE);
for (String line : meta.getLore()) {
info.append(line).append(' ');
}
info.append(ChatColor.RESET).append('\n');
}
}
Map<Enchantment, Integer> enchmap = EnchantMap.getEnchants(stack);
if (enchmap != null && !enchmap.isEmpty()) {
info.append("Enchants: ").append(Format.enchantments(EnchantMap.fullListString(enchmap))).append('\n');
}
info.append("Quantity: ").append(getAmount() == 0 ? ChatColor.DARK_RED + "OUT OF STOCK" + ChatColor.RESET : Format.number(getAmount())).append('\n');
if (canBuy()) {
info.append("Buy Price: ").append(ChatColor.DARK_GREEN).append(ShopPlugin.getEconomy().format(retailPrice)).append(ChatColor.RESET).append('\n');
}
if (canSell()) {
info.append("Sell Price: ").append(ChatColor.BLUE).append(ShopPlugin.getEconomy().format(refundPrice)).append(ChatColor.RESET).append('\n');
}
return info.toString();
}
public String toString(int index, boolean infinite)
{
StringBuilder name;
if(stack.getType() == Material.ENCHANTED_BOOK && EnchantMap.isEnchanted(stack)) {
name = new StringBuilder(Format.enchantments(ItemUtil.getName(this)));
}
else {
name = new StringBuilder(Format.listname(ItemUtil.getName(this)));
if (EnchantMap.isEnchanted(stack)) {
name.append(" ").append(Format.enchantments("(" + EnchantMap.abbreviatedListString(stack) + ")"));
}
}
String potionInfo = ItemUtil.getPotionInfo(stack);
if (!potionInfo.equals("")) {
name.append(" ").append(potionInfo);
}
if (ItemUtil.isDamageable(stack.getType()) && getDurability() > 0) {
if (infinite || getAmount() > 0) {
name.append(ChatColor.YELLOW);
}
name.append(" (Damage: ").append(getDamagePercent()).append("%)");
}
if (canBuy())
name.append(" ").append(Format.retailPrice(retailPrice));
if (canSell())
name.append(" ").append(Format.refundPrice(refundPrice));
if (!(canBuy() || canBuy()))
name.append(" ").append(ChatColor.DARK_RED).append("(Not for sale)");
if (infinite) {
return String.format("%s. %s", Format.bullet(index), Format.listname(name.toString()));
}
else if (getAmount() <= 0) {
return String.format("%s. (0) %s", ChatColor.RED.toString() + ChatColor.STRIKETHROUGH + index, Format.stripColor(name.toString()));
}
else {
return String.format("%d. " + ChatColor.GRAY + "(%d) %s", index, getAmount(), name.toString());
}
}
public static BaxEntry deserialize(Map<String, Object> args)
{
return new BaxEntry(args);
}
public static BaxEntry valueOf(Map<String, Object> args)
{
return deserialize(args);
}
public boolean isSimilar(ItemStack item)
{
if (item == null)
return false;
return stack.isSimilar(item);
}
public boolean isSimilar(ItemStack item, boolean smartStack)
{
return ItemUtil.isSimilar(item, stack, smartStack);
}
public boolean isSimilar(BaxEntry entry)
{
if (entry == null)
return false;
if (Double.compare(entry.retailPrice, retailPrice) != 0) return false;
if (Double.compare(entry.refundPrice, refundPrice) != 0) return false;
return stack.isSimilar(entry.stack);
}
public boolean isSimilar(BaxEntry entry, boolean smartStack)
{
return ItemUtil.isSimilar(entry.stack, stack, smartStack);
}
@Override
public int hashCode()
{
return Objects.hash(retailPrice, refundPrice, quantity);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj instanceof BaxEntry)
return equals((BaxEntry)obj);
if (obj instanceof ItemStack)
return equals((ItemStack)obj);
return false;
}
public boolean equals(BaxEntry entry)
{
if (entry == null) return false;
if (this == entry) return true;
if (Double.compare(entry.retailPrice, retailPrice) != 0) return false;
if (Double.compare(entry.refundPrice, refundPrice) != 0) return false;
if (buySell != entry.buySell) return false;
return stack.isSimilar(entry.stack) && quantity == entry.quantity;
}
public boolean equals(BaxEntry entry, boolean smartStack)
{
if (!smartStack) return equals(entry);
if (!equals(entry)) {
return entry.getType() == getType()
&& entry.getAmount() == quantity
&& buySell == entry.buySell
&& retailPrice == entry.retailPrice
&& refundPrice == entry.refundPrice
&& (ItemUtil.isSameBanner(entry.stack, stack)
|| ItemUtil.isSameBook(entry.stack, stack));
}
return true;
}
public boolean equals(ItemStack stack)
{
if (stack == null)
return false;
return this.stack.isSimilar(stack) && stack.getAmount() == quantity;
}
public String getAlias()
{
String name = ItemUtil.getName(this).toLowerCase();
return name.replace(' ', '_');
}
}
| src/main/java/org/tbax/baxshops/BaxEntry.java | /*
* Copyright (C) Timothy Baxendale
* Portions derived from Shops Copyright (c) 2012 Nathan Dinsmore and Sam Lazarus.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.tbax.baxshops;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.tbax.baxshops.items.EnchantMap;
import org.tbax.baxshops.items.ItemUtil;
import org.tbax.baxshops.serialization.SafeMap;
import org.tbax.baxshops.serialization.UpgradeableSerializable;
import org.tbax.baxshops.serialization.UpgradeableSerialization;
import java.util.Map;
import java.util.Objects;
@SuppressWarnings("unused")
public final class BaxEntry implements UpgradeableSerializable
{
private static final int CAN_BUY = 1;
private static final int CAN_SELL = 2;
private ItemStack stack = new ItemStack(Material.AIR);
private double retailPrice = Integer.MAX_VALUE;
private double refundPrice = 0;
private int buySell = CAN_BUY;
private int quantity = 0;
public BaxEntry()
{
}
public BaxEntry(@NotNull BaxEntry other)
{
quantity = other.quantity;
refundPrice = other.refundPrice;
retailPrice = other.retailPrice;
buySell = other.buySell;
stack = other.stack.clone();
}
public BaxEntry(@NotNull ItemStack item)
{
setItem(item);
quantity = item.getAmount();
}
public BaxEntry(Map<String, Object> args)
{
UpgradeableSerialization.upgrade(this, args);
}
@Override @SuppressWarnings("unchecked")
public void upgrade00300(@NotNull SafeMap map)
{
retailPrice = map.getDouble("retailPrice", 10000);
refundPrice = map.getDouble("refundPrice", 0);
if (map.get("stack") instanceof Map) {
stack = ItemStack.deserialize((Map) map.get("stack"));
}
quantity = map.getInteger("quantity");
buySell = CAN_BUY;
}
@Override @SuppressWarnings("unchecked")
public void upgrade00421(@NotNull SafeMap map)
{
retailPrice = map.getDouble("retailPrice", retailPrice);
refundPrice = map.getDouble("refundPrice", 0);
quantity = map.getInteger("quantity", 0);
if (map.get("stack") instanceof Map) {
stack = ItemStack.deserialize((Map) map.get("stack"));
}
buySell = CAN_BUY;
}
@Override
public void upgrade00450(@NotNull SafeMap map)
{
stack = map.getItemStack("stack", stack);
retailPrice = map.getDouble("retailPrice", retailPrice);
refundPrice = map.getDouble("refundPrice", 0);
quantity = map.getInteger("quantity", 0);
buySell = CAN_BUY | (refundPrice >= 0 ? CAN_SELL : 0);
}
@Override
public void upgrade00451(@NotNull SafeMap map)
{
stack = map.getItemStack("stack", stack);
retailPrice = map.getDouble("retailPrice", retailPrice);
refundPrice = Math.max(map.getDouble("refundPrice", refundPrice), 0);
quantity = map.getInteger("quantity", 0);
buySell = map.getBoolean("canBuy", true) ? CAN_BUY : 0;
buySell = buySell | (map.getBoolean("canSell", false) ? CAN_SELL : 0);
}
public boolean canBuy()
{
return (buySell & CAN_BUY) == CAN_BUY;
}
public void canBuy(boolean value)
{
if (value) {
buySell = buySell | CAN_BUY;
}
else {
buySell = buySell & ~CAN_BUY;
}
}
public boolean canSell()
{
return (buySell & CAN_SELL) == CAN_SELL;
}
public void canSell(boolean value)
{
if (value) {
buySell = buySell | CAN_SELL;
}
else {
buySell = buySell & ~CAN_SELL;
}
}
public double getRetailPrice()
{
return retailPrice;
}
public void setRetailPrice(double price)
{
retailPrice = price;
}
public double getRefundPrice()
{
return refundPrice;
}
public void setRefundPrice(double price)
{
refundPrice = price;
}
public Material getType()
{
return stack.getType();
}
public void add(int amt)
{
setAmount(getAmount() + amt);
}
public void subtract(int amt)
{
setAmount(getAmount() - amt);
}
public void setItem(@NotNull ItemStack item)
{
stack = item.clone();
}
public void setItem(@NotNull ItemStack item, int qty)
{
setItem(item);
quantity = qty;
}
public void setItem(Material type)
{
stack = new ItemStack(type, getAmount());
}
public void setItem(Material type, int damage)
{
stack = new ItemStack(type, getAmount());
setDurability(damage);
}
/**
* clones this entry's item stack and sets its amount to this entry's quantity
* If the entry quantity is equal to zero, the material type may be AIR
* @return an ItemStack
*/
public @NotNull ItemStack toItemStack()
{
ItemStack stack = this.stack.clone();
stack.setAmount(quantity);
if (quantity == 0)
stack.setType(this.stack.getType());
return stack;
}
/**
* gets a reference to the ItemStack that this entry points to. the amount is not guaranteed to be the entry
* quantity
* @return the ItemStack
*/
public @NotNull ItemStack getItemStack()
{
return stack;
}
public Map<Enchantment, Integer> getEnchantments()
{
return EnchantMap.getEnchants(stack);
}
public boolean hasItemMeta()
{
return stack.hasItemMeta();
}
public ItemMeta getItemMeta()
{
return stack.getItemMeta();
}
public void setAmount(int amt)
{
quantity = amt;
}
public int getAmount()
{
return quantity;
}
public int getDurability()
{
return ItemUtil.getDurability(stack);
}
public void setDurability(int durability)
{
ItemUtil.setDurability(stack, durability);
}
public int getDamagePercent()
{
return (int)Math.round((getDurability() * 100d) / ItemUtil.getMaxDamage(stack.getType()));
}
public void setDamagePercent(int pct)
{
double damage = (pct / 100d) * ItemUtil.getMaxDamage(stack.getType());
setDurability((int)damage);
}
public @NotNull String getName()
{
return ItemUtil.getName(this);
}
public @NotNull String getFormattedName()
{
return Format.itemName(getAmount(), getName());
}
public @NotNull String getFormattedSellPrice()
{
return Format.money(MathUtil.multiply(refundPrice, getAmount()));
}
public @NotNull String getFormattedSellPrice2()
{
return Format.money2(MathUtil.multiply(refundPrice, getAmount()));
}
public @NotNull String getFormattedBuyPrice()
{
return Format.money(MathUtil.multiply(retailPrice, getAmount()));
}
public @NotNull String getFormattedBuyPrice2()
{
return Format.money2(MathUtil.multiply(retailPrice, getAmount()));
}
@Override
public String toString()
{
StringBuilder info = new StringBuilder();
info.append(Format.header("BaxEntry Information"));
info.append('\n');
info.append("Name: ").append(Format.itemName(ItemUtil.getName(this))).append('\n');
info.append("Material: ").append(Format.command(stack.getType().toString())).append('\n');
if (ItemUtil.isDamageable(stack.getType())) {
info.append("Damage: ").append(ChatColor.YELLOW).append(getDamagePercent()).append('%').append(ChatColor.RESET).append('\n');
}
if (stack.hasItemMeta()) {
ItemMeta meta = stack.getItemMeta();
if (meta.hasDisplayName()) {
info.append("Display Name: ").append(ChatColor.YELLOW).append(stack.getItemMeta().getDisplayName()).append(ChatColor.RESET).append('\n');
}
if (meta.hasLore()) {
info.append("Description: ").append(ChatColor.BLUE);
for (String line : meta.getLore()) {
info.append(line).append(' ');
}
info.append(ChatColor.RESET).append('\n');
}
}
Map<Enchantment, Integer> enchmap = EnchantMap.getEnchants(stack);
if (enchmap != null && !enchmap.isEmpty()) {
info.append("Enchants: ").append(Format.enchantments(EnchantMap.fullListString(enchmap))).append('\n');
}
info.append("Quantity: ").append(getAmount() == 0 ? ChatColor.DARK_RED + "OUT OF STOCK" + ChatColor.RESET : Format.number(getAmount())).append('\n');
info.append("Buy Price: ").append(ChatColor.DARK_GREEN).append(ShopPlugin.getEconomy().format(retailPrice)).append(ChatColor.RESET).append('\n');
if (refundPrice >= 0) {
info.append("Sell Price: ").append(ChatColor.BLUE).append(ShopPlugin.getEconomy().format(refundPrice)).append(ChatColor.RESET).append('\n');
}
return info.toString();
}
public String toString(int index, boolean infinite)
{
StringBuilder name;
if(stack.getType() == Material.ENCHANTED_BOOK && EnchantMap.isEnchanted(stack)) {
name = new StringBuilder(Format.enchantments(ItemUtil.getName(this)));
}
else {
name = new StringBuilder(Format.listname(ItemUtil.getName(this)));
if (EnchantMap.isEnchanted(stack)) {
name.append(" ").append(Format.enchantments("(" + EnchantMap.abbreviatedListString(stack) + ")"));
}
}
String potionInfo = ItemUtil.getPotionInfo(stack);
if (!potionInfo.equals("")) {
name.append(" ").append(potionInfo);
}
if (ItemUtil.isDamageable(stack.getType()) && getDurability() > 0) {
if (infinite || getAmount() > 0) {
name.append(ChatColor.YELLOW);
}
name.append(" (Damage: ").append(getDamagePercent()).append("%)");
}
if (canBuy())
name.append(" ").append(Format.retailPrice(retailPrice));
if (canSell())
name.append(" ").append(Format.refundPrice(refundPrice));
if (!(canBuy() || canBuy()))
name.append(" ").append(ChatColor.DARK_RED).append("(Not for sale)");
if (infinite) {
return String.format("%s. %s", Format.bullet(index), Format.listname(name.toString()));
}
else if (getAmount() <= 0) {
return String.format("%s. (0) %s", ChatColor.RED.toString() + ChatColor.STRIKETHROUGH + index, Format.stripColor(name.toString()));
}
else {
return String.format("%d. " + ChatColor.GRAY + "(%d) %s", index, getAmount(), name.toString());
}
}
public static BaxEntry deserialize(Map<String, Object> args)
{
return new BaxEntry(args);
}
public static BaxEntry valueOf(Map<String, Object> args)
{
return deserialize(args);
}
public boolean isSimilar(ItemStack item)
{
if (item == null)
return false;
return stack.isSimilar(item);
}
public boolean isSimilar(ItemStack item, boolean smartStack)
{
return ItemUtil.isSimilar(item, stack, smartStack);
}
public boolean isSimilar(BaxEntry entry)
{
if (entry == null)
return false;
if (Double.compare(entry.retailPrice, retailPrice) != 0) return false;
if (Double.compare(entry.refundPrice, refundPrice) != 0) return false;
return stack.isSimilar(entry.stack);
}
public boolean isSimilar(BaxEntry entry, boolean smartStack)
{
return ItemUtil.isSimilar(entry.stack, stack, smartStack);
}
@Override
public int hashCode()
{
return Objects.hash(retailPrice, refundPrice, quantity);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj instanceof BaxEntry)
return equals((BaxEntry)obj);
if (obj instanceof ItemStack)
return equals((ItemStack)obj);
return false;
}
public boolean equals(BaxEntry entry)
{
if (entry == null) return false;
if (this == entry) return true;
if (Double.compare(entry.retailPrice, retailPrice) != 0) return false;
if (Double.compare(entry.refundPrice, refundPrice) != 0) return false;
if (buySell != entry.buySell) return false;
return stack.isSimilar(entry.stack) && quantity == entry.quantity;
}
public boolean equals(BaxEntry entry, boolean smartStack)
{
if (!smartStack) return equals(entry);
if (!equals(entry)) {
return entry.getType() == getType()
&& entry.getAmount() == quantity
&& buySell == entry.buySell
&& retailPrice == entry.retailPrice
&& refundPrice == entry.refundPrice
&& (ItemUtil.isSameBanner(entry.stack, stack)
|| ItemUtil.isSameBook(entry.stack, stack));
}
return true;
}
public boolean equals(ItemStack stack)
{
if (stack == null)
return false;
return this.stack.isSimilar(stack) && stack.getAmount() == quantity;
}
public String getAlias()
{
String name = ItemUtil.getName(this).toLowerCase();
return name.replace(' ', '_');
}
}
| Add canBuy()/canSell() conditions for CmdInfo
| src/main/java/org/tbax/baxshops/BaxEntry.java | Add canBuy()/canSell() conditions for CmdInfo | <ide><path>rc/main/java/org/tbax/baxshops/BaxEntry.java
<ide> info.append("Enchants: ").append(Format.enchantments(EnchantMap.fullListString(enchmap))).append('\n');
<ide> }
<ide> info.append("Quantity: ").append(getAmount() == 0 ? ChatColor.DARK_RED + "OUT OF STOCK" + ChatColor.RESET : Format.number(getAmount())).append('\n');
<del> info.append("Buy Price: ").append(ChatColor.DARK_GREEN).append(ShopPlugin.getEconomy().format(retailPrice)).append(ChatColor.RESET).append('\n');
<del> if (refundPrice >= 0) {
<add> if (canBuy()) {
<add> info.append("Buy Price: ").append(ChatColor.DARK_GREEN).append(ShopPlugin.getEconomy().format(retailPrice)).append(ChatColor.RESET).append('\n');
<add> }
<add> if (canSell()) {
<ide> info.append("Sell Price: ").append(ChatColor.BLUE).append(ShopPlugin.getEconomy().format(refundPrice)).append(ChatColor.RESET).append('\n');
<ide> }
<ide> return info.toString(); |
|
Java | lgpl-2.1 | f1669b9422679b560491b8220a79b73f17df08d6 | 0 | ethaneldridge/vassal,ethaneldridge/vassal,ethaneldridge/vassal | /*
* $Id$
*
* Copyright (c) 2000-2008 by Rodney Kinney, Joel Uckelman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.launch;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.lang.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import VASSAL.Info;
import VASSAL.tools.ErrorDialog;
/**
* @author Joel Uckelman
* @since 3.1.0
*/
public class StartUp {
private static final Logger logger = LoggerFactory.getLogger(StartUp.class);
public void initSystemProperties() {
initHTTPProxyProperties();
initSystemSpecificProperties();
initUIProperties();
}
protected void initHTTPProxyProperties() {
final String httpProxyHost = "http.proxyHost"; //$NON-NLS-1$
final String proxyHost = "proxyHost"; //$NON-NLS-1$
if (System.getProperty(httpProxyHost) == null &&
System.getProperty(proxyHost) != null) {
System.setProperty(httpProxyHost, System.getProperty(proxyHost));
}
final String httpProxyPort = "http.proxyPort"; //$NON-NLS-1$
final String proxyPort = "proxyPort"; //$NON-NLS-1$
if (System.getProperty(httpProxyPort) == null &&
System.getProperty(proxyPort) != null) {
System.setProperty(httpProxyPort, System.getProperty(proxyPort));
}
}
protected void initUIProperties() {
System.setProperty("swing.aatext", "true"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("swing.boldMetal", "false"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("awt.useSystemAAFontSettings", "on"); //$NON-NLS-1$ //$NON-NLS-2$
if (!SystemUtils.IS_OS_WINDOWS) {
// use native LookAndFeel
// NB: This must be after Mac-specific properties
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException e) {
ErrorDialog.bug(e);
}
catch (IllegalAccessException e) {
ErrorDialog.bug(e);
}
catch (InstantiationException e) {
ErrorDialog.bug(e);
}
catch (UnsupportedLookAndFeelException e) {
ErrorDialog.bug(e);
}
}
// Ensure consistent behavior in NOT consuming "mousePressed" events
// upon a JPopupMenu closing (added for Windows L&F, but others might
// also be affected.
UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE);
}
protected void initSystemSpecificProperties() {}
public void startErrorLog() {
// begin the error log
logger.info("Starting"); //$NON-NLS-1$
logger.info("OS " + System.getProperty("os.name")); //$NON-NLS-1$ //$NON-NLS-2$
logger.info("Java version " + System.getProperty("java.version")); //$NON-NLS-1$ //$NON-NLS-2$
logger.info("VASSAL version " + Info.getVersion()); //$NON-NLS-1$
}
}
| src/VASSAL/launch/StartUp.java | /*
* $Id$
*
* Copyright (c) 2000-2008 by Rodney Kinney, Joel Uckelman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.launch;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import VASSAL.Info;
import VASSAL.tools.ErrorDialog;
/**
* @author Joel Uckelman
* @since 3.1.0
*/
public class StartUp {
private static final Logger logger = LoggerFactory.getLogger(StartUp.class);
public void initSystemProperties() {
initHTTPProxyProperties();
initSystemSpecificProperties();
initUIProperties();
}
protected void initHTTPProxyProperties() {
final String httpProxyHost = "http.proxyHost"; //$NON-NLS-1$
final String proxyHost = "proxyHost"; //$NON-NLS-1$
if (System.getProperty(httpProxyHost) == null &&
System.getProperty(proxyHost) != null) {
System.setProperty(httpProxyHost, System.getProperty(proxyHost));
}
final String httpProxyPort = "http.proxyPort"; //$NON-NLS-1$
final String proxyPort = "proxyPort"; //$NON-NLS-1$
if (System.getProperty(httpProxyPort) == null &&
System.getProperty(proxyPort) != null) {
System.setProperty(httpProxyPort, System.getProperty(proxyPort));
}
}
protected void initUIProperties() {
System.setProperty("swing.aatext", "true"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("swing.boldMetal", "false"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("awt.useSystemAAFontSettings", "on"); //$NON-NLS-1$ //$NON-NLS-2$
// use native LookAndFeel
// NB: This must be after Mac-specific properties
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException e) {
ErrorDialog.bug(e);
}
catch (IllegalAccessException e) {
ErrorDialog.bug(e);
}
catch (InstantiationException e) {
ErrorDialog.bug(e);
}
catch (UnsupportedLookAndFeelException e) {
ErrorDialog.bug(e);
}
// Ensure consistent behavior in NOT consuming "mousePressed" events
// upon a JPopupMenu closing (added for Windows L&F, but others might
// also be affected.
UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE);
}
protected void initSystemSpecificProperties() {}
public void startErrorLog() {
// begin the error log
logger.info("Starting"); //$NON-NLS-1$
logger.info("OS " + System.getProperty("os.name")); //$NON-NLS-1$ //$NON-NLS-2$
logger.info("Java version " + System.getProperty("java.version")); //$NON-NLS-1$ //$NON-NLS-2$
logger.info("VASSAL version " + Info.getVersion()); //$NON-NLS-1$
}
}
| Don't use native LookAndFeel on Windows, as it causes too many problems there. Argh.
git-svn-id: 3948e88432e1a59e1cb2bc472f8f957688004121@8079 67b53d14-2c14-4ace-a08f-0dab2b34000c
| src/VASSAL/launch/StartUp.java | Don't use native LookAndFeel on Windows, as it causes too many problems there. Argh. | <ide><path>rc/VASSAL/launch/StartUp.java
<ide>
<ide> import javax.swing.UIManager;
<ide> import javax.swing.UnsupportedLookAndFeelException;
<add>
<add>import org.apache.commons.lang.SystemUtils;
<ide>
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide> System.setProperty("swing.boldMetal", "false"); //$NON-NLS-1$ //$NON-NLS-2$
<ide> System.setProperty("awt.useSystemAAFontSettings", "on"); //$NON-NLS-1$ //$NON-NLS-2$
<ide>
<del> // use native LookAndFeel
<del> // NB: This must be after Mac-specific properties
<del> try {
<del> UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
<del> }
<del> catch (ClassNotFoundException e) {
<del> ErrorDialog.bug(e);
<del> }
<del> catch (IllegalAccessException e) {
<del> ErrorDialog.bug(e);
<del> }
<del> catch (InstantiationException e) {
<del> ErrorDialog.bug(e);
<del> }
<del> catch (UnsupportedLookAndFeelException e) {
<del> ErrorDialog.bug(e);
<add> if (!SystemUtils.IS_OS_WINDOWS) {
<add> // use native LookAndFeel
<add> // NB: This must be after Mac-specific properties
<add> try {
<add> UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
<add> }
<add> catch (ClassNotFoundException e) {
<add> ErrorDialog.bug(e);
<add> }
<add> catch (IllegalAccessException e) {
<add> ErrorDialog.bug(e);
<add> }
<add> catch (InstantiationException e) {
<add> ErrorDialog.bug(e);
<add> }
<add> catch (UnsupportedLookAndFeelException e) {
<add> ErrorDialog.bug(e);
<add> }
<ide> }
<ide>
<ide> // Ensure consistent behavior in NOT consuming "mousePressed" events |
|
Java | lgpl-2.1 | 73b3497c5235347786525303a088bf19b0afd77b | 0 | IsaacYangSLA/nuxeo-drive,DirkHoffmann/nuxeo-drive,DirkHoffmann/nuxeo-drive,arameshkumar/base-nuxeo-drive,ssdi-drive/nuxeo-drive,rsoumyassdi/nuxeo-drive,ssdi-drive/nuxeo-drive,loopingz/nuxeo-drive,loopingz/nuxeo-drive,arameshkumar/nuxeo-drive,DirkHoffmann/nuxeo-drive,DirkHoffmann/nuxeo-drive,arameshkumar/nuxeo-drive,IsaacYangSLA/nuxeo-drive,arameshkumar/nuxeo-drive,rsoumyassdi/nuxeo-drive,arameshkumar/base-nuxeo-drive,IsaacYangSLA/nuxeo-drive,arameshkumar/base-nuxeo-drive,loopingz/nuxeo-drive,IsaacYangSLA/nuxeo-drive,loopingz/nuxeo-drive,arameshkumar/base-nuxeo-drive,arameshkumar/nuxeo-drive,rsoumyassdi/nuxeo-drive,ssdi-drive/nuxeo-drive,rsoumyassdi/nuxeo-drive,DirkHoffmann/nuxeo-drive,IsaacYangSLA/nuxeo-drive,loopingz/nuxeo-drive | /*
* (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Olivier Grisel <[email protected]>
*/
package org.nuxeo.drive.listener;
import java.security.Principal;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import org.nuxeo.drive.adapter.FileSystemItem;
import org.nuxeo.drive.adapter.RootlessItemException;
import org.nuxeo.drive.service.FileSystemItemAdapterService;
import org.nuxeo.drive.service.NuxeoDriveEvents;
import org.nuxeo.drive.service.NuxeoDriveManager;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.LifeCycleConstants;
import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
import org.nuxeo.ecm.core.api.event.CoreEventConstants;
import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventListener;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
import org.nuxeo.ecm.core.schema.FacetNames;
import org.nuxeo.ecm.platform.audit.api.AuditLogger;
import org.nuxeo.ecm.platform.audit.api.ExtendedInfo;
import org.nuxeo.ecm.platform.audit.api.LogEntry;
import org.nuxeo.runtime.api.Framework;
/**
* Event listener to track events that should be mapped to file system item
* deletions in the the ChangeSummary computation.
*
* In particular this includes
*
* <li>Synchronization root unregistration (user specific)</li>
*
* <li>Simple document or root document lifecycle change to the 'deleted' state</li>
*
* <li>Simple document or root physical removal from the directory.</li>
*/
public class NuxeoDriveFileSystemDeletionListener implements EventListener {
@Override
public void handleEvent(Event event) throws ClientException {
DocumentEventContext ctx;
if (event.getContext() instanceof DocumentEventContext) {
ctx = (DocumentEventContext) event.getContext();
} else {
// Not interested in events that are not related to documents
return;
}
DocumentModel doc = ctx.getSourceDocument();
if (doc.hasFacet(FacetNames.SYSTEM_DOCUMENT)) {
// Not interested in system documents
return;
}
DocumentModel docForLogEntry = doc;
if (DocumentEventTypes.BEFORE_DOC_UPDATE.equals(event.getName())) {
docForLogEntry = handleBeforeDocUpdate(ctx, doc);
if (docForLogEntry == null) {
return;
}
}
if (DocumentEventTypes.ABOUT_TO_MOVE.equals(event.getName())
&& !handleAboutToMove(ctx, doc)) {
return;
}
if (LifeCycleConstants.TRANSITION_EVENT.equals(event.getName())
&& !handleLifeCycleTransition(ctx)) {
return;
}
if (DocumentEventTypes.ABOUT_TO_REMOVE.equals(event.getName())
&& !handleAboutToRemove(doc)) {
return;
}
// Some events will only impact a specific user (e.g. root
// unregistration)
String impactedUserName = (String) ctx.getProperty(NuxeoDriveEvents.IMPACTED_USERNAME_PROPERTY);
logDeletionEvent(docForLogEntry, ctx.getPrincipal(), impactedUserName);
}
protected DocumentModel handleBeforeDocUpdate(DocumentEventContext ctx,
DocumentModel doc) throws ClientException {
// Interested in update of a BlobHolder whose blob has been removed
boolean blobRemoved = false;
DocumentModel previousDoc = (DocumentModel) ctx.getProperty(CoreEventConstants.PREVIOUS_DOCUMENT_MODEL);
if (previousDoc != null) {
BlobHolder previousBh = previousDoc.getAdapter(BlobHolder.class);
if (previousBh != null) {
BlobHolder bh = doc.getAdapter(BlobHolder.class);
if (bh != null) {
blobRemoved = previousBh.getBlob() != null
&& bh.getBlob() == null;
}
}
}
if (blobRemoved) {
// Use previous doc holding a Blob for it to be adaptable as a
// FileSystemItem
return previousDoc;
} else {
return null;
}
}
protected boolean handleAboutToMove(DocumentEventContext ctx,
DocumentModel doc) throws ClientException {
// Interested in a move from a synchronization root to a non
// synchronized container
DocumentRef dstRef = (DocumentRef) ctx.getProperty(CoreEventConstants.DESTINATION_REF);
if (dstRef == null) {
return false;
}
CoreSession session = doc.getCoreSession();
IdRef dstIdRef;
if (dstRef instanceof IdRef) {
dstIdRef = (IdRef) dstRef;
} else {
DocumentModel dstDoc = session.getDocument(dstRef);
dstIdRef = new IdRef(dstDoc.getId());
}
if (Framework.getLocalService(NuxeoDriveManager.class).getSynchronizationRootReferences(
session).contains(dstIdRef)) {
return false;
}
return true;
}
protected boolean handleLifeCycleTransition(DocumentEventContext ctx)
throws ClientException {
String transition = (String) ctx.getProperty(LifeCycleConstants.TRANSTION_EVENT_OPTION_TRANSITION);
// Interested in 'deleted' life cycle transition only
return transition != null
&& LifeCycleConstants.DELETE_TRANSITION.equals(transition);
}
protected boolean handleAboutToRemove(DocumentModel doc)
throws ClientException {
// Document deletion of document that are already in deleted
// state should not be marked as FS deletion to avoid duplicates
return !LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState());
}
protected void logDeletionEvent(DocumentModel doc, Principal principal,
String impactedUserName) throws ClientException {
AuditLogger logger = Framework.getLocalService(AuditLogger.class);
if (logger == null) {
// The log is not deployed (probably in unittest)
return;
}
FileSystemItem fsItem = null;
try {
fsItem = Framework.getLocalService(
FileSystemItemAdapterService.class).getFileSystemItem(doc,
true);
} catch (RootlessItemException e) {
// can happen when deleting a folder under and unregistered root:
// nothing to do
return;
}
if (fsItem == null) {
return;
}
LogEntry entry = logger.newLogEntry();
entry.setEventId(NuxeoDriveEvents.DELETED_EVENT);
// XXX: shall we use the server local for the event date or UTC?
entry.setEventDate(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
entry.setCategory((String) NuxeoDriveEvents.EVENT_CATEGORY);
entry.setDocUUID(doc.getId());
entry.setDocPath(doc.getPathAsString());
entry.setPrincipalName(principal.getName());
entry.setDocType(doc.getType());
entry.setRepositoryId(doc.getRepositoryName());
entry.setDocLifeCycle(doc.getCurrentLifeCycleState());
Map<String, ExtendedInfo> extendedInfos = new HashMap<String, ExtendedInfo>();
if (impactedUserName != null) {
extendedInfos.put("impactedUserName",
logger.newExtendedInfo(impactedUserName));
}
// We do not serialize the whole object as it's too big to fit in a
// StringInfo column and
extendedInfos.put("fileSystemItemId",
logger.newExtendedInfo(fsItem.getId()));
extendedInfos.put("fileSystemItemName",
logger.newExtendedInfo(fsItem.getName()));
entry.setExtendedInfos(extendedInfos);
logger.addLogEntries(Collections.singletonList(entry));
}
}
| nuxeo-drive-server/nuxeo-drive-core/src/main/java/org/nuxeo/drive/listener/NuxeoDriveFileSystemDeletionListener.java | /*
* (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Olivier Grisel <[email protected]>
*/
package org.nuxeo.drive.listener;
import java.security.Principal;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import org.nuxeo.drive.adapter.FileSystemItem;
import org.nuxeo.drive.adapter.RootlessItemException;
import org.nuxeo.drive.service.FileSystemItemAdapterService;
import org.nuxeo.drive.service.NuxeoDriveEvents;
import org.nuxeo.drive.service.NuxeoDriveManager;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.LifeCycleConstants;
import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
import org.nuxeo.ecm.core.api.event.CoreEventConstants;
import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventListener;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
import org.nuxeo.ecm.platform.audit.api.AuditLogger;
import org.nuxeo.ecm.platform.audit.api.ExtendedInfo;
import org.nuxeo.ecm.platform.audit.api.LogEntry;
import org.nuxeo.runtime.api.Framework;
/**
* Event listener to track events that should be mapped to file system item
* deletions in the the ChangeSummary computation.
*
* In particular this includes
*
* <li>Synchronization root unregistration (user specific)</li>
*
* <li>Simple document or root document lifecycle change to the 'deleted' state</li>
*
* <li>Simple document or root physical removal from the directory.</li>
*/
public class NuxeoDriveFileSystemDeletionListener implements EventListener {
@Override
public void handleEvent(Event event) throws ClientException {
DocumentEventContext ctx;
if (event.getContext() instanceof DocumentEventContext) {
ctx = (DocumentEventContext) event.getContext();
} else {
// Not interested in events that are not related to documents
return;
}
DocumentModel doc = ctx.getSourceDocument();
DocumentModel docForLogEntry = doc;
if (DocumentEventTypes.BEFORE_DOC_UPDATE.equals(event.getName())) {
docForLogEntry = handleBeforeDocUpdate(ctx, doc);
if (docForLogEntry == null) {
return;
}
}
if (DocumentEventTypes.ABOUT_TO_MOVE.equals(event.getName())
&& !handleAboutToMove(ctx, doc)) {
return;
}
if (LifeCycleConstants.TRANSITION_EVENT.equals(event.getName())
&& !handleLifeCycleTransition(ctx)) {
return;
}
if (DocumentEventTypes.ABOUT_TO_REMOVE.equals(event.getName())
&& !handleAboutToRemove(doc)) {
return;
}
// Some events will only impact a specific user (e.g. root
// unregistration)
String impactedUserName = (String) ctx.getProperty(NuxeoDriveEvents.IMPACTED_USERNAME_PROPERTY);
logDeletionEvent(docForLogEntry, ctx.getPrincipal(), impactedUserName);
}
protected DocumentModel handleBeforeDocUpdate(DocumentEventContext ctx,
DocumentModel doc) throws ClientException {
// Interested in update of a BlobHolder whose blob has been removed
boolean blobRemoved = false;
DocumentModel previousDoc = (DocumentModel) ctx.getProperty(CoreEventConstants.PREVIOUS_DOCUMENT_MODEL);
if (previousDoc != null) {
BlobHolder previousBh = previousDoc.getAdapter(BlobHolder.class);
if (previousBh != null) {
BlobHolder bh = doc.getAdapter(BlobHolder.class);
if (bh != null) {
blobRemoved = previousBh.getBlob() != null
&& bh.getBlob() == null;
}
}
}
if (blobRemoved) {
// Use previous doc holding a Blob for it to be adaptable as a
// FileSystemItem
return previousDoc;
} else {
return null;
}
}
protected boolean handleAboutToMove(DocumentEventContext ctx,
DocumentModel doc) throws ClientException {
// Interested in a move from a synchronization root to a non
// synchronized container
DocumentRef dstRef = (DocumentRef) ctx.getProperty(CoreEventConstants.DESTINATION_REF);
if (dstRef == null) {
return false;
}
CoreSession session = doc.getCoreSession();
IdRef dstIdRef;
if (dstRef instanceof IdRef) {
dstIdRef = (IdRef) dstRef;
} else {
DocumentModel dstDoc = session.getDocument(dstRef);
dstIdRef = new IdRef(dstDoc.getId());
}
if (Framework.getLocalService(NuxeoDriveManager.class).getSynchronizationRootReferences(
session).contains(dstIdRef)) {
return false;
}
return true;
}
protected boolean handleLifeCycleTransition(DocumentEventContext ctx)
throws ClientException {
String transition = (String) ctx.getProperty(LifeCycleConstants.TRANSTION_EVENT_OPTION_TRANSITION);
// Interested in 'deleted' life cycle transition only
return transition != null
&& LifeCycleConstants.DELETE_TRANSITION.equals(transition);
}
protected boolean handleAboutToRemove(DocumentModel doc)
throws ClientException {
// Document deletion of document that are already in deleted
// state should not be marked as FS deletion to avoid duplicates
return !LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState());
}
protected void logDeletionEvent(DocumentModel doc, Principal principal,
String impactedUserName) throws ClientException {
AuditLogger logger = Framework.getLocalService(AuditLogger.class);
if (logger == null) {
// The log is not deployed (probably in unittest)
return;
}
FileSystemItem fsItem = null;
try {
fsItem = Framework.getLocalService(
FileSystemItemAdapterService.class).getFileSystemItem(doc,
true);
} catch (RootlessItemException e) {
// can happen when deleting a folder under and unregistered root:
// nothing to do
return;
}
if (fsItem == null) {
return;
}
LogEntry entry = logger.newLogEntry();
entry.setEventId(NuxeoDriveEvents.DELETED_EVENT);
// XXX: shall we use the server local for the event date or UTC?
entry.setEventDate(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
entry.setCategory((String) NuxeoDriveEvents.EVENT_CATEGORY);
entry.setDocUUID(doc.getId());
entry.setDocPath(doc.getPathAsString());
entry.setPrincipalName(principal.getName());
entry.setDocType(doc.getType());
entry.setRepositoryId(doc.getRepositoryName());
entry.setDocLifeCycle(doc.getCurrentLifeCycleState());
Map<String, ExtendedInfo> extendedInfos = new HashMap<String, ExtendedInfo>();
if (impactedUserName != null) {
extendedInfos.put("impactedUserName",
logger.newExtendedInfo(impactedUserName));
}
// We do not serialize the whole object as it's too big to fit in a
// StringInfo column and
extendedInfos.put("fileSystemItemId",
logger.newExtendedInfo(fsItem.getId()));
extendedInfos.put("fileSystemItemName",
logger.newExtendedInfo(fsItem.getName()));
entry.setExtendedInfos(extendedInfos);
logger.addLogEntries(Collections.singletonList(entry));
}
}
| Make NuxeoDriveFileSystemDeletionListener ignore system documents
| nuxeo-drive-server/nuxeo-drive-core/src/main/java/org/nuxeo/drive/listener/NuxeoDriveFileSystemDeletionListener.java | Make NuxeoDriveFileSystemDeletionListener ignore system documents | <ide><path>uxeo-drive-server/nuxeo-drive-core/src/main/java/org/nuxeo/drive/listener/NuxeoDriveFileSystemDeletionListener.java
<ide> import org.nuxeo.ecm.core.event.Event;
<ide> import org.nuxeo.ecm.core.event.EventListener;
<ide> import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
<add>import org.nuxeo.ecm.core.schema.FacetNames;
<ide> import org.nuxeo.ecm.platform.audit.api.AuditLogger;
<ide> import org.nuxeo.ecm.platform.audit.api.ExtendedInfo;
<ide> import org.nuxeo.ecm.platform.audit.api.LogEntry;
<ide> return;
<ide> }
<ide> DocumentModel doc = ctx.getSourceDocument();
<add> if (doc.hasFacet(FacetNames.SYSTEM_DOCUMENT)) {
<add> // Not interested in system documents
<add> return;
<add> }
<ide> DocumentModel docForLogEntry = doc;
<ide> if (DocumentEventTypes.BEFORE_DOC_UPDATE.equals(event.getName())) {
<ide> docForLogEntry = handleBeforeDocUpdate(ctx, doc); |
|
Java | agpl-3.0 | bdc393711771298f0d620ba6cbba888da97f8156 | 0 | dzhw/metadatamanagement,dzhw/metadatamanagement,dzhw/metadatamanagement,dzhw/metadatamanagement,dzhw/metadatamanagement | package eu.dzhw.fdz.metadatamanagement.projectmanagement.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.domain.DataSet;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.domain.SubDataSet;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.repository.DataSetRepository;
import eu.dzhw.fdz.metadatamanagement.instrumentmanagement.domain.Instrument;
import eu.dzhw.fdz.metadatamanagement.instrumentmanagement.repository.InstrumentRepository;
import eu.dzhw.fdz.metadatamanagement.projectmanagement.rest.dto.PostValidationMessageDto;
import eu.dzhw.fdz.metadatamanagement.questionmanagement.domain.Question;
import eu.dzhw.fdz.metadatamanagement.questionmanagement.repository.QuestionRepository;
import eu.dzhw.fdz.metadatamanagement.questionmanagement.service.QuestionImageService;
import eu.dzhw.fdz.metadatamanagement.studymanagement.domain.Study;
import eu.dzhw.fdz.metadatamanagement.studymanagement.repository.StudyRepository;
import eu.dzhw.fdz.metadatamanagement.surveymanagement.repository.SurveyRepository;
import eu.dzhw.fdz.metadatamanagement.variablemanagement.domain.Variable;
import eu.dzhw.fdz.metadatamanagement.variablemanagement.repository.VariableRepository;
/**
* This service handels the post-validation of projects. It checks the foreign keys and references
* between different domain objects. If a foreign key or reference is not valid, the service adds a
* error message to a list. If everthing is checked, the service returns a list with all errors.
*
* @author Daniel Katzberg
*
*/
@Service
public class PostValidationService {
/* Repositories for loading data from the repository */
@Inject
private VariableRepository variableRepository;
@Inject
private SurveyRepository surveyRepository;
@Inject
private DataSetRepository dataSetRepository;
@Inject
private InstrumentRepository instrumentRepository;
@Inject
private QuestionRepository questionRepository;
@Inject
private StudyRepository studyRepository;
@Inject
private QuestionImageService questionImageService;
/**
* This method handels the complete post validation of a project.
*
* @param dataAcquisitionProjectId The id of the data acquisition project id.
* @return a list of all post validation errors.
*/
public List<PostValidationMessageDto> postValidate(String dataAcquisitionProjectId) {
List<PostValidationMessageDto> errors = new ArrayList<>();
//Check Study
Study study =
this.studyRepository.findOneByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateStudies(study, errors);
// Check questions
List<Question> questions =
this.questionRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateQuestions(questions, errors);
// check data sets
List<DataSet> dataSets =
this.dataSetRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateDataSets(dataSets, errors);
// check variables
List<Variable> variables =
this.variableRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateVariables(variables, errors);
// check instruments
List<Instrument> instruments =
this.instrumentRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateInstruments(instruments, errors);
// check that there is a study for the project (all other domain objects might link to it)
if (studyRepository.findOne(dataAcquisitionProjectId) == null) {
String[] information = {dataAcquisitionProjectId, dataAcquisitionProjectId};
errors.add(new PostValidationMessageDto("data-acquisition-project-management.error."
+ "post-validation.project-has-no-study", Arrays.asList(information)));
}
return errors;
}
/**
* This method checks all potential issues for study by post-validation.
* @param studies All studies of a project.
* @param errors The list of known errors.
* @return The updated list of errors.
*/
private List<PostValidationMessageDto> postValidateStudies(Study study,
List<PostValidationMessageDto> errors) {
//Check all AccessWays (if there some saved)
if (study != null && study.getAccessWays().size() > 0) {
List<DataSet> dataSets =
this.dataSetRepository.findByDataAcquisitionProjectId(study.getId());
boolean found = false;
for (String accessWay : study.getAccessWays()) {
found = false; //Next Accessway is found yet
dataSetLoop: for (DataSet dataSet : dataSets) {
for (SubDataSet subDataSet : dataSet.getSubDataSets()) {
if (subDataSet.getAccessWay().equals(accessWay)) {
found = true;
break dataSetLoop;
}
} //END FOR SUBDATASET
} //END FOR DATASET
//check if no AccessWay was found.
if (!found) {
String[] information = {study.getId(), accessWay};
errors.add(new PostValidationMessageDto("study-management.error.post-validation."
+ "study-has-an-accessway-which-was-not-found-in-"
+ "sub-data-sets", Arrays.asList(information)));
}
} // END FOR ACCESSWAY
}
return errors;
}
/**
* This method checks all foreign keys and references within questions to other domain
* objects.
*
* @return a list of errors of the post validation of questions.
*/
private List<PostValidationMessageDto> postValidateQuestions(
List<Question> questions, List<PostValidationMessageDto> errors) {
for (Question question : questions) {
// question.instrumentId: there must be a instrument with that id
if (this.instrumentRepository.findOne(question.getInstrumentId()) == null) {
String[] information = {question.getId(), question.getInstrumentId()};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-invalid-instrument-id", Arrays.asList(information)));
}
// question.surveyId: there must be a survey with that id
if (this.surveyRepository.findOne(question.getSurveyId()) == null) {
String[] information = {question.getId(), question.getSurveyId()};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-invalid-survey-id", Arrays.asList(information)));
}
// question.successors: there must be a question with that id
if (question.getSuccessors() != null && !question.getSuccessors().isEmpty()) {
for (String successor : question.getSuccessors()) {
if (questionRepository.findOne(successor) == null) {
String[] information = {question.getId(), successor};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-invalid-successor", Arrays.asList(information)));
}
}
}
//check the image for question
if (this.questionImageService.findQuestionImage(question.getId()) == null) {
String[] information = {question.getId()};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-no-image", Arrays.asList(information)));
}
}
return errors;
}
/**
* This method checks all foreign keys and references within data sets to other domain objects.
*
* @return a list of errors of the post validation of data sets.
*/
private List<PostValidationMessageDto> postValidateDataSets(List<DataSet> dataSets,
List<PostValidationMessageDto> errors) {
for (DataSet dataSet : dataSets) {
// dataSet.SurveyIds: there must be a survey with that id
for (String surveyId : dataSet.getSurveyIds()) {
if (this.surveyRepository.findOne(surveyId) == null) {
String[] information = {dataSet.getId(), surveyId};
errors.add(new PostValidationMessageDto("data-set-management.error."
+ "post-validation.data-set-has-invalid-survey-id", Arrays.asList(information)));
}
}
// dataSet.VariableIds: there must be a variable with that id
for (String variableId : dataSet.getVariableIds()) {
if (this.variableRepository.findOne(variableId) == null) {
String[] information = {dataSet.getId(), variableId};
errors.add(new PostValidationMessageDto("data-set-management.error."
+ "post-validation.data-set-has-invalid-variable-id", Arrays.asList(information)));
}
}
//check if all access ways of all sub dataset are in the study list of accessways.
Study study = this.studyRepository
.findOneByDataAcquisitionProjectId(dataSet.getDataAcquisitionProjectId());
if (study != null) {
for (SubDataSet subDataSet : dataSet.getSubDataSets()) {
if (!study.getAccessWays().contains(subDataSet.getAccessWay())) {
String[] information = {subDataSet.getName(), subDataSet.getAccessWay()};
errors.add(new PostValidationMessageDto("data-set-management.error.post-validation."
+ "sub-data-set-has-an-accessway-which-was-not-found-in-"
+ "study", Arrays.asList(information)));
}
}
}
}
return errors;
}
/**
* This method checks all foreign keys and references within instruments to other domain objects.
*
* @return a list of errors of the post validation of instruments.
*/
private List<PostValidationMessageDto> postValidateInstruments(List<Instrument> instruments,
List<PostValidationMessageDto> errors) {
for (Instrument instrument : instruments) {
// instrument.surveyId: there must be a survey with that id
if (this.surveyRepository.findOne(instrument.getSurveyId()) == null) {
String[] information = {instrument.getId(), instrument.getSurveyId()};
errors.add(new PostValidationMessageDto("instrument-management.error."
+ "post-validation.instrument-has-invalid-survey-id", Arrays.asList(information)));
}
}
return errors;
}
/**
* This method checks all foreign keys and references within variables to other domain objects.
*
* @return a list of errors of the post validation of variables.
*/
private List<PostValidationMessageDto> postValidateVariables(List<Variable> variables,
List<PostValidationMessageDto> errors) {
for (Variable variable : variables) {
// variable.SurveyId: there must be a survey with that id
for (String surveyId : variable.getSurveyIds()) {
if (this.surveyRepository.findOne(surveyId) == null) {
String[] information = {variable.getId(), surveyId};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-has-invalid-survey-id", Arrays.asList(information)));
}
}
// variable.SameVariablesInPanel: there must be a variable with that id
if (variable.getSameVariablesInPanel() != null) {
for (String variableId : variable.getSameVariablesInPanel()) {
if (this.variableRepository.findOne(variableId) == null) {
String[] information = {variable.getId(), variableId};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-id-is-not-in-invalid-variables-panel",
Arrays.asList(information)));
}
}
}
// variable.questionId: If there is no genereationDetail every variable needs a
// questionId (and vice versa)
if (variable.getQuestionId() != null
&& this.questionRepository.findOne(variable.getQuestionId()) == null) {
String[] information = {variable.getId(), variable.getQuestionId()};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-has-invalid-question-id", Arrays.asList(information)));
}
//variable.relatedVariables: Check for variable ids
if (variable.getRelatedVariables() != null) {
for (String variableId : variable.getRelatedVariables()) {
if (this.variableRepository.findOne(variableId) == null) {
String[] information = {variable.getId(), variableId};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-id-is-not-valid-in-related-variables",
Arrays.asList(information)));
}
}
}
}
return errors;
}
}
| src/main/java/eu/dzhw/fdz/metadatamanagement/projectmanagement/service/PostValidationService.java | package eu.dzhw.fdz.metadatamanagement.projectmanagement.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.domain.DataSet;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.domain.SubDataSet;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.repository.DataSetRepository;
import eu.dzhw.fdz.metadatamanagement.instrumentmanagement.domain.Instrument;
import eu.dzhw.fdz.metadatamanagement.instrumentmanagement.repository.InstrumentRepository;
import eu.dzhw.fdz.metadatamanagement.projectmanagement.rest.dto.PostValidationMessageDto;
import eu.dzhw.fdz.metadatamanagement.questionmanagement.domain.Question;
import eu.dzhw.fdz.metadatamanagement.questionmanagement.repository.QuestionRepository;
import eu.dzhw.fdz.metadatamanagement.questionmanagement.service.QuestionImageService;
import eu.dzhw.fdz.metadatamanagement.studymanagement.domain.Study;
import eu.dzhw.fdz.metadatamanagement.studymanagement.repository.StudyRepository;
import eu.dzhw.fdz.metadatamanagement.surveymanagement.repository.SurveyRepository;
import eu.dzhw.fdz.metadatamanagement.variablemanagement.domain.Variable;
import eu.dzhw.fdz.metadatamanagement.variablemanagement.repository.VariableRepository;
/**
* This service handels the post-validation of projects. It checks the foreign keys and references
* between different domain objects. If a foreign key or reference is not valid, the service adds a
* error message to a list. If everthing is checked, the service returns a list with all errors.
*
* @author Daniel Katzberg
*
*/
@Service
public class PostValidationService {
/* Repositories for loading data from the repository */
@Inject
private VariableRepository variableRepository;
@Inject
private SurveyRepository surveyRepository;
@Inject
private DataSetRepository dataSetRepository;
@Inject
private InstrumentRepository instrumentRepository;
@Inject
private QuestionRepository questionRepository;
@Inject
private StudyRepository studyRepository;
@Inject
private QuestionImageService questionImageService;
/**
* This method handels the complete post validation of a project.
*
* @param dataAcquisitionProjectId The id of the data acquisition project id.
* @return a list of all post validation errors.
*/
public List<PostValidationMessageDto> postValidate(String dataAcquisitionProjectId) {
List<PostValidationMessageDto> errors = new ArrayList<>();
//Check Study
Study study =
this.studyRepository.findOneByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateStudies(study, errors);
// Check questions
List<Question> questions =
this.questionRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateQuestions(questions, errors);
// check data sets
List<DataSet> dataSets =
this.dataSetRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateDataSets(dataSets, errors);
// check variables
List<Variable> variables =
this.variableRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateVariables(variables, errors);
// check instruments
List<Instrument> instruments =
this.instrumentRepository.findByDataAcquisitionProjectId(dataAcquisitionProjectId);
errors = this.postValidateInstruments(instruments, errors);
// check that there is a study for the project (all other domain objects might link to it)
if (studyRepository.findOne(dataAcquisitionProjectId) == null) {
String[] information = {dataAcquisitionProjectId, dataAcquisitionProjectId};
errors.add(new PostValidationMessageDto("data-acquisition-project-management.error."
+ "post-validation.project-has-no-study", Arrays.asList(information)));
}
return errors;
}
/**
* This method checks all potential issues for study by post-validation.
* @param studies All studies of a project.
* @param errors The list of known errors.
* @return The updated list of errors.
*/
private List<PostValidationMessageDto> postValidateStudies(Study study,
List<PostValidationMessageDto> errors) {
//Check all AccessWays (if there some saved)
if (study != null && study.getAccessWays().size() > 0) {
List<DataSet> dataSets =
this.dataSetRepository.findByDataAcquisitionProjectId(study.getId());
boolean found = false;
for (String accessWay : study.getAccessWays()) {
found = false; //Next Accessway is found yet
dataSetLoop: for (DataSet dataSet : dataSets) {
for (SubDataSet subDataSet : dataSet.getSubDataSets()) {
if (subDataSet.getAccessWay().equals(accessWay)) {
found = true;
break dataSetLoop;
}
} //END FOR SUBDATASET
} //END FOR DATASET
//check if no AccessWay was found.
if (!found) {
String[] information = {study.getId(), accessWay};
errors.add(new PostValidationMessageDto("study-management.error.post-validation."
+ "study-has-an-accessway-which-was-not-found-in-"
+ "sub-data-sets", Arrays.asList(information)));
}
} // END FOR ACCESSWAY
}
return errors;
}
/**
* This method checks all foreign keys and references within questions to other domain
* objects.
*
* @return a list of errors of the post validation of questions.
*/
private List<PostValidationMessageDto> postValidateQuestions(
List<Question> questions, List<PostValidationMessageDto> errors) {
for (Question question : questions) {
// question.instrumentId: there must be a instrument with that id
if (this.instrumentRepository.findOne(question.getInstrumentId()) == null) {
String[] information = {question.getId(), question.getInstrumentId()};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-invalid-instrument-id", Arrays.asList(information)));
}
// question.surveyId: there must be a survey with that id
if (this.surveyRepository.findOne(question.getSurveyId()) == null) {
String[] information = {question.getId(), question.getSurveyId()};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-invalid-survey-id", Arrays.asList(information)));
}
// question.successors: there must be a question with that id
if (question.getSuccessors() != null && !question.getSuccessors().isEmpty()) {
for (String successor : question.getSuccessors()) {
if (questionRepository.findOne(successor) == null) {
String[] information = {question.getId(), successor};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-invalid-successor", Arrays.asList(information)));
}
}
}
//check the image for question
if (this.questionImageService.findQuestionImage(question.getId()) == null) {
String[] information = {question.getId()};
errors.add(new PostValidationMessageDto("question-management.error."
+ "post-validation.question-has-no-image", Arrays.asList(information)));
}
}
return errors;
}
/**
* This method checks all foreign keys and references within data sets to other domain objects.
*
* @return a list of errors of the post validation of data sets.
*/
private List<PostValidationMessageDto> postValidateDataSets(List<DataSet> dataSets,
List<PostValidationMessageDto> errors) {
for (DataSet dataSet : dataSets) {
// dataSet.SurveyIds: there must be a survey with that id
for (String surveyId : dataSet.getSurveyIds()) {
if (this.surveyRepository.findOne(surveyId) == null) {
String[] information = {dataSet.getId(), surveyId};
errors.add(new PostValidationMessageDto("data-set-management.error."
+ "post-validation.data-set-has-invalid-survey-id", Arrays.asList(information)));
}
}
// dataSet.VariableIds: there must be a variable with that id
for (String variableId : dataSet.getVariableIds()) {
if (this.variableRepository.findOne(variableId) == null) {
String[] information = {dataSet.getId(), variableId};
errors.add(new PostValidationMessageDto("data-set-management.error."
+ "post-validation.data-set-has-invalid-variable-id", Arrays.asList(information)));
}
}
//check if all access ways of all sub dataset are in the study list of accessways.
Study study = this.studyRepository
.findOneByDataAcquisitionProjectId(dataSet.getDataAcquisitionProjectId());
if (study != null) {
for (SubDataSet subDataSet : dataSet.getSubDataSets()) {
if (!study.getAccessWays().contains(subDataSet.getAccessWay())) {
String[] information = {subDataSet.getName(), subDataSet.getAccessWay()};
errors.add(new PostValidationMessageDto("data-set-management.error.post-validation."
+ "sub-data-set-has-an-accessway-which-was-not-found-in-"
+ "study", Arrays.asList(information)));
}
}
}
}
return errors;
}
/**
* This method checks all foreign keys and references within instruments to other domain objects.
*
* @return a list of errors of the post validation of instruments.
*/
private List<PostValidationMessageDto> postValidateInstruments(List<Instrument> instruments,
List<PostValidationMessageDto> errors) {
for (Instrument instrument : instruments) {
// instrument.surveyId: there must be a survey with that id
if (this.surveyRepository.findOne(instrument.getSurveyId()) == null) {
String[] information = {instrument.getId(), instrument.getSurveyId()};
errors.add(new PostValidationMessageDto("instrument-management.error."
+ "post-validation.instrument-has-invalid-survey-id", Arrays.asList(information)));
}
}
return errors;
}
/**
* This method checks all foreign keys and references within variables to other domain objects.
*
* @return a list of errors of the post validation of variables.
*/
private List<PostValidationMessageDto> postValidateVariables(List<Variable> variables,
List<PostValidationMessageDto> errors) {
for (Variable variable : variables) {
// variable.SurveyId: there must be a survey with that id
for (String surveyId : variable.getSurveyIds()) {
if (this.surveyRepository.findOne(surveyId) == null) {
String[] information = {variable.getId(), surveyId};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-has-invalid-survey-id", Arrays.asList(information)));
}
}
// variable.SameVariablesInPanel: there must be a variable with that id
if (variable.getSameVariablesInPanel() != null) {
for (String variableId : variable.getSameVariablesInPanel()) {
if (this.variableRepository.findOne(variableId) == null) {
String[] information = {variable.getId(), variableId};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-id-is-not-in-invalid-variables-panel",
Arrays.asList(information)));
}
}
}
// variable.questionId: If there is no genereationDetail every variable needs a
// questionId (and vice versa)
if (variable.getQuestionId() != null
&& this.questionRepository.findOne(variable.getQuestionId()) == null) {
String[] information = {variable.getId(), variable.getQuestionId()};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-has-invalid-question-id", Arrays.asList(information)));
}
if (variable.getRelatedVariables() != null) {
for (String variableId : variable.getRelatedVariables()) {
if (this.variableRepository.findOne(variableId) == null) {
String[] information = {variable.getId(), variableId};
errors.add(new PostValidationMessageDto("variable-management.error."
+ "post-validation.variable-id-is-not-valid-in-related-variables",
Arrays.asList(information)));
}
}
}
}
return errors;
}
}
| #841 updated comments
| src/main/java/eu/dzhw/fdz/metadatamanagement/projectmanagement/service/PostValidationService.java | #841 updated comments | <ide><path>rc/main/java/eu/dzhw/fdz/metadatamanagement/projectmanagement/service/PostValidationService.java
<ide> + "post-validation.variable-has-invalid-question-id", Arrays.asList(information)));
<ide> }
<ide>
<del>
<add> //variable.relatedVariables: Check for variable ids
<ide> if (variable.getRelatedVariables() != null) {
<ide> for (String variableId : variable.getRelatedVariables()) {
<ide> if (this.variableRepository.findOne(variableId) == null) { |
|
JavaScript | mit | b93cb0477b7dc70f22a52b8abb314f6d84788fe2 | 0 | Raynos/distributed | var MessageStream = require("message-stream")
var net = require("net")
var argv = require("optimist").argv
var EventEmitter = require("events").EventEmitter
var port = argv.port || 2503
var myIp = require("my-local-ip")()
var id = id + ":" + port
var host = argv.host || myIp
var name = argv.name || "Anonymous"
function Messages() {
var messages = new EventEmitter()
messages.send = function (text) {
messages.emit("message", {
text: text,
name: name,
id: id,
time: Date.now()
})
}
messages.receive = function (message, source) {
console.log(message.name + " > " + message.text)
messages.emit("message", message, source)
}
messages.createStream = function () {
var stream = MessageStream(function (message) {
messages.receive(message, stream)
})
messages.on("message", function (message, source) {
if (source !== stream) {
stream.queue(message)
}
})
return stream
}
return messages
}
var messages = Messages()
process.stdin.on("data", function (text) {
messages.send(String(text))
})
if (argv.server) {
var server = net.createServer(function (stream) {
stream.pipe(messages.createStream()).pipe(stream)
})
server.listen(port)
console.log("Started server on port", port)
} else {
var client = net.connect(port, host)
client.pipe(messages.createStream()).pipe(client)
console.log("Connected to server on port", port)
}
| 1-basic-chat.js | var MessageStream = require("message-stream")
var net = require("net")
var argv = require("optimist").argv
var EventEmitter = require("events").EventEmitter
var port = argv.port || 2503
var id = require("my-local-ip")() + ":" + port
var name = argv.name || "Anonymous"
function Messages() {
var messages = new EventEmitter()
messages.send = function (text) {
messages.emit("message", {
text: text,
name: name,
id: id,
time: Date.now()
})
}
messages.receive = function (message, source) {
console.log(message.name + " > " + message.text)
messages.emit("message", message, source)
}
messages.createStream = function () {
var stream = MessageStream(function (message) {
messages.receive(message, stream)
})
messages.on("message", function (message, source) {
if (source !== stream) {
stream.queue(message)
}
})
return stream
}
return messages
}
var messages = Messages()
process.stdin.on("data", function (text) {
messages.send(String(text))
})
if (argv.server) {
var server = net.createServer(function (stream) {
stream.pipe(messages.createStream()).pipe(stream)
})
server.listen(port)
console.log("Started server on port", port)
} else {
var client = net.connect(port)
client.pipe(messages.createStream()).pipe(client)
console.log("Connected to server on port", port)
}
| make host an option
| 1-basic-chat.js | make host an option | <ide><path>-basic-chat.js
<ide> var EventEmitter = require("events").EventEmitter
<ide>
<ide> var port = argv.port || 2503
<del>var id = require("my-local-ip")() + ":" + port
<add>var myIp = require("my-local-ip")()
<add>var id = id + ":" + port
<add>var host = argv.host || myIp
<ide>
<ide> var name = argv.name || "Anonymous"
<ide>
<ide> server.listen(port)
<ide> console.log("Started server on port", port)
<ide> } else {
<del> var client = net.connect(port)
<add> var client = net.connect(port, host)
<ide>
<ide> client.pipe(messages.createStream()).pipe(client)
<ide> console.log("Connected to server on port", port) |
|
Java | agpl-3.0 | 8597f141eeeb816dfde0372820cde4022e2edb86 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 4d862c2e-2e62-11e5-9284-b827eb9e62be | hello.java | 4d80911a-2e62-11e5-9284-b827eb9e62be | 4d862c2e-2e62-11e5-9284-b827eb9e62be | hello.java | 4d862c2e-2e62-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>4d80911a-2e62-11e5-9284-b827eb9e62be
<add>4d862c2e-2e62-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 0bcfc7f50e918a6b74496d580597df37b16fe0c3 | 0 | AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx | /*
* Copyright (C) 2012 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 android.support.v4.app;
import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.annotation.RestrictTo;
import android.support.v4.view.GravityCompat;
import android.view.Gravity;
import android.widget.RemoteViews;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Helper for accessing features in {@link android.app.Notification}
* introduced after API level 4 in a backwards compatible fashion.
*/
public class NotificationCompat {
/**
* Use all default values (where applicable).
*/
public static final int DEFAULT_ALL = ~0;
/**
* Use the default notification sound. This will ignore any sound set using
* {@link Builder#setSound}
*
* <p>
* A notification that is noisy is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_SOUND = 1;
/**
* Use the default notification vibrate. This will ignore any vibrate set using
* {@link Builder#setVibrate}. Using phone vibration requires the
* {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
*
* <p>
* A notification that vibrates is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_VIBRATE = 2;
/**
* Use the default notification lights. This will ignore the
* {@link #FLAG_SHOW_LIGHTS} bit, and values set with {@link Builder#setLights}.
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_LIGHTS = 4;
/**
* Use this constant as the value for audioStreamType to request that
* the default stream type for notifications be used. Currently the
* default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
*/
public static final int STREAM_DEFAULT = -1;
/**
* Bit set in the Notification flags field when LEDs should be turned on
* for this notification.
*/
public static final int FLAG_SHOW_LIGHTS = 0x00000001;
/**
* Bit set in the Notification flags field if this notification is in
* reference to something that is ongoing, like a phone call. It should
* not be set if this notification is in reference to something that
* happened at a particular point in time, like a missed phone call.
*/
public static final int FLAG_ONGOING_EVENT = 0x00000002;
/**
* Bit set in the Notification flags field if
* the audio will be repeated until the notification is
* cancelled or the notification window is opened.
*/
public static final int FLAG_INSISTENT = 0x00000004;
/**
* Bit set in the Notification flags field if the notification's sound,
* vibrate and ticker should only be played if the notification is not already showing.
*/
public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008;
/**
* Bit set in the Notification flags field if the notification should be canceled when
* it is clicked by the user.
*/
public static final int FLAG_AUTO_CANCEL = 0x00000010;
/**
* Bit set in the Notification flags field if the notification should not be canceled
* when the user clicks the Clear all button.
*/
public static final int FLAG_NO_CLEAR = 0x00000020;
/**
* Bit set in the Notification flags field if this notification represents a currently
* running service. This will normally be set for you by
* {@link android.app.Service#startForeground}.
*/
public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
/**
* Obsolete flag indicating high-priority notifications; use the priority field instead.
*
* @deprecated Use {@link NotificationCompat.Builder#setPriority(int)} with a positive value.
*/
@Deprecated
public static final int FLAG_HIGH_PRIORITY = 0x00000080;
/**
* Bit set in the Notification flags field if this notification is relevant to the current
* device only and it is not recommended that it bridge to other devices.
*/
public static final int FLAG_LOCAL_ONLY = 0x00000100;
/**
* Bit set in the Notification flags field if this notification is the group summary for a
* group of notifications. Grouped notifications may display in a cluster or stack on devices
* which support such rendering. Requires a group key also be set using
* {@link Builder#setGroup}.
*/
public static final int FLAG_GROUP_SUMMARY = 0x00000200;
/**
* Default notification priority for {@link NotificationCompat.Builder#setPriority(int)}.
* If your application does not prioritize its own notifications,
* use this value for all notifications.
*/
public static final int PRIORITY_DEFAULT = 0;
/**
* Lower notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for items that are less important. The UI may choose to show
* these items smaller, or at a different position in the list,
* compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_LOW = -1;
/**
* Lowest notification priority for {@link NotificationCompat.Builder#setPriority(int)};
* these items might not be shown to the user except under
* special circumstances, such as detailed notification logs.
*/
public static final int PRIORITY_MIN = -2;
/**
* Higher notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for more important notifications or alerts. The UI may choose
* to show these items larger, or at a different position in
* notification lists, compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_HIGH = 1;
/**
* Highest notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for your application's most important items that require the user's
* prompt attention or input.
*/
public static final int PRIORITY_MAX = 2;
/**
* Notification extras key: this is the title of the notification,
* as supplied to {@link Builder#setContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE = "android.title";
/**
* Notification extras key: this is the title of the notification when shown in expanded form,
* e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
/**
* Notification extras key: this is the main text payload, as supplied to
* {@link Builder#setContentText(CharSequence)}.
*/
public static final String EXTRA_TEXT = "android.text";
/**
* Notification extras key: this is a third line of text, as supplied to
* {@link Builder#setSubText(CharSequence)}.
*/
public static final String EXTRA_SUB_TEXT = "android.subText";
/**
* Notification extras key: this is the remote input history, as supplied to
* {@link Builder#setRemoteInputHistory(CharSequence[])}.
*
* Apps can fill this through {@link Builder#setRemoteInputHistory(CharSequence[])}
* with the most recent inputs that have been sent through a {@link RemoteInput} of this
* Notification and are expected to clear it once the it is no longer relevant (e.g. for chat
* notifications once the other party has responded).
*
* The extra with this key is of type CharSequence[] and contains the most recent entry at
* the 0 index, the second most recent at the 1 index, etc.
*
* @see Builder#setRemoteInputHistory(CharSequence[])
*/
public static final String EXTRA_REMOTE_INPUT_HISTORY = "android.remoteInputHistory";
/**
* Notification extras key: this is a small piece of additional text as supplied to
* {@link Builder#setContentInfo(CharSequence)}.
*/
public static final String EXTRA_INFO_TEXT = "android.infoText";
/**
* Notification extras key: this is a line of summary information intended to be shown
* alongside expanded notifications, as supplied to (e.g.)
* {@link BigTextStyle#setSummaryText(CharSequence)}.
*/
public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
/**
* Notification extras key: this is the longer text shown in the big form of a
* {@link BigTextStyle} notification, as supplied to
* {@link BigTextStyle#bigText(CharSequence)}.
*/
public static final String EXTRA_BIG_TEXT = "android.bigText";
/**
* Notification extras key: this is the resource ID of the notification's main small icon, as
* supplied to {@link Builder#setSmallIcon(int)}.
*/
public static final String EXTRA_SMALL_ICON = "android.icon";
/**
* Notification extras key: this is a bitmap to be used instead of the small icon when showing the
* notification payload, as
* supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON = "android.largeIcon";
/**
* Notification extras key: this is a bitmap to be used instead of the one from
* {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
* shown in its expanded form, as supplied to
* {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
/**
* Notification extras key: this is the progress value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS = "android.progress";
/**
* Notification extras key: this is the maximum value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
/**
* Notification extras key: whether the progress bar is indeterminate, supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown as a count-up timer (specifically a {@link android.widget.Chronometer}) instead
* of a timestamp, as supplied to {@link Builder#setUsesChronometer(boolean)}.
*/
public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown, as supplied to {@link Builder#setShowWhen(boolean)}.
*/
public static final String EXTRA_SHOW_WHEN = "android.showWhen";
/**
* Notification extras key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
* notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
*/
public static final String EXTRA_PICTURE = "android.picture";
/**
* Notification extras key: An array of CharSequences to show in {@link InboxStyle} expanded
* notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
*/
public static final String EXTRA_TEXT_LINES = "android.textLines";
/**
* Notification extras key: A string representing the name of the specific
* {@link android.app.Notification.Style} used to create this notification.
*/
public static final String EXTRA_TEMPLATE = "android.template";
/**
* Notification extras key: A String array containing the people that this
* notification relates to, each of which was supplied to
* {@link Builder#addPerson(String)}.
*/
public static final String EXTRA_PEOPLE = "android.people";
/**
* Notification extras key: A
* {@link android.content.ContentUris content URI} pointing to an image that can be displayed
* in the background when the notification is selected. The URI must point to an image stream
* suitable for passing into
* {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
* BitmapFactory.decodeStream}; all other content types will be ignored. The content provider
* URI used for this purpose must require no permissions to read the image data.
*/
public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
/**
* Notification key: A
* {@link android.media.session.MediaSession.Token} associated with a
* {@link android.app.Notification.MediaStyle} notification.
*/
public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
/**
* Notification extras key: the indices of actions to be shown in the compact view,
* as supplied to (e.g.) {@link Notification.MediaStyle#setShowActionsInCompactView(int...)}.
*/
public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
/**
* Notification key: the username to be displayed for all messages sent by the user
* including
* direct replies
* {@link MessagingStyle} notification.
*/
public static final String EXTRA_SELF_DISPLAY_NAME = "android.selfDisplayName";
/**
* Notification key: a {@link String} to be displayed as the title to a conversation
* represented by a {@link MessagingStyle}
*/
public static final String EXTRA_CONVERSATION_TITLE = "android.conversationTitle";
/**
* Notification key: an array of {@link Bundle} objects representing
* {@link MessagingStyle.Message} objects for a {@link MessagingStyle} notification.
*/
public static final String EXTRA_MESSAGES = "android.messages";
/**
* Keys into the {@link #getExtras} Bundle: the audio contents of this notification.
*
* This is for use when rendering the notification on an audio-focused interface;
* the audio contents are a complete sound sample that contains the contents/body of the
* notification. This may be used in substitute of a Text-to-Speech reading of the
* notification. For example if the notification represents a voice message this should point
* to the audio of that message.
*
* The data stored under this key should be a String representation of a Uri that contains the
* audio contents in one of the following formats: WAV, PCM 16-bit, AMR-WB.
*
* This extra is unnecessary if you are using {@code MessagingStyle} since each {@code Message}
* has a field for holding data URI. That field can be used for audio.
* See {@code Message#setData}.
*
* Example usage:
* <pre>
* {@code
* NotificationCompat.Builder myBuilder = (build your Notification as normal);
* myBuilder.getExtras().putString(EXTRA_AUDIO_CONTENTS_URI, myAudioUri.toString());
* }
* </pre>
*/
public static final String EXTRA_AUDIO_CONTENTS_URI = "android.audioContents";
/**
* Value of {@link Notification#color} equal to 0 (also known as
* {@link android.graphics.Color#TRANSPARENT Color.TRANSPARENT}),
* telling the system not to decorate this notification with any special color but instead use
* default colors when presenting this notification.
*/
@ColorInt
public static final int COLOR_DEFAULT = Color.TRANSPARENT;
/** @hide */
@Retention(SOURCE)
@IntDef({VISIBILITY_PUBLIC, VISIBILITY_PRIVATE, VISIBILITY_SECRET})
public @interface NotificationVisibility {}
/**
* Notification visibility: Show this notification in its entirety on all lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PUBLIC = 1;
/**
* Notification visibility: Show this notification on all lockscreens, but conceal sensitive or
* private information on secure lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PRIVATE = 0;
/**
* Notification visibility: Do not reveal any part of this notification on a secure lockscreen.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_SECRET = -1;
/**
* Notification category: incoming call (voice or video) or similar synchronous communication request.
*/
public static final String CATEGORY_CALL = Notification.CATEGORY_CALL;
/**
* Notification category: incoming direct message (SMS, instant message, etc.).
*/
public static final String CATEGORY_MESSAGE = Notification.CATEGORY_MESSAGE;
/**
* Notification category: asynchronous bulk message (email).
*/
public static final String CATEGORY_EMAIL = Notification.CATEGORY_EMAIL;
/**
* Notification category: calendar event.
*/
public static final String CATEGORY_EVENT = Notification.CATEGORY_EVENT;
/**
* Notification category: promotion or advertisement.
*/
public static final String CATEGORY_PROMO = Notification.CATEGORY_PROMO;
/**
* Notification category: alarm or timer.
*/
public static final String CATEGORY_ALARM = Notification.CATEGORY_ALARM;
/**
* Notification category: progress of a long-running background operation.
*/
public static final String CATEGORY_PROGRESS = Notification.CATEGORY_PROGRESS;
/**
* Notification category: social network or sharing update.
*/
public static final String CATEGORY_SOCIAL = Notification.CATEGORY_SOCIAL;
/**
* Notification category: error in background operation or authentication status.
*/
public static final String CATEGORY_ERROR = Notification.CATEGORY_ERROR;
/**
* Notification category: media transport control for playback.
*/
public static final String CATEGORY_TRANSPORT = Notification.CATEGORY_TRANSPORT;
/**
* Notification category: system or device status update. Reserved for system use.
*/
public static final String CATEGORY_SYSTEM = Notification.CATEGORY_SYSTEM;
/**
* Notification category: indication of running background service.
*/
public static final String CATEGORY_SERVICE = Notification.CATEGORY_SERVICE;
/**
* Notification category: user-scheduled reminder.
*/
public static final String CATEGORY_REMINDER = Notification.CATEGORY_REMINDER;
/**
* Notification category: a specific, timely recommendation for a single thing.
* For example, a news app might want to recommend a news story it believes the user will
* want to read next.
*/
public static final String CATEGORY_RECOMMENDATION =
Notification.CATEGORY_RECOMMENDATION;
/**
* Notification category: ongoing information about device or contextual status.
*/
public static final String CATEGORY_STATUS = Notification.CATEGORY_STATUS;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@RestrictTo(LIBRARY_GROUP)
@IntDef({BADGE_ICON_NONE, BADGE_ICON_SMALL, BADGE_ICON_LARGE})
public @interface BadgeIconType {}
/**
* If this notification is being shown as a badge, always show as a number.
*/
public static final int BADGE_ICON_NONE = Notification.BADGE_ICON_NONE;
/**
* If this notification is being shown as a badge, use the icon provided to
* {@link Builder#setSmallIcon(int)} to represent this notification.
*/
public static final int BADGE_ICON_SMALL = Notification.BADGE_ICON_SMALL;
/**
* If this notification is being shown as a badge, use the icon provided to
* {@link Builder#setLargeIcon(Bitmap) to represent this notification.
*/
public static final int BADGE_ICON_LARGE = Notification.BADGE_ICON_LARGE;
/**
* Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all notifications in a
* group with sound or vibration ought to make sound or vibrate (respectively), so this
* notification will not be muted when it is in a group.
*/
public static final int GROUP_ALERT_ALL = 0;
/**
* Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all children
* notification in a group should be silenced (no sound or vibration) even if they would
* otherwise make sound or vibrate. Use this constant to mute this notification if this
* notification is a group child.
*
* <p> For example, you might want to use this constant if you post a number of children
* notifications at once (say, after a periodic sync), and only need to notify the user
* audibly once.
*/
public static final int GROUP_ALERT_SUMMARY = 1;
/**
* Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that the summary
* notification in a group should be silenced (no sound or vibration) even if they would
* otherwise make sound or vibrate. Use this constant
* to mute this notification if this notification is a group summary.
*
* <p>For example, you might want to use this constant if only the children notifications
* in your group have content and the summary is only used to visually group notifications.
*/
public static final int GROUP_ALERT_CHILDREN = 2;
static final NotificationCompatImpl IMPL;
interface NotificationCompatImpl {
Notification build(Builder b, BuilderExtender extender);
Action getAction(Notification n, int actionIndex);
Action[] getActionsFromParcelableArrayList(ArrayList<Parcelable> parcelables);
ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions);
Bundle getBundleForUnreadConversation(NotificationCompatBase.UnreadConversation uc);
NotificationCompatBase.UnreadConversation getUnreadConversationFromBundle(
Bundle b, NotificationCompatBase.UnreadConversation.Factory factory,
RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory);
}
/**
* Interface for appcompat to extend v4 builder with media style.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected static class BuilderExtender {
public Notification build(Builder b, NotificationBuilderWithBuilderAccessor builder) {
Notification n = builder.build();
if (b.mContentView != null) {
n.contentView = b.mContentView;
}
return n;
}
}
static class NotificationCompatBaseImpl implements NotificationCompatImpl {
public static class BuilderBase implements NotificationBuilderWithBuilderAccessor {
private Notification.Builder mBuilder;
BuilderBase(Context context, Notification n, CharSequence contentTitle,
CharSequence contentText, CharSequence contentInfo, RemoteViews tickerView,
int number, PendingIntent contentIntent, PendingIntent fullScreenIntent,
Bitmap largeIcon, int progressMax, int progress,
boolean progressIndeterminate) {
mBuilder = new Notification.Builder(context)
.setWhen(n.when)
.setSmallIcon(n.icon, n.iconLevel)
.setContent(n.contentView)
.setTicker(n.tickerText, tickerView)
.setSound(n.sound, n.audioStreamType)
.setVibrate(n.vibrate)
.setLights(n.ledARGB, n.ledOnMS, n.ledOffMS)
.setOngoing((n.flags & Notification.FLAG_ONGOING_EVENT) != 0)
.setOnlyAlertOnce((n.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0)
.setAutoCancel((n.flags & Notification.FLAG_AUTO_CANCEL) != 0)
.setDefaults(n.defaults)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setContentInfo(contentInfo)
.setContentIntent(contentIntent)
.setDeleteIntent(n.deleteIntent)
.setFullScreenIntent(fullScreenIntent,
(n.flags & Notification.FLAG_HIGH_PRIORITY) != 0)
.setLargeIcon(largeIcon)
.setNumber(number)
.setProgress(progressMax, progress, progressIndeterminate);
}
@Override
public Notification.Builder getBuilder() {
return mBuilder;
}
@Override
public Notification build() {
return mBuilder.getNotification();
}
}
@Override
public Notification build(Builder b, BuilderExtender extender) {
BuilderBase builder =
new BuilderBase(b.mContext, b.mNotification,
b.resolveTitle(), b.resolveText(), b.mContentInfo, b.mTickerView,
b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate);
return extender.build(b, builder);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return null;
}
@Override
public Action[] getActionsFromParcelableArrayList(ArrayList<Parcelable> parcelables) {
return null;
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions) {
return null;
}
@Override
public Bundle getBundleForUnreadConversation(NotificationCompatBase.UnreadConversation uc) {
return null;
}
@Override
public NotificationCompatBase.UnreadConversation getUnreadConversationFromBundle(
Bundle b, NotificationCompatBase.UnreadConversation.Factory factory,
RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory) {
return null;
}
}
@RequiresApi(16)
static class NotificationCompatApi16Impl extends NotificationCompatBaseImpl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatJellybean.Builder builder = new NotificationCompatJellybean.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView);
addActionsToBuilder(builder, b.mActions);
if (b.mStyle != null) {
b.mStyle.apply(builder);
}
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
Bundle extras = getExtras(notification);
if (extras != null) {
b.mStyle.addCompatExtras(extras);
}
}
return notification;
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatJellybean.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatJellybean.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatJellybean.getParcelableArrayListForActions(actions);
}
}
@RequiresApi(19)
static class NotificationCompatApi19Impl extends NotificationCompatApi16Impl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatKitKat.Builder builder = new NotificationCompatKitKat.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly,
b.mPeople, b.mExtras, b.mGroupKey, b.mGroupSummary, b.mSortKey,
b.mContentView, b.mBigContentView);
addActionsToBuilder(builder, b.mActions);
if (b.mStyle != null) {
b.mStyle.apply(builder);
}
return extender.build(b, builder);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatKitKat.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
}
@RequiresApi(20)
static class NotificationCompatApi20Impl extends NotificationCompatApi19Impl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatApi20.Builder builder = new NotificationCompatApi20.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mPeople, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
if (b.mStyle != null) {
b.mStyle.apply(builder);
}
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatApi20.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatApi20.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatApi20.getParcelableArrayListForActions(actions);
}
}
@RequiresApi(21)
static class NotificationCompatApi21Impl extends NotificationCompatApi20Impl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatApi21.Builder builder = new NotificationCompatApi21.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
b.mHeadsUpContentView, b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
if (b.mStyle != null) {
b.mStyle.apply(builder);
}
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
@Override
public Bundle getBundleForUnreadConversation(NotificationCompatBase.UnreadConversation uc) {
return NotificationCompatApi21.getBundleForUnreadConversation(uc);
}
@Override
public NotificationCompatBase.UnreadConversation getUnreadConversationFromBundle(
Bundle b, NotificationCompatBase.UnreadConversation.Factory factory,
RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory) {
return NotificationCompatApi21.getUnreadConversationFromBundle(
b, factory, remoteInputFactory);
}
}
@RequiresApi(24)
static class NotificationCompatApi24Impl extends NotificationCompatApi21Impl {
@Override
public Notification build(Builder b,
BuilderExtender extender) {
NotificationCompatApi24.Builder builder = new NotificationCompatApi24.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mRemoteInputHistory, b.mContentView,
b.mBigContentView, b.mHeadsUpContentView, b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
if (b.mStyle != null) {
b.mStyle.apply(builder);
}
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
}
@RequiresApi(26)
static class NotificationCompatApi26Impl extends NotificationCompatApi24Impl {
@Override
public Notification build(Builder b,
BuilderExtender extender) {
NotificationCompatApi26.Builder builder = new NotificationCompatApi26.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mRemoteInputHistory, b.mContentView,
b.mBigContentView, b.mHeadsUpContentView, b.mChannelId, b.mBadgeIcon,
b.mShortcutId, b.mTimeout, b.mColorized, b.mColorizedSet,
b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
if (b.mStyle != null) {
b.mStyle.apply(builder);
}
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
}
static void addActionsToBuilder(NotificationBuilderWithActions builder,
ArrayList<Action> actions) {
for (Action action : actions) {
builder.addAction(action);
}
}
static {
if (Build.VERSION.SDK_INT >= 26) {
IMPL = new NotificationCompatApi26Impl();
} else if (Build.VERSION.SDK_INT >= 24) {
IMPL = new NotificationCompatApi24Impl();
} else if (Build.VERSION.SDK_INT >= 21) {
IMPL = new NotificationCompatApi21Impl();
} else if (Build.VERSION.SDK_INT >= 20) {
IMPL = new NotificationCompatApi20Impl();
} else if (Build.VERSION.SDK_INT >= 19) {
IMPL = new NotificationCompatApi19Impl();
} else if (Build.VERSION.SDK_INT >= 16) {
IMPL = new NotificationCompatApi16Impl();
} else {
IMPL = new NotificationCompatBaseImpl();
}
}
/**
* Builder class for {@link NotificationCompat} objects. Allows easier control over
* all the flags, as well as help constructing the typical notification layouts.
* <p>
* On platform versions that don't offer expanded notifications, methods that depend on
* expanded notifications have no effect.
* </p>
* <p>
* For example, action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later.
* <p>
* For this reason, you should always ensure that UI controls in a notification are also
* available in an {@link android.app.Activity} in your app, and you should always start that
* {@link android.app.Activity} when users click the notification. To do this, use the
* {@link NotificationCompat.Builder#setContentIntent setContentIntent()}
* method.
* </p>
*
*/
public static class Builder {
/**
* Maximum length of CharSequences accepted by Builder and friends.
*
* <p>
* Avoids spamming the system with overly large strings such as full e-mails.
*/
private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024;
// All these variables are declared public/hidden so they can be accessed by a builder
// extender.
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Context mContext;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mContentTitle;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mContentText;
PendingIntent mContentIntent;
PendingIntent mFullScreenIntent;
RemoteViews mTickerView;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Bitmap mLargeIcon;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mContentInfo;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public int mNumber;
int mPriority;
boolean mShowWhen = true;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public boolean mUseChronometer;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Style mStyle;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mSubText;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence[] mRemoteInputHistory;
int mProgressMax;
int mProgress;
boolean mProgressIndeterminate;
String mGroupKey;
boolean mGroupSummary;
String mSortKey;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public ArrayList<Action> mActions = new ArrayList<Action>();
boolean mLocalOnly = false;
boolean mColorized;
boolean mColorizedSet;
String mCategory;
Bundle mExtras;
int mColor = COLOR_DEFAULT;
int mVisibility = VISIBILITY_PRIVATE;
Notification mPublicVersion;
RemoteViews mContentView;
RemoteViews mBigContentView;
RemoteViews mHeadsUpContentView;
String mChannelId;
int mBadgeIcon = BADGE_ICON_NONE;
String mShortcutId;
long mTimeout;
private int mGroupAlertBehavior = GROUP_ALERT_ALL;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Notification mNotification = new Notification();
public ArrayList<String> mPeople;
/**
* Constructor.
*
* Automatically sets the when field to {@link System#currentTimeMillis()
* System.currentTimeMillis()} and the audio stream to the
* {@link Notification#STREAM_DEFAULT}.
*
* @param context A {@link Context} that will be used to construct the
* RemoteViews. The Context will not be held past the lifetime of this
* Builder object.
* @param channelId The constructed Notification will be posted on this
* NotificationChannel.
*/
public Builder(@NonNull Context context, @NonNull String channelId) {
mContext = context;
mChannelId = channelId;
// Set defaults to match the defaults of a Notification
mNotification.when = System.currentTimeMillis();
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
mPriority = PRIORITY_DEFAULT;
mPeople = new ArrayList<String>();
}
/**
* @deprecated use
* {@link NotificationCompat.Builder#NotificationCompat.Builder(Context, String)} instead.
* All posted Notifications must specify a NotificationChannel Id.
*/
@Deprecated
public Builder(Context context) {
this(context, null);
}
/**
* Set the time that the event occurred. Notifications in the panel are
* sorted by this time.
*/
public Builder setWhen(long when) {
mNotification.when = when;
return this;
}
/**
* Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
* in the content view.
*/
public Builder setShowWhen(boolean show) {
mShowWhen = show;
return this;
}
/**
* Show the {@link Notification#when} field as a stopwatch.
*
* Instead of presenting <code>when</code> as a timestamp, the notification will show an
* automatically updating display of the minutes and seconds since <code>when</code>.
*
* Useful when showing an elapsed time (like an ongoing phone call).
*
* @see android.widget.Chronometer
* @see Notification#when
*/
public Builder setUsesChronometer(boolean b) {
mUseChronometer = b;
return this;
}
/**
* Set the small icon to use in the notification layouts. Different classes of devices
* may return different sizes. See the UX guidelines for more information on how to
* design these icons.
*
* @param icon A resource ID in the application's package of the drawable to use.
*/
public Builder setSmallIcon(int icon) {
mNotification.icon = icon;
return this;
}
/**
* A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
* level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
* LevelListDrawable}.
*
* @param icon A resource ID in the application's package of the drawable to use.
* @param level The level to use for the icon.
*
* @see android.graphics.drawable.LevelListDrawable
*/
public Builder setSmallIcon(int icon, int level) {
mNotification.icon = icon;
mNotification.iconLevel = level;
return this;
}
/**
* Set the title (first row) of the notification, in a standard notification.
*/
public Builder setContentTitle(CharSequence title) {
mContentTitle = limitCharSequenceLength(title);
return this;
}
/**
* Set the text (second row) of the notification, in a standard notification.
*/
public Builder setContentText(CharSequence text) {
mContentText = limitCharSequenceLength(text);
return this;
}
/**
* Set the third line of text in the platform notification template.
* Don't use if you're also using {@link #setProgress(int, int, boolean)};
* they occupy the same location in the standard template.
* <br>
* If the platform does not provide large-format notifications, this method has no effect.
* The third line of text only appears in expanded view.
* <br>
*/
public Builder setSubText(CharSequence text) {
mSubText = limitCharSequenceLength(text);
return this;
}
/**
* Set the remote input history.
*
* This should be set to the most recent inputs that have been sent
* through a {@link RemoteInput} of this Notification and cleared once the it is no
* longer relevant (e.g. for chat notifications once the other party has responded).
*
* The most recent input must be stored at the 0 index, the second most recent at the
* 1 index, etc. Note that the system will limit both how far back the inputs will be shown
* and how much of each individual input is shown.
*
* <p>Note: The reply text will only be shown on notifications that have least one action
* with a {@code RemoteInput}.</p>
*/
public Builder setRemoteInputHistory(CharSequence[] text) {
mRemoteInputHistory = text;
return this;
}
/**
* Set the large number at the right-hand side of the notification. This is
* equivalent to setContentInfo, although it might show the number in a different
* font size for readability.
*/
public Builder setNumber(int number) {
mNumber = number;
return this;
}
/**
* Set the large text at the right-hand side of the notification.
*/
public Builder setContentInfo(CharSequence info) {
mContentInfo = limitCharSequenceLength(info);
return this;
}
/**
* Set the progress this notification represents, which may be
* represented as a {@link android.widget.ProgressBar}.
*/
public Builder setProgress(int max, int progress, boolean indeterminate) {
mProgressMax = max;
mProgress = progress;
mProgressIndeterminate = indeterminate;
return this;
}
/**
* Supply a custom RemoteViews to use instead of the standard one.
*/
public Builder setContent(RemoteViews views) {
mNotification.contentView = views;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is clicked.
* If you do not supply an intent, you can now add PendingIntents to individual
* views to be launched when clicked by calling {@link RemoteViews#setOnClickPendingIntent
* RemoteViews.setOnClickPendingIntent(int,PendingIntent)}. Be sure to
* read {@link Notification#contentIntent Notification.contentIntent} for
* how to correctly use this.
*/
public Builder setContentIntent(PendingIntent intent) {
mContentIntent = intent;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is cleared by the user
* directly from the notification panel. For example, this intent is sent when the user
* clicks the "Clear all" button, or the individual "X" buttons on notifications. This
* intent is not sent when the application calls
* {@link android.app.NotificationManager#cancel NotificationManager.cancel(int)}.
*/
public Builder setDeleteIntent(PendingIntent intent) {
mNotification.deleteIntent = intent;
return this;
}
/**
* An intent to launch instead of posting the notification to the status bar.
* Only for use with extremely high-priority notifications demanding the user's
* <strong>immediate</strong> attention, such as an incoming phone call or
* alarm clock that the user has explicitly set to a particular time.
* If this facility is used for something else, please give the user an option
* to turn it off and use a normal notification, as this can be extremely
* disruptive.
*
* <p>
* On some platforms, the system UI may choose to display a heads-up notification,
* instead of launching this intent, while the user is using the device.
* </p>
*
* @param intent The pending intent to launch.
* @param highPriority Passing true will cause this notification to be sent
* even if other notifications are suppressed.
*/
public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
mFullScreenIntent = intent;
setFlag(FLAG_HIGH_PRIORITY, highPriority);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives.
*/
public Builder setTicker(CharSequence tickerText) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives, and also a RemoteViews object that may be displayed instead on some
* devices.
*/
public Builder setTicker(CharSequence tickerText, RemoteViews views) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
mTickerView = views;
return this;
}
/**
* Set the large icon that is shown in the ticker and notification.
*/
public Builder setLargeIcon(Bitmap icon) {
mLargeIcon = icon;
return this;
}
/**
* Set the sound to play. It will play on the default stream.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*/
public Builder setSound(Uri sound) {
mNotification.sound = sound;
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
return this;
}
/**
* Set the sound to play. It will play on the stream you supply.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see Notification#STREAM_DEFAULT
* @see AudioManager for the <code>STREAM_</code> constants.
*/
public Builder setSound(Uri sound, int streamType) {
mNotification.sound = sound;
mNotification.audioStreamType = streamType;
return this;
}
/**
* Set the vibration pattern to use.
*
* <p>
* On some platforms, a notification that vibrates is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see android.os.Vibrator for a discussion of the <code>pattern</code>
* parameter.
*/
public Builder setVibrate(long[] pattern) {
mNotification.vibrate = pattern;
return this;
}
/**
* Set the argb value that you would like the LED on the device to blink, as well as the
* rate. The rate is specified in terms of the number of milliseconds to be on
* and then the number of milliseconds to be off.
*/
public Builder setLights(@ColorInt int argb, int onMs, int offMs) {
mNotification.ledARGB = argb;
mNotification.ledOnMS = onMs;
mNotification.ledOffMS = offMs;
boolean showLights = mNotification.ledOnMS != 0 && mNotification.ledOffMS != 0;
mNotification.flags = (mNotification.flags & ~Notification.FLAG_SHOW_LIGHTS) |
(showLights ? Notification.FLAG_SHOW_LIGHTS : 0);
return this;
}
/**
* Set whether this is an ongoing notification.
*
* <p>Ongoing notifications differ from regular notifications in the following ways:
* <ul>
* <li>Ongoing notifications are sorted above the regular notifications in the
* notification panel.</li>
* <li>Ongoing notifications do not have an 'X' close button, and are not affected
* by the "Clear all" button.
* </ul>
*/
public Builder setOngoing(boolean ongoing) {
setFlag(Notification.FLAG_ONGOING_EVENT, ongoing);
return this;
}
/**
* Set whether this notification should be colorized. When set, the color set with
* {@link #setColor(int)} will be used as the background color of this notification.
* <p>
* This should only be used for high priority ongoing tasks like navigation, an ongoing
* call, or other similarly high-priority events for the user.
* <p>
* For most styles, the coloring will only be applied if the notification is for a
* foreground service notification.
* <p>
* However, for MediaStyle and DecoratedMediaCustomViewStyle notifications
* that have a media session attached there is no such requirement.
* <p>
* Calling this method on any version prior to {@link android.os.Build.VERSION_CODES#O} will
* not have an effect on the notification and it won't be colorized.
*
* @see #setColor(int)
*/
public Builder setColorized(boolean colorize) {
mColorized = colorize;
mColorizedSet = true;
return this;
}
/**
* Set this flag if you would only like the sound, vibrate
* and ticker to be played if the notification is not already showing.
*/
public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
setFlag(Notification.FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
return this;
}
/**
* Setting this flag will make it so the notification is automatically
* canceled when the user clicks it in the panel. The PendingIntent
* set with {@link #setDeleteIntent} will be broadcast when the notification
* is canceled.
*/
public Builder setAutoCancel(boolean autoCancel) {
setFlag(Notification.FLAG_AUTO_CANCEL, autoCancel);
return this;
}
/**
* Set whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* This hint can be set to recommend this notification not be bridged.
*/
public Builder setLocalOnly(boolean b) {
mLocalOnly = b;
return this;
}
/**
* Set the notification category.
*
* <p>Must be one of the predefined notification categories (see the <code>CATEGORY_*</code>
* constants in {@link Notification}) that best describes this notification.
* May be used by the system for ranking and filtering.
*/
public Builder setCategory(String category) {
mCategory = category;
return this;
}
/**
* Set the default notification options that will be used.
* <p>
* The value should be one or more of the following fields combined with
* bitwise-or:
* {@link Notification#DEFAULT_SOUND}, {@link Notification#DEFAULT_VIBRATE},
* {@link Notification#DEFAULT_LIGHTS}.
* <p>
* For all default values, use {@link Notification#DEFAULT_ALL}.
*/
public Builder setDefaults(int defaults) {
mNotification.defaults = defaults;
if ((defaults & Notification.DEFAULT_LIGHTS) != 0) {
mNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
}
return this;
}
private void setFlag(int mask, boolean value) {
if (value) {
mNotification.flags |= mask;
} else {
mNotification.flags &= ~mask;
}
}
/**
* Set the relative priority for this notification.
*
* Priority is an indication of how much of the user's
* valuable attention should be consumed by this
* notification. Low-priority notifications may be hidden from
* the user in certain situations, while the user might be
* interrupted for a higher-priority notification.
* The system sets a notification's priority based on various factors including the
* setPriority value. The effect may differ slightly on different platforms.
*
* @param pri Relative priority for this notification. Must be one of
* the priority constants defined by {@link NotificationCompat}.
* Acceptable values range from {@link
* NotificationCompat#PRIORITY_MIN} (-2) to {@link
* NotificationCompat#PRIORITY_MAX} (2).
*/
public Builder setPriority(int pri) {
mPriority = pri;
return this;
}
/**
* Add a person that is relevant to this notification.
*
* <P>
* Depending on user preferences, this annotation may allow the notification to pass
* through interruption filters, and to appear more prominently in the user interface.
* </P>
*
* <P>
* The person should be specified by the {@code String} representation of a
* {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}.
* </P>
*
* <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema
* URIs. The path part of these URIs must exist in the contacts database, in the
* appropriate column, or the reference will be discarded as invalid. Telephone schema
* URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}.
* </P>
*
* @param uri A URI for the person.
* @see Notification#EXTRA_PEOPLE
*/
public Builder addPerson(String uri) {
mPeople.add(uri);
return this;
}
/**
* Set this notification to be part of a group of notifications sharing the same key.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering.
*
* <p>To make this notification the summary for its group, also call
* {@link #setGroupSummary}. A sort order can be specified for group members by using
* {@link #setSortKey}.
* @param groupKey The group key of the group.
* @return this object for method chaining
*/
public Builder setGroup(String groupKey) {
mGroupKey = groupKey;
return this;
}
/**
* Set this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link #setGroup}.
* @param isGroupSummary Whether this notification should be a group summary.
* @return this object for method chaining
*/
public Builder setGroupSummary(boolean isGroupSummary) {
mGroupSummary = isGroupSummary;
return this;
}
/**
* Set a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public Builder setSortKey(String sortKey) {
mSortKey = sortKey;
return this;
}
/**
* Merge additional metadata into this notification.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see Notification#extras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
if (mExtras == null) {
mExtras = new Bundle(extras);
} else {
mExtras.putAll(extras);
}
}
return this;
}
/**
* Set metadata for this notification.
*
* <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
* current contents are copied into the Notification each time {@link #build()} is
* called.
*
* <p>Replaces any existing extras values with those from the provided Bundle.
* Use {@link #addExtras} to merge in metadata instead.
*
* @see Notification#extras
*/
public Builder setExtras(Bundle extras) {
mExtras = extras;
return this;
}
/**
* Get the current metadata Bundle used by this notification Builder.
*
* <p>The returned Bundle is shared with this Builder.
*
* <p>The current contents of this Bundle are copied into the Notification each time
* {@link #build()} is called.
*
* @see Notification#extras
*/
public Bundle getExtras() {
if (mExtras == null) {
mExtras = new Bundle();
}
return mExtras;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param icon Resource ID of a drawable that represents the action.
* @param title Text describing the action.
* @param intent {@link android.app.PendingIntent} to be fired when the action is invoked.
*/
public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
mActions.add(new Action(icon, title, intent));
return this;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param action The action to add.
*/
public Builder addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Add a rich notification style to be applied at build time.
* <br>
* If the platform does not provide rich notification styles, this method has no effect. The
* user will always see the normal notification style.
*
* @param style Object responsible for modifying the notification style.
*/
public Builder setStyle(Style style) {
if (mStyle != style) {
mStyle = style;
if (mStyle != null) {
mStyle.setBuilder(this);
}
}
return this;
}
/**
* Sets {@link Notification#color}.
*
* @param argb The accent color to use
*
* @return The same Builder.
*/
public Builder setColor(@ColorInt int argb) {
mColor = argb;
return this;
}
/**
* Sets {@link Notification#visibility}.
*
* @param visibility One of {@link Notification#VISIBILITY_PRIVATE} (the default),
* {@link Notification#VISIBILITY_PUBLIC}, or
* {@link Notification#VISIBILITY_SECRET}.
*/
public Builder setVisibility(@NotificationVisibility int visibility) {
mVisibility = visibility;
return this;
}
/**
* Supply a replacement Notification whose contents should be shown in insecure contexts
* (i.e. atop the secure lockscreen). See {@link Notification#visibility} and
* {@link #VISIBILITY_PUBLIC}.
*
* @param n A replacement notification, presumably with some or all info redacted.
* @return The same Builder.
*/
public Builder setPublicVersion(Notification n) {
mPublicVersion = n;
return this;
}
/**
* Supply custom RemoteViews to use instead of the platform template.
*
* This will override the layout that would otherwise be constructed by this Builder
* object.
*/
public Builder setCustomContentView(RemoteViews contentView) {
mContentView = contentView;
return this;
}
/**
* Supply custom RemoteViews to use instead of the platform template in the expanded form.
*
* This will override the expanded layout that would otherwise be constructed by this
* Builder object.
*
* No-op on versions prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.
*/
public Builder setCustomBigContentView(RemoteViews contentView) {
mBigContentView = contentView;
return this;
}
/**
* Supply custom RemoteViews to use instead of the platform template in the heads up dialog.
*
* This will override the heads-up layout that would otherwise be constructed by this
* Builder object.
*
* No-op on versions prior to {@link android.os.Build.VERSION_CODES#LOLLIPOP}.
*/
public Builder setCustomHeadsUpContentView(RemoteViews contentView) {
mHeadsUpContentView = contentView;
return this;
}
/**
* Specifies the channel the notification should be delivered on.
*
* No-op on versions prior to {@link android.os.Build.VERSION_CODES#O} .
*/
public Builder setChannelId(@NonNull String channelId) {
mChannelId = channelId;
return this;
}
/** @deprecated removed from API 26 */
@Deprecated
public Builder setChannel(@NonNull String channelId) {
return setChannelId(channelId);
}
/**
* Specifies the time at which this notification should be canceled, if it is not already
* canceled.
*/
public Builder setTimeoutAfter(long durationMs) {
mTimeout = durationMs;
return this;
}
/** @deprecated removed from API 26 */
@Deprecated
public Builder setTimeout(long durationMs) {
return setTimeoutAfter(durationMs);
}
/**
* If this notification is duplicative of a Launcher shortcut, sets the
* {@link android.support.v4.content.pm.ShortcutInfoCompat#getId() id} of the shortcut, in
* case the Launcher wants to hide the shortcut.
*
* <p><strong>Note:</strong>This field will be ignored by Launchers that don't support
* badging or {@link android.support.v4.content.pm.ShortcutManagerCompat shortcuts}.
*
* @param shortcutId the {@link android.support.v4.content.pm.ShortcutInfoCompat#getId() id}
* of the shortcut this notification supersedes
*/
public Builder setShortcutId(String shortcutId) {
mShortcutId = shortcutId;
return this;
}
/**
* Sets which icon to display as a badge for this notification.
*
* <p>Must be one of {@link #BADGE_ICON_NONE}, {@link #BADGE_ICON_SMALL},
* {@link #BADGE_ICON_LARGE}.
*
* <p><strong>Note:</strong> This value might be ignored, for launchers that don't support
* badge icons.
*/
public Builder setBadgeIconType(@BadgeIconType int icon) {
mBadgeIcon = icon;
return this;
}
/**
* Sets the group alert behavior for this notification. Use this method to mute this
* notification if alerts for this notification's group should be handled by a different
* notification. This is only applicable for notifications that belong to a
* {@link #setGroup(String) group}.
*
* <p> The default value is {@link #GROUP_ALERT_ALL}.</p>
*/
public Builder setGroupAlertBehavior(int groupAlertBehavior) {
mGroupAlertBehavior = groupAlertBehavior;
return this;
}
/**
* Apply an extender to this notification builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* @deprecated Use {@link #build()} instead.
*/
@Deprecated
public Notification getNotification() {
return build();
}
/**
* Combine all of the options that have been set and return a new {@link Notification}
* object.
*/
public Notification build() {
return IMPL.build(this, getExtender());
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected BuilderExtender getExtender() {
return new BuilderExtender();
}
protected static CharSequence limitCharSequenceLength(CharSequence cs) {
if (cs == null) return cs;
if (cs.length() > MAX_CHARSEQUENCE_LENGTH) {
cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH);
}
return cs;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public RemoteViews getContentView() {
return mContentView;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public RemoteViews getBigContentView() {
return mBigContentView;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public RemoteViews getHeadsUpContentView() {
return mHeadsUpContentView;
}
/**
* return when if it is showing or 0 otherwise
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public long getWhenIfShowing() {
return mShowWhen ? mNotification.when : 0;
}
/**
* @return the priority set on the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public int getPriority() {
return mPriority;
}
/**
* @return the color of the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public int getColor() {
return mColor;
}
/**
* @return the text of the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected CharSequence resolveText() {
return mContentText;
}
/**
* @return the title of the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected CharSequence resolveTitle() {
return mContentTitle;
}
}
/**
* An object that can apply a rich notification style to a {@link Notification.Builder}
* object.
* <br>
* If the platform does not provide rich notification styles, methods in this class have no
* effect.
*/
public static abstract class Style {
Builder mBuilder;
CharSequence mBigContentTitle;
CharSequence mSummaryText;
boolean mSummaryTextSet = false;
public void setBuilder(Builder builder) {
if (mBuilder != builder) {
mBuilder = builder;
if (mBuilder != null) {
mBuilder.setStyle(this);
}
}
}
public Notification build() {
Notification notification = null;
if (mBuilder != null) {
notification = mBuilder.build();
}
return notification;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
// TODO: implement for all styles
public void apply(NotificationBuilderWithBuilderAccessor builder) {
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
// TODO: implement for all styles
public void addCompatExtras(Bundle extras) {
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
// TODO: implement for all styles
protected void restoreFromCompatExtras(Bundle extras) {
}
}
/**
* Helper class for generating large-format notifications that include a large image attachment.
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notification = new Notification.Builder(mContext)
* .setContentTitle("New photo from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_post)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigPictureStyle()
* .bigPicture(aBigBitmap))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigPictureStyle extends Style {
private Bitmap mPicture;
private Bitmap mBigLargeIcon;
private boolean mBigLargeIconSet;
public BigPictureStyle() {
}
public BigPictureStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigPictureStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigPictureStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the bitmap to be used as the payload for the BigPicture notification.
*/
public BigPictureStyle bigPicture(Bitmap b) {
mPicture = b;
return this;
}
/**
* Override the large icon when the big notification is shown.
*/
public BigPictureStyle bigLargeIcon(Bitmap b) {
mBigLargeIcon = b;
mBigLargeIconSet = true;
return this;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
public void apply(NotificationBuilderWithBuilderAccessor builder) {
if (Build.VERSION.SDK_INT >= 16) {
NotificationCompatJellybean.addBigPictureStyle(builder,
mBigContentTitle,
mSummaryTextSet,
mSummaryText,
mPicture,
mBigLargeIcon,
mBigLargeIconSet);
}
}
}
/**
* Helper class for generating large-format notifications that include a lot of text.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notification = new Notification.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigTextStyle()
* .bigText(aVeryLongString))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigTextStyle extends Style {
private CharSequence mBigText;
public BigTextStyle() {
}
public BigTextStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigTextStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigTextStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the longer text to be displayed in the big form of the
* template in place of the content text.
*/
public BigTextStyle bigText(CharSequence cs) {
mBigText = Builder.limitCharSequenceLength(cs);
return this;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
public void apply(NotificationBuilderWithBuilderAccessor builder) {
if (Build.VERSION.SDK_INT >= 16) {
NotificationCompatJellybean.addBigTextStyle(builder,
mBigContentTitle,
mSummaryTextSet,
mSummaryText,
mBigText);
}
}
}
/**
* Helper class for generating large-format notifications that include multiple back-and-forth
* messages of varying types between any number of people.
*
* <br>
* In order to get a backwards compatible behavior, the app needs to use the v7 version of the
* notification builder together with this style, otherwise the user will see the normal
* notification view.
*
* <br>
* Use {@link MessagingStyle#setConversationTitle(CharSequence)} to set a conversation title for
* group chats with more than two people. This could be the user-created name of the group or,
* if it doesn't have a specific name, a list of the participants in the conversation. Do not
* set a conversation title for one-on-one chats, since platforms use the existence of this
* field as a hint that the conversation is a group.
*
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like
* so:
* <pre class="prettyprint">
*
* Notification notification = new Notification.Builder()
* .setContentTitle("2 new messages with " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_message)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.MessagingStyle(resources.getString(R.string.reply_name))
* .addMessage(messages[0].getText(), messages[0].getTime(), messages[0].getSender())
* .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getSender()))
* .build();
* </pre>
*/
public static class MessagingStyle extends Style {
/**
* The maximum number of messages that will be retained in the Notification itself (the
* number displayed is up to the platform).
*/
public static final int MAXIMUM_RETAINED_MESSAGES = 25;
CharSequence mUserDisplayName;
CharSequence mConversationTitle;
List<Message> mMessages = new ArrayList<>();
MessagingStyle() {
}
/**
* @param userDisplayName Required - the name to be displayed for any replies sent by the
* user before the posting app reposts the notification with those messages after they've
* been actually sent and in previous messages sent by the user added in
* {@link #addMessage(Message)}
*/
public MessagingStyle(@NonNull CharSequence userDisplayName) {
mUserDisplayName = userDisplayName;
}
/**
* Returns the name to be displayed for any replies sent by the user
*/
public CharSequence getUserDisplayName() {
return mUserDisplayName;
}
/**
* Sets the title to be displayed on this conversation. This should only be used for
* group messaging and left unset for one-on-one conversations.
* @param conversationTitle Title displayed for this conversation.
* @return this object for method chaining.
*/
public MessagingStyle setConversationTitle(CharSequence conversationTitle) {
mConversationTitle = conversationTitle;
return this;
}
/**
* Return the title to be displayed on this conversation. Can be <code>null</code> and
* should be for one-on-one conversations
*/
public CharSequence getConversationTitle() {
return mConversationTitle;
}
/**
* Adds a message for display by this notification. Convenience call for a simple
* {@link Message} in {@link #addMessage(Message)}
* @param text A {@link CharSequence} to be displayed as the message content
* @param timestamp Time at which the message arrived
* @param sender A {@link CharSequence} to be used for displaying the name of the
* sender. Should be <code>null</code> for messages by the current user, in which case
* the platform will insert {@link #getUserDisplayName()}.
* Should be unique amongst all individuals in the conversation, and should be
* consistent during re-posts of the notification.
*
* @see Message#Message(CharSequence, long, CharSequence)
*
* @return this object for method chaining
*/
public MessagingStyle addMessage(CharSequence text, long timestamp, CharSequence sender) {
mMessages.add(new Message(text, timestamp, sender));
if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
mMessages.remove(0);
}
return this;
}
/**
* Adds a {@link Message} for display in this notification.
* @param message The {@link Message} to be displayed
* @return this object for method chaining
*/
public MessagingStyle addMessage(Message message) {
mMessages.add(message);
if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
mMessages.remove(0);
}
return this;
}
/**
* Gets the list of {@code Message} objects that represent the notification
*/
public List<Message> getMessages() {
return mMessages;
}
/**
* Retrieves a {@link MessagingStyle} from a {@link Notification}, enabling an application
* that has set a {@link MessagingStyle} using {@link NotificationCompat} or
* {@link android.app.Notification.Builder} to send messaging information to another
* application using {@link NotificationCompat}, regardless of the API level of the system.
* Returns {@code null} if there is no {@link MessagingStyle} set.
*/
public static MessagingStyle extractMessagingStyleFromNotification(
Notification notification) {
MessagingStyle style;
Bundle extras = NotificationCompat.getExtras(notification);
if (extras != null && !extras.containsKey(EXTRA_SELF_DISPLAY_NAME)) {
style = null;
} else {
try {
style = new MessagingStyle();
style.restoreFromCompatExtras(extras);
} catch (ClassCastException e) {
style = null;
}
}
return style;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
public void apply(NotificationBuilderWithBuilderAccessor builder) {
if (Build.VERSION.SDK_INT >= 24) {
List<CharSequence> texts = new ArrayList<>();
List<Long> timestamps = new ArrayList<>();
List<CharSequence> senders = new ArrayList<>();
List<String> dataMimeTypes = new ArrayList<>();
List<Uri> dataUris = new ArrayList<>();
for (MessagingStyle.Message message : mMessages) {
texts.add(message.getText());
timestamps.add(message.getTimestamp());
senders.add(message.getSender());
dataMimeTypes.add(message.getDataMimeType());
dataUris.add(message.getDataUri());
}
NotificationCompatApi24.addMessagingStyle(builder, mUserDisplayName,
mConversationTitle, texts, timestamps, senders,
dataMimeTypes, dataUris);
}
}
@Override
public void addCompatExtras(Bundle extras) {
super.addCompatExtras(extras);
if (mUserDisplayName != null) {
extras.putCharSequence(EXTRA_SELF_DISPLAY_NAME, mUserDisplayName);
}
if (mConversationTitle != null) {
extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle);
}
if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES,
Message.getBundleArrayForMessages(mMessages));
}
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
protected void restoreFromCompatExtras(Bundle extras) {
mMessages.clear();
mUserDisplayName = extras.getString(EXTRA_SELF_DISPLAY_NAME);
mConversationTitle = extras.getString(EXTRA_CONVERSATION_TITLE);
Parcelable[] parcelables = extras.getParcelableArray(EXTRA_MESSAGES);
if (parcelables != null) {
mMessages = Message.getMessagesFromBundleArray(parcelables);
}
}
public static final class Message {
static final String KEY_TEXT = "text";
static final String KEY_TIMESTAMP = "time";
static final String KEY_SENDER = "sender";
static final String KEY_DATA_MIME_TYPE = "type";
static final String KEY_DATA_URI= "uri";
static final String KEY_EXTRAS_BUNDLE = "extras";
private final CharSequence mText;
private final long mTimestamp;
private final CharSequence mSender;
private Bundle mExtras = new Bundle();
private String mDataMimeType;
private Uri mDataUri;
/**
* Constructor
* @param text A {@link CharSequence} to be displayed as the message content
* @param timestamp Time at which the message arrived
* @param sender A {@link CharSequence} to be used for displaying the name of the
* sender. Should be <code>null</code> for messages by the current user, in which case
* the platform will insert {@link MessagingStyle#getUserDisplayName()}.
* Should be unique amongst all individuals in the conversation, and should be
* consistent during re-posts of the notification.
*/
public Message(CharSequence text, long timestamp, CharSequence sender){
mText = text;
mTimestamp = timestamp;
mSender = sender;
}
/**
* Sets a binary blob of data and an associated MIME type for a message. In the case
* where the platform doesn't support the MIME type, the original text provided in the
* constructor will be used.
* @param dataMimeType The MIME type of the content. See
* <a href="{@docRoot}notifications/messaging.html"> for the list of supported MIME
* types on Android and Android Wear.
* @param dataUri The uri containing the content whose type is given by the MIME type.
* <p class="note">
* <ol>
* <li>Notification Listeners including the System UI need permission to access the
* data the Uri points to. The recommended ways to do this are:</li>
* <li>Store the data in your own ContentProvider, making sure that other apps have
* the correct permission to access your provider. The preferred mechanism for
* providing access is to use per-URI permissions which are temporary and only
* grant access to the receiving application. An easy way to create a
* ContentProvider like this is to use the FileProvider helper class.</li>
* <li>Use the system MediaStore. The MediaStore is primarily aimed at video, audio
* and image MIME types, however beginning with Android 3.0 (API level 11) it can
* also store non-media types (see MediaStore.Files for more info). Files can be
* inserted into the MediaStore using scanFile() after which a content:// style
* Uri suitable for sharing is passed to the provided onScanCompleted() callback.
* Note that once added to the system MediaStore the content is accessible to any
* app on the device.</li>
* </ol>
* @return this object for method chaining
*/
public Message setData(String dataMimeType, Uri dataUri) {
mDataMimeType = dataMimeType;
mDataUri = dataUri;
return this;
}
/**
* Get the text to be used for this message, or the fallback text if a type and content
* Uri have been set
*/
public CharSequence getText() {
return mText;
}
/**
* Get the time at which this message arrived
*/
public long getTimestamp() {
return mTimestamp;
}
/**
* Get the extras Bundle for this message.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Get the text used to display the contact's name in the messaging experience
*/
public CharSequence getSender() {
return mSender;
}
/**
* Get the MIME type of the data pointed to by the Uri
*/
public String getDataMimeType() {
return mDataMimeType;
}
/**
* Get the the Uri pointing to the content of the message. Can be null, in which case
* {@see #getText()} is used.
*/
public Uri getDataUri() {
return mDataUri;
}
private Bundle toBundle() {
Bundle bundle = new Bundle();
if (mText != null) {
bundle.putCharSequence(KEY_TEXT, mText);
}
bundle.putLong(KEY_TIMESTAMP, mTimestamp);
if (mSender != null) {
bundle.putCharSequence(KEY_SENDER, mSender);
}
if (mDataMimeType != null) {
bundle.putString(KEY_DATA_MIME_TYPE, mDataMimeType);
}
if (mDataUri != null) {
bundle.putParcelable(KEY_DATA_URI, mDataUri);
}
if (mExtras != null) {
bundle.putBundle(KEY_EXTRAS_BUNDLE, mExtras);
}
return bundle;
}
static Bundle[] getBundleArrayForMessages(List<Message> messages) {
Bundle[] bundles = new Bundle[messages.size()];
final int N = messages.size();
for (int i = 0; i < N; i++) {
bundles[i] = messages.get(i).toBundle();
}
return bundles;
}
static List<Message> getMessagesFromBundleArray(Parcelable[] bundles) {
List<Message> messages = new ArrayList<>(bundles.length);
for (int i = 0; i < bundles.length; i++) {
if (bundles[i] instanceof Bundle) {
Message message = getMessageFromBundle((Bundle)bundles[i]);
if (message != null) {
messages.add(message);
}
}
}
return messages;
}
static Message getMessageFromBundle(Bundle bundle) {
try {
if (!bundle.containsKey(KEY_TEXT) || !bundle.containsKey(KEY_TIMESTAMP)) {
return null;
} else {
Message message = new Message(bundle.getCharSequence(KEY_TEXT),
bundle.getLong(KEY_TIMESTAMP), bundle.getCharSequence(KEY_SENDER));
if (bundle.containsKey(KEY_DATA_MIME_TYPE) &&
bundle.containsKey(KEY_DATA_URI)) {
message.setData(bundle.getString(KEY_DATA_MIME_TYPE),
(Uri) bundle.getParcelable(KEY_DATA_URI));
}
if (bundle.containsKey(KEY_EXTRAS_BUNDLE)) {
message.getExtras().putAll(bundle.getBundle(KEY_EXTRAS_BUNDLE));
}
return message;
}
} catch (ClassCastException e) {
return null;
}
}
}
}
/**
* Helper class for generating large-format notifications that include a list of (up to 5) strings.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notification = new Notification.Builder()
* .setContentTitle("5 New mails from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.InboxStyle()
* .addLine(str1)
* .addLine(str2)
* .setContentTitle("")
* .setSummaryText("+3 more"))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class InboxStyle extends Style {
private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
public InboxStyle() {
}
public InboxStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public InboxStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public InboxStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Append a line to the digest section of the Inbox notification.
*/
public InboxStyle addLine(CharSequence cs) {
mTexts.add(Builder.limitCharSequenceLength(cs));
return this;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
public void apply(NotificationBuilderWithBuilderAccessor builder) {
if (Build.VERSION.SDK_INT >= 16) {
NotificationCompatJellybean.addInboxStyle(builder,
mBigContentTitle,
mSummaryTextSet,
mSummaryText,
mTexts);
}
}
}
/**
* Structure to encapsulate a named action that can be shown as part of this notification.
* It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
* selected by the user. Action buttons won't appear on platforms prior to Android 4.1.
* <p>
* Apps should use {@link NotificationCompat.Builder#addAction(int, CharSequence, PendingIntent)}
* or {@link NotificationCompat.Builder#addAction(NotificationCompat.Action)}
* to attach actions.
*/
public static class Action extends NotificationCompatBase.Action {
final Bundle mExtras;
private final RemoteInput[] mRemoteInputs;
/**
* Holds {@link RemoteInput}s that only accept data, meaning
* {@link RemoteInput#getAllowFreeFormInput} is false, {@link RemoteInput#getChoices}
* is null or empty, and {@link RemoteInput#getAllowedDataTypes is non-null and not
* empty. These {@link RemoteInput}s will be ignored by devices that do not
* support non-text-based {@link RemoteInput}s. See {@link Builder#build}.
*
* You can test if a RemoteInput matches these constraints using
* {@link RemoteInput#isDataOnly}.
*/
private final RemoteInput[] mDataOnlyRemoteInputs;
private boolean mAllowGeneratedReplies;
/**
* Small icon representing the action.
*/
public int icon;
/**
* Title of the action.
*/
public CharSequence title;
/**
* Intent to send when the user invokes this action. May be null, in which case the action
* may be rendered in a disabled presentation.
*/
public PendingIntent actionIntent;
public Action(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle(), null, null, true);
}
Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
RemoteInput[] remoteInputs, RemoteInput[] dataOnlyRemoteInputs,
boolean allowGeneratedReplies) {
this.icon = icon;
this.title = NotificationCompat.Builder.limitCharSequenceLength(title);
this.actionIntent = intent;
this.mExtras = extras != null ? extras : new Bundle();
this.mRemoteInputs = remoteInputs;
this.mDataOnlyRemoteInputs = dataOnlyRemoteInputs;
this.mAllowGeneratedReplies = allowGeneratedReplies;
}
@Override
public int getIcon() {
return icon;
}
@Override
public CharSequence getTitle() {
return title;
}
@Override
public PendingIntent getActionIntent() {
return actionIntent;
}
/**
* Get additional metadata carried around with this Action.
*/
@Override
public Bundle getExtras() {
return mExtras;
}
/**
* Return whether the platform should automatically generate possible replies for this
* {@link Action}
*/
@Override
public boolean getAllowGeneratedReplies() {
return mAllowGeneratedReplies;
}
/**
* Get the list of inputs to be collected from the user when this action is sent.
* May return null if no remote inputs were added. Only returns inputs which accept
* a text input. For inputs which only accept data use {@link #getDataOnlyRemoteInputs}.
*/
@Override
public RemoteInput[] getRemoteInputs() {
return mRemoteInputs;
}
/**
* Get the list of inputs to be collected from the user that ONLY accept data when this
* action is sent. These remote inputs are guaranteed to return true on a call to
* {@link RemoteInput#isDataOnly}.
*
* <p>May return null if no data-only remote inputs were added.
*
* <p>This method exists so that legacy RemoteInput collectors that pre-date the addition
* of non-textual RemoteInputs do not access these remote inputs.
*/
@Override
public RemoteInput[] getDataOnlyRemoteInputs() {
return mDataOnlyRemoteInputs;
}
/**
* Builder class for {@link Action} objects.
*/
public static final class Builder {
private final int mIcon;
private final CharSequence mTitle;
private final PendingIntent mIntent;
private boolean mAllowGeneratedReplies = true;
private final Bundle mExtras;
private ArrayList<RemoteInput> mRemoteInputs;
/**
* Construct a new builder for {@link Action} object.
* @param icon icon to show for this action
* @param title the title of the action
* @param intent the {@link PendingIntent} to fire when users trigger this action
*/
public Builder(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle(), null, true);
}
/**
* Construct a new builder for {@link Action} object using the fields from an
* {@link Action}.
* @param action the action to read fields from.
*/
public Builder(Action action) {
this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras),
action.getRemoteInputs(), action.getAllowGeneratedReplies());
}
private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras,
RemoteInput[] remoteInputs, boolean allowGeneratedReplies) {
mIcon = icon;
mTitle = NotificationCompat.Builder.limitCharSequenceLength(title);
mIntent = intent;
mExtras = extras;
mRemoteInputs = remoteInputs == null ? null : new ArrayList<>(
Arrays.asList(remoteInputs));
mAllowGeneratedReplies = allowGeneratedReplies;
}
/**
* Merge additional metadata into this builder.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see NotificationCompat.Action#getExtras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
mExtras.putAll(extras);
}
return this;
}
/**
* Get the metadata Bundle used by this Builder.
*
* <p>The returned Bundle is shared with this Builder.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Add an input to be collected from the user when this action is sent.
* Response values can be retrieved from the fired intent by using the
* {@link RemoteInput#getResultsFromIntent} function.
* @param remoteInput a {@link RemoteInput} to add to the action
* @return this object for method chaining
*/
public Builder addRemoteInput(RemoteInput remoteInput) {
if (mRemoteInputs == null) {
mRemoteInputs = new ArrayList<RemoteInput>();
}
mRemoteInputs.add(remoteInput);
return this;
}
/**
* Set whether the platform should automatically generate possible replies to add to
* {@link RemoteInput#getChoices()}. If the {@link Action} doesn't have a
* {@link RemoteInput}, this has no effect.
* @param allowGeneratedReplies {@code true} to allow generated replies, {@code false}
* otherwise
* @return this object for method chaining
* The default value is {@code true}
*/
public Builder setAllowGeneratedReplies(boolean allowGeneratedReplies) {
mAllowGeneratedReplies = allowGeneratedReplies;
return this;
}
/**
* Apply an extender to this action builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* Combine all of the options that have been set and return a new {@link Action}
* object.
* @return the built action
*/
public Action build() {
List<RemoteInput> dataOnlyInputs = new ArrayList<>();
List<RemoteInput> textInputs = new ArrayList<>();
if (mRemoteInputs != null) {
for (RemoteInput input : mRemoteInputs) {
if (input.isDataOnly()) {
dataOnlyInputs.add(input);
} else {
textInputs.add(input);
}
}
}
RemoteInput[] dataOnlyInputsArr = dataOnlyInputs.isEmpty()
? null : dataOnlyInputs.toArray(new RemoteInput[dataOnlyInputs.size()]);
RemoteInput[] textInputsArr = textInputs.isEmpty()
? null : textInputs.toArray(new RemoteInput[textInputs.size()]);
return new Action(mIcon, mTitle, mIntent, mExtras, textInputsArr,
dataOnlyInputsArr, mAllowGeneratedReplies);
}
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on an action builder.
*/
public interface Extender {
/**
* Apply this extender to a notification action builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
Builder extend(Builder builder);
}
/**
* Wearable extender for notification actions. To add extensions to an action,
* create a new {@link NotificationCompat.Action.WearableExtender} object using
* the {@code WearableExtender()} constructor and apply it to a
* {@link NotificationCompat.Action.Builder} using
* {@link NotificationCompat.Action.Builder#extend}.
*
* <pre class="prettyprint">
* NotificationCompat.Action action = new NotificationCompat.Action.Builder(
* R.drawable.archive_all, "Archive all", actionIntent)
* .extend(new NotificationCompat.Action.WearableExtender()
* .setAvailableOffline(false))
* .build();</pre>
*/
public static final class WearableExtender implements Extender {
/** Notification action extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
// Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
private static final String KEY_FLAGS = "flags";
private static final String KEY_IN_PROGRESS_LABEL = "inProgressLabel";
private static final String KEY_CONFIRM_LABEL = "confirmLabel";
private static final String KEY_CANCEL_LABEL = "cancelLabel";
// Flags bitwise-ored to mFlags
private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
private static final int FLAG_HINT_LAUNCHES_ACTIVITY = 1 << 1;
private static final int FLAG_HINT_DISPLAY_INLINE = 1 << 2;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
private int mFlags = DEFAULT_FLAGS;
private CharSequence mInProgressLabel;
private CharSequence mConfirmLabel;
private CharSequence mCancelLabel;
/**
* Create a {@link NotificationCompat.Action.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
/**
* Create a {@link NotificationCompat.Action.WearableExtender} by reading
* wearable options present in an existing notification action.
* @param action the notification action to inspect.
*/
public WearableExtender(Action action) {
Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
if (wearableBundle != null) {
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
mInProgressLabel = wearableBundle.getCharSequence(KEY_IN_PROGRESS_LABEL);
mConfirmLabel = wearableBundle.getCharSequence(KEY_CONFIRM_LABEL);
mCancelLabel = wearableBundle.getCharSequence(KEY_CANCEL_LABEL);
}
}
/**
* Apply wearable extensions to a notification action that is being built. This is
* typically called by the {@link NotificationCompat.Action.Builder#extend}
* method of {@link NotificationCompat.Action.Builder}.
*/
@Override
public Action.Builder extend(Action.Builder builder) {
Bundle wearableBundle = new Bundle();
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
if (mInProgressLabel != null) {
wearableBundle.putCharSequence(KEY_IN_PROGRESS_LABEL, mInProgressLabel);
}
if (mConfirmLabel != null) {
wearableBundle.putCharSequence(KEY_CONFIRM_LABEL, mConfirmLabel);
}
if (mCancelLabel != null) {
wearableBundle.putCharSequence(KEY_CANCEL_LABEL, mCancelLabel);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mFlags = this.mFlags;
that.mInProgressLabel = this.mInProgressLabel;
that.mConfirmLabel = this.mConfirmLabel;
that.mCancelLabel = this.mCancelLabel;
return that;
}
/**
* Set whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public WearableExtender setAvailableOffline(boolean availableOffline) {
setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
return this;
}
/**
* Get whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public boolean isAvailableOffline() {
return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
/**
* Set a label to display while the wearable is preparing to automatically execute the
* action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
*
* @param label the label to display while the action is being prepared to execute
* @return this object for method chaining
*/
public WearableExtender setInProgressLabel(CharSequence label) {
mInProgressLabel = label;
return this;
}
/**
* Get the label to display while the wearable is preparing to automatically execute
* the action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
*
* @return the label to display while the action is being prepared to execute
*/
public CharSequence getInProgressLabel() {
return mInProgressLabel;
}
/**
* Set a label to display to confirm that the action should be executed.
* This is usually an imperative verb like "Send".
*
* @param label the label to confirm the action should be executed
* @return this object for method chaining
*/
public WearableExtender setConfirmLabel(CharSequence label) {
mConfirmLabel = label;
return this;
}
/**
* Get the label to display to confirm that the action should be executed.
* This is usually an imperative verb like "Send".
*
* @return the label to confirm the action should be executed
*/
public CharSequence getConfirmLabel() {
return mConfirmLabel;
}
/**
* Set a label to display to cancel the action.
* This is usually an imperative verb, like "Cancel".
*
* @param label the label to display to cancel the action
* @return this object for method chaining
*/
public WearableExtender setCancelLabel(CharSequence label) {
mCancelLabel = label;
return this;
}
/**
* Get the label to display to cancel the action.
* This is usually an imperative verb like "Cancel".
*
* @return the label to display to cancel the action
*/
public CharSequence getCancelLabel() {
return mCancelLabel;
}
/**
* Set a hint that this Action will launch an {@link Activity} directly, telling the
* platform that it can generate the appropriate transitions.
* @param hintLaunchesActivity {@code true} if the content intent will launch
* an activity and transitions should be generated, false otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintLaunchesActivity(
boolean hintLaunchesActivity) {
setFlag(FLAG_HINT_LAUNCHES_ACTIVITY, hintLaunchesActivity);
return this;
}
/**
* Get a hint that this Action will launch an {@link Activity} directly, telling the
* platform that it can generate the appropriate transitions
* @return {@code true} if the content intent will launch an activity and transitions
* should be generated, false otherwise. The default value is {@code false} if this was
* never set.
*/
public boolean getHintLaunchesActivity() {
return (mFlags & FLAG_HINT_LAUNCHES_ACTIVITY) != 0;
}
/**
* Set a hint that this Action should be displayed inline - i.e. it will have a visual
* representation directly on the notification surface in addition to the expanded
* Notification
*
* @param hintDisplayInline {@code true} if action should be displayed inline, false
* otherwise
* @return this object for method chaining
*/
public WearableExtender setHintDisplayActionInline(
boolean hintDisplayInline) {
setFlag(FLAG_HINT_DISPLAY_INLINE, hintDisplayInline);
return this;
}
/**
* Get a hint that this Action should be displayed inline - i.e. it should have a
* visual representation directly on the notification surface in addition to the
* expanded Notification
*
* @return {@code true} if the Action should be displayed inline, {@code false}
* otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintDisplayActionInline() {
return (mFlags & FLAG_HINT_DISPLAY_INLINE) != 0;
}
}
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public static final Factory FACTORY = new Factory() {
@Override
public NotificationCompatBase.Action build(int icon, CharSequence title,
PendingIntent actionIntent, Bundle extras,
RemoteInputCompatBase.RemoteInput[] remoteInputs,
RemoteInputCompatBase.RemoteInput[] dataOnlyRemoteInputs,
boolean allowGeneratedReplies) {
return new Action(icon, title, actionIntent, extras,
(RemoteInput[]) remoteInputs, (RemoteInput[]) dataOnlyRemoteInputs,
allowGeneratedReplies);
}
@Override
public Action[] newArray(int length) {
return new Action[length];
}
};
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on a notification builder.
*/
public interface Extender {
/**
* Apply this extender to a notification builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
Builder extend(Builder builder);
}
/**
* Helper class to add wearable extensions to notifications.
* <p class="note"> See
* <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
* for Android Wear</a> for more information on how to use this class.
* <p>
* To create a notification with wearable extensions:
* <ol>
* <li>Create a {@link NotificationCompat.Builder}, setting any desired
* properties.
* <li>Create a {@link NotificationCompat.WearableExtender}.
* <li>Set wearable-specific properties using the
* {@code add} and {@code set} methods of {@link NotificationCompat.WearableExtender}.
* <li>Call {@link NotificationCompat.Builder#extend} to apply the extensions to a
* notification.
* <li>Post the notification to the notification
* system with the {@code NotificationManagerCompat.notify(...)} methods
* and not the {@code NotificationManager.notify(...)} methods.
* </ol>
*
* <pre class="prettyprint">
* Notification notification = new NotificationCompat.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .extend(new NotificationCompat.WearableExtender()
* .setContentIcon(R.drawable.new_mail))
* .build();
* NotificationManagerCompat.from(mContext).notify(0, notification);</pre>
*
* <p>Wearable extensions can be accessed on an existing notification by using the
* {@code WearableExtender(Notification)} constructor,
* and then using the {@code get} methods to access values.
*
* <pre class="prettyprint">
* NotificationCompat.WearableExtender wearableExtender =
* new NotificationCompat.WearableExtender(notification);
* List<Notification> pages = wearableExtender.getPages();</pre>
*/
public static final class WearableExtender implements Extender {
/**
* Sentinel value for an action index that is unset.
*/
public static final int UNSET_ACTION_INDEX = -1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification with
* default sizing.
* <p>For custom display notifications created using {@link #setDisplayIntent},
* the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based
* on their content.
*/
public static final int SIZE_DEFAULT = 0;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with an extra small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_XSMALL = 1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_SMALL = 2;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a medium size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_MEDIUM = 3;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a large size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_LARGE = 4;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* full screen.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_FULL_SCREEN = 5;
/**
* Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a
* short amount of time when this notification is displayed on the screen. This
* is the default value.
*/
public static final int SCREEN_TIMEOUT_SHORT = 0;
/**
* Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on
* for a longer amount of time when this notification is displayed on the screen.
*/
public static final int SCREEN_TIMEOUT_LONG = -1;
/** Notification extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
// Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
private static final String KEY_ACTIONS = "actions";
private static final String KEY_FLAGS = "flags";
private static final String KEY_DISPLAY_INTENT = "displayIntent";
private static final String KEY_PAGES = "pages";
private static final String KEY_BACKGROUND = "background";
private static final String KEY_CONTENT_ICON = "contentIcon";
private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
private static final String KEY_GRAVITY = "gravity";
private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout";
private static final String KEY_DISMISSAL_ID = "dismissalId";
private static final String KEY_BRIDGE_TAG = "bridgeTag";
// Flags bitwise-ored to mFlags
private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4;
private static final int FLAG_BIG_PICTURE_AMBIENT = 1 << 5;
private static final int FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY = 1 << 6;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
private static final int DEFAULT_CONTENT_ICON_GRAVITY = GravityCompat.END;
private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
private ArrayList<Action> mActions = new ArrayList<Action>();
private int mFlags = DEFAULT_FLAGS;
private PendingIntent mDisplayIntent;
private ArrayList<Notification> mPages = new ArrayList<Notification>();
private Bitmap mBackground;
private int mContentIcon;
private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
private int mContentActionIndex = UNSET_ACTION_INDEX;
private int mCustomSizePreset = SIZE_DEFAULT;
private int mCustomContentHeight;
private int mGravity = DEFAULT_GRAVITY;
private int mHintScreenTimeout;
private String mDismissalId;
private String mBridgeTag;
/**
* Create a {@link NotificationCompat.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
public WearableExtender(Notification notification) {
Bundle extras = getExtras(notification);
Bundle wearableBundle = extras != null ? extras.getBundle(EXTRA_WEARABLE_EXTENSIONS)
: null;
if (wearableBundle != null) {
Action[] actions = IMPL.getActionsFromParcelableArrayList(
wearableBundle.getParcelableArrayList(KEY_ACTIONS));
if (actions != null) {
Collections.addAll(mActions, actions);
}
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
Notification[] pages = getNotificationArrayFromBundle(
wearableBundle, KEY_PAGES);
if (pages != null) {
Collections.addAll(mPages, pages);
}
mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
DEFAULT_CONTENT_ICON_GRAVITY);
mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
UNSET_ACTION_INDEX);
mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
SIZE_DEFAULT);
mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT);
mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID);
mBridgeTag = wearableBundle.getString(KEY_BRIDGE_TAG);
}
}
/**
* Apply wearable extensions to a notification that is being built. This is typically
* called by the {@link NotificationCompat.Builder#extend} method of
* {@link NotificationCompat.Builder}.
*/
@Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
Bundle wearableBundle = new Bundle();
if (!mActions.isEmpty()) {
wearableBundle.putParcelableArrayList(KEY_ACTIONS,
IMPL.getParcelableArrayListForActions(mActions.toArray(
new Action[mActions.size()])));
}
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
if (mDisplayIntent != null) {
wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
}
if (!mPages.isEmpty()) {
wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
new Notification[mPages.size()]));
}
if (mBackground != null) {
wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
}
if (mContentIcon != 0) {
wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
}
if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
}
if (mContentActionIndex != UNSET_ACTION_INDEX) {
wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
mContentActionIndex);
}
if (mCustomSizePreset != SIZE_DEFAULT) {
wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
}
if (mCustomContentHeight != 0) {
wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
}
if (mGravity != DEFAULT_GRAVITY) {
wearableBundle.putInt(KEY_GRAVITY, mGravity);
}
if (mHintScreenTimeout != 0) {
wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout);
}
if (mDismissalId != null) {
wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId);
}
if (mBridgeTag != null) {
wearableBundle.putString(KEY_BRIDGE_TAG, mBridgeTag);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mActions = new ArrayList<Action>(this.mActions);
that.mFlags = this.mFlags;
that.mDisplayIntent = this.mDisplayIntent;
that.mPages = new ArrayList<Notification>(this.mPages);
that.mBackground = this.mBackground;
that.mContentIcon = this.mContentIcon;
that.mContentIconGravity = this.mContentIconGravity;
that.mContentActionIndex = this.mContentActionIndex;
that.mCustomSizePreset = this.mCustomSizePreset;
that.mCustomContentHeight = this.mCustomContentHeight;
that.mGravity = this.mGravity;
that.mHintScreenTimeout = this.mHintScreenTimeout;
that.mDismissalId = this.mDismissalId;
that.mBridgeTag = this.mBridgeTag;
return that;
}
/**
* Add a wearable action to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param action the action to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Adds wearable actions to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param actions the actions to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addActions(List<Action> actions) {
mActions.addAll(actions);
return this;
}
/**
* Clear all wearable actions present on this builder.
* @return this object for method chaining.
* @see #addAction
*/
public WearableExtender clearActions() {
mActions.clear();
return this;
}
/**
* Get the wearable actions present on this notification.
*/
public List<Action> getActions() {
return mActions;
}
/**
* Set an intent to launch inside of an activity view when displaying
* this notification. The {@link PendingIntent} provided should be for an activity.
*
* <pre class="prettyprint">
* Intent displayIntent = new Intent(context, MyDisplayActivity.class);
* PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
* 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
* Notification notification = new NotificationCompat.Builder(context)
* .extend(new NotificationCompat.WearableExtender()
* .setDisplayIntent(displayPendingIntent)
* .setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_MEDIUM))
* .build();</pre>
*
* <p>The activity to launch needs to allow embedding, must be exported, and
* should have an empty task affinity. It is also recommended to use the device
* default light theme.
*
* <p>Example AndroidManifest.xml entry:
* <pre class="prettyprint">
* <activity android:name="com.example.MyDisplayActivity"
* android:exported="true"
* android:allowEmbedded="true"
* android:taskAffinity=""
* android:theme="@android:style/Theme.DeviceDefault.Light" /></pre>
*
* @param intent the {@link PendingIntent} for an activity
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getDisplayIntent
*/
public WearableExtender setDisplayIntent(PendingIntent intent) {
mDisplayIntent = intent;
return this;
}
/**
* Get the intent to launch inside of an activity view when displaying this
* notification. This {@code PendingIntent} should be for an activity.
*/
public PendingIntent getDisplayIntent() {
return mDisplayIntent;
}
/**
* Add an additional page of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param page the notification to add as another page
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPage(Notification page) {
mPages.add(page);
return this;
}
/**
* Add additional pages of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param pages a list of notifications
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPages(List<Notification> pages) {
mPages.addAll(pages);
return this;
}
/**
* Clear all additional pages present on this builder.
* @return this object for method chaining.
* @see #addPage
*/
public WearableExtender clearPages() {
mPages.clear();
return this;
}
/**
* Get the array of additional pages of content for displaying this notification. The
* current notification forms the first page, and elements within this array form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
* @return the pages for this notification
*/
public List<Notification> getPages() {
return mPages;
}
/**
* Set a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @param background the background bitmap
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getBackground
*/
public WearableExtender setBackground(Bitmap background) {
mBackground = background;
return this;
}
/**
* Get a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @return the background image
* @see NotificationCompat.WearableExtender#setBackground
*/
public Bitmap getBackground() {
return mBackground;
}
/**
* Set an icon that goes with the content of this notification.
*/
public WearableExtender setContentIcon(int icon) {
mContentIcon = icon;
return this;
}
/**
* Get an icon that goes with the content of this notification.
*/
public int getContentIcon() {
return mContentIcon;
}
/**
* Set the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #setContentIcon
*/
public WearableExtender setContentIconGravity(int contentIconGravity) {
mContentIconGravity = contentIconGravity;
return this;
}
/**
* Get the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #getContentIcon
*/
public int getContentIconGravity() {
return mContentIconGravity;
}
/**
* Set an action from this notification's actions to be clickable with the content of
* this notification. This action will no longer display separately from the
* notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* @param actionIndex The index of the action to hoist onto the current notification page.
* If wearable actions were added to the main notification, this index
* will apply to that list, otherwise it will apply to the regular
* actions list.
*/
public WearableExtender setContentAction(int actionIndex) {
mContentActionIndex = actionIndex;
return this;
}
/**
* Get the index of the notification action, if any, that was specified as being clickable
* with the content of this notification. This action will no longer display separately
* from the notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* <p>If wearable specific actions were added to the main notification, this index will
* apply to that list, otherwise it will apply to the regular actions list.
*
* @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
*/
public int getContentAction() {
return mContentActionIndex;
}
/**
* Set the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public WearableExtender setGravity(int gravity) {
mGravity = gravity;
return this;
}
/**
* Get the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public int getGravity() {
return mGravity;
}
/**
* Set the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. Check the
* documentation for the preset in question. See also
* {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
*/
public WearableExtender setCustomSizePreset(int sizePreset) {
mCustomSizePreset = sizePreset;
return this;
}
/**
* Get the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link #setDisplayIntent}. Check the documentation for the preset in question.
* See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
*/
public int getCustomSizePreset() {
return mCustomSizePreset;
}
/**
* Set the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. See also
* {@link NotificationCompat.WearableExtender#setCustomSizePreset} and
* {@link #getCustomContentHeight}.
*/
public WearableExtender setCustomContentHeight(int height) {
mCustomContentHeight = height;
return this;
}
/**
* Get the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
* {@link #setCustomContentHeight}.
*/
public int getCustomContentHeight() {
return mCustomContentHeight;
}
/**
* Set whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
return this;
}
/**
* Get whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public boolean getStartScrollBottom() {
return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
}
/**
* Set whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public WearableExtender setContentIntentAvailableOffline(
boolean contentIntentAvailableOffline) {
setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
return this;
}
/**
* Get whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public boolean getContentIntentAvailableOffline() {
return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
}
/**
* Set a hint that this notification's icon should not be displayed.
* @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintHideIcon(boolean hintHideIcon) {
setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
return this;
}
/**
* Get a hint that this notification's icon should not be displayed.
* @return {@code true} if this icon should not be displayed, false otherwise.
* The default value is {@code false} if this was never set.
*/
public boolean getHintHideIcon() {
return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
}
/**
* Set a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link #addPage}.
*/
public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
return this;
}
/**
* Get a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link NotificationCompat.WearableExtender#addPage}.
*/
public boolean getHintShowBackgroundOnly() {
return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
}
/**
* Set a hint that this notification's background should not be clipped if possible,
* and should instead be resized to fully display on the screen, retaining the aspect
* ratio of the image. This can be useful for images like barcodes or qr codes.
* @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible.
* @return this object for method chaining
*/
public WearableExtender setHintAvoidBackgroundClipping(
boolean hintAvoidBackgroundClipping) {
setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping);
return this;
}
/**
* Get a hint that this notification's background should not be clipped if possible,
* and should instead be resized to fully display on the screen, retaining the aspect
* ratio of the image. This can be useful for images like barcodes or qr codes.
* @return {@code true} if it's ok if the background is clipped on the screen, false
* otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintAvoidBackgroundClipping() {
return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0;
}
/**
* Set a hint that the screen should remain on for at least this duration when
* this notification is displayed on the screen.
* @param timeout The requested screen timeout in milliseconds. Can also be either
* {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
* @return this object for method chaining
*/
public WearableExtender setHintScreenTimeout(int timeout) {
mHintScreenTimeout = timeout;
return this;
}
/**
* Get the duration, in milliseconds, that the screen should remain on for
* when this notification is displayed.
* @return the duration in milliseconds if > 0, or either one of the sentinel values
* {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
*/
public int getHintScreenTimeout() {
return mHintScreenTimeout;
}
/**
* Set a hint that this notification's {@link BigPictureStyle} (if present) should be
* converted to low-bit and displayed in ambient mode, especially useful for barcodes and
* qr codes, as well as other simple black-and-white tickets.
* @param hintAmbientBigPicture {@code true} to enable converstion and ambient.
* @return this object for method chaining
*/
public WearableExtender setHintAmbientBigPicture(boolean hintAmbientBigPicture) {
setFlag(FLAG_BIG_PICTURE_AMBIENT, hintAmbientBigPicture);
return this;
}
/**
* Get a hint that this notification's {@link BigPictureStyle} (if present) should be
* converted to low-bit and displayed in ambient mode, especially useful for barcodes and
* qr codes, as well as other simple black-and-white tickets.
* @return {@code true} if it should be displayed in ambient, false otherwise
* otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintAmbientBigPicture() {
return (mFlags & FLAG_BIG_PICTURE_AMBIENT) != 0;
}
/**
* Set a hint that this notification's content intent will launch an {@link Activity}
* directly, telling the platform that it can generate the appropriate transitions.
* @param hintContentIntentLaunchesActivity {@code true} if the content intent will launch
* an activity and transitions should be generated, false otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintContentIntentLaunchesActivity(
boolean hintContentIntentLaunchesActivity) {
setFlag(FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY, hintContentIntentLaunchesActivity);
return this;
}
/**
* Get a hint that this notification's content intent will launch an {@link Activity}
* directly, telling the platform that it can generate the appropriate transitions
* @return {@code true} if the content intent will launch an activity and transitions should
* be generated, false otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintContentIntentLaunchesActivity() {
return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0;
}
/**
* Sets the dismissal id for this notification. If a notification is posted with a
* dismissal id, then when that notification is canceled, notifications on other wearables
* and the paired Android phone having that same dismissal id will also be canceled. See
* <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to
* Notifications</a> for more information.
* @param dismissalId the dismissal id of the notification.
* @return this object for method chaining
*/
public WearableExtender setDismissalId(String dismissalId) {
mDismissalId = dismissalId;
return this;
}
/**
* Returns the dismissal id of the notification.
* @return the dismissal id of the notification or null if it has not been set.
*/
public String getDismissalId() {
return mDismissalId;
}
/**
* Sets a bridge tag for this notification. A bridge tag can be set for notifications
* posted from a phone to provide finer-grained control on what notifications are bridged
* to wearables. See <a href="{@docRoot}wear/notifications/index.html">Adding Wearable
* Features to Notifications</a> for more information.
* @param bridgeTag the bridge tag of the notification.
* @return this object for method chaining
*/
public WearableExtender setBridgeTag(String bridgeTag) {
mBridgeTag = bridgeTag;
return this;
}
/**
* Returns the bridge tag of the notification.
* @return the bridge tag or null if not present.
*/
public String getBridgeTag() {
return mBridgeTag;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
}
/**
* <p>Helper class to add Android Auto extensions to notifications. To create a notification
* with car extensions:
*
* <ol>
* <li>Create an {@link NotificationCompat.Builder}, setting any desired
* properties.
* <li>Create a {@link CarExtender}.
* <li>Set car-specific properties using the {@code add} and {@code set} methods of
* {@link CarExtender}.
* <li>Call {@link android.support.v4.app.NotificationCompat.Builder#extend(NotificationCompat.Extender)}
* to apply the extensions to a notification.
* <li>Post the notification to the notification system with the
* {@code NotificationManagerCompat.notify(...)} methods and not the
* {@code NotificationManager.notify(...)} methods.
* </ol>
*
* <pre class="prettyprint">
* Notification notification = new NotificationCompat.Builder(context)
* ...
* .extend(new CarExtender()
* .set*(...))
* .build();
* </pre>
*
* <p>Car extensions can be accessed on an existing notification by using the
* {@code CarExtender(Notification)} constructor, and then using the {@code get} methods
* to access values.
*/
public static final class CarExtender implements Extender {
private static final String TAG = "CarExtender";
private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS";
private static final String EXTRA_LARGE_ICON = "large_icon";
private static final String EXTRA_CONVERSATION = "car_conversation";
private static final String EXTRA_COLOR = "app_color";
private Bitmap mLargeIcon;
private UnreadConversation mUnreadConversation;
private int mColor = NotificationCompat.COLOR_DEFAULT;
/**
* Create a {@link CarExtender} with default options.
*/
public CarExtender() {
}
/**
* Create a {@link CarExtender} from the CarExtender options of an existing Notification.
*
* @param notification The notification from which to copy options.
*/
public CarExtender(Notification notification) {
if (Build.VERSION.SDK_INT < 21) {
return;
}
Bundle carBundle = getExtras(notification) == null
? null : getExtras(notification).getBundle(EXTRA_CAR_EXTENDER);
if (carBundle != null) {
mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON);
mColor = carBundle.getInt(EXTRA_COLOR, NotificationCompat.COLOR_DEFAULT);
Bundle b = carBundle.getBundle(EXTRA_CONVERSATION);
mUnreadConversation = (UnreadConversation) IMPL.getUnreadConversationFromBundle(
b, UnreadConversation.FACTORY, RemoteInput.FACTORY);
}
}
/**
* Apply car extensions to a notification that is being built. This is typically called by
* the {@link android.support.v4.app.NotificationCompat.Builder#extend(NotificationCompat.Extender)}
* method of {@link NotificationCompat.Builder}.
*/
@Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
if (Build.VERSION.SDK_INT < 21) {
return builder;
}
Bundle carExtensions = new Bundle();
if (mLargeIcon != null) {
carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
}
if (mColor != NotificationCompat.COLOR_DEFAULT) {
carExtensions.putInt(EXTRA_COLOR, mColor);
}
if (mUnreadConversation != null) {
Bundle b = IMPL.getBundleForUnreadConversation(mUnreadConversation);
carExtensions.putBundle(EXTRA_CONVERSATION, b);
}
builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions);
return builder;
}
/**
* Sets the accent color to use when Android Auto presents the notification.
*
* Android Auto uses the color set with {@link android.support.v4.app.NotificationCompat.Builder#setColor(int)}
* to accent the displayed notification. However, not all colors are acceptable in an
* automotive setting. This method can be used to override the color provided in the
* notification in such a situation.
*/
public CarExtender setColor(@ColorInt int color) {
mColor = color;
return this;
}
/**
* Gets the accent color.
*
* @see #setColor
*/
@ColorInt
public int getColor() {
return mColor;
}
/**
* Sets the large icon of the car notification.
*
* If no large icon is set in the extender, Android Auto will display the icon
* specified by {@link android.support.v4.app.NotificationCompat.Builder#setLargeIcon(android.graphics.Bitmap)}
*
* @param largeIcon The large icon to use in the car notification.
* @return This object for method chaining.
*/
public CarExtender setLargeIcon(Bitmap largeIcon) {
mLargeIcon = largeIcon;
return this;
}
/**
* Gets the large icon used in this car notification, or null if no icon has been set.
*
* @return The large icon for the car notification.
* @see CarExtender#setLargeIcon
*/
public Bitmap getLargeIcon() {
return mLargeIcon;
}
/**
* Sets the unread conversation in a message notification.
*
* @param unreadConversation The unread part of the conversation this notification conveys.
* @return This object for method chaining.
*/
public CarExtender setUnreadConversation(UnreadConversation unreadConversation) {
mUnreadConversation = unreadConversation;
return this;
}
/**
* Returns the unread conversation conveyed by this notification.
* @see #setUnreadConversation(UnreadConversation)
*/
public UnreadConversation getUnreadConversation() {
return mUnreadConversation;
}
/**
* A class which holds the unread messages from a conversation.
*/
public static class UnreadConversation extends NotificationCompatBase.UnreadConversation {
private final String[] mMessages;
private final RemoteInput mRemoteInput;
private final PendingIntent mReplyPendingIntent;
private final PendingIntent mReadPendingIntent;
private final String[] mParticipants;
private final long mLatestTimestamp;
UnreadConversation(String[] messages, RemoteInput remoteInput,
PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
String[] participants, long latestTimestamp) {
mMessages = messages;
mRemoteInput = remoteInput;
mReadPendingIntent = readPendingIntent;
mReplyPendingIntent = replyPendingIntent;
mParticipants = participants;
mLatestTimestamp = latestTimestamp;
}
/**
* Gets the list of messages conveyed by this notification.
*/
@Override
public String[] getMessages() {
return mMessages;
}
/**
* Gets the remote input that will be used to convey the response to a message list, or
* null if no such remote input exists.
*/
@Override
public RemoteInput getRemoteInput() {
return mRemoteInput;
}
/**
* Gets the pending intent that will be triggered when the user replies to this
* notification.
*/
@Override
public PendingIntent getReplyPendingIntent() {
return mReplyPendingIntent;
}
/**
* Gets the pending intent that Android Auto will send after it reads aloud all messages
* in this object's message list.
*/
@Override
public PendingIntent getReadPendingIntent() {
return mReadPendingIntent;
}
/**
* Gets the participants in the conversation.
*/
@Override
public String[] getParticipants() {
return mParticipants;
}
/**
* Gets the firs participant in the conversation.
*/
@Override
public String getParticipant() {
return mParticipants.length > 0 ? mParticipants[0] : null;
}
/**
* Gets the timestamp of the conversation.
*/
@Override
public long getLatestTimestamp() {
return mLatestTimestamp;
}
static final Factory FACTORY = new Factory() {
@Override
public UnreadConversation build(
String[] messages, RemoteInputCompatBase.RemoteInput remoteInput,
PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
String[] participants, long latestTimestamp) {
return new UnreadConversation(
messages, (RemoteInput) remoteInput, replyPendingIntent,
readPendingIntent,
participants, latestTimestamp);
}
};
/**
* Builder class for {@link CarExtender.UnreadConversation} objects.
*/
public static class Builder {
private final List<String> mMessages = new ArrayList<String>();
private final String mParticipant;
private RemoteInput mRemoteInput;
private PendingIntent mReadPendingIntent;
private PendingIntent mReplyPendingIntent;
private long mLatestTimestamp;
/**
* Constructs a new builder for {@link CarExtender.UnreadConversation}.
*
* @param name The name of the other participant in the conversation.
*/
public Builder(String name) {
mParticipant = name;
}
/**
* Appends a new unread message to the list of messages for this conversation.
*
* The messages should be added from oldest to newest.
*
* @param message The text of the new unread message.
* @return This object for method chaining.
*/
public Builder addMessage(String message) {
mMessages.add(message);
return this;
}
/**
* Sets the pending intent and remote input which will convey the reply to this
* notification.
*
* @param pendingIntent The pending intent which will be triggered on a reply.
* @param remoteInput The remote input parcelable which will carry the reply.
* @return This object for method chaining.
*
* @see CarExtender.UnreadConversation#getRemoteInput
* @see CarExtender.UnreadConversation#getReplyPendingIntent
*/
public Builder setReplyAction(
PendingIntent pendingIntent, RemoteInput remoteInput) {
mRemoteInput = remoteInput;
mReplyPendingIntent = pendingIntent;
return this;
}
/**
* Sets the pending intent that will be sent once the messages in this notification
* are read.
*
* @param pendingIntent The pending intent to use.
* @return This object for method chaining.
*/
public Builder setReadPendingIntent(PendingIntent pendingIntent) {
mReadPendingIntent = pendingIntent;
return this;
}
/**
* Sets the timestamp of the most recent message in an unread conversation.
*
* If a messaging notification has been posted by your application and has not
* yet been cancelled, posting a later notification with the same id and tag
* but without a newer timestamp may result in Android Auto not displaying a
* heads up notification for the later notification.
*
* @param timestamp The timestamp of the most recent message in the conversation.
* @return This object for method chaining.
*/
public Builder setLatestTimestamp(long timestamp) {
mLatestTimestamp = timestamp;
return this;
}
/**
* Builds a new unread conversation object.
*
* @return The new unread conversation object.
*/
public UnreadConversation build() {
String[] messages = mMessages.toArray(new String[mMessages.size()]);
String[] participants = { mParticipant };
return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent,
mReadPendingIntent, participants, mLatestTimestamp);
}
}
}
}
/**
* Get an array of Notification objects from a parcelable array bundle field.
* Update the bundle to have a typed array so fetches in the future don't need
* to do an array copy.
*/
static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
Parcelable[] array = bundle.getParcelableArray(key);
if (array instanceof Notification[] || array == null) {
return (Notification[]) array;
}
Notification[] typedArray = new Notification[array.length];
for (int i = 0; i < array.length; i++) {
typedArray[i] = (Notification) array[i];
}
bundle.putParcelableArray(key, typedArray);
return typedArray;
}
/**
* Gets the {@link Notification#extras} field from a notification in a backwards
* compatible manner. Extras field was supported from JellyBean (Api level 16)
* forwards. This function will return null on older api levels.
*/
public static Bundle getExtras(Notification notification) {
if (Build.VERSION.SDK_INT >= 19) {
return notification.extras;
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification);
} else {
return null;
}
}
/**
* Get the number of actions in this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
*/
public static int getActionCount(Notification notification) {
if (Build.VERSION.SDK_INT >= 19) {
return notification.actions != null ? notification.actions.length : 0;
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getActionCount(notification);
} else {
return 0;
}
}
/**
* Get an action on this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
* @param notification The notification to inspect.
* @param actionIndex The index of the action to retrieve.
*/
public static Action getAction(Notification notification, int actionIndex) {
return IMPL.getAction(notification, actionIndex);
}
/**
* Get the category of this notification in a backwards compatible
* manner.
* @param notification The notification to inspect.
*/
public static String getCategory(Notification notification) {
if (Build.VERSION.SDK_INT >= 21) {
return notification.category;
} else {
return null;
}
}
/**
* Get whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* If this hint is set, it is recommend that this notification not be bridged.
*/
public static boolean getLocalOnly(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return (notification.flags & Notification.FLAG_LOCAL_ONLY) != 0;
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getBoolean(NotificationCompatExtras.EXTRA_LOCAL_ONLY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getBoolean(
NotificationCompatExtras.EXTRA_LOCAL_ONLY);
} else {
return false;
}
}
/**
* Get the key used to group this notification into a cluster or stack
* with other notifications on devices which support such rendering.
*/
public static String getGroup(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return notification.getGroup();
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getString(NotificationCompatExtras.EXTRA_GROUP_KEY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getString(
NotificationCompatExtras.EXTRA_GROUP_KEY);
} else {
return null;
}
}
/**
* Get whether this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
* @return Whether this notification is a group summary.
*/
public static boolean isGroupSummary(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return (notification.flags & Notification.FLAG_GROUP_SUMMARY) != 0;
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getBoolean(NotificationCompatExtras.EXTRA_GROUP_SUMMARY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getBoolean(
NotificationCompatExtras.EXTRA_GROUP_SUMMARY);
} else {
return false;
}
}
/**
* Get a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public static String getSortKey(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return notification.getSortKey();
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getString(NotificationCompatExtras.EXTRA_SORT_KEY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getString(
NotificationCompatExtras.EXTRA_SORT_KEY);
} else {
return null;
}
}
/**
* @return the ID of the channel this notification posts to.
*/
public static String getChannelId(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getChannelId();
} else {
return null;
}
}
/** @deprecated removed from API 26 */
@Deprecated
public static String getChannel(Notification notification) {
return getChannelId(notification);
}
/**
* Returns the time at which this notification should be canceled by the system, if it's not
* canceled already.
*/
public static long getTimeoutAfter(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getTimeoutAfter();
} else {
return 0;
}
}
/** @deprecated removed from API 26 */
@Deprecated
public static long getTimeout(Notification notification) {
return getTimeoutAfter(notification);
}
/**
* Returns what icon should be shown for this notification if it is being displayed in a
* Launcher that supports badging. Will be one of {@link #BADGE_ICON_NONE},
* {@link #BADGE_ICON_SMALL}, or {@link #BADGE_ICON_LARGE}.
*/
public static int getBadgeIconType(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getBadgeIconType();
} else {
return BADGE_ICON_NONE;
}
}
/**
* Returns the {@link android.support.v4.content.pm.ShortcutInfoCompat#getId() id} that this
* notification supersedes, if any.
*/
public static String getShortcutId(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getShortcutId();
} else {
return null;
}
}
/**
* Returns which type of notifications in a group are responsible for audibly alerting the
* user. See {@link #GROUP_ALERT_ALL}, {@link #GROUP_ALERT_CHILDREN},
* {@link #GROUP_ALERT_SUMMARY}.
*/
public static int getGroupAlertBehavior(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getGroupAlertBehavior();
} else {
return GROUP_ALERT_ALL;
}
}
}
| compat/java/android/support/v4/app/NotificationCompat.java | /*
* Copyright (C) 2012 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 android.support.v4.app;
import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.annotation.RestrictTo;
import android.support.v4.view.GravityCompat;
import android.view.Gravity;
import android.widget.RemoteViews;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Helper for accessing features in {@link android.app.Notification}
* introduced after API level 4 in a backwards compatible fashion.
*/
public class NotificationCompat {
/**
* Use all default values (where applicable).
*/
public static final int DEFAULT_ALL = ~0;
/**
* Use the default notification sound. This will ignore any sound set using
* {@link Builder#setSound}
*
* <p>
* A notification that is noisy is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_SOUND = 1;
/**
* Use the default notification vibrate. This will ignore any vibrate set using
* {@link Builder#setVibrate}. Using phone vibration requires the
* {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
*
* <p>
* A notification that vibrates is more likely to be presented as a heads-up notification,
* on some platforms.
* </p>
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_VIBRATE = 2;
/**
* Use the default notification lights. This will ignore the
* {@link #FLAG_SHOW_LIGHTS} bit, and values set with {@link Builder#setLights}.
*
* @see Builder#setDefaults
*/
public static final int DEFAULT_LIGHTS = 4;
/**
* Use this constant as the value for audioStreamType to request that
* the default stream type for notifications be used. Currently the
* default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
*/
public static final int STREAM_DEFAULT = -1;
/**
* Bit set in the Notification flags field when LEDs should be turned on
* for this notification.
*/
public static final int FLAG_SHOW_LIGHTS = 0x00000001;
/**
* Bit set in the Notification flags field if this notification is in
* reference to something that is ongoing, like a phone call. It should
* not be set if this notification is in reference to something that
* happened at a particular point in time, like a missed phone call.
*/
public static final int FLAG_ONGOING_EVENT = 0x00000002;
/**
* Bit set in the Notification flags field if
* the audio will be repeated until the notification is
* cancelled or the notification window is opened.
*/
public static final int FLAG_INSISTENT = 0x00000004;
/**
* Bit set in the Notification flags field if the notification's sound,
* vibrate and ticker should only be played if the notification is not already showing.
*/
public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008;
/**
* Bit set in the Notification flags field if the notification should be canceled when
* it is clicked by the user.
*/
public static final int FLAG_AUTO_CANCEL = 0x00000010;
/**
* Bit set in the Notification flags field if the notification should not be canceled
* when the user clicks the Clear all button.
*/
public static final int FLAG_NO_CLEAR = 0x00000020;
/**
* Bit set in the Notification flags field if this notification represents a currently
* running service. This will normally be set for you by
* {@link android.app.Service#startForeground}.
*/
public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
/**
* Obsolete flag indicating high-priority notifications; use the priority field instead.
*
* @deprecated Use {@link NotificationCompat.Builder#setPriority(int)} with a positive value.
*/
@Deprecated
public static final int FLAG_HIGH_PRIORITY = 0x00000080;
/**
* Bit set in the Notification flags field if this notification is relevant to the current
* device only and it is not recommended that it bridge to other devices.
*/
public static final int FLAG_LOCAL_ONLY = 0x00000100;
/**
* Bit set in the Notification flags field if this notification is the group summary for a
* group of notifications. Grouped notifications may display in a cluster or stack on devices
* which support such rendering. Requires a group key also be set using
* {@link Builder#setGroup}.
*/
public static final int FLAG_GROUP_SUMMARY = 0x00000200;
/**
* Default notification priority for {@link NotificationCompat.Builder#setPriority(int)}.
* If your application does not prioritize its own notifications,
* use this value for all notifications.
*/
public static final int PRIORITY_DEFAULT = 0;
/**
* Lower notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for items that are less important. The UI may choose to show
* these items smaller, or at a different position in the list,
* compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_LOW = -1;
/**
* Lowest notification priority for {@link NotificationCompat.Builder#setPriority(int)};
* these items might not be shown to the user except under
* special circumstances, such as detailed notification logs.
*/
public static final int PRIORITY_MIN = -2;
/**
* Higher notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for more important notifications or alerts. The UI may choose
* to show these items larger, or at a different position in
* notification lists, compared with your app's {@link #PRIORITY_DEFAULT} items.
*/
public static final int PRIORITY_HIGH = 1;
/**
* Highest notification priority for {@link NotificationCompat.Builder#setPriority(int)},
* for your application's most important items that require the user's
* prompt attention or input.
*/
public static final int PRIORITY_MAX = 2;
/**
* Notification extras key: this is the title of the notification,
* as supplied to {@link Builder#setContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE = "android.title";
/**
* Notification extras key: this is the title of the notification when shown in expanded form,
* e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
*/
public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
/**
* Notification extras key: this is the main text payload, as supplied to
* {@link Builder#setContentText(CharSequence)}.
*/
public static final String EXTRA_TEXT = "android.text";
/**
* Notification extras key: this is a third line of text, as supplied to
* {@link Builder#setSubText(CharSequence)}.
*/
public static final String EXTRA_SUB_TEXT = "android.subText";
/**
* Notification extras key: this is the remote input history, as supplied to
* {@link Builder#setRemoteInputHistory(CharSequence[])}.
*
* Apps can fill this through {@link Builder#setRemoteInputHistory(CharSequence[])}
* with the most recent inputs that have been sent through a {@link RemoteInput} of this
* Notification and are expected to clear it once the it is no longer relevant (e.g. for chat
* notifications once the other party has responded).
*
* The extra with this key is of type CharSequence[] and contains the most recent entry at
* the 0 index, the second most recent at the 1 index, etc.
*
* @see Builder#setRemoteInputHistory(CharSequence[])
*/
public static final String EXTRA_REMOTE_INPUT_HISTORY = "android.remoteInputHistory";
/**
* Notification extras key: this is a small piece of additional text as supplied to
* {@link Builder#setContentInfo(CharSequence)}.
*/
public static final String EXTRA_INFO_TEXT = "android.infoText";
/**
* Notification extras key: this is a line of summary information intended to be shown
* alongside expanded notifications, as supplied to (e.g.)
* {@link BigTextStyle#setSummaryText(CharSequence)}.
*/
public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
/**
* Notification extras key: this is the longer text shown in the big form of a
* {@link BigTextStyle} notification, as supplied to
* {@link BigTextStyle#bigText(CharSequence)}.
*/
public static final String EXTRA_BIG_TEXT = "android.bigText";
/**
* Notification extras key: this is the resource ID of the notification's main small icon, as
* supplied to {@link Builder#setSmallIcon(int)}.
*/
public static final String EXTRA_SMALL_ICON = "android.icon";
/**
* Notification extras key: this is a bitmap to be used instead of the small icon when showing the
* notification payload, as
* supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON = "android.largeIcon";
/**
* Notification extras key: this is a bitmap to be used instead of the one from
* {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
* shown in its expanded form, as supplied to
* {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
*/
public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
/**
* Notification extras key: this is the progress value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS = "android.progress";
/**
* Notification extras key: this is the maximum value supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
/**
* Notification extras key: whether the progress bar is indeterminate, supplied to
* {@link Builder#setProgress(int, int, boolean)}.
*/
public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown as a count-up timer (specifically a {@link android.widget.Chronometer}) instead
* of a timestamp, as supplied to {@link Builder#setUsesChronometer(boolean)}.
*/
public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
/**
* Notification extras key: whether the when field set using {@link Builder#setWhen} should
* be shown, as supplied to {@link Builder#setShowWhen(boolean)}.
*/
public static final String EXTRA_SHOW_WHEN = "android.showWhen";
/**
* Notification extras key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
* notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
*/
public static final String EXTRA_PICTURE = "android.picture";
/**
* Notification extras key: An array of CharSequences to show in {@link InboxStyle} expanded
* notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
*/
public static final String EXTRA_TEXT_LINES = "android.textLines";
/**
* Notification extras key: A string representing the name of the specific
* {@link android.app.Notification.Style} used to create this notification.
*/
public static final String EXTRA_TEMPLATE = "android.template";
/**
* Notification extras key: A String array containing the people that this
* notification relates to, each of which was supplied to
* {@link Builder#addPerson(String)}.
*/
public static final String EXTRA_PEOPLE = "android.people";
/**
* Notification extras key: A
* {@link android.content.ContentUris content URI} pointing to an image that can be displayed
* in the background when the notification is selected. The URI must point to an image stream
* suitable for passing into
* {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
* BitmapFactory.decodeStream}; all other content types will be ignored. The content provider
* URI used for this purpose must require no permissions to read the image data.
*/
public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
/**
* Notification key: A
* {@link android.media.session.MediaSession.Token} associated with a
* {@link android.app.Notification.MediaStyle} notification.
*/
public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
/**
* Notification extras key: the indices of actions to be shown in the compact view,
* as supplied to (e.g.) {@link Notification.MediaStyle#setShowActionsInCompactView(int...)}.
*/
public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
/**
* Notification key: the username to be displayed for all messages sent by the user
* including
* direct replies
* {@link MessagingStyle} notification.
*/
public static final String EXTRA_SELF_DISPLAY_NAME = "android.selfDisplayName";
/**
* Notification key: a {@link String} to be displayed as the title to a conversation
* represented by a {@link MessagingStyle}
*/
public static final String EXTRA_CONVERSATION_TITLE = "android.conversationTitle";
/**
* Notification key: an array of {@link Bundle} objects representing
* {@link MessagingStyle.Message} objects for a {@link MessagingStyle} notification.
*/
public static final String EXTRA_MESSAGES = "android.messages";
/**
* Keys into the {@link #getExtras} Bundle: the audio contents of this notification.
*
* This is for use when rendering the notification on an audio-focused interface;
* the audio contents are a complete sound sample that contains the contents/body of the
* notification. This may be used in substitute of a Text-to-Speech reading of the
* notification. For example if the notification represents a voice message this should point
* to the audio of that message.
*
* The data stored under this key should be a String representation of a Uri that contains the
* audio contents in one of the following formats: WAV, PCM 16-bit, AMR-WB.
*
* This extra is unnecessary if you are using {@code MessagingStyle} since each {@code Message}
* has a field for holding data URI. That field can be used for audio.
* See {@code Message#setData}.
*
* Example usage:
* <pre>
* {@code
* NotificationCompat.Builder myBuilder = (build your Notification as normal);
* myBuilder.getExtras().putString(EXTRA_AUDIO_CONTENTS_URI, myAudioUri.toString());
* }
* </pre>
*/
public static final String EXTRA_AUDIO_CONTENTS_URI = "android.audioContents";
/**
* Value of {@link Notification#color} equal to 0 (also known as
* {@link android.graphics.Color#TRANSPARENT Color.TRANSPARENT}),
* telling the system not to decorate this notification with any special color but instead use
* default colors when presenting this notification.
*/
@ColorInt
public static final int COLOR_DEFAULT = Color.TRANSPARENT;
/** @hide */
@Retention(SOURCE)
@IntDef({VISIBILITY_PUBLIC, VISIBILITY_PRIVATE, VISIBILITY_SECRET})
public @interface NotificationVisibility {}
/**
* Notification visibility: Show this notification in its entirety on all lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PUBLIC = 1;
/**
* Notification visibility: Show this notification on all lockscreens, but conceal sensitive or
* private information on secure lockscreens.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_PRIVATE = 0;
/**
* Notification visibility: Do not reveal any part of this notification on a secure lockscreen.
*
* {@see android.app.Notification#visibility}
*/
public static final int VISIBILITY_SECRET = -1;
/**
* Notification category: incoming call (voice or video) or similar synchronous communication request.
*/
public static final String CATEGORY_CALL = Notification.CATEGORY_CALL;
/**
* Notification category: incoming direct message (SMS, instant message, etc.).
*/
public static final String CATEGORY_MESSAGE = Notification.CATEGORY_MESSAGE;
/**
* Notification category: asynchronous bulk message (email).
*/
public static final String CATEGORY_EMAIL = Notification.CATEGORY_EMAIL;
/**
* Notification category: calendar event.
*/
public static final String CATEGORY_EVENT = Notification.CATEGORY_EVENT;
/**
* Notification category: promotion or advertisement.
*/
public static final String CATEGORY_PROMO = Notification.CATEGORY_PROMO;
/**
* Notification category: alarm or timer.
*/
public static final String CATEGORY_ALARM = Notification.CATEGORY_ALARM;
/**
* Notification category: progress of a long-running background operation.
*/
public static final String CATEGORY_PROGRESS = Notification.CATEGORY_PROGRESS;
/**
* Notification category: social network or sharing update.
*/
public static final String CATEGORY_SOCIAL = Notification.CATEGORY_SOCIAL;
/**
* Notification category: error in background operation or authentication status.
*/
public static final String CATEGORY_ERROR = Notification.CATEGORY_ERROR;
/**
* Notification category: media transport control for playback.
*/
public static final String CATEGORY_TRANSPORT = Notification.CATEGORY_TRANSPORT;
/**
* Notification category: system or device status update. Reserved for system use.
*/
public static final String CATEGORY_SYSTEM = Notification.CATEGORY_SYSTEM;
/**
* Notification category: indication of running background service.
*/
public static final String CATEGORY_SERVICE = Notification.CATEGORY_SERVICE;
/**
* Notification category: user-scheduled reminder.
*/
public static final String CATEGORY_REMINDER = Notification.CATEGORY_REMINDER;
/**
* Notification category: a specific, timely recommendation for a single thing.
* For example, a news app might want to recommend a news story it believes the user will
* want to read next.
*/
public static final String CATEGORY_RECOMMENDATION =
Notification.CATEGORY_RECOMMENDATION;
/**
* Notification category: ongoing information about device or contextual status.
*/
public static final String CATEGORY_STATUS = Notification.CATEGORY_STATUS;
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@RestrictTo(LIBRARY_GROUP)
@IntDef({BADGE_ICON_NONE, BADGE_ICON_SMALL, BADGE_ICON_LARGE})
public @interface BadgeIconType {}
/**
* If this notification is being shown as a badge, always show as a number.
*/
public static final int BADGE_ICON_NONE = Notification.BADGE_ICON_NONE;
/**
* If this notification is being shown as a badge, use the icon provided to
* {@link Builder#setSmallIcon(int)} to represent this notification.
*/
public static final int BADGE_ICON_SMALL = Notification.BADGE_ICON_SMALL;
/**
* If this notification is being shown as a badge, use the icon provided to
* {@link Builder#setLargeIcon(Bitmap) to represent this notification.
*/
public static final int BADGE_ICON_LARGE = Notification.BADGE_ICON_LARGE;
/**
* Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all notifications in a
* group with sound or vibration ought to make sound or vibrate (respectively), so this
* notification will not be muted when it is in a group.
*/
public static final int GROUP_ALERT_ALL = 0;
/**
* Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all children
* notification in a group should be silenced (no sound or vibration) even if they would
* otherwise make sound or vibrate. Use this constant to mute this notification if this
* notification is a group child.
*
* <p> For example, you might want to use this constant if you post a number of children
* notifications at once (say, after a periodic sync), and only need to notify the user
* audibly once.
*/
public static final int GROUP_ALERT_SUMMARY = 1;
/**
* Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that the summary
* notification in a group should be silenced (no sound or vibration) even if they would
* otherwise make sound or vibrate. Use this constant
* to mute this notification if this notification is a group summary.
*
* <p>For example, you might want to use this constant if only the children notifications
* in your group have content and the summary is only used to visually group notifications.
*/
public static final int GROUP_ALERT_CHILDREN = 2;
static final NotificationCompatImpl IMPL;
interface NotificationCompatImpl {
Notification build(Builder b, BuilderExtender extender);
Action getAction(Notification n, int actionIndex);
Action[] getActionsFromParcelableArrayList(ArrayList<Parcelable> parcelables);
ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions);
Bundle getBundleForUnreadConversation(NotificationCompatBase.UnreadConversation uc);
NotificationCompatBase.UnreadConversation getUnreadConversationFromBundle(
Bundle b, NotificationCompatBase.UnreadConversation.Factory factory,
RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory);
}
/**
* Interface for appcompat to extend v4 builder with media style.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected static class BuilderExtender {
public Notification build(Builder b, NotificationBuilderWithBuilderAccessor builder) {
Notification n = builder.build();
if (b.mContentView != null) {
n.contentView = b.mContentView;
}
return n;
}
}
static class NotificationCompatBaseImpl implements NotificationCompatImpl {
public static class BuilderBase implements NotificationBuilderWithBuilderAccessor {
private Notification.Builder mBuilder;
BuilderBase(Context context, Notification n, CharSequence contentTitle,
CharSequence contentText, CharSequence contentInfo, RemoteViews tickerView,
int number, PendingIntent contentIntent, PendingIntent fullScreenIntent,
Bitmap largeIcon, int progressMax, int progress,
boolean progressIndeterminate) {
mBuilder = new Notification.Builder(context)
.setWhen(n.when)
.setSmallIcon(n.icon, n.iconLevel)
.setContent(n.contentView)
.setTicker(n.tickerText, tickerView)
.setSound(n.sound, n.audioStreamType)
.setVibrate(n.vibrate)
.setLights(n.ledARGB, n.ledOnMS, n.ledOffMS)
.setOngoing((n.flags & Notification.FLAG_ONGOING_EVENT) != 0)
.setOnlyAlertOnce((n.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0)
.setAutoCancel((n.flags & Notification.FLAG_AUTO_CANCEL) != 0)
.setDefaults(n.defaults)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setContentInfo(contentInfo)
.setContentIntent(contentIntent)
.setDeleteIntent(n.deleteIntent)
.setFullScreenIntent(fullScreenIntent,
(n.flags & Notification.FLAG_HIGH_PRIORITY) != 0)
.setLargeIcon(largeIcon)
.setNumber(number)
.setProgress(progressMax, progress, progressIndeterminate);
}
@Override
public Notification.Builder getBuilder() {
return mBuilder;
}
@Override
public Notification build() {
return mBuilder.getNotification();
}
}
@Override
public Notification build(Builder b, BuilderExtender extender) {
BuilderBase builder =
new BuilderBase(b.mContext, b.mNotification,
b.resolveTitle(), b.resolveText(), b.mContentInfo, b.mTickerView,
b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate);
return extender.build(b, builder);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return null;
}
@Override
public Action[] getActionsFromParcelableArrayList(ArrayList<Parcelable> parcelables) {
return null;
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(Action[] actions) {
return null;
}
@Override
public Bundle getBundleForUnreadConversation(NotificationCompatBase.UnreadConversation uc) {
return null;
}
@Override
public NotificationCompatBase.UnreadConversation getUnreadConversationFromBundle(
Bundle b, NotificationCompatBase.UnreadConversation.Factory factory,
RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory) {
return null;
}
}
@RequiresApi(16)
static class NotificationCompatApi16Impl extends NotificationCompatBaseImpl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatJellybean.Builder builder = new NotificationCompatJellybean.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
Bundle extras = getExtras(notification);
if (extras != null) {
b.mStyle.addCompatExtras(extras);
}
}
return notification;
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatJellybean.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatJellybean.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatJellybean.getParcelableArrayListForActions(actions);
}
}
@RequiresApi(19)
static class NotificationCompatApi19Impl extends NotificationCompatApi16Impl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatKitKat.Builder builder = new NotificationCompatKitKat.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly,
b.mPeople, b.mExtras, b.mGroupKey, b.mGroupSummary, b.mSortKey,
b.mContentView, b.mBigContentView);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
return extender.build(b, builder);
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatKitKat.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
}
@RequiresApi(20)
static class NotificationCompatApi20Impl extends NotificationCompatApi19Impl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatApi20.Builder builder = new NotificationCompatApi20.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mPeople, b.mExtras,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
@Override
public Action getAction(Notification n, int actionIndex) {
return (Action) NotificationCompatApi20.getAction(n, actionIndex, Action.FACTORY,
RemoteInput.FACTORY);
}
@Override
public Action[] getActionsFromParcelableArrayList(
ArrayList<Parcelable> parcelables) {
return (Action[]) NotificationCompatApi20.getActionsFromParcelableArrayList(
parcelables, Action.FACTORY, RemoteInput.FACTORY);
}
@Override
public ArrayList<Parcelable> getParcelableArrayListForActions(
Action[] actions) {
return NotificationCompatApi20.getParcelableArrayListForActions(actions);
}
}
@RequiresApi(21)
static class NotificationCompatApi21Impl extends NotificationCompatApi20Impl {
@Override
public Notification build(Builder b, BuilderExtender extender) {
NotificationCompatApi21.Builder builder = new NotificationCompatApi21.Builder(
b.mContext, b.mNotification, b.resolveTitle(), b.resolveText(), b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
b.mHeadsUpContentView, b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderJellybean(builder, b.mStyle);
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
@Override
public Bundle getBundleForUnreadConversation(NotificationCompatBase.UnreadConversation uc) {
return NotificationCompatApi21.getBundleForUnreadConversation(uc);
}
@Override
public NotificationCompatBase.UnreadConversation getUnreadConversationFromBundle(
Bundle b, NotificationCompatBase.UnreadConversation.Factory factory,
RemoteInputCompatBase.RemoteInput.Factory remoteInputFactory) {
return NotificationCompatApi21.getUnreadConversationFromBundle(
b, factory, remoteInputFactory);
}
}
@RequiresApi(24)
static class NotificationCompatApi24Impl extends NotificationCompatApi21Impl {
@Override
public Notification build(Builder b,
BuilderExtender extender) {
NotificationCompatApi24.Builder builder = new NotificationCompatApi24.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mRemoteInputHistory, b.mContentView,
b.mBigContentView, b.mHeadsUpContentView, b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderApi24(builder, b.mStyle);
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
}
@RequiresApi(26)
static class NotificationCompatApi26Impl extends NotificationCompatApi24Impl {
@Override
public Notification build(Builder b,
BuilderExtender extender) {
NotificationCompatApi26.Builder builder = new NotificationCompatApi26.Builder(
b.mContext, b.mNotification, b.mContentTitle, b.mContentText, b.mContentInfo,
b.mTickerView, b.mNumber, b.mContentIntent, b.mFullScreenIntent, b.mLargeIcon,
b.mProgressMax, b.mProgress, b.mProgressIndeterminate, b.mShowWhen,
b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mCategory,
b.mPeople, b.mExtras, b.mColor, b.mVisibility, b.mPublicVersion,
b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mRemoteInputHistory, b.mContentView,
b.mBigContentView, b.mHeadsUpContentView, b.mChannelId, b.mBadgeIcon,
b.mShortcutId, b.mTimeout, b.mColorized, b.mColorizedSet,
b.mGroupAlertBehavior);
addActionsToBuilder(builder, b.mActions);
addStyleToBuilderApi24(builder, b.mStyle);
Notification notification = extender.build(b, builder);
if (b.mStyle != null) {
b.mStyle.addCompatExtras(getExtras(notification));
}
return notification;
}
}
static void addActionsToBuilder(NotificationBuilderWithActions builder,
ArrayList<Action> actions) {
for (Action action : actions) {
builder.addAction(action);
}
}
@RequiresApi(16)
static void addStyleToBuilderJellybean(NotificationBuilderWithBuilderAccessor builder,
Style style) {
if (style != null) {
if (style instanceof BigTextStyle) {
BigTextStyle bigTextStyle = (BigTextStyle) style;
NotificationCompatJellybean.addBigTextStyle(builder,
bigTextStyle.mBigContentTitle,
bigTextStyle.mSummaryTextSet,
bigTextStyle.mSummaryText,
bigTextStyle.mBigText);
} else if (style instanceof InboxStyle) {
InboxStyle inboxStyle = (InboxStyle) style;
NotificationCompatJellybean.addInboxStyle(builder,
inboxStyle.mBigContentTitle,
inboxStyle.mSummaryTextSet,
inboxStyle.mSummaryText,
inboxStyle.mTexts);
} else if (style instanceof BigPictureStyle) {
BigPictureStyle bigPictureStyle = (BigPictureStyle) style;
NotificationCompatJellybean.addBigPictureStyle(builder,
bigPictureStyle.mBigContentTitle,
bigPictureStyle.mSummaryTextSet,
bigPictureStyle.mSummaryText,
bigPictureStyle.mPicture,
bigPictureStyle.mBigLargeIcon,
bigPictureStyle.mBigLargeIconSet);
}
}
}
@RequiresApi(24)
static void addStyleToBuilderApi24(NotificationBuilderWithBuilderAccessor builder,
Style style) {
if (style != null) {
if (style instanceof MessagingStyle) {
MessagingStyle messagingStyle = (MessagingStyle) style;
List<CharSequence> texts = new ArrayList<>();
List<Long> timestamps = new ArrayList<>();
List<CharSequence> senders = new ArrayList<>();
List<String> dataMimeTypes = new ArrayList<>();
List<Uri> dataUris = new ArrayList<>();
for (MessagingStyle.Message message : messagingStyle.mMessages) {
texts.add(message.getText());
timestamps.add(message.getTimestamp());
senders.add(message.getSender());
dataMimeTypes.add(message.getDataMimeType());
dataUris.add(message.getDataUri());
}
NotificationCompatApi24.addMessagingStyle(builder, messagingStyle.mUserDisplayName,
messagingStyle.mConversationTitle, texts, timestamps, senders,
dataMimeTypes, dataUris);
} else {
addStyleToBuilderJellybean(builder, style);
}
}
}
static {
if (Build.VERSION.SDK_INT >= 26) {
IMPL = new NotificationCompatApi26Impl();
} else if (Build.VERSION.SDK_INT >= 24) {
IMPL = new NotificationCompatApi24Impl();
} else if (Build.VERSION.SDK_INT >= 21) {
IMPL = new NotificationCompatApi21Impl();
} else if (Build.VERSION.SDK_INT >= 20) {
IMPL = new NotificationCompatApi20Impl();
} else if (Build.VERSION.SDK_INT >= 19) {
IMPL = new NotificationCompatApi19Impl();
} else if (Build.VERSION.SDK_INT >= 16) {
IMPL = new NotificationCompatApi16Impl();
} else {
IMPL = new NotificationCompatBaseImpl();
}
}
/**
* Builder class for {@link NotificationCompat} objects. Allows easier control over
* all the flags, as well as help constructing the typical notification layouts.
* <p>
* On platform versions that don't offer expanded notifications, methods that depend on
* expanded notifications have no effect.
* </p>
* <p>
* For example, action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later.
* <p>
* For this reason, you should always ensure that UI controls in a notification are also
* available in an {@link android.app.Activity} in your app, and you should always start that
* {@link android.app.Activity} when users click the notification. To do this, use the
* {@link NotificationCompat.Builder#setContentIntent setContentIntent()}
* method.
* </p>
*
*/
public static class Builder {
/**
* Maximum length of CharSequences accepted by Builder and friends.
*
* <p>
* Avoids spamming the system with overly large strings such as full e-mails.
*/
private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024;
// All these variables are declared public/hidden so they can be accessed by a builder
// extender.
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Context mContext;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mContentTitle;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mContentText;
PendingIntent mContentIntent;
PendingIntent mFullScreenIntent;
RemoteViews mTickerView;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Bitmap mLargeIcon;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mContentInfo;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public int mNumber;
int mPriority;
boolean mShowWhen = true;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public boolean mUseChronometer;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Style mStyle;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence mSubText;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public CharSequence[] mRemoteInputHistory;
int mProgressMax;
int mProgress;
boolean mProgressIndeterminate;
String mGroupKey;
boolean mGroupSummary;
String mSortKey;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public ArrayList<Action> mActions = new ArrayList<Action>();
boolean mLocalOnly = false;
boolean mColorized;
boolean mColorizedSet;
String mCategory;
Bundle mExtras;
int mColor = COLOR_DEFAULT;
int mVisibility = VISIBILITY_PRIVATE;
Notification mPublicVersion;
RemoteViews mContentView;
RemoteViews mBigContentView;
RemoteViews mHeadsUpContentView;
String mChannelId;
int mBadgeIcon = BADGE_ICON_NONE;
String mShortcutId;
long mTimeout;
private int mGroupAlertBehavior = GROUP_ALERT_ALL;
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public Notification mNotification = new Notification();
public ArrayList<String> mPeople;
/**
* Constructor.
*
* Automatically sets the when field to {@link System#currentTimeMillis()
* System.currentTimeMillis()} and the audio stream to the
* {@link Notification#STREAM_DEFAULT}.
*
* @param context A {@link Context} that will be used to construct the
* RemoteViews. The Context will not be held past the lifetime of this
* Builder object.
* @param channelId The constructed Notification will be posted on this
* NotificationChannel.
*/
public Builder(@NonNull Context context, @NonNull String channelId) {
mContext = context;
mChannelId = channelId;
// Set defaults to match the defaults of a Notification
mNotification.when = System.currentTimeMillis();
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
mPriority = PRIORITY_DEFAULT;
mPeople = new ArrayList<String>();
}
/**
* @deprecated use
* {@link NotificationCompat.Builder#NotificationCompat.Builder(Context, String)} instead.
* All posted Notifications must specify a NotificationChannel Id.
*/
@Deprecated
public Builder(Context context) {
this(context, null);
}
/**
* Set the time that the event occurred. Notifications in the panel are
* sorted by this time.
*/
public Builder setWhen(long when) {
mNotification.when = when;
return this;
}
/**
* Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
* in the content view.
*/
public Builder setShowWhen(boolean show) {
mShowWhen = show;
return this;
}
/**
* Show the {@link Notification#when} field as a stopwatch.
*
* Instead of presenting <code>when</code> as a timestamp, the notification will show an
* automatically updating display of the minutes and seconds since <code>when</code>.
*
* Useful when showing an elapsed time (like an ongoing phone call).
*
* @see android.widget.Chronometer
* @see Notification#when
*/
public Builder setUsesChronometer(boolean b) {
mUseChronometer = b;
return this;
}
/**
* Set the small icon to use in the notification layouts. Different classes of devices
* may return different sizes. See the UX guidelines for more information on how to
* design these icons.
*
* @param icon A resource ID in the application's package of the drawable to use.
*/
public Builder setSmallIcon(int icon) {
mNotification.icon = icon;
return this;
}
/**
* A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
* level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
* LevelListDrawable}.
*
* @param icon A resource ID in the application's package of the drawable to use.
* @param level The level to use for the icon.
*
* @see android.graphics.drawable.LevelListDrawable
*/
public Builder setSmallIcon(int icon, int level) {
mNotification.icon = icon;
mNotification.iconLevel = level;
return this;
}
/**
* Set the title (first row) of the notification, in a standard notification.
*/
public Builder setContentTitle(CharSequence title) {
mContentTitle = limitCharSequenceLength(title);
return this;
}
/**
* Set the text (second row) of the notification, in a standard notification.
*/
public Builder setContentText(CharSequence text) {
mContentText = limitCharSequenceLength(text);
return this;
}
/**
* Set the third line of text in the platform notification template.
* Don't use if you're also using {@link #setProgress(int, int, boolean)};
* they occupy the same location in the standard template.
* <br>
* If the platform does not provide large-format notifications, this method has no effect.
* The third line of text only appears in expanded view.
* <br>
*/
public Builder setSubText(CharSequence text) {
mSubText = limitCharSequenceLength(text);
return this;
}
/**
* Set the remote input history.
*
* This should be set to the most recent inputs that have been sent
* through a {@link RemoteInput} of this Notification and cleared once the it is no
* longer relevant (e.g. for chat notifications once the other party has responded).
*
* The most recent input must be stored at the 0 index, the second most recent at the
* 1 index, etc. Note that the system will limit both how far back the inputs will be shown
* and how much of each individual input is shown.
*
* <p>Note: The reply text will only be shown on notifications that have least one action
* with a {@code RemoteInput}.</p>
*/
public Builder setRemoteInputHistory(CharSequence[] text) {
mRemoteInputHistory = text;
return this;
}
/**
* Set the large number at the right-hand side of the notification. This is
* equivalent to setContentInfo, although it might show the number in a different
* font size for readability.
*/
public Builder setNumber(int number) {
mNumber = number;
return this;
}
/**
* Set the large text at the right-hand side of the notification.
*/
public Builder setContentInfo(CharSequence info) {
mContentInfo = limitCharSequenceLength(info);
return this;
}
/**
* Set the progress this notification represents, which may be
* represented as a {@link android.widget.ProgressBar}.
*/
public Builder setProgress(int max, int progress, boolean indeterminate) {
mProgressMax = max;
mProgress = progress;
mProgressIndeterminate = indeterminate;
return this;
}
/**
* Supply a custom RemoteViews to use instead of the standard one.
*/
public Builder setContent(RemoteViews views) {
mNotification.contentView = views;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is clicked.
* If you do not supply an intent, you can now add PendingIntents to individual
* views to be launched when clicked by calling {@link RemoteViews#setOnClickPendingIntent
* RemoteViews.setOnClickPendingIntent(int,PendingIntent)}. Be sure to
* read {@link Notification#contentIntent Notification.contentIntent} for
* how to correctly use this.
*/
public Builder setContentIntent(PendingIntent intent) {
mContentIntent = intent;
return this;
}
/**
* Supply a {@link PendingIntent} to send when the notification is cleared by the user
* directly from the notification panel. For example, this intent is sent when the user
* clicks the "Clear all" button, or the individual "X" buttons on notifications. This
* intent is not sent when the application calls
* {@link android.app.NotificationManager#cancel NotificationManager.cancel(int)}.
*/
public Builder setDeleteIntent(PendingIntent intent) {
mNotification.deleteIntent = intent;
return this;
}
/**
* An intent to launch instead of posting the notification to the status bar.
* Only for use with extremely high-priority notifications demanding the user's
* <strong>immediate</strong> attention, such as an incoming phone call or
* alarm clock that the user has explicitly set to a particular time.
* If this facility is used for something else, please give the user an option
* to turn it off and use a normal notification, as this can be extremely
* disruptive.
*
* <p>
* On some platforms, the system UI may choose to display a heads-up notification,
* instead of launching this intent, while the user is using the device.
* </p>
*
* @param intent The pending intent to launch.
* @param highPriority Passing true will cause this notification to be sent
* even if other notifications are suppressed.
*/
public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
mFullScreenIntent = intent;
setFlag(FLAG_HIGH_PRIORITY, highPriority);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives.
*/
public Builder setTicker(CharSequence tickerText) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
return this;
}
/**
* Set the text that is displayed in the status bar when the notification first
* arrives, and also a RemoteViews object that may be displayed instead on some
* devices.
*/
public Builder setTicker(CharSequence tickerText, RemoteViews views) {
mNotification.tickerText = limitCharSequenceLength(tickerText);
mTickerView = views;
return this;
}
/**
* Set the large icon that is shown in the ticker and notification.
*/
public Builder setLargeIcon(Bitmap icon) {
mLargeIcon = icon;
return this;
}
/**
* Set the sound to play. It will play on the default stream.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*/
public Builder setSound(Uri sound) {
mNotification.sound = sound;
mNotification.audioStreamType = Notification.STREAM_DEFAULT;
return this;
}
/**
* Set the sound to play. It will play on the stream you supply.
*
* <p>
* On some platforms, a notification that is noisy is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see Notification#STREAM_DEFAULT
* @see AudioManager for the <code>STREAM_</code> constants.
*/
public Builder setSound(Uri sound, int streamType) {
mNotification.sound = sound;
mNotification.audioStreamType = streamType;
return this;
}
/**
* Set the vibration pattern to use.
*
* <p>
* On some platforms, a notification that vibrates is more likely to be presented
* as a heads-up notification.
* </p>
*
* @see android.os.Vibrator for a discussion of the <code>pattern</code>
* parameter.
*/
public Builder setVibrate(long[] pattern) {
mNotification.vibrate = pattern;
return this;
}
/**
* Set the argb value that you would like the LED on the device to blink, as well as the
* rate. The rate is specified in terms of the number of milliseconds to be on
* and then the number of milliseconds to be off.
*/
public Builder setLights(@ColorInt int argb, int onMs, int offMs) {
mNotification.ledARGB = argb;
mNotification.ledOnMS = onMs;
mNotification.ledOffMS = offMs;
boolean showLights = mNotification.ledOnMS != 0 && mNotification.ledOffMS != 0;
mNotification.flags = (mNotification.flags & ~Notification.FLAG_SHOW_LIGHTS) |
(showLights ? Notification.FLAG_SHOW_LIGHTS : 0);
return this;
}
/**
* Set whether this is an ongoing notification.
*
* <p>Ongoing notifications differ from regular notifications in the following ways:
* <ul>
* <li>Ongoing notifications are sorted above the regular notifications in the
* notification panel.</li>
* <li>Ongoing notifications do not have an 'X' close button, and are not affected
* by the "Clear all" button.
* </ul>
*/
public Builder setOngoing(boolean ongoing) {
setFlag(Notification.FLAG_ONGOING_EVENT, ongoing);
return this;
}
/**
* Set whether this notification should be colorized. When set, the color set with
* {@link #setColor(int)} will be used as the background color of this notification.
* <p>
* This should only be used for high priority ongoing tasks like navigation, an ongoing
* call, or other similarly high-priority events for the user.
* <p>
* For most styles, the coloring will only be applied if the notification is for a
* foreground service notification.
* <p>
* However, for MediaStyle and DecoratedMediaCustomViewStyle notifications
* that have a media session attached there is no such requirement.
* <p>
* Calling this method on any version prior to {@link android.os.Build.VERSION_CODES#O} will
* not have an effect on the notification and it won't be colorized.
*
* @see #setColor(int)
*/
public Builder setColorized(boolean colorize) {
mColorized = colorize;
mColorizedSet = true;
return this;
}
/**
* Set this flag if you would only like the sound, vibrate
* and ticker to be played if the notification is not already showing.
*/
public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
setFlag(Notification.FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
return this;
}
/**
* Setting this flag will make it so the notification is automatically
* canceled when the user clicks it in the panel. The PendingIntent
* set with {@link #setDeleteIntent} will be broadcast when the notification
* is canceled.
*/
public Builder setAutoCancel(boolean autoCancel) {
setFlag(Notification.FLAG_AUTO_CANCEL, autoCancel);
return this;
}
/**
* Set whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* This hint can be set to recommend this notification not be bridged.
*/
public Builder setLocalOnly(boolean b) {
mLocalOnly = b;
return this;
}
/**
* Set the notification category.
*
* <p>Must be one of the predefined notification categories (see the <code>CATEGORY_*</code>
* constants in {@link Notification}) that best describes this notification.
* May be used by the system for ranking and filtering.
*/
public Builder setCategory(String category) {
mCategory = category;
return this;
}
/**
* Set the default notification options that will be used.
* <p>
* The value should be one or more of the following fields combined with
* bitwise-or:
* {@link Notification#DEFAULT_SOUND}, {@link Notification#DEFAULT_VIBRATE},
* {@link Notification#DEFAULT_LIGHTS}.
* <p>
* For all default values, use {@link Notification#DEFAULT_ALL}.
*/
public Builder setDefaults(int defaults) {
mNotification.defaults = defaults;
if ((defaults & Notification.DEFAULT_LIGHTS) != 0) {
mNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
}
return this;
}
private void setFlag(int mask, boolean value) {
if (value) {
mNotification.flags |= mask;
} else {
mNotification.flags &= ~mask;
}
}
/**
* Set the relative priority for this notification.
*
* Priority is an indication of how much of the user's
* valuable attention should be consumed by this
* notification. Low-priority notifications may be hidden from
* the user in certain situations, while the user might be
* interrupted for a higher-priority notification.
* The system sets a notification's priority based on various factors including the
* setPriority value. The effect may differ slightly on different platforms.
*
* @param pri Relative priority for this notification. Must be one of
* the priority constants defined by {@link NotificationCompat}.
* Acceptable values range from {@link
* NotificationCompat#PRIORITY_MIN} (-2) to {@link
* NotificationCompat#PRIORITY_MAX} (2).
*/
public Builder setPriority(int pri) {
mPriority = pri;
return this;
}
/**
* Add a person that is relevant to this notification.
*
* <P>
* Depending on user preferences, this annotation may allow the notification to pass
* through interruption filters, and to appear more prominently in the user interface.
* </P>
*
* <P>
* The person should be specified by the {@code String} representation of a
* {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}.
* </P>
*
* <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema
* URIs. The path part of these URIs must exist in the contacts database, in the
* appropriate column, or the reference will be discarded as invalid. Telephone schema
* URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}.
* </P>
*
* @param uri A URI for the person.
* @see Notification#EXTRA_PEOPLE
*/
public Builder addPerson(String uri) {
mPeople.add(uri);
return this;
}
/**
* Set this notification to be part of a group of notifications sharing the same key.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering.
*
* <p>To make this notification the summary for its group, also call
* {@link #setGroupSummary}. A sort order can be specified for group members by using
* {@link #setSortKey}.
* @param groupKey The group key of the group.
* @return this object for method chaining
*/
public Builder setGroup(String groupKey) {
mGroupKey = groupKey;
return this;
}
/**
* Set this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link #setGroup}.
* @param isGroupSummary Whether this notification should be a group summary.
* @return this object for method chaining
*/
public Builder setGroupSummary(boolean isGroupSummary) {
mGroupSummary = isGroupSummary;
return this;
}
/**
* Set a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public Builder setSortKey(String sortKey) {
mSortKey = sortKey;
return this;
}
/**
* Merge additional metadata into this notification.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see Notification#extras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
if (mExtras == null) {
mExtras = new Bundle(extras);
} else {
mExtras.putAll(extras);
}
}
return this;
}
/**
* Set metadata for this notification.
*
* <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
* current contents are copied into the Notification each time {@link #build()} is
* called.
*
* <p>Replaces any existing extras values with those from the provided Bundle.
* Use {@link #addExtras} to merge in metadata instead.
*
* @see Notification#extras
*/
public Builder setExtras(Bundle extras) {
mExtras = extras;
return this;
}
/**
* Get the current metadata Bundle used by this notification Builder.
*
* <p>The returned Bundle is shared with this Builder.
*
* <p>The current contents of this Bundle are copied into the Notification each time
* {@link #build()} is called.
*
* @see Notification#extras
*/
public Bundle getExtras() {
if (mExtras == null) {
mExtras = new Bundle();
}
return mExtras;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param icon Resource ID of a drawable that represents the action.
* @param title Text describing the action.
* @param intent {@link android.app.PendingIntent} to be fired when the action is invoked.
*/
public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
mActions.add(new Action(icon, title, intent));
return this;
}
/**
* Add an action to this notification. Actions are typically displayed by
* the system as a button adjacent to the notification content.
* <br>
* Action buttons won't appear on platforms prior to Android 4.1. Action
* buttons depend on expanded notifications, which are only available in Android 4.1
* and later. To ensure that an action button's functionality is always available, first
* implement the functionality in the {@link android.app.Activity} that starts when a user
* clicks the notification (see {@link #setContentIntent setContentIntent()}), and then
* enhance the notification by implementing the same functionality with
* {@link #addAction addAction()}.
*
* @param action The action to add.
*/
public Builder addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Add a rich notification style to be applied at build time.
* <br>
* If the platform does not provide rich notification styles, this method has no effect. The
* user will always see the normal notification style.
*
* @param style Object responsible for modifying the notification style.
*/
public Builder setStyle(Style style) {
if (mStyle != style) {
mStyle = style;
if (mStyle != null) {
mStyle.setBuilder(this);
}
}
return this;
}
/**
* Sets {@link Notification#color}.
*
* @param argb The accent color to use
*
* @return The same Builder.
*/
public Builder setColor(@ColorInt int argb) {
mColor = argb;
return this;
}
/**
* Sets {@link Notification#visibility}.
*
* @param visibility One of {@link Notification#VISIBILITY_PRIVATE} (the default),
* {@link Notification#VISIBILITY_PUBLIC}, or
* {@link Notification#VISIBILITY_SECRET}.
*/
public Builder setVisibility(@NotificationVisibility int visibility) {
mVisibility = visibility;
return this;
}
/**
* Supply a replacement Notification whose contents should be shown in insecure contexts
* (i.e. atop the secure lockscreen). See {@link Notification#visibility} and
* {@link #VISIBILITY_PUBLIC}.
*
* @param n A replacement notification, presumably with some or all info redacted.
* @return The same Builder.
*/
public Builder setPublicVersion(Notification n) {
mPublicVersion = n;
return this;
}
/**
* Supply custom RemoteViews to use instead of the platform template.
*
* This will override the layout that would otherwise be constructed by this Builder
* object.
*/
public Builder setCustomContentView(RemoteViews contentView) {
mContentView = contentView;
return this;
}
/**
* Supply custom RemoteViews to use instead of the platform template in the expanded form.
*
* This will override the expanded layout that would otherwise be constructed by this
* Builder object.
*
* No-op on versions prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.
*/
public Builder setCustomBigContentView(RemoteViews contentView) {
mBigContentView = contentView;
return this;
}
/**
* Supply custom RemoteViews to use instead of the platform template in the heads up dialog.
*
* This will override the heads-up layout that would otherwise be constructed by this
* Builder object.
*
* No-op on versions prior to {@link android.os.Build.VERSION_CODES#LOLLIPOP}.
*/
public Builder setCustomHeadsUpContentView(RemoteViews contentView) {
mHeadsUpContentView = contentView;
return this;
}
/**
* Specifies the channel the notification should be delivered on.
*
* No-op on versions prior to {@link android.os.Build.VERSION_CODES#O} .
*/
public Builder setChannelId(@NonNull String channelId) {
mChannelId = channelId;
return this;
}
/** @deprecated removed from API 26 */
@Deprecated
public Builder setChannel(@NonNull String channelId) {
return setChannelId(channelId);
}
/**
* Specifies the time at which this notification should be canceled, if it is not already
* canceled.
*/
public Builder setTimeoutAfter(long durationMs) {
mTimeout = durationMs;
return this;
}
/** @deprecated removed from API 26 */
@Deprecated
public Builder setTimeout(long durationMs) {
return setTimeoutAfter(durationMs);
}
/**
* If this notification is duplicative of a Launcher shortcut, sets the
* {@link android.support.v4.content.pm.ShortcutInfoCompat#getId() id} of the shortcut, in
* case the Launcher wants to hide the shortcut.
*
* <p><strong>Note:</strong>This field will be ignored by Launchers that don't support
* badging or {@link android.support.v4.content.pm.ShortcutManagerCompat shortcuts}.
*
* @param shortcutId the {@link android.support.v4.content.pm.ShortcutInfoCompat#getId() id}
* of the shortcut this notification supersedes
*/
public Builder setShortcutId(String shortcutId) {
mShortcutId = shortcutId;
return this;
}
/**
* Sets which icon to display as a badge for this notification.
*
* <p>Must be one of {@link #BADGE_ICON_NONE}, {@link #BADGE_ICON_SMALL},
* {@link #BADGE_ICON_LARGE}.
*
* <p><strong>Note:</strong> This value might be ignored, for launchers that don't support
* badge icons.
*/
public Builder setBadgeIconType(@BadgeIconType int icon) {
mBadgeIcon = icon;
return this;
}
/**
* Sets the group alert behavior for this notification. Use this method to mute this
* notification if alerts for this notification's group should be handled by a different
* notification. This is only applicable for notifications that belong to a
* {@link #setGroup(String) group}.
*
* <p> The default value is {@link #GROUP_ALERT_ALL}.</p>
*/
public Builder setGroupAlertBehavior(int groupAlertBehavior) {
mGroupAlertBehavior = groupAlertBehavior;
return this;
}
/**
* Apply an extender to this notification builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* @deprecated Use {@link #build()} instead.
*/
@Deprecated
public Notification getNotification() {
return build();
}
/**
* Combine all of the options that have been set and return a new {@link Notification}
* object.
*/
public Notification build() {
return IMPL.build(this, getExtender());
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected BuilderExtender getExtender() {
return new BuilderExtender();
}
protected static CharSequence limitCharSequenceLength(CharSequence cs) {
if (cs == null) return cs;
if (cs.length() > MAX_CHARSEQUENCE_LENGTH) {
cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH);
}
return cs;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public RemoteViews getContentView() {
return mContentView;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public RemoteViews getBigContentView() {
return mBigContentView;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public RemoteViews getHeadsUpContentView() {
return mHeadsUpContentView;
}
/**
* return when if it is showing or 0 otherwise
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public long getWhenIfShowing() {
return mShowWhen ? mNotification.when : 0;
}
/**
* @return the priority set on the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public int getPriority() {
return mPriority;
}
/**
* @return the color of the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
public int getColor() {
return mColor;
}
/**
* @return the text of the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected CharSequence resolveText() {
return mContentText;
}
/**
* @return the title of the notification
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
protected CharSequence resolveTitle() {
return mContentTitle;
}
}
/**
* An object that can apply a rich notification style to a {@link Notification.Builder}
* object.
* <br>
* If the platform does not provide rich notification styles, methods in this class have no
* effect.
*/
public static abstract class Style {
Builder mBuilder;
CharSequence mBigContentTitle;
CharSequence mSummaryText;
boolean mSummaryTextSet = false;
public void setBuilder(Builder builder) {
if (mBuilder != builder) {
mBuilder = builder;
if (mBuilder != null) {
mBuilder.setStyle(this);
}
}
}
public Notification build() {
Notification notification = null;
if (mBuilder != null) {
notification = mBuilder.build();
}
return notification;
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
// TODO: implement for all styles
public void addCompatExtras(Bundle extras) {
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
// TODO: implement for all styles
protected void restoreFromCompatExtras(Bundle extras) {
}
}
/**
* Helper class for generating large-format notifications that include a large image attachment.
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notification = new Notification.Builder(mContext)
* .setContentTitle("New photo from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_post)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigPictureStyle()
* .bigPicture(aBigBitmap))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigPictureStyle extends Style {
Bitmap mPicture;
Bitmap mBigLargeIcon;
boolean mBigLargeIconSet;
public BigPictureStyle() {
}
public BigPictureStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigPictureStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigPictureStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the bitmap to be used as the payload for the BigPicture notification.
*/
public BigPictureStyle bigPicture(Bitmap b) {
mPicture = b;
return this;
}
/**
* Override the large icon when the big notification is shown.
*/
public BigPictureStyle bigLargeIcon(Bitmap b) {
mBigLargeIcon = b;
mBigLargeIconSet = true;
return this;
}
}
/**
* Helper class for generating large-format notifications that include a lot of text.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notification = new Notification.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.BigTextStyle()
* .bigText(aVeryLongString))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class BigTextStyle extends Style {
CharSequence mBigText;
public BigTextStyle() {
}
public BigTextStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public BigTextStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public BigTextStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Provide the longer text to be displayed in the big form of the
* template in place of the content text.
*/
public BigTextStyle bigText(CharSequence cs) {
mBigText = Builder.limitCharSequenceLength(cs);
return this;
}
}
/**
* Helper class for generating large-format notifications that include multiple back-and-forth
* messages of varying types between any number of people.
*
* <br>
* In order to get a backwards compatible behavior, the app needs to use the v7 version of the
* notification builder together with this style, otherwise the user will see the normal
* notification view.
*
* <br>
* Use {@link MessagingStyle#setConversationTitle(CharSequence)} to set a conversation title for
* group chats with more than two people. This could be the user-created name of the group or,
* if it doesn't have a specific name, a list of the participants in the conversation. Do not
* set a conversation title for one-on-one chats, since platforms use the existence of this
* field as a hint that the conversation is a group.
*
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like
* so:
* <pre class="prettyprint">
*
* Notification notification = new Notification.Builder()
* .setContentTitle("2 new messages with " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_message)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.MessagingStyle(resources.getString(R.string.reply_name))
* .addMessage(messages[0].getText(), messages[0].getTime(), messages[0].getSender())
* .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getSender()))
* .build();
* </pre>
*/
public static class MessagingStyle extends Style {
/**
* The maximum number of messages that will be retained in the Notification itself (the
* number displayed is up to the platform).
*/
public static final int MAXIMUM_RETAINED_MESSAGES = 25;
CharSequence mUserDisplayName;
CharSequence mConversationTitle;
List<Message> mMessages = new ArrayList<>();
MessagingStyle() {
}
/**
* @param userDisplayName Required - the name to be displayed for any replies sent by the
* user before the posting app reposts the notification with those messages after they've
* been actually sent and in previous messages sent by the user added in
* {@link #addMessage(Message)}
*/
public MessagingStyle(@NonNull CharSequence userDisplayName) {
mUserDisplayName = userDisplayName;
}
/**
* Returns the name to be displayed for any replies sent by the user
*/
public CharSequence getUserDisplayName() {
return mUserDisplayName;
}
/**
* Sets the title to be displayed on this conversation. This should only be used for
* group messaging and left unset for one-on-one conversations.
* @param conversationTitle Title displayed for this conversation.
* @return this object for method chaining.
*/
public MessagingStyle setConversationTitle(CharSequence conversationTitle) {
mConversationTitle = conversationTitle;
return this;
}
/**
* Return the title to be displayed on this conversation. Can be <code>null</code> and
* should be for one-on-one conversations
*/
public CharSequence getConversationTitle() {
return mConversationTitle;
}
/**
* Adds a message for display by this notification. Convenience call for a simple
* {@link Message} in {@link #addMessage(Message)}
* @param text A {@link CharSequence} to be displayed as the message content
* @param timestamp Time at which the message arrived
* @param sender A {@link CharSequence} to be used for displaying the name of the
* sender. Should be <code>null</code> for messages by the current user, in which case
* the platform will insert {@link #getUserDisplayName()}.
* Should be unique amongst all individuals in the conversation, and should be
* consistent during re-posts of the notification.
*
* @see Message#Message(CharSequence, long, CharSequence)
*
* @return this object for method chaining
*/
public MessagingStyle addMessage(CharSequence text, long timestamp, CharSequence sender) {
mMessages.add(new Message(text, timestamp, sender));
if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
mMessages.remove(0);
}
return this;
}
/**
* Adds a {@link Message} for display in this notification.
* @param message The {@link Message} to be displayed
* @return this object for method chaining
*/
public MessagingStyle addMessage(Message message) {
mMessages.add(message);
if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
mMessages.remove(0);
}
return this;
}
/**
* Gets the list of {@code Message} objects that represent the notification
*/
public List<Message> getMessages() {
return mMessages;
}
/**
* Retrieves a {@link MessagingStyle} from a {@link Notification}, enabling an application
* that has set a {@link MessagingStyle} using {@link NotificationCompat} or
* {@link android.app.Notification.Builder} to send messaging information to another
* application using {@link NotificationCompat}, regardless of the API level of the system.
* Returns {@code null} if there is no {@link MessagingStyle} set.
*/
public static MessagingStyle extractMessagingStyleFromNotification(
Notification notification) {
MessagingStyle style;
Bundle extras = NotificationCompat.getExtras(notification);
if (extras != null && !extras.containsKey(EXTRA_SELF_DISPLAY_NAME)) {
style = null;
} else {
try {
style = new MessagingStyle();
style.restoreFromCompatExtras(extras);
} catch (ClassCastException e) {
style = null;
}
}
return style;
}
@Override
public void addCompatExtras(Bundle extras) {
super.addCompatExtras(extras);
if (mUserDisplayName != null) {
extras.putCharSequence(EXTRA_SELF_DISPLAY_NAME, mUserDisplayName);
}
if (mConversationTitle != null) {
extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle);
}
if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES,
Message.getBundleArrayForMessages(mMessages));
}
}
/**
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
protected void restoreFromCompatExtras(Bundle extras) {
mMessages.clear();
mUserDisplayName = extras.getString(EXTRA_SELF_DISPLAY_NAME);
mConversationTitle = extras.getString(EXTRA_CONVERSATION_TITLE);
Parcelable[] parcelables = extras.getParcelableArray(EXTRA_MESSAGES);
if (parcelables != null) {
mMessages = Message.getMessagesFromBundleArray(parcelables);
}
}
public static final class Message {
static final String KEY_TEXT = "text";
static final String KEY_TIMESTAMP = "time";
static final String KEY_SENDER = "sender";
static final String KEY_DATA_MIME_TYPE = "type";
static final String KEY_DATA_URI= "uri";
static final String KEY_EXTRAS_BUNDLE = "extras";
private final CharSequence mText;
private final long mTimestamp;
private final CharSequence mSender;
private Bundle mExtras = new Bundle();
private String mDataMimeType;
private Uri mDataUri;
/**
* Constructor
* @param text A {@link CharSequence} to be displayed as the message content
* @param timestamp Time at which the message arrived
* @param sender A {@link CharSequence} to be used for displaying the name of the
* sender. Should be <code>null</code> for messages by the current user, in which case
* the platform will insert {@link MessagingStyle#getUserDisplayName()}.
* Should be unique amongst all individuals in the conversation, and should be
* consistent during re-posts of the notification.
*/
public Message(CharSequence text, long timestamp, CharSequence sender){
mText = text;
mTimestamp = timestamp;
mSender = sender;
}
/**
* Sets a binary blob of data and an associated MIME type for a message. In the case
* where the platform doesn't support the MIME type, the original text provided in the
* constructor will be used.
* @param dataMimeType The MIME type of the content. See
* <a href="{@docRoot}notifications/messaging.html"> for the list of supported MIME
* types on Android and Android Wear.
* @param dataUri The uri containing the content whose type is given by the MIME type.
* <p class="note">
* <ol>
* <li>Notification Listeners including the System UI need permission to access the
* data the Uri points to. The recommended ways to do this are:</li>
* <li>Store the data in your own ContentProvider, making sure that other apps have
* the correct permission to access your provider. The preferred mechanism for
* providing access is to use per-URI permissions which are temporary and only
* grant access to the receiving application. An easy way to create a
* ContentProvider like this is to use the FileProvider helper class.</li>
* <li>Use the system MediaStore. The MediaStore is primarily aimed at video, audio
* and image MIME types, however beginning with Android 3.0 (API level 11) it can
* also store non-media types (see MediaStore.Files for more info). Files can be
* inserted into the MediaStore using scanFile() after which a content:// style
* Uri suitable for sharing is passed to the provided onScanCompleted() callback.
* Note that once added to the system MediaStore the content is accessible to any
* app on the device.</li>
* </ol>
* @return this object for method chaining
*/
public Message setData(String dataMimeType, Uri dataUri) {
mDataMimeType = dataMimeType;
mDataUri = dataUri;
return this;
}
/**
* Get the text to be used for this message, or the fallback text if a type and content
* Uri have been set
*/
public CharSequence getText() {
return mText;
}
/**
* Get the time at which this message arrived
*/
public long getTimestamp() {
return mTimestamp;
}
/**
* Get the extras Bundle for this message.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Get the text used to display the contact's name in the messaging experience
*/
public CharSequence getSender() {
return mSender;
}
/**
* Get the MIME type of the data pointed to by the Uri
*/
public String getDataMimeType() {
return mDataMimeType;
}
/**
* Get the the Uri pointing to the content of the message. Can be null, in which case
* {@see #getText()} is used.
*/
public Uri getDataUri() {
return mDataUri;
}
private Bundle toBundle() {
Bundle bundle = new Bundle();
if (mText != null) {
bundle.putCharSequence(KEY_TEXT, mText);
}
bundle.putLong(KEY_TIMESTAMP, mTimestamp);
if (mSender != null) {
bundle.putCharSequence(KEY_SENDER, mSender);
}
if (mDataMimeType != null) {
bundle.putString(KEY_DATA_MIME_TYPE, mDataMimeType);
}
if (mDataUri != null) {
bundle.putParcelable(KEY_DATA_URI, mDataUri);
}
if (mExtras != null) {
bundle.putBundle(KEY_EXTRAS_BUNDLE, mExtras);
}
return bundle;
}
static Bundle[] getBundleArrayForMessages(List<Message> messages) {
Bundle[] bundles = new Bundle[messages.size()];
final int N = messages.size();
for (int i = 0; i < N; i++) {
bundles[i] = messages.get(i).toBundle();
}
return bundles;
}
static List<Message> getMessagesFromBundleArray(Parcelable[] bundles) {
List<Message> messages = new ArrayList<>(bundles.length);
for (int i = 0; i < bundles.length; i++) {
if (bundles[i] instanceof Bundle) {
Message message = getMessageFromBundle((Bundle)bundles[i]);
if (message != null) {
messages.add(message);
}
}
}
return messages;
}
static Message getMessageFromBundle(Bundle bundle) {
try {
if (!bundle.containsKey(KEY_TEXT) || !bundle.containsKey(KEY_TIMESTAMP)) {
return null;
} else {
Message message = new Message(bundle.getCharSequence(KEY_TEXT),
bundle.getLong(KEY_TIMESTAMP), bundle.getCharSequence(KEY_SENDER));
if (bundle.containsKey(KEY_DATA_MIME_TYPE) &&
bundle.containsKey(KEY_DATA_URI)) {
message.setData(bundle.getString(KEY_DATA_MIME_TYPE),
(Uri) bundle.getParcelable(KEY_DATA_URI));
}
if (bundle.containsKey(KEY_EXTRAS_BUNDLE)) {
message.getExtras().putAll(bundle.getBundle(KEY_EXTRAS_BUNDLE));
}
return message;
}
} catch (ClassCastException e) {
return null;
}
}
}
}
/**
* Helper class for generating large-format notifications that include a list of (up to 5) strings.
*
* <br>
* If the platform does not provide large-format notifications, this method has no effect. The
* user will always see the normal notification view.
* <br>
* This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like so:
* <pre class="prettyprint">
* Notification notification = new Notification.Builder()
* .setContentTitle("5 New mails from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .setLargeIcon(aBitmap)
* .setStyle(new Notification.InboxStyle()
* .addLine(str1)
* .addLine(str2)
* .setContentTitle("")
* .setSummaryText("+3 more"))
* .build();
* </pre>
*
* @see Notification#bigContentView
*/
public static class InboxStyle extends Style {
ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
public InboxStyle() {
}
public InboxStyle(Builder builder) {
setBuilder(builder);
}
/**
* Overrides ContentTitle in the big form of the template.
* This defaults to the value passed to setContentTitle().
*/
public InboxStyle setBigContentTitle(CharSequence title) {
mBigContentTitle = Builder.limitCharSequenceLength(title);
return this;
}
/**
* Set the first line of text after the detail section in the big form of the template.
*/
public InboxStyle setSummaryText(CharSequence cs) {
mSummaryText = Builder.limitCharSequenceLength(cs);
mSummaryTextSet = true;
return this;
}
/**
* Append a line to the digest section of the Inbox notification.
*/
public InboxStyle addLine(CharSequence cs) {
mTexts.add(Builder.limitCharSequenceLength(cs));
return this;
}
}
/**
* Structure to encapsulate a named action that can be shown as part of this notification.
* It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
* selected by the user. Action buttons won't appear on platforms prior to Android 4.1.
* <p>
* Apps should use {@link NotificationCompat.Builder#addAction(int, CharSequence, PendingIntent)}
* or {@link NotificationCompat.Builder#addAction(NotificationCompat.Action)}
* to attach actions.
*/
public static class Action extends NotificationCompatBase.Action {
final Bundle mExtras;
private final RemoteInput[] mRemoteInputs;
/**
* Holds {@link RemoteInput}s that only accept data, meaning
* {@link RemoteInput#getAllowFreeFormInput} is false, {@link RemoteInput#getChoices}
* is null or empty, and {@link RemoteInput#getAllowedDataTypes is non-null and not
* empty. These {@link RemoteInput}s will be ignored by devices that do not
* support non-text-based {@link RemoteInput}s. See {@link Builder#build}.
*
* You can test if a RemoteInput matches these constraints using
* {@link RemoteInput#isDataOnly}.
*/
private final RemoteInput[] mDataOnlyRemoteInputs;
private boolean mAllowGeneratedReplies;
/**
* Small icon representing the action.
*/
public int icon;
/**
* Title of the action.
*/
public CharSequence title;
/**
* Intent to send when the user invokes this action. May be null, in which case the action
* may be rendered in a disabled presentation.
*/
public PendingIntent actionIntent;
public Action(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle(), null, null, true);
}
Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
RemoteInput[] remoteInputs, RemoteInput[] dataOnlyRemoteInputs,
boolean allowGeneratedReplies) {
this.icon = icon;
this.title = NotificationCompat.Builder.limitCharSequenceLength(title);
this.actionIntent = intent;
this.mExtras = extras != null ? extras : new Bundle();
this.mRemoteInputs = remoteInputs;
this.mDataOnlyRemoteInputs = dataOnlyRemoteInputs;
this.mAllowGeneratedReplies = allowGeneratedReplies;
}
@Override
public int getIcon() {
return icon;
}
@Override
public CharSequence getTitle() {
return title;
}
@Override
public PendingIntent getActionIntent() {
return actionIntent;
}
/**
* Get additional metadata carried around with this Action.
*/
@Override
public Bundle getExtras() {
return mExtras;
}
/**
* Return whether the platform should automatically generate possible replies for this
* {@link Action}
*/
@Override
public boolean getAllowGeneratedReplies() {
return mAllowGeneratedReplies;
}
/**
* Get the list of inputs to be collected from the user when this action is sent.
* May return null if no remote inputs were added. Only returns inputs which accept
* a text input. For inputs which only accept data use {@link #getDataOnlyRemoteInputs}.
*/
@Override
public RemoteInput[] getRemoteInputs() {
return mRemoteInputs;
}
/**
* Get the list of inputs to be collected from the user that ONLY accept data when this
* action is sent. These remote inputs are guaranteed to return true on a call to
* {@link RemoteInput#isDataOnly}.
*
* <p>May return null if no data-only remote inputs were added.
*
* <p>This method exists so that legacy RemoteInput collectors that pre-date the addition
* of non-textual RemoteInputs do not access these remote inputs.
*/
@Override
public RemoteInput[] getDataOnlyRemoteInputs() {
return mDataOnlyRemoteInputs;
}
/**
* Builder class for {@link Action} objects.
*/
public static final class Builder {
private final int mIcon;
private final CharSequence mTitle;
private final PendingIntent mIntent;
private boolean mAllowGeneratedReplies = true;
private final Bundle mExtras;
private ArrayList<RemoteInput> mRemoteInputs;
/**
* Construct a new builder for {@link Action} object.
* @param icon icon to show for this action
* @param title the title of the action
* @param intent the {@link PendingIntent} to fire when users trigger this action
*/
public Builder(int icon, CharSequence title, PendingIntent intent) {
this(icon, title, intent, new Bundle(), null, true);
}
/**
* Construct a new builder for {@link Action} object using the fields from an
* {@link Action}.
* @param action the action to read fields from.
*/
public Builder(Action action) {
this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras),
action.getRemoteInputs(), action.getAllowGeneratedReplies());
}
private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras,
RemoteInput[] remoteInputs, boolean allowGeneratedReplies) {
mIcon = icon;
mTitle = NotificationCompat.Builder.limitCharSequenceLength(title);
mIntent = intent;
mExtras = extras;
mRemoteInputs = remoteInputs == null ? null : new ArrayList<>(
Arrays.asList(remoteInputs));
mAllowGeneratedReplies = allowGeneratedReplies;
}
/**
* Merge additional metadata into this builder.
*
* <p>Values within the Bundle will replace existing extras values in this Builder.
*
* @see NotificationCompat.Action#getExtras
*/
public Builder addExtras(Bundle extras) {
if (extras != null) {
mExtras.putAll(extras);
}
return this;
}
/**
* Get the metadata Bundle used by this Builder.
*
* <p>The returned Bundle is shared with this Builder.
*/
public Bundle getExtras() {
return mExtras;
}
/**
* Add an input to be collected from the user when this action is sent.
* Response values can be retrieved from the fired intent by using the
* {@link RemoteInput#getResultsFromIntent} function.
* @param remoteInput a {@link RemoteInput} to add to the action
* @return this object for method chaining
*/
public Builder addRemoteInput(RemoteInput remoteInput) {
if (mRemoteInputs == null) {
mRemoteInputs = new ArrayList<RemoteInput>();
}
mRemoteInputs.add(remoteInput);
return this;
}
/**
* Set whether the platform should automatically generate possible replies to add to
* {@link RemoteInput#getChoices()}. If the {@link Action} doesn't have a
* {@link RemoteInput}, this has no effect.
* @param allowGeneratedReplies {@code true} to allow generated replies, {@code false}
* otherwise
* @return this object for method chaining
* The default value is {@code true}
*/
public Builder setAllowGeneratedReplies(boolean allowGeneratedReplies) {
mAllowGeneratedReplies = allowGeneratedReplies;
return this;
}
/**
* Apply an extender to this action builder. Extenders may be used to add
* metadata or change options on this builder.
*/
public Builder extend(Extender extender) {
extender.extend(this);
return this;
}
/**
* Combine all of the options that have been set and return a new {@link Action}
* object.
* @return the built action
*/
public Action build() {
List<RemoteInput> dataOnlyInputs = new ArrayList<>();
List<RemoteInput> textInputs = new ArrayList<>();
if (mRemoteInputs != null) {
for (RemoteInput input : mRemoteInputs) {
if (input.isDataOnly()) {
dataOnlyInputs.add(input);
} else {
textInputs.add(input);
}
}
}
RemoteInput[] dataOnlyInputsArr = dataOnlyInputs.isEmpty()
? null : dataOnlyInputs.toArray(new RemoteInput[dataOnlyInputs.size()]);
RemoteInput[] textInputsArr = textInputs.isEmpty()
? null : textInputs.toArray(new RemoteInput[textInputs.size()]);
return new Action(mIcon, mTitle, mIntent, mExtras, textInputsArr,
dataOnlyInputsArr, mAllowGeneratedReplies);
}
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on an action builder.
*/
public interface Extender {
/**
* Apply this extender to a notification action builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
Builder extend(Builder builder);
}
/**
* Wearable extender for notification actions. To add extensions to an action,
* create a new {@link NotificationCompat.Action.WearableExtender} object using
* the {@code WearableExtender()} constructor and apply it to a
* {@link NotificationCompat.Action.Builder} using
* {@link NotificationCompat.Action.Builder#extend}.
*
* <pre class="prettyprint">
* NotificationCompat.Action action = new NotificationCompat.Action.Builder(
* R.drawable.archive_all, "Archive all", actionIntent)
* .extend(new NotificationCompat.Action.WearableExtender()
* .setAvailableOffline(false))
* .build();</pre>
*/
public static final class WearableExtender implements Extender {
/** Notification action extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
// Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
private static final String KEY_FLAGS = "flags";
private static final String KEY_IN_PROGRESS_LABEL = "inProgressLabel";
private static final String KEY_CONFIRM_LABEL = "confirmLabel";
private static final String KEY_CANCEL_LABEL = "cancelLabel";
// Flags bitwise-ored to mFlags
private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
private static final int FLAG_HINT_LAUNCHES_ACTIVITY = 1 << 1;
private static final int FLAG_HINT_DISPLAY_INLINE = 1 << 2;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
private int mFlags = DEFAULT_FLAGS;
private CharSequence mInProgressLabel;
private CharSequence mConfirmLabel;
private CharSequence mCancelLabel;
/**
* Create a {@link NotificationCompat.Action.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
/**
* Create a {@link NotificationCompat.Action.WearableExtender} by reading
* wearable options present in an existing notification action.
* @param action the notification action to inspect.
*/
public WearableExtender(Action action) {
Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
if (wearableBundle != null) {
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
mInProgressLabel = wearableBundle.getCharSequence(KEY_IN_PROGRESS_LABEL);
mConfirmLabel = wearableBundle.getCharSequence(KEY_CONFIRM_LABEL);
mCancelLabel = wearableBundle.getCharSequence(KEY_CANCEL_LABEL);
}
}
/**
* Apply wearable extensions to a notification action that is being built. This is
* typically called by the {@link NotificationCompat.Action.Builder#extend}
* method of {@link NotificationCompat.Action.Builder}.
*/
@Override
public Action.Builder extend(Action.Builder builder) {
Bundle wearableBundle = new Bundle();
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
if (mInProgressLabel != null) {
wearableBundle.putCharSequence(KEY_IN_PROGRESS_LABEL, mInProgressLabel);
}
if (mConfirmLabel != null) {
wearableBundle.putCharSequence(KEY_CONFIRM_LABEL, mConfirmLabel);
}
if (mCancelLabel != null) {
wearableBundle.putCharSequence(KEY_CANCEL_LABEL, mCancelLabel);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mFlags = this.mFlags;
that.mInProgressLabel = this.mInProgressLabel;
that.mConfirmLabel = this.mConfirmLabel;
that.mCancelLabel = this.mCancelLabel;
return that;
}
/**
* Set whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public WearableExtender setAvailableOffline(boolean availableOffline) {
setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
return this;
}
/**
* Get whether this action is available when the wearable device is not connected to
* a companion device. The user can still trigger this action when the wearable device
* is offline, but a visual hint will indicate that the action may not be available.
* Defaults to true.
*/
public boolean isAvailableOffline() {
return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
/**
* Set a label to display while the wearable is preparing to automatically execute the
* action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
*
* @param label the label to display while the action is being prepared to execute
* @return this object for method chaining
*/
public WearableExtender setInProgressLabel(CharSequence label) {
mInProgressLabel = label;
return this;
}
/**
* Get the label to display while the wearable is preparing to automatically execute
* the action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
*
* @return the label to display while the action is being prepared to execute
*/
public CharSequence getInProgressLabel() {
return mInProgressLabel;
}
/**
* Set a label to display to confirm that the action should be executed.
* This is usually an imperative verb like "Send".
*
* @param label the label to confirm the action should be executed
* @return this object for method chaining
*/
public WearableExtender setConfirmLabel(CharSequence label) {
mConfirmLabel = label;
return this;
}
/**
* Get the label to display to confirm that the action should be executed.
* This is usually an imperative verb like "Send".
*
* @return the label to confirm the action should be executed
*/
public CharSequence getConfirmLabel() {
return mConfirmLabel;
}
/**
* Set a label to display to cancel the action.
* This is usually an imperative verb, like "Cancel".
*
* @param label the label to display to cancel the action
* @return this object for method chaining
*/
public WearableExtender setCancelLabel(CharSequence label) {
mCancelLabel = label;
return this;
}
/**
* Get the label to display to cancel the action.
* This is usually an imperative verb like "Cancel".
*
* @return the label to display to cancel the action
*/
public CharSequence getCancelLabel() {
return mCancelLabel;
}
/**
* Set a hint that this Action will launch an {@link Activity} directly, telling the
* platform that it can generate the appropriate transitions.
* @param hintLaunchesActivity {@code true} if the content intent will launch
* an activity and transitions should be generated, false otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintLaunchesActivity(
boolean hintLaunchesActivity) {
setFlag(FLAG_HINT_LAUNCHES_ACTIVITY, hintLaunchesActivity);
return this;
}
/**
* Get a hint that this Action will launch an {@link Activity} directly, telling the
* platform that it can generate the appropriate transitions
* @return {@code true} if the content intent will launch an activity and transitions
* should be generated, false otherwise. The default value is {@code false} if this was
* never set.
*/
public boolean getHintLaunchesActivity() {
return (mFlags & FLAG_HINT_LAUNCHES_ACTIVITY) != 0;
}
/**
* Set a hint that this Action should be displayed inline - i.e. it will have a visual
* representation directly on the notification surface in addition to the expanded
* Notification
*
* @param hintDisplayInline {@code true} if action should be displayed inline, false
* otherwise
* @return this object for method chaining
*/
public WearableExtender setHintDisplayActionInline(
boolean hintDisplayInline) {
setFlag(FLAG_HINT_DISPLAY_INLINE, hintDisplayInline);
return this;
}
/**
* Get a hint that this Action should be displayed inline - i.e. it should have a
* visual representation directly on the notification surface in addition to the
* expanded Notification
*
* @return {@code true} if the Action should be displayed inline, {@code false}
* otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintDisplayActionInline() {
return (mFlags & FLAG_HINT_DISPLAY_INLINE) != 0;
}
}
/** @hide */
@RestrictTo(LIBRARY_GROUP)
public static final Factory FACTORY = new Factory() {
@Override
public NotificationCompatBase.Action build(int icon, CharSequence title,
PendingIntent actionIntent, Bundle extras,
RemoteInputCompatBase.RemoteInput[] remoteInputs,
RemoteInputCompatBase.RemoteInput[] dataOnlyRemoteInputs,
boolean allowGeneratedReplies) {
return new Action(icon, title, actionIntent, extras,
(RemoteInput[]) remoteInputs, (RemoteInput[]) dataOnlyRemoteInputs,
allowGeneratedReplies);
}
@Override
public Action[] newArray(int length) {
return new Action[length];
}
};
}
/**
* Extender interface for use with {@link Builder#extend}. Extenders may be used to add
* metadata or change options on a notification builder.
*/
public interface Extender {
/**
* Apply this extender to a notification builder.
* @param builder the builder to be modified.
* @return the build object for chaining.
*/
Builder extend(Builder builder);
}
/**
* Helper class to add wearable extensions to notifications.
* <p class="note"> See
* <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
* for Android Wear</a> for more information on how to use this class.
* <p>
* To create a notification with wearable extensions:
* <ol>
* <li>Create a {@link NotificationCompat.Builder}, setting any desired
* properties.
* <li>Create a {@link NotificationCompat.WearableExtender}.
* <li>Set wearable-specific properties using the
* {@code add} and {@code set} methods of {@link NotificationCompat.WearableExtender}.
* <li>Call {@link NotificationCompat.Builder#extend} to apply the extensions to a
* notification.
* <li>Post the notification to the notification
* system with the {@code NotificationManagerCompat.notify(...)} methods
* and not the {@code NotificationManager.notify(...)} methods.
* </ol>
*
* <pre class="prettyprint">
* Notification notification = new NotificationCompat.Builder(mContext)
* .setContentTitle("New mail from " + sender.toString())
* .setContentText(subject)
* .setSmallIcon(R.drawable.new_mail)
* .extend(new NotificationCompat.WearableExtender()
* .setContentIcon(R.drawable.new_mail))
* .build();
* NotificationManagerCompat.from(mContext).notify(0, notification);</pre>
*
* <p>Wearable extensions can be accessed on an existing notification by using the
* {@code WearableExtender(Notification)} constructor,
* and then using the {@code get} methods to access values.
*
* <pre class="prettyprint">
* NotificationCompat.WearableExtender wearableExtender =
* new NotificationCompat.WearableExtender(notification);
* List<Notification> pages = wearableExtender.getPages();</pre>
*/
public static final class WearableExtender implements Extender {
/**
* Sentinel value for an action index that is unset.
*/
public static final int UNSET_ACTION_INDEX = -1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification with
* default sizing.
* <p>For custom display notifications created using {@link #setDisplayIntent},
* the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based
* on their content.
*/
public static final int SIZE_DEFAULT = 0;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with an extra small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_XSMALL = 1;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a small size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_SMALL = 2;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a medium size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_MEDIUM = 3;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* with a large size.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_LARGE = 4;
/**
* Size value for use with {@link #setCustomSizePreset} to show this notification
* full screen.
* <p>This value is only applicable for custom display notifications created using
* {@link #setDisplayIntent}.
*/
public static final int SIZE_FULL_SCREEN = 5;
/**
* Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a
* short amount of time when this notification is displayed on the screen. This
* is the default value.
*/
public static final int SCREEN_TIMEOUT_SHORT = 0;
/**
* Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on
* for a longer amount of time when this notification is displayed on the screen.
*/
public static final int SCREEN_TIMEOUT_LONG = -1;
/** Notification extra which contains wearable extensions */
private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
// Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
private static final String KEY_ACTIONS = "actions";
private static final String KEY_FLAGS = "flags";
private static final String KEY_DISPLAY_INTENT = "displayIntent";
private static final String KEY_PAGES = "pages";
private static final String KEY_BACKGROUND = "background";
private static final String KEY_CONTENT_ICON = "contentIcon";
private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
private static final String KEY_GRAVITY = "gravity";
private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout";
private static final String KEY_DISMISSAL_ID = "dismissalId";
private static final String KEY_BRIDGE_TAG = "bridgeTag";
// Flags bitwise-ored to mFlags
private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4;
private static final int FLAG_BIG_PICTURE_AMBIENT = 1 << 5;
private static final int FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY = 1 << 6;
// Default value for flags integer
private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
private static final int DEFAULT_CONTENT_ICON_GRAVITY = GravityCompat.END;
private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
private ArrayList<Action> mActions = new ArrayList<Action>();
private int mFlags = DEFAULT_FLAGS;
private PendingIntent mDisplayIntent;
private ArrayList<Notification> mPages = new ArrayList<Notification>();
private Bitmap mBackground;
private int mContentIcon;
private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
private int mContentActionIndex = UNSET_ACTION_INDEX;
private int mCustomSizePreset = SIZE_DEFAULT;
private int mCustomContentHeight;
private int mGravity = DEFAULT_GRAVITY;
private int mHintScreenTimeout;
private String mDismissalId;
private String mBridgeTag;
/**
* Create a {@link NotificationCompat.WearableExtender} with default
* options.
*/
public WearableExtender() {
}
public WearableExtender(Notification notification) {
Bundle extras = getExtras(notification);
Bundle wearableBundle = extras != null ? extras.getBundle(EXTRA_WEARABLE_EXTENSIONS)
: null;
if (wearableBundle != null) {
Action[] actions = IMPL.getActionsFromParcelableArrayList(
wearableBundle.getParcelableArrayList(KEY_ACTIONS));
if (actions != null) {
Collections.addAll(mActions, actions);
}
mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
Notification[] pages = getNotificationArrayFromBundle(
wearableBundle, KEY_PAGES);
if (pages != null) {
Collections.addAll(mPages, pages);
}
mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
DEFAULT_CONTENT_ICON_GRAVITY);
mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
UNSET_ACTION_INDEX);
mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
SIZE_DEFAULT);
mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT);
mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID);
mBridgeTag = wearableBundle.getString(KEY_BRIDGE_TAG);
}
}
/**
* Apply wearable extensions to a notification that is being built. This is typically
* called by the {@link NotificationCompat.Builder#extend} method of
* {@link NotificationCompat.Builder}.
*/
@Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
Bundle wearableBundle = new Bundle();
if (!mActions.isEmpty()) {
wearableBundle.putParcelableArrayList(KEY_ACTIONS,
IMPL.getParcelableArrayListForActions(mActions.toArray(
new Action[mActions.size()])));
}
if (mFlags != DEFAULT_FLAGS) {
wearableBundle.putInt(KEY_FLAGS, mFlags);
}
if (mDisplayIntent != null) {
wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
}
if (!mPages.isEmpty()) {
wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
new Notification[mPages.size()]));
}
if (mBackground != null) {
wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
}
if (mContentIcon != 0) {
wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
}
if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
}
if (mContentActionIndex != UNSET_ACTION_INDEX) {
wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
mContentActionIndex);
}
if (mCustomSizePreset != SIZE_DEFAULT) {
wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
}
if (mCustomContentHeight != 0) {
wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
}
if (mGravity != DEFAULT_GRAVITY) {
wearableBundle.putInt(KEY_GRAVITY, mGravity);
}
if (mHintScreenTimeout != 0) {
wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout);
}
if (mDismissalId != null) {
wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId);
}
if (mBridgeTag != null) {
wearableBundle.putString(KEY_BRIDGE_TAG, mBridgeTag);
}
builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
return builder;
}
@Override
public WearableExtender clone() {
WearableExtender that = new WearableExtender();
that.mActions = new ArrayList<Action>(this.mActions);
that.mFlags = this.mFlags;
that.mDisplayIntent = this.mDisplayIntent;
that.mPages = new ArrayList<Notification>(this.mPages);
that.mBackground = this.mBackground;
that.mContentIcon = this.mContentIcon;
that.mContentIconGravity = this.mContentIconGravity;
that.mContentActionIndex = this.mContentActionIndex;
that.mCustomSizePreset = this.mCustomSizePreset;
that.mCustomContentHeight = this.mCustomContentHeight;
that.mGravity = this.mGravity;
that.mHintScreenTimeout = this.mHintScreenTimeout;
that.mDismissalId = this.mDismissalId;
that.mBridgeTag = this.mBridgeTag;
return that;
}
/**
* Add a wearable action to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param action the action to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addAction(Action action) {
mActions.add(action);
return this;
}
/**
* Adds wearable actions to this notification.
*
* <p>When wearable actions are added using this method, the set of actions that
* show on a wearable device splits from devices that only show actions added
* using {@link NotificationCompat.Builder#addAction}. This allows for customization
* of which actions display on different devices.
*
* @param actions the actions to add to this notification
* @return this object for method chaining
* @see NotificationCompat.Action
*/
public WearableExtender addActions(List<Action> actions) {
mActions.addAll(actions);
return this;
}
/**
* Clear all wearable actions present on this builder.
* @return this object for method chaining.
* @see #addAction
*/
public WearableExtender clearActions() {
mActions.clear();
return this;
}
/**
* Get the wearable actions present on this notification.
*/
public List<Action> getActions() {
return mActions;
}
/**
* Set an intent to launch inside of an activity view when displaying
* this notification. The {@link PendingIntent} provided should be for an activity.
*
* <pre class="prettyprint">
* Intent displayIntent = new Intent(context, MyDisplayActivity.class);
* PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
* 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
* Notification notification = new NotificationCompat.Builder(context)
* .extend(new NotificationCompat.WearableExtender()
* .setDisplayIntent(displayPendingIntent)
* .setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_MEDIUM))
* .build();</pre>
*
* <p>The activity to launch needs to allow embedding, must be exported, and
* should have an empty task affinity. It is also recommended to use the device
* default light theme.
*
* <p>Example AndroidManifest.xml entry:
* <pre class="prettyprint">
* <activity android:name="com.example.MyDisplayActivity"
* android:exported="true"
* android:allowEmbedded="true"
* android:taskAffinity=""
* android:theme="@android:style/Theme.DeviceDefault.Light" /></pre>
*
* @param intent the {@link PendingIntent} for an activity
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getDisplayIntent
*/
public WearableExtender setDisplayIntent(PendingIntent intent) {
mDisplayIntent = intent;
return this;
}
/**
* Get the intent to launch inside of an activity view when displaying this
* notification. This {@code PendingIntent} should be for an activity.
*/
public PendingIntent getDisplayIntent() {
return mDisplayIntent;
}
/**
* Add an additional page of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param page the notification to add as another page
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPage(Notification page) {
mPages.add(page);
return this;
}
/**
* Add additional pages of content to display with this notification. The current
* notification forms the first page, and pages added using this function form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
*
* @param pages a list of notifications
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getPages
*/
public WearableExtender addPages(List<Notification> pages) {
mPages.addAll(pages);
return this;
}
/**
* Clear all additional pages present on this builder.
* @return this object for method chaining.
* @see #addPage
*/
public WearableExtender clearPages() {
mPages.clear();
return this;
}
/**
* Get the array of additional pages of content for displaying this notification. The
* current notification forms the first page, and elements within this array form
* subsequent pages. This field can be used to separate a notification into multiple
* sections.
* @return the pages for this notification
*/
public List<Notification> getPages() {
return mPages;
}
/**
* Set a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @param background the background bitmap
* @return this object for method chaining
* @see NotificationCompat.WearableExtender#getBackground
*/
public WearableExtender setBackground(Bitmap background) {
mBackground = background;
return this;
}
/**
* Get a background image to be displayed behind the notification content.
* Contrary to the {@link NotificationCompat.BigPictureStyle}, this background
* will work with any notification style.
*
* @return the background image
* @see NotificationCompat.WearableExtender#setBackground
*/
public Bitmap getBackground() {
return mBackground;
}
/**
* Set an icon that goes with the content of this notification.
*/
public WearableExtender setContentIcon(int icon) {
mContentIcon = icon;
return this;
}
/**
* Get an icon that goes with the content of this notification.
*/
public int getContentIcon() {
return mContentIcon;
}
/**
* Set the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #setContentIcon
*/
public WearableExtender setContentIconGravity(int contentIconGravity) {
mContentIconGravity = contentIconGravity;
return this;
}
/**
* Get the gravity that the content icon should have within the notification display.
* Supported values include {@link android.view.Gravity#START} and
* {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
* @see #getContentIcon
*/
public int getContentIconGravity() {
return mContentIconGravity;
}
/**
* Set an action from this notification's actions to be clickable with the content of
* this notification. This action will no longer display separately from the
* notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* @param actionIndex The index of the action to hoist onto the current notification page.
* If wearable actions were added to the main notification, this index
* will apply to that list, otherwise it will apply to the regular
* actions list.
*/
public WearableExtender setContentAction(int actionIndex) {
mContentActionIndex = actionIndex;
return this;
}
/**
* Get the index of the notification action, if any, that was specified as being clickable
* with the content of this notification. This action will no longer display separately
* from the notification's content.
*
* <p>For notifications with multiple pages, child pages can also have content actions
* set, although the list of available actions comes from the main notification and not
* from the child page's notification.
*
* <p>If wearable specific actions were added to the main notification, this index will
* apply to that list, otherwise it will apply to the regular actions list.
*
* @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
*/
public int getContentAction() {
return mContentActionIndex;
}
/**
* Set the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public WearableExtender setGravity(int gravity) {
mGravity = gravity;
return this;
}
/**
* Get the gravity that this notification should have within the available viewport space.
* Supported values include {@link android.view.Gravity#TOP},
* {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
* The default value is {@link android.view.Gravity#BOTTOM}.
*/
public int getGravity() {
return mGravity;
}
/**
* Set the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. Check the
* documentation for the preset in question. See also
* {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
*/
public WearableExtender setCustomSizePreset(int sizePreset) {
mCustomSizePreset = sizePreset;
return this;
}
/**
* Get the custom size preset for the display of this notification out of the available
* presets found in {@link NotificationCompat.WearableExtender}, e.g.
* {@link #SIZE_LARGE}.
* <p>Some custom size presets are only applicable for custom display notifications created
* using {@link #setDisplayIntent}. Check the documentation for the preset in question.
* See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
*/
public int getCustomSizePreset() {
return mCustomSizePreset;
}
/**
* Set the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link NotificationCompat.WearableExtender#setDisplayIntent}. See also
* {@link NotificationCompat.WearableExtender#setCustomSizePreset} and
* {@link #getCustomContentHeight}.
*/
public WearableExtender setCustomContentHeight(int height) {
mCustomContentHeight = height;
return this;
}
/**
* Get the custom height in pixels for the display of this notification's content.
* <p>This option is only available for custom display notifications created
* using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
* {@link #setCustomContentHeight}.
*/
public int getCustomContentHeight() {
return mCustomContentHeight;
}
/**
* Set whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
return this;
}
/**
* Get whether the scrolling position for the contents of this notification should start
* at the bottom of the contents instead of the top when the contents are too long to
* display within the screen. Default is false (start scroll at the top).
*/
public boolean getStartScrollBottom() {
return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
}
/**
* Set whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public WearableExtender setContentIntentAvailableOffline(
boolean contentIntentAvailableOffline) {
setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
return this;
}
/**
* Get whether the content intent is available when the wearable device is not connected
* to a companion device. The user can still trigger this intent when the wearable device
* is offline, but a visual hint will indicate that the content intent may not be available.
* Defaults to true.
*/
public boolean getContentIntentAvailableOffline() {
return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
}
/**
* Set a hint that this notification's icon should not be displayed.
* @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintHideIcon(boolean hintHideIcon) {
setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
return this;
}
/**
* Get a hint that this notification's icon should not be displayed.
* @return {@code true} if this icon should not be displayed, false otherwise.
* The default value is {@code false} if this was never set.
*/
public boolean getHintHideIcon() {
return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
}
/**
* Set a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link #addPage}.
*/
public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
return this;
}
/**
* Get a visual hint that only the background image of this notification should be
* displayed, and other semantic content should be hidden. This hint is only applicable
* to sub-pages added using {@link NotificationCompat.WearableExtender#addPage}.
*/
public boolean getHintShowBackgroundOnly() {
return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
}
/**
* Set a hint that this notification's background should not be clipped if possible,
* and should instead be resized to fully display on the screen, retaining the aspect
* ratio of the image. This can be useful for images like barcodes or qr codes.
* @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible.
* @return this object for method chaining
*/
public WearableExtender setHintAvoidBackgroundClipping(
boolean hintAvoidBackgroundClipping) {
setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping);
return this;
}
/**
* Get a hint that this notification's background should not be clipped if possible,
* and should instead be resized to fully display on the screen, retaining the aspect
* ratio of the image. This can be useful for images like barcodes or qr codes.
* @return {@code true} if it's ok if the background is clipped on the screen, false
* otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintAvoidBackgroundClipping() {
return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0;
}
/**
* Set a hint that the screen should remain on for at least this duration when
* this notification is displayed on the screen.
* @param timeout The requested screen timeout in milliseconds. Can also be either
* {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
* @return this object for method chaining
*/
public WearableExtender setHintScreenTimeout(int timeout) {
mHintScreenTimeout = timeout;
return this;
}
/**
* Get the duration, in milliseconds, that the screen should remain on for
* when this notification is displayed.
* @return the duration in milliseconds if > 0, or either one of the sentinel values
* {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
*/
public int getHintScreenTimeout() {
return mHintScreenTimeout;
}
/**
* Set a hint that this notification's {@link BigPictureStyle} (if present) should be
* converted to low-bit and displayed in ambient mode, especially useful for barcodes and
* qr codes, as well as other simple black-and-white tickets.
* @param hintAmbientBigPicture {@code true} to enable converstion and ambient.
* @return this object for method chaining
*/
public WearableExtender setHintAmbientBigPicture(boolean hintAmbientBigPicture) {
setFlag(FLAG_BIG_PICTURE_AMBIENT, hintAmbientBigPicture);
return this;
}
/**
* Get a hint that this notification's {@link BigPictureStyle} (if present) should be
* converted to low-bit and displayed in ambient mode, especially useful for barcodes and
* qr codes, as well as other simple black-and-white tickets.
* @return {@code true} if it should be displayed in ambient, false otherwise
* otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintAmbientBigPicture() {
return (mFlags & FLAG_BIG_PICTURE_AMBIENT) != 0;
}
/**
* Set a hint that this notification's content intent will launch an {@link Activity}
* directly, telling the platform that it can generate the appropriate transitions.
* @param hintContentIntentLaunchesActivity {@code true} if the content intent will launch
* an activity and transitions should be generated, false otherwise.
* @return this object for method chaining
*/
public WearableExtender setHintContentIntentLaunchesActivity(
boolean hintContentIntentLaunchesActivity) {
setFlag(FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY, hintContentIntentLaunchesActivity);
return this;
}
/**
* Get a hint that this notification's content intent will launch an {@link Activity}
* directly, telling the platform that it can generate the appropriate transitions
* @return {@code true} if the content intent will launch an activity and transitions should
* be generated, false otherwise. The default value is {@code false} if this was never set.
*/
public boolean getHintContentIntentLaunchesActivity() {
return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0;
}
/**
* Sets the dismissal id for this notification. If a notification is posted with a
* dismissal id, then when that notification is canceled, notifications on other wearables
* and the paired Android phone having that same dismissal id will also be canceled. See
* <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to
* Notifications</a> for more information.
* @param dismissalId the dismissal id of the notification.
* @return this object for method chaining
*/
public WearableExtender setDismissalId(String dismissalId) {
mDismissalId = dismissalId;
return this;
}
/**
* Returns the dismissal id of the notification.
* @return the dismissal id of the notification or null if it has not been set.
*/
public String getDismissalId() {
return mDismissalId;
}
/**
* Sets a bridge tag for this notification. A bridge tag can be set for notifications
* posted from a phone to provide finer-grained control on what notifications are bridged
* to wearables. See <a href="{@docRoot}wear/notifications/index.html">Adding Wearable
* Features to Notifications</a> for more information.
* @param bridgeTag the bridge tag of the notification.
* @return this object for method chaining
*/
public WearableExtender setBridgeTag(String bridgeTag) {
mBridgeTag = bridgeTag;
return this;
}
/**
* Returns the bridge tag of the notification.
* @return the bridge tag or null if not present.
*/
public String getBridgeTag() {
return mBridgeTag;
}
private void setFlag(int mask, boolean value) {
if (value) {
mFlags |= mask;
} else {
mFlags &= ~mask;
}
}
}
/**
* <p>Helper class to add Android Auto extensions to notifications. To create a notification
* with car extensions:
*
* <ol>
* <li>Create an {@link NotificationCompat.Builder}, setting any desired
* properties.
* <li>Create a {@link CarExtender}.
* <li>Set car-specific properties using the {@code add} and {@code set} methods of
* {@link CarExtender}.
* <li>Call {@link android.support.v4.app.NotificationCompat.Builder#extend(NotificationCompat.Extender)}
* to apply the extensions to a notification.
* <li>Post the notification to the notification system with the
* {@code NotificationManagerCompat.notify(...)} methods and not the
* {@code NotificationManager.notify(...)} methods.
* </ol>
*
* <pre class="prettyprint">
* Notification notification = new NotificationCompat.Builder(context)
* ...
* .extend(new CarExtender()
* .set*(...))
* .build();
* </pre>
*
* <p>Car extensions can be accessed on an existing notification by using the
* {@code CarExtender(Notification)} constructor, and then using the {@code get} methods
* to access values.
*/
public static final class CarExtender implements Extender {
private static final String TAG = "CarExtender";
private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS";
private static final String EXTRA_LARGE_ICON = "large_icon";
private static final String EXTRA_CONVERSATION = "car_conversation";
private static final String EXTRA_COLOR = "app_color";
private Bitmap mLargeIcon;
private UnreadConversation mUnreadConversation;
private int mColor = NotificationCompat.COLOR_DEFAULT;
/**
* Create a {@link CarExtender} with default options.
*/
public CarExtender() {
}
/**
* Create a {@link CarExtender} from the CarExtender options of an existing Notification.
*
* @param notification The notification from which to copy options.
*/
public CarExtender(Notification notification) {
if (Build.VERSION.SDK_INT < 21) {
return;
}
Bundle carBundle = getExtras(notification) == null
? null : getExtras(notification).getBundle(EXTRA_CAR_EXTENDER);
if (carBundle != null) {
mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON);
mColor = carBundle.getInt(EXTRA_COLOR, NotificationCompat.COLOR_DEFAULT);
Bundle b = carBundle.getBundle(EXTRA_CONVERSATION);
mUnreadConversation = (UnreadConversation) IMPL.getUnreadConversationFromBundle(
b, UnreadConversation.FACTORY, RemoteInput.FACTORY);
}
}
/**
* Apply car extensions to a notification that is being built. This is typically called by
* the {@link android.support.v4.app.NotificationCompat.Builder#extend(NotificationCompat.Extender)}
* method of {@link NotificationCompat.Builder}.
*/
@Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
if (Build.VERSION.SDK_INT < 21) {
return builder;
}
Bundle carExtensions = new Bundle();
if (mLargeIcon != null) {
carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
}
if (mColor != NotificationCompat.COLOR_DEFAULT) {
carExtensions.putInt(EXTRA_COLOR, mColor);
}
if (mUnreadConversation != null) {
Bundle b = IMPL.getBundleForUnreadConversation(mUnreadConversation);
carExtensions.putBundle(EXTRA_CONVERSATION, b);
}
builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions);
return builder;
}
/**
* Sets the accent color to use when Android Auto presents the notification.
*
* Android Auto uses the color set with {@link android.support.v4.app.NotificationCompat.Builder#setColor(int)}
* to accent the displayed notification. However, not all colors are acceptable in an
* automotive setting. This method can be used to override the color provided in the
* notification in such a situation.
*/
public CarExtender setColor(@ColorInt int color) {
mColor = color;
return this;
}
/**
* Gets the accent color.
*
* @see #setColor
*/
@ColorInt
public int getColor() {
return mColor;
}
/**
* Sets the large icon of the car notification.
*
* If no large icon is set in the extender, Android Auto will display the icon
* specified by {@link android.support.v4.app.NotificationCompat.Builder#setLargeIcon(android.graphics.Bitmap)}
*
* @param largeIcon The large icon to use in the car notification.
* @return This object for method chaining.
*/
public CarExtender setLargeIcon(Bitmap largeIcon) {
mLargeIcon = largeIcon;
return this;
}
/**
* Gets the large icon used in this car notification, or null if no icon has been set.
*
* @return The large icon for the car notification.
* @see CarExtender#setLargeIcon
*/
public Bitmap getLargeIcon() {
return mLargeIcon;
}
/**
* Sets the unread conversation in a message notification.
*
* @param unreadConversation The unread part of the conversation this notification conveys.
* @return This object for method chaining.
*/
public CarExtender setUnreadConversation(UnreadConversation unreadConversation) {
mUnreadConversation = unreadConversation;
return this;
}
/**
* Returns the unread conversation conveyed by this notification.
* @see #setUnreadConversation(UnreadConversation)
*/
public UnreadConversation getUnreadConversation() {
return mUnreadConversation;
}
/**
* A class which holds the unread messages from a conversation.
*/
public static class UnreadConversation extends NotificationCompatBase.UnreadConversation {
private final String[] mMessages;
private final RemoteInput mRemoteInput;
private final PendingIntent mReplyPendingIntent;
private final PendingIntent mReadPendingIntent;
private final String[] mParticipants;
private final long mLatestTimestamp;
UnreadConversation(String[] messages, RemoteInput remoteInput,
PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
String[] participants, long latestTimestamp) {
mMessages = messages;
mRemoteInput = remoteInput;
mReadPendingIntent = readPendingIntent;
mReplyPendingIntent = replyPendingIntent;
mParticipants = participants;
mLatestTimestamp = latestTimestamp;
}
/**
* Gets the list of messages conveyed by this notification.
*/
@Override
public String[] getMessages() {
return mMessages;
}
/**
* Gets the remote input that will be used to convey the response to a message list, or
* null if no such remote input exists.
*/
@Override
public RemoteInput getRemoteInput() {
return mRemoteInput;
}
/**
* Gets the pending intent that will be triggered when the user replies to this
* notification.
*/
@Override
public PendingIntent getReplyPendingIntent() {
return mReplyPendingIntent;
}
/**
* Gets the pending intent that Android Auto will send after it reads aloud all messages
* in this object's message list.
*/
@Override
public PendingIntent getReadPendingIntent() {
return mReadPendingIntent;
}
/**
* Gets the participants in the conversation.
*/
@Override
public String[] getParticipants() {
return mParticipants;
}
/**
* Gets the firs participant in the conversation.
*/
@Override
public String getParticipant() {
return mParticipants.length > 0 ? mParticipants[0] : null;
}
/**
* Gets the timestamp of the conversation.
*/
@Override
public long getLatestTimestamp() {
return mLatestTimestamp;
}
static final Factory FACTORY = new Factory() {
@Override
public UnreadConversation build(
String[] messages, RemoteInputCompatBase.RemoteInput remoteInput,
PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
String[] participants, long latestTimestamp) {
return new UnreadConversation(
messages, (RemoteInput) remoteInput, replyPendingIntent,
readPendingIntent,
participants, latestTimestamp);
}
};
/**
* Builder class for {@link CarExtender.UnreadConversation} objects.
*/
public static class Builder {
private final List<String> mMessages = new ArrayList<String>();
private final String mParticipant;
private RemoteInput mRemoteInput;
private PendingIntent mReadPendingIntent;
private PendingIntent mReplyPendingIntent;
private long mLatestTimestamp;
/**
* Constructs a new builder for {@link CarExtender.UnreadConversation}.
*
* @param name The name of the other participant in the conversation.
*/
public Builder(String name) {
mParticipant = name;
}
/**
* Appends a new unread message to the list of messages for this conversation.
*
* The messages should be added from oldest to newest.
*
* @param message The text of the new unread message.
* @return This object for method chaining.
*/
public Builder addMessage(String message) {
mMessages.add(message);
return this;
}
/**
* Sets the pending intent and remote input which will convey the reply to this
* notification.
*
* @param pendingIntent The pending intent which will be triggered on a reply.
* @param remoteInput The remote input parcelable which will carry the reply.
* @return This object for method chaining.
*
* @see CarExtender.UnreadConversation#getRemoteInput
* @see CarExtender.UnreadConversation#getReplyPendingIntent
*/
public Builder setReplyAction(
PendingIntent pendingIntent, RemoteInput remoteInput) {
mRemoteInput = remoteInput;
mReplyPendingIntent = pendingIntent;
return this;
}
/**
* Sets the pending intent that will be sent once the messages in this notification
* are read.
*
* @param pendingIntent The pending intent to use.
* @return This object for method chaining.
*/
public Builder setReadPendingIntent(PendingIntent pendingIntent) {
mReadPendingIntent = pendingIntent;
return this;
}
/**
* Sets the timestamp of the most recent message in an unread conversation.
*
* If a messaging notification has been posted by your application and has not
* yet been cancelled, posting a later notification with the same id and tag
* but without a newer timestamp may result in Android Auto not displaying a
* heads up notification for the later notification.
*
* @param timestamp The timestamp of the most recent message in the conversation.
* @return This object for method chaining.
*/
public Builder setLatestTimestamp(long timestamp) {
mLatestTimestamp = timestamp;
return this;
}
/**
* Builds a new unread conversation object.
*
* @return The new unread conversation object.
*/
public UnreadConversation build() {
String[] messages = mMessages.toArray(new String[mMessages.size()]);
String[] participants = { mParticipant };
return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent,
mReadPendingIntent, participants, mLatestTimestamp);
}
}
}
}
/**
* Get an array of Notification objects from a parcelable array bundle field.
* Update the bundle to have a typed array so fetches in the future don't need
* to do an array copy.
*/
static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
Parcelable[] array = bundle.getParcelableArray(key);
if (array instanceof Notification[] || array == null) {
return (Notification[]) array;
}
Notification[] typedArray = new Notification[array.length];
for (int i = 0; i < array.length; i++) {
typedArray[i] = (Notification) array[i];
}
bundle.putParcelableArray(key, typedArray);
return typedArray;
}
/**
* Gets the {@link Notification#extras} field from a notification in a backwards
* compatible manner. Extras field was supported from JellyBean (Api level 16)
* forwards. This function will return null on older api levels.
*/
public static Bundle getExtras(Notification notification) {
if (Build.VERSION.SDK_INT >= 19) {
return notification.extras;
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification);
} else {
return null;
}
}
/**
* Get the number of actions in this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
*/
public static int getActionCount(Notification notification) {
if (Build.VERSION.SDK_INT >= 19) {
return notification.actions != null ? notification.actions.length : 0;
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getActionCount(notification);
} else {
return 0;
}
}
/**
* Get an action on this notification in a backwards compatible
* manner. Actions were supported from JellyBean (Api level 16) forwards.
* @param notification The notification to inspect.
* @param actionIndex The index of the action to retrieve.
*/
public static Action getAction(Notification notification, int actionIndex) {
return IMPL.getAction(notification, actionIndex);
}
/**
* Get the category of this notification in a backwards compatible
* manner.
* @param notification The notification to inspect.
*/
public static String getCategory(Notification notification) {
if (Build.VERSION.SDK_INT >= 21) {
return notification.category;
} else {
return null;
}
}
/**
* Get whether or not this notification is only relevant to the current device.
*
* <p>Some notifications can be bridged to other devices for remote display.
* If this hint is set, it is recommend that this notification not be bridged.
*/
public static boolean getLocalOnly(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return (notification.flags & Notification.FLAG_LOCAL_ONLY) != 0;
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getBoolean(NotificationCompatExtras.EXTRA_LOCAL_ONLY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getBoolean(
NotificationCompatExtras.EXTRA_LOCAL_ONLY);
} else {
return false;
}
}
/**
* Get the key used to group this notification into a cluster or stack
* with other notifications on devices which support such rendering.
*/
public static String getGroup(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return notification.getGroup();
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getString(NotificationCompatExtras.EXTRA_GROUP_KEY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getString(
NotificationCompatExtras.EXTRA_GROUP_KEY);
} else {
return null;
}
}
/**
* Get whether this notification to be the group summary for a group of notifications.
* Grouped notifications may display in a cluster or stack on devices which
* support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
* @return Whether this notification is a group summary.
*/
public static boolean isGroupSummary(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return (notification.flags & Notification.FLAG_GROUP_SUMMARY) != 0;
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getBoolean(NotificationCompatExtras.EXTRA_GROUP_SUMMARY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getBoolean(
NotificationCompatExtras.EXTRA_GROUP_SUMMARY);
} else {
return false;
}
}
/**
* Get a sort key that orders this notification among other notifications from the
* same package. This can be useful if an external sort was already applied and an app
* would like to preserve this. Notifications will be sorted lexicographically using this
* value, although providing different priorities in addition to providing sort key may
* cause this value to be ignored.
*
* <p>This sort key can also be used to order members of a notification group. See
* {@link Builder#setGroup}.
*
* @see String#compareTo(String)
*/
public static String getSortKey(Notification notification) {
if (Build.VERSION.SDK_INT >= 20) {
return notification.getSortKey();
} else if (Build.VERSION.SDK_INT >= 19) {
return notification.extras.getString(NotificationCompatExtras.EXTRA_SORT_KEY);
} else if (Build.VERSION.SDK_INT >= 16) {
return NotificationCompatJellybean.getExtras(notification).getString(
NotificationCompatExtras.EXTRA_SORT_KEY);
} else {
return null;
}
}
/**
* @return the ID of the channel this notification posts to.
*/
public static String getChannelId(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getChannelId();
} else {
return null;
}
}
/** @deprecated removed from API 26 */
@Deprecated
public static String getChannel(Notification notification) {
return getChannelId(notification);
}
/**
* Returns the time at which this notification should be canceled by the system, if it's not
* canceled already.
*/
public static long getTimeoutAfter(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getTimeoutAfter();
} else {
return 0;
}
}
/** @deprecated removed from API 26 */
@Deprecated
public static long getTimeout(Notification notification) {
return getTimeoutAfter(notification);
}
/**
* Returns what icon should be shown for this notification if it is being displayed in a
* Launcher that supports badging. Will be one of {@link #BADGE_ICON_NONE},
* {@link #BADGE_ICON_SMALL}, or {@link #BADGE_ICON_LARGE}.
*/
public static int getBadgeIconType(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getBadgeIconType();
} else {
return BADGE_ICON_NONE;
}
}
/**
* Returns the {@link android.support.v4.content.pm.ShortcutInfoCompat#getId() id} that this
* notification supersedes, if any.
*/
public static String getShortcutId(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getShortcutId();
} else {
return null;
}
}
/**
* Returns which type of notifications in a group are responsible for audibly alerting the
* user. See {@link #GROUP_ALERT_ALL}, {@link #GROUP_ALERT_CHILDREN},
* {@link #GROUP_ALERT_SUMMARY}.
*/
public static int getGroupAlertBehavior(Notification notification) {
if (Build.VERSION.SDK_INT >= 26) {
return notification.getGroupAlertBehavior();
} else {
return GROUP_ALERT_ALL;
}
}
}
| Make NotificationCompat.Style apply themselves
Instead of the NotificationCompatImpl using
instanceof checks to handle each Style, create a
generic apply() method that each Style can implement
to do their own encapsulated version checking and
changes that are specific to that style.
Updates BigTextStyle, InboxStyle, BigPictureStyle,
and the API 24+ route for MessagingStyle to use this
new functionality.
Test: Manual inspection
Bug: 33042051
Change-Id: I304dacee71bf25a9d8f2c5a24e319671465e8d2b
| compat/java/android/support/v4/app/NotificationCompat.java | Make NotificationCompat.Style apply themselves | <ide><path>ompat/java/android/support/v4/app/NotificationCompat.java
<ide> b.mUseChronometer, b.mPriority, b.mSubText, b.mLocalOnly, b.mExtras,
<ide> b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView);
<ide> addActionsToBuilder(builder, b.mActions);
<del> addStyleToBuilderJellybean(builder, b.mStyle);
<add> if (b.mStyle != null) {
<add> b.mStyle.apply(builder);
<add> }
<ide> Notification notification = extender.build(b, builder);
<ide> if (b.mStyle != null) {
<ide> Bundle extras = getExtras(notification);
<ide> b.mPeople, b.mExtras, b.mGroupKey, b.mGroupSummary, b.mSortKey,
<ide> b.mContentView, b.mBigContentView);
<ide> addActionsToBuilder(builder, b.mActions);
<del> addStyleToBuilderJellybean(builder, b.mStyle);
<add> if (b.mStyle != null) {
<add> b.mStyle.apply(builder);
<add> }
<ide> return extender.build(b, builder);
<ide> }
<ide>
<ide> b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
<ide> b.mGroupAlertBehavior);
<ide> addActionsToBuilder(builder, b.mActions);
<del> addStyleToBuilderJellybean(builder, b.mStyle);
<add> if (b.mStyle != null) {
<add> b.mStyle.apply(builder);
<add> }
<ide> Notification notification = extender.build(b, builder);
<ide> if (b.mStyle != null) {
<ide> b.mStyle.addCompatExtras(getExtras(notification));
<ide> b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mContentView, b.mBigContentView,
<ide> b.mHeadsUpContentView, b.mGroupAlertBehavior);
<ide> addActionsToBuilder(builder, b.mActions);
<del> addStyleToBuilderJellybean(builder, b.mStyle);
<add> if (b.mStyle != null) {
<add> b.mStyle.apply(builder);
<add> }
<ide> Notification notification = extender.build(b, builder);
<ide> if (b.mStyle != null) {
<ide> b.mStyle.addCompatExtras(getExtras(notification));
<ide> b.mGroupKey, b.mGroupSummary, b.mSortKey, b.mRemoteInputHistory, b.mContentView,
<ide> b.mBigContentView, b.mHeadsUpContentView, b.mGroupAlertBehavior);
<ide> addActionsToBuilder(builder, b.mActions);
<del> addStyleToBuilderApi24(builder, b.mStyle);
<add> if (b.mStyle != null) {
<add> b.mStyle.apply(builder);
<add> }
<ide> Notification notification = extender.build(b, builder);
<ide> if (b.mStyle != null) {
<ide> b.mStyle.addCompatExtras(getExtras(notification));
<ide> b.mShortcutId, b.mTimeout, b.mColorized, b.mColorizedSet,
<ide> b.mGroupAlertBehavior);
<ide> addActionsToBuilder(builder, b.mActions);
<del> addStyleToBuilderApi24(builder, b.mStyle);
<add> if (b.mStyle != null) {
<add> b.mStyle.apply(builder);
<add> }
<ide> Notification notification = extender.build(b, builder);
<ide> if (b.mStyle != null) {
<ide> b.mStyle.addCompatExtras(getExtras(notification));
<ide> ArrayList<Action> actions) {
<ide> for (Action action : actions) {
<ide> builder.addAction(action);
<del> }
<del> }
<del>
<del> @RequiresApi(16)
<del> static void addStyleToBuilderJellybean(NotificationBuilderWithBuilderAccessor builder,
<del> Style style) {
<del> if (style != null) {
<del> if (style instanceof BigTextStyle) {
<del> BigTextStyle bigTextStyle = (BigTextStyle) style;
<del> NotificationCompatJellybean.addBigTextStyle(builder,
<del> bigTextStyle.mBigContentTitle,
<del> bigTextStyle.mSummaryTextSet,
<del> bigTextStyle.mSummaryText,
<del> bigTextStyle.mBigText);
<del> } else if (style instanceof InboxStyle) {
<del> InboxStyle inboxStyle = (InboxStyle) style;
<del> NotificationCompatJellybean.addInboxStyle(builder,
<del> inboxStyle.mBigContentTitle,
<del> inboxStyle.mSummaryTextSet,
<del> inboxStyle.mSummaryText,
<del> inboxStyle.mTexts);
<del> } else if (style instanceof BigPictureStyle) {
<del> BigPictureStyle bigPictureStyle = (BigPictureStyle) style;
<del> NotificationCompatJellybean.addBigPictureStyle(builder,
<del> bigPictureStyle.mBigContentTitle,
<del> bigPictureStyle.mSummaryTextSet,
<del> bigPictureStyle.mSummaryText,
<del> bigPictureStyle.mPicture,
<del> bigPictureStyle.mBigLargeIcon,
<del> bigPictureStyle.mBigLargeIconSet);
<del> }
<del> }
<del> }
<del>
<del> @RequiresApi(24)
<del> static void addStyleToBuilderApi24(NotificationBuilderWithBuilderAccessor builder,
<del> Style style) {
<del> if (style != null) {
<del> if (style instanceof MessagingStyle) {
<del> MessagingStyle messagingStyle = (MessagingStyle) style;
<del> List<CharSequence> texts = new ArrayList<>();
<del> List<Long> timestamps = new ArrayList<>();
<del> List<CharSequence> senders = new ArrayList<>();
<del> List<String> dataMimeTypes = new ArrayList<>();
<del> List<Uri> dataUris = new ArrayList<>();
<del>
<del> for (MessagingStyle.Message message : messagingStyle.mMessages) {
<del> texts.add(message.getText());
<del> timestamps.add(message.getTimestamp());
<del> senders.add(message.getSender());
<del> dataMimeTypes.add(message.getDataMimeType());
<del> dataUris.add(message.getDataUri());
<del> }
<del> NotificationCompatApi24.addMessagingStyle(builder, messagingStyle.mUserDisplayName,
<del> messagingStyle.mConversationTitle, texts, timestamps, senders,
<del> dataMimeTypes, dataUris);
<del> } else {
<del> addStyleToBuilderJellybean(builder, style);
<del> }
<ide> }
<ide> }
<ide>
<ide> */
<ide> @RestrictTo(LIBRARY_GROUP)
<ide> // TODO: implement for all styles
<add> public void apply(NotificationBuilderWithBuilderAccessor builder) {
<add> }
<add>
<add> /**
<add> * @hide
<add> */
<add> @RestrictTo(LIBRARY_GROUP)
<add> // TODO: implement for all styles
<ide> public void addCompatExtras(Bundle extras) {
<ide> }
<ide>
<ide> * @see Notification#bigContentView
<ide> */
<ide> public static class BigPictureStyle extends Style {
<del> Bitmap mPicture;
<del> Bitmap mBigLargeIcon;
<del> boolean mBigLargeIconSet;
<add> private Bitmap mPicture;
<add> private Bitmap mBigLargeIcon;
<add> private boolean mBigLargeIconSet;
<ide>
<ide> public BigPictureStyle() {
<ide> }
<ide> mBigLargeIcon = b;
<ide> mBigLargeIconSet = true;
<ide> return this;
<add> }
<add>
<add> /**
<add> * @hide
<add> */
<add> @RestrictTo(LIBRARY_GROUP)
<add> @Override
<add> public void apply(NotificationBuilderWithBuilderAccessor builder) {
<add> if (Build.VERSION.SDK_INT >= 16) {
<add> NotificationCompatJellybean.addBigPictureStyle(builder,
<add> mBigContentTitle,
<add> mSummaryTextSet,
<add> mSummaryText,
<add> mPicture,
<add> mBigLargeIcon,
<add> mBigLargeIconSet);
<add> }
<ide> }
<ide> }
<ide>
<ide> * @see Notification#bigContentView
<ide> */
<ide> public static class BigTextStyle extends Style {
<del> CharSequence mBigText;
<add> private CharSequence mBigText;
<ide>
<ide> public BigTextStyle() {
<ide> }
<ide> public BigTextStyle bigText(CharSequence cs) {
<ide> mBigText = Builder.limitCharSequenceLength(cs);
<ide> return this;
<add> }
<add>
<add> /**
<add> * @hide
<add> */
<add> @RestrictTo(LIBRARY_GROUP)
<add> @Override
<add> public void apply(NotificationBuilderWithBuilderAccessor builder) {
<add> if (Build.VERSION.SDK_INT >= 16) {
<add> NotificationCompatJellybean.addBigTextStyle(builder,
<add> mBigContentTitle,
<add> mSummaryTextSet,
<add> mSummaryText,
<add> mBigText);
<add> }
<ide> }
<ide> }
<ide>
<ide> }
<ide> }
<ide> return style;
<add> }
<add>
<add> /**
<add> * @hide
<add> */
<add> @RestrictTo(LIBRARY_GROUP)
<add> @Override
<add> public void apply(NotificationBuilderWithBuilderAccessor builder) {
<add> if (Build.VERSION.SDK_INT >= 24) {
<add> List<CharSequence> texts = new ArrayList<>();
<add> List<Long> timestamps = new ArrayList<>();
<add> List<CharSequence> senders = new ArrayList<>();
<add> List<String> dataMimeTypes = new ArrayList<>();
<add> List<Uri> dataUris = new ArrayList<>();
<add>
<add> for (MessagingStyle.Message message : mMessages) {
<add> texts.add(message.getText());
<add> timestamps.add(message.getTimestamp());
<add> senders.add(message.getSender());
<add> dataMimeTypes.add(message.getDataMimeType());
<add> dataUris.add(message.getDataUri());
<add> }
<add> NotificationCompatApi24.addMessagingStyle(builder, mUserDisplayName,
<add> mConversationTitle, texts, timestamps, senders,
<add> dataMimeTypes, dataUris);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> * @see Notification#bigContentView
<ide> */
<ide> public static class InboxStyle extends Style {
<del> ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
<add> private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>();
<ide>
<ide> public InboxStyle() {
<ide> }
<ide> public InboxStyle addLine(CharSequence cs) {
<ide> mTexts.add(Builder.limitCharSequenceLength(cs));
<ide> return this;
<add> }
<add>
<add> /**
<add> * @hide
<add> */
<add> @RestrictTo(LIBRARY_GROUP)
<add> @Override
<add> public void apply(NotificationBuilderWithBuilderAccessor builder) {
<add> if (Build.VERSION.SDK_INT >= 16) {
<add> NotificationCompatJellybean.addInboxStyle(builder,
<add> mBigContentTitle,
<add> mSummaryTextSet,
<add> mSummaryText,
<add> mTexts);
<add> }
<ide> }
<ide> }
<ide> |
|
Java | bsd-3-clause | 070c6280d40e15cc7ca87d054239ba53e9670b58 | 0 | TheGreenMachine/Zephyr-Java | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.edinarobotics.zephyr;
import com.edinarobotics.utils.autonomous.AutonomousManager;
import com.edinarobotics.utils.autonomous.AutonomousStep;
import com.edinarobotics.utils.gamepad.FilterSet;
import com.edinarobotics.utils.gamepad.Gamepad;
import com.edinarobotics.utils.gamepad.GamepadResult;
import com.edinarobotics.utils.gamepad.filters.DeadzoneFilter;
import com.edinarobotics.utils.gamepad.filters.ScalingFilter;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.SimpleRobot;
import com.edinarobotics.utils.sensors.FIRFilter;
import com.edinarobotics.zephyr.autonomous.DriveStep;
import com.edinarobotics.zephyr.autonomous.IdleStopStep;
import com.edinarobotics.zephyr.autonomous.FireShooterStep;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Zephyr extends SimpleRobot {
//Driving Variables
public double leftDrive = 0;
public double rightDrive = 0;
//Shooter Variables
public double shooterSpeed = 0;
public boolean ballLoaderUp = false;
private final double SHOOTER_SPEED_STEP = 0.0005;
private double lastManualSpeed = 0;
//Sensor Variables
private double filteringWeights[] = {.67, 17, .16};
private FIRFilter firFiltering = new FIRFilter(filteringWeights);
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
AutonomousStep[] steps = new AutonomousStep[2];
steps[0] = new FireShooterStep(0.8,this);
steps[1] = new IdleStopStep(this);
AutonomousManager manager = new AutonomousManager(steps, this);
manager.start();
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
FilterSet filters = new FilterSet();
filters.addFilter(new DeadzoneFilter(.05));
filters.addFilter(new ScalingFilter());
Gamepad gamepad1 = new Gamepad(1);
Gamepad gamepad2 = new Gamepad(2);
Components components = Components.getInstance();
while(this.isOperatorControl()&&this.isEnabled()){
GamepadResult joystick = filters.filter(gamepad1.getJoysticks());
leftDrive = joystick.getLeftY();
rightDrive = joystick.getRightY()*-1;
if(gamepad1.getRawButton(Gamepad.RIGHT_BUMPER)){
//Step speed of shooter up.
shooterSpeed -= SHOOTER_SPEED_STEP;
if(shooterSpeed<=-1){
shooterSpeed = -1;//Max speed is reverse 1 (-1).
}
lastManualSpeed = shooterSpeed;
}
else if(gamepad1.getRawButton(Gamepad.LEFT_BUMPER)){
//Step speed of shooter down.
shooterSpeed += SHOOTER_SPEED_STEP;
if(shooterSpeed>=0){
shooterSpeed = 0;
}
lastManualSpeed = shooterSpeed;
}
if(gamepad1.getRawButton(Gamepad.BUTTON_1)){
//Jump shooter speed to max.
shooterSpeed = -1; //Max is -1
}
else if(gamepad1.getRawButton(Gamepad.BUTTON_2)){
//Jump shooter speed to min.
shooterSpeed = 0;
}
else if(gamepad1.getRawButton(Gamepad.BUTTON_3)){
shooterSpeed = lastManualSpeed;
}
ballLoaderUp = gamepad1.getRawButton(Gamepad.RIGHT_TRIGGER);
mechanismSet();
}
}
public void mechanismSet(){
Components robotParts = Components.getInstance();
robotParts.driveControl.tankDrive(leftDrive, rightDrive);
robotParts.shooterJaguar.set(shooterSpeed);
robotParts.ballLoadPiston.set((ballLoaderUp ? Relay.Value.kReverse :
Relay.Value.kForward));
String shooterPowerString = "Shooter: "+shooterSpeed;
String sonarValue = "Sonar reads: " + firFiltering.filter(robotParts.sonar.getValue());
robotParts.textOutput.println(DriverStationLCD.Line.kUser2, 1, shooterPowerString);
robotParts.textOutput.println(DriverStationLCD.Line.kUser3, 1, sonarValue);
robotParts.textOutput.updateLCD();
}
public void stop(){
leftDrive = 0;
rightDrive = 0;
shooterSpeed = 0;
ballLoaderUp = false;
mechanismSet();
}
}
| src/com/edinarobotics/zephyr/Zephyr.java | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.edinarobotics.zephyr;
import com.edinarobotics.utils.autonomous.AutonomousManager;
import com.edinarobotics.utils.autonomous.AutonomousStep;
import com.edinarobotics.utils.gamepad.FilterSet;
import com.edinarobotics.utils.gamepad.Gamepad;
import com.edinarobotics.utils.gamepad.GamepadResult;
import com.edinarobotics.utils.gamepad.filters.DeadzoneFilter;
import com.edinarobotics.utils.gamepad.filters.ScalingFilter;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.SimpleRobot;
import com.edinarobotics.utils.sensors.FIRFilter;
import com.edinarobotics.zephyr.autonomous.DriveStep;
import com.edinarobotics.zephyr.autonomous.IdleStep;
import com.edinarobotics.zephyr.autonomous.FireShooterStep;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Zephyr extends SimpleRobot {
//Driving Variables
public double leftDrive = 0;
public double rightDrive = 0;
//Shooter Variables
public double shooterSpeed = 0;
public boolean ballLoaderUp = false;
private final double SHOOTER_SPEED_STEP = 0.0005;
private double lastManualSpeed = 0;
//Sensor Variables
private double filteringWeights[] = {.67, 17, .16};
private FIRFilter firFiltering = new FIRFilter(filteringWeights);
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
AutonomousStep[] steps = new AutonomousStep[2];
steps[0] = new FireShooterStep(0.8,this);
steps[1] = new IdleStep(this);
AutonomousManager manager = new AutonomousManager(steps, this);
manager.start();
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
FilterSet filters = new FilterSet();
filters.addFilter(new DeadzoneFilter(.05));
filters.addFilter(new ScalingFilter());
Gamepad gamepad1 = new Gamepad(1);
Gamepad gamepad2 = new Gamepad(2);
Components components = Components.getInstance();
while(this.isOperatorControl()&&this.isEnabled()){
GamepadResult joystick = filters.filter(gamepad1.getJoysticks());
leftDrive = joystick.getLeftY();
rightDrive = joystick.getRightY()*-1;
if(gamepad1.getRawButton(Gamepad.RIGHT_BUMPER)){
//Step speed of shooter up.
shooterSpeed -= SHOOTER_SPEED_STEP;
if(shooterSpeed<=-1){
shooterSpeed = -1;//Max speed is reverse 1 (-1).
}
lastManualSpeed = shooterSpeed;
}
else if(gamepad1.getRawButton(Gamepad.LEFT_BUMPER)){
//Step speed of shooter down.
shooterSpeed += SHOOTER_SPEED_STEP;
if(shooterSpeed>=0){
shooterSpeed = 0;
}
lastManualSpeed = shooterSpeed;
}
if(gamepad1.getRawButton(Gamepad.BUTTON_1)){
//Jump shooter speed to max.
shooterSpeed = -1; //Max is -1
}
else if(gamepad1.getRawButton(Gamepad.BUTTON_2)){
//Jump shooter speed to min.
shooterSpeed = 0;
}
else if(gamepad1.getRawButton(Gamepad.BUTTON_3)){
shooterSpeed = lastManualSpeed;
}
ballLoaderUp = gamepad1.getRawButton(Gamepad.RIGHT_TRIGGER);
mechanismSet();
}
}
public void mechanismSet(){
Components robotParts = Components.getInstance();
robotParts.driveControl.tankDrive(leftDrive, rightDrive);
robotParts.shooterJaguar.set(shooterSpeed);
robotParts.ballLoadPiston.set((ballLoaderUp ? Relay.Value.kReverse :
Relay.Value.kForward));
String shooterPowerString = "Shooter: "+shooterSpeed;
String sonarValue = "Sonar reads: " + firFiltering.filter(robotParts.sonar.getValue());
robotParts.textOutput.println(DriverStationLCD.Line.kUser2, 1, shooterPowerString);
robotParts.textOutput.println(DriverStationLCD.Line.kUser3, 1, sonarValue);
robotParts.textOutput.updateLCD();
}
public void stop(){
leftDrive = 0;
rightDrive = 0;
shooterSpeed = 0;
ballLoaderUp = false;
mechanismSet();
}
}
| Zephyr now uses IdleStopStep instead of IdleStep.
| src/com/edinarobotics/zephyr/Zephyr.java | Zephyr now uses IdleStopStep instead of IdleStep. | <ide><path>rc/com/edinarobotics/zephyr/Zephyr.java
<ide> import edu.wpi.first.wpilibj.SimpleRobot;
<ide> import com.edinarobotics.utils.sensors.FIRFilter;
<ide> import com.edinarobotics.zephyr.autonomous.DriveStep;
<del>import com.edinarobotics.zephyr.autonomous.IdleStep;
<add>import com.edinarobotics.zephyr.autonomous.IdleStopStep;
<ide> import com.edinarobotics.zephyr.autonomous.FireShooterStep;
<ide>
<ide> /**
<ide> public void autonomous() {
<ide> AutonomousStep[] steps = new AutonomousStep[2];
<ide> steps[0] = new FireShooterStep(0.8,this);
<del> steps[1] = new IdleStep(this);
<add> steps[1] = new IdleStopStep(this);
<ide> AutonomousManager manager = new AutonomousManager(steps, this);
<ide> manager.start();
<ide> } |
|
JavaScript | mit | d0f9313a41aa452030d5e4ea3d41d3ab6b913f82 | 0 | cmdalbem/bikedeboa,cmdalbem/bikedeboa | // Include gulp
const gulp = require('gulp');
// Include Our Plugins
// const jshint = require('gulp-jshint');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const babel = require('gulp-babel');
const child = require('child_process');
const autoprefixer = require('gulp-autoprefixer');
const imagemin = require('gulp-imagemin');
const runSequence = require('run-sequence');
const fileSizes = require('gulp-size');
const sourcemaps = require('gulp-sourcemaps');
const del = require('del');
const plumber = require('gulp-plumber');
const mainBowerFiles = require('main-bower-files');
const filter = require('gulp-filter');
const flatten = require('gulp-flatten');
const minifycss = require('gulp-clean-css');
const path = require('path');
const swPrecache = require('sw-precache');
const htmlmin = require('gulp-htmlmin');
const environments = require('gulp-environments');
const replace = require('gulp-replace');
const BOWER_PATH = './bower_components';
const DEST_PATH = 'dist';
// Environment specific variables
const development = environments.development;
const production = environments.production;
const facebookEnv = process.env.FACEBOOK_ENV || 'localhost';
console.log('NODE_ENV =', development() ? 'development' : 'production');
console.log('FACEBOOK_ENV =', facebookEnv);
const DATABASE_URL = process.env.DATABASE_URL || 'https://bdb-test-api.herokuapp.com';
const isProdDatabase = process.env.DATABASE_URL === 'https://bdb-api.herokuapp.com';
const FACEBOOK_IDS = {
production: '1814653185457307',
beta: '1554610834551808',
development: '116937842287717',
localhost: '478533412529512'
};
const GOOGLE_PROD = '823944645076-nr3b0ha8cet2ru3h3501vvk5dms81gkf.apps.googleusercontent.com';
const GOOGLE_DEV = '823944645076-knkq7sq3v5eflsue67os43p6dbre4e9d.apps.googleusercontent.com';
const GOOGLE_MAPS_PROD = 'AIzaSyD6TeLzQCvWopEQ7hBdbktYsmYI9aNjFc8';
const FACEBOOK_CLIENT_ID = FACEBOOK_IDS[facebookEnv];
const GOOGLE_CLIENT_ID = isProdDatabase ? GOOGLE_PROD : GOOGLE_DEV;
const GOOGLE_MAPS_ID = GOOGLE_MAPS_PROD;
// const GOOGLE_MAPS_ID = development() ? 'AIzaSyD1dNf2iN1XS0wx17MTf2lPTbPg8UIJqfA' : 'AIzaSyD6TeLzQCvWopEQ7hBdbktYsmYI9aNjFc8';
// SASS
gulp.task('sass', () => {
return gulp.src('app/scss/*.scss')
.pipe(sourcemaps.init())
.pipe(plumber())
.pipe(sass())
.on('error', function(e) {
console.log(e);
this.emit('end');
})
.pipe(autoprefixer({
browsers: ['> 1%']
}))
.pipe(concat('main.min.css'))
.pipe(minifycss())
.pipe(sourcemaps.write('.'))
.pipe(fileSizes({title: 'main.min.css', gzip: true}))
.pipe(gulp.dest('dist/css'));
});
// Javascript
gulp.task('scripts', () => {
gulp.src('app/service-worker-registration.js')
.pipe(gulp.dest('dist/'));
return gulp.src('app/js/*.js')
.pipe(development(sourcemaps.init()))
.pipe(replace('<DATABASE_URL>', DATABASE_URL))
.pipe(replace('<FACEBOOK_CLIENT_ID>', FACEBOOK_CLIENT_ID))
.pipe(replace('<GOOGLE_CLIENT_ID>', GOOGLE_CLIENT_ID))
.pipe(plumber())
.pipe(concat('app.js'))
.pipe(babel({
presets: ['es2015']
}))
// .on('error', function(e) {
// console.log(e);
// this.emit('end');
// })
// .pipe(sourcemaps.write('maps'))
// .pipe(gulp.dest('dist/js'))
.pipe(rename('app.min.js'))
.pipe(production(uglify()))
.pipe(sourcemaps.write('maps'))
.pipe(fileSizes({title: 'app.min.js', gzip: true}))
.pipe(gulp.dest('dist/js'));
});
// HTML
gulp.task('html', () => {
return gulp.src('app/*.html')
.pipe(development(replace('manifest.webmanifest', 'manifest-dev.webmanifest')))
.pipe(development(replace('/favicons/', '/favicons-dev/')))
.pipe(replace('<GOOGLE_MAPS_ID>', GOOGLE_MAPS_ID))
.pipe(production(htmlmin({
collapseWhitespace: true,
removeComments: true,
minifyJS: true,
// processScripts: ['text/x-handlebars-template']
})))
.pipe(gulp.dest('dist/'));
});
// Service Worker (sw-precache)
gulp.task('generate-service-worker', function(callback) {
swPrecache.write(`dist/service-worker.js`, {
staticFileGlobs: [
'dist/**/*.{js,html,css}',
'assets/**/*.{svg,png,jpg}',
'dist/**/*.{ttf,woff,woff2}',
'public/**/*.{webmanifest}'
],
stripPrefixMulti: {
'dist/': '/',
'assets/': '/',
'public/': '/'
},
// If handleFetch is false (i.e. because this is called from generate-service-worker-dev), then
// the service worker will precache resources but won't actually serve them.
// This allows you to test precaching behavior without worry about the cache preventing your
// local changes from being picked up during the development cycle.
handleFetch: true
}, callback);
});
// grab libraries files from bower_components, minify and push in DEST_PATH
gulp.task('bower', function() {
var jsFilter = filter('**/*.js', {restore: true}),
cssFilter = filter('**/*.css', {restore: true}),
fontFilter = filter(['**/*.eot', '**/*.woff', '**/*.svg', '**/*.ttf'], {restore: true});
// console.log(mainBowerFiles());
return gulp.src(mainBowerFiles(), { base: BOWER_PATH })
.pipe(fileSizes({title: 'bower files', gzip: true, showFiles: true}))
// grab vendor js files from bower_components, minify and push in DEST_PATH
.pipe(jsFilter)
// .pipe(gulp.dest(DEST_PATH + '/js/'))
// .pipe(concat('vendors.min.js'))
.pipe(rename({dirname: ''}))
.pipe(production(uglify()))
// .pipe(rename({
// suffix: ".min"
// }))
.pipe(fileSizes({title: 'vendors.min.js', gzip: true}))
.pipe(gulp.dest(DEST_PATH + '/js/lib/'))
.pipe(jsFilter.restore)
// grab vendor css files from bower_components, minify and push in DEST_PATH
.pipe(cssFilter)
.pipe(concat('vendors.min.css'))
// .pipe(gulp.dest(DEST_PATH + '/css'))
.pipe(production(minifycss()))
// .pipe(rename({
// suffix: ".min"
// }))
.pipe(fileSizes({title: 'vendors.min.css', gzip: true}))
.pipe(gulp.dest(DEST_PATH + '/css'))
.pipe(cssFilter.restore);
// grab vendor font files from bower_components and push in DEST_PATH
// .pipe(fontFilter)
// .pipe(flatten())
// .pipe(gulp.dest(DEST_PATH + '/fonts'));
});
gulp.task('bower-fonts', function() {
return gulp.src('./bower_components/**/*.{ttf,woff,woff2}')
.pipe(flatten())
.pipe(fileSizes({title: 'bower fonts', gzip: true}))
.pipe(gulp.dest(DEST_PATH + '/fonts'));
});
// Watch Files For Changes
gulp.task('watch', () => {
// gulp.watch('js/*.js', ['lint', 'scripts']);
// gulp.watch('assets/*', ['images']);
gulp.watch('app/js/*.js', () => {
runSequence(['scripts'], ['generate-service-worker'])
});
gulp.watch('app/scss/*.scss', () => {
runSequence(['sass'], ['generate-service-worker'])
});
gulp.watch('app/*.html', () => {
runSequence(['html'], ['generate-service-worker'])
});
});
gulp.task('images', () => {
return gulp.src('assets/img/**/*')
.pipe(imagemin())
.pipe(gulp.dest('dist/img'));
});
gulp.task('server', () => {
child.spawn('node', ['server.js']);
// var log = fs.createWriteStream('server.log', {flags: 'a'});
// server.stdout.pipe(log);
// server.stderr.pipe(log);
});
gulp.task('clean', del.bind(null, ['dist']));
gulp.task('build', () => {
runSequence(['clean'], ['bower', 'bower-fonts', 'html', 'sass', 'scripts'], ['generate-service-worker'], () => {
return gulp.src('dist/**/*').pipe(fileSizes({title: 'total output', gzip: true}));
});
});
gulp.task('default', () => {
runSequence('build', 'server', 'watch');
});
| gulpfile.js | // Include gulp
const gulp = require('gulp');
// Include Our Plugins
// const jshint = require('gulp-jshint');
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const babel = require('gulp-babel');
const child = require('child_process');
const autoprefixer = require('gulp-autoprefixer');
const imagemin = require('gulp-imagemin');
const runSequence = require('run-sequence');
const fileSizes = require('gulp-size');
const sourcemaps = require('gulp-sourcemaps');
const del = require('del');
const plumber = require('gulp-plumber');
const mainBowerFiles = require('main-bower-files');
const filter = require('gulp-filter');
const flatten = require('gulp-flatten');
const minifycss = require('gulp-clean-css');
const path = require('path');
const swPrecache = require('sw-precache');
const htmlmin = require('gulp-htmlmin');
const environments = require('gulp-environments');
const replace = require('gulp-replace');
const BOWER_PATH = './bower_components';
const DEST_PATH = 'dist';
// Environment specific variables
const development = environments.development;
const production = environments.production;
const facebookEnv = process.env.FACEBOOK_ENV || 'development';
console.log('NODE_ENV =', development() ? 'development' : 'production');
console.log('FACEBOOK_ENV =', facebookEnv);
const DATABASE_URL = process.env.DATABASE_URL || 'https://bdb-test-api.herokuapp.com';
const isProdDatabase = process.env.DATABASE_URL === 'https://bdb-api.herokuapp.com';
const FACEBOOK_IDS = {
production: '1814653185457307',
beta: '116937842287717',
development: '1554610834551808'
};
const GOOGLE_PROD = '823944645076-nr3b0ha8cet2ru3h3501vvk5dms81gkf.apps.googleusercontent.com';
const GOOGLE_DEV = '823944645076-knkq7sq3v5eflsue67os43p6dbre4e9d.apps.googleusercontent.com';
const GOOGLE_MAPS_PROD = 'AIzaSyD6TeLzQCvWopEQ7hBdbktYsmYI9aNjFc8';
const FACEBOOK_CLIENT_ID = FACEBOOK_IDS[facebookEnv];
const GOOGLE_CLIENT_ID = isProdDatabase ? GOOGLE_PROD : GOOGLE_DEV;
const GOOGLE_MAPS_ID = GOOGLE_MAPS_PROD;
// const GOOGLE_MAPS_ID = development() ? 'AIzaSyD1dNf2iN1XS0wx17MTf2lPTbPg8UIJqfA' : 'AIzaSyD6TeLzQCvWopEQ7hBdbktYsmYI9aNjFc8';
// SASS
gulp.task('sass', () => {
return gulp.src('app/scss/*.scss')
.pipe(sourcemaps.init())
.pipe(plumber())
.pipe(sass())
.on('error', function(e) {
console.log(e);
this.emit('end');
})
.pipe(autoprefixer({
browsers: ['> 1%']
}))
.pipe(concat('main.min.css'))
.pipe(minifycss())
.pipe(sourcemaps.write('.'))
.pipe(fileSizes({title: 'main.min.css', gzip: true}))
.pipe(gulp.dest('dist/css'));
});
// Javascript
gulp.task('scripts', () => {
gulp.src('app/service-worker-registration.js')
.pipe(gulp.dest('dist/'));
return gulp.src('app/js/*.js')
.pipe(development(sourcemaps.init()))
.pipe(replace('<DATABASE_URL>', DATABASE_URL))
.pipe(replace('<FACEBOOK_CLIENT_ID>', FACEBOOK_CLIENT_ID))
.pipe(replace('<GOOGLE_CLIENT_ID>', GOOGLE_CLIENT_ID))
.pipe(plumber())
.pipe(concat('app.js'))
.pipe(babel({
presets: ['es2015']
}))
// .on('error', function(e) {
// console.log(e);
// this.emit('end');
// })
// .pipe(sourcemaps.write('maps'))
// .pipe(gulp.dest('dist/js'))
.pipe(rename('app.min.js'))
.pipe(production(uglify()))
.pipe(sourcemaps.write('maps'))
.pipe(fileSizes({title: 'app.min.js', gzip: true}))
.pipe(gulp.dest('dist/js'));
});
// HTML
gulp.task('html', () => {
return gulp.src('app/*.html')
.pipe(development(replace('manifest.webmanifest', 'manifest-dev.webmanifest')))
.pipe(development(replace('/favicons/', '/favicons-dev/')))
.pipe(replace('<GOOGLE_MAPS_ID>', GOOGLE_MAPS_ID))
.pipe(production(htmlmin({
collapseWhitespace: true,
removeComments: true,
minifyJS: true,
// processScripts: ['text/x-handlebars-template']
})))
.pipe(gulp.dest('dist/'));
});
// Service Worker (sw-precache)
gulp.task('generate-service-worker', function(callback) {
swPrecache.write(`dist/service-worker.js`, {
staticFileGlobs: [
'dist/**/*.{js,html,css}',
'assets/**/*.{svg,png,jpg}',
'dist/**/*.{ttf,woff,woff2}',
'public/**/*.{webmanifest}'
],
stripPrefixMulti: {
'dist/': '/',
'assets/': '/',
'public/': '/'
},
// If handleFetch is false (i.e. because this is called from generate-service-worker-dev), then
// the service worker will precache resources but won't actually serve them.
// This allows you to test precaching behavior without worry about the cache preventing your
// local changes from being picked up during the development cycle.
handleFetch: true
}, callback);
});
// grab libraries files from bower_components, minify and push in DEST_PATH
gulp.task('bower', function() {
var jsFilter = filter('**/*.js', {restore: true}),
cssFilter = filter('**/*.css', {restore: true}),
fontFilter = filter(['**/*.eot', '**/*.woff', '**/*.svg', '**/*.ttf'], {restore: true});
// console.log(mainBowerFiles());
return gulp.src(mainBowerFiles(), { base: BOWER_PATH })
.pipe(fileSizes({title: 'bower files', gzip: true, showFiles: true}))
// grab vendor js files from bower_components, minify and push in DEST_PATH
.pipe(jsFilter)
// .pipe(gulp.dest(DEST_PATH + '/js/'))
// .pipe(concat('vendors.min.js'))
.pipe(rename({dirname: ''}))
.pipe(production(uglify()))
// .pipe(rename({
// suffix: ".min"
// }))
.pipe(fileSizes({title: 'vendors.min.js', gzip: true}))
.pipe(gulp.dest(DEST_PATH + '/js/lib/'))
.pipe(jsFilter.restore)
// grab vendor css files from bower_components, minify and push in DEST_PATH
.pipe(cssFilter)
.pipe(concat('vendors.min.css'))
// .pipe(gulp.dest(DEST_PATH + '/css'))
.pipe(production(minifycss()))
// .pipe(rename({
// suffix: ".min"
// }))
.pipe(fileSizes({title: 'vendors.min.css', gzip: true}))
.pipe(gulp.dest(DEST_PATH + '/css'))
.pipe(cssFilter.restore);
// grab vendor font files from bower_components and push in DEST_PATH
// .pipe(fontFilter)
// .pipe(flatten())
// .pipe(gulp.dest(DEST_PATH + '/fonts'));
});
gulp.task('bower-fonts', function() {
return gulp.src('./bower_components/**/*.{ttf,woff,woff2}')
.pipe(flatten())
.pipe(fileSizes({title: 'bower fonts', gzip: true}))
.pipe(gulp.dest(DEST_PATH + '/fonts'));
});
// Watch Files For Changes
gulp.task('watch', () => {
// gulp.watch('js/*.js', ['lint', 'scripts']);
// gulp.watch('assets/*', ['images']);
gulp.watch('app/js/*.js', () => {
runSequence(['scripts'], ['generate-service-worker'])
});
gulp.watch('app/scss/*.scss', () => {
runSequence(['sass'], ['generate-service-worker'])
});
gulp.watch('app/*.html', () => {
runSequence(['html'], ['generate-service-worker'])
});
});
gulp.task('images', () => {
return gulp.src('assets/img/**/*')
.pipe(imagemin())
.pipe(gulp.dest('dist/img'));
});
gulp.task('server', () => {
child.spawn('node', ['server.js']);
// var log = fs.createWriteStream('server.log', {flags: 'a'});
// server.stdout.pipe(log);
// server.stderr.pipe(log);
});
gulp.task('clean', del.bind(null, ['dist']));
gulp.task('build', () => {
runSequence(['clean'], ['bower', 'bower-fonts', 'html', 'sass', 'scripts'], ['generate-service-worker'], () => {
return gulp.src('dist/**/*').pipe(fileSizes({title: 'total output', gzip: true}));
});
});
gulp.task('default', () => {
runSequence('build', 'server', 'watch');
});
| rearrange Facebook API keys
| gulpfile.js | rearrange Facebook API keys | <ide><path>ulpfile.js
<ide> // Environment specific variables
<ide> const development = environments.development;
<ide> const production = environments.production;
<del>const facebookEnv = process.env.FACEBOOK_ENV || 'development';
<add>const facebookEnv = process.env.FACEBOOK_ENV || 'localhost';
<ide>
<ide> console.log('NODE_ENV =', development() ? 'development' : 'production');
<ide> console.log('FACEBOOK_ENV =', facebookEnv);
<ide>
<ide> const FACEBOOK_IDS = {
<ide> production: '1814653185457307',
<del> beta: '116937842287717',
<del> development: '1554610834551808'
<add> beta: '1554610834551808',
<add> development: '116937842287717',
<add> localhost: '478533412529512'
<ide> };
<ide> const GOOGLE_PROD = '823944645076-nr3b0ha8cet2ru3h3501vvk5dms81gkf.apps.googleusercontent.com';
<ide> const GOOGLE_DEV = '823944645076-knkq7sq3v5eflsue67os43p6dbre4e9d.apps.googleusercontent.com'; |
|
Java | epl-1.0 | 768e456f6a1a3d4c8fca8e29077c75168cc9f79c | 0 | Cooperate-Project/Cooperate,Cooperate-Project/Cooperate,Cooperate-Project/CooperateModelingEnvironment,Cooperate-Project/CooperateModelingEnvironment | package de.cooperateproject.modeling.textual.xtext.generator.resources;
import org.eclipse.xtext.Grammar;
import org.eclipse.xtext.GrammarUtil;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.scoping.IGlobalScopeProvider;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.ui.editor.model.XtextDocumentProvider;
import org.eclipse.xtext.ui.resource.IResourceSetProvider;
import org.eclipse.xtext.ui.resource.XtextLiveScopeResourceSetProvider;
import org.eclipse.xtext.xtext.generator.AbstractXtextGeneratorFragment;
import org.eclipse.xtext.xtext.generator.XtextGeneratorNaming;
import org.eclipse.xtext.xtext.generator.model.FileAccessFactory;
import org.eclipse.xtext.xtext.generator.model.GuiceModuleAccess;
import org.eclipse.xtext.xtext.generator.model.JavaFileAccess;
import org.eclipse.xtext.xtext.generator.model.TypeReference;
import com.google.inject.Inject;
import de.cooperateproject.modeling.textual.xtext.runtime.editor.CooperateCDOXtextDocumentProvider;
import de.cooperateproject.modeling.textual.xtext.runtime.editor.CooperateXtextDocument;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.IIssueCodeRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.IssueCodeRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.AutomatedIssueResolutionFactoryRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.IAutomatedIssueResolutionFactoryRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.IAutomatedIssueResolutionProvider;
import de.cooperateproject.modeling.textual.xtext.runtime.resources.CooperateResourceSet;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.ConventionalUMLUriFinder;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.CooperateGlobalScopeProvider;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.DefaultUMLPrimitiveTypeSelector;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.IUMLPrimitiveTypeSelector;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.IUMLUriFinder;
import de.cooperateproject.modeling.textual.xtext.runtime.validator.CooperateAutomatedValidator;
import de.cooperateproject.modeling.textual.xtext.runtime.validator.ICooperateAutomatedValidator;
@SuppressWarnings("restriction")
public class CooperateResourceHandlingBindingsFragment2 extends AbstractXtextGeneratorFragment {
@Inject
Grammar grammar;
@Inject
XtextGeneratorNaming naming;
@Inject
FileAccessFactory fileAccessFactory;
@Override
public void generate() {
registerGuiceBindingsUi();
registerGuiceBindingsRt();
generateIAutomatedIssueResolutionProvider();
generateAutomatedIssueResolutionFactoryBase();
}
private static TypeReference typeRef(Class<?> clazz) {
return TypeReference.typeRef(clazz);
}
private static TypeReference typeRef(String fqn) {
return TypeReference.typeRef(fqn);
}
private void registerGuiceBindingsRt() {
new GuiceModuleAccess.BindingFactory()
.addTypeToType(typeRef(XtextResourceSet.class), typeRef(CooperateResourceSet.class))
.addTypeToType(typeRef(IGlobalScopeProvider.class), typeRef(CooperateGlobalScopeProvider.class))
.addTypeToType(typeRef(IUMLUriFinder.class), typeRef(ConventionalUMLUriFinder.class))
.addTypeToType(typeRef(IUMLPrimitiveTypeSelector.class), typeRef(DefaultUMLPrimitiveTypeSelector.class))
.addTypeToType(typeRef(IAutomatedIssueResolutionProvider.class),
typeRef(getAutomatedIssueResolutionProviderName()))
.addTypeToType(typeRef(IIssueCodeRegistry.class), typeRef(IssueCodeRegistry.class))
.addTypeToType(typeRef(ICooperateAutomatedValidator.class), typeRef(CooperateAutomatedValidator.class))
.addTypeToType(typeRef(IAutomatedIssueResolutionFactoryRegistry.class),
typeRef(AutomatedIssueResolutionFactoryRegistry.class))
.contributeTo(getLanguage().getRuntimeGenModule());
getProjectConfig().getRuntime().getManifest().getRequiredBundles()
.add("de.cooperateproject.modeling.textual.xtext.runtime;visibility:=reexport");
}
private void registerGuiceBindingsUi() {
new GuiceModuleAccess.BindingFactory()
.addTypeToType(typeRef(XtextDocument.class), typeRef(CooperateXtextDocument.class))
.addTypeToType(typeRef(XtextDocumentProvider.class), typeRef(CooperateCDOXtextDocumentProvider.class))
.addTypeToType(typeRef(IResourceSetProvider.class), typeRef(XtextLiveScopeResourceSetProvider.class))
.contributeTo(getLanguage().getEclipsePluginGenModule());
getProjectConfig().getEclipsePlugin().getManifest().getRequiredBundles()
.add("de.cooperateproject.modeling.textual.xtext.runtime.ui");
}
private void generateIAutomatedIssueResolutionProvider() {
JavaFileAccess jva = fileAccessFactory.createJavaFile(typeRef(getAutomatedIssueResolutionProviderName()));
AutomatedIssueResolutionProviderGenerator generator = new AutomatedIssueResolutionProviderGenerator(naming,
grammar);
generator.create(jva, getAutomatedIssueResolutionProviderSimpleName());
jva.writeTo(getProjectConfig().getRuntime().getSrc());
getProjectConfig().getRuntime().getManifest().getExportedPackages().add(getIssuesPackageName());
}
private void generateAutomatedIssueResolutionFactoryBase() {
TypeReference tr = typeRef(getAutomatedIssueResolutionFactoryBaseName());
JavaFileAccess jva = fileAccessFactory.createJavaFile(tr);
AutomatedIssueResolutionFactoryBaseGenerator generator = new AutomatedIssueResolutionFactoryBaseGenerator(
naming, grammar);
generator.create(jva, tr.getSimpleName());
jva.writeTo(getProjectConfig().getRuntime().getSrc());
getProjectConfig().getRuntime().getManifest().getExportedPackages().add(getIssuesPackageName());
}
private String getAutomatedIssueResolutionFactoryBaseName() {
return getIssuesPackageName() + "." + GrammarUtil.getSimpleName(grammar)
+ "AutomatedIssueResolutionFactoryBase";
}
private String getAutomatedIssueResolutionProviderName() {
return getIssuesPackageName() + "." + getAutomatedIssueResolutionProviderSimpleName();
}
private String getIssuesPackageName() {
return naming.getRuntimeBasePackage(grammar) + ".issues";
}
private String getAutomatedIssueResolutionProviderSimpleName() {
return GrammarUtil.getSimpleName(grammar) + "AutomatedIssueResolutionProvider";
}
}
| bundles/de.cooperateproject.modeling.textual.xtext.generator/src/de/cooperateproject/modeling/textual/xtext/generator/resources/CooperateResourceHandlingBindingsFragment2.java | package de.cooperateproject.modeling.textual.xtext.generator.resources;
import org.eclipse.xtext.Grammar;
import org.eclipse.xtext.GrammarUtil;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.scoping.IGlobalScopeProvider;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.ui.editor.model.XtextDocumentProvider;
import org.eclipse.xtext.ui.resource.IResourceSetProvider;
import org.eclipse.xtext.ui.resource.XtextLiveScopeResourceSetProvider;
import org.eclipse.xtext.xtext.generator.AbstractXtextGeneratorFragment;
import org.eclipse.xtext.xtext.generator.XtextGeneratorNaming;
import org.eclipse.xtext.xtext.generator.model.FileAccessFactory;
import org.eclipse.xtext.xtext.generator.model.GuiceModuleAccess;
import org.eclipse.xtext.xtext.generator.model.JavaFileAccess;
import org.eclipse.xtext.xtext.generator.model.TypeReference;
import com.google.inject.Inject;
import de.cooperateproject.modeling.textual.common.scoping.ConventionalUMLUriFinder;
import de.cooperateproject.modeling.textual.xtext.runtime.editor.CooperateCDOXtextDocumentProvider;
import de.cooperateproject.modeling.textual.xtext.runtime.editor.CooperateXtextDocument;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.IIssueCodeRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.IssueCodeRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.AutomatedIssueResolutionFactoryRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.IAutomatedIssueResolutionFactoryRegistry;
import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.IAutomatedIssueResolutionProvider;
import de.cooperateproject.modeling.textual.xtext.runtime.resources.CooperateResourceSet;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.CooperateGlobalScopeProvider;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.DefaultUMLPrimitiveTypeSelector;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.IUMLPrimitiveTypeSelector;
import de.cooperateproject.modeling.textual.xtext.runtime.scoping.IUMLUriFinder;
import de.cooperateproject.modeling.textual.xtext.runtime.validator.CooperateAutomatedValidator;
import de.cooperateproject.modeling.textual.xtext.runtime.validator.ICooperateAutomatedValidator;
@SuppressWarnings("restriction")
public class CooperateResourceHandlingBindingsFragment2 extends AbstractXtextGeneratorFragment {
@Inject
Grammar grammar;
@Inject
XtextGeneratorNaming naming;
@Inject
FileAccessFactory fileAccessFactory;
@Override
public void generate() {
registerGuiceBindingsUi();
registerGuiceBindingsRt();
generateIAutomatedIssueResolutionProvider();
generateAutomatedIssueResolutionFactoryBase();
}
private static TypeReference typeRef(Class<?> clazz) {
return TypeReference.typeRef(clazz);
}
private static TypeReference typeRef(String fqn) {
return TypeReference.typeRef(fqn);
}
private void registerGuiceBindingsRt() {
new GuiceModuleAccess.BindingFactory()
.addTypeToType(typeRef(XtextResourceSet.class), typeRef(CooperateResourceSet.class))
.addTypeToType(typeRef(IGlobalScopeProvider.class), typeRef(CooperateGlobalScopeProvider.class))
.addTypeToType(typeRef(IUMLUriFinder.class), typeRef(ConventionalUMLUriFinder.class))
.addTypeToType(typeRef(IUMLPrimitiveTypeSelector.class), typeRef(DefaultUMLPrimitiveTypeSelector.class))
.addTypeToType(typeRef(IAutomatedIssueResolutionProvider.class),
typeRef(getAutomatedIssueResolutionProviderName()))
.addTypeToType(typeRef(IIssueCodeRegistry.class), typeRef(IssueCodeRegistry.class))
.addTypeToType(typeRef(ICooperateAutomatedValidator.class), typeRef(CooperateAutomatedValidator.class))
.addTypeToType(typeRef(IAutomatedIssueResolutionFactoryRegistry.class),
typeRef(AutomatedIssueResolutionFactoryRegistry.class))
.contributeTo(getLanguage().getRuntimeGenModule());
getProjectConfig().getRuntime().getManifest().getRequiredBundles()
.add("de.cooperateproject.modeling.textual.xtext.runtime;visibility:=reexport");
}
private void registerGuiceBindingsUi() {
new GuiceModuleAccess.BindingFactory()
.addTypeToType(typeRef(XtextDocument.class), typeRef(CooperateXtextDocument.class))
.addTypeToType(typeRef(XtextDocumentProvider.class), typeRef(CooperateCDOXtextDocumentProvider.class))
.addTypeToType(typeRef(IResourceSetProvider.class), typeRef(XtextLiveScopeResourceSetProvider.class))
.contributeTo(getLanguage().getEclipsePluginGenModule());
getProjectConfig().getEclipsePlugin().getManifest().getRequiredBundles()
.add("de.cooperateproject.modeling.textual.xtext.runtime.ui");
}
private void generateIAutomatedIssueResolutionProvider() {
JavaFileAccess jva = fileAccessFactory.createJavaFile(typeRef(getAutomatedIssueResolutionProviderName()));
AutomatedIssueResolutionProviderGenerator generator = new AutomatedIssueResolutionProviderGenerator(naming,
grammar);
generator.create(jva, getAutomatedIssueResolutionProviderSimpleName());
jva.writeTo(getProjectConfig().getRuntime().getSrc());
getProjectConfig().getRuntime().getManifest().getExportedPackages().add(getIssuesPackageName());
}
private void generateAutomatedIssueResolutionFactoryBase() {
TypeReference tr = typeRef(getAutomatedIssueResolutionFactoryBaseName());
JavaFileAccess jva = fileAccessFactory.createJavaFile(tr);
AutomatedIssueResolutionFactoryBaseGenerator generator = new AutomatedIssueResolutionFactoryBaseGenerator(
naming, grammar);
generator.create(jva, tr.getSimpleName());
jva.writeTo(getProjectConfig().getRuntime().getSrc());
getProjectConfig().getRuntime().getManifest().getExportedPackages().add(getIssuesPackageName());
}
private String getAutomatedIssueResolutionFactoryBaseName() {
return getIssuesPackageName() + "." + GrammarUtil.getSimpleName(grammar)
+ "AutomatedIssueResolutionFactoryBase";
}
private String getAutomatedIssueResolutionProviderName() {
return getIssuesPackageName() + "." + getAutomatedIssueResolutionProviderSimpleName();
}
private String getIssuesPackageName() {
return naming.getRuntimeBasePackage(grammar) + ".issues";
}
private String getAutomatedIssueResolutionProviderSimpleName() {
return GrammarUtil.getSimpleName(grammar) + "AutomatedIssueResolutionProvider";
}
}
| Moved resolving of missing UML comments to commons bundle, somehow this change escapted the previous commit.
| bundles/de.cooperateproject.modeling.textual.xtext.generator/src/de/cooperateproject/modeling/textual/xtext/generator/resources/CooperateResourceHandlingBindingsFragment2.java | Moved resolving of missing UML comments to commons bundle, somehow this change escapted the previous commit. | <ide><path>undles/de.cooperateproject.modeling.textual.xtext.generator/src/de/cooperateproject/modeling/textual/xtext/generator/resources/CooperateResourceHandlingBindingsFragment2.java
<ide>
<ide> import com.google.inject.Inject;
<ide>
<del>import de.cooperateproject.modeling.textual.common.scoping.ConventionalUMLUriFinder;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.editor.CooperateCDOXtextDocumentProvider;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.editor.CooperateXtextDocument;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.issues.IIssueCodeRegistry;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.IAutomatedIssueResolutionFactoryRegistry;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.issues.automatedfixing.IAutomatedIssueResolutionProvider;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.resources.CooperateResourceSet;
<add>import de.cooperateproject.modeling.textual.xtext.runtime.scoping.ConventionalUMLUriFinder;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.scoping.CooperateGlobalScopeProvider;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.scoping.DefaultUMLPrimitiveTypeSelector;
<ide> import de.cooperateproject.modeling.textual.xtext.runtime.scoping.IUMLPrimitiveTypeSelector; |
|
Java | lgpl-2.1 | bb1719a64a57eefddcf528e028f74ab272ff721a | 0 | xxv/SimpleContentProvider | package edu.mit.mobile.android.content.column;
/*
* Copyright (C) 2011 MIT Mobile Experience Lab
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import android.database.DatabaseUtils;
import edu.mit.mobile.android.content.AndroidVersions;
import edu.mit.mobile.android.content.ContentItem;
import edu.mit.mobile.android.content.DBTable;
import edu.mit.mobile.android.content.SQLGenUtils;
import edu.mit.mobile.android.content.SQLGenerationException;
import edu.mit.mobile.android.content.SimpleContentProvider;
/**
* This defines a database column for use with the {@link SimpleContentProvider} framework. This
* should be used on static final Strings, the value of which defines the column name. Various
* column definition parameters can be set.
*
* eg.:
*
* <pre>
* @DBColumn(type=IntegerColumn.class)
* final static String MY_COL = "my_col"
* </pre>
*
* The names and structure of this are based loosely on Django's Model/Field framework.
*
* @author <a href="mailto:[email protected]">Steve Pomeroy</a>
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface DBColumn {
// this is required because Java doesn't allow null as a default value.
// For some reason, null is not considered a constant expression.
public static final String NULL = "██████NULL██████";
public static final long NULL_LONG = Long.MIN_VALUE;
public static final int NULL_INT = Integer.MIN_VALUE;
public static final float NULL_FLOAT = Float.MIN_VALUE;
public static final double NULL_DOUBLE = Double.MIN_VALUE;
/**
* Specify one of the column types by passing its class object.
*
*
* @see IntegerColumn
* @see TextColumn
* @see TimestampColumn
* @see DatetimeColumn
*
* @return the column type
*/
Class<? extends DBColumnType<?>> type();
/**
* Sets this column to be NOT NULL.
*
* @return true if the column is NOT NULL
*/
boolean notnull() default false;
/**
* Sets this column to be a PRIMARY KEY.
*
* @return true if the column is a primary key
*/
boolean primaryKey() default false;
/**
* Adds the AUTOINCREMENT flag if {@link #primaryKey()} has also been set.
*
* @return true if this column should be auto-incremented
*/
boolean autoIncrement() default false;
/**
* Sets a default value for the column. Values are automatically quoted as strings in SQL. To
* avoid escaping (for use with reserved words and such), prefix with
* {@link DBColumnType#DEFAULT_VALUE_ESCAPE}.
*
* @return the default value
*/
String defaultValue() default NULL;
/**
* Sets the default value for the column.
*
* @return the default value
*/
int defaultValueInt() default NULL_INT;
/**
* Sets the default value for the column.
*
* @return the default value
*/
long defaultValueLong() default NULL_LONG;
/**
* Sets the default value for the column.
*
* @return the default value
*/
float defaultValueFloat() default NULL_FLOAT;
/**
* Sets the default value for the column.
*
* @return the default value
*/
double defaultValueDouble() default NULL_DOUBLE;
/**
* If true, ensures that this column is unique.
*
* @return true if this column is UNIQUE
*/
boolean unique() default false;
public static enum OnConflict {
UNSPECIFIED, ROLLBACK, ABORT, FAIL, IGNORE, REPLACE
}
/**
* If the column is marked unique, this determines what to do if there's a conflict. This is
* ignored if the column is not unique.
*
* @return the desired conflict resolution
*/
OnConflict onConflict() default OnConflict.UNSPECIFIED;
public static enum CollationName {
DEFAULT, BINARY, NOCASE, RTRIM
}
/**
* Defines a collation for the column.
*
* @return the collation type
*/
CollationName collate() default CollationName.DEFAULT;
/**
* Suffixes the column declaration with this string.
*
* @return a string of any supplemental column declarations
*/
String extraColDef() default NULL;
/**
* Column type-specific flags.
*
* @return
*/
int flags() default 0;
/**
* Generates SQL from a {@link ContentItem}. This inspects the class, parses all its
* annotations, and so on.
*
* @author <a href="mailto:[email protected]">Steve Pomeroy</a>
* @see DBColumn
*
*/
public static class Extractor {
private static final String DOUBLE_ESCAPE = DBColumnType.DEFAULT_VALUE_ESCAPE
+ DBColumnType.DEFAULT_VALUE_ESCAPE;
private final Class<? extends ContentItem> mDataItem;
private final String mTable;
public Extractor(Class<? extends ContentItem> contentItem) throws SQLGenerationException {
mDataItem = contentItem;
mTable = extractTableName(mDataItem);
}
/**
* Inspects the {@link ContentItem} and extracts a table name from it. If there is a @DBTable
* annotation, uses that name. Otherwise, uses a lower-cased, sanitized version of the
* classname.
*
* @return a valid table name
* @throws SQLGenerationException
*/
public static String extractTableName(Class<? extends ContentItem> mDataItem)
throws SQLGenerationException {
String tableName = null;
final DBTable tableNameAnnotation = mDataItem.getAnnotation(DBTable.class);
if (tableNameAnnotation != null) {
tableName = tableNameAnnotation.value();
if (!SQLGenUtils.isValidName(tableName)) {
throw new SQLGenerationException("Illegal table name: '" + tableName + "'");
}
} else {
tableName = SQLGenUtils.toValidName(mDataItem);
}
return tableName;
}
/**
* The table name is auto-generated using {@link #extractTableName(Class)}.
*
* @return the name of the table for this {@link ContentItem}.
*/
public String getTableName() {
return mTable;
}
/**
* For a given {@code field}, return the value of the field. All fields must be
* {@code static String}s whose content is the column name. This method ensures that they
* fit this requirement.
*
* @param field
* the {@code static String} field
* @return the value of the field.
* @throws SQLGenerationException
* if the field doesn't meet the necessary requirements.
*/
public String getDbColumnName(Field field) throws SQLGenerationException {
String dbColumnName;
try {
dbColumnName = (String) field.get(null);
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException("programming error", e);
} catch (final IllegalAccessException e) {
throw new SQLGenerationException("field '" + field.getName()
+ "' cannot be accessed", e);
} catch (final NullPointerException e) {
throw new SQLGenerationException("field '" + field.getName() + "' is not static", e);
}
if (!SQLGenUtils.isValidName(dbColumnName)) {
throw new SQLGenerationException("@DBColumn '" + dbColumnName
+ "' is not a valid SQLite column name.");
}
return dbColumnName;
}
private void appendColumnDef(StringBuilder tableSQL, DBColumn t, Field field,
List<String> preSql, List<String> postSql) throws IllegalAccessException,
InstantiationException {
@SuppressWarnings("rawtypes")
final Class<? extends DBColumnType> columnType = t.type();
@SuppressWarnings("rawtypes")
final DBColumnType typeInstance = columnType.newInstance();
final String colName = getDbColumnName(field);
tableSQL.append(typeInstance.toCreateColumn(colName));
if (t.primaryKey()) {
tableSQL.append(" PRIMARY KEY");
if (t.autoIncrement()) {
tableSQL.append(" AUTOINCREMENT");
}
}
if (t.unique()) {
tableSQL.append(" UNIQUE");
if (t.onConflict() != OnConflict.UNSPECIFIED) {
tableSQL.append(" ON CONFLICT");
}
switch (t.onConflict()) {
case ABORT:
tableSQL.append(" ABORT");
break;
case FAIL:
tableSQL.append(" FAIL");
break;
case IGNORE:
tableSQL.append(" IGNORE");
break;
case REPLACE:
tableSQL.append(" REPLACE");
break;
case ROLLBACK:
tableSQL.append(" ROLLBACK");
break;
case UNSPECIFIED:
break;
}
}
if (t.notnull()) {
tableSQL.append(" NOT NULL");
}
switch (t.collate()) {
case BINARY:
tableSQL.append(" COLLATE BINARY");
break;
case NOCASE:
tableSQL.append(" COLLATE NOCASE");
break;
case RTRIM:
tableSQL.append(" COLLATE RTRIM");
break;
case DEFAULT:
break;
}
final String defaultValue = t.defaultValue();
final int defaultValueInt = t.defaultValueInt();
final long defaultValueLong = t.defaultValueLong();
final float defaultValueFloat = t.defaultValueFloat();
final double defaultValueDouble = t.defaultValueDouble();
if (!DBColumn.NULL.equals(defaultValue)) {
tableSQL.append(" DEFAULT ");
// double-escape to insert the escape character literally.
if (defaultValue.startsWith(DOUBLE_ESCAPE)) {
DatabaseUtils.appendValueToSql(tableSQL, defaultValue.substring(1));
} else if (defaultValue.startsWith(DBColumnType.DEFAULT_VALUE_ESCAPE)) {
tableSQL.append(defaultValue.substring(1));
} else {
DatabaseUtils.appendValueToSql(tableSQL, defaultValue);
}
} else if (defaultValueInt != DBColumn.NULL_INT) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueInt);
} else if (defaultValueLong != DBColumn.NULL_LONG) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueLong);
} else if (defaultValueFloat != DBColumn.NULL_FLOAT) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueFloat);
} else if (defaultValueDouble != DBColumn.NULL_DOUBLE) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueDouble);
}
final String extraColDef = t.extraColDef();
if (!DBColumn.NULL.equals(extraColDef)) {
tableSQL.append(extraColDef);
}
final int flags = t.flags();
final String pre = typeInstance.preTableSql(mTable, colName, flags);
if (pre != null) {
preSql.add(pre);
}
final String post = typeInstance.postTableSql(mTable, colName, flags);
if (post != null) {
postSql.add(post);
}
}
/**
* Gets the database column type of the field. The field must have a {@link DBColumn}
* annotation.
*
* @param fieldName
* the name of the field. This is whatever name you've used for the
* {@code static String}, not its value.
* @return the {@link DBColumnType} of the field
* @throws SQLGenerationException
* @throws NoSuchFieldException
*/
public Class<? extends DBColumnType<?>> getFieldType(String fieldName)
throws SQLGenerationException, NoSuchFieldException {
final Field field = mDataItem.getField(fieldName);
return getFieldType(field);
}
/**
* Gets the database column type of the field. The field must have a {@link DBColumn}
* annotation.
*
* @param field
* the given {@code static String} field.
* @return the type of the field, as defined in the annotation or {@code null} if the given
* field has no {@link DBColumn} annotation.
* @throws SQLGenerationException
* if an annotation is present, but there's an error in the field definition.
*/
public Class<? extends DBColumnType<?>> getFieldType(Field field)
throws SQLGenerationException {
try {
final DBColumn t = field.getAnnotation(DBColumn.class);
if (t == null) {
return null;
}
final int m = field.getModifiers();
if (!String.class.equals(field.getType()) || !Modifier.isStatic(m)
|| !Modifier.isFinal(m)) {
throw new SQLGenerationException(
"Columns defined using @DBColumn must be static final Strings.");
}
return t.type();
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException(
"field claimed to be static, but something went wrong on invocation", e);
} catch (final SecurityException e) {
throw new SQLGenerationException("cannot access class fields", e);
}
}
/**
* Generates SQL code for creating this object's table. Creation is done by inspecting the
* static strings that are marked with {@link DBColumn} annotations.
*
* @return CREATE TABLE code for creating this table.
* @throws SQLGenerationException
* if there were any problems creating the table
* @see DBColumn
* @see DBTable
*/
public List<String> getTableCreation() throws SQLGenerationException {
// pre, create table, post
final LinkedList<String> preTableSql = new LinkedList<String>();
final LinkedList<String> postTableSql = new LinkedList<String>();
try {
final StringBuilder tableSQL = new StringBuilder();
tableSQL.append("CREATE TABLE ");
tableSQL.append(mTable);
tableSQL.append(" (");
boolean needSep = false;
for (final Field field : mDataItem.getFields()) {
final DBColumn t = field.getAnnotation(DBColumn.class);
final DBForeignKeyColumn fk = field.getAnnotation(DBForeignKeyColumn.class);
if (t == null && fk == null) {
continue;
}
final int m = field.getModifiers();
if (!String.class.equals(field.getType()) || !Modifier.isStatic(m)
|| !Modifier.isFinal(m)) {
throw new SQLGenerationException(
"Columns defined using @DBColumn must be static final Strings.");
}
if (needSep) {
tableSQL.append(',');
}
if (t != null) {
appendColumnDef(tableSQL, t, field, preTableSql, postTableSql);
} else if (fk != null) {
appendFKColumnDef(tableSQL, fk, field);
}
needSep = true;
}
tableSQL.append(")");
preTableSql.add(tableSQL.toString());
preTableSql.addAll(postTableSql);
return preTableSql;
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException(
"field claimed to be static, but something went wrong on invocation", e);
} catch (final IllegalAccessException e) {
throw new SQLGenerationException("default constructor not visible", e);
} catch (final SecurityException e) {
throw new SQLGenerationException("cannot access class fields", e);
} catch (final InstantiationException e) {
throw new SQLGenerationException("cannot instantiate field type class", e);
}
}
private void appendFKColumnDef(StringBuilder tableSQL, DBForeignKeyColumn fk, Field field)
throws IllegalArgumentException, IllegalAccessException {
tableSQL.append("'");
tableSQL.append(getDbColumnName(field));
tableSQL.append("' INTEGER");
if (fk.notnull()) {
tableSQL.append(" NOT NULL");
}
if (AndroidVersions.SQLITE_SUPPORTS_FOREIGN_KEYS) {
tableSQL.append(" REFERENCES ");
final String parentTable = extractTableName(fk.parent());
tableSQL.append("'");
tableSQL.append(parentTable);
tableSQL.append("' (");
tableSQL.append(ContentItem._ID);
tableSQL.append(") ON DELETE CASCADE"); // TODO make this configurable
}
}
}
}
| src/edu/mit/mobile/android/content/column/DBColumn.java | package edu.mit.mobile.android.content.column;
/*
* Copyright (C) 2011 MIT Mobile Experience Lab
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import android.database.DatabaseUtils;
import edu.mit.mobile.android.content.AndroidVersions;
import edu.mit.mobile.android.content.ContentItem;
import edu.mit.mobile.android.content.DBTable;
import edu.mit.mobile.android.content.SQLGenUtils;
import edu.mit.mobile.android.content.SQLGenerationException;
import edu.mit.mobile.android.content.SimpleContentProvider;
/**
* This defines a database column for use with the {@link SimpleContentProvider} framework. This
* should be used on static final Strings, the value of which defines the column name. Various
* column definition parameters can be set.
*
* eg.:
*
* <pre>
* @DBColumn(type=IntegerColumn.class)
* final static String MY_COL = "my_col"
* </pre>
*
* The names and structure of this are based loosely on Django's Model/Field framework.
*
* @author steve
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface DBColumn {
// this is required because Java doesn't allow null as a default value.
// For some reason, null is not considered a constant expression.
public static final String NULL = "██████NULL██████";
public static final long NULL_LONG = Long.MIN_VALUE;
public static final int NULL_INT = Integer.MIN_VALUE;
public static final float NULL_FLOAT = Float.MIN_VALUE;
public static final double NULL_DOUBLE = Double.MIN_VALUE;
/**
* Specify one of the column types by passing its class object.
*
*
* @see IntegerColumn
* @see TextColumn
* @see TimestampColumn
* @see DatetimeColumn
*
* @return the column type
*/
Class<? extends DBColumnType<?>> type();
/**
* Sets this column to be NOT NULL.
*
* @return true if the column is NOT NULL
*/
boolean notnull() default false;
/**
* Sets this column to be a PRIMARY KEY.
*
* @return true if the column is a primary key
*/
boolean primaryKey() default false;
/**
* Adds the AUTOINCREMENT flag if {@link #primaryKey()} has also been set.
*
* @return true if this column should be auto-incremented
*/
boolean autoIncrement() default false;
/**
* Sets a default value for the column. Values are automatically quoted as strings in SQL. To
* avoid escaping (for use with reserved words and such), prefix with
* {@link DBColumnType#DEFAULT_VALUE_ESCAPE}.
*
* @return the default value
*/
String defaultValue() default NULL;
/**
* Sets the default value for the column.
*
* @return the default value
*/
int defaultValueInt() default NULL_INT;
/**
* Sets the default value for the column.
*
* @return the default value
*/
long defaultValueLong() default NULL_LONG;
/**
* Sets the default value for the column.
*
* @return the default value
*/
float defaultValueFloat() default NULL_FLOAT;
/**
* Sets the default value for the column.
*
* @return the default value
*/
double defaultValueDouble() default NULL_DOUBLE;
/**
* If true, ensures that this column is unique.
*
* @return true if this column is UNIQUE
*/
boolean unique() default false;
public static enum OnConflict {
UNSPECIFIED, ROLLBACK, ABORT, FAIL, IGNORE, REPLACE
}
/**
* If the column is marked unique, this determines what to do if there's a conflict. This is
* ignored if the column is not unique.
*
* @return the desired conflict resolution
*/
OnConflict onConflict() default OnConflict.UNSPECIFIED;
public static enum CollationName {
DEFAULT, BINARY, NOCASE, RTRIM
}
/**
* Defines a collation for the column.
*
* @return the collation type
*/
CollationName collate() default CollationName.DEFAULT;
/**
* Suffixes the column declaration with this string.
*
* @return a string of any supplemental column declarations
*/
String extraColDef() default NULL;
/**
* Column type-specific flags.
*
* @return
*/
int flags() default 0;
/**
* Generates SQL from a {@link ContentItem}. This inspects the class, parses all its
* annotations, and so on.
*
* @author <a href="mailto:[email protected]">Steve Pomeroy</a>
*
*/
public static class Extractor {
private static final String DOUBLE_ESCAPE = DBColumnType.DEFAULT_VALUE_ESCAPE
+ DBColumnType.DEFAULT_VALUE_ESCAPE;
private final Class<? extends ContentItem> mDataItem;
private final String mTable;
public Extractor(Class<? extends ContentItem> contentItem) throws SQLGenerationException {
mDataItem = contentItem;
mTable = extractTableName(mDataItem);
}
/**
* Inspects the {@link ContentItem} and extracts a table name from it. If there is a @DBTable
* annotation, uses that name. Otherwise, uses a lower-cased, sanitized version of the
* classname.
*
* @return a valid table name
* @throws SQLGenerationException
*/
public static String extractTableName(Class<? extends ContentItem> mDataItem)
throws SQLGenerationException {
String tableName = null;
final DBTable tableNameAnnotation = mDataItem.getAnnotation(DBTable.class);
if (tableNameAnnotation != null) {
tableName = tableNameAnnotation.value();
if (!SQLGenUtils.isValidName(tableName)) {
throw new SQLGenerationException("Illegal table name: '" + tableName + "'");
}
} else {
tableName = SQLGenUtils.toValidName(mDataItem);
}
return tableName;
}
public String getTableName() {
return mTable;
}
public String getDbColumnName(Field field) throws SQLGenerationException {
String dbColumnName;
try {
dbColumnName = (String) field.get(null);
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException("programming error", e);
} catch (final IllegalAccessException e) {
throw new SQLGenerationException("field '" + field.getName()
+ "' cannot be accessed", e);
} catch (final NullPointerException e) {
throw new SQLGenerationException("field '" + field.getName() + "' is not static", e);
}
if (!SQLGenUtils.isValidName(dbColumnName)) {
throw new SQLGenerationException("@DBColumn '" + dbColumnName
+ "' is not a valid SQLite column name.");
}
return dbColumnName;
}
private void appendColumnDef(StringBuilder tableSQL, DBColumn t, Field field,
List<String> preSql, List<String> postSql)
throws IllegalAccessException, InstantiationException {
@SuppressWarnings("rawtypes")
final Class<? extends DBColumnType> columnType = t.type();
@SuppressWarnings("rawtypes")
final DBColumnType typeInstance = columnType.newInstance();
final String colName = getDbColumnName(field);
tableSQL.append(typeInstance.toCreateColumn(colName));
if (t.primaryKey()) {
tableSQL.append(" PRIMARY KEY");
if (t.autoIncrement()) {
tableSQL.append(" AUTOINCREMENT");
}
}
if (t.unique()) {
tableSQL.append(" UNIQUE");
if (t.onConflict() != OnConflict.UNSPECIFIED) {
tableSQL.append(" ON CONFLICT");
}
switch (t.onConflict()) {
case ABORT:
tableSQL.append(" ABORT");
break;
case FAIL:
tableSQL.append(" FAIL");
break;
case IGNORE:
tableSQL.append(" IGNORE");
break;
case REPLACE:
tableSQL.append(" REPLACE");
break;
case ROLLBACK:
tableSQL.append(" ROLLBACK");
break;
case UNSPECIFIED:
break;
}
}
if (t.notnull()) {
tableSQL.append(" NOT NULL");
}
switch (t.collate()) {
case BINARY:
tableSQL.append(" COLLATE BINARY");
break;
case NOCASE:
tableSQL.append(" COLLATE NOCASE");
break;
case RTRIM:
tableSQL.append(" COLLATE RTRIM");
break;
case DEFAULT:
break;
}
final String defaultValue = t.defaultValue();
final int defaultValueInt = t.defaultValueInt();
final long defaultValueLong = t.defaultValueLong();
final float defaultValueFloat = t.defaultValueFloat();
final double defaultValueDouble = t.defaultValueDouble();
if (!DBColumn.NULL.equals(defaultValue)) {
tableSQL.append(" DEFAULT ");
// double-escape to insert the escape character literally.
if (defaultValue.startsWith(DOUBLE_ESCAPE)) {
DatabaseUtils.appendValueToSql(tableSQL, defaultValue.substring(1));
} else if (defaultValue.startsWith(DBColumnType.DEFAULT_VALUE_ESCAPE)) {
tableSQL.append(defaultValue.substring(1));
} else {
DatabaseUtils.appendValueToSql(tableSQL, defaultValue);
}
} else if (defaultValueInt != DBColumn.NULL_INT) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueInt);
} else if (defaultValueLong != DBColumn.NULL_LONG) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueLong);
} else if (defaultValueFloat != DBColumn.NULL_FLOAT) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueFloat);
} else if (defaultValueDouble != DBColumn.NULL_DOUBLE) {
tableSQL.append(" DEFAULT ");
tableSQL.append(defaultValueDouble);
}
final String extraColDef = t.extraColDef();
if (!DBColumn.NULL.equals(extraColDef)) {
tableSQL.append(extraColDef);
}
final int flags = t.flags();
final String pre = typeInstance.preTableSql(mTable, colName, flags);
if (pre != null) {
preSql.add(pre);
}
final String post = typeInstance.postTableSql(mTable, colName, flags);
if (post != null) {
postSql.add(post);
}
}
/**
* Gets the database column type of the field. The field must have a {@link DBColumn}
* annotation.
*
* @param fieldName
* the name of the field. This is whatever name you've used for the
* {@code static String}, not its value.
* @return the {@link DBColumnType} of the field
* @throws SQLGenerationException
* @throws NoSuchFieldException
*/
public Class<? extends DBColumnType<?>> getFieldType(String fieldName)
throws SQLGenerationException, NoSuchFieldException {
final Field field = mDataItem.getField(fieldName);
return getFieldType(field);
}
/**
* Gets the database column type of the field. The field must have a {@link DBColumn}
* annotation.
*
* @param field
* the given {@code static String} field.
* @return the type of the field, as defined in the annotation or {@code null} if the given
* field has no {@link DBColumn} annotation.
* @throws SQLGenerationException
* if an annotation is present, but there's an error in the field definition.
*/
public Class<? extends DBColumnType<?>> getFieldType(Field field)
throws SQLGenerationException {
try {
final DBColumn t = field.getAnnotation(DBColumn.class);
if (t == null) {
return null;
}
final int m = field.getModifiers();
if (!String.class.equals(field.getType()) || !Modifier.isStatic(m)
|| !Modifier.isFinal(m)) {
throw new SQLGenerationException(
"Columns defined using @DBColumn must be static final Strings.");
}
return t.type();
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException(
"field claimed to be static, but something went wrong on invocation", e);
} catch (final SecurityException e) {
throw new SQLGenerationException("cannot access class fields", e);
}
}
/**
* Generates SQL code for creating this object's table. Creation is done by inspecting the
* static strings that are marked with {@link DBColumn} annotations.
*
* @return CREATE TABLE code for creating this table.
* @throws SQLGenerationException
* if there were any problems creating the table
* @see DBColumn
* @see DBTable
*/
public List<String> getTableCreation()
throws SQLGenerationException {
// pre, create table, post
final LinkedList<String> preTableSql = new LinkedList<String>();
final LinkedList<String> postTableSql = new LinkedList<String>();
try {
final StringBuilder tableSQL = new StringBuilder();
tableSQL.append("CREATE TABLE ");
tableSQL.append(mTable);
tableSQL.append(" (");
boolean needSep = false;
for (final Field field : mDataItem.getFields()) {
final DBColumn t = field.getAnnotation(DBColumn.class);
final DBForeignKeyColumn fk = field.getAnnotation(DBForeignKeyColumn.class);
if (t == null && fk == null) {
continue;
}
final int m = field.getModifiers();
if (!String.class.equals(field.getType()) || !Modifier.isStatic(m)
|| !Modifier.isFinal(m)) {
throw new SQLGenerationException(
"Columns defined using @DBColumn must be static final Strings.");
}
if (needSep) {
tableSQL.append(',');
}
if (t != null) {
appendColumnDef(tableSQL, t, field, preTableSql, postTableSql);
} else if (fk != null) {
appendFKColumnDef(tableSQL, fk, field);
}
needSep = true;
}
tableSQL.append(")");
preTableSql.add(tableSQL.toString());
preTableSql.addAll(postTableSql);
return preTableSql;
} catch (final IllegalArgumentException e) {
throw new SQLGenerationException(
"field claimed to be static, but something went wrong on invocation", e);
} catch (final IllegalAccessException e) {
throw new SQLGenerationException("default constructor not visible", e);
} catch (final SecurityException e) {
throw new SQLGenerationException("cannot access class fields", e);
} catch (final InstantiationException e) {
throw new SQLGenerationException("cannot instantiate field type class", e);
}
}
private void appendFKColumnDef(StringBuilder tableSQL, DBForeignKeyColumn fk, Field field)
throws IllegalArgumentException, IllegalAccessException {
tableSQL.append("'");
tableSQL.append(getDbColumnName(field));
tableSQL.append("' INTEGER");
if (fk.notnull()) {
tableSQL.append(" NOT NULL");
}
if (AndroidVersions.SQLITE_SUPPORTS_FOREIGN_KEYS) {
tableSQL.append(" REFERENCES ");
final String parentTable = extractTableName(fk.parent());
tableSQL.append("'");
tableSQL.append(parentTable);
tableSQL.append("' (");
tableSQL.append(ContentItem._ID);
tableSQL.append(") ON DELETE CASCADE"); // TODO make this configurable
}
}
}
}
| Adds documentation
| src/edu/mit/mobile/android/content/column/DBColumn.java | Adds documentation | <ide><path>rc/edu/mit/mobile/android/content/column/DBColumn.java
<ide> *
<ide> * The names and structure of this are based loosely on Django's Model/Field framework.
<ide> *
<del> * @author steve
<add> * @author <a href="mailto:[email protected]">Steve Pomeroy</a>
<ide> *
<ide> */
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> * annotations, and so on.
<ide> *
<ide> * @author <a href="mailto:[email protected]">Steve Pomeroy</a>
<add> * @see DBColumn
<ide> *
<ide> */
<ide> public static class Extractor {
<ide> return tableName;
<ide> }
<ide>
<add> /**
<add> * The table name is auto-generated using {@link #extractTableName(Class)}.
<add> *
<add> * @return the name of the table for this {@link ContentItem}.
<add> */
<ide> public String getTableName() {
<ide> return mTable;
<ide> }
<ide>
<add> /**
<add> * For a given {@code field}, return the value of the field. All fields must be
<add> * {@code static String}s whose content is the column name. This method ensures that they
<add> * fit this requirement.
<add> *
<add> * @param field
<add> * the {@code static String} field
<add> * @return the value of the field.
<add> * @throws SQLGenerationException
<add> * if the field doesn't meet the necessary requirements.
<add> */
<ide> public String getDbColumnName(Field field) throws SQLGenerationException {
<ide> String dbColumnName;
<ide> try {
<ide> }
<ide>
<ide> private void appendColumnDef(StringBuilder tableSQL, DBColumn t, Field field,
<del> List<String> preSql, List<String> postSql)
<del> throws IllegalAccessException, InstantiationException {
<add> List<String> preSql, List<String> postSql) throws IllegalAccessException,
<add> InstantiationException {
<ide> @SuppressWarnings("rawtypes")
<ide> final Class<? extends DBColumnType> columnType = t.type();
<ide> @SuppressWarnings("rawtypes")
<ide> * @see DBColumn
<ide> * @see DBTable
<ide> */
<del> public List<String> getTableCreation()
<del> throws SQLGenerationException {
<add> public List<String> getTableCreation() throws SQLGenerationException {
<ide> // pre, create table, post
<ide> final LinkedList<String> preTableSql = new LinkedList<String>();
<ide> final LinkedList<String> postTableSql = new LinkedList<String>(); |
|
JavaScript | mit | b298192f68bc1583c5e31f108584ef34effd54bb | 0 | Druid-of-Luhn/cropper.js,Druid-of-Luhn/cropper.js | /**
* @file Allows uploading, cropping (with automatic resizing) and exporting
* of images.
* @author Billy Brown
* @license MIT
* @version 1.0.0
*/
/**
* <p>Creates an Uploader instance with parameters passed as an object.</p>
* <p>Available parameters are:</p>
* <ul>
* <li>exceptions {function}: the exceptions handler to use, function that takes a string.</li>
* <li>input {string} (required): the classname (prefixed with ".") for the input element. Instantiation fails if not provided.</li>
* <li>types {array}: the file types accepted by the uploader.</li>
* </ul>
*
* @example
* var uploader = new Uploader({
* input: document.querySelector('.js-fileinput'),
* types: [ 'gif', 'jpg', 'jpeg', 'png' ]
* });
*
* @class
* @param {object} options - the parameters to be passed for instantiation
*/
class Uploader {
constructor(options) {
if (!options.input) {
throw '[Uploader] Missing input file element.';
}
this.fileInput = options.input;
this.types = options.types || [ 'gif', 'jpg', 'jpeg', 'png' ];
this.reader = new FileReader();
}
listen() {
return new Promise((resolve, reject) => {
this.fileInput.onchange = (e) => {
// Do not submit the form
e.preventDefault();
// Make sure one file was selected
if (!this.fileInput.files || this.fileInput.files.length !== 1) {
reject('[Uploader:listen] Select only one file.');
} else {
this.fileReaderSetup(this.fileInput.files[0], resolve, reject);
}
};
});
}
fileReaderSetup(file, resolve) {
if (this.validFileType(file.type)) {
// Read the image as base64 data
this.reader.readAsDataURL(file);
// Resolve the promise with the image data
this.reader.onload = (e) => resolve(e.target.result);
} else {
reject('[Uploader:fileReaderSetup] Invalid file type.');
}
}
validFileType(filename) {
// Get the second part of the MIME type
let extension = filename.split('/').pop().toLowerCase();
// See if it is in the array of allowed types
return this.types.includes(extension);
}
}
/**
* <p>Creates a Cropper instance with parameters passed as an object.</p>
* <p>Available parameters are:</p>
* <ul>
* <li>exceptions {function}: the exceptions handler to use, function that takes a string.</li>
* <li>size {object} (required): the dimensions of the cropped, resized image. Must have 'width' and 'height' fields. </li>
* <li>canvas {string} (required): the classname (prefixed with ".") for the cropping canvas element. Instantiation fails if not provided.</li>
* <li>preview {string} (required): the classname (prefixed with ".") for the preview canvas element. Instantiation fails if not provided.</li>
* </ul>
*
* @example
* var editor = new Cropper({
* size: { width: 128, height: 128 },
* limit: 600,
* canvas: document.querySelector('.js-editorcanvas'),
* preview: document.querySelector('.js-previewcanvas')
* });
*
* @class
* @param {object} options - the parameters to be passed for instantiation
*/
class Cropper {
constructor(options) {
// Check the inputs
if (!options.size) {
throw 'Size field in options is required';
}
if (!options.canvas) {
throw 'Could not find image canvas element.';
}
if (!options.preview) {
throw 'Could not find preview canvas element.';
}
// Hold on to the values
this.imageCanvas = options.canvas;
this.previewCanvas = options.preview;
this.c = this.imageCanvas.getContext("2d");
// Create the cropping square
this.crop = {
size: options.size,
tl: { x: 0, y: 0 },
br: { x: options.size.width, y: options.size.height }
};
this.lastEvent = null;
// Images larger than options.limit are resized
this.limit = options.limit || 600; // default to 600px
}
setImageSource(source) {
this.image = new Image();
this.image.src = source;
this.image.onload = this.readyEditor.bind(this);
// Perform an initial render
this.render();
}
export(img) {
img.setAttribute('src', this.previewCanvas.toDataURL());
}
/** @private */
readyEditor(e) {
this.imageCanvas.classList.remove('hidden');
this.render();
// Listen for clicks in the canvas
this.imageCanvas.onmousedown = this.clickStart.bind(this);
this.boundDrag = this.drag.bind(this);
this.boundClickStop = this.clickStop.bind(this);
}
/** @private */
render() {
this.c.clearRect(0, 0, this.imageCanvas.width, this.imageCanvas.height);
this.displayImage();
this.preview();
this.drawCropWindow();
}
/** @private */
clickStart(e) {
// Get the crop handle to use
var position = { x: e.offsetX, y: e.offsetY };
this.lastEvent = {
position: position,
resizing: this.isResizing(position),
moving: this.isMoving(position)
};
// Listen for mouse movement and mouse release
this.imageCanvas.addEventListener('mousemove', this.boundDrag);
this.imageCanvas.addEventListener('mouseup', this.boundClickStop);
}
/** @private */
clickStop(e) {
this.imageCanvas.removeEventListener("mousemove", this.boundDrag);
this.imageCanvas.removeEventListener("mouseup", this.boundClickStop);
}
/** @private */
drag(e) {
var position = { x: e.offsetX, y: e.offsetY };
var dx = position.x - this.lastEvent.position.x;
var dy = position.y - this.lastEvent.position.y;
// Determine whether we are resizing, moving, or nothing
if (this.lastEvent.resizing) {
this.resize(dx, dy);
} else if (this.lastEvent.moving) {
this.move(dx, dy);
}
// Update the last position
this.lastEvent.position = position;
this.render();
}
/** @private */
resize(dx, dy) {
var handle = this.crop.br;
// Maintain the aspect ratio
var amount = Math.abs(dx) > Math.abs(dy) ? dx : dy;
if (this.inBounds(handle.x + amount, handle.y + amount)) {
handle.x += amount;
handle.y += amount;
}
}
/** @private */
move(dx, dy) {
var tl = this.crop.tl;
var br = this.crop.br;
// Make sure all four corners are in bounds
if (this.inBounds(tl.x + dx, tl.y + dy) &&
this.inBounds(br.x + dx, tl.y + dy) &&
this.inBounds(br.x + dx, br.y + dy) &&
this.inBounds(tl.x + dx, br.y + dy)) {
tl.x += dx;
tl.y += dy;
br.x += dx;
br.y += dy;
}
}
/** @private */
displayImage() {
// Resize the original to the maximum allowed size
if (this.image.width > this.limit) {
this.image.height *= this.limit / this.image.width;
this.image.width = this.limit;
} else if (this.image.height > this.limit) {
this.image.width *= this.limit / this.image.height;
this.image.height = this.limit;
}
// Fit the image to the canvas (fixed width canvas, dynamic height)
this.imageCanvas.width = this.image.width;
this.imageCanvas.height = this.image.height;
this.c.drawImage(this.image, 0, 0, this.image.width, this.image.height);
}
/** @private */
drawCropWindow() {
var tl = this.crop.tl;
var br = this.crop.br;
this.c.strokeStyle = 'red';
this.c.fillStyle = 'red';
// Draw the crop window outline
this.c.strokeRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
// Draw the draggable handle
var path = new Path2D();
path.arc(br.x, br.y, 3, 0, Math.PI * 2, true);
this.c.fill(path);
}
/** @private */
preview() {
var tl = this.crop.tl;
var br = this.crop.br;
var imageData = this.c.getImageData(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
if (imageData === null) {
return false;
}
var ctx = this.previewCanvas.getContext('2d');
this.previewCanvas.width = this.crop.size.width;
this.previewCanvas.height = this.crop.size.height;
ctx.clearRect(0, 0, this.previewCanvas.width, this.previewCanvas.height);
// Draw the image to the preview canvas, resizing it to fit
ctx.drawImage(this.imageCanvas,
// Top left corner coordinates of image
tl.x, tl.y,
// Width and height of image
br.x - tl.x, br.y - tl.y,
// Top left corner coordinates of result in canvas
0, 0,
// Width and height of result in canvas
this.previewCanvas.width, this.previewCanvas.height);
}
/** @private */
isResizing(pos) {
var errorOffset = 10;
var handle = this.crop.br;
return !(pos.x < handle.x - errorOffset || pos.x > handle.x + errorOffset ||
pos.y < handle.y - errorOffset || pos.y > handle.y + errorOffset);
}
/** @private */
isMoving(pos) {
var tl = this.crop.tl;
var br = this.crop.br;
return !(pos.x < tl.x || pos.x > br.x || pos.y < tl.y || pos.y > br.y);
}
/** @private */
inBounds(x, y) {
return x >= 0 && x <= this.imageCanvas.width &&
y >= 0 && y <= this.imageCanvas.height;
}
}
| cropper.js | /**
* @file Allows uploading, cropping (with automatic resizing) and exporting
* of images.
* @author Billy Brown
* @license MIT
* @version 1.0.0
*/
/**
* <p>Creates an Uploader instance with parameters passed as an object.</p>
* <p>Available parameters are:</p>
* <ul>
* <li>exceptions {function}: the exceptions handler to use, function that takes a string.</li>
* <li>input {string} (required): the classname (prefixed with ".") for the input element. Instantiation fails if not provided.</li>
* <li>types {array}: the file types accepted by the uploader.</li>
* </ul>
*
* @example
* var uploader = new Uploader({
* input: document.querySelector('.js-fileinput'),
* types: [ 'gif', 'jpg', 'jpeg', 'png' ]
* });
*
* @class
* @param {object} options - the parameters to be passed for instantiation
*/
class Uploader {
constructor(options) {
if (!options.input) {
throw '[Uploader] Missing input file element.';
}
this.fileInput = options.input;
this.types = options.types || [ 'gif', 'jpg', 'jpeg', 'png' ];
this.reader = new FileReader();
}
listen() {
return new Promise((resolve, reject) => {
this.fileInput.onchange = (e) => {
// Do not submit the form
e.preventDefault();
// Make sure one file was selected
if (!this.fileInput.files || this.fileInput.files.length !== 1) {
reject('[Uploader:listen] Select only one file.');
} else {
this.fileReaderSetup(this.fileInput.files[0], resolve, reject);
}
};
});
}
fileReaderSetup(file, resolve) {
if (this.validFileType(file.type)) {
// Read the image as base64 data
this.reader.readAsDataURL(file);
// Resolve the promise with the image data
this.reader.onload = (e) => resolve(e.target.result);
} else {
reject('[Uploader:fileReaderSetup] Invalid file type.');
}
}
validFileType(filename) {
// Get the second part of the MIME type
let extension = filename.split('/').pop().toLowerCase();
// See if it is in the array of allowed types
return this.types.includes(extension);
}
}
/**
* <p>Creates a Cropper instance with parameters passed as an object.</p>
* <p>Available parameters are:</p>
* <ul>
* <li>exceptions {function}: the exceptions handler to use, function that takes a string.</li>
* <li>size {object} (required): the dimensions of the cropped, resized image. Must have 'width' and 'height' fields. </li>
* <li>canvas {string} (required): the classname (prefixed with ".") for the cropping canvas element. Instantiation fails if not provided.</li>
* <li>preview {string} (required): the classname (prefixed with ".") for the preview canvas element. Instantiation fails if not provided.</li>
* </ul>
*
* @example
* var editor = new Cropper({
* size: { width: 128, height: 128 },
* canvas: document.querySelector('.js-editorcanvas'),
* preview: document.querySelector('.js-previewcanvas')
* });
*
* @class
* @param {object} options - the parameters to be passed for instantiation
*/
class Cropper {
constructor(options) {
// Check the inputs
if (!options.size) {
throw 'Size field in options is required';
}
if (!options.canvas) {
throw 'Could not find image canvas element.';
}
if (!options.preview) {
throw 'Could not find preview canvas element.';
}
// Hold on to the values
this.imageCanvas = options.canvas;
this.previewCanvas = options.preview;
this.c = this.imageCanvas.getContext("2d");
// Create the cropping square
this.crop = {
size: options.size,
tl: { x: 0, y: 0 },
br: { x: options.size.width, y: options.size.height }
};
this.lastEvent = null;
}
setImageSource(source) {
this.image = new Image();
this.image.src = source;
this.image.onload = this.readyEditor.bind(this);
}
export(img) {
img.setAttribute('src', this.previewCanvas.toDataURL());
}
/** @private */
readyEditor(e) {
this.imageCanvas.classList.remove('hidden');
this.render();
// Listen for clicks in the canvas
this.imageCanvas.onmousedown = this.clickStart.bind(this);
this.boundDrag = this.drag.bind(this);
this.boundClickStop = this.clickStop.bind(this);
}
/** @private */
render() {
this.c.clearRect(0, 0, this.imageCanvas.width, this.imageCanvas.height);
this.displayImage();
this.preview();
this.drawCropWindow();
}
/** @private */
clickStart(e) {
// Get the crop handle to use
var position = { x: e.offsetX, y: e.offsetY };
this.lastEvent = {
position: position,
resizing: this.isResizing(position),
moving: this.isMoving(position)
};
// Listen for mouse movement and mouse release
this.imageCanvas.addEventListener('mousemove', this.boundDrag);
this.imageCanvas.addEventListener('mouseup', this.boundClickStop);
}
/** @private */
clickStop(e) {
this.imageCanvas.removeEventListener("mousemove", this.boundDrag);
this.imageCanvas.removeEventListener("mouseup", this.boundClickStop);
}
/** @private */
drag(e) {
var position = { x: e.offsetX, y: e.offsetY };
var dx = position.x - this.lastEvent.position.x;
var dy = position.y - this.lastEvent.position.y;
// Determine whether we are resizing, moving, or nothing
if (this.lastEvent.resizing) {
this.resize(dx, dy);
} else if (this.lastEvent.moving) {
this.move(dx, dy);
}
// Update the last position
this.lastEvent.position = position;
this.render();
}
/** @private */
resize(dx, dy) {
var handle = this.crop.br;
// Maintain the aspect ratio
var amount = Math.abs(dx) > Math.abs(dy) ? dx : dy;
if (this.inBounds(handle.x + amount, handle.y + amount)) {
handle.x += amount;
handle.y += amount;
}
}
/** @private */
move(dx, dy) {
var tl = this.crop.tl;
var br = this.crop.br;
// Make sure all four corners are in bounds
if (this.inBounds(tl.x + dx, tl.y + dy) &&
this.inBounds(br.x + dx, tl.y + dy) &&
this.inBounds(br.x + dx, br.y + dy) &&
this.inBounds(tl.x + dx, br.y + dy)) {
tl.x += dx;
tl.y += dy;
br.x += dx;
br.y += dy;
}
}
/** @private */
displayImage() {
var maxSide = 600;
// Resize the original to the maximum allowed size
if (this.image.width > maxSide) {
this.image.height *= maxSide / this.image.width;
this.image.width = maxSide;
} else if (this.image.height > maxSide) {
this.image.width *= maxSide / this.image.height;
this.image.height = maxSide;
}
// Fit the image to the canvas (fixed width canvas, dynamic height)
this.imageCanvas.width = this.image.width;
this.imageCanvas.height = this.image.height;
this.c.drawImage(this.image, 0, 0, this.image.width, this.image.height);
}
/** @private */
drawCropWindow() {
var tl = this.crop.tl;
var br = this.crop.br;
this.c.strokeStyle = 'red';
this.c.fillStyle = 'red';
// Draw the crop window outline
this.c.strokeRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
// Draw the draggable handle
var path = new Path2D();
path.arc(br.x, br.y, 3, 0, Math.PI * 2, true);
this.c.fill(path);
}
/** @private */
preview() {
var tl = this.crop.tl;
var br = this.crop.br;
var imageData = this.c.getImageData(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
if (imageData === null) {
return false;
}
var ctx = this.previewCanvas.getContext('2d');
this.previewCanvas.width = this.crop.size.width;
this.previewCanvas.height = this.crop.size.height;
ctx.clearRect(0, 0, this.previewCanvas.width, this.previewCanvas.height);
// Draw the image to the preview canvas, resizing it to fit
ctx.drawImage(this.imageCanvas,
// Top left corner coordinates of image
tl.x, tl.y,
// Width and height of image
br.x - tl.x, br.y - tl.y,
// Top left corner coordinates of result in canvas
0, 0,
// Width and height of result in canvas
this.previewCanvas.width, this.previewCanvas.height);
}
/** @private */
isResizing(pos) {
var errorOffset = 10;
var handle = this.crop.br;
return !(pos.x < handle.x - errorOffset || pos.x > handle.x + errorOffset ||
pos.y < handle.y - errorOffset || pos.y > handle.y + errorOffset);
}
/** @private */
isMoving(pos) {
var tl = this.crop.tl;
var br = this.crop.br;
return !(pos.x < tl.x || pos.x > br.x || pos.y < tl.y || pos.y > br.y);
}
/** @private */
inBounds(x, y) {
return x >= 0 && x <= this.imageCanvas.width &&
y >= 0 && y <= this.imageCanvas.height;
}
}
| Optional limit argument in Cropper for display size
| cropper.js | Optional limit argument in Cropper for display size | <ide><path>ropper.js
<ide> * @example
<ide> * var editor = new Cropper({
<ide> * size: { width: 128, height: 128 },
<add> * limit: 600,
<ide> * canvas: document.querySelector('.js-editorcanvas'),
<ide> * preview: document.querySelector('.js-previewcanvas')
<ide> * });
<ide> br: { x: options.size.width, y: options.size.height }
<ide> };
<ide> this.lastEvent = null;
<add> // Images larger than options.limit are resized
<add> this.limit = options.limit || 600; // default to 600px
<ide> }
<ide>
<ide> setImageSource(source) {
<ide> this.image = new Image();
<ide> this.image.src = source;
<ide> this.image.onload = this.readyEditor.bind(this);
<add> // Perform an initial render
<add> this.render();
<ide> }
<ide>
<ide> export(img) {
<ide>
<ide> /** @private */
<ide> displayImage() {
<del> var maxSide = 600;
<ide> // Resize the original to the maximum allowed size
<del> if (this.image.width > maxSide) {
<del> this.image.height *= maxSide / this.image.width;
<del> this.image.width = maxSide;
<del> } else if (this.image.height > maxSide) {
<del> this.image.width *= maxSide / this.image.height;
<del> this.image.height = maxSide;
<add> if (this.image.width > this.limit) {
<add> this.image.height *= this.limit / this.image.width;
<add> this.image.width = this.limit;
<add> } else if (this.image.height > this.limit) {
<add> this.image.width *= this.limit / this.image.height;
<add> this.image.height = this.limit;
<ide> }
<ide> // Fit the image to the canvas (fixed width canvas, dynamic height)
<ide> this.imageCanvas.width = this.image.width; |
|
Java | apache-2.0 | a250e5957365fcdf51ef6e7719272ef949d800e1 | 0 | gradle/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle | /*
* Copyright 2012 the original author or authors.
*
* 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 org.gradle.api.internal.filestore;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.file.EmptyFileVisitor;
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.internal.file.IdentityFileResolver;
import org.gradle.api.internal.file.collections.DirectoryFileTree;
import org.gradle.api.internal.file.copy.DeleteActionImpl;
import org.gradle.api.tasks.util.PatternFilterable;
import org.gradle.api.tasks.util.PatternSet;
import org.gradle.util.GFileUtils;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* File store that accepts the target path as the key for the entry.
*
* This implementation is explicitly NOT THREAD SAFE. Concurrent access must be organised externally.
* <p>
* There is always at most one entry for a given key for this file store. If an entry already exists at the given path, it will be overwritten.
* Paths can contain directory components, which will be created on demand.
* <p>
* This file store is self repairing in so far that any files partially written before a fatal error will be ignored and
* removed at a later time.
* <p>
* This file store also provides searching via relative ant path patterns.
*/
public class PathKeyFileStore implements FileStore<String>, FileStoreSearcher<String> {
/*
When writing a file into the filestore a marker file with this suffix is written alongside,
then removed after the write. This is used to detect partially written files (due to a serious crash)
and to silently clean them.
*/
public static final String IN_PROGRESS_MARKER_FILE_SUFFIX = ".fslck";
private File baseDir;
private final DeleteActionImpl deleteAction = new DeleteActionImpl(new IdentityFileResolver());
public PathKeyFileStore(File baseDir) {
this.baseDir = baseDir;
}
public File getBaseDir() {
return baseDir;
}
public FileStoreEntry move(String path, File source) {
return saveIntoFileStore(source, getFile(path), true);
}
public FileStoreEntry copy(String path, File source) {
return saveIntoFileStore(source, getFile(path), false);
}
private File getFile(String path) {
return new File(baseDir, path);
}
private File getFileWhileCleaningInProgress(String path) {
File file = getFile(path);
File markerFile = getInProgressMarkerFile(file);
if (markerFile.exists()) {
deleteAction.delete(file);
deleteAction.delete(markerFile);
}
return file;
}
public void moveFilestore(File destination) {
if (baseDir.exists()) {
GFileUtils.moveDirectory(baseDir, destination);
}
baseDir = destination;
}
public FileStoreEntry add(String path, Action<File> addAction) {
String error = String.format("Failed to add into filestore '%s' at '%s' ", getBaseDir().getAbsolutePath(), path);
return doAdd(getFile(path), error, addAction);
}
protected FileStoreEntry saveIntoFileStore(final File source, final File destination, final boolean isMove) {
String verb = isMove ? "move" : "copy";
if (!source.exists()) {
throw new GradleException(String.format("Cannot %s '%s' into filestore @ '%s' as it does not exist", verb, source, destination));
}
String error = String.format("Failed to %s file '%s' into filestore at '%s' ", verb, source, destination);
return doAdd(destination, error, new Action<File>() {
public void execute(File file) {
if (isMove) {
GFileUtils.moveFile(source, destination);
} else {
GFileUtils.copyFile(source, destination);
}
}
});
}
protected FileStoreEntry doAdd(File destination, String failureDescription, Action<File> action) {
try {
GFileUtils.parentMkdirs(destination);
File inProgressMarkerFile = getInProgressMarkerFile(destination);
GFileUtils.touch(inProgressMarkerFile);
try {
deleteAction.delete(destination);
action.execute(destination);
} catch (Throwable t) {
deleteAction.delete(destination);
throw t;
} finally {
deleteAction.delete(inProgressMarkerFile);
}
} catch (Throwable t) {
throw new GradleException(failureDescription, t);
}
return entryAt(destination);
}
public Set<? extends FileStoreEntry> search(String pattern) {
if (!getBaseDir().exists()) {
return Collections.emptySet();
}
final Set<FileStoreEntry> entries = new HashSet<FileStoreEntry>();
findFiles(pattern).visit(new EmptyFileVisitor() {
public void visitFile(FileVisitDetails fileDetails) {
final File file = fileDetails.getFile();
// We cannot clean in progress markers, or in progress files here because
// the file system visitor stuff can't handle the file system mutating while visiting
if (!isInProgressMarkerFile(file) && !isInProgressFile(file)) {
entries.add(entryAt(file));
}
}
});
return entries;
}
private File getInProgressMarkerFile(File file) {
return new File(file.getParent(), file.getName() + IN_PROGRESS_MARKER_FILE_SUFFIX);
}
private boolean isInProgressMarkerFile(File file) {
return file.getName().endsWith(IN_PROGRESS_MARKER_FILE_SUFFIX);
}
private boolean isInProgressFile(File file) {
return getInProgressMarkerFile(file).exists();
}
private DirectoryFileTree findFiles(String pattern) {
DirectoryFileTree fileTree = new DirectoryFileTree(baseDir);
PatternFilterable patternSet = new PatternSet();
patternSet.include(pattern);
return fileTree.filter(patternSet);
}
protected FileStoreEntry entryAt(File file) {
return entryAt(GFileUtils.relativePath(baseDir, file));
}
protected FileStoreEntry entryAt(final String path) {
return new AbstractFileStoreEntry() {
public File getFile() {
return new File(baseDir, path);
}
};
}
public FileStoreEntry get(String key) {
final File file = getFileWhileCleaningInProgress(key);
if (file.exists()) {
return entryAt(file);
} else {
return null;
}
}
}
| subprojects/core/src/main/groovy/org/gradle/api/internal/filestore/PathKeyFileStore.java | /*
* Copyright 2012 the original author or authors.
*
* 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 org.gradle.api.internal.filestore;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.file.EmptyFileVisitor;
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.internal.file.IdentityFileResolver;
import org.gradle.api.internal.file.collections.DirectoryFileTree;
import org.gradle.api.internal.file.copy.DeleteActionImpl;
import org.gradle.api.tasks.util.PatternFilterable;
import org.gradle.api.tasks.util.PatternSet;
import org.gradle.util.GFileUtils;
import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* File store that accepts the target path as the key for the entry.
*
* This implementation is explicitly NOT THREAD SAFE. Concurrent access must be organised externally.
* <p>
* There is always at most one entry for a given key for this file store. If an entry already exists at the given path, it will be overwritten.
* Paths can contain directory components, which will be created on demand.
* <p>
* This file store is self repairing in so far that any files partially written before a fatal error will be ignored and
* removed at a later time.
* <p>
* This file store also provides searching via relative ant path patterns.
*/
public class PathKeyFileStore implements FileStore<String>, FileStoreSearcher<String> {
/*
When writing a file into the filestore a marker file with this suffix is written alongside,
then removed after the write. This is used to detect partially written files (due to a serious crash)
and to silently clean them.
*/
public static final String IN_PROGRESS_MARKER_FILE_SUFFIX = ".fslck";
private File baseDir;
private final DeleteActionImpl deleteAction = new DeleteActionImpl(new IdentityFileResolver());
public PathKeyFileStore(File baseDir) {
this.baseDir = baseDir;
}
public File getBaseDir() {
return baseDir;
}
public FileStoreEntry move(String path, File source) {
return saveIntoFileStore(source, getFile(path), true);
}
public FileStoreEntry copy(String path, File source) {
return saveIntoFileStore(source, getFile(path), false);
}
private File getFile(String path) {
return new File(baseDir, path);
}
private File getFileWhileCleaningInProgress(String path) {
File file = getFile(path);
File markerFile = getInProgressMarkerFile(file);
if (markerFile.exists()) {
deleteAction.delete(file);
deleteAction.delete(markerFile);
}
return file;
}
public void moveFilestore(File destination) {
if (baseDir.exists()) {
GFileUtils.moveDirectory(baseDir, destination);
}
baseDir = destination;
}
public FileStoreEntry add(String path, Action<File> addAction) {
String error = String.format("Failed to add into filestore '%s' at '%s' ", getBaseDir().getAbsolutePath(), path);
return doAdd(getFile(path), error, addAction);
}
protected FileStoreEntry saveIntoFileStore(final File source, final File destination, final boolean isMove) {
String verb = isMove ? "move" : "copy";
if (!source.exists()) {
throw new GradleException(String.format("Cannot %s '%s' into filestore @ '%s' as it does not exist", verb, source, destination));
}
String error = String.format("Failed to %s file '%s' into filestore at '%s' ", verb, source, destination);
return doAdd(destination, error, new Action<File>() {
public void execute(File file) {
if (isMove) {
GFileUtils.moveFile(source, destination);
} else {
GFileUtils.copyFile(source, destination);
}
}
});
}
protected FileStoreEntry doAdd(File destination, String failureDescription, Action<File> action) {
File inProgressMarkerFile = null;
try {
GFileUtils.parentMkdirs(destination);
inProgressMarkerFile = getInProgressMarkerFile(destination);
GFileUtils.touch(inProgressMarkerFile);
deleteAction.delete(destination);
action.execute(destination);
} catch (Exception exception) {
deleteAction.delete(destination);
throw new GradleException(failureDescription, exception);
} finally {
deleteAction.delete(inProgressMarkerFile);
}
return entryAt(destination);
}
public Set<? extends FileStoreEntry> search(String pattern) {
if (!getBaseDir().exists()) {
return Collections.emptySet();
}
final Set<FileStoreEntry> entries = new HashSet<FileStoreEntry>();
findFiles(pattern).visit(new EmptyFileVisitor() {
public void visitFile(FileVisitDetails fileDetails) {
final File file = fileDetails.getFile();
// We cannot clean in progress markers, or in progress files here because
// the file system visitor stuff can't handle the file system mutating while visiting
if (!isInProgressMarkerFile(file) && !isInProgressFile(file)) {
entries.add(entryAt(file));
}
}
});
return entries;
}
private File getInProgressMarkerFile(File file) {
return new File(file.getParent(), file.getName() + IN_PROGRESS_MARKER_FILE_SUFFIX);
}
private boolean isInProgressMarkerFile(File file) {
return file.getName().endsWith(IN_PROGRESS_MARKER_FILE_SUFFIX);
}
private boolean isInProgressFile(File file) {
return getInProgressMarkerFile(file).exists();
}
private DirectoryFileTree findFiles(String pattern) {
DirectoryFileTree fileTree = new DirectoryFileTree(baseDir);
PatternFilterable patternSet = new PatternSet();
patternSet.include(pattern);
return fileTree.filter(patternSet);
}
protected FileStoreEntry entryAt(File file) {
return entryAt(GFileUtils.relativePath(baseDir, file));
}
protected FileStoreEntry entryAt(final String path) {
return new AbstractFileStoreEntry() {
public File getFile() {
return new File(baseDir, path);
}
};
}
public FileStoreEntry get(String key) {
final File file = getFileWhileCleaningInProgress(key);
if (file.exists()) {
return entryAt(file);
} else {
return null;
}
}
}
| Fixed NPE if a problem happens creating the marker file.
| subprojects/core/src/main/groovy/org/gradle/api/internal/filestore/PathKeyFileStore.java | Fixed NPE if a problem happens creating the marker file. | <ide><path>ubprojects/core/src/main/groovy/org/gradle/api/internal/filestore/PathKeyFileStore.java
<ide> }
<ide>
<ide> protected FileStoreEntry doAdd(File destination, String failureDescription, Action<File> action) {
<del> File inProgressMarkerFile = null;
<ide> try {
<ide> GFileUtils.parentMkdirs(destination);
<del> inProgressMarkerFile = getInProgressMarkerFile(destination);
<add> File inProgressMarkerFile = getInProgressMarkerFile(destination);
<ide> GFileUtils.touch(inProgressMarkerFile);
<del> deleteAction.delete(destination);
<del> action.execute(destination);
<del> } catch (Exception exception) {
<del> deleteAction.delete(destination);
<del> throw new GradleException(failureDescription, exception);
<del> } finally {
<del> deleteAction.delete(inProgressMarkerFile);
<add> try {
<add> deleteAction.delete(destination);
<add> action.execute(destination);
<add> } catch (Throwable t) {
<add> deleteAction.delete(destination);
<add> throw t;
<add> } finally {
<add> deleteAction.delete(inProgressMarkerFile);
<add> }
<add> } catch (Throwable t) {
<add> throw new GradleException(failureDescription, t);
<ide> }
<ide> return entryAt(destination);
<ide> } |
|
Java | apache-2.0 | 423336f44a1513534f25c707df5587e11a5e6e7d | 0 | everit-org/ecm-annotation-metadatabuilder,zsigmond-czine-everit/ecm-annotation-metadatabuilder | /*
* Copyright (C) 2011 Everit Kft. (http://www.everit.org)
*
* 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 org.everit.osgi.ecm.annotation.metadatabuilder;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.Generated;
import org.everit.osgi.ecm.annotation.Activate;
import org.everit.osgi.ecm.annotation.AutoDetect;
import org.everit.osgi.ecm.annotation.BundleCapabilityRef;
import org.everit.osgi.ecm.annotation.BundleCapabilityRefs;
import org.everit.osgi.ecm.annotation.Component;
import org.everit.osgi.ecm.annotation.Deactivate;
import org.everit.osgi.ecm.annotation.Service;
import org.everit.osgi.ecm.annotation.ServiceRef;
import org.everit.osgi.ecm.annotation.ServiceRefs;
import org.everit.osgi.ecm.annotation.ThreeStateBoolean;
import org.everit.osgi.ecm.annotation.Update;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttribute;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttributes;
import org.everit.osgi.ecm.annotation.attribute.ByteAttribute;
import org.everit.osgi.ecm.annotation.attribute.ByteAttributes;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttribute;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttributes;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttribute;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttributes;
import org.everit.osgi.ecm.annotation.attribute.FloatAttribute;
import org.everit.osgi.ecm.annotation.attribute.FloatAttributes;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttribute;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttributes;
import org.everit.osgi.ecm.annotation.attribute.LongAttribute;
import org.everit.osgi.ecm.annotation.attribute.LongAttributes;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttribute;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttributes;
import org.everit.osgi.ecm.annotation.attribute.ShortAttribute;
import org.everit.osgi.ecm.annotation.attribute.ShortAttributes;
import org.everit.osgi.ecm.annotation.attribute.StringAttribute;
import org.everit.osgi.ecm.annotation.attribute.StringAttributes;
import org.everit.osgi.ecm.component.ServiceHolder;
import org.everit.osgi.ecm.metadata.AttributeMetadata;
import org.everit.osgi.ecm.metadata.AttributeMetadata.AttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BooleanAttributeMetadata.BooleanAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BundleCapabilityReferenceMetadata.BundleCapabilityReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ByteAttributeMetadata.ByteAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.CharacterAttributeMetadata.CharacterAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ComponentMetadata;
import org.everit.osgi.ecm.metadata.ComponentMetadata.ComponentMetadataBuilder;
import org.everit.osgi.ecm.metadata.ConfigurationPolicy;
import org.everit.osgi.ecm.metadata.DoubleAttributeMetadata.DoubleAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.FloatAttributeMetadata.FloatAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.Icon;
import org.everit.osgi.ecm.metadata.IntegerAttributeMetadata.IntegerAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.LongAttributeMetadata.LongAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.MetadataValidationException;
import org.everit.osgi.ecm.metadata.PasswordAttributeMetadata.PasswordAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.PropertyAttributeMetadata.PropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ReferenceConfigurationType;
import org.everit.osgi.ecm.metadata.ReferenceMetadata.ReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.SelectablePropertyAttributeMetadata.SelectablePropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ServiceMetadata.ServiceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ServiceReferenceMetadata.ServiceReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ShortAttributeMetadata.ShortAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.StringAttributeMetadata.StringAttributeMetadataBuilder;
import org.everit.osgi.ecm.util.method.MethodDescriptor;
import org.everit.osgi.ecm.util.method.MethodUtil;
/**
* Programmers can use the {@link MetadataBuilder} to generate component metadata from annotated
* classes.
*
* @param <C>
* The type of the Component.
*/
public final class MetadataBuilder<C> {
/**
* Compares {@link AttributeMetadata} classes based on their priority and than their names.
*/
private static final class AttributeMetadataComparator
implements Comparator<AttributeMetadata<?>>, Serializable {
private static final long serialVersionUID = -7796104393729198249L;
@Override
public int compare(final AttributeMetadata<?> attr1, final AttributeMetadata<?> attr2) {
float attr1Priority = attr1.getPriority();
float attr2Priority = attr2.getPriority();
int compare = Float.compare(attr1Priority, attr2Priority);
if (compare != 0) {
return compare;
}
String attr1Id = attr1.getAttributeId();
String attr2Id = attr2.getAttributeId();
return attr1Id.compareTo(attr2Id);
}
}
private static final Set<Class<?>> ANNOTATION_CONTAINER_TYPES;
private static final AttributeMetadataComparator ATTRIBUTE_METADATA_COMPARATOR =
new AttributeMetadataComparator();
private static final Map<Class<?>, Class<?>> PRIMITIVE_BOXING_TYPE_MAPPING;
static {
ANNOTATION_CONTAINER_TYPES = new HashSet<Class<?>>();
ANNOTATION_CONTAINER_TYPES.add(ServiceRefs.class);
ANNOTATION_CONTAINER_TYPES.add(BundleCapabilityRefs.class);
ANNOTATION_CONTAINER_TYPES.add(BooleanAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ByteAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(CharacterAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(DoubleAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(FloatAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(IntegerAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(LongAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(PasswordAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ShortAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(StringAttributes.class);
PRIMITIVE_BOXING_TYPE_MAPPING = new HashMap<>();
PRIMITIVE_BOXING_TYPE_MAPPING.put(boolean.class, Boolean.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(byte.class, Byte.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(char.class, Character.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(double.class, Double.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(float.class, Float.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(int.class, Integer.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(long.class, Long.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(short.class, Short.class);
}
/**
* Generates ECM Component Metadata from an annotated class.
*
* @param clazz
* The type of the class that is annotated.
* @return The generated Metadata that can be used to set up an ECM Component Container.
*/
public static <C> ComponentMetadata buildComponentMetadata(final Class<C> clazz) {
MetadataBuilder<C> metadataBuilder = new MetadataBuilder<C>(clazz);
return metadataBuilder.build();
}
private NavigableSet<AttributeMetadata<?>> attributes =
new TreeSet<>(ATTRIBUTE_METADATA_COMPARATOR);
private Class<C> clazz;
private MetadataBuilder() {
}
private MetadataBuilder(final Class<C> clazz) {
this.clazz = clazz;
}
private ComponentMetadata build() {
Component componentAnnotation = clazz.getAnnotation(Component.class);
if (componentAnnotation == null) {
throw new ComponentAnnotationMissingException("Component annotation is missing on type "
+ clazz.toString());
}
ComponentMetadataBuilder componentMetaBuilder = new ComponentMetadataBuilder()
.withComponentId(makeStringNullIfEmpty(componentAnnotation.componentId()))
.withConfigurationPid(makeStringNullIfEmpty(componentAnnotation.configurationPid()))
.withConfigurationPolicy(
convertConfigurationPolicy(componentAnnotation.configurationPolicy()))
.withDescription(makeStringNullIfEmpty(componentAnnotation.description()))
.withIcons(convertIcons(componentAnnotation.icons()))
.withMetatype(componentAnnotation.metatype())
.withLabel(makeStringNullIfEmpty(componentAnnotation.label()))
.withLocalizationBase(makeStringNullIfEmpty(componentAnnotation.localizationBase()))
.withType(clazz.getName())
.withActivate(findMethodWithAnnotation(Activate.class))
.withDeactivate(findMethodWithAnnotation(Deactivate.class))
.withUpdate(findMethodWithAnnotation(Update.class));
generateMetaForAttributeHolders();
componentMetaBuilder.withAttributes(attributes.toArray(
new AttributeMetadata<?>[attributes.size()]));
Service serviceAnnotation = clazz.getAnnotation(Service.class);
if (serviceAnnotation != null) {
ServiceMetadataBuilder serviceMetadataBuilder = new ServiceMetadataBuilder();
Class<?>[] serviceInterfaces = serviceAnnotation.value();
serviceMetadataBuilder.withClazzes(serviceInterfaces);
componentMetaBuilder.withService(serviceMetadataBuilder.build());
}
return componentMetaBuilder.build();
}
private <R> R callMethodOfAnnotation(final Annotation annotation, final String fieldName) {
Class<? extends Annotation> annotationType = annotation.getClass();
Method method;
try {
method = annotationType.getMethod(fieldName);
@SuppressWarnings("unchecked")
R result = (R) method.invoke(annotation);
return result;
} catch (NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private ConfigurationPolicy convertConfigurationPolicy(
final org.everit.osgi.ecm.annotation.ConfigurationPolicy configurationPolicy) {
switch (configurationPolicy) {
case IGNORE:
return ConfigurationPolicy.IGNORE;
case REQUIRE:
return ConfigurationPolicy.REQUIRE;
case FACTORY:
return ConfigurationPolicy.FACTORY;
default:
return ConfigurationPolicy.OPTIONAL;
}
}
private Icon[] convertIcons(final org.everit.osgi.ecm.annotation.Icon[] icons) {
if (icons == null) {
final Icon[] noIconDefined = null;
return noIconDefined;
}
Icon[] result = new Icon[icons.length];
for (int i = 0; i < icons.length; i++) {
result[i] = new Icon(icons[i].path(), icons[i].size());
}
return result;
}
private ReferenceConfigurationType convertReferenceConfigurationType(
final org.everit.osgi.ecm.annotation.ReferenceConfigurationType attributeType) {
if (attributeType.equals(org.everit.osgi.ecm.annotation.ReferenceConfigurationType.CLAUSE)) {
return ReferenceConfigurationType.CLAUSE;
} else {
return ReferenceConfigurationType.FILTER;
}
}
private String deriveReferenceId(final Member member, final Annotation annotation) {
String name = callMethodOfAnnotation(annotation, "referenceId");
name = makeStringNullIfEmpty(name);
if (name != null) {
return name;
}
if (member != null) {
String memberName = member.getName();
if (member instanceof Field) {
return memberName;
} else if (member instanceof Method) {
return resolveIdIfMethodNameStartsWith(memberName, "set");
}
}
return null;
}
private Class<?> deriveServiceInterface(final Member member, final ServiceRef annotation) {
Class<?> referenceInterface = annotation.referenceInterface();
if (!AutoDetect.class.equals(referenceInterface)) {
if (Void.class.equals(referenceInterface)) {
return null;
}
return referenceInterface;
}
if (member != null) {
if (member instanceof Field) {
return resolveServiceInterfaceBasedOnGenericType(((Field) member).getGenericType());
} else if (member instanceof Method) {
Method method = ((Method) member);
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1 || parameterTypes[0].isPrimitive()) {
throw new InconsistentAnnotationException(
"Reference auto detection can work only on a method that has one"
+ " non-primitive parameter:" + method.toGenericString());
}
return resolveServiceInterfaceBasedOnGenericType(method.getGenericParameterTypes()[0]);
}
}
return null;
}
private <V_ARRAY, B extends AttributeMetadataBuilder<V_ARRAY, B>> void fillAttributeMetaBuilder(
final Member member,
final Annotation annotation,
final AttributeMetadataBuilder<V_ARRAY, B> builder) {
Boolean dynamic = callMethodOfAnnotation(annotation, "dynamic");
Boolean optional = callMethodOfAnnotation(annotation, "optional");
boolean multiple = resolveMultiple(annotation, member);
Boolean metatype = callMethodOfAnnotation(annotation, "metatype");
String label = callMethodOfAnnotation(annotation, "label");
String description = callMethodOfAnnotation(annotation, "description");
Class<? extends Annotation> annotationType = annotation.annotationType();
float priority = 0;
if (annotationType.equals(ServiceRef.class)
|| annotationType.equals(BundleCapabilityRef.class)) {
priority = callMethodOfAnnotation(annotation, "attributePriority");
} else {
priority = callMethodOfAnnotation(annotation, "priority");
}
Object defaultValueArray = callMethodOfAnnotation(annotation, "defaultValue");
@SuppressWarnings("unchecked")
V_ARRAY typedDefaultValueArray = (V_ARRAY) defaultValueArray;
if (!multiple && Array.getLength(typedDefaultValueArray) == 0) {
typedDefaultValueArray = null;
}
builder.withDynamic(dynamic)
.withOptional(optional)
.withMultiple(multiple)
.withMetatype(metatype)
.withLabel(makeStringNullIfEmpty(label))
.withDescription(makeStringNullIfEmpty(description))
.withPriority(priority)
.withDefaultValue(typedDefaultValueArray);
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> void fillPropertyAttributeBuilder(
final Member member,
final Annotation annotation,
final PropertyAttributeMetadataBuilder<V, B> builder) {
String attributeId = callMethodOfAnnotation(annotation, "attributeId");
attributeId = makeStringNullIfEmpty(attributeId);
if (attributeId == null && member != null) {
String memberName = member.getName();
if (member instanceof Field) {
attributeId = memberName;
} else if (member instanceof Method) {
attributeId = resolveIdIfMethodNameStartsWith(memberName, "set");
}
}
builder.withAttributeId(attributeId);
fillAttributeMetaBuilder(member, annotation, builder);
String setter = callMethodOfAnnotation(annotation, "setter");
setter = makeStringNullIfEmpty(setter);
if (setter != null) {
builder.withSetter(new MethodDescriptor(setter));
} else if (member != null) {
if (member instanceof Method) {
builder.withSetter(new MethodDescriptor((Method) member));
} else if (member instanceof Field) {
String fieldName = member.getName();
String setterName = "set" + fieldName.substring(0, 1).toUpperCase(Locale.getDefault())
+ fieldName.substring(1);
MethodDescriptor methodDescriptor = resolveSetter(builder, setterName);
if (methodDescriptor != null) {
builder.withSetter(methodDescriptor);
}
}
}
}
private <B extends ReferenceMetadataBuilder<B>> void fillReferenceBuilder(final Member member,
final Annotation annotation, final ReferenceMetadataBuilder<B> builder) {
fillAttributeMetaBuilder(member, annotation, builder);
org.everit.osgi.ecm.annotation.ReferenceConfigurationType configurationType =
callMethodOfAnnotation(annotation, "configurationType");
ReferenceConfigurationType convertedConfigurationType =
convertReferenceConfigurationType(configurationType);
String referenceId = deriveReferenceId(member, annotation);
if (referenceId == null) {
throw new MetadataValidationException(
"Reference id for one of the references could not be determined in class "
+ clazz.getName());
}
String setterName =
makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "setter"));
if (setterName != null) {
builder.withSetter(new MethodDescriptor(setterName));
} else if (member instanceof Method) {
builder.withSetter(new MethodDescriptor((Method) member));
}
builder
.withReferenceId(referenceId)
.withAttributeId(
makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "attributeId")))
.withReferenceConfigurationType(convertedConfigurationType);
}
private <V_ARRAY, B extends SelectablePropertyAttributeMetadataBuilder<V_ARRAY, B>> void fillSelectablePropertyAttributeBuilder(// CS_DISABLE_LINE_LENGTH
final Member member, final Annotation annotation,
final SelectablePropertyAttributeMetadataBuilder<V_ARRAY, B> builder) {
fillPropertyAttributeBuilder(member, annotation, builder);
Object optionAnnotationArray = callMethodOfAnnotation(annotation, "options");
int length = Array.getLength(optionAnnotationArray);
if (length == 0) {
builder.withOptions(null, null);
return;
}
String[] labels = new String[length];
@SuppressWarnings("unchecked")
V_ARRAY values = (V_ARRAY) Array.newInstance(builder.getValueType(), length);
for (int i = 0; i < length; i++) {
Annotation optionAnnotation = (Annotation) Array.get(optionAnnotationArray, i);
String label = callMethodOfAnnotation(optionAnnotation, "label");
Object value = callMethodOfAnnotation(optionAnnotation, "value");
label = makeStringNullIfEmpty(label);
if (label == null) {
label = value.toString();
}
labels[i] = label;
Array.set(values, i, value);
}
builder.withOptions(labels, values);
}
private MethodDescriptor findMethodWithAnnotation(
final Class<? extends Annotation> annotationClass) {
Method foundMethod = null;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Annotation annotation = method.getAnnotation(annotationClass);
if (annotation != null) {
if (foundMethod != null) {
throw new InconsistentAnnotationException("The '" + annotationClass.getName()
+ "' annotation is attached to more than one method in class '" + clazz.getName()
+ "'.");
}
foundMethod = method;
}
}
if (foundMethod != null) {
return new MethodDescriptor(foundMethod);
} else {
return null;
}
}
private void generateAttributeMetaForAnnotatedElements(
final AnnotatedElement[] annotatedElements) {
for (AnnotatedElement annotatedElement : annotatedElements) {
Annotation[] annotations = annotatedElement.getAnnotations();
for (Annotation annotation : annotations) {
if (annotatedElement instanceof Member) {
processAttributeHolderAnnotation((Member) annotatedElement, annotation);
} else {
processAttributeHolderAnnotation(null, annotation);
}
}
}
}
private void generateMetaForAttributeHolders() {
generateAttributeMetaForAnnotatedElements(new AnnotatedElement[] { clazz });
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredFields());
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredMethods());
}
private String makeStringNullIfEmpty(final String text) {
if (text == null) {
return null;
}
if ("".equals(text.trim())) {
return null;
}
return text;
}
private void processAnnotationContainer(final Annotation annotationContainer) {
try {
Method method = annotationContainer.annotationType().getMethod("value");
Annotation[] annotations = (Annotation[]) method.invoke(annotationContainer);
for (Annotation annotation : annotations) {
processAttributeHolderAnnotation(null, annotation);
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException("Error during processing class " + clazz.getName(), e);
}
}
@Generated("avoid_checkstyle_alert_about_complexity")
private void processAttributeHolderAnnotation(final Member element, final Annotation annotation) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (ANNOTATION_CONTAINER_TYPES.contains(annotationType)) {
processAnnotationContainer(annotation);
} else if (annotationType.equals(ServiceRef.class)) {
processServiceReferenceAnnotation(element, (ServiceRef) annotation);
} else if (annotationType.equals(BundleCapabilityRef.class)) {
processBundleCapabilityReferenceAnnotation(element, (BundleCapabilityRef) annotation);
} else if (annotationType.equals(BooleanAttribute.class)) {
processBooleanAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ByteAttribute.class)) {
processByteAttributeAnnotation(element, annotation);
} else if (annotationType.equals(CharacterAttribute.class)) {
processCharacterAttributeAnnotation(element, annotation);
} else if (annotationType.equals(DoubleAttribute.class)) {
processDoubleAttributeAnnotation(element, annotation);
} else if (annotationType.equals(FloatAttribute.class)) {
processFloatAttributeAnnotation(element, annotation);
} else if (annotationType.equals(IntegerAttribute.class)) {
processIntegerAttributeAnnotation(element, annotation);
} else if (annotationType.equals(LongAttribute.class)) {
processLongAttributeAnnotation(element, annotation);
} else if (annotationType.equals(PasswordAttribute.class)) {
processPasswordAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ShortAttribute.class)) {
processShortAttributeAnnotation(element, annotation);
} else if (annotationType.equals(StringAttribute.class)) {
processStringAttributeAnnotation(element, annotation);
}
}
private void processBooleanAttributeAnnotation(final Member element,
final Annotation annotation) {
BooleanAttributeMetadataBuilder builder = new BooleanAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processBundleCapabilityReferenceAnnotation(final Member member,
final BundleCapabilityRef annotation) {
BundleCapabilityReferenceMetadataBuilder builder =
new BundleCapabilityReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withNamespace(annotation.namespace()).withStateMask(annotation.stateMask());
putIntoAttributes(builder);
}
private void processByteAttributeAnnotation(final Member element, final Annotation annotation) {
ByteAttributeMetadataBuilder builder = new ByteAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processCharacterAttributeAnnotation(final Member element,
final Annotation annotation) {
CharacterAttributeMetadataBuilder builder = new CharacterAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processDoubleAttributeAnnotation(final Member element, final Annotation annotation) {
DoubleAttributeMetadataBuilder builder = new DoubleAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processFloatAttributeAnnotation(final Member element, final Annotation annotation) {
FloatAttributeMetadataBuilder builder = new FloatAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processIntegerAttributeAnnotation(final Member element,
final Annotation annotation) {
IntegerAttributeMetadataBuilder builder = new IntegerAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processLongAttributeAnnotation(final Member element, final Annotation annotation) {
LongAttributeMetadataBuilder builder = new LongAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processPasswordAttributeAnnotation(final Member element,
final Annotation annotation) {
PasswordAttributeMetadataBuilder builder = new PasswordAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processServiceReferenceAnnotation(final Member member, final ServiceRef annotation) {
ServiceReferenceMetadataBuilder builder = new ServiceReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withServiceInterface(deriveServiceInterface(member, annotation));
putIntoAttributes(builder);
}
private void processShortAttributeAnnotation(final Member element, final Annotation annotation) {
ShortAttributeMetadataBuilder builder = new ShortAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processStringAttributeAnnotation(final Member element, final Annotation annotation) {
StringAttributeMetadataBuilder builder = new StringAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void putIntoAttributes(final AttributeMetadataBuilder<?, ?> builder) {
AttributeMetadata<?> attributeMetadata = builder.build();
boolean exists = attributes.add(attributeMetadata);
if (!exists) {
throw new MetadataValidationException("Duplicate attribute id '"
+ attributeMetadata.getAttributeId()
+ "' found in class '" + clazz.getName() + "'.");
}
}
private String resolveIdIfMethodNameStartsWith(final String memberName, final String prefix) {
int prefixLength = prefix.length();
if (memberName.startsWith(prefix) && memberName.length() > prefixLength) {
return memberName.substring(prefixLength, prefixLength + 1).toLowerCase(Locale.getDefault())
+ memberName.substring(prefixLength + 1);
} else {
return null;
}
}
private boolean resolveMultiple(final Annotation annotation, final Member member) {
ThreeStateBoolean multiple = callMethodOfAnnotation(annotation, "multiple");
if (multiple == ThreeStateBoolean.TRUE) {
return true;
}
if (multiple == ThreeStateBoolean.FALSE) {
return false;
}
if (member == null) {
return false;
}
if (member instanceof Method) {
Class<?>[] parameterTypes = ((Method) member).getParameterTypes();
if (parameterTypes.length == 0) {
throw new InconsistentAnnotationException(
"Could not determine the multiplicity of attribute based on annotation '"
+ annotation.toString() + "' that is defined on the method '" + member.toString()
+ "' in the class " + clazz.getName());
}
return parameterTypes[0].isArray();
} else if (member instanceof Field) {
Class<?> fieldType = ((Field) member).getType();
return fieldType.isArray();
}
throw new InconsistentAnnotationException(
"Could not determine the multiplicity of attribute based on annotation '"
+ annotation.toString() + "' in the class " + clazz.getName());
}
private Class<?> resolveServiceInterfaceBasedOnClassType(final Class<?> classType) {
if (classType.equals(ServiceHolder.class)) {
return null;
} else {
return classType;
}
}
private Class<?> resolveServiceInterfaceBasedOnGenericType(final Type genericType) {
if (genericType instanceof Class) {
Class<?> classType = (Class<?>) genericType;
if (!classType.isArray()) {
return classType;
}
Class<?> componentType = classType.getComponentType();
return resolveServiceInterfaceBasedOnClassType(componentType);
}
if (genericType instanceof GenericArrayType) {
GenericArrayType genericArrayType = (GenericArrayType) genericType;
Type genericComponentType = genericArrayType.getGenericComponentType();
if (genericComponentType instanceof Class) {
return resolveServiceInterfaceBasedOnClassType((Class<?>) genericComponentType);
}
if (genericComponentType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericComponentType;
return resolveServiceInterfaceBasedOnParameterizedType(parameterizedType);
}
}
if (genericType instanceof ParameterizedType) {
return resolveServiceInterfaceBasedOnParameterizedType((ParameterizedType) genericType);
}
throw new MetadataValidationException(
"Could not determine the OSGi service interface based on type "
+ genericType + " in class " + clazz.getName());
}
private Class<?> resolveServiceInterfaceBasedOnParameterizedType(
final ParameterizedType parameterizedType) {
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class) {
Class<?> classType = (Class<?>) rawType;
if (!classType.equals(ServiceHolder.class)) {
return classType;
}
Type serviceInterfaceType = parameterizedType.getActualTypeArguments()[0];
if (serviceInterfaceType instanceof WildcardType) {
return null;
}
if (serviceInterfaceType instanceof Class) {
return (Class<?>) serviceInterfaceType;
}
if (serviceInterfaceType instanceof ParameterizedType) {
Type raw = ((ParameterizedType) serviceInterfaceType).getRawType();
if (raw instanceof Class) {
return (Class<?>) raw;
}
}
}
throw new MetadataValidationException(
"Could not determine the OSGi service interface based on type "
+ parameterizedType + " in class " + clazz.getName());
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> MethodDescriptor resolveSetter(
final PropertyAttributeMetadataBuilder<V, B> builder, final String setterName) {
List<MethodDescriptor> potentialDescriptors = new ArrayList<MethodDescriptor>();
Class<?> attributeType = builder.getValueType();
boolean multiple = builder.isMultiple();
if (multiple) {
String parameterTypeName = attributeType.getCanonicalName() + "[]";
potentialDescriptors
.add(new MethodDescriptor(setterName, new String[] { parameterTypeName }));
} else {
if (attributeType.isPrimitive()) {
Class<?> boxingType = PRIMITIVE_BOXING_TYPE_MAPPING.get(attributeType);
potentialDescriptors.add(new MethodDescriptor(setterName,
new String[] { boxingType.getCanonicalName() }));
}
potentialDescriptors
.add(new MethodDescriptor(setterName, new String[] { attributeType.getCanonicalName() }));
}
Method method = MethodUtil.locateMethodByPreference(clazz, false,
potentialDescriptors.toArray(new MethodDescriptor[potentialDescriptors.size()]));
if (method == null) {
return null;
}
return new MethodDescriptor(method);
}
}
| src/main/java/org/everit/osgi/ecm/annotation/metadatabuilder/MetadataBuilder.java | /*
* Copyright (C) 2011 Everit Kft. (http://www.everit.org)
*
* 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 org.everit.osgi.ecm.annotation.metadatabuilder;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.Generated;
import org.everit.osgi.ecm.annotation.Activate;
import org.everit.osgi.ecm.annotation.AutoDetect;
import org.everit.osgi.ecm.annotation.BundleCapabilityRef;
import org.everit.osgi.ecm.annotation.BundleCapabilityRefs;
import org.everit.osgi.ecm.annotation.Component;
import org.everit.osgi.ecm.annotation.Deactivate;
import org.everit.osgi.ecm.annotation.Service;
import org.everit.osgi.ecm.annotation.ServiceRef;
import org.everit.osgi.ecm.annotation.ServiceRefs;
import org.everit.osgi.ecm.annotation.ThreeStateBoolean;
import org.everit.osgi.ecm.annotation.Update;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttribute;
import org.everit.osgi.ecm.annotation.attribute.BooleanAttributes;
import org.everit.osgi.ecm.annotation.attribute.ByteAttribute;
import org.everit.osgi.ecm.annotation.attribute.ByteAttributes;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttribute;
import org.everit.osgi.ecm.annotation.attribute.CharacterAttributes;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttribute;
import org.everit.osgi.ecm.annotation.attribute.DoubleAttributes;
import org.everit.osgi.ecm.annotation.attribute.FloatAttribute;
import org.everit.osgi.ecm.annotation.attribute.FloatAttributes;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttribute;
import org.everit.osgi.ecm.annotation.attribute.IntegerAttributes;
import org.everit.osgi.ecm.annotation.attribute.LongAttribute;
import org.everit.osgi.ecm.annotation.attribute.LongAttributes;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttribute;
import org.everit.osgi.ecm.annotation.attribute.PasswordAttributes;
import org.everit.osgi.ecm.annotation.attribute.ShortAttribute;
import org.everit.osgi.ecm.annotation.attribute.ShortAttributes;
import org.everit.osgi.ecm.annotation.attribute.StringAttribute;
import org.everit.osgi.ecm.annotation.attribute.StringAttributes;
import org.everit.osgi.ecm.component.ServiceHolder;
import org.everit.osgi.ecm.metadata.AttributeMetadata;
import org.everit.osgi.ecm.metadata.AttributeMetadata.AttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BooleanAttributeMetadata.BooleanAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.BundleCapabilityReferenceMetadata.BundleCapabilityReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ByteAttributeMetadata.ByteAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.CharacterAttributeMetadata.CharacterAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ComponentMetadata;
import org.everit.osgi.ecm.metadata.ComponentMetadata.ComponentMetadataBuilder;
import org.everit.osgi.ecm.metadata.ConfigurationPolicy;
import org.everit.osgi.ecm.metadata.DoubleAttributeMetadata.DoubleAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.FloatAttributeMetadata.FloatAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.Icon;
import org.everit.osgi.ecm.metadata.IntegerAttributeMetadata.IntegerAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.LongAttributeMetadata.LongAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.MetadataValidationException;
import org.everit.osgi.ecm.metadata.PasswordAttributeMetadata.PasswordAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.PropertyAttributeMetadata.PropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ReferenceConfigurationType;
import org.everit.osgi.ecm.metadata.ReferenceMetadata.ReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.SelectablePropertyAttributeMetadata.SelectablePropertyAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.ServiceMetadata.ServiceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ServiceReferenceMetadata.ServiceReferenceMetadataBuilder;
import org.everit.osgi.ecm.metadata.ShortAttributeMetadata.ShortAttributeMetadataBuilder;
import org.everit.osgi.ecm.metadata.StringAttributeMetadata.StringAttributeMetadataBuilder;
import org.everit.osgi.ecm.util.method.MethodDescriptor;
import org.everit.osgi.ecm.util.method.MethodUtil;
/**
* Programmers can use the {@link MetadataBuilder} to generate component metadata from annotated
* classes.
*
* @param <C>
* The type of the Component.
*/
public final class MetadataBuilder<C> {
/**
* Compares {@link AttributeMetadata} classes based on their priority and than their names.
*/
private static final class AttributeMetadataComparator
implements Comparator<AttributeMetadata<?>>, Serializable {
private static final long serialVersionUID = -7796104393729198249L;
@Override
public int compare(final AttributeMetadata<?> attr1, final AttributeMetadata<?> attr2) {
if (attr1 == null) {
return -1;
}
if (attr2 == null) {
return 1;
}
float attr1Priority = attr1.getPriority();
float attr2Priority = attr2.getPriority();
int compare = Float.compare(attr1Priority, attr2Priority);
if (compare != 0) {
return compare;
}
String attr1Id = attr1.getAttributeId();
String attr2Id = attr2.getAttributeId();
return attr1Id.compareTo(attr2Id);
}
}
private static final Set<Class<?>> ANNOTATION_CONTAINER_TYPES;
private static final AttributeMetadataComparator ATTRIBUTE_METADATA_COMPARATOR =
new AttributeMetadataComparator();
private static final Map<Class<?>, Class<?>> PRIMITIVE_BOXING_TYPE_MAPPING;
static {
ANNOTATION_CONTAINER_TYPES = new HashSet<Class<?>>();
ANNOTATION_CONTAINER_TYPES.add(ServiceRefs.class);
ANNOTATION_CONTAINER_TYPES.add(BundleCapabilityRefs.class);
ANNOTATION_CONTAINER_TYPES.add(BooleanAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ByteAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(CharacterAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(DoubleAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(FloatAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(IntegerAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(LongAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(PasswordAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(ShortAttributes.class);
ANNOTATION_CONTAINER_TYPES.add(StringAttributes.class);
PRIMITIVE_BOXING_TYPE_MAPPING = new HashMap<>();
PRIMITIVE_BOXING_TYPE_MAPPING.put(boolean.class, Boolean.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(byte.class, Byte.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(char.class, Character.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(double.class, Double.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(float.class, Float.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(int.class, Integer.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(long.class, Long.class);
PRIMITIVE_BOXING_TYPE_MAPPING.put(short.class, Short.class);
}
/**
* Generates ECM Component Metadata from an annotated class.
*
* @param clazz
* The type of the class that is annotated.
* @return The generated Metadata that can be used to set up an ECM Component Container.
*/
public static <C> ComponentMetadata buildComponentMetadata(final Class<C> clazz) {
MetadataBuilder<C> metadataBuilder = new MetadataBuilder<C>(clazz);
return metadataBuilder.build();
}
private NavigableSet<AttributeMetadata<?>> attributes =
new TreeSet<>(ATTRIBUTE_METADATA_COMPARATOR);
private Class<C> clazz;
private MetadataBuilder() {
}
private MetadataBuilder(final Class<C> clazz) {
this.clazz = clazz;
}
private ComponentMetadata build() {
Component componentAnnotation = clazz.getAnnotation(Component.class);
if (componentAnnotation == null) {
throw new ComponentAnnotationMissingException("Component annotation is missing on type "
+ clazz.toString());
}
ComponentMetadataBuilder componentMetaBuilder = new ComponentMetadataBuilder()
.withComponentId(makeStringNullIfEmpty(componentAnnotation.componentId()))
.withConfigurationPid(makeStringNullIfEmpty(componentAnnotation.configurationPid()))
.withConfigurationPolicy(
convertConfigurationPolicy(componentAnnotation.configurationPolicy()))
.withDescription(makeStringNullIfEmpty(componentAnnotation.description()))
.withIcons(convertIcons(componentAnnotation.icons()))
.withMetatype(componentAnnotation.metatype())
.withLabel(makeStringNullIfEmpty(componentAnnotation.label()))
.withLocalizationBase(makeStringNullIfEmpty(componentAnnotation.localizationBase()))
.withType(clazz.getName())
.withActivate(findMethodWithAnnotation(Activate.class))
.withDeactivate(findMethodWithAnnotation(Deactivate.class))
.withUpdate(findMethodWithAnnotation(Update.class));
generateMetaForAttributeHolders();
componentMetaBuilder.withAttributes(attributes.toArray(
new AttributeMetadata<?>[attributes.size()]));
Service serviceAnnotation = clazz.getAnnotation(Service.class);
if (serviceAnnotation != null) {
ServiceMetadataBuilder serviceMetadataBuilder = new ServiceMetadataBuilder();
Class<?>[] serviceInterfaces = serviceAnnotation.value();
serviceMetadataBuilder.withClazzes(serviceInterfaces);
componentMetaBuilder.withService(serviceMetadataBuilder.build());
}
return componentMetaBuilder.build();
}
private <R> R callMethodOfAnnotation(final Annotation annotation, final String fieldName) {
Class<? extends Annotation> annotationType = annotation.getClass();
Method method;
try {
method = annotationType.getMethod(fieldName);
@SuppressWarnings("unchecked")
R result = (R) method.invoke(annotation);
return result;
} catch (NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private ConfigurationPolicy convertConfigurationPolicy(
final org.everit.osgi.ecm.annotation.ConfigurationPolicy configurationPolicy) {
switch (configurationPolicy) {
case IGNORE:
return ConfigurationPolicy.IGNORE;
case REQUIRE:
return ConfigurationPolicy.REQUIRE;
case FACTORY:
return ConfigurationPolicy.FACTORY;
default:
return ConfigurationPolicy.OPTIONAL;
}
}
private Icon[] convertIcons(final org.everit.osgi.ecm.annotation.Icon[] icons) {
if (icons == null) {
final Icon[] noIconDefined = null;
return noIconDefined;
}
Icon[] result = new Icon[icons.length];
for (int i = 0; i < icons.length; i++) {
result[i] = new Icon(icons[i].path(), icons[i].size());
}
return result;
}
private ReferenceConfigurationType convertReferenceConfigurationType(
final org.everit.osgi.ecm.annotation.ReferenceConfigurationType attributeType) {
if (attributeType.equals(org.everit.osgi.ecm.annotation.ReferenceConfigurationType.CLAUSE)) {
return ReferenceConfigurationType.CLAUSE;
} else {
return ReferenceConfigurationType.FILTER;
}
}
private String deriveReferenceId(final Member member, final Annotation annotation) {
String name = callMethodOfAnnotation(annotation, "referenceId");
name = makeStringNullIfEmpty(name);
if (name != null) {
return name;
}
if (member != null) {
String memberName = member.getName();
if (member instanceof Field) {
return memberName;
} else if (member instanceof Method) {
return resolveIdIfMethodNameStartsWith(memberName, "set");
}
}
return null;
}
private Class<?> deriveServiceInterface(final Member member, final ServiceRef annotation) {
Class<?> referenceInterface = annotation.referenceInterface();
if (!AutoDetect.class.equals(referenceInterface)) {
if (Void.class.equals(referenceInterface)) {
return null;
}
return referenceInterface;
}
if (member != null) {
if (member instanceof Field) {
return resolveServiceInterfaceBasedOnGenericType(((Field) member).getGenericType());
} else if (member instanceof Method) {
Method method = ((Method) member);
Class<?>[] parameterTypes = method.getParameterTypes();
if ((parameterTypes.length != 1) || parameterTypes[0].isPrimitive()) {
throw new InconsistentAnnotationException(
"Reference auto detection can work only on a method that has one"
+ " non-primitive parameter:" + method.toGenericString());
}
return resolveServiceInterfaceBasedOnGenericType(method.getGenericParameterTypes()[0]);
}
}
return null;
}
private <V_ARRAY, B extends AttributeMetadataBuilder<V_ARRAY, B>> void fillAttributeMetaBuilder(
final Member member,
final Annotation annotation,
final AttributeMetadataBuilder<V_ARRAY, B> builder) {
Boolean dynamic = callMethodOfAnnotation(annotation, "dynamic");
Boolean optional = callMethodOfAnnotation(annotation, "optional");
boolean multiple = resolveMultiple(annotation, member);
Boolean metatype = callMethodOfAnnotation(annotation, "metatype");
String label = callMethodOfAnnotation(annotation, "label");
String description = callMethodOfAnnotation(annotation, "description");
Class<? extends Annotation> annotationType = annotation.annotationType();
float priority = 0;
if (annotationType.equals(ServiceRef.class)
|| annotationType.equals(BundleCapabilityRef.class)) {
priority = callMethodOfAnnotation(annotation, "attributePriority");
} else {
priority = callMethodOfAnnotation(annotation, "priority");
}
Object defaultValueArray = callMethodOfAnnotation(annotation, "defaultValue");
@SuppressWarnings("unchecked")
V_ARRAY typedDefaultValueArray = (V_ARRAY) defaultValueArray;
if (!multiple && (Array.getLength(typedDefaultValueArray) == 0)) {
typedDefaultValueArray = null;
}
builder.withDynamic(dynamic)
.withOptional(optional)
.withMultiple(multiple)
.withMetatype(metatype)
.withLabel(makeStringNullIfEmpty(label))
.withDescription(makeStringNullIfEmpty(description))
.withPriority(priority)
.withDefaultValue(typedDefaultValueArray);
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> void fillPropertyAttributeBuilder(
final Member member,
final Annotation annotation,
final PropertyAttributeMetadataBuilder<V, B> builder) {
String attributeId = callMethodOfAnnotation(annotation, "attributeId");
attributeId = makeStringNullIfEmpty(attributeId);
if ((attributeId == null) && (member != null)) {
String memberName = member.getName();
if (member instanceof Field) {
attributeId = memberName;
} else if (member instanceof Method) {
attributeId = resolveIdIfMethodNameStartsWith(memberName, "set");
}
}
builder.withAttributeId(attributeId);
fillAttributeMetaBuilder(member, annotation, builder);
String setter = callMethodOfAnnotation(annotation, "setter");
setter = makeStringNullIfEmpty(setter);
if (setter != null) {
builder.withSetter(new MethodDescriptor(setter));
} else if (member != null) {
if (member instanceof Method) {
builder.withSetter(new MethodDescriptor((Method) member));
} else if (member instanceof Field) {
String fieldName = member.getName();
String setterName = "set" + fieldName.substring(0, 1).toUpperCase(Locale.getDefault())
+ fieldName.substring(1);
MethodDescriptor methodDescriptor = resolveSetter(builder, setterName);
if (methodDescriptor != null) {
builder.withSetter(methodDescriptor);
}
}
}
}
private <B extends ReferenceMetadataBuilder<B>> void fillReferenceBuilder(final Member member,
final Annotation annotation, final ReferenceMetadataBuilder<B> builder) {
fillAttributeMetaBuilder(member, annotation, builder);
org.everit.osgi.ecm.annotation.ReferenceConfigurationType configurationType =
callMethodOfAnnotation(annotation, "configurationType");
ReferenceConfigurationType convertedConfigurationType =
convertReferenceConfigurationType(configurationType);
String referenceId = deriveReferenceId(member, annotation);
if (referenceId == null) {
throw new MetadataValidationException(
"Reference id for one of the references could not be determined in class "
+ clazz.getName());
}
String setterName =
makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "setter"));
if (setterName != null) {
builder.withSetter(new MethodDescriptor(setterName));
} else if (member instanceof Method) {
builder.withSetter(new MethodDescriptor((Method) member));
}
builder
.withReferenceId(referenceId)
.withAttributeId(
makeStringNullIfEmpty((String) callMethodOfAnnotation(annotation, "attributeId")))
.withReferenceConfigurationType(convertedConfigurationType);
}
private <V_ARRAY, B extends SelectablePropertyAttributeMetadataBuilder<V_ARRAY, B>> void fillSelectablePropertyAttributeBuilder(// CS_DISABLE_LINE_LENGTH
final Member member, final Annotation annotation,
final SelectablePropertyAttributeMetadataBuilder<V_ARRAY, B> builder) {
fillPropertyAttributeBuilder(member, annotation, builder);
Object optionAnnotationArray = callMethodOfAnnotation(annotation, "options");
int length = Array.getLength(optionAnnotationArray);
if (length == 0) {
builder.withOptions(null, null);
return;
}
String[] labels = new String[length];
@SuppressWarnings("unchecked")
V_ARRAY values = (V_ARRAY) Array.newInstance(builder.getValueType(), length);
for (int i = 0; i < length; i++) {
Annotation optionAnnotation = (Annotation) Array.get(optionAnnotationArray, i);
String label = callMethodOfAnnotation(optionAnnotation, "label");
Object value = callMethodOfAnnotation(optionAnnotation, "value");
label = makeStringNullIfEmpty(label);
if (label == null) {
label = value.toString();
}
labels[i] = label;
Array.set(values, i, value);
}
builder.withOptions(labels, values);
}
private MethodDescriptor findMethodWithAnnotation(
final Class<? extends Annotation> annotationClass) {
Method foundMethod = null;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Annotation annotation = method.getAnnotation(annotationClass);
if (annotation != null) {
if (foundMethod != null) {
throw new InconsistentAnnotationException("The '" + annotationClass.getName()
+ "' annotation is attached to more than one method in class '" + clazz.getName()
+ "'.");
}
foundMethod = method;
}
}
if (foundMethod != null) {
return new MethodDescriptor(foundMethod);
} else {
return null;
}
}
private void generateAttributeMetaForAnnotatedElements(
final AnnotatedElement[] annotatedElements) {
for (AnnotatedElement annotatedElement : annotatedElements) {
Annotation[] annotations = annotatedElement.getAnnotations();
for (Annotation annotation : annotations) {
if (annotatedElement instanceof Member) {
processAttributeHolderAnnotation((Member) annotatedElement, annotation);
} else {
processAttributeHolderAnnotation(null, annotation);
}
}
}
}
private void generateMetaForAttributeHolders() {
generateAttributeMetaForAnnotatedElements(new AnnotatedElement[] { clazz });
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredFields());
generateAttributeMetaForAnnotatedElements(clazz.getDeclaredMethods());
}
private String makeStringNullIfEmpty(final String text) {
if (text == null) {
return null;
}
if ("".equals(text.trim())) {
return null;
}
return text;
}
private void processAnnotationContainer(final Annotation annotationContainer) {
try {
Method method = annotationContainer.annotationType().getMethod("value");
Annotation[] annotations = (Annotation[]) method.invoke(annotationContainer);
for (Annotation annotation : annotations) {
processAttributeHolderAnnotation(null, annotation);
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException("Error during processing class " + clazz.getName(), e);
}
}
@Generated("avoid_checkstyle_alert_about_complexity")
private void processAttributeHolderAnnotation(final Member element, final Annotation annotation) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (ANNOTATION_CONTAINER_TYPES.contains(annotationType)) {
processAnnotationContainer(annotation);
} else if (annotationType.equals(ServiceRef.class)) {
processServiceReferenceAnnotation(element, (ServiceRef) annotation);
} else if (annotationType.equals(BundleCapabilityRef.class)) {
processBundleCapabilityReferenceAnnotation(element, (BundleCapabilityRef) annotation);
} else if (annotationType.equals(BooleanAttribute.class)) {
processBooleanAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ByteAttribute.class)) {
processByteAttributeAnnotation(element, annotation);
} else if (annotationType.equals(CharacterAttribute.class)) {
processCharacterAttributeAnnotation(element, annotation);
} else if (annotationType.equals(DoubleAttribute.class)) {
processDoubleAttributeAnnotation(element, annotation);
} else if (annotationType.equals(FloatAttribute.class)) {
processFloatAttributeAnnotation(element, annotation);
} else if (annotationType.equals(IntegerAttribute.class)) {
processIntegerAttributeAnnotation(element, annotation);
} else if (annotationType.equals(LongAttribute.class)) {
processLongAttributeAnnotation(element, annotation);
} else if (annotationType.equals(PasswordAttribute.class)) {
processPasswordAttributeAnnotation(element, annotation);
} else if (annotationType.equals(ShortAttribute.class)) {
processShortAttributeAnnotation(element, annotation);
} else if (annotationType.equals(StringAttribute.class)) {
processStringAttributeAnnotation(element, annotation);
}
}
private void processBooleanAttributeAnnotation(final Member element,
final Annotation annotation) {
BooleanAttributeMetadataBuilder builder = new BooleanAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processBundleCapabilityReferenceAnnotation(final Member member,
final BundleCapabilityRef annotation) {
BundleCapabilityReferenceMetadataBuilder builder =
new BundleCapabilityReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withNamespace(annotation.namespace()).withStateMask(annotation.stateMask());
putIntoAttributes(builder);
}
private void processByteAttributeAnnotation(final Member element, final Annotation annotation) {
ByteAttributeMetadataBuilder builder = new ByteAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processCharacterAttributeAnnotation(final Member element,
final Annotation annotation) {
CharacterAttributeMetadataBuilder builder = new CharacterAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processDoubleAttributeAnnotation(final Member element, final Annotation annotation) {
DoubleAttributeMetadataBuilder builder = new DoubleAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processFloatAttributeAnnotation(final Member element, final Annotation annotation) {
FloatAttributeMetadataBuilder builder = new FloatAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processIntegerAttributeAnnotation(final Member element,
final Annotation annotation) {
IntegerAttributeMetadataBuilder builder = new IntegerAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processLongAttributeAnnotation(final Member element, final Annotation annotation) {
LongAttributeMetadataBuilder builder = new LongAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processPasswordAttributeAnnotation(final Member element,
final Annotation annotation) {
PasswordAttributeMetadataBuilder builder = new PasswordAttributeMetadataBuilder();
fillPropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processServiceReferenceAnnotation(final Member member, final ServiceRef annotation) {
ServiceReferenceMetadataBuilder builder = new ServiceReferenceMetadataBuilder();
fillReferenceBuilder(member, annotation, builder);
builder.withServiceInterface(deriveServiceInterface(member, annotation));
putIntoAttributes(builder);
}
private void processShortAttributeAnnotation(final Member element, final Annotation annotation) {
ShortAttributeMetadataBuilder builder = new ShortAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void processStringAttributeAnnotation(final Member element, final Annotation annotation) {
StringAttributeMetadataBuilder builder = new StringAttributeMetadataBuilder();
fillSelectablePropertyAttributeBuilder(element, annotation, builder);
putIntoAttributes(builder);
}
private void putIntoAttributes(final AttributeMetadataBuilder<?, ?> builder) {
AttributeMetadata<?> attributeMetadata = builder.build();
boolean exists = attributes.add(attributeMetadata);
if (!exists) {
throw new MetadataValidationException("Duplicate attribute id '"
+ attributeMetadata.getAttributeId()
+ "' found in class '" + clazz.getName() + "'.");
}
}
private String resolveIdIfMethodNameStartsWith(final String memberName, final String prefix) {
int prefixLength = prefix.length();
if (memberName.startsWith(prefix) && (memberName.length() > prefixLength)) {
return memberName.substring(prefixLength, prefixLength + 1).toLowerCase(Locale.getDefault())
+ memberName.substring(prefixLength + 1);
} else {
return null;
}
}
private boolean resolveMultiple(final Annotation annotation, final Member member) {
ThreeStateBoolean multiple = callMethodOfAnnotation(annotation, "multiple");
if (multiple == ThreeStateBoolean.TRUE) {
return true;
}
if (multiple == ThreeStateBoolean.FALSE) {
return false;
}
if (member == null) {
return false;
}
if (member instanceof Method) {
Class<?>[] parameterTypes = ((Method) member).getParameterTypes();
if (parameterTypes.length == 0) {
throw new InconsistentAnnotationException(
"Could not determine the multiplicity of attribute based on annotation '"
+ annotation.toString() + "' that is defined on the method '" + member.toString()
+ "' in the class " + clazz.getName());
}
return parameterTypes[0].isArray();
} else if (member instanceof Field) {
Class<?> fieldType = ((Field) member).getType();
return fieldType.isArray();
}
throw new InconsistentAnnotationException(
"Could not determine the multiplicity of attribute based on annotation '"
+ annotation.toString() + "' in the class " + clazz.getName());
}
private Class<?> resolveServiceInterfaceBasedOnClassType(final Class<?> classType) {
if (classType.equals(ServiceHolder.class)) {
return null;
} else {
return classType;
}
}
private Class<?> resolveServiceInterfaceBasedOnGenericType(final Type genericType) {
if (genericType instanceof Class) {
Class<?> classType = (Class<?>) genericType;
if (!classType.isArray()) {
return classType;
}
Class<?> componentType = classType.getComponentType();
return resolveServiceInterfaceBasedOnClassType(componentType);
}
if (genericType instanceof GenericArrayType) {
GenericArrayType genericArrayType = (GenericArrayType) genericType;
Type genericComponentType = genericArrayType.getGenericComponentType();
if (genericComponentType instanceof Class) {
return resolveServiceInterfaceBasedOnClassType((Class<?>) genericComponentType);
}
if (genericComponentType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericComponentType;
return resolveServiceInterfaceBasedOnParameterizedType(parameterizedType);
}
}
if (genericType instanceof ParameterizedType) {
return resolveServiceInterfaceBasedOnParameterizedType((ParameterizedType) genericType);
}
throw new MetadataValidationException(
"Could not determine the OSGi service interface based on type "
+ genericType + " in class " + clazz.getName());
}
private Class<?> resolveServiceInterfaceBasedOnParameterizedType(
final ParameterizedType parameterizedType) {
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class) {
Class<?> classType = (Class<?>) rawType;
if (!classType.equals(ServiceHolder.class)) {
return classType;
}
Type serviceInterfaceType = parameterizedType.getActualTypeArguments()[0];
if (serviceInterfaceType instanceof WildcardType) {
return null;
}
if (serviceInterfaceType instanceof Class) {
return (Class<?>) serviceInterfaceType;
}
if (serviceInterfaceType instanceof ParameterizedType) {
Type raw = ((ParameterizedType) serviceInterfaceType).getRawType();
if (raw instanceof Class) {
return (Class<?>) raw;
}
}
}
throw new MetadataValidationException(
"Could not determine the OSGi service interface based on type "
+ parameterizedType + " in class " + clazz.getName());
}
private <V, B extends PropertyAttributeMetadataBuilder<V, B>> MethodDescriptor resolveSetter(
final PropertyAttributeMetadataBuilder<V, B> builder, final String setterName) {
List<MethodDescriptor> potentialDescriptors = new ArrayList<MethodDescriptor>();
Class<?> attributeType = builder.getValueType();
boolean multiple = builder.isMultiple();
if (multiple) {
String parameterTypeName = attributeType.getCanonicalName() + "[]";
potentialDescriptors
.add(new MethodDescriptor(setterName, new String[] { parameterTypeName }));
} else {
if (attributeType.isPrimitive()) {
Class<?> boxingType = PRIMITIVE_BOXING_TYPE_MAPPING.get(attributeType);
potentialDescriptors.add(new MethodDescriptor(setterName,
new String[] { boxingType.getCanonicalName() }));
}
potentialDescriptors
.add(new MethodDescriptor(setterName, new String[] { attributeType.getCanonicalName() }));
}
Method method = MethodUtil.locateMethodByPreference(clazz, false,
potentialDescriptors.toArray(new MethodDescriptor[potentialDescriptors.size()]));
if (method == null) {
return null;
}
return new MethodDescriptor(method);
}
}
| update compare method. Turn off automatic wrapper formatter option
(reset modified rows). | src/main/java/org/everit/osgi/ecm/annotation/metadatabuilder/MetadataBuilder.java | update compare method. Turn off automatic wrapper formatter option (reset modified rows). | <ide><path>rc/main/java/org/everit/osgi/ecm/annotation/metadatabuilder/MetadataBuilder.java
<ide>
<ide> @Override
<ide> public int compare(final AttributeMetadata<?> attr1, final AttributeMetadata<?> attr2) {
<del> if (attr1 == null) {
<del> return -1;
<del> }
<del> if (attr2 == null) {
<del> return 1;
<del> }
<del>
<ide> float attr1Priority = attr1.getPriority();
<ide> float attr2Priority = attr2.getPriority();
<ide> int compare = Float.compare(attr1Priority, attr2Priority);
<ide> } else if (member instanceof Method) {
<ide> Method method = ((Method) member);
<ide> Class<?>[] parameterTypes = method.getParameterTypes();
<del> if ((parameterTypes.length != 1) || parameterTypes[0].isPrimitive()) {
<add> if (parameterTypes.length != 1 || parameterTypes[0].isPrimitive()) {
<ide> throw new InconsistentAnnotationException(
<ide> "Reference auto detection can work only on a method that has one"
<ide> + " non-primitive parameter:" + method.toGenericString());
<ide> @SuppressWarnings("unchecked")
<ide> V_ARRAY typedDefaultValueArray = (V_ARRAY) defaultValueArray;
<ide>
<del> if (!multiple && (Array.getLength(typedDefaultValueArray) == 0)) {
<add> if (!multiple && Array.getLength(typedDefaultValueArray) == 0) {
<ide> typedDefaultValueArray = null;
<ide> }
<ide>
<ide> String attributeId = callMethodOfAnnotation(annotation, "attributeId");
<ide> attributeId = makeStringNullIfEmpty(attributeId);
<ide>
<del> if ((attributeId == null) && (member != null)) {
<add> if (attributeId == null && member != null) {
<ide> String memberName = member.getName();
<ide> if (member instanceof Field) {
<ide> attributeId = memberName;
<ide>
<ide> private String resolveIdIfMethodNameStartsWith(final String memberName, final String prefix) {
<ide> int prefixLength = prefix.length();
<del> if (memberName.startsWith(prefix) && (memberName.length() > prefixLength)) {
<add> if (memberName.startsWith(prefix) && memberName.length() > prefixLength) {
<ide> return memberName.substring(prefixLength, prefixLength + 1).toLowerCase(Locale.getDefault())
<ide> + memberName.substring(prefixLength + 1);
<ide> } else { |
|
JavaScript | bsd-3-clause | e01917c9dfada3fe255bff756e447a9991c6747f | 0 | emanchado/narrows,emanchado/narrows | import fs from "fs-extra";
import path from "path";
import config from "config";
import mysql from "mysql";
import Q from "q";
import ejs from "ejs";
import generateToken from "./token-generator";
const JSON_TO_DB = {
id: "id",
title: "title",
intro: "intro",
status: "status",
audio: "audio",
backgroundImage: "background_image",
text: "main_text",
published: "published",
narratorId: "narrator_id",
introBackgroundImage: "intro_background_image",
introAudio: "intro_audio",
defaultBackgroundImage: "default_background_image",
defaultAudio: "default_audio",
notes: "notes",
name: "name",
description: "description",
backstory: "backstory",
introSent: "intro_sent",
playerId: "player_id"
};
const AUDIO_REGEXP = new RegExp("\.mp3$", "i");
const VALID_NARRATION_STATUSES = ['active', 'finished', 'abandoned'];
const NARRATION_STYLES_CSS_TEMPLATE = `
<% if (titleFont) { %>
@font-face {
font-family: "NARROWS heading user font";
src: url("fonts/<%= titleFont %>");
}
<% } %>
<% if (bodyTextFont) { %>
@font-face {
font-family: "NARROWS body user font";
src: url("fonts/<%= bodyTextFont %>");
}
<% } %>
<% if (titleFont || titleColor || titleShadowColor) { %>
#top-image {
<% if (titleFont) { %>
font-family: "NARROWS heading user font";
<% } %>
<% if (titleFontSize) { %>
font-size: <%= titleFontSize %>px;
<% } %>
<% if (titleColor) { %>
color: <%= titleColor %>;
<% } %>
<% if (titleShadowColor) { %>
text-shadow: 3px 3px 0 <%= titleShadowColor %>, -1px -1px 0 <%= titleShadowColor %>, 1px -1px 0 <%= titleShadowColor %>, -1px 1px 0 <%= titleShadowColor %>, 1px 1px 0 <%= titleShadowColor %>;
<% } %>
}
<% } %>
<% if (bodyTextFont || bodyTextFontSize) { %>
.chapter {
<% if (bodyTextFont) { %>
font-family: "NARROWS body user font";
<% } %>
<% if (bodyTextFontSize) { %>
font-size: <%= bodyTextFontSize %>px;
<% } %>
}
<% } %>
<% if (bodyTextColor || bodyTextBackgroundColor) { %>
.chapter > p, .chapter > blockquote,
.chapter > h1, .chapter > h2, .chapter > h3,
.chapter ul, .chapter ol, .chapter .separator {
<% if (bodyTextColor) { %>
color: <%= bodyTextColor %>;
<% } %>
<% if (bodyTextBackgroundColor) { %>
background-color: <%= bodyTextBackgroundColor %>;
<% } %>
}
<% } %>
<% if (separatorImage) { %>
.chapter .separator {
background-image: url(/static/narrations/<%= narrationId %>/images/<%= separatorImage %>);
}
<% } %>
`;
function convertToDb(fieldName) {
if (!(fieldName in JSON_TO_DB)) {
throw new Error("Don't understand field " + fieldName);
}
return JSON_TO_DB[fieldName];
}
/**
* Return a promise that returns the files in a directory. If the
* directory doesn't exist, simply return an empty array.
*/
function filesInDir(dir) {
return Q.nfcall(fs.readdir, dir).catch(() => []);
}
function getFinalFilename(dir, filename) {
const probePath = path.join(dir, filename);
return Q.nfcall(fs.access, probePath).then(() => {
const ext = path.extname(filename);
const basename = path.basename(filename, ext);
const newFilename = `${basename} extra${ext}`;
return getFinalFilename(dir, newFilename);
}).catch(() => probePath);
}
function pad(number) {
return number < 10 ? `0${number}` : number;
}
function mysqlTimestamp(dateString) {
if (!dateString) {
return dateString;
}
const d = new Date(dateString);
const year = d.getFullYear(),
month = d.getMonth() + 1,
day = d.getDate();
const hour = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds();
return `${year}-${pad(month)}-${pad(day)} ` +
`${pad(hour)}:${pad(minutes)}:${pad(seconds)}`;
}
// Parses the JSON text for a narration intro and returns the parsed
// JS object. If the intro is effectively empty, return null as if the
// input had been null.
function parseIntroText(introText) {
const parsedIntro = JSON.parse(introText);
if (
parsedIntro &&
parsedIntro.content &&
parsedIntro.content.length === 1 &&
!("content" in parsedIntro.content[0])
) {
return null;
}
return parsedIntro;
}
function escapeCss(cssText) {
return (typeof cssText === 'string') ?
cssText.replace(new RegExp('[/;]', 'ig'), '') :
cssText;
}
class NarrowsStore {
constructor(connConfig, narrationDir) {
this.connConfig = connConfig;
this.narrationDir = narrationDir;
}
connect() {
this.db = new mysql.createPool(this.connConfig);
// Temporary extra methods for compatibility with the sqlite API
this.db.run = function(stmt, binds, cb) {
this.query(stmt, binds, function(err, results, fields) {
cb(err, results);
});
};
this.db.get = function(stmt, binds, cb) {
this.query(stmt, binds, function(err, results, fields) {
if (err) {
cb(err);
return;
}
if (results.length !== 1) {
cb('Did not receive exactly one result');
return;
}
cb(err, results[0]);
});
};
this.db.all = function(stmt, binds, cb) {
this.query(stmt, binds, function(err, results, fields) {
cb(err, results);
});
};
}
createNarration(props) {
const deferred = Q.defer();
const fields = Object.keys(props).map(convertToDb).concat("token");
const token = generateToken();
this.db.run(
`INSERT INTO narrations (${ fields.join(", ") })
VALUES (${ fields.map(() => "?").join(", ") })`,
Object.keys(props).map(f => props[f]).concat(token),
function(err, result) {
if (err) {
deferred.reject(err);
return;
}
const finalNarration = Object.assign({ id: result.insertId },
props);
deferred.resolve(finalNarration);
}
);
return deferred.promise;
}
_updateNarrationStyles(narrationId, newStyles) {
const cssFilePath = path.join(config.files.path,
narrationId.toString(),
"styles.css");
if (
Object.keys(newStyles).every(name => (
newStyles[name] === null || newStyles[name] === ''
))
) {
return Q.ninvoke(
this.db,
"run",
"DELETE FROM narration_styles WHERE narration_id = ?",
narrationId
).then(() => {
fs.removeSync(cssFilePath);
});
} else {
return Q.ninvoke(
this.db,
"run",
`REPLACE INTO narration_styles
(narration_id, title_font, title_font_size,
title_color, title_shadow_color,
body_text_font, body_text_font_size,
body_text_color, body_text_background_color,
separator_image)
VALUES (?, ?, ?,
?, ?,
?, ?,
?, ?,
?)`,
[narrationId, newStyles.titleFont, newStyles.titleFontSize,
newStyles.titleColor, newStyles.titleShadowColor,
newStyles.bodyTextFont, newStyles.bodyTextFontSize,
newStyles.bodyTextColor, newStyles.bodyTextBackgroundColor,
newStyles.separatorImage]
).then(() => {
const cssText = ejs.render(
NARRATION_STYLES_CSS_TEMPLATE,
Object.assign({narrationId: narrationId}, newStyles),
{escape: escapeCss}
);
fs.writeFileSync(cssFilePath, cssText);
});
}
}
updateNarration(narrationId, newProps) {
let initialPromise = Q(null);
if ("status" in newProps &&
VALID_NARRATION_STATUSES.indexOf(newProps.status) === -1) {
return Q.reject(new Error("Invalid status '" + newProps.status + "'"));
}
if ("intro" in newProps) {
newProps.intro = JSON.stringify(newProps.intro);
}
if ("styles" in newProps) {
const newStyles = newProps.styles;
delete newProps.styles;
initialPromise = this._updateNarrationStyles(narrationId, newStyles);
}
const propNames = Object.keys(newProps).map(convertToDb),
propNameStrings = propNames.map(p => `${p} = ?`);
const propValues = Object.keys(newProps).map(p => newProps[p]);
if (!propValues.length) {
return this.getNarration(narrationId);
}
return initialPromise.then(() => (
Q.ninvoke(
this.db,
"run",
`UPDATE narrations SET ${ propNameStrings.join(", ") } WHERE id = ?`,
propValues.concat(narrationId)
).then(
() => this.getNarration(narrationId)
)
));
}
_getNarrationCharacters(narrationId) {
return Q.ninvoke(
this.db,
"all",
`SELECT characters.id, name, display_name AS displayName,
token, novel_token AS novelToken, avatar
FROM characters
LEFT JOIN users
ON characters.player_id = users.id
WHERE narration_id = ?`,
narrationId
);
}
_getPublicNarrationCharacters(narrationId) {
return Q.ninvoke(
this.db,
"all",
`SELECT id, player_id IS NOT NULL AS claimed, name, avatar, description
FROM characters
WHERE narration_id = ?`,
narrationId
).then(characters => {
characters.forEach(c => {
c.claimed = !!c.claimed;
c.description = JSON.parse(c.description);
});
return characters;
});
}
_getNarrationFiles(narrationId) {
const filesDir = path.join(config.files.path, narrationId.toString());
return Q.all([
filesInDir(path.join(filesDir, "background-images")),
filesInDir(path.join(filesDir, "audio")),
filesInDir(path.join(filesDir, "images")),
filesInDir(path.join(filesDir, "fonts"))
]).spread((backgroundImages, audio, images, fonts) => {
return { backgroundImages, audio, images, fonts };
});
}
getNarration(id) {
return Q.ninvoke(
this.db,
"get",
`SELECT id, token, title, intro, status,
narrator_id AS narratorId,
intro_background_image AS introBackgroundImage,
intro_audio AS introAudio,
default_audio AS defaultAudio,
default_background_image AS defaultBackgroundImage,
COALESCE(notes, '') AS notes
FROM narrations WHERE id = ?`,
id
).then(narrationInfo => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + id);
}
if (narrationInfo.intro) {
narrationInfo.intro = parseIntroText(narrationInfo.intro);
}
narrationInfo.introUrl = `${config.publicAddress}/narrations/${narrationInfo.token}/intro`;
return Q.all([
this._getNarrationCharacters(id),
this._getNarrationFiles(id),
this._getNarrationStyles(id)
]).spread((characters, files, styles) => {
narrationInfo.characters = characters;
narrationInfo.files = files;
narrationInfo.styles = styles;
return narrationInfo;
});
});
}
getNarratorId(narrationId) {
return Q.ninvoke(
this.db,
"get",
`SELECT narrator_id AS narratorId
FROM narrations WHERE id = ?`,
narrationId
).then(narrationInfo => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + narrationId);
}
return narrationInfo.narratorId;
});
}
getNarrationByToken(token) {
return Q.ninvoke(
this.db,
"get",
`SELECT id, title, intro, status, narrator_id AS narratorId,
intro_background_image AS backgroundImage,
intro_audio AS audio
FROM narrations WHERE token = ?`,
token
).then(narrationInfo => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + token);
}
if (narrationInfo.intro) {
narrationInfo.intro = parseIntroText(narrationInfo.intro);
}
return this._getPublicNarrationCharacters(narrationInfo.id).then(characters => {
narrationInfo.characters = characters;
return narrationInfo;
});
});
}
getPublicNarration(id) {
return Q.all([
Q.ninvoke(
this.db,
"get",
`SELECT id, title, intro, intro_audio AS introAudio,
intro_background_image AS introBackgroundImage,
default_audio AS defaultAudio,
default_background_image AS defaultBackgroundImage
FROM narrations WHERE id = ?`,
id
),
this._getPublicNarrationCharacters(id)
]).spread((narrationInfo, characters) => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + id);
}
narrationInfo.intro = parseIntroText(narrationInfo.intro);
narrationInfo.characters = characters;
return narrationInfo;
});
}
getNarrationChapters(id, userOpts) {
const opts = Object.assign({ limit: -1 }, userOpts);
const limitClause = opts.limit > 0 ?
`LIMIT ${parseInt(opts.limit, 10)}` : "";
return Q.ninvoke(
this.db,
"all",
`SELECT id, title, published
FROM chapters
WHERE narration_id = ?
ORDER BY COALESCE(published, created) DESC
${ limitClause }`,
id
).then(chapters => {
if (chapters.length === 0) {
return [[], {}];
}
const chapterMap = {};
chapters.forEach(chapter => {
chapterMap[chapter.id] = chapter;
chapter.participants = [];
chapter.activeUsers = [];
chapter.numberMessages = 0;
});
return [chapters, chapterMap];
}).spread((chapters, chapterMap) => {
if (chapters.length === 0) {
return [];
}
const placeholders = chapters.map(_ => "?");
return Q.ninvoke(
this.db,
"all",
`SELECT chapter_id AS chapterId,
COUNT(*) AS numberMessages
FROM messages
WHERE chapter_id IN (${ placeholders.join(", ") })
GROUP BY chapter_id`,
chapters.map(f => f.id)
).then(numberMessagesPerChapter => {
numberMessagesPerChapter.forEach(numberAndChapter => {
chapterMap[numberAndChapter.chapterId].numberMessages =
numberAndChapter.numberMessages;
});
return Q.ninvoke(
this.db,
"all",
`SELECT DISTINCT chapter_id AS chapterId,
CH.id, CH.name, CH.avatar
FROM messages M
JOIN characters CH
ON M.sender_id = CH.id
WHERE chapter_id IN (${ placeholders.join(", ") })`,
chapters.map(f => f.id)
);
}).then(activeUsers => {
activeUsers.forEach(({ chapterId, name, avatar }) => {
chapterMap[chapterId].activeUsers.push({
id: id,
name: name,
avatar: avatar
});
});
return Q.ninvoke(
this.db,
"all",
`SELECT chapter_id AS chapterId,
CH.id, CH.name, CH.avatar
FROM chapter_participants CP
JOIN characters CH
ON CP.character_id = CH.id
WHERE chapter_id IN (${ placeholders.join(", ") })`,
chapters.map(f => f.id)
);
}).then(participants => {
participants.forEach(({ chapterId, id, name, avatar }) => {
chapterMap[chapterId].participants.push({
id: id,
name: name,
avatar: avatar
});
});
return chapters;
});
});
}
getNarrationOverview(userId, opts) {
const userOpts = Object.assign({ status: null }, opts);
let extraConditions = "";
const binds = [userId];
if (userOpts.status) {
extraConditions = " AND status = ?";
binds.push(userOpts.status);
}
return Q.ninvoke(
this.db,
"all",
`SELECT id, token, title, intro, status,
default_audio AS defaultAudio,
default_background_image AS defaultBackgroundImage,
COALESCE(notes, '') AS notes
FROM narrations
WHERE narrator_id = ?
${ extraConditions }
ORDER BY created DESC`,
binds
).then(rows => (
Q.all([
Q.all(rows.map(row => (
this.getNarrationChapters(row.id, { limit: 5 })
))),
Q.all(rows.map(row => this._getNarrationCharacters(row.id))),
Q.all(rows.map(row => this._getNarrationFiles(row.id))),
Q.all(rows.map(row => this._getNarrationStyles(row.id)))
]).spread((chapterLists, characterLists, fileLists, styleLists) => ({
narrations: chapterLists.map((chapters, i) => ({
narration: Object.assign(rows[i],
{characters: characterLists[i],
files: fileLists[i],
styles: styleLists[i],
intro: parseIntroText(rows[i].intro),
introUrl: `${config.publicAddress}/narrations/${rows[i].token}/intro`}),
chapters: chapters
}))
}))
));
}
_getNarrationStyles(narrationId) {
return Q.ninvoke(
this.db,
"all",
`SELECT title_font AS titleFont, title_font_size AS titleFontSize,
title_color AS titleColor, title_shadow_color AS titleShadowColor,
body_text_font AS bodyTextFont,
body_text_font_size AS bodyTextFontSize,
body_text_color AS bodyTextColor,
body_text_background_color AS bodyTextBackgroundColor,
separator_image AS separatorImage
FROM narration_styles
WHERE narration_id = ?`,
narrationId
).then(rows => (
rows.length ? rows[0] : {}
));
}
getCharacterOverview(userId, opts) {
const userOpts = Object.assign({ status: null }, opts);
let extraQuery = "";
let extraBinds = [];
if (userOpts.status === "active") {
const narrationGraceTime = new Date();
narrationGraceTime.setDate(narrationGraceTime.getDate() - 14);
extraQuery = "HAVING status = 'active' OR last_published > ?";
extraBinds = [narrationGraceTime];
}
return Q.ninvoke(
this.db,
"all",
`SELECT CHR.id, status,
COALESCE(MAX(published), NOW()) AS last_published
FROM narrations N
JOIN characters CHR ON CHR.narration_id = N.id
LEFT JOIN chapters C ON C.narration_id = N.id
WHERE player_id = ?
GROUP BY CHR.id
${extraQuery}
ORDER BY last_published DESC`,
[userId].concat(extraBinds)
).then(rows => (
Q.all(rows.map(row => this.getFullCharacterStats(row.id)))
));
}
deleteNarration(id) {
return Q.ninvoke(
this.db,
"run",
"SELECT id FROM characters WHERE narration_id = ?",
id
).then(characters => (
Q.all(characters.map(char => (
this.removeCharacter(char.id)
)))
)).then(() => (
Q.ninvoke(
this.db,
"run",
"DELETE FROM chapters WHERE narration_id = ?",
id
)
)).then(() => (
Q.ninvoke(
this.db,
"run",
"DELETE FROM narrations WHERE id = ?",
id
)
)).then(result => {
// Delete the files
const filesDir = path.join(config.files.path, id.toString());
fs.removeSync(filesDir);
// Return if there was a deleted narration in the above query
return result.affectedRows === 1;
});
}
deleteChapter(id) {
return Q.ninvoke(
this.db,
"run",
"DELETE FROM chapters WHERE id = ?",
id
).catch(err => true);
}
_insertParticipants(id, participants) {
let promise = Q(true);
participants.forEach(participant => {
promise = promise.then(() => {
return Q.ninvoke(
this.db,
"run",
`INSERT INTO chapter_participants (chapter_id, character_id)
VALUES (?, ?)`,
[id, participant.id]
);
});
});
return promise;
}
/**
* Creates a new chapter for the given narration, with the given
* properties. Properties have to include at least "text" (JSON in
* ProseMirror format) and "participants" (an array of ids for the
* characters in the chapter).
*/
createChapter(narrationId, chapterProps) {
if (!chapterProps.text) {
throw new Error("Cannot create a new chapter without text");
}
if (!chapterProps.participants) {
throw new Error("Cannot create a new chapter without participants");
}
return this.getNarration(narrationId).then(narration => {
const basicProps = {
backgroundImage: narration.defaultBackgroundImage,
audio: narration.defaultAudio
};
Object.keys(JSON_TO_DB).forEach(field => {
if (field in chapterProps) {
basicProps[field] = chapterProps[field];
}
});
basicProps.text = JSON.stringify(basicProps.text);
return this._insertChapter(narrationId,
basicProps,
chapterProps.participants);
});
}
_insertChapter(narrationId, basicProps, participants) {
const deferred = Q.defer();
const fields = Object.keys(basicProps).map(convertToDb),
fieldString = fields.join(", "),
placeholderString = fields.map(_ => "?").join(", "),
values = Object.keys(basicProps).map(f => (
f === "published" ?
mysqlTimestamp(basicProps[f]) : basicProps[f]
));
const self = this;
this.db.run(
`INSERT INTO chapters
(${ fieldString }, narration_id)
VALUES (${ placeholderString }, ?)`,
values.concat(narrationId),
function(err, result) {
if (err) {
deferred.reject(err);
return;
}
const newChapterId = result.insertId;
self._insertParticipants(newChapterId, participants).then(() => {
return self.getChapter(newChapterId, { includePrivateFields: true });
}).then(chapter => {
deferred.resolve(chapter);
}).catch(err => {
return self.deleteChapter(newChapterId).then(() => {
deferred.reject(err);
});
});
}
);
return deferred.promise;
}
getNarratorEmail(narrationId) {
return Q.ninvoke(
this.db,
"get",
`SELECT email
FROM narrations N
JOIN users U
ON N.narrator_id = U.id
WHERE N.id = ?`,
narrationId
).then(
narrationRow => narrationRow.email
);
}
getChapterParticipants(chapterId, userOpts) {
const opts = userOpts || {};
const extraFields = opts.includePrivateFields ?
", C.player_id, U.display_name AS displayName, C.token, C.novel_token AS novelToken, C.notes" : "";
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.name, C.avatar, C.description,
CASE WHEN C.player_id THEN TRUE ELSE FALSE END AS claimed
${ extraFields }
FROM characters C
JOIN chapter_participants CP ON C.id = CP.character_id
LEFT JOIN users U ON U.id = C.player_id
WHERE chapter_id = ?`,
chapterId
).then(participants => (
participants.map(participant => (
Object.assign(
participant,
{ description: JSON.parse(participant.description),
claimed: !!participant.claimed }
)
))
));
}
isCharacterParticipant(characterId, chapterId) {
return Q.ninvoke(
this.db,
"query",
`SELECT COUNT(*) AS cnt
FROM chapter_participants
WHERE character_id = ? AND chapter_id = ?`,
[characterId, chapterId]
).spread(rows => (
rows[0].cnt > 0
)).catch(err => (
false
));
}
getChapter(id, opts) {
return Q.ninvoke(
this.db,
"get",
`SELECT id, title, audio, narration_id as narrationId,
background_image AS backgroundImage,
main_text AS text, published
FROM chapters
WHERE id = ?`,
id
).then(chapterData => {
if (!chapterData) {
throw new Error("Cannot find chapter " + id);
}
chapterData.text = JSON.parse(chapterData.text.replace(/\r/g, ""));
return this.getChapterParticipants(id, opts).then(participants => {
chapterData.participants = participants;
return chapterData;
});
});
}
_updateChapterParticipants(id, newParticipantList) {
return this.getChapterParticipants(id).then(currentParticipantList => {
const newHash = {}, currentHash = {};
newParticipantList.forEach(newParticipant => {
newHash[newParticipant.id] = true;
});
currentParticipantList.forEach(currentParticipant => {
currentHash[currentParticipant.id] = true;
});
newParticipantList.forEach(newParticipant => {
if (!currentHash.hasOwnProperty(newParticipant.id)) {
this._addParticipant(id, newParticipant.id);
}
});
currentParticipantList.forEach(currentParticipant => {
if (!newHash.hasOwnProperty(currentParticipant.id)) {
this._removeParticipant(id, currentParticipant.id);
}
});
});
}
updateChapter(id, props) {
const participants = props.participants;
delete props.participants;
if ("text" in props) {
props.text = JSON.stringify(props.text);
}
let updatePromise;
if (Object.keys(props).length === 0) {
// No regular fields to update, avoid SQL error
updatePromise = Q(true);
} else {
const propNames = Object.keys(props).map(convertToDb),
propNameStrings = propNames.map(p => `${p} = ?`);
const propValues = Object.keys(props).map(n => (
n === "published" ? mysqlTimestamp(props[n]) : props[n]
));
updatePromise = Q.ninvoke(
this.db,
"run",
`UPDATE chapters SET ${ propNameStrings.join(", ") }
WHERE id = ?`,
propValues.concat(id)
);
}
return updatePromise.then(
() => this._updateChapterParticipants(id, participants)
).then(
() => this.getChapter(id, { includePrivateFields: true })
);
}
getCharacterInfo(characterToken, extraFields) {
extraFields = extraFields || [];
const extraFieldString = extraFields.length !== 0 ?
`, ${ extraFields.join(", ") }` :
"";
return Q.ninvoke(
this.db,
"get",
`SELECT id, name, token, notes${ extraFieldString }
FROM characters WHERE token = ?`,
characterToken
);
}
getCharacterInfoById(characterId, extraFields) {
extraFields = extraFields || [];
const extraFieldString = extraFields.length !== 0 ?
`, ${ extraFields.join(", ") }` :
"";
return Q.ninvoke(
this.db,
"get",
`SELECT id, name, token, notes, narration_id AS narrationId${ extraFieldString }
FROM characters WHERE id = ?`,
characterId
);
}
getCharacterInfoBulk(characterIds) {
if (!characterIds.length) {
return Q({});
}
const placeholders = characterIds.map(_ => "?");
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.name, U.email
FROM characters C
LEFT JOIN users U
ON C.player_id = U.id
WHERE C.id IN (${placeholders.join(', ')})`,
characterIds
).then(rows => {
const info = {};
rows.forEach(row => {
info[row.id] = { name: row.name, email: row.email };
});
return info;
});
}
getCharacterTokenById(characterId) {
return Q.ninvoke(
this.db,
"get",
"SELECT token FROM characters WHERE id = ?",
characterId
).then(
row => row.token
);
}
addCharacter(name, userId, narrationId) {
const deferred = Q.defer();
const newToken = generateToken();
const newNovelToken = generateToken();
return Q.ninvoke(
this.db,
"run",
`INSERT INTO characters (name, token, novel_token, player_id, narration_id)
VALUES (?, ?, ?, ?, ?)`,
[name, newToken, newNovelToken, userId, narrationId]
).then(() => (
this.getCharacterInfo(newToken)
));
}
_addParticipant(chapterId, characterId) {
return this.getChapter(chapterId).then(() => (
this.getChapterParticipants(chapterId)
)).then(participants => {
if (participants.some(p => p.id === characterId)) {
return participants;
}
return Q.ninvoke(
this.db,
"run",
`INSERT INTO chapter_participants (chapter_id, character_id)
VALUES (?, ?)`,
[chapterId, characterId]
);
});
}
_removeParticipant(chapterId, characterId) {
return Q.ninvoke(
this.db,
"run",
`DELETE FROM chapter_participants
WHERE chapter_id = ? AND character_id = ?`,
[chapterId, characterId]
);
}
/**
* Adds a media file to the given narration, specifying its
* filename and a temporary path where the file lives.
*/
addMediaFile(narrationId, filename, tmpPath, type) {
const filesDir = path.join(config.files.path, narrationId.toString());
const typeDir = type === "backgroundImages" ?
"background-images" : type;
const finalDir = path.join(filesDir, typeDir);
return getFinalFilename(finalDir, filename).then(finalPath => {
return Q.nfcall(fs.move, tmpPath, finalPath).then(() => ({
name: path.basename(finalPath),
type: type
}));
});
}
_formatMessageList(messages) {
if (messages.length === 0) {
return messages;
}
const messageIds = messages.map(m => m.id);
const placeholders = messageIds.map(_ => "?").join(", ");
return Q.ninvoke(
this.db,
"all",
`SELECT MD.message_id AS messageId,
MD.recipient_id AS recipientId,
C.name, C.avatar
FROM message_deliveries MD JOIN characters C
ON MD.recipient_id = C.id
WHERE message_id IN (${ placeholders })`,
messageIds
).then(deliveries => {
const deliveryMap = {};
deliveries.forEach(({ messageId, recipientId, name, avatar }) => {
deliveryMap[messageId] = deliveryMap[messageId] || [];
deliveryMap[messageId].push({ id: recipientId,
name: name,
avatar: avatar });
});
messages.forEach(message => {
message.recipients = deliveryMap[message.id];
});
return messages;
}).then(messages => {
const placeholders = messages.map(_ => "?");
return Q.ninvoke(
this.db,
"all",
`SELECT id, name, avatar FROM characters
WHERE id IN (${ placeholders })`,
messages.map(m => m.senderId)
).then(characters => {
const characterMap = {};
characters.forEach(c => {
characterMap[c.id] = {id: c.id,
name: c.name,
avatar: c.avatar};
});
messages.forEach(m => {
m.sender = characterMap[m.senderId];
delete m.senderId;
});
return messages;
});
});
}
getChapterMessages(chapterId, characterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT DISTINCT id, sender_id AS senderId, body, sent AS sentAt
FROM messages M LEFT JOIN message_deliveries MD
ON M.id = MD.message_id
WHERE M.chapter_id = ?
AND (recipient_id = ? OR sender_id = ?)
ORDER BY sent`,
[chapterId, characterId, characterId]
).then(
this._formatMessageList.bind(this)
);
}
getAllChapterMessages(chapterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT DISTINCT id, sender_id AS senderId, body, sent AS sentAt
FROM messages M LEFT JOIN message_deliveries MD
ON M.id = MD.message_id
WHERE M.chapter_id = ?
ORDER BY sent`,
[chapterId]
).then(
this._formatMessageList.bind(this)
);
}
addMessage(chapterId, senderId, text, recipients) {
const deferred = Q.defer();
const self = this;
this.db.run(
`INSERT INTO messages (chapter_id, sender_id, body)
VALUES (?, ?, ?)`,
[chapterId, senderId, text],
function(err, result) {
if (err) {
deferred.reject(err);
return;
}
// Message without recipients is only for the narrator
// (as the narrator is a "user", not a "character", it
// cannot be in the recipient list, and instead is an
// implicit recipient of all messages).
if (!recipients.length) {
deferred.resolve({});
return;
}
const messageId = result.insertId;
const valueQueryPart =
recipients.map(() => "(?, ?)").join(", ");
const queryValues = recipients.reduce((acc, mr) => (
acc.concat(messageId, mr)
), []);
Q.ninvoke(
self.db,
"run",
`INSERT INTO message_deliveries
(message_id, recipient_id) VALUES ${ valueQueryPart }`,
queryValues
).then(() => {
deferred.resolve({});
}).catch(err => {
deferred.reject(err);
});
}
);
return deferred.promise;
}
getActiveChapter(characterId) {
return Q.ninvoke(
this.db,
"get",
`SELECT CHPT.id, CHPT.title, CHPT.published
FROM chapters CHPT
JOIN characters CHR
ON CHPT.narration_id = CHR.narration_id
JOIN chapter_participants CP
ON (CP.chapter_id = CHPT.id AND
CP.character_id = CHR.id)
WHERE CHR.id = ? AND published IS NOT NULL
ORDER BY published DESC
LIMIT 1`,
characterId
);
}
saveCharacterNotes(characterId, newNotes) {
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET notes = ? WHERE id = ?`,
[newNotes, characterId]
);
}
getChapterLastReactions(chapterId) {
return Q.ninvoke(
this.db,
"get",
`SELECT published, narration_id AS narrationId
FROM chapters
WHERE id = ?`,
chapterId
).then(row => (
this.getNarrationLastReactions(row.narrationId, row.published)
));
}
getNarrationLastReactions(narrationId, beforeDate) {
const binds = [narrationId];
let extraWhereClause = "";
if (beforeDate) {
extraWhereClause += "AND published < ?";
binds.push(beforeDate);
}
binds.push(narrationId);
return Q.ninvoke(
this.db,
"all",
`SELECT CHPT.id, CHPT.title,
CHPT.main_text AS text
FROM chapters CHPT
JOIN characters CHR
ON CHPT.narration_id = CHR.narration_id
JOIN (SELECT MAX(CHAP.published) AS published, character_id
FROM chapter_participants CP
JOIN chapters CHAP
ON CP.chapter_id = CHAP.id
WHERE narration_id = ?
${ extraWhereClause }
GROUP BY character_id) AS reaction_per_character
ON reaction_per_character.published = CHPT.published
AND reaction_per_character.character_id = CHR.id
WHERE CHR.narration_id = ?
AND CHPT.published IS NOT NULL
GROUP BY CHPT.id`,
binds
).then(lastChapters => {
const chapterIds = lastChapters.map(c => c.id);
return Q.all(
chapterIds.map(id => this.getAllChapterMessages(id))
).then(lastChapterMessages => {
lastChapterMessages.forEach((messages, i) => {
lastChapters[i].messages = messages;
});
return Q.all(
chapterIds.map(id => this.getChapterParticipants(id))
);
}).then(lastChapterParticipants => {
lastChapterParticipants.forEach((participants, i) => {
lastChapters[i].participants = participants;
});
return lastChapters;
});
});
}
getCharacterChaptersBasic(characterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.title
FROM chapters C
JOIN chapter_participants CP
ON C.id = CP.chapter_id
WHERE published IS NOT NULL
AND CP.character_id = ?`,
characterId
);
}
getCharacterChapters(characterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.title, C.main_text AS text,
C.audio, C.background_image AS backgroundImage
FROM chapters C
JOIN chapter_participants CP
ON C.id = CP.chapter_id
WHERE published IS NOT NULL
AND CP.character_id = ?`,
characterId
).then(chapters => {
chapters.forEach(c => {
c.text = JSON.parse(c.text.replace(/\r/g, ""));
});
return chapters;
});
}
getFullCharacterStats(characterId) {
return Q.all([
Q.ninvoke(
this.db,
"get",
`SELECT C.id, C.name, C.token, C.avatar, C.description,
C.backstory, C.novel_token AS novelToken,
U.display_name AS displayName,
N.id AS narrationId, N.title AS narrationTitle,
N.status
FROM characters C
JOIN narrations N
ON C.narration_id = N.id
LEFT JOIN users U
ON C.player_id = U.id
WHERE C.id = ?`,
characterId
),
this.getCharacterChaptersBasic(characterId)
]).spread((basicStats, chapters) => {
return this._getPublicNarrationCharacters(basicStats.narrationId).then(characters => ({
id: basicStats.id,
token: basicStats.token,
displayName: basicStats.displayName,
name: basicStats.name,
avatar: basicStats.avatar,
novelToken: basicStats.novelToken,
description: JSON.parse(basicStats.description),
backstory: JSON.parse(basicStats.backstory),
narration: {
id: basicStats.narrationId,
title: basicStats.narrationTitle,
status: basicStats.status,
chapters: chapters,
characters: characters.filter(character => (
character.id !== basicStats.id
))
}
}));
});
}
resetCharacterToken(characterId) {
const newToken = generateToken();
return Q.ninvoke(
this.db,
"run",
'UPDATE characters SET token = ? WHERE id = ?',
[newToken, characterId]
).then(() => (
this.getCharacterInfo(newToken)
));
}
updateCharacter(characterId, props) {
const propNames = Object.keys(props).map(convertToDb),
propNameStrings = propNames.map(p => `${p} = ?`);
const propValues = Object.keys(props).map(p => (
(["description", "backstory"].indexOf(p) !== -1) ?
((typeof props[p] === "string") ?
props[p] : JSON.stringify(props[p])) :
props[p]
));
if (!propValues.length) {
return this.getFullCharacterStats(characterId);
}
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET ${ propNameStrings.join(", ") } WHERE id = ?`,
propValues.concat(characterId)
).then(
() => this.getFullCharacterStats(characterId)
);
}
updateCharacterAvatar(characterId, filename, tmpPath) {
return Q.ninvoke(
this.db,
"query",
`SELECT narration_id AS narrationId FROM characters WHERE id = ?`,
characterId
).spread(results => {
const narrationId = results[0].narrationId;
const filesDir = path.join(config.files.path, narrationId.toString());
const fileExtension = path.extname(filename);
const finalBasename = `${ characterId }${ fileExtension }`;
const finalPath = path.join(filesDir, "avatars", finalBasename);
return Q.nfcall(fs.move, tmpPath, finalPath, {clobber: true}).then(() => {
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET avatar = ? WHERE id = ?`,
[finalBasename, characterId]
);
}).then(() => (
this.getFullCharacterStats(characterId)
));
});
}
getNovelInfo(novelToken) {
return Q.ninvoke(
this.db,
"query",
`SELECT C.id AS characterId,
C.narration_id AS narrationId
FROM characters C
WHERE C.novel_token = ?`,
novelToken
).spread(results => {
if (results.length !== 1) {
throw new Error(
`Could not find (a single) novel with token ${novelToken}`
);
}
return results[0];
});
}
searchNarration(narrationId, searchTerms) {
return Q.ninvoke(
this.db,
"query",
`SELECT id, title
FROM chapters
WHERE narration_id = ?
AND (main_text LIKE ? OR title LIKE ?)
AND published IS NOT NULL`,
[narrationId, `%${searchTerms}%`, `%${searchTerms}%`]
).spread(results => (
results.map(result => ({
id: result.id,
title: result.title
}))
));
}
claimCharacter(characterId, userId) {
return Q.ninvoke(
this.db,
"query",
`SELECT id, name, narration_id, player_id
FROM characters
WHERE player_id = ?
AND narration_id = (SELECT narration_id
FROM characters
WHERE id = ?)`,
[userId, characterId]
).spread(results => {
// Don't allow claiming more than one character per player
// in the same narration
if (results.length > 0) {
throw new Error(
"Cannot claim more than one character in the same " +
"narration"
);
}
// Yes, possibility of race condition here, but... MySQL
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET player_id = ?
WHERE id = ?
AND player_id IS NULL`,
[userId, characterId]
);
}).then(() => (
Q.ninvoke(
this.db,
"query",
`SELECT player_id FROM characters WHERE id = ?`,
[characterId]
).spread(results => {
if (results[0].player_id === userId) {
return results[0].player_id;
} else {
throw new Error(
`Could not claim character ${characterId} ` +
`with user id ${userId} (claimed by ` +
`${results[0].player_id})`
);
}
})
));
}
unclaimCharacter(characterId) {
return Q.ninvoke(
this.db,
"query",
`UPDATE characters
SET player_id = NULL
WHERE id = ?`,
[characterId]
).then(() => (
this.resetCharacterToken(characterId)
));
}
removeCharacter(characterId) {
return Q.ninvoke(
this.db,
"run",
`DELETE FROM messages WHERE sender_id = ?`,
[characterId]
).then(() => (
Q.ninvoke(
this.db,
"run",
`DELETE FROM characters WHERE id = ?`,
[characterId]
)
)).then(result => (
result.affectedRows === 1
));
}
}
export default NarrowsStore;
| src/backend/NarrowsStore.js | import fs from "fs-extra";
import path from "path";
import config from "config";
import mysql from "mysql";
import Q from "q";
import ejs from "ejs";
import generateToken from "./token-generator";
const JSON_TO_DB = {
id: "id",
title: "title",
intro: "intro",
status: "status",
audio: "audio",
backgroundImage: "background_image",
text: "main_text",
published: "published",
narratorId: "narrator_id",
introBackgroundImage: "intro_background_image",
introAudio: "intro_audio",
defaultBackgroundImage: "default_background_image",
defaultAudio: "default_audio",
notes: "notes",
name: "name",
description: "description",
backstory: "backstory",
introSent: "intro_sent",
playerId: "player_id"
};
const AUDIO_REGEXP = new RegExp("\.mp3$", "i");
const VALID_NARRATION_STATUSES = ['active', 'finished', 'abandoned'];
const NARRATION_STYLES_CSS_TEMPLATE = `
<% if (titleFont) { %>
@font-face {
font-family: "NARROWS heading user font";
src: url("fonts/<%= titleFont %>");
}
<% } %>
<% if (bodyTextFont) { %>
@font-face {
font-family: "NARROWS body user font";
src: url("fonts/<%= bodyTextFont %>");
}
<% } %>
<% if (titleFont || titleColor || titleShadowColor) { %>
#top-image {
<% if (titleFont) { %>
font-family: "NARROWS heading user font";
<% } %>
<% if (titleFontSize) { %>
font-size: <%= titleFontSize %>px;
<% } %>
<% if (titleColor) { %>
color: <%= titleColor %>;
<% } %>
<% if (titleShadowColor) { %>
text-shadow: 3px 3px 0 <%= titleShadowColor %>, -1px -1px 0 <%= titleShadowColor %>, 1px -1px 0 <%= titleShadowColor %>, -1px 1px 0 <%= titleShadowColor %>, 1px 1px 0 <%= titleShadowColor %>;
<% } %>
}
<% } %>
<% if (bodyTextFont || bodyTextFontSize) { %>
.chapter {
<% if (bodyTextFont) { %>
font-family: "NARROWS body user font";
<% } %>
<% if (bodyTextFontSize) { %>
font-size: <%= bodyTextFontSize %>px;
<% } %>
}
<% } %>
<% if (bodyTextColor || bodyTextBackgroundColor) { %>
.chapter > p, .chapter > blockquote,
.chapter > h1, .chapter > h2, .chapter > h3,
.chapter ul, .chapter ol, .chapter .separator {
<% if (bodyTextColor) { %>
color: <%= bodyTextColor %>;
<% } %>
<% if (bodyTextBackgroundColor) { %>
background-color: <%= bodyTextBackgroundColor %>;
<% } %>
}
<% } %>
<% if (separatorImage) { %>
.chapter .separator {
background-image: url(/static/narrations/<%= narrationId %>/images/<%= separatorImage %>);
}
<% } %>
`;
function convertToDb(fieldName) {
if (!(fieldName in JSON_TO_DB)) {
throw new Error("Don't understand field " + fieldName);
}
return JSON_TO_DB[fieldName];
}
/**
* Return a promise that returns the files in a directory. If the
* directory doesn't exist, simply return an empty array.
*/
function filesInDir(dir) {
return Q.nfcall(fs.readdir, dir).catch(() => []);
}
function getFinalFilename(dir, filename) {
const probePath = path.join(dir, filename);
return Q.nfcall(fs.access, probePath).then(() => {
const ext = path.extname(filename);
const basename = path.basename(filename, ext);
const newFilename = `${basename} extra${ext}`;
return getFinalFilename(dir, newFilename);
}).catch(() => probePath);
}
function pad(number) {
return number < 10 ? `0${number}` : number;
}
function mysqlTimestamp(dateString) {
if (!dateString) {
return dateString;
}
const d = new Date(dateString);
const year = d.getFullYear(),
month = d.getMonth() + 1,
day = d.getDate();
const hour = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds();
return `${year}-${pad(month)}-${pad(day)} ` +
`${pad(hour)}:${pad(minutes)}:${pad(seconds)}`;
}
// Parses the JSON text for a narration intro and returns the parsed
// JS object. If the intro is effectively empty, return null as if the
// input had been null.
function parseIntroText(introText) {
const parsedIntro = JSON.parse(introText);
if (
parsedIntro &&
parsedIntro.content &&
parsedIntro.content.length === 1 &&
!("content" in parsedIntro.content[0])
) {
return null;
}
return parsedIntro;
}
function escapeCss(cssText) {
return (typeof cssText === 'string') ?
cssText.replace(new RegExp('[/;]', 'ig'), '') :
cssText;
}
class NarrowsStore {
constructor(connConfig, narrationDir) {
this.connConfig = connConfig;
this.narrationDir = narrationDir;
}
connect() {
this.db = new mysql.createPool(this.connConfig);
// Temporary extra methods for compatibility with the sqlite API
this.db.run = function(stmt, binds, cb) {
this.query(stmt, binds, function(err, results, fields) {
cb(err, results);
});
};
this.db.get = function(stmt, binds, cb) {
this.query(stmt, binds, function(err, results, fields) {
if (err) {
cb(err);
return;
}
if (results.length !== 1) {
cb('Did not receive exactly one result');
return;
}
cb(err, results[0]);
});
};
this.db.all = function(stmt, binds, cb) {
this.query(stmt, binds, function(err, results, fields) {
cb(err, results);
});
};
}
createNarration(props) {
const deferred = Q.defer();
const fields = Object.keys(props).map(convertToDb).concat("token");
const token = generateToken();
this.db.run(
`INSERT INTO narrations (${ fields.join(", ") })
VALUES (${ fields.map(() => "?").join(", ") })`,
Object.keys(props).map(f => props[f]).concat(token),
function(err, result) {
if (err) {
deferred.reject(err);
return;
}
const finalNarration = Object.assign({ id: result.insertId },
props);
deferred.resolve(finalNarration);
}
);
return deferred.promise;
}
_updateNarrationStyles(narrationId, newStyles) {
const cssFilePath = path.join(config.files.path,
narrationId.toString(),
"styles.css");
if (
Object.keys(newStyles).every(name => (
newStyles[name] === null || newStyles[name] === ''
))
) {
return Q.ninvoke(
this.db,
"run",
"DELETE FROM narration_styles WHERE narration_id = ?",
narrationId
).then(() => {
fs.unlinkSync(cssFilePath);
});
} else {
return Q.ninvoke(
this.db,
"run",
`REPLACE INTO narration_styles
(narration_id, title_font, title_font_size,
title_color, title_shadow_color,
body_text_font, body_text_font_size,
body_text_color, body_text_background_color,
separator_image)
VALUES (?, ?, ?,
?, ?,
?, ?,
?, ?,
?)`,
[narrationId, newStyles.titleFont, newStyles.titleFontSize,
newStyles.titleColor, newStyles.titleShadowColor,
newStyles.bodyTextFont, newStyles.bodyTextFontSize,
newStyles.bodyTextColor, newStyles.bodyTextBackgroundColor,
newStyles.separatorImage]
).then(() => {
const cssText = ejs.render(
NARRATION_STYLES_CSS_TEMPLATE,
Object.assign({narrationId: narrationId}, newStyles),
{escape: escapeCss}
);
fs.writeFileSync(cssFilePath, cssText);
});
}
}
updateNarration(narrationId, newProps) {
let initialPromise = Q(null);
if ("status" in newProps &&
VALID_NARRATION_STATUSES.indexOf(newProps.status) === -1) {
return Q.reject(new Error("Invalid status '" + newProps.status + "'"));
}
if ("intro" in newProps) {
newProps.intro = JSON.stringify(newProps.intro);
}
if ("styles" in newProps) {
const newStyles = newProps.styles;
delete newProps.styles;
initialPromise = this._updateNarrationStyles(narrationId, newStyles);
}
const propNames = Object.keys(newProps).map(convertToDb),
propNameStrings = propNames.map(p => `${p} = ?`);
const propValues = Object.keys(newProps).map(p => newProps[p]);
if (!propValues.length) {
return this.getNarration(narrationId);
}
return initialPromise.then(() => (
Q.ninvoke(
this.db,
"run",
`UPDATE narrations SET ${ propNameStrings.join(", ") } WHERE id = ?`,
propValues.concat(narrationId)
).then(
() => this.getNarration(narrationId)
)
));
}
_getNarrationCharacters(narrationId) {
return Q.ninvoke(
this.db,
"all",
`SELECT characters.id, name, display_name AS displayName,
token, novel_token AS novelToken, avatar
FROM characters
LEFT JOIN users
ON characters.player_id = users.id
WHERE narration_id = ?`,
narrationId
);
}
_getPublicNarrationCharacters(narrationId) {
return Q.ninvoke(
this.db,
"all",
`SELECT id, player_id IS NOT NULL AS claimed, name, avatar, description
FROM characters
WHERE narration_id = ?`,
narrationId
).then(characters => {
characters.forEach(c => {
c.claimed = !!c.claimed;
c.description = JSON.parse(c.description);
});
return characters;
});
}
_getNarrationFiles(narrationId) {
const filesDir = path.join(config.files.path, narrationId.toString());
return Q.all([
filesInDir(path.join(filesDir, "background-images")),
filesInDir(path.join(filesDir, "audio")),
filesInDir(path.join(filesDir, "images")),
filesInDir(path.join(filesDir, "fonts"))
]).spread((backgroundImages, audio, images, fonts) => {
return { backgroundImages, audio, images, fonts };
});
}
getNarration(id) {
return Q.ninvoke(
this.db,
"get",
`SELECT id, token, title, intro, status,
narrator_id AS narratorId,
intro_background_image AS introBackgroundImage,
intro_audio AS introAudio,
default_audio AS defaultAudio,
default_background_image AS defaultBackgroundImage,
COALESCE(notes, '') AS notes
FROM narrations WHERE id = ?`,
id
).then(narrationInfo => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + id);
}
if (narrationInfo.intro) {
narrationInfo.intro = parseIntroText(narrationInfo.intro);
}
narrationInfo.introUrl = `${config.publicAddress}/narrations/${narrationInfo.token}/intro`;
return Q.all([
this._getNarrationCharacters(id),
this._getNarrationFiles(id),
this._getNarrationStyles(id)
]).spread((characters, files, styles) => {
narrationInfo.characters = characters;
narrationInfo.files = files;
narrationInfo.styles = styles;
return narrationInfo;
});
});
}
getNarratorId(narrationId) {
return Q.ninvoke(
this.db,
"get",
`SELECT narrator_id AS narratorId
FROM narrations WHERE id = ?`,
narrationId
).then(narrationInfo => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + narrationId);
}
return narrationInfo.narratorId;
});
}
getNarrationByToken(token) {
return Q.ninvoke(
this.db,
"get",
`SELECT id, title, intro, status, narrator_id AS narratorId,
intro_background_image AS backgroundImage,
intro_audio AS audio
FROM narrations WHERE token = ?`,
token
).then(narrationInfo => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + token);
}
if (narrationInfo.intro) {
narrationInfo.intro = parseIntroText(narrationInfo.intro);
}
return this._getPublicNarrationCharacters(narrationInfo.id).then(characters => {
narrationInfo.characters = characters;
return narrationInfo;
});
});
}
getPublicNarration(id) {
return Q.all([
Q.ninvoke(
this.db,
"get",
`SELECT id, title, intro, intro_audio AS introAudio,
intro_background_image AS introBackgroundImage,
default_audio AS defaultAudio,
default_background_image AS defaultBackgroundImage
FROM narrations WHERE id = ?`,
id
),
this._getPublicNarrationCharacters(id)
]).spread((narrationInfo, characters) => {
if (!narrationInfo) {
throw new Error("Cannot find narration " + id);
}
narrationInfo.intro = parseIntroText(narrationInfo.intro);
narrationInfo.characters = characters;
return narrationInfo;
});
}
getNarrationChapters(id, userOpts) {
const opts = Object.assign({ limit: -1 }, userOpts);
const limitClause = opts.limit > 0 ?
`LIMIT ${parseInt(opts.limit, 10)}` : "";
return Q.ninvoke(
this.db,
"all",
`SELECT id, title, published
FROM chapters
WHERE narration_id = ?
ORDER BY COALESCE(published, created) DESC
${ limitClause }`,
id
).then(chapters => {
if (chapters.length === 0) {
return [[], {}];
}
const chapterMap = {};
chapters.forEach(chapter => {
chapterMap[chapter.id] = chapter;
chapter.participants = [];
chapter.activeUsers = [];
chapter.numberMessages = 0;
});
return [chapters, chapterMap];
}).spread((chapters, chapterMap) => {
if (chapters.length === 0) {
return [];
}
const placeholders = chapters.map(_ => "?");
return Q.ninvoke(
this.db,
"all",
`SELECT chapter_id AS chapterId,
COUNT(*) AS numberMessages
FROM messages
WHERE chapter_id IN (${ placeholders.join(", ") })
GROUP BY chapter_id`,
chapters.map(f => f.id)
).then(numberMessagesPerChapter => {
numberMessagesPerChapter.forEach(numberAndChapter => {
chapterMap[numberAndChapter.chapterId].numberMessages =
numberAndChapter.numberMessages;
});
return Q.ninvoke(
this.db,
"all",
`SELECT DISTINCT chapter_id AS chapterId,
CH.id, CH.name, CH.avatar
FROM messages M
JOIN characters CH
ON M.sender_id = CH.id
WHERE chapter_id IN (${ placeholders.join(", ") })`,
chapters.map(f => f.id)
);
}).then(activeUsers => {
activeUsers.forEach(({ chapterId, name, avatar }) => {
chapterMap[chapterId].activeUsers.push({
id: id,
name: name,
avatar: avatar
});
});
return Q.ninvoke(
this.db,
"all",
`SELECT chapter_id AS chapterId,
CH.id, CH.name, CH.avatar
FROM chapter_participants CP
JOIN characters CH
ON CP.character_id = CH.id
WHERE chapter_id IN (${ placeholders.join(", ") })`,
chapters.map(f => f.id)
);
}).then(participants => {
participants.forEach(({ chapterId, id, name, avatar }) => {
chapterMap[chapterId].participants.push({
id: id,
name: name,
avatar: avatar
});
});
return chapters;
});
});
}
getNarrationOverview(userId, opts) {
const userOpts = Object.assign({ status: null }, opts);
let extraConditions = "";
const binds = [userId];
if (userOpts.status) {
extraConditions = " AND status = ?";
binds.push(userOpts.status);
}
return Q.ninvoke(
this.db,
"all",
`SELECT id, token, title, intro, status,
default_audio AS defaultAudio,
default_background_image AS defaultBackgroundImage,
COALESCE(notes, '') AS notes
FROM narrations
WHERE narrator_id = ?
${ extraConditions }
ORDER BY created DESC`,
binds
).then(rows => (
Q.all([
Q.all(rows.map(row => (
this.getNarrationChapters(row.id, { limit: 5 })
))),
Q.all(rows.map(row => this._getNarrationCharacters(row.id))),
Q.all(rows.map(row => this._getNarrationFiles(row.id))),
Q.all(rows.map(row => this._getNarrationStyles(row.id)))
]).spread((chapterLists, characterLists, fileLists, styleLists) => ({
narrations: chapterLists.map((chapters, i) => ({
narration: Object.assign(rows[i],
{characters: characterLists[i],
files: fileLists[i],
styles: styleLists[i],
intro: parseIntroText(rows[i].intro),
introUrl: `${config.publicAddress}/narrations/${rows[i].token}/intro`}),
chapters: chapters
}))
}))
));
}
_getNarrationStyles(narrationId) {
return Q.ninvoke(
this.db,
"all",
`SELECT title_font AS titleFont, title_font_size AS titleFontSize,
title_color AS titleColor, title_shadow_color AS titleShadowColor,
body_text_font AS bodyTextFont,
body_text_font_size AS bodyTextFontSize,
body_text_color AS bodyTextColor,
body_text_background_color AS bodyTextBackgroundColor,
separator_image AS separatorImage
FROM narration_styles
WHERE narration_id = ?`,
narrationId
).then(rows => (
rows.length ? rows[0] : {}
));
}
getCharacterOverview(userId, opts) {
const userOpts = Object.assign({ status: null }, opts);
let extraQuery = "";
let extraBinds = [];
if (userOpts.status === "active") {
const narrationGraceTime = new Date();
narrationGraceTime.setDate(narrationGraceTime.getDate() - 14);
extraQuery = "HAVING status = 'active' OR last_published > ?";
extraBinds = [narrationGraceTime];
}
return Q.ninvoke(
this.db,
"all",
`SELECT CHR.id, status,
COALESCE(MAX(published), NOW()) AS last_published
FROM narrations N
JOIN characters CHR ON CHR.narration_id = N.id
LEFT JOIN chapters C ON C.narration_id = N.id
WHERE player_id = ?
GROUP BY CHR.id
${extraQuery}
ORDER BY last_published DESC`,
[userId].concat(extraBinds)
).then(rows => (
Q.all(rows.map(row => this.getFullCharacterStats(row.id)))
));
}
deleteNarration(id) {
return Q.ninvoke(
this.db,
"run",
"SELECT id FROM characters WHERE narration_id = ?",
id
).then(characters => (
Q.all(characters.map(char => (
this.removeCharacter(char.id)
)))
)).then(() => (
Q.ninvoke(
this.db,
"run",
"DELETE FROM chapters WHERE narration_id = ?",
id
)
)).then(() => (
Q.ninvoke(
this.db,
"run",
"DELETE FROM narrations WHERE id = ?",
id
)
)).then(result => {
// Delete the files
const filesDir = path.join(config.files.path, id.toString());
fs.removeSync(filesDir);
// Return if there was a deleted narration in the above query
return result.affectedRows === 1;
});
}
deleteChapter(id) {
return Q.ninvoke(
this.db,
"run",
"DELETE FROM chapters WHERE id = ?",
id
).catch(err => true);
}
_insertParticipants(id, participants) {
let promise = Q(true);
participants.forEach(participant => {
promise = promise.then(() => {
return Q.ninvoke(
this.db,
"run",
`INSERT INTO chapter_participants (chapter_id, character_id)
VALUES (?, ?)`,
[id, participant.id]
);
});
});
return promise;
}
/**
* Creates a new chapter for the given narration, with the given
* properties. Properties have to include at least "text" (JSON in
* ProseMirror format) and "participants" (an array of ids for the
* characters in the chapter).
*/
createChapter(narrationId, chapterProps) {
if (!chapterProps.text) {
throw new Error("Cannot create a new chapter without text");
}
if (!chapterProps.participants) {
throw new Error("Cannot create a new chapter without participants");
}
return this.getNarration(narrationId).then(narration => {
const basicProps = {
backgroundImage: narration.defaultBackgroundImage,
audio: narration.defaultAudio
};
Object.keys(JSON_TO_DB).forEach(field => {
if (field in chapterProps) {
basicProps[field] = chapterProps[field];
}
});
basicProps.text = JSON.stringify(basicProps.text);
return this._insertChapter(narrationId,
basicProps,
chapterProps.participants);
});
}
_insertChapter(narrationId, basicProps, participants) {
const deferred = Q.defer();
const fields = Object.keys(basicProps).map(convertToDb),
fieldString = fields.join(", "),
placeholderString = fields.map(_ => "?").join(", "),
values = Object.keys(basicProps).map(f => (
f === "published" ?
mysqlTimestamp(basicProps[f]) : basicProps[f]
));
const self = this;
this.db.run(
`INSERT INTO chapters
(${ fieldString }, narration_id)
VALUES (${ placeholderString }, ?)`,
values.concat(narrationId),
function(err, result) {
if (err) {
deferred.reject(err);
return;
}
const newChapterId = result.insertId;
self._insertParticipants(newChapterId, participants).then(() => {
return self.getChapter(newChapterId, { includePrivateFields: true });
}).then(chapter => {
deferred.resolve(chapter);
}).catch(err => {
return self.deleteChapter(newChapterId).then(() => {
deferred.reject(err);
});
});
}
);
return deferred.promise;
}
getNarratorEmail(narrationId) {
return Q.ninvoke(
this.db,
"get",
`SELECT email
FROM narrations N
JOIN users U
ON N.narrator_id = U.id
WHERE N.id = ?`,
narrationId
).then(
narrationRow => narrationRow.email
);
}
getChapterParticipants(chapterId, userOpts) {
const opts = userOpts || {};
const extraFields = opts.includePrivateFields ?
", C.player_id, U.display_name AS displayName, C.token, C.novel_token AS novelToken, C.notes" : "";
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.name, C.avatar, C.description,
CASE WHEN C.player_id THEN TRUE ELSE FALSE END AS claimed
${ extraFields }
FROM characters C
JOIN chapter_participants CP ON C.id = CP.character_id
LEFT JOIN users U ON U.id = C.player_id
WHERE chapter_id = ?`,
chapterId
).then(participants => (
participants.map(participant => (
Object.assign(
participant,
{ description: JSON.parse(participant.description),
claimed: !!participant.claimed }
)
))
));
}
isCharacterParticipant(characterId, chapterId) {
return Q.ninvoke(
this.db,
"query",
`SELECT COUNT(*) AS cnt
FROM chapter_participants
WHERE character_id = ? AND chapter_id = ?`,
[characterId, chapterId]
).spread(rows => (
rows[0].cnt > 0
)).catch(err => (
false
));
}
getChapter(id, opts) {
return Q.ninvoke(
this.db,
"get",
`SELECT id, title, audio, narration_id as narrationId,
background_image AS backgroundImage,
main_text AS text, published
FROM chapters
WHERE id = ?`,
id
).then(chapterData => {
if (!chapterData) {
throw new Error("Cannot find chapter " + id);
}
chapterData.text = JSON.parse(chapterData.text.replace(/\r/g, ""));
return this.getChapterParticipants(id, opts).then(participants => {
chapterData.participants = participants;
return chapterData;
});
});
}
_updateChapterParticipants(id, newParticipantList) {
return this.getChapterParticipants(id).then(currentParticipantList => {
const newHash = {}, currentHash = {};
newParticipantList.forEach(newParticipant => {
newHash[newParticipant.id] = true;
});
currentParticipantList.forEach(currentParticipant => {
currentHash[currentParticipant.id] = true;
});
newParticipantList.forEach(newParticipant => {
if (!currentHash.hasOwnProperty(newParticipant.id)) {
this._addParticipant(id, newParticipant.id);
}
});
currentParticipantList.forEach(currentParticipant => {
if (!newHash.hasOwnProperty(currentParticipant.id)) {
this._removeParticipant(id, currentParticipant.id);
}
});
});
}
updateChapter(id, props) {
const participants = props.participants;
delete props.participants;
if ("text" in props) {
props.text = JSON.stringify(props.text);
}
let updatePromise;
if (Object.keys(props).length === 0) {
// No regular fields to update, avoid SQL error
updatePromise = Q(true);
} else {
const propNames = Object.keys(props).map(convertToDb),
propNameStrings = propNames.map(p => `${p} = ?`);
const propValues = Object.keys(props).map(n => (
n === "published" ? mysqlTimestamp(props[n]) : props[n]
));
updatePromise = Q.ninvoke(
this.db,
"run",
`UPDATE chapters SET ${ propNameStrings.join(", ") }
WHERE id = ?`,
propValues.concat(id)
);
}
return updatePromise.then(
() => this._updateChapterParticipants(id, participants)
).then(
() => this.getChapter(id, { includePrivateFields: true })
);
}
getCharacterInfo(characterToken, extraFields) {
extraFields = extraFields || [];
const extraFieldString = extraFields.length !== 0 ?
`, ${ extraFields.join(", ") }` :
"";
return Q.ninvoke(
this.db,
"get",
`SELECT id, name, token, notes${ extraFieldString }
FROM characters WHERE token = ?`,
characterToken
);
}
getCharacterInfoById(characterId, extraFields) {
extraFields = extraFields || [];
const extraFieldString = extraFields.length !== 0 ?
`, ${ extraFields.join(", ") }` :
"";
return Q.ninvoke(
this.db,
"get",
`SELECT id, name, token, notes, narration_id AS narrationId${ extraFieldString }
FROM characters WHERE id = ?`,
characterId
);
}
getCharacterInfoBulk(characterIds) {
if (!characterIds.length) {
return Q({});
}
const placeholders = characterIds.map(_ => "?");
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.name, U.email
FROM characters C
LEFT JOIN users U
ON C.player_id = U.id
WHERE C.id IN (${placeholders.join(', ')})`,
characterIds
).then(rows => {
const info = {};
rows.forEach(row => {
info[row.id] = { name: row.name, email: row.email };
});
return info;
});
}
getCharacterTokenById(characterId) {
return Q.ninvoke(
this.db,
"get",
"SELECT token FROM characters WHERE id = ?",
characterId
).then(
row => row.token
);
}
addCharacter(name, userId, narrationId) {
const deferred = Q.defer();
const newToken = generateToken();
const newNovelToken = generateToken();
return Q.ninvoke(
this.db,
"run",
`INSERT INTO characters (name, token, novel_token, player_id, narration_id)
VALUES (?, ?, ?, ?, ?)`,
[name, newToken, newNovelToken, userId, narrationId]
).then(() => (
this.getCharacterInfo(newToken)
));
}
_addParticipant(chapterId, characterId) {
return this.getChapter(chapterId).then(() => (
this.getChapterParticipants(chapterId)
)).then(participants => {
if (participants.some(p => p.id === characterId)) {
return participants;
}
return Q.ninvoke(
this.db,
"run",
`INSERT INTO chapter_participants (chapter_id, character_id)
VALUES (?, ?)`,
[chapterId, characterId]
);
});
}
_removeParticipant(chapterId, characterId) {
return Q.ninvoke(
this.db,
"run",
`DELETE FROM chapter_participants
WHERE chapter_id = ? AND character_id = ?`,
[chapterId, characterId]
);
}
/**
* Adds a media file to the given narration, specifying its
* filename and a temporary path where the file lives.
*/
addMediaFile(narrationId, filename, tmpPath, type) {
const filesDir = path.join(config.files.path, narrationId.toString());
const typeDir = type === "backgroundImages" ?
"background-images" : type;
const finalDir = path.join(filesDir, typeDir);
return getFinalFilename(finalDir, filename).then(finalPath => {
return Q.nfcall(fs.move, tmpPath, finalPath).then(() => ({
name: path.basename(finalPath),
type: type
}));
});
}
_formatMessageList(messages) {
if (messages.length === 0) {
return messages;
}
const messageIds = messages.map(m => m.id);
const placeholders = messageIds.map(_ => "?").join(", ");
return Q.ninvoke(
this.db,
"all",
`SELECT MD.message_id AS messageId,
MD.recipient_id AS recipientId,
C.name, C.avatar
FROM message_deliveries MD JOIN characters C
ON MD.recipient_id = C.id
WHERE message_id IN (${ placeholders })`,
messageIds
).then(deliveries => {
const deliveryMap = {};
deliveries.forEach(({ messageId, recipientId, name, avatar }) => {
deliveryMap[messageId] = deliveryMap[messageId] || [];
deliveryMap[messageId].push({ id: recipientId,
name: name,
avatar: avatar });
});
messages.forEach(message => {
message.recipients = deliveryMap[message.id];
});
return messages;
}).then(messages => {
const placeholders = messages.map(_ => "?");
return Q.ninvoke(
this.db,
"all",
`SELECT id, name, avatar FROM characters
WHERE id IN (${ placeholders })`,
messages.map(m => m.senderId)
).then(characters => {
const characterMap = {};
characters.forEach(c => {
characterMap[c.id] = {id: c.id,
name: c.name,
avatar: c.avatar};
});
messages.forEach(m => {
m.sender = characterMap[m.senderId];
delete m.senderId;
});
return messages;
});
});
}
getChapterMessages(chapterId, characterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT DISTINCT id, sender_id AS senderId, body, sent AS sentAt
FROM messages M LEFT JOIN message_deliveries MD
ON M.id = MD.message_id
WHERE M.chapter_id = ?
AND (recipient_id = ? OR sender_id = ?)
ORDER BY sent`,
[chapterId, characterId, characterId]
).then(
this._formatMessageList.bind(this)
);
}
getAllChapterMessages(chapterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT DISTINCT id, sender_id AS senderId, body, sent AS sentAt
FROM messages M LEFT JOIN message_deliveries MD
ON M.id = MD.message_id
WHERE M.chapter_id = ?
ORDER BY sent`,
[chapterId]
).then(
this._formatMessageList.bind(this)
);
}
addMessage(chapterId, senderId, text, recipients) {
const deferred = Q.defer();
const self = this;
this.db.run(
`INSERT INTO messages (chapter_id, sender_id, body)
VALUES (?, ?, ?)`,
[chapterId, senderId, text],
function(err, result) {
if (err) {
deferred.reject(err);
return;
}
// Message without recipients is only for the narrator
// (as the narrator is a "user", not a "character", it
// cannot be in the recipient list, and instead is an
// implicit recipient of all messages).
if (!recipients.length) {
deferred.resolve({});
return;
}
const messageId = result.insertId;
const valueQueryPart =
recipients.map(() => "(?, ?)").join(", ");
const queryValues = recipients.reduce((acc, mr) => (
acc.concat(messageId, mr)
), []);
Q.ninvoke(
self.db,
"run",
`INSERT INTO message_deliveries
(message_id, recipient_id) VALUES ${ valueQueryPart }`,
queryValues
).then(() => {
deferred.resolve({});
}).catch(err => {
deferred.reject(err);
});
}
);
return deferred.promise;
}
getActiveChapter(characterId) {
return Q.ninvoke(
this.db,
"get",
`SELECT CHPT.id, CHPT.title, CHPT.published
FROM chapters CHPT
JOIN characters CHR
ON CHPT.narration_id = CHR.narration_id
JOIN chapter_participants CP
ON (CP.chapter_id = CHPT.id AND
CP.character_id = CHR.id)
WHERE CHR.id = ? AND published IS NOT NULL
ORDER BY published DESC
LIMIT 1`,
characterId
);
}
saveCharacterNotes(characterId, newNotes) {
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET notes = ? WHERE id = ?`,
[newNotes, characterId]
);
}
getChapterLastReactions(chapterId) {
return Q.ninvoke(
this.db,
"get",
`SELECT published, narration_id AS narrationId
FROM chapters
WHERE id = ?`,
chapterId
).then(row => (
this.getNarrationLastReactions(row.narrationId, row.published)
));
}
getNarrationLastReactions(narrationId, beforeDate) {
const binds = [narrationId];
let extraWhereClause = "";
if (beforeDate) {
extraWhereClause += "AND published < ?";
binds.push(beforeDate);
}
binds.push(narrationId);
return Q.ninvoke(
this.db,
"all",
`SELECT CHPT.id, CHPT.title,
CHPT.main_text AS text
FROM chapters CHPT
JOIN characters CHR
ON CHPT.narration_id = CHR.narration_id
JOIN (SELECT MAX(CHAP.published) AS published, character_id
FROM chapter_participants CP
JOIN chapters CHAP
ON CP.chapter_id = CHAP.id
WHERE narration_id = ?
${ extraWhereClause }
GROUP BY character_id) AS reaction_per_character
ON reaction_per_character.published = CHPT.published
AND reaction_per_character.character_id = CHR.id
WHERE CHR.narration_id = ?
AND CHPT.published IS NOT NULL
GROUP BY CHPT.id`,
binds
).then(lastChapters => {
const chapterIds = lastChapters.map(c => c.id);
return Q.all(
chapterIds.map(id => this.getAllChapterMessages(id))
).then(lastChapterMessages => {
lastChapterMessages.forEach((messages, i) => {
lastChapters[i].messages = messages;
});
return Q.all(
chapterIds.map(id => this.getChapterParticipants(id))
);
}).then(lastChapterParticipants => {
lastChapterParticipants.forEach((participants, i) => {
lastChapters[i].participants = participants;
});
return lastChapters;
});
});
}
getCharacterChaptersBasic(characterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.title
FROM chapters C
JOIN chapter_participants CP
ON C.id = CP.chapter_id
WHERE published IS NOT NULL
AND CP.character_id = ?`,
characterId
);
}
getCharacterChapters(characterId) {
return Q.ninvoke(
this.db,
"all",
`SELECT C.id, C.title, C.main_text AS text,
C.audio, C.background_image AS backgroundImage
FROM chapters C
JOIN chapter_participants CP
ON C.id = CP.chapter_id
WHERE published IS NOT NULL
AND CP.character_id = ?`,
characterId
).then(chapters => {
chapters.forEach(c => {
c.text = JSON.parse(c.text.replace(/\r/g, ""));
});
return chapters;
});
}
getFullCharacterStats(characterId) {
return Q.all([
Q.ninvoke(
this.db,
"get",
`SELECT C.id, C.name, C.token, C.avatar, C.description,
C.backstory, C.novel_token AS novelToken,
U.display_name AS displayName,
N.id AS narrationId, N.title AS narrationTitle,
N.status
FROM characters C
JOIN narrations N
ON C.narration_id = N.id
LEFT JOIN users U
ON C.player_id = U.id
WHERE C.id = ?`,
characterId
),
this.getCharacterChaptersBasic(characterId)
]).spread((basicStats, chapters) => {
return this._getPublicNarrationCharacters(basicStats.narrationId).then(characters => ({
id: basicStats.id,
token: basicStats.token,
displayName: basicStats.displayName,
name: basicStats.name,
avatar: basicStats.avatar,
novelToken: basicStats.novelToken,
description: JSON.parse(basicStats.description),
backstory: JSON.parse(basicStats.backstory),
narration: {
id: basicStats.narrationId,
title: basicStats.narrationTitle,
status: basicStats.status,
chapters: chapters,
characters: characters.filter(character => (
character.id !== basicStats.id
))
}
}));
});
}
resetCharacterToken(characterId) {
const newToken = generateToken();
return Q.ninvoke(
this.db,
"run",
'UPDATE characters SET token = ? WHERE id = ?',
[newToken, characterId]
).then(() => (
this.getCharacterInfo(newToken)
));
}
updateCharacter(characterId, props) {
const propNames = Object.keys(props).map(convertToDb),
propNameStrings = propNames.map(p => `${p} = ?`);
const propValues = Object.keys(props).map(p => (
(["description", "backstory"].indexOf(p) !== -1) ?
((typeof props[p] === "string") ?
props[p] : JSON.stringify(props[p])) :
props[p]
));
if (!propValues.length) {
return this.getFullCharacterStats(characterId);
}
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET ${ propNameStrings.join(", ") } WHERE id = ?`,
propValues.concat(characterId)
).then(
() => this.getFullCharacterStats(characterId)
);
}
updateCharacterAvatar(characterId, filename, tmpPath) {
return Q.ninvoke(
this.db,
"query",
`SELECT narration_id AS narrationId FROM characters WHERE id = ?`,
characterId
).spread(results => {
const narrationId = results[0].narrationId;
const filesDir = path.join(config.files.path, narrationId.toString());
const fileExtension = path.extname(filename);
const finalBasename = `${ characterId }${ fileExtension }`;
const finalPath = path.join(filesDir, "avatars", finalBasename);
return Q.nfcall(fs.move, tmpPath, finalPath, {clobber: true}).then(() => {
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET avatar = ? WHERE id = ?`,
[finalBasename, characterId]
);
}).then(() => (
this.getFullCharacterStats(characterId)
));
});
}
getNovelInfo(novelToken) {
return Q.ninvoke(
this.db,
"query",
`SELECT C.id AS characterId,
C.narration_id AS narrationId
FROM characters C
WHERE C.novel_token = ?`,
novelToken
).spread(results => {
if (results.length !== 1) {
throw new Error(
`Could not find (a single) novel with token ${novelToken}`
);
}
return results[0];
});
}
searchNarration(narrationId, searchTerms) {
return Q.ninvoke(
this.db,
"query",
`SELECT id, title
FROM chapters
WHERE narration_id = ?
AND (main_text LIKE ? OR title LIKE ?)
AND published IS NOT NULL`,
[narrationId, `%${searchTerms}%`, `%${searchTerms}%`]
).spread(results => (
results.map(result => ({
id: result.id,
title: result.title
}))
));
}
claimCharacter(characterId, userId) {
return Q.ninvoke(
this.db,
"query",
`SELECT id, name, narration_id, player_id
FROM characters
WHERE player_id = ?
AND narration_id = (SELECT narration_id
FROM characters
WHERE id = ?)`,
[userId, characterId]
).spread(results => {
// Don't allow claiming more than one character per player
// in the same narration
if (results.length > 0) {
throw new Error(
"Cannot claim more than one character in the same " +
"narration"
);
}
// Yes, possibility of race condition here, but... MySQL
return Q.ninvoke(
this.db,
"run",
`UPDATE characters SET player_id = ?
WHERE id = ?
AND player_id IS NULL`,
[userId, characterId]
);
}).then(() => (
Q.ninvoke(
this.db,
"query",
`SELECT player_id FROM characters WHERE id = ?`,
[characterId]
).spread(results => {
if (results[0].player_id === userId) {
return results[0].player_id;
} else {
throw new Error(
`Could not claim character ${characterId} ` +
`with user id ${userId} (claimed by ` +
`${results[0].player_id})`
);
}
})
));
}
unclaimCharacter(characterId) {
return Q.ninvoke(
this.db,
"query",
`UPDATE characters
SET player_id = NULL
WHERE id = ?`,
[characterId]
).then(() => (
this.resetCharacterToken(characterId)
));
}
removeCharacter(characterId) {
return Q.ninvoke(
this.db,
"run",
`DELETE FROM messages WHERE sender_id = ?`,
[characterId]
).then(() => (
Q.ninvoke(
this.db,
"run",
`DELETE FROM characters WHERE id = ?`,
[characterId]
)
)).then(result => (
result.affectedRows === 1
));
}
}
export default NarrowsStore;
| Ignore non-existent style file when trying to remove it
| src/backend/NarrowsStore.js | Ignore non-existent style file when trying to remove it | <ide><path>rc/backend/NarrowsStore.js
<ide> "DELETE FROM narration_styles WHERE narration_id = ?",
<ide> narrationId
<ide> ).then(() => {
<del> fs.unlinkSync(cssFilePath);
<add> fs.removeSync(cssFilePath);
<ide> });
<ide> } else {
<ide> return Q.ninvoke( |
|
Java | apache-2.0 | 106b80beafa008f950ff3958b91658d29aa09d61 | 0 | webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno | /*******************************************************************************
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.clarin.webanno.webapp.security.preauth;
import java.io.File;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.ResourcePropertySource;
public class WebAnnoApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
private static final String PROFILE_PREAUTH = "auto-mode-preauth";
private static final String PROFILE_DATABASE = "auto-mode-builtin";
private static final String PROP_AUTH_MODE = "auth.mode";
private static final String PROP_USER_HOME = "user.home";
private static final String PROP_WEBANNO_HOME = "webanno.home";
private static final String SETTINGS_FILE = "settings.properties";
private static final String WEBANNO_USER_HOME_SUBDIR = ".webanno";
private static final String AUTH_MODE_PREAUTH = "preauth";
private final Log log = LogFactory.getLog(getClass());
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext)
{
ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();
String appHome = System.getProperty(PROP_WEBANNO_HOME);
String userHome = System.getProperty(PROP_USER_HOME);
// Locate settings, first in webanno.home, then in user home
File settings = null;
if (appHome != null) {
settings = new File(appHome, SETTINGS_FILE);
}
else if (userHome != null) {
settings = new File(userHome + "/" + WEBANNO_USER_HOME_SUBDIR, SETTINGS_FILE);
}
// If settings were found, add them to the environment
if (settings != null && settings.exists()) {
log.info("Settings: " + settings);
try {
aEnvironment.getPropertySources().addFirst(
new ResourcePropertySource(new FileSystemResource(settings)));
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
// Activate bean profile depending on authentication mode
if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(PROP_AUTH_MODE))) {
aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
log.info("Authentication: pre-auth");
}
else {
aEnvironment.setActiveProfiles(PROFILE_DATABASE);
log.info("Authentication: database");
}
}
} | webanno.webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/security/preauth/WebAnnoApplicationContextInitializer.java | /*******************************************************************************
* Copyright 2014
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* 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 de.tudarmstadt.ukp.clarin.webanno.webapp.security.preauth;
import java.io.File;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.ResourcePropertySource;
public class WebAnnoApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
private static final String PROFILE_PREAUTH = "auto-mode-preauth";
private static final String PROFILE_DATABASE = "auto-mode-builtin";
private static final String PROP_AUTH_MODE = "auth.mode";
private static final String PROP_USER_HOME = "user.home";
private static final String PROP_WEBANNO_HOME = "webanno.home";
private static final String SETTINGS_FILE = "settings.properties";
private static final String WEBANNO_USER_HOME_SUBDIR = ".webanno";
private static final String AUTH_MODE_PREAUTH = "preauth";
private final Log log = LogFactory.getLog(getClass());
@Override
public void initialize(ConfigurableApplicationContext aApplicationContext)
{
ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment();
String appHome = System.getProperty(PROP_WEBANNO_HOME);
String userHome = System.getProperty(PROP_USER_HOME);
// Locate settings, first in webanno.home, then in user home
File settings = null;
if (appHome != null) {
settings = new File(appHome, SETTINGS_FILE);
}
else if (userHome != null) {
settings = new File(userHome + "/" + WEBANNO_USER_HOME_SUBDIR, SETTINGS_FILE);
}
// If settings were found, add them to the environment
if (settings != null && settings.exists()) {
log.info("Settings: " + settings);
try {
aEnvironment.getPropertySources().addFirst(
new ResourcePropertySource(new FileSystemResource(settings)));
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
// Activate bean profile depending on authentication mode
if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(PROP_AUTH_MODE))) {
aEnvironment.setActiveProfiles(PROFILE_PREAUTH);
log.info("Authentication: pre-auth");
}
else {
aEnvironment.setActiveProfiles(PROFILE_DATABASE);
log.info("Authentication: database");
}
aApplicationContext.refresh();
}
} | #1132 - Allow switching between built-in authentication and pre-authentication
- Refreshing the context again should not be necessary, the ContextInitializers are called before the context is refreshed initially.
| webanno.webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/security/preauth/WebAnnoApplicationContextInitializer.java | #1132 - Allow switching between built-in authentication and pre-authentication - Refreshing the context again should not be necessary, the ContextInitializers are called before the context is refreshed initially. | <ide><path>ebanno.webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/security/preauth/WebAnnoApplicationContextInitializer.java
<ide> aEnvironment.setActiveProfiles(PROFILE_DATABASE);
<ide> log.info("Authentication: database");
<ide> }
<del>
<del> aApplicationContext.refresh();
<ide> }
<ide> } |
|
Java | apache-2.0 | 7bdcafadaeb69436ddee5999661ff5acd06f8add | 0 | Teradata/kylo,Teradata/kylo,Teradata/kylo,Teradata/kylo,Teradata/kylo | package com.thinkbiganalytics.nifi.v2.core.metadata;
import com.fasterxml.jackson.core.type.TypeReference;
/*-
* #%L
* thinkbig-nifi-core-service
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.thinkbiganalytics.metadata.rest.client.MetadataClient;
import com.thinkbiganalytics.metadata.rest.model.feed.InitializationStatus;
import com.thinkbiganalytics.nifi.core.api.metadata.ActiveWaterMarksCancelledException;
import com.thinkbiganalytics.metadata.rest.model.feed.reindex.FeedDataHistoryReindexParams;
import com.thinkbiganalytics.metadata.rest.model.feed.reindex.HistoryReindexingStatus;
import com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder;
import com.thinkbiganalytics.nifi.core.api.metadata.WaterMarkActiveException;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.exception.ProcessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.util.HashSet;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nonnull;
public class MetadataClientRecorder implements MetadataRecorder {
private static final Logger log = LoggerFactory.getLogger(MetadataClientRecorder.class);
// private static final int FEED_INIT_STATUS_EXPIRE_SEC = 60;
private static final int FEED_INIT_STATUS_CACHE_SIZE = 1024;
private static final String CURRENT_WATER_MARKS_ATTR = "activeWaterMarks";
private static final TypeReference<NavigableMap<String, WaterMarkParam>> WM_MAP_TYPE = new TypeReference<NavigableMap<String, WaterMarkParam>>() { };
private static final ObjectReader WATER_MARKS_READER = new ObjectMapper().reader().forType(WM_MAP_TYPE);
private static final ObjectWriter WATER_MARKS_WRITER = new ObjectMapper().writer().forType(WM_MAP_TYPE);
private MetadataClient client;
private NavigableMap<String, Long> activeWaterMarks = new ConcurrentSkipListMap<>();
private volatile Cache<String, Optional<InitializationStatus>> initStatusCache;
/**
* constructor creates a MetadataClientRecorder with the default URI constant
*/
public MetadataClientRecorder() {
this(URI.create("http://localhost:8420/api/v1/metadata"));
}
/**
* constructor creates a MetadataClientRecorder with the URI provided
*
* @param baseUri the REST endpoint of the Metadata recorder
*/
public MetadataClientRecorder(URI baseUri) {
this(new MetadataClient(baseUri));
}
/**
* constructor creates a MetadataClientProvider with the required {@link MetadataClientRecorder}
*
* @param client the MetadataClient will be used to connect with the Metadata store
*/
public MetadataClientRecorder(MetadataClient client) {
this.client = client;
getInitStatusCache();
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#loadWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public FlowFile loadWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String parameterName, String initialValue) throws WaterMarkActiveException {
long timestamp = recordActiveWaterMark(feedId, waterMarkName);
try {
String value = getHighWaterMarkValue(feedId, waterMarkName).orElse(initialValue);
FlowFile resultFF = addToCurrentWaterMarksAttr(session, ff, waterMarkName, parameterName, timestamp);
resultFF = session.putAttribute(resultFF, parameterName, value);
return session.putAttribute(resultFF, originalValueParameterName(parameterName), value);
} catch (Exception e) {
cancelActiveWaterMark(feedId, waterMarkName);
throw e;
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#cancelWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public boolean cancelWaterMark(String feedId, String waterMarkName) {
return cancelActiveWaterMark(feedId, waterMarkName);
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#cancelAndLoadWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public FlowFile cancelAndLoadWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String parameterName, String initialValue) throws WaterMarkActiveException {
cancelActiveWaterMark(feedId, waterMarkName);
return loadWaterMark(session, ff, feedId, waterMarkName, parameterName, initialValue);
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#recordWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String, java.io.Serializable)
*/
@Override
public FlowFile recordWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String parameterName, String newValue) {
Map<String, WaterMarkParam> actives = getCurrentWaterMarksAttr(ff);
if (actives.containsKey(waterMarkName)) {
return session.putAttribute(ff, parameterName, newValue);
} else {
throw new IllegalStateException("No active high-water mark named \"" + waterMarkName + "\"");
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#commitWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public FlowFile commitWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName) {
FlowFile resultFF = ff;
Map<String, WaterMarkParam> ffWaterMarks = getCurrentWaterMarksAttr(ff);
WaterMarkParam param = ffWaterMarks.get(waterMarkName);
Long activeTimestamp = getActiveWaterMarkTimestamp(feedId, waterMarkName);
if (param == null) {
log.error("Received request to commit a water mark that does not exist in the flowfile: {}", waterMarkName);
return resultFF;
} else if (activeTimestamp == null) {
log.warn("Received request to commit a water mark that is not active: {}", waterMarkName);
return resultFF;
} else if (param.timestamp != activeTimestamp) {
// If the water mark timestamp does not match the one recorded as an active water mark this means
// this flowfile's water mark has been canceled and another flow file should be considered the active one.
// So this water mark value has been superseded and its value should not be committed and a canceled exception thrown.
log.info("Received request to commit a water mark version that is no longer active: {}/{}", waterMarkName, param.timestamp);
throw new ActiveWaterMarksCancelledException(feedId, waterMarkName);
}
try {
String value = resultFF.getAttribute(param.name);
updateHighWaterMarkValue(feedId, waterMarkName, value);
} finally {
releaseActiveWaterMark(feedId, waterMarkName, activeTimestamp);
resultFF = removeFromCurrentWaterMarksAttr(session, resultFF, waterMarkName, param.name);
}
return resultFF;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#commitAllWaterMarks(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String)
*/
@Override
public FlowFile commitAllWaterMarks(ProcessSession session, FlowFile ff, String feedId) {
FlowFile resultFF = ff;
Set<String> cancelledWaterMarks = new HashSet<>();
// TODO do more efficiently
for (String waterMarkName : new HashSet<String>(getCurrentWaterMarksAttr(ff).keySet())) {
try {
resultFF = commitWaterMark(session, resultFF, feedId, waterMarkName);
} catch (ActiveWaterMarksCancelledException e) {
cancelledWaterMarks.addAll(e.getWaterMarkNames());
}
}
if (cancelledWaterMarks.size() > 0) {
throw new ActiveWaterMarksCancelledException(feedId, cancelledWaterMarks);
} else {
return resultFF;
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#releaseWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public FlowFile releaseWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName) {
FlowFile resultFF = ff;
Map<String, WaterMarkParam> ffWaterMarks = getCurrentWaterMarksAttr(ff);
WaterMarkParam param = ffWaterMarks.get(waterMarkName);
try {
if (param != null) {
// Update the flowfile with the modified set of active water marks.
removeFromCurrentWaterMarksAttr(session, resultFF, waterMarkName, param.name);
resetWaterMarkParam(session, resultFF, feedId, waterMarkName, param.name);
} else {
log.warn("Received request to release a water mark not found in the flow file: {}", waterMarkName);
}
} finally {
// Even if water mark resetting fails we should always release the water mark.
Long activeTimestamp = getActiveWaterMarkTimestamp(feedId, waterMarkName);
if (activeTimestamp != null) {
if (param == null || param.timestamp == activeTimestamp) {
releaseActiveWaterMark(feedId, waterMarkName, activeTimestamp);
} else if (param.timestamp != activeTimestamp) {
// If the water mark timestamp does not match the one recorded as an active water mark this means
// this flowfile's water mark has been canceled and another flow file should be considered the active one.
// In this case this water mark value has been superseded and no release should occur.
log.info("Received request to release a water mark version that is no longer active: {}", waterMarkName);
}
} else {
// The water mark is not one recognize as an active one.
log.warn("Received request to release a non-active water mark: {}", waterMarkName);
}
}
return resultFF;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#releaseAllWaterMarks(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String)
*/
@Override
public FlowFile releaseAllWaterMarks(ProcessSession session, FlowFile ff, String feedId) {
FlowFile resultFF = ff;
for (String waterMarkName : new HashSet<String>(getCurrentWaterMarksAttr(ff).keySet())) {
resultFF = releaseWaterMark(session, resultFF, feedId, waterMarkName);
}
return resultFF;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#getFeedInitializationStatus(java.lang.String)
*/
@Override
public Optional<InitializationStatus> getInitializationStatus(String feedId) {
try {
return getInitStatusCache().get(feedId, () -> getFeedInitStatus(feedId));
} catch (ExecutionException e) {
log.error("Failed to obtain initialization status feed: {}", feedId, e);
throw new ProcessException("Failed to obtain initialization status feed: " + feedId, e.getCause());
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#startFeedInitialization(java.lang.String)
*/
@Override
public InitializationStatus startFeedInitialization(String feedId) {
InitializationStatus status = new InitializationStatus(InitializationStatus.State.IN_PROGRESS);
try {
this.client.updateCurrentInitStatus(feedId, status);
getInitStatusCache().put(feedId, Optional.of(status));
return status;
} catch (Exception e) {
log.error("Failed to update metadata with feed initialization in-progress status: {}, feed: {}", status.getState(), feedId, e);
getInitStatusCache().invalidate(feedId);
throw new ProcessException("Failed to update metadata with feed initialization in-progress status: " + status + ", feed: " + feedId, e);
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#completeFeedInitialization(java.lang.String)
*/
@Override
public InitializationStatus completeFeedInitialization(String feedId) {
InitializationStatus status = new InitializationStatus(InitializationStatus.State.SUCCESS);
try {
this.client.updateCurrentInitStatus(feedId, status);
getInitStatusCache().put(feedId, Optional.of(status));
return status;
} catch (Exception e) {
log.error("Failed to update metadata with feed initialization completion status: {}, feed: {}", status.getState(), feedId, e);
getInitStatusCache().invalidate(feedId);
throw new ProcessException("Failed to update metadata with feed initialization completion status: " + status + ", feed: " + feedId, e);
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#failFeedInitialization(java.lang.String)
*/
@Override
public InitializationStatus failFeedInitialization(String feedId, boolean isReinitialize) {
InitializationStatus.State state = isReinitialize ? InitializationStatus.State.REINITIALIZE_FAILED : InitializationStatus.State.FAILED;
InitializationStatus status = new InitializationStatus(state);
try {
this.client.updateCurrentInitStatus(feedId, status);
getInitStatusCache().put(feedId, Optional.of(status));
return status;
} catch (Exception e) {
log.error("Failed to update feed initialization failed status: {}, feed: {}", status.getState(), feedId);
getInitStatusCache().invalidate(feedId);
return status;
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#initializationStatusChanged(java.lang.String, com.thinkbiganalytics.metadata.rest.model.feed.InitializationStatus)
*/
@Override
public void initializationStatusChanged(String feedId, InitializationStatus status) {
getInitStatusCache().invalidate(feedId);
}
@Override
public void updateFeedStatus(ProcessSession session, FlowFile ff, String statusMsg) {
// TODO Auto-generated method stub
}
@Override
public FeedDataHistoryReindexParams updateFeedHistoryReindexing(@Nonnull String feedId, @Nonnull HistoryReindexingStatus historyReindexingStatus) {
return (this.client.updateFeedHistoryReindexing(feedId, historyReindexingStatus));
}
private Optional<InitializationStatus> getFeedInitStatus(String feedId) {
return Optional.ofNullable(this.client.getCurrentInitStatus(feedId));
}
private Cache<String, Optional<InitializationStatus>> getInitStatusCache() {
Cache<String, Optional<InitializationStatus>> cache = this.initStatusCache;
if (cache == null) {
synchronized (this) {
cache = this.initStatusCache;
if (cache == null) {
this.initStatusCache = cache = CacheBuilder.newBuilder()
// .expireAfterWrite(FEED_INIT_STATUS_EXPIRE_SEC, TimeUnit.SECONDS)
.maximumSize(FEED_INIT_STATUS_CACHE_SIZE)
.build();
}
}
}
return cache;
}
private String toWaterMarksKey(String feedId) {
return feedId + ".~";
}
private String toWaterMarkKey(String feedId, String waterMarkName) {
return feedId + "." + waterMarkName;
}
private Long getActiveWaterMarkTimestamp(String feedId, String waterMarkName) {
return this.activeWaterMarks.get(toWaterMarkKey(feedId, waterMarkName));
}
private Map<String, Long> getActiveWaterMarks(String feedId, String waterMarkName) {
return this.activeWaterMarks.subMap(feedId, toWaterMarksKey(feedId));
}
private boolean cancelActiveWaterMark(String feedId, String waterMarkName) {
return this.activeWaterMarks.remove(toWaterMarkKey(feedId, waterMarkName)) == null;
}
private long recordActiveWaterMark(String feedId, String waterMarkName) throws WaterMarkActiveException {
long newTimestamp = System.currentTimeMillis();
long timestamp = this.activeWaterMarks.computeIfAbsent(toWaterMarkKey(feedId, waterMarkName), k -> newTimestamp);
if (timestamp != newTimestamp) {
throw new WaterMarkActiveException(waterMarkName);
} else {
return newTimestamp;
}
}
private boolean releaseActiveWaterMark(String feedId, String waterMarkName, long expectedTimestamp) {
long timestamp = this.activeWaterMarks.remove(toWaterMarkKey(feedId, waterMarkName));
return expectedTimestamp == timestamp;
}
private NavigableMap<String, WaterMarkParam> getCurrentWaterMarksAttr(FlowFile ff) {
try {
String activeStr = ff.getAttribute(CURRENT_WATER_MARKS_ATTR);
if (activeStr == null) {
return new TreeMap<>();
} else {
return WATER_MARKS_READER.readValue(activeStr);
}
} catch (Exception e) {
// Should never happen.
throw new IllegalStateException(e);
}
}
private FlowFile setCurrentWaterMarksAttr(ProcessSession session, FlowFile ff, NavigableMap<String, WaterMarkParam> actives) {
try {
return session.putAttribute(ff, CURRENT_WATER_MARKS_ATTR, WATER_MARKS_WRITER.writeValueAsString(actives));
} catch (Exception e) {
// Should never happen.
throw new IllegalStateException(e);
}
}
private FlowFile resetWaterMarkParam(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String paramName) {
// Update the flowfile with the original value for the water mark parameter.
String value = getHighWaterMarkValue(feedId, waterMarkName).orElse(ff.getAttribute(originalValueParameterName(paramName)));
if (value != null) {
return session.putAttribute(ff, paramName, value);
} else {
log.error("Failed to reset water mark - original value not found in flowfile for water mark: {}", waterMarkName);
throw new IllegalStateException("Failed to reset water mark - original value not found in flowfile for water mark: " + waterMarkName);
}
}
private FlowFile addToCurrentWaterMarksAttr(ProcessSession session, FlowFile ff, String waterMarkName, String parameterName, long timestamp) {
NavigableMap<String, WaterMarkParam> actives = getCurrentWaterMarksAttr(ff);
actives.put(waterMarkName, new WaterMarkParam(timestamp, parameterName));
return setCurrentWaterMarksAttr(session, ff, actives);
}
private FlowFile removeFromCurrentWaterMarksAttr(ProcessSession session, FlowFile ff, String waterMarkName, String parameterName) {
NavigableMap<String, WaterMarkParam> actives = getCurrentWaterMarksAttr(ff);
actives.remove(waterMarkName);
return setCurrentWaterMarksAttr(session, ff, actives);
}
private Optional<String> getHighWaterMarkValue(String feedId, String waterMarkName) {
return this.client.getHighWaterMarkValue(feedId, waterMarkName);
}
private void updateHighWaterMarkValue(String feedId, String waterMarkName, String value) {
this.client.updateHighWaterMarkValue(feedId, waterMarkName, value);
}
private String originalValueParameterName(String parameterName) {
return parameterName + ".original";
}
public static class WaterMarkParam {
private long timestamp;
private String name;
public WaterMarkParam() {
super();
}
public WaterMarkParam(long timestamp, String value) {
this.timestamp = timestamp;
this.name = value;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| integrations/nifi/nifi-nar-bundles/nifi-standard-services/nifi-core-service-bundle/nifi-core-service/src/main/java/com/thinkbiganalytics/nifi/v2/core/metadata/MetadataClientRecorder.java | package com.thinkbiganalytics.nifi.v2.core.metadata;
import com.fasterxml.jackson.core.type.TypeReference;
/*-
* #%L
* thinkbig-nifi-core-service
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.thinkbiganalytics.metadata.rest.client.MetadataClient;
import com.thinkbiganalytics.metadata.rest.model.feed.InitializationStatus;
import com.thinkbiganalytics.nifi.core.api.metadata.ActiveWaterMarksCancelledException;
import com.thinkbiganalytics.metadata.rest.model.feed.reindex.FeedDataHistoryReindexParams;
import com.thinkbiganalytics.metadata.rest.model.feed.reindex.HistoryReindexingStatus;
import com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder;
import com.thinkbiganalytics.nifi.core.api.metadata.WaterMarkActiveException;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.exception.ProcessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.util.HashSet;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nonnull;
public class MetadataClientRecorder implements MetadataRecorder {
private static final Logger log = LoggerFactory.getLogger(MetadataClientRecorder.class);
// private static final int FEED_INIT_STATUS_EXPIRE_SEC = 60;
private static final int FEED_INIT_STATUS_CACHE_SIZE = 1024;
private static final String CURRENT_WATER_MARKS_ATTR = "activeWaterMarks";
private static final TypeReference<NavigableMap<String, WaterMarkParam>> WM_MAP_TYPE = new TypeReference<NavigableMap<String, WaterMarkParam>>() { };
private static final ObjectReader WATER_MARKS_READER = new ObjectMapper().reader().forType(WM_MAP_TYPE);
private static final ObjectWriter WATER_MARKS_WRITER = new ObjectMapper().writer().forType(WM_MAP_TYPE);
private MetadataClient client;
private NavigableMap<String, Long> activeWaterMarks = new ConcurrentSkipListMap<>();
private volatile Cache<String, Optional<InitializationStatus>> initStatusCache;
/**
* constructor creates a MetadataClientRecorder with the default URI constant
*/
public MetadataClientRecorder() {
this(URI.create("http://localhost:8420/api/v1/metadata"));
}
/**
* constructor creates a MetadataClientRecorder with the URI provided
*
* @param baseUri the REST endpoint of the Metadata recorder
*/
public MetadataClientRecorder(URI baseUri) {
this(new MetadataClient(baseUri));
}
/**
* constructor creates a MetadataClientProvider with the required {@link MetadataClientRecorder}
*
* @param client the MetadataClient will be used to connect with the Metadata store
*/
public MetadataClientRecorder(MetadataClient client) {
this.client = client;
getInitStatusCache();
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#loadWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public FlowFile loadWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String parameterName, String initialValue) throws WaterMarkActiveException {
long timestamp = recordActiveWaterMark(feedId, waterMarkName);
String value = getHighWaterMarkValue(feedId, waterMarkName).orElse(initialValue);
FlowFile resultFF = addToCurrentWaterMarksAttr(session, ff, waterMarkName, parameterName, timestamp);
resultFF = session.putAttribute(resultFF, parameterName, value);
return session.putAttribute(resultFF, originalValueParameterName(parameterName), value);
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#cancelWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public boolean cancelWaterMark(String feedId, String waterMarkName) {
return cancelActiveWaterMark(feedId, waterMarkName);
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#cancelAndLoadWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public FlowFile cancelAndLoadWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String parameterName, String initialValue) throws WaterMarkActiveException {
cancelActiveWaterMark(feedId, waterMarkName);
return loadWaterMark(session, ff, feedId, waterMarkName, parameterName, initialValue);
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#recordWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String, java.io.Serializable)
*/
@Override
public FlowFile recordWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String parameterName, String newValue) {
Map<String, WaterMarkParam> actives = getCurrentWaterMarksAttr(ff);
if (actives.containsKey(waterMarkName)) {
return session.putAttribute(ff, parameterName, newValue);
} else {
throw new IllegalStateException("No active high-water mark named \"" + waterMarkName + "\"");
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#commitWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public FlowFile commitWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName) {
FlowFile resultFF = ff;
Map<String, WaterMarkParam> ffWaterMarks = getCurrentWaterMarksAttr(ff);
WaterMarkParam param = ffWaterMarks.get(waterMarkName);
Long activeTimestamp = getActiveWaterMarkTimestamp(feedId, waterMarkName);
if (param == null) {
log.error("Received request to commit a water mark that does not exist in the flowfile: {}", waterMarkName);
return resultFF;
} else if (activeTimestamp == null) {
log.warn("Received request to commit a water mark that is not active: {}", waterMarkName);
return resultFF;
} else if (param.timestamp != activeTimestamp) {
// If the water mark timestamp does not match the one recorded as an active water mark this means
// this flowfile's water mark has been canceled and another flow file should be considered the active one.
// So this water mark value has been superseded and its value should not be committed and a canceled exception thrown.
log.info("Received request to commit a water mark version that is no longer active: {}/{}", waterMarkName, param.timestamp);
throw new ActiveWaterMarksCancelledException(feedId, waterMarkName);
}
try {
String value = resultFF.getAttribute(param.name);
updateHighWaterMarkValue(feedId, waterMarkName, value);
} finally {
releaseActiveWaterMark(feedId, waterMarkName, activeTimestamp);
resultFF = removeFromCurrentWaterMarksAttr(session, resultFF, waterMarkName, param.name);
}
return resultFF;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#commitAllWaterMarks(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String)
*/
@Override
public FlowFile commitAllWaterMarks(ProcessSession session, FlowFile ff, String feedId) {
FlowFile resultFF = ff;
Set<String> cancelledWaterMarks = new HashSet<>();
// TODO do more efficiently
for (String waterMarkName : new HashSet<String>(getCurrentWaterMarksAttr(ff).keySet())) {
try {
resultFF = commitWaterMark(session, resultFF, feedId, waterMarkName);
} catch (ActiveWaterMarksCancelledException e) {
cancelledWaterMarks.addAll(e.getWaterMarkNames());
}
}
if (cancelledWaterMarks.size() > 0) {
throw new ActiveWaterMarksCancelledException(feedId, cancelledWaterMarks);
} else {
return resultFF;
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#releaseWaterMark(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String, java.lang.String)
*/
@Override
public FlowFile releaseWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName) {
FlowFile resultFF = ff;
Map<String, WaterMarkParam> ffWaterMarks = getCurrentWaterMarksAttr(ff);
WaterMarkParam param = ffWaterMarks.get(waterMarkName);
try {
if (param != null) {
// Update the flowfile with the modified set of active water marks.
removeFromCurrentWaterMarksAttr(session, resultFF, waterMarkName, param.name);
resetWaterMarkParam(session, resultFF, feedId, waterMarkName, param.name);
} else {
log.warn("Received request to release a water mark not found in the flow file: {}", waterMarkName);
}
} finally {
// Even if water mark resetting fails we should always release the water mark.
Long activeTimestamp = getActiveWaterMarkTimestamp(feedId, waterMarkName);
if (activeTimestamp != null) {
if (param == null || param.timestamp == activeTimestamp) {
releaseActiveWaterMark(feedId, waterMarkName, activeTimestamp);
} else if (param.timestamp != activeTimestamp) {
// If the water mark timestamp does not match the one recorded as an active water mark this means
// this flowfile's water mark has been canceled and another flow file should be considered the active one.
// In this case this water mark value has been superseded and no release should occur.
log.info("Received request to release a water mark version that is no longer active: {}", waterMarkName);
}
} else {
// The water mark is not one recognize as an active one.
log.warn("Received request to release a non-active water mark: {}", waterMarkName);
}
}
return resultFF;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#releaseAllWaterMarks(org.apache.nifi.processor.ProcessSession, org.apache.nifi.flowfile.FlowFile, java.lang.String)
*/
@Override
public FlowFile releaseAllWaterMarks(ProcessSession session, FlowFile ff, String feedId) {
FlowFile resultFF = ff;
for (String waterMarkName : new HashSet<String>(getCurrentWaterMarksAttr(ff).keySet())) {
resultFF = releaseWaterMark(session, resultFF, feedId, waterMarkName);
}
return resultFF;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#getFeedInitializationStatus(java.lang.String)
*/
@Override
public Optional<InitializationStatus> getInitializationStatus(String feedId) {
try {
return getInitStatusCache().get(feedId, () -> getFeedInitStatus(feedId));
} catch (ExecutionException e) {
log.error("Failed to obtain initialization status feed: {}", feedId, e);
throw new ProcessException("Failed to obtain initialization status feed: " + feedId, e.getCause());
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#startFeedInitialization(java.lang.String)
*/
@Override
public InitializationStatus startFeedInitialization(String feedId) {
InitializationStatus status = new InitializationStatus(InitializationStatus.State.IN_PROGRESS);
try {
this.client.updateCurrentInitStatus(feedId, status);
getInitStatusCache().put(feedId, Optional.of(status));
return status;
} catch (Exception e) {
log.error("Failed to update metadata with feed initialization in-progress status: {}, feed: {}", status.getState(), feedId, e);
getInitStatusCache().invalidate(feedId);
throw new ProcessException("Failed to update metadata with feed initialization in-progress status: " + status + ", feed: " + feedId, e);
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#completeFeedInitialization(java.lang.String)
*/
@Override
public InitializationStatus completeFeedInitialization(String feedId) {
InitializationStatus status = new InitializationStatus(InitializationStatus.State.SUCCESS);
try {
this.client.updateCurrentInitStatus(feedId, status);
getInitStatusCache().put(feedId, Optional.of(status));
return status;
} catch (Exception e) {
log.error("Failed to update metadata with feed initialization completion status: {}, feed: {}", status.getState(), feedId, e);
getInitStatusCache().invalidate(feedId);
throw new ProcessException("Failed to update metadata with feed initialization completion status: " + status + ", feed: " + feedId, e);
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#failFeedInitialization(java.lang.String)
*/
@Override
public InitializationStatus failFeedInitialization(String feedId, boolean isReinitialize) {
InitializationStatus.State state = isReinitialize ? InitializationStatus.State.REINITIALIZE_FAILED : InitializationStatus.State.FAILED;
InitializationStatus status = new InitializationStatus(state);
try {
this.client.updateCurrentInitStatus(feedId, status);
getInitStatusCache().put(feedId, Optional.of(status));
return status;
} catch (Exception e) {
log.error("Failed to update feed initialization failed status: {}, feed: {}", status.getState(), feedId);
getInitStatusCache().invalidate(feedId);
return status;
}
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.nifi.core.api.metadata.MetadataRecorder#initializationStatusChanged(java.lang.String, com.thinkbiganalytics.metadata.rest.model.feed.InitializationStatus)
*/
@Override
public void initializationStatusChanged(String feedId, InitializationStatus status) {
getInitStatusCache().invalidate(feedId);
}
@Override
public void updateFeedStatus(ProcessSession session, FlowFile ff, String statusMsg) {
// TODO Auto-generated method stub
}
@Override
public FeedDataHistoryReindexParams updateFeedHistoryReindexing(@Nonnull String feedId, @Nonnull HistoryReindexingStatus historyReindexingStatus) {
return (this.client.updateFeedHistoryReindexing(feedId, historyReindexingStatus));
}
private Optional<InitializationStatus> getFeedInitStatus(String feedId) {
return Optional.ofNullable(this.client.getCurrentInitStatus(feedId));
}
private Cache<String, Optional<InitializationStatus>> getInitStatusCache() {
Cache<String, Optional<InitializationStatus>> cache = this.initStatusCache;
if (cache == null) {
synchronized (this) {
cache = this.initStatusCache;
if (cache == null) {
this.initStatusCache = cache = CacheBuilder.newBuilder()
// .expireAfterWrite(FEED_INIT_STATUS_EXPIRE_SEC, TimeUnit.SECONDS)
.maximumSize(FEED_INIT_STATUS_CACHE_SIZE)
.build();
}
}
}
return cache;
}
private String toWaterMarksKey(String feedId) {
return feedId + ".~";
}
private String toWaterMarkKey(String feedId, String waterMarkName) {
return feedId + "." + waterMarkName;
}
private Long getActiveWaterMarkTimestamp(String feedId, String waterMarkName) {
return this.activeWaterMarks.get(toWaterMarkKey(feedId, waterMarkName));
}
private Map<String, Long> getActiveWaterMarks(String feedId, String waterMarkName) {
return this.activeWaterMarks.subMap(feedId, toWaterMarksKey(feedId));
}
private boolean cancelActiveWaterMark(String feedId, String waterMarkName) {
return this.activeWaterMarks.remove(toWaterMarkKey(feedId, waterMarkName)) == null;
}
private long recordActiveWaterMark(String feedId, String waterMarkName) throws WaterMarkActiveException {
long newTimestamp = System.currentTimeMillis();
long timestamp = this.activeWaterMarks.computeIfAbsent(toWaterMarkKey(feedId, waterMarkName), k -> newTimestamp);
if (timestamp != newTimestamp) {
throw new WaterMarkActiveException(waterMarkName);
} else {
return newTimestamp;
}
}
private boolean releaseActiveWaterMark(String feedId, String waterMarkName, long expectedTimestamp) {
long timestamp = this.activeWaterMarks.remove(toWaterMarkKey(feedId, waterMarkName));
return expectedTimestamp == timestamp;
}
private NavigableMap<String, WaterMarkParam> getCurrentWaterMarksAttr(FlowFile ff) {
try {
String activeStr = ff.getAttribute(CURRENT_WATER_MARKS_ATTR);
if (activeStr == null) {
return new TreeMap<>();
} else {
return WATER_MARKS_READER.readValue(activeStr);
}
} catch (Exception e) {
// Should never happen.
throw new IllegalStateException(e);
}
}
private FlowFile setCurrentWaterMarksAttr(ProcessSession session, FlowFile ff, NavigableMap<String, WaterMarkParam> actives) {
try {
return session.putAttribute(ff, CURRENT_WATER_MARKS_ATTR, WATER_MARKS_WRITER.writeValueAsString(actives));
} catch (Exception e) {
// Should never happen.
throw new IllegalStateException(e);
}
}
private FlowFile resetWaterMarkParam(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String paramName) {
// Update the flowfile with the original value for the water mark parameter.
String value = getHighWaterMarkValue(feedId, waterMarkName).orElse(ff.getAttribute(originalValueParameterName(paramName)));
if (value != null) {
return session.putAttribute(ff, paramName, value);
} else {
log.error("Failed to reset water mark - original value not found in flowfile for water mark: {}", waterMarkName);
throw new IllegalStateException("Failed to reset water mark - original value not found in flowfile for water mark: " + waterMarkName);
}
}
private FlowFile addToCurrentWaterMarksAttr(ProcessSession session, FlowFile ff, String waterMarkName, String parameterName, long timestamp) {
NavigableMap<String, WaterMarkParam> actives = getCurrentWaterMarksAttr(ff);
actives.put(waterMarkName, new WaterMarkParam(timestamp, parameterName));
return setCurrentWaterMarksAttr(session, ff, actives);
}
private FlowFile removeFromCurrentWaterMarksAttr(ProcessSession session, FlowFile ff, String waterMarkName, String parameterName) {
NavigableMap<String, WaterMarkParam> actives = getCurrentWaterMarksAttr(ff);
actives.remove(waterMarkName);
return setCurrentWaterMarksAttr(session, ff, actives);
}
private Optional<String> getHighWaterMarkValue(String feedId, String waterMarkName) {
return this.client.getHighWaterMarkValue(feedId, waterMarkName);
}
private void updateHighWaterMarkValue(String feedId, String waterMarkName, String value) {
this.client.updateHighWaterMarkValue(feedId, waterMarkName, value);
}
private String originalValueParameterName(String parameterName) {
return parameterName + ".original";
}
public static class WaterMarkParam {
private long timestamp;
private String name;
public WaterMarkParam() {
super();
}
public WaterMarkParam(long timestamp, String value) {
this.timestamp = timestamp;
this.name = value;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| KYLO-2171: Ensures active water mark is cancelled when kylo-services comms are lost during load.
| integrations/nifi/nifi-nar-bundles/nifi-standard-services/nifi-core-service-bundle/nifi-core-service/src/main/java/com/thinkbiganalytics/nifi/v2/core/metadata/MetadataClientRecorder.java | KYLO-2171: Ensures active water mark is cancelled when kylo-services comms are lost during load. | <ide><path>ntegrations/nifi/nifi-nar-bundles/nifi-standard-services/nifi-core-service-bundle/nifi-core-service/src/main/java/com/thinkbiganalytics/nifi/v2/core/metadata/MetadataClientRecorder.java
<ide> public FlowFile loadWaterMark(ProcessSession session, FlowFile ff, String feedId, String waterMarkName, String parameterName, String initialValue) throws WaterMarkActiveException {
<ide> long timestamp = recordActiveWaterMark(feedId, waterMarkName);
<ide>
<del> String value = getHighWaterMarkValue(feedId, waterMarkName).orElse(initialValue);
<del> FlowFile resultFF = addToCurrentWaterMarksAttr(session, ff, waterMarkName, parameterName, timestamp);
<del> resultFF = session.putAttribute(resultFF, parameterName, value);
<del> return session.putAttribute(resultFF, originalValueParameterName(parameterName), value);
<add> try {
<add> String value = getHighWaterMarkValue(feedId, waterMarkName).orElse(initialValue);
<add> FlowFile resultFF = addToCurrentWaterMarksAttr(session, ff, waterMarkName, parameterName, timestamp);
<add> resultFF = session.putAttribute(resultFF, parameterName, value);
<add> return session.putAttribute(resultFF, originalValueParameterName(parameterName), value);
<add> } catch (Exception e) {
<add> cancelActiveWaterMark(feedId, waterMarkName);
<add> throw e;
<add> }
<ide> }
<ide>
<ide> /* (non-Javadoc) |
|
Java | apache-2.0 | e1485152260e6b8a0eaf3eeffd7de6885ab66389 | 0 | clumsy/intellij-community,caot/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,samthor/intellij-community,holmes/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,caot/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,fitermay/intellij-community,blademainer/intellij-community,slisson/intellij-community,youdonghai/intellij-community,allotria/intellij-community,adedayo/intellij-community,da1z/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,vladmm/intellij-community,FHannes/intellij-community,holmes/intellij-community,kdwink/intellij-community,asedunov/intellij-community,clumsy/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,clumsy/intellij-community,ibinti/intellij-community,caot/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,signed/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,izonder/intellij-community,holmes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,jagguli/intellij-community,apixandru/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,holmes/intellij-community,hurricup/intellij-community,fnouama/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,supersven/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,samthor/intellij-community,caot/intellij-community,kool79/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,allotria/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,signed/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,samthor/intellij-community,FHannes/intellij-community,holmes/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,amith01994/intellij-community,kool79/intellij-community,gnuhub/intellij-community,kool79/intellij-community,holmes/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,semonte/intellij-community,fitermay/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,youdonghai/intellij-community,samthor/intellij-community,retomerz/intellij-community,robovm/robovm-studio,samthor/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,signed/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,caot/intellij-community,robovm/robovm-studio,retomerz/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,slisson/intellij-community,ryano144/intellij-community,signed/intellij-community,wreckJ/intellij-community,slisson/intellij-community,adedayo/intellij-community,supersven/intellij-community,asedunov/intellij-community,semonte/intellij-community,akosyakov/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,signed/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,supersven/intellij-community,vladmm/intellij-community,da1z/intellij-community,clumsy/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,izonder/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,youdonghai/intellij-community,da1z/intellij-community,youdonghai/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,hurricup/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,signed/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,signed/intellij-community,clumsy/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,kdwink/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,kdwink/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,kdwink/intellij-community,holmes/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,kdwink/intellij-community,dslomov/intellij-community,slisson/intellij-community,jagguli/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,allotria/intellij-community,adedayo/intellij-community,apixandru/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,allotria/intellij-community,jagguli/intellij-community,ibinti/intellij-community,allotria/intellij-community,kdwink/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,allotria/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,blademainer/intellij-community,clumsy/intellij-community,samthor/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,jagguli/intellij-community,slisson/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,nicolargo/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,asedunov/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,signed/intellij-community,supersven/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,kool79/intellij-community,robovm/robovm-studio,adedayo/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,FHannes/intellij-community,supersven/intellij-community,fnouama/intellij-community,fnouama/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,adedayo/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,caot/intellij-community,izonder/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,petteyg/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,apixandru/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,allotria/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,izonder/intellij-community,caot/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,diorcety/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,da1z/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,samthor/intellij-community,ryano144/intellij-community,samthor/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,samthor/intellij-community,xfournet/intellij-community,blademainer/intellij-community,retomerz/intellij-community,allotria/intellij-community,apixandru/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,fitermay/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,amith01994/intellij-community,vladmm/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,supersven/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,caot/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,dslomov/intellij-community,supersven/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,diorcety/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,petteyg/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,caot/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,hurricup/intellij-community,retomerz/intellij-community,petteyg/intellij-community,kool79/intellij-community,kdwink/intellij-community,semonte/intellij-community,holmes/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,izonder/intellij-community,kool79/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,supersven/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,izonder/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,amith01994/intellij-community,izonder/intellij-community | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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 org.jetbrains.idea.maven.server;
import com.intellij.openapi.util.Comparing;
import com.intellij.util.SystemProperties;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.apache.maven.*;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager;
import org.apache.maven.artifact.resolver.*;
import org.apache.maven.cli.MavenCli;
import org.apache.maven.execution.*;
import org.apache.maven.model.Activation;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.Profile;
import org.apache.maven.model.interpolation.ModelInterpolator;
import org.apache.maven.model.profile.DefaultProfileInjector;
import org.apache.maven.plugin.LegacySupport;
import org.apache.maven.plugin.internal.PluginDependenciesResolver;
import org.apache.maven.profiles.activation.*;
import org.apache.maven.project.*;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.apache.maven.project.inheritance.DefaultModelInheritanceAssembler;
import org.apache.maven.project.interpolation.AbstractStringBasedModelInterpolator;
import org.apache.maven.project.interpolation.ModelInterpolationException;
import org.apache.maven.project.path.DefaultPathTranslator;
import org.apache.maven.project.path.PathTranslator;
import org.apache.maven.project.validation.ModelValidationResult;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.building.DefaultSettingsBuildingRequest;
import org.apache.maven.settings.building.SettingsBuilder;
import org.apache.maven.settings.building.SettingsBuildingException;
import org.apache.maven.settings.building.SettingsBuildingRequest;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeResolutionListener;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.context.DefaultContext;
import org.codehaus.plexus.logging.BaseLoggerManager;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.*;
import org.jetbrains.idea.maven.server.embedder.*;
import org.jetbrains.idea.maven.server.embedder.MavenExecutionResult;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.repository.LocalRepositoryManager;
import org.sonatype.aether.util.DefaultRepositorySystemSession;
import org.sonatype.aether.util.graph.PreorderNodeListGenerator;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
/**
* Overridden maven components:
maven-compat:
org.jetbrains.idea.maven.server.embedder.CustomMaven3RepositoryMetadataManager <-> org.apache.maven.artifact.repository.metadata.DefaultRepositoryMetadataManager
org.jetbrains.idea.maven.server.embedder.CustomMaven3ArtifactResolver <-> org.apache.maven.artifact.resolver.DefaultArtifactResolver
org.jetbrains.idea.maven.server.embedder.CustomMaven3ModelInterpolator <-> org.apache.maven.project.interpolation.StringSearchModelInterpolator
maven-core:
org.jetbrains.idea.maven.server.embedder.CustomMaven3ArtifactFactory <-> org.apache.maven.artifact.factory.DefaultArtifactFactory
org.jetbrains.idea.maven.server.embedder.CustomPluginDescriptorCache <-> org.apache.maven.plugin.DefaultPluginDescriptorCache
maven-model-builder:
org.jetbrains.idea.maven.server.embedder.CustomMaven3ModelInterpolator2 <-> org.apache.maven.model.interpolation.StringSearchModelInterpolator
*/
public class Maven3ServerEmbedderImpl extends MavenRemoteObject implements MavenServerEmbedder {
private final static boolean USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING = System.getProperty("idea.maven3.use.compat.resolver") != null;
@NotNull private final DefaultPlexusContainer myContainer;
@NotNull private final Settings myMavenSettings;
private final ArtifactRepository myLocalRepository;
private final Maven3ServerConsoleLogger myConsoleWrapper;
private final Properties mySystemProperties;
private volatile MavenServerProgressIndicator myCurrentIndicator;
private MavenWorkspaceMap myWorkspaceMap;
private Date myBuildStartTime;
private boolean myAlwaysUpdateSnapshots;
public Maven3ServerEmbedderImpl(MavenServerSettings settings) throws RemoteException {
File mavenHome = settings.getMavenHome();
if (mavenHome != null) {
System.setProperty("maven.home", mavenHome.getPath());
}
myConsoleWrapper = new Maven3ServerConsoleLogger();
myConsoleWrapper.setThreshold(settings.getLoggingLevel());
ClassWorld classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
MavenCli cli = new MavenCli(classWorld) {
@Override
protected void customizeContainer(PlexusContainer container) {
((DefaultPlexusContainer)container).setLoggerManager(new BaseLoggerManager() {
@Override
protected Logger createLogger(String s) {
return myConsoleWrapper;
}
});
}
};
Class cliRequestClass;
try {
cliRequestClass = MavenCli.class.getClassLoader().loadClass("org.apache.maven.cli.MavenCli$CliRequest");
}
catch (ClassNotFoundException e) {
throw new RuntimeException("Class \"org.apache.maven.cli.MavenCli$CliRequest\" not found");
}
Object cliRequest;
try {
String[] commandLineOptions = new String[settings.getUserProperties().size()];
int idx = 0;
for (Map.Entry<Object, Object> each : settings.getUserProperties().entrySet()) {
commandLineOptions[idx++] = "-D" + each.getKey() + "=" + each.getValue();
}
Constructor constructor = cliRequestClass.getDeclaredConstructor(String[].class, ClassWorld.class);
constructor.setAccessible(true);
cliRequest = constructor.newInstance(commandLineOptions, classWorld);
for (String each : new String[]{"initialize", "cli", "properties", "container"}) {
Method m = MavenCli.class.getDeclaredMethod(each, cliRequestClass);
m.setAccessible(true);
m.invoke(cli, cliRequest);
}
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
// reset threshold
myContainer = FieldAccessor.get(MavenCli.class, cli, "container");
myContainer.getLoggerManager().setThreshold(settings.getLoggingLevel());
mySystemProperties = FieldAccessor.<Properties>get(cliRequestClass, cliRequest, "systemProperties");
if (settings.getProjectJdk() != null) {
mySystemProperties.setProperty("java.home", settings.getProjectJdk());
}
myMavenSettings =
buildSettings(FieldAccessor.<SettingsBuilder>get(MavenCli.class, cli, "settingsBuilder"), settings, mySystemProperties,
FieldAccessor.<Properties>get(cliRequestClass, cliRequest, "userProperties"));
myLocalRepository = createLocalRepository();
}
private static Settings buildSettings(SettingsBuilder builder,
MavenServerSettings settings,
Properties systemProperties,
Properties userProperties) throws RemoteException {
SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
settingsRequest.setGlobalSettingsFile(settings.getGlobalSettingsFile());
settingsRequest.setUserSettingsFile(settings.getUserSettingsFile());
settingsRequest.setSystemProperties(systemProperties);
settingsRequest.setUserProperties(userProperties);
Settings result = new Settings();
try {
result = builder.build(settingsRequest).getEffectiveSettings();
}
catch (SettingsBuildingException e) {
Maven3ServerGlobals.getLogger().info(e);
}
result.setOffline(settings.isOffline());
if (settings.getLocalRepository() != null) {
result.setLocalRepository(settings.getLocalRepository().getPath());
}
if (result.getLocalRepository() == null) {
result.setLocalRepository(new File(SystemProperties.getUserHome(), ".m2/repository").getPath());
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T getComponent(Class<T> clazz, String roleHint) {
try {
return (T)myContainer.lookup(clazz.getName(), roleHint);
}
catch (ComponentLookupException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings({"unchecked"})
public <T> T getComponent(Class<T> clazz) {
try {
return (T)myContainer.lookup(clazz.getName());
}
catch (ComponentLookupException e) {
throw new RuntimeException(e);
}
}
private ArtifactRepository createLocalRepository() {
try {
final ArtifactRepository localRepository =
getComponent(RepositorySystem.class).createLocalRepository(new File(myMavenSettings.getLocalRepository()));
final String customRepoId = System.getProperty("maven3.localRepository.id");
if(customRepoId != null) {
// see details at http://youtrack.jetbrains.com/issue/IDEA-121292
localRepository.setId(customRepoId);
}
return localRepository;
}
catch (InvalidRepositoryException e) {
throw new RuntimeException(e);
// Legacy code.
}
//ArtifactRepositoryLayout layout = getComponent(ArtifactRepositoryLayout.class, "default");
//ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class);
//
//String url = myMavenSettings.getLocalRepository();
//if (!url.startsWith("file:")) url = "file://" + url;
//
//ArtifactRepository localRepository = factory.createArtifactRepository("local", url, layout, null, null);
//
//boolean snapshotPolicySet = myMavenSettings.isOffline();
//if (!snapshotPolicySet && snapshotUpdatePolicy == MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE) {
// factory.setGlobalUpdatePolicy(ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS);
//}
//factory.setGlobalChecksumPolicy(ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);
//
//return localRepository;
}
@Override
public void customize(@Nullable MavenWorkspaceMap workspaceMap,
boolean failOnUnresolvedDependency,
@NotNull MavenServerConsole console,
@NotNull MavenServerProgressIndicator indicator,
boolean alwaysUpdateSnapshots) throws RemoteException {
try {
((CustomMaven3ArtifactFactory)getComponent(ArtifactFactory.class)).customize();
((CustomMaven3ArtifactResolver)getComponent(ArtifactResolver.class)).customize(workspaceMap, failOnUnresolvedDependency);
((CustomMaven3RepositoryMetadataManager)getComponent(RepositoryMetadataManager.class)).customize(workspaceMap);
//((CustomMaven3WagonManager)getComponent(WagonManager.class)).customize(failOnUnresolvedDependency);
myWorkspaceMap = workspaceMap;
myBuildStartTime = new Date();
myAlwaysUpdateSnapshots = alwaysUpdateSnapshots;
setConsoleAndIndicator(console, new MavenServerProgressIndicatorWrapper(indicator));
}
catch (Exception e) {
throw rethrowException(e);
}
}
private void setConsoleAndIndicator(MavenServerConsole console, MavenServerProgressIndicator indicator) {
myConsoleWrapper.setWrappee(console);
myCurrentIndicator = indicator;
}
@NotNull
@Override
public MavenServerExecutionResult resolveProject(@NotNull File file,
@NotNull Collection<String> activeProfiles,
@NotNull Collection<String> inactiveProfiles)
throws RemoteException, MavenServerProcessCanceledException {
DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(myConsoleWrapper);
MavenExecutionResult result = doResolveProject(file, new ArrayList<String>(activeProfiles), new ArrayList<String>(inactiveProfiles),
Arrays.<ResolutionListener>asList(listener));
return createExecutionResult(file, result, listener.getRootNode());
}
@Nullable
@Override
public String evaluateEffectivePom(@NotNull File file, @NotNull List<String> activeProfiles, @NotNull List<String> inactiveProfiles)
throws RemoteException, MavenServerProcessCanceledException {
return MavenEffectivePomDumper.evaluateEffectivePom(this, file, activeProfiles, inactiveProfiles);
}
public void executeWithMavenSession(MavenExecutionRequest request, Runnable runnable) {
DefaultMaven maven = (DefaultMaven)getComponent(Maven.class);
RepositorySystemSession repositorySession = maven.newRepositorySession(request);
request.getProjectBuildingRequest().setRepositorySession(repositorySession);
MavenSession mavenSession = new MavenSession(myContainer, repositorySession, request, new DefaultMavenExecutionResult());
LegacySupport legacySupport = getComponent(LegacySupport.class);
MavenSession oldSession = legacySupport.getSession();
legacySupport.setSession(mavenSession);
/** adapted from {@link org.apache.maven.DefaultMaven#doExecute(org.apache.maven.execution.MavenExecutionRequest)} */
try {
for (AbstractMavenLifecycleParticipant listener : getLifecycleParticipants(Collections.<MavenProject>emptyList())) {
listener.afterSessionStart(mavenSession);
}
}
catch (MavenExecutionException e) {
throw new RuntimeException(e);
}
try {
runnable.run();
}
finally {
legacySupport.setSession(oldSession);
}
}
@NotNull
public MavenExecutionResult doResolveProject(@NotNull final File file,
@NotNull final List<String> activeProfiles,
@NotNull final List<String> inactiveProfiles,
final List<ResolutionListener> listeners) throws RemoteException {
final MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, Collections.<String>emptyList());
request.setUpdateSnapshots(myAlwaysUpdateSnapshots);
final AtomicReference<MavenExecutionResult> ref = new AtomicReference<MavenExecutionResult>();
executeWithMavenSession(request, new Runnable() {
@Override
public void run() {
try {
// copied from DefaultMavenProjectBuilder.buildWithDependencies
ProjectBuilder builder = getComponent(ProjectBuilder.class);
CustomMaven3ModelInterpolator2 modelInterpolator = (CustomMaven3ModelInterpolator2)getComponent(ModelInterpolator.class);
String savedLocalRepository = modelInterpolator.getLocalRepository();
modelInterpolator.setLocalRepository(request.getLocalRepositoryPath().getAbsolutePath());
List<ProjectBuildingResult> results;
try {
// Don't use build(File projectFile, ProjectBuildingRequest request) , because it don't use cache !!!!!!!! (see http://devnet.jetbrains.com/message/5500218)
results = builder.build(Collections.singletonList(new File(file.getPath())), false, request.getProjectBuildingRequest());
}
finally {
modelInterpolator.setLocalRepository(savedLocalRepository);
}
ProjectBuildingResult buildingResult = results.get(0);
MavenProject project = buildingResult.getProject();
RepositorySystemSession repositorySession = getComponent(LegacySupport.class).getRepositorySession();
if (repositorySession instanceof DefaultRepositorySystemSession) {
((DefaultRepositorySystemSession)repositorySession).setTransferListener(new TransferListenerAdapter(myCurrentIndicator));
if (myWorkspaceMap != null) {
((DefaultRepositorySystemSession)repositorySession).setWorkspaceReader(new Maven3WorkspaceReader(myWorkspaceMap));
}
}
List<Exception> exceptions = new ArrayList<Exception>();
loadExtensions(project, exceptions);
//Artifact projectArtifact = project.getArtifact();
//Map managedVersions = project.getManagedVersionMap();
//ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
project.setDependencyArtifacts(project.createArtifacts(getComponent(ArtifactFactory.class), null, null));
//
if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
resolutionRequest.setArtifactDependencies(project.getDependencyArtifacts());
resolutionRequest.setArtifact(project.getArtifact());
resolutionRequest.setManagedVersionMap(project.getManagedVersionMap());
resolutionRequest.setLocalRepository(myLocalRepository);
resolutionRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
resolutionRequest.setListeners(listeners);
resolutionRequest.setResolveRoot(false);
resolutionRequest.setResolveTransitively(true);
ArtifactResolver resolver = getComponent(ArtifactResolver.class);
ArtifactResolutionResult result = resolver.resolve(resolutionRequest);
project.setArtifacts(result.getArtifacts());
// end copied from DefaultMavenProjectBuilder.buildWithDependencies
ref.set(new MavenExecutionResult(project, exceptions));
}
else {
final DependencyResolutionResult dependencyResolutionResult = resolveDependencies(project, repositorySession);
final List<Dependency> dependencies = dependencyResolutionResult.getDependencies();
Set<Artifact> artifacts = new LinkedHashSet<Artifact>(dependencies.size());
for (Dependency dependency : dependencies) {
final Artifact artifact = RepositoryUtils.toArtifact(dependency.getArtifact());
artifact.setScope(dependency.getScope());
artifact.setOptional(dependency.isOptional());
artifacts.add(artifact);
resolveAsModule(artifact);
}
project.setArtifacts(artifacts);
ref.set(new MavenExecutionResult(project, dependencyResolutionResult, exceptions));
}
}
catch (Exception e) {
ref.set(handleException(e));
}
}
});
return ref.get();
}
private boolean resolveAsModule(Artifact a) {
MavenWorkspaceMap map = myWorkspaceMap;
if (map == null) return false;
MavenWorkspaceMap.Data resolved = map.findFileAndOriginalId(MavenModelConverter.createMavenId(a));
if (resolved == null) return false;
a.setResolved(true);
a.setFile(resolved.getFile(a.getType()));
a.selectVersion(resolved.originalId.getVersion());
return true;
}
/**
* copied from {@link org.apache.maven.project.DefaultProjectBuilder#resolveDependencies(org.apache.maven.project.MavenProject, org.sonatype.aether.RepositorySystemSession)}
*/
private DependencyResolutionResult resolveDependencies(MavenProject project, RepositorySystemSession session) {
DependencyResolutionResult resolutionResult;
try {
ProjectDependenciesResolver dependencyResolver = getComponent(ProjectDependenciesResolver.class);
DefaultDependencyResolutionRequest resolution = new DefaultDependencyResolutionRequest(project, session);
resolutionResult = dependencyResolver.resolve(resolution);
}
catch (DependencyResolutionException e) {
resolutionResult = e.getResult();
}
Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
if (resolutionResult.getDependencyGraph() != null) {
RepositoryUtils.toArtifacts(artifacts, resolutionResult.getDependencyGraph().getChildren(),
Collections.singletonList(project.getArtifact().getId()), null);
// Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not
LocalRepositoryManager lrm = session.getLocalRepositoryManager();
for (Artifact artifact : artifacts) {
if (!artifact.isResolved()) {
String path = lrm.getPathForLocalArtifact(RepositoryUtils.toArtifact(artifact));
artifact.setFile(new File(lrm.getRepository().getBasedir(), path));
}
}
}
project.setResolvedArtifacts(artifacts);
project.setArtifacts(artifacts);
return resolutionResult;
}
/**
* adapted from {@link org.apache.maven.DefaultMaven#doExecute(org.apache.maven.execution.MavenExecutionRequest)}
*/
private void loadExtensions(MavenProject project, List<Exception> exceptions) {
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
Collection<AbstractMavenLifecycleParticipant> lifecycleParticipants = getLifecycleParticipants(Arrays.asList(project));
if (!lifecycleParticipants.isEmpty()) {
LegacySupport legacySupport = getComponent(LegacySupport.class);
MavenSession session = legacySupport.getSession();
session.setCurrentProject(project);
session.setProjects(Arrays.asList(project));
for (AbstractMavenLifecycleParticipant listener : lifecycleParticipants) {
Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader());
try {
listener.afterProjectsRead(session);
}
catch (MavenExecutionException e) {
exceptions.add(e);
}
finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
}
}
/**
* adapted from {@link org.apache.maven.DefaultMaven#getLifecycleParticipants(java.util.Collection)}
*/
private Collection<AbstractMavenLifecycleParticipant> getLifecycleParticipants(Collection<MavenProject> projects) {
Collection<AbstractMavenLifecycleParticipant> lifecycleListeners = new LinkedHashSet<AbstractMavenLifecycleParticipant>();
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
try {
lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
}
catch (ComponentLookupException e) {
// this is just silly, lookupList should return an empty list!
warn("Failed to lookup lifecycle participants", e);
}
Collection<ClassLoader> scannedRealms = new HashSet<ClassLoader>();
for (MavenProject project : projects) {
ClassLoader projectRealm = project.getClassRealm();
if (projectRealm != null && scannedRealms.add(projectRealm)) {
Thread.currentThread().setContextClassLoader(projectRealm);
try {
lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
}
catch (ComponentLookupException e) {
// this is just silly, lookupList should return an empty list!
warn("Failed to lookup lifecycle participants", e);
}
}
}
}
finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
return lifecycleListeners;
}
private static void warn(String message, Throwable e) {
try {
Maven3ServerGlobals.getLogger().warn(new RuntimeException(message, e));
}
catch (RemoteException e1) {
throw new RuntimeException(e1);
}
}
public MavenExecutionRequest createRequest(File file, List<String> activeProfiles, List<String> inactiveProfiles, List<String> goals)
throws RemoteException {
//Properties executionProperties = myMavenSettings.getProperties();
//if (executionProperties == null) {
// executionProperties = new Properties();
//}
MavenExecutionRequest result = new DefaultMavenExecutionRequest();
try {
getComponent(MavenExecutionRequestPopulator.class).populateFromSettings(result, myMavenSettings);
result.setGoals(goals);
result.setPom(file);
getComponent(MavenExecutionRequestPopulator.class).populateDefaults(result);
result.setSystemProperties(mySystemProperties);
result.setActiveProfiles(activeProfiles);
result.setInactiveProfiles(inactiveProfiles);
result.setStartTime(myBuildStartTime);
return result;
}
catch (MavenExecutionRequestPopulationException e) {
throw new RuntimeException(e);
}
}
private static MavenExecutionResult handleException(Throwable e) {
if (e instanceof Error) throw (Error)e;
return new MavenExecutionResult(null, Collections.singletonList((Exception)e));
}
@NotNull
public File getLocalRepositoryFile() {
return new File(myLocalRepository.getBasedir());
}
@NotNull
private MavenServerExecutionResult createExecutionResult(File file, MavenExecutionResult result, DependencyNode rootNode)
throws RemoteException {
Collection<MavenProjectProblem> problems = MavenProjectProblem.createProblemsList();
THashSet<MavenId> unresolvedArtifacts = new THashSet<MavenId>();
validate(file, result.getExceptions(), problems, unresolvedArtifacts);
MavenProject mavenProject = result.getMavenProject();
if (mavenProject == null) return new MavenServerExecutionResult(null, problems, unresolvedArtifacts);
MavenModel model = null;
try {
if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
//noinspection unchecked
final List<DependencyNode> dependencyNodes = rootNode == null ? Collections.emptyList() : rootNode.getChildren();
model = MavenModelConverter.convertModel(
mavenProject.getModel(), mavenProject.getCompileSourceRoots(), mavenProject.getTestCompileSourceRoots(),
mavenProject.getArtifacts(), dependencyNodes, mavenProject.getExtensionArtifacts(), getLocalRepositoryFile());
}
else {
final DependencyResolutionResult dependencyResolutionResult = result.getDependencyResolutionResult();
final org.sonatype.aether.graph.DependencyNode dependencyGraph =
dependencyResolutionResult != null ? dependencyResolutionResult.getDependencyGraph() : null;
final List<org.sonatype.aether.graph.DependencyNode> dependencyNodes =
dependencyGraph != null ? dependencyGraph.getChildren() : Collections.<org.sonatype.aether.graph.DependencyNode>emptyList();
model = AetherModelConverter.convertModelWithAetherDependencyTree(
mavenProject.getModel(), mavenProject.getCompileSourceRoots(), mavenProject.getTestCompileSourceRoots(),
mavenProject.getArtifacts(), dependencyNodes, mavenProject.getExtensionArtifacts(), getLocalRepositoryFile());
}
}
catch (Exception e) {
validate(mavenProject.getFile(), Collections.singleton(e), problems, null);
}
RemoteNativeMavenProjectHolder holder = new RemoteNativeMavenProjectHolder(mavenProject);
try {
UnicastRemoteObject.exportObject(holder, 0);
}
catch (RemoteException e) {
throw new RuntimeException(e);
}
Collection<String> activatedProfiles = collectActivatedProfiles(mavenProject);
MavenServerExecutionResult.ProjectData data =
new MavenServerExecutionResult.ProjectData(model, MavenModelConverter.convertToMap(mavenProject.getModel()), holder,
activatedProfiles);
return new MavenServerExecutionResult(data, problems, unresolvedArtifacts);
}
private static Collection<String> collectActivatedProfiles(MavenProject mavenProject)
throws RemoteException {
// for some reason project's active profiles do not contain parent's profiles - only local and settings'.
// parent's profiles do not contain settings' profiles.
List<Profile> profiles = new ArrayList<Profile>();
try {
while (mavenProject != null) {
profiles.addAll(mavenProject.getActiveProfiles());
mavenProject = mavenProject.getParent();
}
}
catch (Exception e) {
// don't bother user if maven failed to build parent project
Maven3ServerGlobals.getLogger().info(e);
}
return collectProfilesIds(profiles);
}
private void validate(@NotNull File file,
@NotNull Collection<Exception> exceptions,
@NotNull Collection<MavenProjectProblem> problems,
@Nullable Collection<MavenId> unresolvedArtifacts) throws RemoteException {
for (Throwable each : exceptions) {
Maven3ServerGlobals.getLogger().info(each);
if(each instanceof IllegalStateException && each.getCause() != null) {
each = each.getCause();
}
if (each instanceof InvalidProjectModelException) {
ModelValidationResult modelValidationResult = ((InvalidProjectModelException)each).getValidationResult();
if (modelValidationResult != null) {
for (Object eachValidationProblem : modelValidationResult.getMessages()) {
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), (String)eachValidationProblem));
}
}
else {
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getCause().getMessage()));
}
}
else if (each instanceof ProjectBuildingException) {
String causeMessage = each.getCause() != null ? each.getCause().getMessage() : each.getMessage();
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), causeMessage));
}
else {
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getMessage()));
}
}
if (unresolvedArtifacts != null) {
unresolvedArtifacts.addAll(retrieveUnresolvedArtifactIds());
}
}
private Set<MavenId> retrieveUnresolvedArtifactIds() {
Set<MavenId> result = new THashSet<MavenId>();
// TODO collect unresolved artifacts
//((CustomMaven3WagonManager)getComponent(WagonManager.class)).getUnresolvedCollector().retrieveUnresolvedIds(result);
//((CustomMaven3ArtifactResolver)getComponent(ArtifactResolver.class)).getUnresolvedCollector().retrieveUnresolvedIds(result);
return result;
}
@NotNull
@Override
public MavenArtifact resolve(@NotNull MavenArtifactInfo info, @NotNull List<MavenRemoteRepository> remoteRepositories)
throws RemoteException, MavenServerProcessCanceledException {
return doResolve(info, remoteRepositories);
}
@NotNull
@Override
public List<MavenArtifact> resolveTransitively(@NotNull List<MavenArtifactInfo> artifacts,
@NotNull List<MavenRemoteRepository> remoteRepositories)
throws RemoteException, MavenServerProcessCanceledException {
try {
Set<Artifact> toResolve = new LinkedHashSet<Artifact>();
for (MavenArtifactInfo each : artifacts) {
toResolve.add(createArtifact(each));
}
Artifact project = getComponent(ArtifactFactory.class).createBuildArtifact("temp", "temp", "666", "pom");
Set<Artifact> res = getComponent(ArtifactResolver.class)
.resolveTransitively(toResolve, project, Collections.EMPTY_MAP, myLocalRepository, convertRepositories(remoteRepositories),
getComponent(ArtifactMetadataSource.class)).getArtifacts();
return MavenModelConverter.convertArtifacts(res, new THashMap<Artifact, MavenArtifact>(), getLocalRepositoryFile());
}
catch (ArtifactResolutionException e) {
Maven3ServerGlobals.getLogger().info(e);
}
catch (ArtifactNotFoundException e) {
Maven3ServerGlobals.getLogger().info(e);
}
catch (Exception e) {
throw rethrowException(e);
}
return Collections.emptyList();
}
@Override
public Collection<MavenArtifact> resolvePlugin(@NotNull final MavenPlugin plugin,
@NotNull final List<MavenRemoteRepository> repositories,
int nativeMavenProjectId,
final boolean transitive) throws RemoteException, MavenServerProcessCanceledException {
try {
Plugin mavenPlugin = new Plugin();
mavenPlugin.setGroupId(plugin.getGroupId());
mavenPlugin.setArtifactId(plugin.getArtifactId());
mavenPlugin.setVersion(plugin.getVersion());
MavenProject project = RemoteNativeMavenProjectHolder.findProjectById(nativeMavenProjectId);
Plugin pluginFromProject = project.getBuild().getPluginsAsMap().get(plugin.getGroupId() + ':' + plugin.getArtifactId());
if (pluginFromProject != null) {
mavenPlugin.setDependencies(pluginFromProject.getDependencies());
}
final MavenExecutionRequest request =
createRequest(null, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList());
DefaultMaven maven = (DefaultMaven)getComponent(Maven.class);
RepositorySystemSession repositorySystemSession = maven.newRepositorySession(request);
PluginDependenciesResolver pluginDependenciesResolver = getComponent(PluginDependenciesResolver.class);
org.sonatype.aether.artifact.Artifact pluginArtifact =
pluginDependenciesResolver.resolve(mavenPlugin, project.getRemotePluginRepositories(), repositorySystemSession);
org.sonatype.aether.graph.DependencyNode node = pluginDependenciesResolver
.resolve(mavenPlugin, pluginArtifact, null, project.getRemotePluginRepositories(), repositorySystemSession);
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept(nlg);
List<MavenArtifact> res = new ArrayList<MavenArtifact>();
for (org.sonatype.aether.artifact.Artifact artifact : nlg.getArtifacts(true)) {
if (!Comparing.equal(artifact.getArtifactId(), plugin.getArtifactId()) ||
!Comparing.equal(artifact.getGroupId(), plugin.getGroupId())) {
res.add(MavenModelConverter.convertArtifact(RepositoryUtils.toArtifact(artifact), getLocalRepositoryFile()));
}
}
return res;
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().info(e);
return Collections.emptyList();
}
}
private MavenArtifact doResolve(MavenArtifactInfo info, List<MavenRemoteRepository> remoteRepositories) throws RemoteException {
Artifact resolved = doResolve(createArtifact(info), convertRepositories(remoteRepositories));
return MavenModelConverter.convertArtifact(resolved, getLocalRepositoryFile());
}
private Artifact doResolve(Artifact artifact, List<ArtifactRepository> remoteRepositories) throws RemoteException {
try {
resolve(artifact, remoteRepositories);
return artifact;
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().info(e);
}
return artifact;
}
public void resolve(@NotNull final Artifact artifact, @NotNull final List<ArtifactRepository> repos)
throws ArtifactResolutionException, ArtifactNotFoundException {
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
request.setRemoteRepositories(repos);
try {
getComponent(MavenExecutionRequestPopulator.class).populateFromSettings(request, myMavenSettings);
getComponent(MavenExecutionRequestPopulator.class).populateDefaults(request);
}
catch (MavenExecutionRequestPopulationException e) {
throw new RuntimeException(e);
}
getComponent(ArtifactResolver.class).resolve(artifact, request.getRemoteRepositories(), myLocalRepository);
}
private List<ArtifactRepository> convertRepositories(List<MavenRemoteRepository> repositories) throws RemoteException {
List<ArtifactRepository> result = new ArrayList<ArtifactRepository>();
for (MavenRemoteRepository each : repositories) {
try {
ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class);
result.add(ProjectUtils.buildArtifactRepository(MavenModelConverter.toNativeRepository(each), factory, myContainer));
}
catch (InvalidRepositoryException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
return result;
}
private Artifact createArtifact(MavenArtifactInfo info) {
return getComponent(ArtifactFactory.class)
.createArtifactWithClassifier(info.getGroupId(), info.getArtifactId(), info.getVersion(), info.getPackaging(), info.getClassifier());
}
@NotNull
@Override
public MavenServerExecutionResult execute(@NotNull File file,
@NotNull Collection<String> activeProfiles,
@NotNull Collection<String> inactiveProfiles,
@NotNull List<String> goals,
@NotNull List<String> selectedProjects,
boolean alsoMake,
boolean alsoMakeDependents) throws RemoteException, MavenServerProcessCanceledException {
MavenExecutionResult result =
doExecute(file, new ArrayList<String>(activeProfiles), new ArrayList<String>(inactiveProfiles), goals, selectedProjects, alsoMake,
alsoMakeDependents);
return createExecutionResult(file, result, null);
}
private MavenExecutionResult doExecute(@NotNull final File file,
@NotNull final List<String> activeProfiles,
@NotNull final List<String> inactiveProfiles,
@NotNull final List<String> goals,
@NotNull final List<String> selectedProjects,
boolean alsoMake,
boolean alsoMakeDependents) throws RemoteException {
MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, goals);
if (!selectedProjects.isEmpty()) {
request.setRecursive(true);
request.setSelectedProjects(selectedProjects);
if (alsoMake && alsoMakeDependents) {
request.setMakeBehavior(ReactorManager.MAKE_BOTH_MODE);
}
else if (alsoMake) {
request.setMakeBehavior(ReactorManager.MAKE_MODE);
}
else if (alsoMakeDependents) {
request.setMakeBehavior(ReactorManager.MAKE_DEPENDENTS_MODE);
}
}
org.apache.maven.execution.MavenExecutionResult executionResult = safeExecute(request, getComponent(Maven.class));
return new MavenExecutionResult(executionResult.getProject(), filterExceptions(executionResult.getExceptions()));
}
private org.apache.maven.execution.MavenExecutionResult safeExecute(MavenExecutionRequest request, Maven maven) throws RemoteException {
MavenLeakDetector detector = new MavenLeakDetector().mark();
org.apache.maven.execution.MavenExecutionResult result = maven.execute(request);
detector.check();
return result;
}
private static List<Exception> filterExceptions(List<Throwable> list) {
for (Throwable throwable : list) {
if (!(throwable instanceof Exception)) {
throw new RuntimeException(throwable);
}
}
return (List<Exception>)((List)list);
}
@Override
public void reset() throws RemoteException {
try {
setConsoleAndIndicator(null, null);
((CustomMaven3ArtifactFactory)getComponent(ArtifactFactory.class)).reset();
((CustomMaven3ArtifactResolver)getComponent(ArtifactResolver.class)).reset();
((CustomMaven3RepositoryMetadataManager)getComponent(RepositoryMetadataManager.class)).reset();
//((CustomWagonManager)getComponent(WagonManager.class)).reset();
}
catch (Exception e) {
throw rethrowException(e);
}
}
@Override
public void release() throws RemoteException {
myContainer.dispose();
}
public void clearCaches() throws RemoteException {
// do nothing
}
public void clearCachesFor(final MavenId projectId) throws RemoteException {
// do nothing
}
public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException {
Model result = MavenModelConverter.toNativeModel(model);
result = doInterpolate(result, basedir);
PathTranslator pathTranslator = new DefaultPathTranslator();
pathTranslator.alignToBaseDirectory(result, basedir);
return MavenModelConverter.convertModel(result, null);
}
public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException {
Model result = MavenModelConverter.toNativeModel(model);
new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel));
return MavenModelConverter.convertModel(result, null);
}
public static ProfileApplicationResult applyProfiles(MavenModel model,
File basedir,
MavenExplicitProfiles explicitProfiles,
Collection<String> alwaysOnProfiles) throws RemoteException {
Model nativeModel = MavenModelConverter.toNativeModel(model);
Collection<String> enabledProfiles = explicitProfiles.getEnabledProfiles();
Collection<String> disabledProfiles = explicitProfiles.getDisabledProfiles();
List<Profile> activatedPom = new ArrayList<Profile>();
List<Profile> activatedExternal = new ArrayList<Profile>();
List<Profile> activeByDefault = new ArrayList<Profile>();
List<Profile> rawProfiles = nativeModel.getProfiles();
List<Profile> expandedProfilesCache = null;
List<Profile> deactivatedProfiles = new ArrayList<Profile>();
for (int i = 0; i < rawProfiles.size(); i++) {
Profile eachRawProfile = rawProfiles.get(i);
if (disabledProfiles.contains(eachRawProfile.getId())) {
deactivatedProfiles.add(eachRawProfile);
continue;
}
boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId());
Activation activation = eachRawProfile.getActivation();
if (activation != null) {
if (activation.isActiveByDefault()) {
activeByDefault.add(eachRawProfile);
}
// expand only if necessary
if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles();
Profile eachExpandedProfile = expandedProfilesCache.get(i);
for (ProfileActivator eachActivator : getProfileActivators(basedir)) {
try {
if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) {
shouldAdd = true;
break;
}
}
catch (ProfileActivationException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
}
if (shouldAdd) {
if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) {
activatedPom.add(eachRawProfile);
}
else {
activatedExternal.add(eachRawProfile);
}
}
}
List<Profile> activatedProfiles = new ArrayList<Profile>(activatedPom.isEmpty() ? activeByDefault : activatedPom);
activatedProfiles.addAll(activatedExternal);
for (Profile each : activatedProfiles) {
new DefaultProfileInjector().injectProfile(nativeModel, each, null, null);
}
return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null),
new MavenExplicitProfiles(collectProfilesIds(activatedProfiles),
collectProfilesIds(deactivatedProfiles))
);
}
private static Model doInterpolate(Model result, File basedir) throws RemoteException {
try {
AbstractStringBasedModelInterpolator interpolator = new CustomMaven3ModelInterpolator(new DefaultPathTranslator());
interpolator.initialize();
Properties props = MavenServerUtil.collectSystemProperties();
ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props);
config.setBuildStartTime(new Date());
result = interpolator.interpolate(result, basedir, config, false);
}
catch (ModelInterpolationException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
catch (InitializationException e) {
Maven3ServerGlobals.getLogger().error(e);
}
return result;
}
private static Collection<String> collectProfilesIds(List<Profile> profiles) {
Collection<String> result = new THashSet<String>();
for (Profile each : profiles) {
if (each.getId() != null) {
result.add(each.getId());
}
}
return result;
}
private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException {
SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator();
DefaultContext context = new DefaultContext();
context.put("SystemProperties", MavenServerUtil.collectSystemProperties());
try {
sysPropertyActivator.contextualize(context);
}
catch (ContextException e) {
Maven3ServerGlobals.getLogger().error(e);
return new ProfileActivator[0];
}
return new ProfileActivator[]{new MyFileProfileActivator(basedir), sysPropertyActivator, new JdkPrefixProfileActivator(),
new OperatingSystemProfileActivator()};
}
public interface Computable<T> {
T compute();
}
}
| plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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 org.jetbrains.idea.maven.server;
import com.intellij.openapi.util.Comparing;
import com.intellij.util.SystemProperties;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.apache.maven.*;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager;
import org.apache.maven.artifact.resolver.*;
import org.apache.maven.cli.MavenCli;
import org.apache.maven.execution.*;
import org.apache.maven.model.Activation;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.Profile;
import org.apache.maven.model.interpolation.ModelInterpolator;
import org.apache.maven.model.profile.DefaultProfileInjector;
import org.apache.maven.plugin.LegacySupport;
import org.apache.maven.plugin.internal.PluginDependenciesResolver;
import org.apache.maven.profiles.activation.*;
import org.apache.maven.project.*;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.apache.maven.project.inheritance.DefaultModelInheritanceAssembler;
import org.apache.maven.project.interpolation.AbstractStringBasedModelInterpolator;
import org.apache.maven.project.interpolation.ModelInterpolationException;
import org.apache.maven.project.path.DefaultPathTranslator;
import org.apache.maven.project.path.PathTranslator;
import org.apache.maven.project.validation.ModelValidationResult;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.settings.Settings;
import org.apache.maven.settings.building.DefaultSettingsBuildingRequest;
import org.apache.maven.settings.building.SettingsBuilder;
import org.apache.maven.settings.building.SettingsBuildingException;
import org.apache.maven.settings.building.SettingsBuildingRequest;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeResolutionListener;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.classworlds.ClassWorld;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.context.DefaultContext;
import org.codehaus.plexus.logging.BaseLoggerManager;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.model.*;
import org.jetbrains.idea.maven.server.embedder.*;
import org.jetbrains.idea.maven.server.embedder.MavenExecutionResult;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.repository.LocalRepositoryManager;
import org.sonatype.aether.util.DefaultRepositorySystemSession;
import org.sonatype.aether.util.graph.PreorderNodeListGenerator;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
/**
* Overridden maven components:
maven-compat:
org.jetbrains.idea.maven.server.embedder.CustomMaven3RepositoryMetadataManager <-> org.apache.maven.artifact.repository.metadata.DefaultRepositoryMetadataManager
org.jetbrains.idea.maven.server.embedder.CustomMaven3ArtifactResolver <-> org.apache.maven.artifact.resolver.DefaultArtifactResolver
org.jetbrains.idea.maven.server.embedder.CustomMaven3ModelInterpolator <-> org.apache.maven.project.interpolation.StringSearchModelInterpolator
maven-core:
org.jetbrains.idea.maven.server.embedder.CustomMaven3ArtifactFactory <-> org.apache.maven.artifact.factory.DefaultArtifactFactory
org.jetbrains.idea.maven.server.embedder.CustomPluginDescriptorCache <-> org.apache.maven.plugin.DefaultPluginDescriptorCache
maven-model-builder:
org.jetbrains.idea.maven.server.embedder.CustomMaven3ModelInterpolator2 <-> org.apache.maven.model.interpolation.StringSearchModelInterpolator
*/
public class Maven3ServerEmbedderImpl extends MavenRemoteObject implements MavenServerEmbedder {
private final static boolean USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING = System.getProperty("maven3.use.compat.resolver") != null;
@NotNull private final DefaultPlexusContainer myContainer;
@NotNull private final Settings myMavenSettings;
private final ArtifactRepository myLocalRepository;
private final Maven3ServerConsoleLogger myConsoleWrapper;
private final Properties mySystemProperties;
private volatile MavenServerProgressIndicator myCurrentIndicator;
private MavenWorkspaceMap myWorkspaceMap;
private Date myBuildStartTime;
private boolean myAlwaysUpdateSnapshots;
public Maven3ServerEmbedderImpl(MavenServerSettings settings) throws RemoteException {
File mavenHome = settings.getMavenHome();
if (mavenHome != null) {
System.setProperty("maven.home", mavenHome.getPath());
}
myConsoleWrapper = new Maven3ServerConsoleLogger();
myConsoleWrapper.setThreshold(settings.getLoggingLevel());
ClassWorld classWorld = new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
MavenCli cli = new MavenCli(classWorld) {
@Override
protected void customizeContainer(PlexusContainer container) {
((DefaultPlexusContainer)container).setLoggerManager(new BaseLoggerManager() {
@Override
protected Logger createLogger(String s) {
return myConsoleWrapper;
}
});
}
};
Class cliRequestClass;
try {
cliRequestClass = MavenCli.class.getClassLoader().loadClass("org.apache.maven.cli.MavenCli$CliRequest");
}
catch (ClassNotFoundException e) {
throw new RuntimeException("Class \"org.apache.maven.cli.MavenCli$CliRequest\" not found");
}
Object cliRequest;
try {
String[] commandLineOptions = new String[settings.getUserProperties().size()];
int idx = 0;
for (Map.Entry<Object, Object> each : settings.getUserProperties().entrySet()) {
commandLineOptions[idx++] = "-D" + each.getKey() + "=" + each.getValue();
}
Constructor constructor = cliRequestClass.getDeclaredConstructor(String[].class, ClassWorld.class);
constructor.setAccessible(true);
cliRequest = constructor.newInstance(commandLineOptions, classWorld);
for (String each : new String[]{"initialize", "cli", "properties", "container"}) {
Method m = MavenCli.class.getDeclaredMethod(each, cliRequestClass);
m.setAccessible(true);
m.invoke(cli, cliRequest);
}
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
// reset threshold
myContainer = FieldAccessor.get(MavenCli.class, cli, "container");
myContainer.getLoggerManager().setThreshold(settings.getLoggingLevel());
mySystemProperties = FieldAccessor.<Properties>get(cliRequestClass, cliRequest, "systemProperties");
if (settings.getProjectJdk() != null) {
mySystemProperties.setProperty("java.home", settings.getProjectJdk());
}
myMavenSettings =
buildSettings(FieldAccessor.<SettingsBuilder>get(MavenCli.class, cli, "settingsBuilder"), settings, mySystemProperties,
FieldAccessor.<Properties>get(cliRequestClass, cliRequest, "userProperties"));
myLocalRepository = createLocalRepository();
}
private static Settings buildSettings(SettingsBuilder builder,
MavenServerSettings settings,
Properties systemProperties,
Properties userProperties) throws RemoteException {
SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
settingsRequest.setGlobalSettingsFile(settings.getGlobalSettingsFile());
settingsRequest.setUserSettingsFile(settings.getUserSettingsFile());
settingsRequest.setSystemProperties(systemProperties);
settingsRequest.setUserProperties(userProperties);
Settings result = new Settings();
try {
result = builder.build(settingsRequest).getEffectiveSettings();
}
catch (SettingsBuildingException e) {
Maven3ServerGlobals.getLogger().info(e);
}
result.setOffline(settings.isOffline());
if (settings.getLocalRepository() != null) {
result.setLocalRepository(settings.getLocalRepository().getPath());
}
if (result.getLocalRepository() == null) {
result.setLocalRepository(new File(SystemProperties.getUserHome(), ".m2/repository").getPath());
}
return result;
}
@SuppressWarnings({"unchecked"})
public <T> T getComponent(Class<T> clazz, String roleHint) {
try {
return (T)myContainer.lookup(clazz.getName(), roleHint);
}
catch (ComponentLookupException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings({"unchecked"})
public <T> T getComponent(Class<T> clazz) {
try {
return (T)myContainer.lookup(clazz.getName());
}
catch (ComponentLookupException e) {
throw new RuntimeException(e);
}
}
private ArtifactRepository createLocalRepository() {
try {
final ArtifactRepository localRepository =
getComponent(RepositorySystem.class).createLocalRepository(new File(myMavenSettings.getLocalRepository()));
final String customRepoId = System.getProperty("maven3.localRepository.id");
if(customRepoId != null) {
// see details at http://youtrack.jetbrains.com/issue/IDEA-121292
localRepository.setId(customRepoId);
}
return localRepository;
}
catch (InvalidRepositoryException e) {
throw new RuntimeException(e);
// Legacy code.
}
//ArtifactRepositoryLayout layout = getComponent(ArtifactRepositoryLayout.class, "default");
//ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class);
//
//String url = myMavenSettings.getLocalRepository();
//if (!url.startsWith("file:")) url = "file://" + url;
//
//ArtifactRepository localRepository = factory.createArtifactRepository("local", url, layout, null, null);
//
//boolean snapshotPolicySet = myMavenSettings.isOffline();
//if (!snapshotPolicySet && snapshotUpdatePolicy == MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE) {
// factory.setGlobalUpdatePolicy(ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS);
//}
//factory.setGlobalChecksumPolicy(ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);
//
//return localRepository;
}
@Override
public void customize(@Nullable MavenWorkspaceMap workspaceMap,
boolean failOnUnresolvedDependency,
@NotNull MavenServerConsole console,
@NotNull MavenServerProgressIndicator indicator,
boolean alwaysUpdateSnapshots) throws RemoteException {
try {
((CustomMaven3ArtifactFactory)getComponent(ArtifactFactory.class)).customize();
((CustomMaven3ArtifactResolver)getComponent(ArtifactResolver.class)).customize(workspaceMap, failOnUnresolvedDependency);
((CustomMaven3RepositoryMetadataManager)getComponent(RepositoryMetadataManager.class)).customize(workspaceMap);
//((CustomMaven3WagonManager)getComponent(WagonManager.class)).customize(failOnUnresolvedDependency);
myWorkspaceMap = workspaceMap;
myBuildStartTime = new Date();
myAlwaysUpdateSnapshots = alwaysUpdateSnapshots;
setConsoleAndIndicator(console, new MavenServerProgressIndicatorWrapper(indicator));
}
catch (Exception e) {
throw rethrowException(e);
}
}
private void setConsoleAndIndicator(MavenServerConsole console, MavenServerProgressIndicator indicator) {
myConsoleWrapper.setWrappee(console);
myCurrentIndicator = indicator;
}
@NotNull
@Override
public MavenServerExecutionResult resolveProject(@NotNull File file,
@NotNull Collection<String> activeProfiles,
@NotNull Collection<String> inactiveProfiles)
throws RemoteException, MavenServerProcessCanceledException {
DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(myConsoleWrapper);
MavenExecutionResult result = doResolveProject(file, new ArrayList<String>(activeProfiles), new ArrayList<String>(inactiveProfiles),
Arrays.<ResolutionListener>asList(listener));
return createExecutionResult(file, result, listener.getRootNode());
}
@Nullable
@Override
public String evaluateEffectivePom(@NotNull File file, @NotNull List<String> activeProfiles, @NotNull List<String> inactiveProfiles)
throws RemoteException, MavenServerProcessCanceledException {
return MavenEffectivePomDumper.evaluateEffectivePom(this, file, activeProfiles, inactiveProfiles);
}
public void executeWithMavenSession(MavenExecutionRequest request, Runnable runnable) {
DefaultMaven maven = (DefaultMaven)getComponent(Maven.class);
RepositorySystemSession repositorySession = maven.newRepositorySession(request);
request.getProjectBuildingRequest().setRepositorySession(repositorySession);
MavenSession mavenSession = new MavenSession(myContainer, repositorySession, request, new DefaultMavenExecutionResult());
LegacySupport legacySupport = getComponent(LegacySupport.class);
MavenSession oldSession = legacySupport.getSession();
legacySupport.setSession(mavenSession);
/** adapted from {@link org.apache.maven.DefaultMaven#doExecute(org.apache.maven.execution.MavenExecutionRequest)} */
try {
for (AbstractMavenLifecycleParticipant listener : getLifecycleParticipants(Collections.<MavenProject>emptyList())) {
listener.afterSessionStart(mavenSession);
}
}
catch (MavenExecutionException e) {
throw new RuntimeException(e);
}
try {
runnable.run();
}
finally {
legacySupport.setSession(oldSession);
}
}
@NotNull
public MavenExecutionResult doResolveProject(@NotNull final File file,
@NotNull final List<String> activeProfiles,
@NotNull final List<String> inactiveProfiles,
final List<ResolutionListener> listeners) throws RemoteException {
final MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, Collections.<String>emptyList());
request.setUpdateSnapshots(myAlwaysUpdateSnapshots);
final AtomicReference<MavenExecutionResult> ref = new AtomicReference<MavenExecutionResult>();
executeWithMavenSession(request, new Runnable() {
@Override
public void run() {
try {
// copied from DefaultMavenProjectBuilder.buildWithDependencies
ProjectBuilder builder = getComponent(ProjectBuilder.class);
CustomMaven3ModelInterpolator2 modelInterpolator = (CustomMaven3ModelInterpolator2)getComponent(ModelInterpolator.class);
String savedLocalRepository = modelInterpolator.getLocalRepository();
modelInterpolator.setLocalRepository(request.getLocalRepositoryPath().getAbsolutePath());
List<ProjectBuildingResult> results;
try {
// Don't use build(File projectFile, ProjectBuildingRequest request) , because it don't use cache !!!!!!!! (see http://devnet.jetbrains.com/message/5500218)
results = builder.build(Collections.singletonList(new File(file.getPath())), false, request.getProjectBuildingRequest());
}
finally {
modelInterpolator.setLocalRepository(savedLocalRepository);
}
ProjectBuildingResult buildingResult = results.get(0);
MavenProject project = buildingResult.getProject();
RepositorySystemSession repositorySession = getComponent(LegacySupport.class).getRepositorySession();
if (repositorySession instanceof DefaultRepositorySystemSession) {
((DefaultRepositorySystemSession)repositorySession).setTransferListener(new TransferListenerAdapter(myCurrentIndicator));
if (myWorkspaceMap != null) {
((DefaultRepositorySystemSession)repositorySession).setWorkspaceReader(new Maven3WorkspaceReader(myWorkspaceMap));
}
}
List<Exception> exceptions = new ArrayList<Exception>();
loadExtensions(project, exceptions);
//Artifact projectArtifact = project.getArtifact();
//Map managedVersions = project.getManagedVersionMap();
//ArtifactMetadataSource metadataSource = getComponent(ArtifactMetadataSource.class);
project.setDependencyArtifacts(project.createArtifacts(getComponent(ArtifactFactory.class), null, null));
//
if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
resolutionRequest.setArtifactDependencies(project.getDependencyArtifacts());
resolutionRequest.setArtifact(project.getArtifact());
resolutionRequest.setManagedVersionMap(project.getManagedVersionMap());
resolutionRequest.setLocalRepository(myLocalRepository);
resolutionRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
resolutionRequest.setListeners(listeners);
resolutionRequest.setResolveRoot(false);
resolutionRequest.setResolveTransitively(true);
ArtifactResolver resolver = getComponent(ArtifactResolver.class);
ArtifactResolutionResult result = resolver.resolve(resolutionRequest);
project.setArtifacts(result.getArtifacts());
// end copied from DefaultMavenProjectBuilder.buildWithDependencies
ref.set(new MavenExecutionResult(project, exceptions));
}
else {
final DependencyResolutionResult dependencyResolutionResult = resolveDependencies(project, repositorySession);
final List<Dependency> dependencies = dependencyResolutionResult.getDependencies();
Set<Artifact> artifacts = new LinkedHashSet<Artifact>(dependencies.size());
for (Dependency dependency : dependencies) {
final Artifact artifact = RepositoryUtils.toArtifact(dependency.getArtifact());
artifact.setScope(dependency.getScope());
artifact.setOptional(dependency.isOptional());
artifacts.add(artifact);
resolveAsModule(artifact);
}
project.setArtifacts(artifacts);
ref.set(new MavenExecutionResult(project, dependencyResolutionResult, exceptions));
}
}
catch (Exception e) {
ref.set(handleException(e));
}
}
});
return ref.get();
}
private boolean resolveAsModule(Artifact a) {
MavenWorkspaceMap map = myWorkspaceMap;
if (map == null) return false;
MavenWorkspaceMap.Data resolved = map.findFileAndOriginalId(MavenModelConverter.createMavenId(a));
if (resolved == null) return false;
a.setResolved(true);
a.setFile(resolved.getFile(a.getType()));
a.selectVersion(resolved.originalId.getVersion());
return true;
}
/**
* copied from {@link org.apache.maven.project.DefaultProjectBuilder#resolveDependencies(org.apache.maven.project.MavenProject, org.sonatype.aether.RepositorySystemSession)}
*/
private DependencyResolutionResult resolveDependencies(MavenProject project, RepositorySystemSession session) {
DependencyResolutionResult resolutionResult;
try {
ProjectDependenciesResolver dependencyResolver = getComponent(ProjectDependenciesResolver.class);
DefaultDependencyResolutionRequest resolution = new DefaultDependencyResolutionRequest(project, session);
resolutionResult = dependencyResolver.resolve(resolution);
}
catch (DependencyResolutionException e) {
resolutionResult = e.getResult();
}
Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
if (resolutionResult.getDependencyGraph() != null) {
RepositoryUtils.toArtifacts(artifacts, resolutionResult.getDependencyGraph().getChildren(),
Collections.singletonList(project.getArtifact().getId()), null);
// Maven 2.x quirk: an artifact always points at the local repo, regardless whether resolved or not
LocalRepositoryManager lrm = session.getLocalRepositoryManager();
for (Artifact artifact : artifacts) {
if (!artifact.isResolved()) {
String path = lrm.getPathForLocalArtifact(RepositoryUtils.toArtifact(artifact));
artifact.setFile(new File(lrm.getRepository().getBasedir(), path));
}
}
}
project.setResolvedArtifacts(artifacts);
project.setArtifacts(artifacts);
return resolutionResult;
}
/**
* adapted from {@link org.apache.maven.DefaultMaven#doExecute(org.apache.maven.execution.MavenExecutionRequest)}
*/
private void loadExtensions(MavenProject project, List<Exception> exceptions) {
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
Collection<AbstractMavenLifecycleParticipant> lifecycleParticipants = getLifecycleParticipants(Arrays.asList(project));
if (!lifecycleParticipants.isEmpty()) {
LegacySupport legacySupport = getComponent(LegacySupport.class);
MavenSession session = legacySupport.getSession();
session.setCurrentProject(project);
session.setProjects(Arrays.asList(project));
for (AbstractMavenLifecycleParticipant listener : lifecycleParticipants) {
Thread.currentThread().setContextClassLoader(listener.getClass().getClassLoader());
try {
listener.afterProjectsRead(session);
}
catch (MavenExecutionException e) {
exceptions.add(e);
}
finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
}
}
/**
* adapted from {@link org.apache.maven.DefaultMaven#getLifecycleParticipants(java.util.Collection)}
*/
private Collection<AbstractMavenLifecycleParticipant> getLifecycleParticipants(Collection<MavenProject> projects) {
Collection<AbstractMavenLifecycleParticipant> lifecycleListeners = new LinkedHashSet<AbstractMavenLifecycleParticipant>();
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
try {
lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
}
catch (ComponentLookupException e) {
// this is just silly, lookupList should return an empty list!
warn("Failed to lookup lifecycle participants", e);
}
Collection<ClassLoader> scannedRealms = new HashSet<ClassLoader>();
for (MavenProject project : projects) {
ClassLoader projectRealm = project.getClassRealm();
if (projectRealm != null && scannedRealms.add(projectRealm)) {
Thread.currentThread().setContextClassLoader(projectRealm);
try {
lifecycleListeners.addAll(myContainer.lookupList(AbstractMavenLifecycleParticipant.class));
}
catch (ComponentLookupException e) {
// this is just silly, lookupList should return an empty list!
warn("Failed to lookup lifecycle participants", e);
}
}
}
}
finally {
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
return lifecycleListeners;
}
private static void warn(String message, Throwable e) {
try {
Maven3ServerGlobals.getLogger().warn(new RuntimeException(message, e));
}
catch (RemoteException e1) {
throw new RuntimeException(e1);
}
}
public MavenExecutionRequest createRequest(File file, List<String> activeProfiles, List<String> inactiveProfiles, List<String> goals)
throws RemoteException {
//Properties executionProperties = myMavenSettings.getProperties();
//if (executionProperties == null) {
// executionProperties = new Properties();
//}
MavenExecutionRequest result = new DefaultMavenExecutionRequest();
try {
getComponent(MavenExecutionRequestPopulator.class).populateFromSettings(result, myMavenSettings);
result.setGoals(goals);
result.setPom(file);
getComponent(MavenExecutionRequestPopulator.class).populateDefaults(result);
result.setSystemProperties(mySystemProperties);
result.setActiveProfiles(activeProfiles);
result.setInactiveProfiles(inactiveProfiles);
result.setStartTime(myBuildStartTime);
return result;
}
catch (MavenExecutionRequestPopulationException e) {
throw new RuntimeException(e);
}
}
private static MavenExecutionResult handleException(Throwable e) {
if (e instanceof Error) throw (Error)e;
return new MavenExecutionResult(null, Collections.singletonList((Exception)e));
}
@NotNull
public File getLocalRepositoryFile() {
return new File(myLocalRepository.getBasedir());
}
@NotNull
private MavenServerExecutionResult createExecutionResult(File file, MavenExecutionResult result, DependencyNode rootNode)
throws RemoteException {
Collection<MavenProjectProblem> problems = MavenProjectProblem.createProblemsList();
THashSet<MavenId> unresolvedArtifacts = new THashSet<MavenId>();
validate(file, result.getExceptions(), problems, unresolvedArtifacts);
MavenProject mavenProject = result.getMavenProject();
if (mavenProject == null) return new MavenServerExecutionResult(null, problems, unresolvedArtifacts);
MavenModel model = null;
try {
if (USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING) {
//noinspection unchecked
final List<DependencyNode> dependencyNodes = rootNode == null ? Collections.emptyList() : rootNode.getChildren();
model = MavenModelConverter.convertModel(
mavenProject.getModel(), mavenProject.getCompileSourceRoots(), mavenProject.getTestCompileSourceRoots(),
mavenProject.getArtifacts(), dependencyNodes, mavenProject.getExtensionArtifacts(), getLocalRepositoryFile());
}
else {
final DependencyResolutionResult dependencyResolutionResult = result.getDependencyResolutionResult();
final org.sonatype.aether.graph.DependencyNode dependencyGraph =
dependencyResolutionResult != null ? dependencyResolutionResult.getDependencyGraph() : null;
final List<org.sonatype.aether.graph.DependencyNode> dependencyNodes =
dependencyGraph != null ? dependencyGraph.getChildren() : Collections.<org.sonatype.aether.graph.DependencyNode>emptyList();
model = AetherModelConverter.convertModelWithAetherDependencyTree(
mavenProject.getModel(), mavenProject.getCompileSourceRoots(), mavenProject.getTestCompileSourceRoots(),
mavenProject.getArtifacts(), dependencyNodes, mavenProject.getExtensionArtifacts(), getLocalRepositoryFile());
}
}
catch (Exception e) {
validate(mavenProject.getFile(), Collections.singleton(e), problems, null);
}
RemoteNativeMavenProjectHolder holder = new RemoteNativeMavenProjectHolder(mavenProject);
try {
UnicastRemoteObject.exportObject(holder, 0);
}
catch (RemoteException e) {
throw new RuntimeException(e);
}
Collection<String> activatedProfiles = collectActivatedProfiles(mavenProject);
MavenServerExecutionResult.ProjectData data =
new MavenServerExecutionResult.ProjectData(model, MavenModelConverter.convertToMap(mavenProject.getModel()), holder,
activatedProfiles);
return new MavenServerExecutionResult(data, problems, unresolvedArtifacts);
}
private static Collection<String> collectActivatedProfiles(MavenProject mavenProject)
throws RemoteException {
// for some reason project's active profiles do not contain parent's profiles - only local and settings'.
// parent's profiles do not contain settings' profiles.
List<Profile> profiles = new ArrayList<Profile>();
try {
while (mavenProject != null) {
profiles.addAll(mavenProject.getActiveProfiles());
mavenProject = mavenProject.getParent();
}
}
catch (Exception e) {
// don't bother user if maven failed to build parent project
Maven3ServerGlobals.getLogger().info(e);
}
return collectProfilesIds(profiles);
}
private void validate(@NotNull File file,
@NotNull Collection<Exception> exceptions,
@NotNull Collection<MavenProjectProblem> problems,
@Nullable Collection<MavenId> unresolvedArtifacts) throws RemoteException {
for (Throwable each : exceptions) {
Maven3ServerGlobals.getLogger().info(each);
if(each instanceof IllegalStateException && each.getCause() != null) {
each = each.getCause();
}
if (each instanceof InvalidProjectModelException) {
ModelValidationResult modelValidationResult = ((InvalidProjectModelException)each).getValidationResult();
if (modelValidationResult != null) {
for (Object eachValidationProblem : modelValidationResult.getMessages()) {
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), (String)eachValidationProblem));
}
}
else {
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getCause().getMessage()));
}
}
else if (each instanceof ProjectBuildingException) {
String causeMessage = each.getCause() != null ? each.getCause().getMessage() : each.getMessage();
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), causeMessage));
}
else {
problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getMessage()));
}
}
if (unresolvedArtifacts != null) {
unresolvedArtifacts.addAll(retrieveUnresolvedArtifactIds());
}
}
private Set<MavenId> retrieveUnresolvedArtifactIds() {
Set<MavenId> result = new THashSet<MavenId>();
// TODO collect unresolved artifacts
//((CustomMaven3WagonManager)getComponent(WagonManager.class)).getUnresolvedCollector().retrieveUnresolvedIds(result);
//((CustomMaven3ArtifactResolver)getComponent(ArtifactResolver.class)).getUnresolvedCollector().retrieveUnresolvedIds(result);
return result;
}
@NotNull
@Override
public MavenArtifact resolve(@NotNull MavenArtifactInfo info, @NotNull List<MavenRemoteRepository> remoteRepositories)
throws RemoteException, MavenServerProcessCanceledException {
return doResolve(info, remoteRepositories);
}
@NotNull
@Override
public List<MavenArtifact> resolveTransitively(@NotNull List<MavenArtifactInfo> artifacts,
@NotNull List<MavenRemoteRepository> remoteRepositories)
throws RemoteException, MavenServerProcessCanceledException {
try {
Set<Artifact> toResolve = new LinkedHashSet<Artifact>();
for (MavenArtifactInfo each : artifacts) {
toResolve.add(createArtifact(each));
}
Artifact project = getComponent(ArtifactFactory.class).createBuildArtifact("temp", "temp", "666", "pom");
Set<Artifact> res = getComponent(ArtifactResolver.class)
.resolveTransitively(toResolve, project, Collections.EMPTY_MAP, myLocalRepository, convertRepositories(remoteRepositories),
getComponent(ArtifactMetadataSource.class)).getArtifacts();
return MavenModelConverter.convertArtifacts(res, new THashMap<Artifact, MavenArtifact>(), getLocalRepositoryFile());
}
catch (ArtifactResolutionException e) {
Maven3ServerGlobals.getLogger().info(e);
}
catch (ArtifactNotFoundException e) {
Maven3ServerGlobals.getLogger().info(e);
}
catch (Exception e) {
throw rethrowException(e);
}
return Collections.emptyList();
}
@Override
public Collection<MavenArtifact> resolvePlugin(@NotNull final MavenPlugin plugin,
@NotNull final List<MavenRemoteRepository> repositories,
int nativeMavenProjectId,
final boolean transitive) throws RemoteException, MavenServerProcessCanceledException {
try {
Plugin mavenPlugin = new Plugin();
mavenPlugin.setGroupId(plugin.getGroupId());
mavenPlugin.setArtifactId(plugin.getArtifactId());
mavenPlugin.setVersion(plugin.getVersion());
MavenProject project = RemoteNativeMavenProjectHolder.findProjectById(nativeMavenProjectId);
Plugin pluginFromProject = project.getBuild().getPluginsAsMap().get(plugin.getGroupId() + ':' + plugin.getArtifactId());
if (pluginFromProject != null) {
mavenPlugin.setDependencies(pluginFromProject.getDependencies());
}
final MavenExecutionRequest request =
createRequest(null, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList());
DefaultMaven maven = (DefaultMaven)getComponent(Maven.class);
RepositorySystemSession repositorySystemSession = maven.newRepositorySession(request);
PluginDependenciesResolver pluginDependenciesResolver = getComponent(PluginDependenciesResolver.class);
org.sonatype.aether.artifact.Artifact pluginArtifact =
pluginDependenciesResolver.resolve(mavenPlugin, project.getRemotePluginRepositories(), repositorySystemSession);
org.sonatype.aether.graph.DependencyNode node = pluginDependenciesResolver
.resolve(mavenPlugin, pluginArtifact, null, project.getRemotePluginRepositories(), repositorySystemSession);
PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
node.accept(nlg);
List<MavenArtifact> res = new ArrayList<MavenArtifact>();
for (org.sonatype.aether.artifact.Artifact artifact : nlg.getArtifacts(true)) {
if (!Comparing.equal(artifact.getArtifactId(), plugin.getArtifactId()) ||
!Comparing.equal(artifact.getGroupId(), plugin.getGroupId())) {
res.add(MavenModelConverter.convertArtifact(RepositoryUtils.toArtifact(artifact), getLocalRepositoryFile()));
}
}
return res;
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().info(e);
return Collections.emptyList();
}
}
private MavenArtifact doResolve(MavenArtifactInfo info, List<MavenRemoteRepository> remoteRepositories) throws RemoteException {
Artifact resolved = doResolve(createArtifact(info), convertRepositories(remoteRepositories));
return MavenModelConverter.convertArtifact(resolved, getLocalRepositoryFile());
}
private Artifact doResolve(Artifact artifact, List<ArtifactRepository> remoteRepositories) throws RemoteException {
try {
resolve(artifact, remoteRepositories);
return artifact;
}
catch (Exception e) {
Maven3ServerGlobals.getLogger().info(e);
}
return artifact;
}
public void resolve(@NotNull final Artifact artifact, @NotNull final List<ArtifactRepository> repos)
throws ArtifactResolutionException, ArtifactNotFoundException {
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
request.setRemoteRepositories(repos);
try {
getComponent(MavenExecutionRequestPopulator.class).populateFromSettings(request, myMavenSettings);
getComponent(MavenExecutionRequestPopulator.class).populateDefaults(request);
}
catch (MavenExecutionRequestPopulationException e) {
throw new RuntimeException(e);
}
getComponent(ArtifactResolver.class).resolve(artifact, request.getRemoteRepositories(), myLocalRepository);
}
private List<ArtifactRepository> convertRepositories(List<MavenRemoteRepository> repositories) throws RemoteException {
List<ArtifactRepository> result = new ArrayList<ArtifactRepository>();
for (MavenRemoteRepository each : repositories) {
try {
ArtifactRepositoryFactory factory = getComponent(ArtifactRepositoryFactory.class);
result.add(ProjectUtils.buildArtifactRepository(MavenModelConverter.toNativeRepository(each), factory, myContainer));
}
catch (InvalidRepositoryException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
return result;
}
private Artifact createArtifact(MavenArtifactInfo info) {
return getComponent(ArtifactFactory.class)
.createArtifactWithClassifier(info.getGroupId(), info.getArtifactId(), info.getVersion(), info.getPackaging(), info.getClassifier());
}
@NotNull
@Override
public MavenServerExecutionResult execute(@NotNull File file,
@NotNull Collection<String> activeProfiles,
@NotNull Collection<String> inactiveProfiles,
@NotNull List<String> goals,
@NotNull List<String> selectedProjects,
boolean alsoMake,
boolean alsoMakeDependents) throws RemoteException, MavenServerProcessCanceledException {
MavenExecutionResult result =
doExecute(file, new ArrayList<String>(activeProfiles), new ArrayList<String>(inactiveProfiles), goals, selectedProjects, alsoMake,
alsoMakeDependents);
return createExecutionResult(file, result, null);
}
private MavenExecutionResult doExecute(@NotNull final File file,
@NotNull final List<String> activeProfiles,
@NotNull final List<String> inactiveProfiles,
@NotNull final List<String> goals,
@NotNull final List<String> selectedProjects,
boolean alsoMake,
boolean alsoMakeDependents) throws RemoteException {
MavenExecutionRequest request = createRequest(file, activeProfiles, inactiveProfiles, goals);
if (!selectedProjects.isEmpty()) {
request.setRecursive(true);
request.setSelectedProjects(selectedProjects);
if (alsoMake && alsoMakeDependents) {
request.setMakeBehavior(ReactorManager.MAKE_BOTH_MODE);
}
else if (alsoMake) {
request.setMakeBehavior(ReactorManager.MAKE_MODE);
}
else if (alsoMakeDependents) {
request.setMakeBehavior(ReactorManager.MAKE_DEPENDENTS_MODE);
}
}
org.apache.maven.execution.MavenExecutionResult executionResult = safeExecute(request, getComponent(Maven.class));
return new MavenExecutionResult(executionResult.getProject(), filterExceptions(executionResult.getExceptions()));
}
private org.apache.maven.execution.MavenExecutionResult safeExecute(MavenExecutionRequest request, Maven maven) throws RemoteException {
MavenLeakDetector detector = new MavenLeakDetector().mark();
org.apache.maven.execution.MavenExecutionResult result = maven.execute(request);
detector.check();
return result;
}
private static List<Exception> filterExceptions(List<Throwable> list) {
for (Throwable throwable : list) {
if (!(throwable instanceof Exception)) {
throw new RuntimeException(throwable);
}
}
return (List<Exception>)((List)list);
}
@Override
public void reset() throws RemoteException {
try {
setConsoleAndIndicator(null, null);
((CustomMaven3ArtifactFactory)getComponent(ArtifactFactory.class)).reset();
((CustomMaven3ArtifactResolver)getComponent(ArtifactResolver.class)).reset();
((CustomMaven3RepositoryMetadataManager)getComponent(RepositoryMetadataManager.class)).reset();
//((CustomWagonManager)getComponent(WagonManager.class)).reset();
}
catch (Exception e) {
throw rethrowException(e);
}
}
@Override
public void release() throws RemoteException {
myContainer.dispose();
}
public void clearCaches() throws RemoteException {
// do nothing
}
public void clearCachesFor(final MavenId projectId) throws RemoteException {
// do nothing
}
public static MavenModel interpolateAndAlignModel(MavenModel model, File basedir) throws RemoteException {
Model result = MavenModelConverter.toNativeModel(model);
result = doInterpolate(result, basedir);
PathTranslator pathTranslator = new DefaultPathTranslator();
pathTranslator.alignToBaseDirectory(result, basedir);
return MavenModelConverter.convertModel(result, null);
}
public static MavenModel assembleInheritance(MavenModel model, MavenModel parentModel) throws RemoteException {
Model result = MavenModelConverter.toNativeModel(model);
new DefaultModelInheritanceAssembler().assembleModelInheritance(result, MavenModelConverter.toNativeModel(parentModel));
return MavenModelConverter.convertModel(result, null);
}
public static ProfileApplicationResult applyProfiles(MavenModel model,
File basedir,
MavenExplicitProfiles explicitProfiles,
Collection<String> alwaysOnProfiles) throws RemoteException {
Model nativeModel = MavenModelConverter.toNativeModel(model);
Collection<String> enabledProfiles = explicitProfiles.getEnabledProfiles();
Collection<String> disabledProfiles = explicitProfiles.getDisabledProfiles();
List<Profile> activatedPom = new ArrayList<Profile>();
List<Profile> activatedExternal = new ArrayList<Profile>();
List<Profile> activeByDefault = new ArrayList<Profile>();
List<Profile> rawProfiles = nativeModel.getProfiles();
List<Profile> expandedProfilesCache = null;
List<Profile> deactivatedProfiles = new ArrayList<Profile>();
for (int i = 0; i < rawProfiles.size(); i++) {
Profile eachRawProfile = rawProfiles.get(i);
if (disabledProfiles.contains(eachRawProfile.getId())) {
deactivatedProfiles.add(eachRawProfile);
continue;
}
boolean shouldAdd = enabledProfiles.contains(eachRawProfile.getId()) || alwaysOnProfiles.contains(eachRawProfile.getId());
Activation activation = eachRawProfile.getActivation();
if (activation != null) {
if (activation.isActiveByDefault()) {
activeByDefault.add(eachRawProfile);
}
// expand only if necessary
if (expandedProfilesCache == null) expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles();
Profile eachExpandedProfile = expandedProfilesCache.get(i);
for (ProfileActivator eachActivator : getProfileActivators(basedir)) {
try {
if (eachActivator.canDetermineActivation(eachExpandedProfile) && eachActivator.isActive(eachExpandedProfile)) {
shouldAdd = true;
break;
}
}
catch (ProfileActivationException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
}
}
if (shouldAdd) {
if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) {
activatedPom.add(eachRawProfile);
}
else {
activatedExternal.add(eachRawProfile);
}
}
}
List<Profile> activatedProfiles = new ArrayList<Profile>(activatedPom.isEmpty() ? activeByDefault : activatedPom);
activatedProfiles.addAll(activatedExternal);
for (Profile each : activatedProfiles) {
new DefaultProfileInjector().injectProfile(nativeModel, each, null, null);
}
return new ProfileApplicationResult(MavenModelConverter.convertModel(nativeModel, null),
new MavenExplicitProfiles(collectProfilesIds(activatedProfiles),
collectProfilesIds(deactivatedProfiles))
);
}
private static Model doInterpolate(Model result, File basedir) throws RemoteException {
try {
AbstractStringBasedModelInterpolator interpolator = new CustomMaven3ModelInterpolator(new DefaultPathTranslator());
interpolator.initialize();
Properties props = MavenServerUtil.collectSystemProperties();
ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props);
config.setBuildStartTime(new Date());
result = interpolator.interpolate(result, basedir, config, false);
}
catch (ModelInterpolationException e) {
Maven3ServerGlobals.getLogger().warn(e);
}
catch (InitializationException e) {
Maven3ServerGlobals.getLogger().error(e);
}
return result;
}
private static Collection<String> collectProfilesIds(List<Profile> profiles) {
Collection<String> result = new THashSet<String>();
for (Profile each : profiles) {
if (each.getId() != null) {
result.add(each.getId());
}
}
return result;
}
private static ProfileActivator[] getProfileActivators(File basedir) throws RemoteException {
SystemPropertyProfileActivator sysPropertyActivator = new SystemPropertyProfileActivator();
DefaultContext context = new DefaultContext();
context.put("SystemProperties", MavenServerUtil.collectSystemProperties());
try {
sysPropertyActivator.contextualize(context);
}
catch (ContextException e) {
Maven3ServerGlobals.getLogger().error(e);
return new ProfileActivator[0];
}
return new ProfileActivator[]{new MyFileProfileActivator(basedir), sysPropertyActivator, new JdkPrefixProfileActivator(),
new OperatingSystemProfileActivator()};
}
public interface Computable<T> {
T compute();
}
}
| maven: use "idea." prefix for IDEA specific property (maven3.use.compat.resolver)
| plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java | maven: use "idea." prefix for IDEA specific property (maven3.use.compat.resolver) | <ide><path>lugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java
<ide> */
<ide> public class Maven3ServerEmbedderImpl extends MavenRemoteObject implements MavenServerEmbedder {
<ide>
<del> private final static boolean USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING = System.getProperty("maven3.use.compat.resolver") != null;
<add> private final static boolean USE_MVN2_COMPATIBLE_DEPENDENCY_RESOLVING = System.getProperty("idea.maven3.use.compat.resolver") != null;
<ide>
<ide> @NotNull private final DefaultPlexusContainer myContainer;
<ide> @NotNull private final Settings myMavenSettings; |
|
Java | apache-2.0 | 2ba1a0fd02aefef5d59dbdb7cd8a6c3ec6083d3c | 0 | Dark-Keeper/ModsAndMaps | package com.darkkeeper.minecraft.mods;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.appodeal.ads.Appodeal;
/*import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Random;
//import com.google.firebase.analytics.FirebaseAnalytics;
import com.appodeal.ads.BannerCallbacks;
import com.appodeal.ads.BannerView;
import com.appodeal.ads.InterstitialCallbacks;
import com.backendless.Backendless;
import com.backendless.exceptions.BackendlessFault;
import com.darkkeeper.minecraft.mods.entity.DatabaseManager;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
/**
* Created by Dark Keeper on 29.03.2016.
*/
public class BaseActivity extends AppCompatActivity {
/* private Tracker globalTracker;*/
public static String BACKENDLESS_ID = "CB0EF57E-5CF2-1505-FF6A-C070AF81DA00";
public static String BACKENDLESS_SECRET_KEY = "091E1EA1-2543-89FC-FF96-A3EFF6815500";
public final static String APP_VERSION = "v1";
public final static String DEFAULT_LANGUAGE = "en";
public static String CURRENT_LANGUAGE = "en";
protected Tracker globalTracker;
public final static String INTENT_UPDATE = "UPDATE_APP";
protected boolean canShowCommercial = false;
private boolean isBannerShowing = false;
// private static FirebaseAnalytics mFirebaseAnalytics;
private static int backPressedCount = 1;
private Toast toast = null;
private static boolean isActivityVisible;
private List<DatabaseManager> databaseManagers;
private int currentDatabaseManager;
@Override
protected void onResume() {
super.onResume();
isActivityVisible = true;
isBannerShowing = false;
try {
BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );
bannerView1.setVisibility(View.GONE);
} catch (Exception e){
}
try {
BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );
bannerView2.setVisibility(View.GONE);
} catch (Exception e){
}
showBanner(this);
}
@Override
protected void onPause() {
super.onPause();
isActivityVisible = false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch ( item.getItemId() ){
case android.R.id.home:
logFirebaseEvent("Back");
onBackPressed();
return true;
case R.id.action_share:
logFirebaseEvent( "Share" );
canShowCommercial = true;
showInterestial( this );
share( this );
return true;
case R.id.action_rate:
logFirebaseEvent( "Rate" );
canShowCommercial = true;
showInterestial( this );
rate( this );
return true;
case R.id.action_help:
logFirebaseEvent( "Help" );
/* canShowCommercial = true;
showInterestial( this );*/
help( this );
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed(){
super.onBackPressed();
canShowCommercial = true;
showInterestial( this );
/* backPressedCount++;
if ( (3 + backPressedCount)%3 == 0 ){
canShowCommercial = true;
showInterestial( this );
}
super.onBackPressed();*/
}
protected boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
protected void getSystemLanguage (){
CURRENT_LANGUAGE = Locale.getDefault().getLanguage();
}
/* private enum DatabaseIDs {
CB0EF57E-5CF2-1505-FF6A-C070AF81DA00,
"6F1ECA67-ED6D-AC96-FF09-E1C77B2D9C00",
"905AC9E7-ED52-9182-FF6F-617EE08A5700"
}
public enum Gender {
MALE,
FEMALE
}
private Enum DatabaseSecretKeys{
<item>091E1EA1-2543-89FC-FF96-A3EFF6815500</item>
<item>B5480EA7-C95B-9DBF-FF73-9F6F5AAC0700</item>
<item>DA9BFD7A-DD1C-9712-FFFA-B00EC9CA2A00</item>
}*/
protected void setDatabaseManagers() {
databaseManagers = new ArrayList<>(3);
Random r = new Random();
currentDatabaseManager = r.nextInt(3)-1; //should give a number between -1 inclusive and 1 inclusive (3 variants)
//currentDatabaseManager = -1; //should be -1 to start from 0 cause of ++
databaseManagers.add( new DatabaseManager("CB0EF57E-5CF2-1505-FF6A-C070AF81DA00",
"091E1EA1-2543-89FC-FF96-A3EFF6815500"));
databaseManagers.add( new DatabaseManager("6F1ECA67-ED6D-AC96-FF09-E1C77B2D9C00",
"B5480EA7-C95B-9DBF-FF73-9F6F5AAC0700"));
databaseManagers.add( new DatabaseManager("905AC9E7-ED52-9182-FF6F-617EE08A5700",
"DA9BFD7A-DD1C-9712-FFFA-B00EC9CA2A00"));
}
protected void initNextDatabase (){
if ( currentDatabaseManager < (databaseManagers.size()-1) ) {
currentDatabaseManager++;
BACKENDLESS_ID = databaseManagers.get(currentDatabaseManager).getDatabaseID();
BACKENDLESS_SECRET_KEY = databaseManagers.get(currentDatabaseManager).getDatabaseSecretKey();
Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);
} else {
currentDatabaseManager=0; //should be 0
BACKENDLESS_ID = databaseManagers.get(currentDatabaseManager).getDatabaseID();
BACKENDLESS_SECRET_KEY = databaseManagers.get(currentDatabaseManager).getDatabaseSecretKey();
Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);
}
// Log.d("MY_LOGS", "ChangeDatabase to " + currentDatabaseManager );
}
/* protected void initDatabase () {
Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);
}*/
protected void initAds () {
String appKey = getResources().getString(R.string.appodeal_id);
Appodeal.confirm(Appodeal.SKIPPABLE_VIDEO);
// Appodeal.disableNetwork(this, "cheetah");
/* Appodeal.disableNetwork(this, "yandex");
Appodeal.disableNetwork(this, "unity_ads");
Appodeal.disableNetwork(this, "chartboost");*/
// Appodeal.disableNetwork(this, "adcolony");
Appodeal.initialize(this, appKey, Appodeal.BANNER_BOTTOM | Appodeal.INTERSTITIAL | Appodeal.SKIPPABLE_VIDEO );
}
protected void initGoogleAnalytics ( Context context ) {
// mFirebaseAnalytics = FirebaseAnalytics.getInstance( context );
GoogleAnalytics analytics = GoogleAnalytics.getInstance(context);
globalTracker = analytics.newTracker( R.xml.global_tracker );
globalTracker.setScreenName(getPackageName());
globalTracker.send(new HitBuilders.ScreenViewBuilder().build());
/* globalTracker.send(new HitBuilders.EventBuilder()
.setCategory("BackendlessFault")
.setAction( "test" )
.setLabel( "test" )
.build());*/
}
private void logFirebaseEvent ( String event ){
globalTracker.send(new HitBuilders.EventBuilder()
.setCategory(event)
.setAction( "Toolbar Button Clicked" )
.setLabel(event + " Clicked from Toolbar")
.build());
/* Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, event);
// bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, event);
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
}
protected void showInterestial ( Context context ) {
// Log.d("MY_LOGS2", "CAN_SHOW = " + canShowCommercial );
if (canShowCommercial) {
Appodeal.show((Activity) context, Appodeal.INTERSTITIAL );
}
}
protected void showBanner ( Context context ) {
// Log.d("MY_LOGS2", "CAN_SHOW = " + canShowCommercial );
// isBannerShowing = false;
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
}
protected void setAppodealCallbacks ( final Context context ) {
Appodeal.setInterstitialCallbacks(new InterstitialCallbacks() {
private Toast mToast;
@Override
public void onInterstitialLoaded(boolean isPrecache) {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialFailedToLoad() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialShown() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialClicked() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialClosed() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
});
Appodeal.setBannerCallbacks(new BannerCallbacks() {
private Toast mToast;
@Override
public void onBannerLoaded(int height, boolean isPrecache) {
// showToast(String.format("onBannerLoaded, %ddp" + isBannerShowing, height));
/* if ( !isBannerShowing && Appodeal.isLoaded(Appodeal.BANNER_BOTTOM)){
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
isBannerShowing = true;
}*/
}
@Override
public void onBannerFailedToLoad() {
// showToast("onBannerFailedToLoad");
}
@Override
public void onBannerShown() {
/* try {
BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );
bannerView1.setVisibility(View.VISIBLE);
} catch (Exception e){
}
try {
BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );
bannerView2.setVisibility(View.VISIBLE);
NestedScrollView nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView2);
Log.d("MY_LOGS", "heights = " + nestedScrollView.getLayoutParams().height);
nestedScrollView.getLayoutParams().height += 50;
Log.d("MY_LOGS", "heights = " + nestedScrollView.getLayoutParams().height);
nestedScrollView.invalidate();
} catch (Exception e){
Log.d("MY_LOGS", "ERROR = " + e.toString());
e.printStackTrace();
}*/
// showToast("onBannerShown");
}
@Override
public void onBannerClicked() {
// showToast("onBannerClicked");
}
void showToast(final String text) {
if (mToast == null) {
mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
});
}
/* protected void showAdsOnStart ( Context context ) {
Appodeal.show((Activity) context, Appodeal.INTERSTITIAL);
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
}*/
protected void showPermissionDialog ( final Context context ) {
AlertDialog.Builder permissions = new AlertDialog.Builder( context );
permissions.setMessage(R.string.showPermissionMessage)
.setTitle(R.string.notificationMessage)
.setCancelable(false)
.setPositiveButton(R.string.answerOk,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions((MainActivity) context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return;
}
}
);
AlertDialog alert = permissions.create();
alert.show();
}
protected void showInetRequirementMessage ( final Context context ) {
/* if ()
AlertDialog.Builder permissions = new AlertDialog.Builder( context );
permissions.setMessage("You need Internet Connection to use this application. Enable your Internet and try again!")
.setTitle("Notification")
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
return;
}
}
);
AlertDialog alert = permissions.create();
alert.show();*/
if (isActivityVisible) {
try {
toast.getView().isShown();
toast.setText(R.string.networkReq);
} catch (Exception e) {
toast = Toast.makeText(context, R.string.networkReq, Toast.LENGTH_SHORT);
}
toast.show();
}
/* if ( toast==null || toast.getView().getWindowVisibility() != View.GONE ) {
toast = Toast.makeText(context, "Network is Unnavailable", Toast.LENGTH_SHORT);
toast.show();
Log.d("LOGS", "" + toast + " VISIBILITY = " + toast.getView().getWindowVisibility() + " isShown = " + toast.getView().isShown() + " getWindowToken = " + toast.getView().getWindowToken());
}*/
}
protected void showErrorDialog ( final Context context ) {
AlertDialog.Builder builder = new AlertDialog.Builder( context );
builder.setMessage(R.string.errorMessage)
.setTitle(R.string.errorTitle)
.setCancelable(false)
.setPositiveButton(R.string.answerOk,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
protected void showExitDialog ( Context context ) {
Appodeal.show((Activity) context, Appodeal.SKIPPABLE_VIDEO | Appodeal.INTERSTITIAL );
AlertDialog.Builder exit = new AlertDialog.Builder( context );
exit.setMessage(R.string.exitText)
.setTitle(R.string.exitQuestion)
.setCancelable(false)
.setPositiveButton(R.string.answerYes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
}
)
.setNegativeButton(R.string.answerNo,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
);
AlertDialog alert = exit.create();
alert.show();
}
protected void showUpdateDialog ( final Context context ) {
AlertDialog.Builder alert = new AlertDialog.Builder( context );
alert.setMessage(R.string.updateMessage)
.setTitle(R.string.updateTitle)
.setCancelable(false)
.setPositiveButton(R.string.answerInstallNow,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName()));
context.startActivity(i);
}
}
)
.setNegativeButton(R.string.answerLater,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
return;
}
}
);
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
protected void rate ( Context context ) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName()));
context.startActivity(i);
}
protected void share ( Context context ) {
PackageManager pm = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
List<Intent> targetedShareIntents = new ArrayList<Intent>();
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
String urlToShare = context.getString( context.getApplicationInfo().labelRes) + getString(R.string.shareMessage) + "https://play.google.com/store/apps/details?id=" + context.getPackageName();
Intent chooserIntent;
boolean isTargetsFound = false;
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
targetedShare.setType("text/plain");
if (info.activityInfo.packageName.toLowerCase().contains("facebook") || info.activityInfo.name.toLowerCase().contains("facebook") || info.activityInfo.packageName.toLowerCase().contains("twitter") || info.activityInfo.name.toLowerCase().contains("twitter") || info.activityInfo.packageName.toLowerCase().contains("vk") || info.activityInfo.name.toLowerCase().contains("vk") || info.activityInfo.packageName.toLowerCase().contains("kate") || info.activityInfo.name.toLowerCase().contains("kate")) {
targetedShare.putExtra(Intent.EXTRA_TEXT, urlToShare );
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
isTargetsFound = true;
}
}
if ( isTargetsFound ) {
chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), getString(R.string.sharePickApp));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
} else
{
/*String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
chooserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));*/
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
targetedShare.setType("text/plain");
targetedShare.putExtra(Intent.EXTRA_TEXT, urlToShare );
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), getString(R.string.sharePickApp));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
}
context.startActivity(chooserIntent);
}
}
protected void help ( final Context context ) {
Intent i = new Intent( context, HelpActivity.class );
context.startActivity(i);
/* AlertDialog.Builder rate = new AlertDialog.Builder( context );
String helpMessage = "Thank you for downloading " + context.getResources().getString( R.string.app_name ) + "!" + "\n" + "\n" +
"Report any bug to [email protected] and leave five stars on the store! " + "\n" + "\n" +
"Have fun!" + "\n" + "\n" +
"Developer: Andrei Piatosin"
;
rate.setMessage( helpMessage )
.setTitle("Help")
.setCancelable(false)
.setNegativeButton("Rate me!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData( Uri.parse( "https://play.google.com/store/apps/details?id=" + context.getPackageName() ) );
context.startActivity(i);
}
}
)
.setNeutralButton("Report",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sendEmail( context );
return;
}
}
)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
);
AlertDialog alert = rate.create();
alert.show();*/
}
protected void sendEmail( Context context ){
Intent myIntent1 = new Intent(android.content.Intent.ACTION_SEND);
myIntent1.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
final String my1 = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.ANDROID_ID);
final String my2 = android.os.Build.DEVICE;
final String my3 = android.os.Build.MANUFACTURER;
final String my4 = android.os.Build.MODEL;
final String my5 = android.os.Build.VERSION.RELEASE;
final int my6 = android.os.Build.VERSION.SDK_INT;
final String my7 = android.os.Build.BRAND;
final String my8 = android.os.Build.VERSION.INCREMENTAL;
final String my9 = android.os.Build.PRODUCT;
myIntent1.putExtra(android.content.Intent.EXTRA_SUBJECT, "Support Request: " + my1 + " Application: " + context.getPackageName() + " Device: " + my2 + " Manufacturer: " + my3 + " Model: " + my4 + " Version: " + my5 + " SDK: " + my6 + " Brand: " + my7 + " Incremental: " + my8 + " Product: " + my9);
myIntent1.setType("text/plain");
//IN CASE EMAIL APP FAILS, THEN DEFINE THE OPTION TO LAUNCH SUPPORT WEBSITE
String url2 = "";
Intent myIntent2 = new Intent(Intent.ACTION_VIEW);
myIntent2.setData(Uri.parse(url2));
//IF USER CLICKS THE OK BUTTON, THEN DO THIS
try {
// TRY TO LAUNCH TO EMAIL APP
context.startActivity(Intent.createChooser(myIntent1, "Send email to Developer"));
// startActivity(myIntent1);
} catch (ActivityNotFoundException ex) {
// ELSE LAUNCH TO WEB BROWSER
// activity.startActivity(myIntent2);
}
}
protected boolean isPermissionGranted (){
return ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ;
}
protected void sendBackendlessFaultToAnalytics (Tracker globalTracker, String action, BackendlessFault fault){
globalTracker.send(new HitBuilders.EventBuilder()
.setCategory("BackendlessFault")
.setAction( action )
.setLabel( fault.getMessage() )
.build());
}
}
| app/src/main/java/com/darkkeeper/minecraft/mods/BaseActivity.java | package com.darkkeeper.minecraft.mods;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.appodeal.ads.Appodeal;
/*import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Random;
//import com.google.firebase.analytics.FirebaseAnalytics;
import com.appodeal.ads.BannerCallbacks;
import com.appodeal.ads.BannerView;
import com.appodeal.ads.InterstitialCallbacks;
import com.backendless.Backendless;
import com.backendless.exceptions.BackendlessFault;
import com.darkkeeper.minecraft.mods.entity.DatabaseManager;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
/**
* Created by Dark Keeper on 29.03.2016.
*/
public class BaseActivity extends AppCompatActivity {
/* private Tracker globalTracker;*/
public static String BACKENDLESS_ID = "CB0EF57E-5CF2-1505-FF6A-C070AF81DA00";
public static String BACKENDLESS_SECRET_KEY = "091E1EA1-2543-89FC-FF96-A3EFF6815500";
public final static String APP_VERSION = "v1";
public final static String DEFAULT_LANGUAGE = "en";
public static String CURRENT_LANGUAGE = "en";
protected Tracker globalTracker;
public final static String INTENT_UPDATE = "UPDATE_APP";
protected boolean canShowCommercial = false;
private boolean isBannerShowing = false;
// private static FirebaseAnalytics mFirebaseAnalytics;
private static int backPressedCount = 1;
private Toast toast = null;
private static boolean isActivityVisible;
private List<DatabaseManager> databaseManagers;
private int currentDatabaseManager;
@Override
protected void onResume() {
super.onResume();
isActivityVisible = true;
isBannerShowing = false;
try {
BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );
bannerView1.setVisibility(View.GONE);
} catch (Exception e){
}
try {
BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );
bannerView2.setVisibility(View.GONE);
} catch (Exception e){
}
showBanner(this);
}
@Override
protected void onPause() {
super.onPause();
isActivityVisible = false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch ( item.getItemId() ){
case android.R.id.home:
logFirebaseEvent("Back");
onBackPressed();
return true;
case R.id.action_share:
logFirebaseEvent( "Share" );
canShowCommercial = true;
showInterestial( this );
share( this );
return true;
case R.id.action_rate:
logFirebaseEvent( "Rate" );
canShowCommercial = true;
showInterestial( this );
rate( this );
return true;
case R.id.action_help:
logFirebaseEvent( "Help" );
/* canShowCommercial = true;
showInterestial( this );*/
help( this );
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed(){
super.onBackPressed();
canShowCommercial = true;
showInterestial( this );
/* backPressedCount++;
if ( (3 + backPressedCount)%3 == 0 ){
canShowCommercial = true;
showInterestial( this );
}
super.onBackPressed();*/
}
protected boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
protected void getSystemLanguage (){
CURRENT_LANGUAGE = Locale.getDefault().getLanguage();
}
/* private enum DatabaseIDs {
CB0EF57E-5CF2-1505-FF6A-C070AF81DA00,
"6F1ECA67-ED6D-AC96-FF09-E1C77B2D9C00",
"905AC9E7-ED52-9182-FF6F-617EE08A5700"
}
public enum Gender {
MALE,
FEMALE
}
private Enum DatabaseSecretKeys{
<item>091E1EA1-2543-89FC-FF96-A3EFF6815500</item>
<item>B5480EA7-C95B-9DBF-FF73-9F6F5AAC0700</item>
<item>DA9BFD7A-DD1C-9712-FFFA-B00EC9CA2A00</item>
}*/
protected void setDatabaseManagers() {
databaseManagers = new ArrayList<>(3);
Random r = new Random();
currentDatabaseManager = r.nextInt(3)-1; //should give a number between -1 inclusive and 1 inclusive (3 variants)
//currentDatabaseManager = -1; //should be -1 to start from 0 cause of ++
databaseManagers.add( new DatabaseManager("CB0EF57E-5CF2-1505-FF6A-C070AF81DA00",
"091E1EA1-2543-89FC-FF96-A3EFF6815500"));
databaseManagers.add( new DatabaseManager("6F1ECA67-ED6D-AC96-FF09-E1C77B2D9C00",
"B5480EA7-C95B-9DBF-FF73-9F6F5AAC0700"));
databaseManagers.add( new DatabaseManager("905AC9E7-ED52-9182-FF6F-617EE08A5700",
"DA9BFD7A-DD1C-9712-FFFA-B00EC9CA2A00"));
}
protected void initNextDatabase (){
if ( currentDatabaseManager < (databaseManagers.size()-1) ) {
currentDatabaseManager++;
BACKENDLESS_ID = databaseManagers.get(currentDatabaseManager).getDatabaseID();
BACKENDLESS_SECRET_KEY = databaseManagers.get(currentDatabaseManager).getDatabaseSecretKey();
Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);
} else {
currentDatabaseManager=0; //should be 0
BACKENDLESS_ID = databaseManagers.get(currentDatabaseManager).getDatabaseID();
BACKENDLESS_SECRET_KEY = databaseManagers.get(currentDatabaseManager).getDatabaseSecretKey();
Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);
}
// Log.d("MY_LOGS", "ChangeDatabase to " + currentDatabaseManager );
}
/* protected void initDatabase () {
Backendless.initApp(this, BACKENDLESS_ID, BACKENDLESS_SECRET_KEY, APP_VERSION);
}*/
protected void initAds () {
String appKey = getResources().getString(R.string.appodeal_id);
Appodeal.confirm(Appodeal.SKIPPABLE_VIDEO);
// Appodeal.disableNetwork(this, "cheetah");
/* Appodeal.disableNetwork(this, "yandex");
Appodeal.disableNetwork(this, "unity_ads");
Appodeal.disableNetwork(this, "chartboost");*/
// Appodeal.disableNetwork(this, "adcolony");
Appodeal.initialize(this, appKey, Appodeal.BANNER_BOTTOM | Appodeal.INTERSTITIAL | Appodeal.SKIPPABLE_VIDEO );
}
protected void initGoogleAnalytics ( Context context ) {
// mFirebaseAnalytics = FirebaseAnalytics.getInstance( context );
GoogleAnalytics analytics = GoogleAnalytics.getInstance(context);
globalTracker = analytics.newTracker( R.xml.global_tracker );
globalTracker.setScreenName(getPackageName());
globalTracker.send(new HitBuilders.ScreenViewBuilder().build());
/* globalTracker.send(new HitBuilders.EventBuilder()
.setCategory("BackendlessFault")
.setAction( "test" )
.setLabel( "test" )
.build());*/
}
private void logFirebaseEvent ( String event ){
globalTracker.send(new HitBuilders.EventBuilder()
.setCategory(event)
.setAction( "Toolbar Button Clicked" )
.setLabel(event + " Clicked from Toolbar")
.build());
/* Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, event);
// bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, event);
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
}
protected void showInterestial ( Context context ) {
// Log.d("MY_LOGS2", "CAN_SHOW = " + canShowCommercial );
if (canShowCommercial) {
Appodeal.show((Activity) context, Appodeal.SKIPPABLE_VIDEO| Appodeal.INTERSTITIAL );
}
}
protected void showBanner ( Context context ) {
// Log.d("MY_LOGS2", "CAN_SHOW = " + canShowCommercial );
// isBannerShowing = false;
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
}
protected void setAppodealCallbacks ( final Context context ) {
Appodeal.setInterstitialCallbacks(new InterstitialCallbacks() {
private Toast mToast;
@Override
public void onInterstitialLoaded(boolean isPrecache) {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialFailedToLoad() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialShown() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialClicked() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
@Override
public void onInterstitialClosed() {
canShowCommercial = false;
// Log.d("LOG_D", "CanShowCommercial = " + canShowCommercial);
}
});
Appodeal.setBannerCallbacks(new BannerCallbacks() {
private Toast mToast;
@Override
public void onBannerLoaded(int height, boolean isPrecache) {
// showToast(String.format("onBannerLoaded, %ddp" + isBannerShowing, height));
/* if ( !isBannerShowing && Appodeal.isLoaded(Appodeal.BANNER_BOTTOM)){
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
isBannerShowing = true;
}*/
}
@Override
public void onBannerFailedToLoad() {
// showToast("onBannerFailedToLoad");
}
@Override
public void onBannerShown() {
/* try {
BannerView bannerView1 = (BannerView) findViewById( R.id.appodealBannerView );
bannerView1.setVisibility(View.VISIBLE);
} catch (Exception e){
}
try {
BannerView bannerView2 = (BannerView) findViewById( R.id.appodealBannerView2 );
bannerView2.setVisibility(View.VISIBLE);
NestedScrollView nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView2);
Log.d("MY_LOGS", "heights = " + nestedScrollView.getLayoutParams().height);
nestedScrollView.getLayoutParams().height += 50;
Log.d("MY_LOGS", "heights = " + nestedScrollView.getLayoutParams().height);
nestedScrollView.invalidate();
} catch (Exception e){
Log.d("MY_LOGS", "ERROR = " + e.toString());
e.printStackTrace();
}*/
// showToast("onBannerShown");
}
@Override
public void onBannerClicked() {
// showToast("onBannerClicked");
}
void showToast(final String text) {
if (mToast == null) {
mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
});
}
/* protected void showAdsOnStart ( Context context ) {
Appodeal.show((Activity) context, Appodeal.INTERSTITIAL);
Appodeal.show((Activity) context, Appodeal.BANNER_BOTTOM);
}*/
protected void showPermissionDialog ( final Context context ) {
AlertDialog.Builder permissions = new AlertDialog.Builder( context );
permissions.setMessage(R.string.showPermissionMessage)
.setTitle(R.string.notificationMessage)
.setCancelable(false)
.setPositiveButton(R.string.answerOk,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions((MainActivity) context, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return;
}
}
);
AlertDialog alert = permissions.create();
alert.show();
}
protected void showInetRequirementMessage ( final Context context ) {
/* if ()
AlertDialog.Builder permissions = new AlertDialog.Builder( context );
permissions.setMessage("You need Internet Connection to use this application. Enable your Internet and try again!")
.setTitle("Notification")
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
return;
}
}
);
AlertDialog alert = permissions.create();
alert.show();*/
if (isActivityVisible) {
try {
toast.getView().isShown();
toast.setText(R.string.networkReq);
} catch (Exception e) {
toast = Toast.makeText(context, R.string.networkReq, Toast.LENGTH_SHORT);
}
toast.show();
}
/* if ( toast==null || toast.getView().getWindowVisibility() != View.GONE ) {
toast = Toast.makeText(context, "Network is Unnavailable", Toast.LENGTH_SHORT);
toast.show();
Log.d("LOGS", "" + toast + " VISIBILITY = " + toast.getView().getWindowVisibility() + " isShown = " + toast.getView().isShown() + " getWindowToken = " + toast.getView().getWindowToken());
}*/
}
protected void showErrorDialog ( final Context context ) {
AlertDialog.Builder builder = new AlertDialog.Builder( context );
builder.setMessage(R.string.errorMessage)
.setTitle(R.string.errorTitle)
.setCancelable(false)
.setPositiveButton(R.string.answerOk,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
protected void showExitDialog ( Context context ) {
Appodeal.show((Activity) context, Appodeal.SKIPPABLE_VIDEO | Appodeal.INTERSTITIAL );
AlertDialog.Builder exit = new AlertDialog.Builder( context );
exit.setMessage(R.string.exitText)
.setTitle(R.string.exitQuestion)
.setCancelable(false)
.setPositiveButton(R.string.answerYes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
}
)
.setNegativeButton(R.string.answerNo,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
);
AlertDialog alert = exit.create();
alert.show();
}
protected void showUpdateDialog ( final Context context ) {
AlertDialog.Builder alert = new AlertDialog.Builder( context );
alert.setMessage(R.string.updateMessage)
.setTitle(R.string.updateTitle)
.setCancelable(false)
.setPositiveButton(R.string.answerInstallNow,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName()));
context.startActivity(i);
}
}
)
.setNegativeButton(R.string.answerLater,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
return;
}
}
);
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
protected void rate ( Context context ) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName()));
context.startActivity(i);
}
protected void share ( Context context ) {
PackageManager pm = context.getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
List<Intent> targetedShareIntents = new ArrayList<Intent>();
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
String urlToShare = context.getString( context.getApplicationInfo().labelRes) + getString(R.string.shareMessage) + "https://play.google.com/store/apps/details?id=" + context.getPackageName();
Intent chooserIntent;
boolean isTargetsFound = false;
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
targetedShare.setType("text/plain");
if (info.activityInfo.packageName.toLowerCase().contains("facebook") || info.activityInfo.name.toLowerCase().contains("facebook") || info.activityInfo.packageName.toLowerCase().contains("twitter") || info.activityInfo.name.toLowerCase().contains("twitter") || info.activityInfo.packageName.toLowerCase().contains("vk") || info.activityInfo.name.toLowerCase().contains("vk") || info.activityInfo.packageName.toLowerCase().contains("kate") || info.activityInfo.name.toLowerCase().contains("kate")) {
targetedShare.putExtra(Intent.EXTRA_TEXT, urlToShare );
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
isTargetsFound = true;
}
}
if ( isTargetsFound ) {
chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), getString(R.string.sharePickApp));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
} else
{
/*String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
chooserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));*/
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
targetedShare.setType("text/plain");
targetedShare.putExtra(Intent.EXTRA_TEXT, urlToShare );
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), getString(R.string.sharePickApp));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
}
context.startActivity(chooserIntent);
}
}
protected void help ( final Context context ) {
Intent i = new Intent( context, HelpActivity.class );
context.startActivity(i);
/* AlertDialog.Builder rate = new AlertDialog.Builder( context );
String helpMessage = "Thank you for downloading " + context.getResources().getString( R.string.app_name ) + "!" + "\n" + "\n" +
"Report any bug to [email protected] and leave five stars on the store! " + "\n" + "\n" +
"Have fun!" + "\n" + "\n" +
"Developer: Andrei Piatosin"
;
rate.setMessage( helpMessage )
.setTitle("Help")
.setCancelable(false)
.setNegativeButton("Rate me!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setData( Uri.parse( "https://play.google.com/store/apps/details?id=" + context.getPackageName() ) );
context.startActivity(i);
}
}
)
.setNeutralButton("Report",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sendEmail( context );
return;
}
}
)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
}
);
AlertDialog alert = rate.create();
alert.show();*/
}
protected void sendEmail( Context context ){
Intent myIntent1 = new Intent(android.content.Intent.ACTION_SEND);
myIntent1.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
final String my1 = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.ANDROID_ID);
final String my2 = android.os.Build.DEVICE;
final String my3 = android.os.Build.MANUFACTURER;
final String my4 = android.os.Build.MODEL;
final String my5 = android.os.Build.VERSION.RELEASE;
final int my6 = android.os.Build.VERSION.SDK_INT;
final String my7 = android.os.Build.BRAND;
final String my8 = android.os.Build.VERSION.INCREMENTAL;
final String my9 = android.os.Build.PRODUCT;
myIntent1.putExtra(android.content.Intent.EXTRA_SUBJECT, "Support Request: " + my1 + " Application: " + context.getPackageName() + " Device: " + my2 + " Manufacturer: " + my3 + " Model: " + my4 + " Version: " + my5 + " SDK: " + my6 + " Brand: " + my7 + " Incremental: " + my8 + " Product: " + my9);
myIntent1.setType("text/plain");
//IN CASE EMAIL APP FAILS, THEN DEFINE THE OPTION TO LAUNCH SUPPORT WEBSITE
String url2 = "";
Intent myIntent2 = new Intent(Intent.ACTION_VIEW);
myIntent2.setData(Uri.parse(url2));
//IF USER CLICKS THE OK BUTTON, THEN DO THIS
try {
// TRY TO LAUNCH TO EMAIL APP
context.startActivity(Intent.createChooser(myIntent1, "Send email to Developer"));
// startActivity(myIntent1);
} catch (ActivityNotFoundException ex) {
// ELSE LAUNCH TO WEB BROWSER
// activity.startActivity(myIntent2);
}
}
protected boolean isPermissionGranted (){
return ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ;
}
protected void sendBackendlessFaultToAnalytics (Tracker globalTracker, String action, BackendlessFault fault){
globalTracker.send(new HitBuilders.EventBuilder()
.setCategory("BackendlessFault")
.setAction( action )
.setLabel( fault.getMessage() )
.build());
}
}
| 4 mods added
appodeal networks fix
appodeal networks added
install epansion fix with new dialog
| app/src/main/java/com/darkkeeper/minecraft/mods/BaseActivity.java | 4 mods added appodeal networks fix appodeal networks added | <ide><path>pp/src/main/java/com/darkkeeper/minecraft/mods/BaseActivity.java
<ide> protected void showInterestial ( Context context ) {
<ide> // Log.d("MY_LOGS2", "CAN_SHOW = " + canShowCommercial );
<ide> if (canShowCommercial) {
<del> Appodeal.show((Activity) context, Appodeal.SKIPPABLE_VIDEO| Appodeal.INTERSTITIAL );
<add> Appodeal.show((Activity) context, Appodeal.INTERSTITIAL );
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | 04901260a8133b3c706b27d3f58d8d1962263d7d | 0 | Raistlfiren/bolt,cdowdy/bolt,Intendit/bolt,joshuan/bolt,rarila/bolt,romulo1984/bolt,Intendit/bolt,lenvanessen/bolt,Raistlfiren/bolt,joshuan/bolt,lenvanessen/bolt,nikgo/bolt,cdowdy/bolt,nikgo/bolt,romulo1984/bolt,Intendit/bolt,electrolinux/bolt,HonzaMikula/masivnipostele,lenvanessen/bolt,nikgo/bolt,HonzaMikula/masivnipostele,CarsonF/bolt,GawainLynch/bolt,bolt/bolt,bolt/bolt,rarila/bolt,cdowdy/bolt,lenvanessen/bolt,GawainLynch/bolt,nikgo/bolt,GawainLynch/bolt,CarsonF/bolt,romulo1984/bolt,Raistlfiren/bolt,romulo1984/bolt,electrolinux/bolt,HonzaMikula/masivnipostele,rarila/bolt,cdowdy/bolt,electrolinux/bolt,Intendit/bolt,GawainLynch/bolt,CarsonF/bolt,CarsonF/bolt,joshuan/bolt,HonzaMikula/masivnipostele,electrolinux/bolt,Raistlfiren/bolt,bolt/bolt,rarila/bolt,bolt/bolt,joshuan/bolt | /**
* @param {Object} $ - Global jQuery object
*/
(function ($) {
'use strict';
/**
* Interval definition.
*
* @memberOf jQuery.widget.bolt.baseInterval
* @typedef {Object} Interval
* @property {integer} id - Resource id returned by setInterval()
* @property {integer} delay - Update delay
* @property {Object} callbacks - List of update callbacks
*/
/**
* Interval data.
*
* @memberOf jQuery.widget.bolt.baseInterval
* @static
* @type {Object.<string, Interval>}
*/
var interval = {};
/**
* Base interval widget.
*
* @license http://opensource.org/licenses/mit-license.php MIT License
* @author rarila
*
* @class baseInterval
* @memberOf jQuery.widget.bolt
* @param {object} [options] - Options to overide.
*/
$.widget('bolt.baseInterval', /** @lends jQuery.widget.bolt.baseInterval.prototype */ {
/**
* Default options.
*
* @property {integer} delay - Initial update delay, shared by all instances
*/
options: {
delay: 10 * 1000 // 10 seconds
},
/**
* The constructor of the base interval widget.
*
* @private
*/
_create: function () {
var self = this,
name = this.widgetName;
// Set up a interval timer used by all activity panel widgets, if not already done.
if (!interval[name]) {
var callbacks = $.Callbacks(),
id = setInterval(callbacks.fire, this.options.delay);
interval[name] = {
id: id,
delay: this.options.delay,
callbacks: callbacks
};
}
// Add the update function to the callback stack.
this._fncUpdate = function () {
self._update();
};
interval[name].callbacks.add(this._fncUpdate);
},
/**
* Cleaning up.
*
* @private
*/
_destroy: function () {
var name = this.widgetName;
// Remove the update function from the update list.
interval[name].callbacks.remove(this._fncUpdate);
// Remove the interval timer if that was the last moment.
if (!interval[name].callbacks.has()) {
clearInterval(interval[name].id);
delete interval[name];
}
}
});
})(jQuery);
| app/src/js/widgets/base/baseInterval.js | /**
* @param {Object} $ - Global jQuery object
*/
(function ($) {
'use strict';
/**
* Interval definition.
*
* @memberOf jQuery.widget.bolt.baseInterval
* @typedef {Object} Interval
* @property {integer} id - Resource id returned by setInterval()
* @property {integer} delay - Update delay
* @property {Object} callbacks - List of update callbacks
*/
/**
* Interval data.
*
* @memberOf jQuery.widget.bolt.baseInterval
* @static
* @type {Object.<string, Interval>}
*/
var interval = {};
/**
* Base interval widget.
*
* @license http://opensource.org/licenses/mit-license.php MIT License
* @author rarila
*
* @class baseInterval
* @memberOf jQuery.widget.bolt
* @param {object} [options] - Options to overide.
*/
$.widget('bolt.baseInterval', /** @lends jQuery.widget.bolt.baseInterval.prototype */ {
/**
* Default options.
*
* @property {integer} delay - Initial update delay, shared by all instances
*/
options: {
delay: 10 * 1000 // 10 seconds
},
/**
* The constructor of the activity panel widget.
*
* @private
*/
_create: function () {
var self = this,
name = this.widgetName;
// Set up a interval timer used by all activity panel widgets, if not already done.
if (!interval[name]) {
var callbacks = $.Callbacks(),
id = setInterval(callbacks.fire, this.options.delay);
interval[name] = {
id: id,
delay: this.options.delay,
callbacks: callbacks
};
}
// Add the update function to the callback stack.
this._fncUpdate = function () {
self._update();
};
interval[name].callbacks.add(this._fncUpdate);
},
/**
* Cleaning up.
*
* @private
*/
_destroy: function () {
var name = this.widgetName;
// Remove the update function from the update list.
interval[name].callbacks.remove(this._fncUpdate);
// Remove the interval timer if that was the last moment.
if (!interval[name].callbacks.has()) {
clearInterval(interval[name].id);
delete interval[name];
}
}
});
})(jQuery);
| Fix docu | app/src/js/widgets/base/baseInterval.js | Fix docu | <ide><path>pp/src/js/widgets/base/baseInterval.js
<ide> },
<ide>
<ide> /**
<del> * The constructor of the activity panel widget.
<add> * The constructor of the base interval widget.
<ide> *
<ide> * @private
<ide> */ |
|
Java | agpl-3.0 | error: pathspec 'jpos/src/main/org/jpos/q2/QFactory.java' did not match any file(s) known to git
| 2c42251234451801ac447d9e82195c63b29fe498 | 1 | barspi/jPOS,yinheli/jPOS,barspi/jPOS,poynt/jPOS,jpos/jPOS,sebastianpacheco/jPOS,imam-san/jPOS-1,atancasis/jPOS,fayezasar/jPOS,alcarraz/jPOS,juanibdn/jPOS,c0deh4xor/jPOS,imam-san/jPOS-1,fayezasar/jPOS,yinheli/jPOS,c0deh4xor/jPOS,chhil/jPOS,bharavi/jPOS,chhil/jPOS,sebastianpacheco/jPOS,atancasis/jPOS,imam-san/jPOS-1,juanibdn/jPOS,jpos/jPOS,alcarraz/jPOS,alcarraz/jPOS,bharavi/jPOS,poynt/jPOS,poynt/jPOS,atancasis/jPOS,barspi/jPOS,jpos/jPOS,sebastianpacheco/jPOS,yinheli/jPOS,juanibdn/jPOS,c0deh4xor/jPOS,bharavi/jPOS | /*
* Copyright (c) 2000 jPOS.org. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the jPOS project
* (http://www.jpos.org/)". Alternately, this acknowledgment may
* appear in the software itself, if and wherever such third-party
* acknowledgments normally appear.
*
* 4. The names "jPOS" and "jPOS.org" must not be used to endorse
* or promote products derived from this software without prior
* written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "jPOS",
* nor may "jPOS" appear in their name, without prior written
* permission of the jPOS project.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE JPOS PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the jPOS Project. For more
* information please see <http://www.jpos.org/>.
*/
package org.jpos.q2;
import java.io.File;
import java.io.FileFilter;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import javax.management.Attribute;
import javax.management.ObjectName;
import javax.management.MBeanServer;
import javax.management.MBeanException;
import javax.management.MBeanServerFactory;
import org.jdom.Element;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
/**
* @author <a href="mailto:[email protected]">Alireza Taherkordi</a>
* @author <a href="mailto:[email protected]">Alejandro P. Revilla</a>
*/
public class QFactory {
public static QBean createQBean (Q2 server, Element e)
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException
{
QBean qbean = null;
String className = e.getAttributeValue ("class");
Class c = Class.forName (className);
Object obj = c.newInstance ();
if (obj instanceof QBean) {
qbean = (QBean) obj;
initQBean (server, qbean, e);
}
return qbean;
}
public static void initQBean (Q2 server, QBean q, Element e) {
q.setServer (server);
q.init (e);
q.start ();
}
}
| jpos/src/main/org/jpos/q2/QFactory.java | Helper class - creates QBeans
| jpos/src/main/org/jpos/q2/QFactory.java | Helper class - creates QBeans | <ide><path>pos/src/main/org/jpos/q2/QFactory.java
<add>/*
<add> * Copyright (c) 2000 jPOS.org. All rights reserved.
<add> *
<add> * Redistribution and use in source and binary forms, with or without
<add> * modification, are permitted provided that the following conditions
<add> * are met:
<add> *
<add> * 1. Redistributions of source code must retain the above copyright
<add> * notice, this list of conditions and the following disclaimer.
<add> *
<add> * 2. Redistributions in binary form must reproduce the above copyright
<add> * notice, this list of conditions and the following disclaimer in
<add> * the documentation and/or other materials provided with the
<add> * distribution.
<add> *
<add> * 3. The end-user documentation included with the redistribution,
<add> * if any, must include the following acknowledgment:
<add> * "This product includes software developed by the jPOS project
<add> * (http://www.jpos.org/)". Alternately, this acknowledgment may
<add> * appear in the software itself, if and wherever such third-party
<add> * acknowledgments normally appear.
<add> *
<add> * 4. The names "jPOS" and "jPOS.org" must not be used to endorse
<add> * or promote products derived from this software without prior
<add> * written permission. For written permission, please contact
<add> * [email protected].
<add> *
<add> * 5. Products derived from this software may not be called "jPOS",
<add> * nor may "jPOS" appear in their name, without prior written
<add> * permission of the jPOS project.
<add> *
<add> * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
<add> * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
<add> * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
<add> * IN NO EVENT SHALL THE JPOS PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR
<add> * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
<add> * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
<add> * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
<add> * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
<add> * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
<add> * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
<add> * POSSIBILITY OF SUCH DAMAGE.
<add> * ====================================================================
<add> *
<add> * This software consists of voluntary contributions made by many
<add> * individuals on behalf of the jPOS Project. For more
<add> * information please see <http://www.jpos.org/>.
<add> */
<add>
<add>package org.jpos.q2;
<add>
<add>
<add>import java.io.File;
<add>import java.io.FileFilter;
<add>import java.util.Map;
<add>import java.util.Date;
<add>import java.util.HashMap;
<add>import java.util.Iterator;
<add>import javax.management.Attribute;
<add>import javax.management.ObjectName;
<add>import javax.management.MBeanServer;
<add>import javax.management.MBeanException;
<add>import javax.management.MBeanServerFactory;
<add>
<add>import org.jdom.Element;
<add>import org.jdom.Document;
<add>import org.jdom.JDOMException;
<add>import org.jdom.input.SAXBuilder;
<add>import org.jdom.output.XMLOutputter;
<add>
<add>/**
<add> * @author <a href="mailto:[email protected]">Alireza Taherkordi</a>
<add> * @author <a href="mailto:[email protected]">Alejandro P. Revilla</a>
<add> */
<add>public class QFactory {
<add> public static QBean createQBean (Q2 server, Element e)
<add> throws ClassNotFoundException,
<add> InstantiationException,
<add> IllegalAccessException
<add> {
<add> QBean qbean = null;
<add> String className = e.getAttributeValue ("class");
<add>
<add> Class c = Class.forName (className);
<add>
<add> Object obj = c.newInstance ();
<add> if (obj instanceof QBean) {
<add> qbean = (QBean) obj;
<add> initQBean (server, qbean, e);
<add> }
<add> return qbean;
<add> }
<add>
<add> public static void initQBean (Q2 server, QBean q, Element e) {
<add> q.setServer (server);
<add> q.init (e);
<add> q.start ();
<add> }
<add>}
<add> |
|
Java | epl-1.0 | 460be5487feb931b7f4aa261a502715fd83bd362 | 0 | brunchboy/beat-link | package org.deepsymmetry.beatlink.data;
import org.deepsymmetry.beatlink.Util;
import org.deepsymmetry.beatlink.dbserver.BinaryField;
import org.deepsymmetry.beatlink.dbserver.Message;
import org.deepsymmetry.cratedigger.pdb.RekordboxAnlz;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* Provides information about each beat in a track: the number of milliseconds after the start of the track that
* the beat occurs, and where the beat falls within a measure.
*
* @author James Elliott
*/
public class BeatGrid {
/**
* The unique identifier that was used to request this beat grid.
*/
@SuppressWarnings("WeakerAccess")
public final DataReference dataReference;
/**
* The message field holding the raw bytes of the beat grid as it was read over the network.
*/
private final ByteBuffer rawData;
/**
* Get the raw bytes of the beat grid as it was read over the network. This can be used to analyze fields
* that have not yet been reliably understood, and is also used for storing the beat grid in a cache file.
* This is not available when the beat grid was loaded by Crate Digger.
*
* @return the bytes that make up the beat grid
*/
@SuppressWarnings("WeakerAccess")
public ByteBuffer getRawData() {
if (rawData != null) {
rawData.rewind();
return rawData.slice();
}
return null;
}
/**
* The number of beats in the track.
*/
@SuppressWarnings("WeakerAccess")
public final int beatCount;
/**
* Holds the reported musical count of each beat.
*/
private final int[] beatWithinBarValues;
/**
* Holds the reported tempo of each beat.
*/
private final int[] bpmValues;
/**
* Holds the reported start time of each beat in milliseconds.
*/
private final long[] timeWithinTrackValues;
/**
* Constructor for when reading from the network.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param message the response that contained the beat grid data
*/
public BeatGrid(DataReference reference, Message message) {
this(reference, ((BinaryField) message.arguments.get(3)).getValue());
}
/**
* Constructor for reading from a cache file.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param buffer the raw bytes representing the beat grid
*/
public BeatGrid(DataReference reference, ByteBuffer buffer) {
dataReference = reference;
rawData = buffer;
final byte[] gridBytes = new byte[rawData.remaining()];
rawData.get(gridBytes);
beatCount = Math.max(0, (gridBytes.length - 20) / 16); // Handle the case of an empty beat grid
beatWithinBarValues = new int[beatCount];
bpmValues = new int[beatCount];
timeWithinTrackValues = new long[beatCount];
for (int beatNumber = 0; beatNumber < beatCount; beatNumber++) {
final int base = 20 + beatNumber * 16; // Data for the current beat starts here
// For some reason, unlike nearly every other number in the protocol, beat timings are little-endian
beatWithinBarValues[beatNumber] = (int)Util.bytesToNumberLittleEndian(gridBytes, base, 2);
bpmValues[beatNumber] = (int)Util.bytesToNumberLittleEndian(gridBytes, base + 2, 2);
timeWithinTrackValues[beatNumber] = Util.bytesToNumberLittleEndian(gridBytes, base + 4, 4);
}
}
/**
* Helper function to find the beat grid section in a rekordbox track analysis file.
*
* @param anlzFile the file that was downloaded from the player
*
* @return the section containing the beat grid
*/
private RekordboxAnlz.BeatGridTag findTag(RekordboxAnlz anlzFile) {
for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) {
if (section.body() instanceof RekordboxAnlz.BeatGridTag) {
return (RekordboxAnlz.BeatGridTag) section.body();
}
}
throw new IllegalArgumentException("No beat grid found inside analysis file " + anlzFile);
}
/**
* Constructor for when fetched from Crate Digger.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param anlzFile the parsed rekordbox track analysis file containing the waveform preview
*/
public BeatGrid(DataReference reference, RekordboxAnlz anlzFile) {
dataReference = reference;
rawData = null;
RekordboxAnlz.BeatGridTag tag = findTag(anlzFile);
beatCount = (int)tag.lenBeats();
beatWithinBarValues = new int[beatCount];
bpmValues = new int[beatCount];
timeWithinTrackValues = new long[beatCount];
for (int beatNumber = 0; beatNumber < beatCount; beatNumber++) {
RekordboxAnlz.BeatGridBeat beat = tag.beats().get(beatNumber);
beatWithinBarValues[beatNumber] = beat.beatNumber();
bpmValues[beatNumber] = beat.tempo();
timeWithinTrackValues[beatNumber] = beat.time();
}
}
/**
* Constructor for use by an external cache system.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param beatWithinBarValues the musical time on which each beat in the grid falls
* @param bpmValues the tempo of the track at each beat, as beats per minute multiplied by 100
* @param timeWithinTrackValues the time, in milliseconds, at which each beat occurs in the track
*/
public BeatGrid(DataReference reference, int[] beatWithinBarValues, int[] bpmValues, long[] timeWithinTrackValues) {
dataReference = reference;
rawData = null;
beatCount = beatWithinBarValues.length;
if (beatCount != timeWithinTrackValues.length) {
throw new IllegalArgumentException("Arrays must contain the same number of beats.");
}
this.beatWithinBarValues = new int[beatCount];
System.arraycopy(beatWithinBarValues, 0, this.beatWithinBarValues, 0, beatCount);
this.bpmValues = new int[beatCount];
System.arraycopy(bpmValues, 0, this.bpmValues, 0, beatCount);
this.timeWithinTrackValues = new long[beatCount];
System.arraycopy(timeWithinTrackValues, 0, this.timeWithinTrackValues, 0, beatCount);
}
/**
* Calculate where within the beat grid array the information for the specified beat can be found.
* Yes, this is a super simple calculation; the main point of the method is to provide a nice exception
* when the beat is out of bounds.
*
* @param beatNumber the beat desired
*
* @return the offset of the start of our cache arrays for information about that beat
*/
private int beatOffset(int beatNumber) {
if (beatCount == 0) {
throw new IllegalStateException("There are no beats in this beat grid.");
}
if (beatNumber < 1 || beatNumber > beatCount) {
throw new IndexOutOfBoundsException("beatNumber (" + beatNumber + ") must be between 1 and " + beatCount);
}
return beatNumber - 1;
}
/**
* Returns the time at which the specified beat falls within the track. Beat 0 means we are before the
* first beat (e.g. ready to play the track), so we return 0.
*
* @param beatNumber the beat number desired, must fall within the range 1..beatCount
*
* @return the number of milliseconds into the track at which the specified beat occurs
*
* @throws IllegalArgumentException if {@code number} is less than 0 or greater than {@code beatCount}
*/
public long getTimeWithinTrack(int beatNumber) {
if (beatNumber == 0) {
return 0;
}
return timeWithinTrackValues[beatOffset(beatNumber)];
}
/**
* Returns the musical count of the specified beat, represented by <i>B<sub>b</sub></i> in
* the <a href="https://djl-analysis.deepsymmetry.org/djl-analysis/vcdj.html#cdj-status-packets">Packet Analysis document</a>.
* A number from 1 to 4, where 1 is the down beat, or the start of a new measure.
*
* @param beatNumber the number of the beat of interest, must fall within the range 1..beatCount
*
* @return where that beat falls in a bar of music
*
* @throws IllegalArgumentException if {@code number} is less than 1 or greater than {@code beatCount}
*/
public int getBeatWithinBar(int beatNumber) {
return beatWithinBarValues[beatOffset(beatNumber)];
}
/**
* Get the track BPM at the time of a beat. This is an integer representing the BPM times 100, so a track running
* at 120.5 BPM would be represented by the value 12050.
*
* @param beatNumber the beat number desired, must fall within the range 1..beatCount
*
* @return the track BPM at the specified beat number to two decimal places multiplied by 100
*/
public int getBpm(int beatNumber) {
return bpmValues[beatOffset(beatNumber)];
}
/**
* Finds the beat in which the specified track position falls.
*
* @param milliseconds how long the track has been playing
*
* @return the beat number represented by that time, or -1 if the time is before the first beat
*/
@SuppressWarnings("WeakerAccess")
public int findBeatAtTime(long milliseconds) {
int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);
if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number
return found + 1;
} else if (found == -1) { // We are before the first beat
return found;
} else { // We are after some beat, report its beat number
return -(found + 1);
}
}
@Override
public String toString() {
return "BeatGrid[dataReference:" + dataReference + ", beats:" + beatCount + "]";
}
}
| src/main/java/org/deepsymmetry/beatlink/data/BeatGrid.java | package org.deepsymmetry.beatlink.data;
import org.deepsymmetry.beatlink.Util;
import org.deepsymmetry.beatlink.dbserver.BinaryField;
import org.deepsymmetry.beatlink.dbserver.Message;
import org.deepsymmetry.cratedigger.pdb.RekordboxAnlz;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* Provides information about each beat in a track: the number of milliseconds after the start of the track that
* the beat occurs, and where the beat falls within a measure.
*
* @author James Elliott
*/
public class BeatGrid {
/**
* The unique identifier that was used to request this beat grid.
*/
@SuppressWarnings("WeakerAccess")
public final DataReference dataReference;
/**
* The message field holding the raw bytes of the beat grid as it was read over the network.
*/
private final ByteBuffer rawData;
/**
* Get the raw bytes of the beat grid as it was read over the network. This can be used to analyze fields
* that have not yet been reliably understood, and is also used for storing the beat grid in a cache file.
* This is not available when the beat grid was loaded by Crate Digger.
*
* @return the bytes that make up the beat grid
*/
@SuppressWarnings("WeakerAccess")
public ByteBuffer getRawData() {
if (rawData != null) {
rawData.rewind();
return rawData.slice();
}
return null;
}
/**
* The number of beats in the track.
*/
@SuppressWarnings("WeakerAccess")
public final int beatCount;
/**
* Holds the reported musical count of each beat.
*/
private final int[] beatWithinBarValues;
/**
* Holds the reported tempo of each beat.
*/
private final int[] bpmValues;
/**
* Holds the reported start time of each beat in milliseconds.
*/
private final long[] timeWithinTrackValues;
/**
* Constructor for when reading from the network.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param message the response that contained the beat grid data
*/
public BeatGrid(DataReference reference, Message message) {
this(reference, ((BinaryField) message.arguments.get(3)).getValue());
}
/**
* Constructor for reading from a cache file.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param buffer the raw bytes representing the beat grid
*/
public BeatGrid(DataReference reference, ByteBuffer buffer) {
dataReference = reference;
rawData = buffer;
final byte[] gridBytes = new byte[rawData.remaining()];
rawData.get(gridBytes);
beatCount = Math.max(0, (gridBytes.length - 20) / 16); // Handle the case of an empty beat grid
beatWithinBarValues = new int[beatCount];
bpmValues = new int[beatCount];
timeWithinTrackValues = new long[beatCount];
for (int beatNumber = 0; beatNumber < beatCount; beatNumber++) {
final int base = 20 + beatNumber * 16; // Data for the current beat starts here
// For some reason, unlike nearly every other number in the protocol, beat timings are little-endian
beatWithinBarValues[beatNumber] = (int)Util.bytesToNumberLittleEndian(gridBytes, base, 2);
bpmValues[beatNumber] = (int)Util.bytesToNumberLittleEndian(gridBytes, base + 2, 2);
timeWithinTrackValues[beatNumber] = Util.bytesToNumberLittleEndian(gridBytes, base + 4, 4);
}
}
/**
* Helper function to find the beat grid section in a rekordbox track analysis file.
*
* @param anlzFile the file that was downloaded from the player
*
* @return the section containing the beat grid
*/
private RekordboxAnlz.BeatGridTag findTag(RekordboxAnlz anlzFile) {
for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) {
if (section.body() instanceof RekordboxAnlz.BeatGridTag) {
return (RekordboxAnlz.BeatGridTag) section.body();
}
}
throw new IllegalArgumentException("No beat grid found inside analysis file " + anlzFile);
}
/**
* Constructor for when fetched from Crate Digger.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param anlzFile the parsed rekordbox track analysis file containing the waveform preview
*/
public BeatGrid(DataReference reference, RekordboxAnlz anlzFile) {
dataReference = reference;
rawData = null;
RekordboxAnlz.BeatGridTag tag = findTag(anlzFile);
beatCount = (int)tag.lenBeats();
beatWithinBarValues = new int[beatCount];
bpmValues = new int[beatCount];
timeWithinTrackValues = new long[beatCount];
for (int beatNumber = 0; beatNumber < beatCount; beatNumber++) {
RekordboxAnlz.BeatGridBeat beat = tag.beats().get(beatNumber);
beatWithinBarValues[beatNumber] = beat.beatNumber();
bpmValues[beatNumber] = beat.tempo();
timeWithinTrackValues[beatNumber] = beat.time();
}
}
/**
* Constructor for use by an external cache system.
*
* @param reference the unique database reference that was used to request this waveform detail
* @param beatWithinBarValues the musical time on which each beat in the grid falls
* @param bpmValues the tempo of the track at each beat, as beats per minute multiplied by 100
* @param timeWithinTrackValues the time, in milliseconds, at which each beat occurs in the track
*/
public BeatGrid(DataReference reference, int[] beatWithinBarValues, int[] bpmValues, long[] timeWithinTrackValues) {
dataReference = reference;
rawData = null;
beatCount = beatWithinBarValues.length;
if (beatCount != timeWithinTrackValues.length) {
throw new IllegalArgumentException("Arrays must contain the same number of beats.");
}
this.beatWithinBarValues = new int[beatCount];
System.arraycopy(beatWithinBarValues, 0, this.beatWithinBarValues, 0, beatCount);
this.bpmValues = new int[beatCount];
System.arraycopy(bpmValues, 0, this.bpmValues, 0, beatCount);
this.timeWithinTrackValues = new long[beatCount];
System.arraycopy(timeWithinTrackValues, 0, this.timeWithinTrackValues, 0, beatCount);
}
/**
* Calculate where within the beat grid array the information for the specified beat can be found.
* Yes, this is a super simple calculation; the main point of the method is to provide a nice exception
* when the beat is out of bounds.
*
* @param beatNumber the beat desired
*
* @return the offset of the start of our cache arrays for information about that beat
*/
private int beatOffset(int beatNumber) {
if (beatCount == 0) {
throw new IllegalStateException("There are no beats in this beat grid.");
}
if (beatNumber < 1 || beatNumber > beatCount) {
throw new IndexOutOfBoundsException("beatNumber (" + beatNumber + ") must be between 1 and " + beatCount);
}
return beatNumber - 1;
}
/**
* Returns the time at which the specified beat falls within the track. Beat 0 means we are before the
* first beat (e.g. ready to play the track), so we return 0.
*
* @param beatNumber the beat number desired, must fall within the range 1..beatCount
*
* @return the number of milliseconds into the track at which the specified beat occurs
*
* @throws IllegalArgumentException if {@code number} is less than 0 or greater than {@code beatCount}
*/
public long getTimeWithinTrack(int beatNumber) {
if (beatNumber == 0) {
return 0;
}
return timeWithinTrackValues[beatOffset(beatNumber)];
}
/**
* Returns the musical count of the specified beat, represented by <i>B<sub>b</sub></i> in
* the <a href="https://djl-analysis.deepsymmetry.org/djl-analysis/vcdj.html#cdj-status-packets">Packet Analysis document</a>.
* A number from 1 to 4, where 1 is the down beat, or the start of a new measure.
*
* @param beatNumber the number of the beat of interest, must fall within the range 1..beatCount
*
* @return where that beat falls in a bar of music
*
* @throws IllegalArgumentException if {@code number} is less than 1 or greater than {@code beatCount}
*/
public int getBeatWithinBar(int beatNumber) {
return beatWithinBarValues[beatOffset(beatNumber)];
}
/**
* Get the track BPM at the time of a beat. This is an integer representing the BPM times 100, so a track running
* at 120.5 BPM would be represented by the value 12050.
*
* @return the track BPM at the specified beat number to two decimal places multiplied by 100
*/
public int getBpm(int beatNumber) {
return bpmValues[beatOffset(beatNumber)];
}
/**
* Finds the beat in which the specified track position falls.
*
* @param milliseconds how long the track has been playing
*
* @return the beat number represented by that time, or -1 if the time is before the first beat
*/
@SuppressWarnings("WeakerAccess")
public int findBeatAtTime(long milliseconds) {
int found = Arrays.binarySearch(timeWithinTrackValues, milliseconds);
if (found >= 0) { // An exact match, just change 0-based array index to 1-based beat number
return found + 1;
} else if (found == -1) { // We are before the first beat
return found;
} else { // We are after some beat, report its beat number
return -(found + 1);
}
}
@Override
public String toString() {
return "BeatGrid[dataReference:" + dataReference + ", beats:" + beatCount + "]";
}
}
| Add missing param to javadoc.
| src/main/java/org/deepsymmetry/beatlink/data/BeatGrid.java | Add missing param to javadoc. | <ide><path>rc/main/java/org/deepsymmetry/beatlink/data/BeatGrid.java
<ide> * Get the track BPM at the time of a beat. This is an integer representing the BPM times 100, so a track running
<ide> * at 120.5 BPM would be represented by the value 12050.
<ide> *
<add> * @param beatNumber the beat number desired, must fall within the range 1..beatCount
<add> *
<ide> * @return the track BPM at the specified beat number to two decimal places multiplied by 100
<ide> */
<ide> public int getBpm(int beatNumber) { |
|
Java | apache-2.0 | c58e224b7e63d94d9bd801c708c2b0215a8c33bf | 0 | huuthang1993/netty,menacher/netty,drowning/netty,gerdriesselmann/netty,Kingson4Wu/netty,IBYoung/netty,DolphinZhao/netty,phlizik/netty,ninja-/netty,lukw00/netty,nadeeshaan/netty,mx657649013/netty,ichaki5748/netty,junjiemars/netty,ejona86/netty,serioussam/netty,caoyanwei/netty,bob329/netty,seetharamireddy540/netty,tbrooks8/netty,golovnin/netty,kyle-liu/netty4study,CodingFabian/netty,bob329/netty,hyangtack/netty,Apache9/netty,fenik17/netty,Mounika-Chirukuri/netty,nkhuyu/netty,kjniemi/netty,luyiisme/netty,normanmaurer/netty,carl-mastrangelo/netty,nayato/netty,chanakaudaya/netty,daschl/netty,lznhust/netty,Spikhalskiy/netty,Kingson4Wu/netty,dongjiaqiang/netty,kvr000/netty,mubarak/netty,ichaki5748/netty,ninja-/netty,bob329/netty,AchinthaReemal/netty,zxhfirefox/netty,DavidAlphaFox/netty,ngocdaothanh/netty,idelpivnitskiy/netty,dongjiaqiang/netty,zzcclp/netty,huuthang1993/netty,lugt/netty,shuangqiuan/netty,carl-mastrangelo/netty,ifesdjeen/netty,firebase/netty,gigold/netty,Scottmitch/netty,caoyanwei/netty,artgon/netty,Kalvar/netty,orika/netty,bigheary/netty,DolphinZhao/netty,chrisprobst/netty,nat2013/netty,slandelle/netty,exinguu/netty,ioanbsu/netty,smayoorans/netty,djchen/netty,maliqq/netty,mosoft521/netty,qingsong-xu/netty,timboudreau/netty,mway08/netty,johnou/netty,skyao/netty,NiteshKant/netty,lightsocks/netty,junjiemars/netty,sverkera/netty,olupotd/netty,liyang1025/netty,mcanthony/netty,kvr000/netty,jongyeol/netty,DolphinZhao/netty,kjniemi/netty,fantayeneh/netty,normanmaurer/netty,lukw00/netty,Alwayswithme/netty,qingsong-xu/netty,lukehutch/netty,alkemist/netty,chinayin/netty,Squarespace/netty,WangJunTYTL/netty,louiscryan/netty,fenik17/netty,Techcable/netty,carl-mastrangelo/netty,f7753/netty,nadeeshaan/netty,afds/netty,bob329/netty,smayoorans/netty,youprofit/netty,ichaki5748/netty,nayato/netty,seetharamireddy540/netty,yawkat/netty,maliqq/netty,moyiguket/netty,lugt/netty,olupotd/netty,orika/netty,ichaki5748/netty,s-gheldd/netty,jongyeol/netty,mosoft521/netty,SinaTadayon/netty,qingsong-xu/netty,gerdriesselmann/netty,netty/netty,mcobrien/netty,zer0se7en/netty,ninja-/netty,s-gheldd/netty,LuminateWireless/netty,zxhfirefox/netty,Scottmitch/netty,windie/netty,castomer/netty,normanmaurer/netty,hyangtack/netty,danny200309/netty,xiexingguang/netty,wuxiaowei907/netty,lightsocks/netty,develar/netty,AchinthaReemal/netty,carlbai/netty,shism/netty,bob329/netty,yrcourage/netty,nadeeshaan/netty,silvaran/netty,SinaTadayon/netty,CodingFabian/netty,afds/netty,fenik17/netty,IBYoung/netty,louxiu/netty,fantayeneh/netty,mubarak/netty,Kalvar/netty,unei66/netty,Apache9/netty,lugt/netty,mx657649013/netty,sameira/netty,satishsaley/netty,IBYoung/netty,doom369/netty,silvaran/netty,s-gheldd/netty,BrunoColin/netty,luyiisme/netty,LuminateWireless/netty,Apache9/netty,imangry/netty-zh,KatsuraKKKK/netty,SinaTadayon/netty,mx657649013/netty,liuciuse/netty,woshilaiceshide/netty,hepin1989/netty,smayoorans/netty,chinayin/netty,xiongzheng/netty,joansmith/netty,huuthang1993/netty,sammychen105/netty,jongyeol/netty,yawkat/netty,fantayeneh/netty,NiteshKant/netty,orika/netty,shism/netty,ijuma/netty,mcanthony/netty,windie/netty,niuxinghua/netty,ajaysarda/netty,gigold/netty,pengzj/netty,artgon/netty,mcobrien/netty,duqiao/netty,purplefox/netty-4.0.2.8-hacked,xiongzheng/netty,kiril-me/netty,duqiao/netty,hepin1989/netty,silvaran/netty,jenskordowski/netty,lznhust/netty,imangry/netty-zh,liyang1025/netty,lugt/netty,exinguu/netty,Kalvar/netty,WangJunTYTL/netty,afredlyj/learn-netty,hyangtack/netty,zhoffice/netty,x1957/netty,afredlyj/learn-netty,fenik17/netty,huanyi0723/netty,eincs/netty,x1957/netty,nayato/netty,rovarga/netty,rovarga/netty,codevelop/netty,shelsonjava/netty,sunbeansoft/netty,yipen9/netty,afds/netty,pengzj/netty,bryce-anderson/netty,bryce-anderson/netty,NiteshKant/netty,sja/netty,jdivy/netty,lightsocks/netty,danbev/netty,wuxiaowei907/netty,bigheary/netty,mikkokar/netty,AnselQiao/netty,mway08/netty,golovnin/netty,djchen/netty,shenguoquan/netty,lukehutch/netty,danny200309/netty,seetharamireddy540/netty,satishsaley/netty,mway08/netty,balaprasanna/netty,xingguang2013/netty,xiexingguang/netty,danny200309/netty,woshilaiceshide/netty,eonezhang/netty,normanmaurer/netty,mubarak/netty,chanakaudaya/netty,ngocdaothanh/netty,yipen9/netty,mcanthony/netty,tbrooks8/netty,tempbottle/netty,blademainer/netty,fenik17/netty,wuyinxian124/netty,carlbai/netty,idelpivnitskiy/netty,gerdriesselmann/netty,carl-mastrangelo/netty,x1957/netty,ijuma/netty,Kalvar/netty,tbrooks8/netty,xiongzheng/netty,artgon/netty,ninja-/netty,dongjiaqiang/netty,shenguoquan/netty,wangyikai/netty,mikkokar/netty,niuxinghua/netty,serioussam/netty,phlizik/netty,idelpivnitskiy/netty,bigheary/netty,timboudreau/netty,Scottmitch/netty,golovnin/netty,andsel/netty,chanakaudaya/netty,zxhfirefox/netty,jenskordowski/netty,AnselQiao/netty,lightsocks/netty,zhoffice/netty,timboudreau/netty,blucas/netty,sja/netty,codevelop/netty,LuminateWireless/netty,mcanthony/netty,phlizik/netty,carl-mastrangelo/netty,KatsuraKKKK/netty,s-gheldd/netty,Mounika-Chirukuri/netty,hyangtack/netty,nat2013/netty,altihou/netty,KatsuraKKKK/netty,jongyeol/netty,drowning/netty,Techcable/netty,exinguu/netty,joansmith/netty,sameira/netty,sverkera/netty,mikkokar/netty,lznhust/netty,mcanthony/netty,cnoldtree/netty,slandelle/netty,hgl888/netty,Alwayswithme/netty,smayoorans/netty,JungMinu/netty,bryce-anderson/netty,clebertsuconic/netty,olupotd/netty,eincs/netty,fengjiachun/netty,Apache9/netty,hepin1989/netty,artgon/netty,lukw00/netty,jdivy/netty,AchinthaReemal/netty,zhujingling/netty,altihou/netty,KeyNexus/netty,woshilaiceshide/netty,shenguoquan/netty,pengzj/netty,gerdriesselmann/netty,huanyi0723/netty,sja/netty,nadeeshaan/netty,skyao/netty,bryce-anderson/netty,exinguu/netty,CliffYuan/netty,youprofit/netty,yipen9/netty,luyiisme/netty,slandelle/netty,tempbottle/netty,netty/netty,Squarespace/netty,olupotd/netty,liyang1025/netty,danny200309/netty,brennangaunce/netty,louxiu/netty,AnselQiao/netty,danbev/netty,Mounika-Chirukuri/netty,windie/netty,nmittler/netty,timboudreau/netty,yrcourage/netty,skyao/netty,JungMinu/netty,chrisprobst/netty,jovezhougang/netty,Apache9/netty,junjiemars/netty,lukehutch/netty,afds/netty,kyle-liu/netty4study,windie/netty,AchinthaReemal/netty,liuciuse/netty,liyang1025/netty,doom369/netty,gerdriesselmann/netty,mosoft521/netty,zxhfirefox/netty,liuciuse/netty,ioanbsu/netty,normanmaurer/netty,Mounika-Chirukuri/netty,zhoffice/netty,yonglehou/netty-1,firebase/netty,zzcclp/netty,zhujingling/netty,maliqq/netty,duqiao/netty,KeyNexus/netty,Techcable/netty,jroper/netty,chrisprobst/netty,clebertsuconic/netty,andsel/netty,wuyinxian124/netty,balaprasanna/netty,jdivy/netty,jenskordowski/netty,fengjiachun/netty,brennangaunce/netty,carlbai/netty,zer0se7en/netty,windie/netty,Mounika-Chirukuri/netty,drowning/netty,exinguu/netty,chrisprobst/netty,zzcclp/netty,dongjiaqiang/netty,IBYoung/netty,lukw00/netty,jovezhougang/netty,caoyanwei/netty,altihou/netty,lukehutch/netty,altihou/netty,sammychen105/netty,fengshao0907/netty,blademainer/netty,JungMinu/netty,mcobrien/netty,Alwayswithme/netty,yrcourage/netty,shuangqiuan/netty,satishsaley/netty,danbev/netty,chinayin/netty,shelsonjava/netty,xingguang2013/netty,eincs/netty,kiril-me/netty,aperepel/netty,wangyikai/netty,djchen/netty,Scottmitch/netty,moyiguket/netty,seetharamireddy540/netty,nkhuyu/netty,xingguang2013/netty,nkhuyu/netty,ajaysarda/netty,ioanbsu/netty,wangyikai/netty,satishsaley/netty,jchambers/netty,zer0se7en/netty,cnoldtree/netty,luyiisme/netty,MediumOne/netty,wuyinxian124/netty,lukw00/netty,x1957/netty,afds/netty,sverkera/netty,yonglehou/netty-1,bigheary/netty,mcobrien/netty,nayato/netty,louxiu/netty,LuminateWireless/netty,yonglehou/netty-1,zhujingling/netty,tempbottle/netty,ijuma/netty,ajaysarda/netty,smayoorans/netty,hgl888/netty,artgon/netty,duqiao/netty,BrunoColin/netty,xiongzheng/netty,LuminateWireless/netty,Kingson4Wu/netty,Alwayswithme/netty,KatsuraKKKK/netty,DavidAlphaFox/netty,Kingson4Wu/netty,chanakaudaya/netty,jenskordowski/netty,doom369/netty,shuangqiuan/netty,lznhust/netty,imangry/netty-zh,cnoldtree/netty,sunbeansoft/netty,pengzj/netty,junjiemars/netty,sameira/netty,jchambers/netty,hepin1989/netty,blucas/netty,chanakaudaya/netty,alkemist/netty,nmittler/netty,jchambers/netty,yawkat/netty,WangJunTYTL/netty,serioussam/netty,fengjiachun/netty,dongjiaqiang/netty,danbev/netty,moyiguket/netty,huanyi0723/netty,zzcclp/netty,sameira/netty,nat2013/netty,afredlyj/learn-netty,shuangqiuan/netty,mosoft521/netty,blucas/netty,moyiguket/netty,orika/netty,ifesdjeen/netty,kjniemi/netty,fengjiachun/netty,castomer/netty,unei66/netty,niuxinghua/netty,seetharamireddy540/netty,lukehutch/netty,clebertsuconic/netty,louiscryan/netty,gigold/netty,blucas/netty,netty/netty,fengshao0907/netty,tbrooks8/netty,joansmith/netty,phlizik/netty,nkhuyu/netty,rovarga/netty,eincs/netty,yawkat/netty,drowning/netty,zer0se7en/netty,blademainer/netty,IBYoung/netty,louiscryan/netty,hgl888/netty,purplefox/netty-4.0.2.8-hacked,djchen/netty,doom369/netty,CodingFabian/netty,doom369/netty,yonglehou/netty-1,f7753/netty,mway08/netty,kiril-me/netty,orika/netty,Squarespace/netty,castomer/netty,jongyeol/netty,Techcable/netty,sverkera/netty,castomer/netty,BrunoColin/netty,idelpivnitskiy/netty,nadeeshaan/netty,wangyikai/netty,jdivy/netty,golovnin/netty,Kingson4Wu/netty,cnoldtree/netty,satishsaley/netty,gigold/netty,MediumOne/netty,wuyinxian124/netty,DolphinZhao/netty,blucas/netty,liuciuse/netty,qingsong-xu/netty,fantayeneh/netty,louxiu/netty,shelsonjava/netty,imangry/netty-zh,kjniemi/netty,ajaysarda/netty,ngocdaothanh/netty,jchambers/netty,bryce-anderson/netty,sunbeansoft/netty,xiexingguang/netty,brennangaunce/netty,clebertsuconic/netty,xiongzheng/netty,wuxiaowei907/netty,firebase/netty,Alwayswithme/netty,NiteshKant/netty,WangJunTYTL/netty,kvr000/netty,maliqq/netty,blademainer/netty,lugt/netty,silvaran/netty,mcobrien/netty,chrisprobst/netty,hgl888/netty,shelsonjava/netty,youprofit/netty,ioanbsu/netty,kjniemi/netty,eonezhang/netty,nmittler/netty,timboudreau/netty,Squarespace/netty,eonezhang/netty,ngocdaothanh/netty,zhujingling/netty,mosoft521/netty,xiexingguang/netty,ijuma/netty,andsel/netty,zhoffice/netty,shenguoquan/netty,daschl/netty,mx657649013/netty,zhoffice/netty,tempbottle/netty,Spikhalskiy/netty,sja/netty,liyang1025/netty,silvaran/netty,caoyanwei/netty,ejona86/netty,duqiao/netty,carlbai/netty,rovarga/netty,NiteshKant/netty,JungMinu/netty,slandelle/netty,niuxinghua/netty,chinayin/netty,BrunoColin/netty,bigheary/netty,shenguoquan/netty,CliffYuan/netty,nkhuyu/netty,cnoldtree/netty,yrcourage/netty,fengjiachun/netty,ioanbsu/netty,unei66/netty,jenskordowski/netty,develar/netty,skyao/netty,skyao/netty,zhujingling/netty,sammychen105/netty,ijuma/netty,caoyanwei/netty,johnou/netty,Techcable/netty,CodingFabian/netty,shism/netty,daschl/netty,yipen9/netty,MediumOne/netty,alkemist/netty,zxhfirefox/netty,mx657649013/netty,Spikhalskiy/netty,DavidAlphaFox/netty,johnou/netty,Scottmitch/netty,serioussam/netty,AnselQiao/netty,yrcourage/netty,joansmith/netty,youprofit/netty,CodingFabian/netty,kvr000/netty,netty/netty,ejona86/netty,zzcclp/netty,AchinthaReemal/netty,ajaysarda/netty,huanyi0723/netty,xingguang2013/netty,f7753/netty,chinayin/netty,johnou/netty,xingguang2013/netty,buchgr/netty,sunbeansoft/netty,unei66/netty,youprofit/netty,andsel/netty,hgl888/netty,ngocdaothanh/netty,Spikhalskiy/netty,golovnin/netty,balaprasanna/netty,mikkokar/netty,louxiu/netty,shelsonjava/netty,fengshao0907/netty,luyiisme/netty,louiscryan/netty,sja/netty,ejona86/netty,woshilaiceshide/netty,Squarespace/netty,johnou/netty,alkemist/netty,eonezhang/netty,blademainer/netty,mikkokar/netty,brennangaunce/netty,buchgr/netty,clebertsuconic/netty,Kalvar/netty,balaprasanna/netty,shuangqiuan/netty,shism/netty,tempbottle/netty,gigold/netty,altihou/netty,SinaTadayon/netty,firebase/netty,buchgr/netty,purplefox/netty-4.0.2.8-hacked,MediumOne/netty,ejona86/netty,wangyikai/netty,WangJunTYTL/netty,wuxiaowei907/netty,netty/netty,menacher/netty,sverkera/netty,fantayeneh/netty,ichaki5748/netty,MediumOne/netty,kiril-me/netty,serioussam/netty,shism/netty,nayato/netty,woshilaiceshide/netty,sameira/netty,brennangaunce/netty,mubarak/netty,louiscryan/netty,AnselQiao/netty,yonglehou/netty-1,eonezhang/netty,kvr000/netty,liuciuse/netty,mubarak/netty,lznhust/netty,wuxiaowei907/netty,DavidAlphaFox/netty,joansmith/netty,alkemist/netty,eincs/netty,castomer/netty,f7753/netty,ninja-/netty,djchen/netty,maliqq/netty,sunbeansoft/netty,yawkat/netty,BrunoColin/netty,tbrooks8/netty,Spikhalskiy/netty,SinaTadayon/netty,codevelop/netty,purplefox/netty-4.0.2.8-hacked,codevelop/netty,DolphinZhao/netty,jchambers/netty,danbev/netty,carlbai/netty,jovezhougang/netty,jovezhougang/netty,junjiemars/netty,lightsocks/netty,kiril-me/netty,huuthang1993/netty,huanyi0723/netty,unei66/netty,imangry/netty-zh,huuthang1993/netty,xiexingguang/netty,danny200309/netty,balaprasanna/netty,x1957/netty,zer0se7en/netty,buchgr/netty,niuxinghua/netty,olupotd/netty,jovezhougang/netty,idelpivnitskiy/netty,moyiguket/netty,f7753/netty,KatsuraKKKK/netty,s-gheldd/netty,qingsong-xu/netty,mway08/netty,jdivy/netty,andsel/netty | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @author tags. See the COPYRIGHT.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.netty.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
import java.nio.charset.UnsupportedCharsetException;
import java.util.NoSuchElementException;
/**
* Random and sequential accessible sequence of zero or more bytes (octets).
* This interface provides an abstract view for one or more primitive byte
* arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}.
*
* <h3>Creation of a buffer</h3>
*
* It is common for a user to create a new buffer using {@link ChannelBuffers}
* utility class rather than calling an individual implementation's constructor.
*
* <h3>Random Access Indexing</h3>
*
* Just like an ordinary primitive byte array, {@link ChannelBuffer} uses
* <a href="http://en.wikipedia.org/wiki/Index_(information_technology)#Array_element_identifier">zero-based indexing</a>.
* It means the index of the first byte is always {@code 0} and the index of
* the last byte is always {@link #capacity() capacity - 1}. For example, to
* iterate all bytes of a buffer, you can do the following, regardless of
* its internal implementation:
*
* <pre>
* ChannelBuffer buffer = ...;
* for (int i = 0; i < buffer.capacity(); i ++</strong>) {
* byte b = array.getByte(i);
* System.out.println((char) b);
* }
* </pre>
*
* <h3>Sequential Access Indexing</h3>
*
* {@link ChannelBuffer} provides two pointer variables to support sequential
* read and write operations - {@link #readerIndex() readerIndex} for a read
* operation and {@link #writerIndex() writerIndex} for a write operation
* respectively. The following diagram shows how a buffer is segmented into
* three areas by the two pointers:
*
* <pre>
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable space |
* | | (CONTENT) | |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
* </pre>
*
* <h4>Readable bytes (the actual 'content' of the buffer)</h4>
*
* This segment, so called 'the <strong>content</strong> of a buffer', is where
* the actual data is stored. Any operation whose name starts with
* {@code read} or {@code skip} will get or skip the data at the current
* {@link #readerIndex() readerIndex} and increase it by the number of read
* bytes. If the argument of the read operation is also a {@link ChannelBuffer}
* and no start index is specified, the specified buffer's
* {@link #readerIndex() readerIndex} is increased together.
* <p>
* If there's not enough content left, {@link IndexOutOfBoundsException} is
* raised. The default value of newly allocated, wrapped or copied buffer's
* {@link #readerIndex() readerIndex} is {@code 0}.
*
* <pre>
* // Iterates the readable bytes of a buffer.
* ChannelBuffer buffer = ...;
* while (buffer.readable()) {
* System.out.println(buffer.readByte());
* }
* </pre>
*
* <h4>Writable space</h4>
*
* This segment is a undefined space which needs to be filled. Any operation
* whose name ends with {@code write} will write the data at the current
* {@link #writerIndex() writerIndex} and increase it by the number of written
* bytes. If the argument of the write operation is also a {@link ChannelBuffer},
* and no start index is specified, the specified buffer's
* {@link #readerIndex() readerIndex} is increased together.
* <p>
* If there's not enough writable space left, {@link IndexOutOfBoundsException}
* is raised. The default value of newly allocated buffer's
* {@link #writerIndex() writerIndex} is {@code 0}. The default value of
* wrapped or copied buffer's {@link #writerIndex() writerIndex} is the
* {@link #capacity() capacity} of the buffer.
*
* <pre>
* // Fills the writable space of a buffer with random integers.
* ChannelBuffer buffer = ...;
* while (buffer.writableBytes() >= 4) {
* buffer.writeInt(random.nextInt());
* }
* </pre>
*
* <h4>Discardable bytes</h4>
*
* This segment contains the bytes which were read already by a read operation.
* Initially, the size of this segment is {@code 0}, but its size increases up
* to the {@link #writerIndex() writerIndex} as read operations are executed.
* The read bytes can be discarded by calling {@link #discardReadBytes()} to
* reclaim unused area as depicted by the following diagram:
*
* <pre>
* BEFORE discardReadBytes()
*
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable space |
* | | (CONTENT) | |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
*
*
* AFTER discardReadBytes()
*
* +------------------+--------------------------------------+
* | readable bytes | writable space (got more space) |
* | (CONTENT) | |
* +------------------+--------------------------------------+
* | | |
* readerIndex (0) <= writerIndex (decreased) <= capacity
* </pre>
*
* <h4>Clearing the buffer indexes</h4>
*
* You can set both {@link #readerIndex() readerIndex} and
* {@link #writerIndex() writerIndex} to {@code 0} by calling {@link #clear()}.
* It doesn't clear the buffer content (e.g. filling with {@code 0}) but just
* clears the two pointers. Please also note that the semantic of this
* operation is different from {@link ByteBuffer#clear()}.
*
* <pre>
* BEFORE clear()
*
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable space |
* | | (CONTENT) | |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
*
*
* AFTER clear()
*
* +---------------------------------------------------------+
* | writable space (got more space) |
* +---------------------------------------------------------+
* | |
* 0 = readerIndex = writerIndex <= capacity
* </pre>
*
* <h3>Search operations</h3>
*
* Various {@code indexOf()} methods help you locate an index of a value which
* meets a certain criteria. Complicated dynamic sequential search can be done
* with {@link ChannelBufferIndexFinder} as well as simple static single byte
* search.
*
* <h3>Mark and reset</h3>
*
* There are two marker indexes in every buffer. One is for storing
* {@link #readerIndex() readerIndex} and the other is for storing
* {@link #writerIndex() writerIndex}. You can always reposition one of the
* two indexes by calling a reset method. It works in a similar fashion to
* the mark and reset methods in {@link InputStream} except that there's no
* {@code readlimit}.
*
* <h3>Derived buffers</h3>
*
* You can create a view of an existing buffer by calling either
* {@link #duplicate()}, {@link #slice()} or {@link #slice(int, int)}.
* A derived buffer will have an independent {@link #readerIndex() readerIndex},
* {@link #writerIndex() writerIndex} and marker indexes, while it shares
* other internal data representation, just like a NIO {@link ByteBuffer} does.
* <p>
* In case a completely fresh copy of an existing buffer is required, please
* call {@link #copy()} method instead.
*
* <h3>Conversion to existing JDK types</h3>
*
* <h4>NIO {@link ByteBuffer}</h4>
*
* Various {@link #toByteBuffer()} and {@link #toByteBuffers()} methods convert
* a {@link ChannelBuffer} into one or more NIO buffers. These methods avoid
* buffer allocation and memory copy whenever possible, but there's no
* guarantee that memory copy will not be involved or that an explicit memory
* copy will be involved.
*
* <h4>{@link String}</h4>
*
* Various {@link #toString(String)} methods convert a {@link ChannelBuffer}
* into a {@link String}. Plesae note that {@link #toString()} is not a
* conversion method.
*
* <h4>{@link InputStream} and {@link OutputStream}</h4>
*
* Please refer to {@link ChannelBufferInputStream} and
* {@link ChannelBufferOutputStream}.
*
* @author The Netty Project ([email protected])
* @author Trustin Lee ([email protected])
*
* @version $Rev$, $Date$
*
* @apiviz.landmark
*/
public interface ChannelBuffer extends Comparable<ChannelBuffer> {
/**
* A buffer whose capacity is {@code 0}.
*/
static ChannelBuffer EMPTY_BUFFER = new BigEndianHeapChannelBuffer(0);
/**
* Returns the number of bytes (octets) this buffer can contain.
*/
int capacity();
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Endianness">endianness</a>
* of this buffer.
*/
ByteOrder order();
/**
* Returns the {@code readerIndex} of this buffer.
*/
int readerIndex();
/**
* Sets the {@code readerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code readerIndex} is less than 0 or
* greater than {@code this.writerIndex}
*/
void readerIndex(int readerIndex);
/**
* Returns the {@code writerIndex} of this buffer.
*/
int writerIndex();
/**
* Sets the {@code writerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code writerIndex} is less than
* {@code this.readerIndex} or greater than {@code this.capacity}
*/
void writerIndex(int writerIndex);
/**
* Sets the {@code readerIndex} and {@code writerIndex} of this buffer
* in one shot. This method is useful when you have to worry about the
* invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)}
* methods. For example, the following code will fail:
*
* <pre>
* // Create a buffer whose readerIndex, writerIndex and capacity are
* // 0, 0 and 8 respectively.
* ChannelBuffer buf = ChannelBuffers.buffer(8);
*
* // IndexOutOfBoundsException is thrown because the specified
* // readerIndex (2) cannot be greater than the current writerIndex (0).
* buf.readerIndex(2);
* buf.writerIndex(4);
* </pre>
*
* The following code will also fail:
*
* <pre>
* // Create a buffer whose readerIndex, writerIndex and capacity are
* // 0, 8 and 8 respectively.
* ChannelBuffer buf = ChannelBuffers.wrappedBuffer(new byte[8]);
*
* // readerIndex becomes 8.
* buf.readLong();
*
* // IndexOutOfBoundsException is thrown because the specified
* // writerIndex (4) cannot be less than the current readerIndex (8).
* buf.writerIndex(4);
* buf.readerIndex(2);
* </pre>
*
* By contrast, {@link #setIndex(int, int)} guarantees that it never
* throws an {@link IndexOutOfBoundsException} as long as the specified
* indexes meet all constraints, regardless what the current index values
* of the buffer are:
*
* <pre>
* // No matter what the current state of the buffer is, the following
* // call always succeeds as long as the capacity of the buffer is not
* // less than 4.
* buf.setIndex(2, 4);
* </pre>
*
* @throws IndexOutOfBoundsException
* if the specified {@code readerIndex} is less than 0,
* if the specified {@code writerIndex} is less than the specified
* {@code readerIndex} or if the specified {@code writerIndex} is
* greater than {@code this.capacity}
*/
void setIndex(int readerIndex, int writerIndex);
/**
* Returns the number of readable bytes which equals to
* {@code (this.writerIndex - this.readerIndex)}.
*/
int readableBytes();
/**
* Returns the number of writable bytes which equals to
* {@code (this.capacity - this.writerIndex)}.
*/
int writableBytes();
/**
* Returns {@code true}
* if and only if {@code (this.writerIndex - this.readerIndex)} is greater
* than {@code 0}.
*/
boolean readable();
/**
* Returns {@code true}
* if and only if {@code (this.capacity - this.writerIndex)} is greater
* than {@code 0}.
*/
boolean writable();
/**
* Sets the {@code readerIndex} and {@code writerIndex} of this buffer to
* {@code 0}.
* This method is identical to {@link #setIndex(int, int) setIndex(0, 0)}.
* <p>
* Please note that the behavior of this method is different
* from that of NIO {@link ByteBuffer}, which sets the {@code limit} to
* the {@code capacity} of the buffer.
*/
void clear();
/**
* Marks the current {@code readerIndex} in this buffer. You can
* reposition the current {@code readerIndex} to the marked
* {@code readerIndex} by calling {@link #resetReaderIndex()}.
* The initial value of the marked {@code readerIndex} is {@code 0}.
*/
void markReaderIndex();
/**
* Repositions the current {@code readerIndex} to the marked
* {@code readerIndex} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the current {@code writerIndex} is less than the marked
* {@code readerIndex}
*/
void resetReaderIndex();
/**
* Marks the current {@code writerIndex} in this buffer. You can
* reposition the current {@code writerIndex} to the marked
* {@code writerIndex} by calling {@link #resetWriterIndex()}.
* The initial value of the marked {@code writerIndex} is {@code 0}.
*/
void markWriterIndex();
/**
* Repositions the current {@code writerIndex} to the marked
* {@code writerIndex} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the current {@code readerIndex} is greater than the marked
* {@code writerIndex}
*/
void resetWriterIndex();
/**
* Discards the bytes between the 0th index and {@code readerIndex}.
* It moves the bytes between {@code readerIndex} and {@code writerIndex}
* to the 0th index, and sets {@code readerIndex} and {@code writerIndex}
* to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively.
* <p>
* Please refer to the class documentation for more detailed explanation.
*/
void discardReadBytes();
/**
* Gets a byte at the specified absolute {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 1} is greater than {@code this.capacity}
*/
byte getByte(int index);
/**
* Gets a unsigned byte at the specified absolute {@code index} in this
* buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 1} is greater than {@code this.capacity}
*/
short getUnsignedByte(int index);
/**
* Gets a 16-bit short integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 2} is greater than {@code this.capacity}
*/
short getShort(int index);
/**
* Gets a unsigned 16-bit short integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 2} is greater than {@code this.capacity}
*/
int getUnsignedShort(int index);
/**
* Gets a 24-bit medium integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 3} is greater than {@code this.capacity}
*/
int getMedium(int index);
/**
* Gets a unsigned 24-bit medium integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 3} is greater than {@code this.capacity}
*/
int getUnsignedMedium(int index);
/**
* Gets a 32-bit integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 4} is greater than {@code this.capacity}
*/
int getInt(int index);
/**
* Gets a unsigned 32-bit integer at the specified absolute {@code index}
* in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 4} is greater than {@code this.capacity}
*/
long getUnsignedInt(int index);
/**
* Gets a 64-bit long integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 8} is greater than {@code this.capacity}
*/
long getLong(int index);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index} until the destination becomes
* unwritable. This method is basically same with
* {@link #getBytes(int, ChannelBuffer, int, int)}, except that this
* method increases the {@code writerIndex} of the destination by the
* number of the transferred bytes while
* {@link #getBytes(int, ChannelBuffer, int, int)} doesn't.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + dst.writableBytes} is greater than
* {@code this.capacity}
*/
void getBytes(int index, ChannelBuffer dst);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index}.
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code dstIndex} is less than {@code 0},
* if {@code index + length} is greater than
* {@code this.capacity}, or
* if {@code dstIndex + length} is greater than
* {@code dst.capacity}
*/
void getBytes(int index, ChannelBuffer dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + dst.length} is greater than
* {@code this.capacity}
*/
void getBytes(int index, byte[] dst);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index}.
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code dstIndex} is less than {@code 0},
* if {@code index + length} is greater than
* {@code this.capacity}, or
* if {@code dstIndex + length} is greater than
* {@code dst.length}
*/
void getBytes(int index, byte[] dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index} until the destination's position
* reaches to its limit.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + dst.remaining()} is greater than
* {@code this.capacity}
*/
void getBytes(int index, ByteBuffer dst);
/**
* Transfers this buffer's data to the specified stream starting at the
* specified absolute {@code index}.
*
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than
* {@code this.capacity}
* @throws IOException
* if the specified stream threw an exception during I/O
*/
void getBytes(int index, OutputStream out, int length) throws IOException;
/**
* Transfers this buffer's data to the specified channel starting at the
* specified absolute {@code index}.
*
* @param length the maximum number of bytes to transfer
*
* @return the actual number of bytes written out to the specified channel
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than
* {@code this.capacity}
* @throws IOException
* if the specified channel threw an exception during I/O
*/
int getBytes(int index, GatheringByteChannel out, int length) throws IOException;
/**
* Sets the specified byte at the specified absolute {@code index} in this
* buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 1} is greater than {@code this.capacity}
*/
void setByte(int index, byte value);
/**
* Sets the specified 16-bit short integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 2} is greater than {@code this.capacity}
*/
void setShort(int index, short value);
/**
* Sets the specified 24-bit medium integer at the specified absolute
* {@code index} in this buffer. Please note that the most significant
* byte is ignored in the specified value.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 3} is greater than {@code this.capacity}
*/
void setMedium(int index, int value);
/**
* Sets the specified 32-bit integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 4} is greater than {@code this.capacity}
*/
void setInt(int index, int value);
/**
* Sets the specified 64-bit long integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 8} is greater than {@code this.capacity}
*/
void setLong(int index, long value);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index} until the destination becomes
* unreadable. This method is basically same with
* {@link #setBytes(int, ChannelBuffer, int, int)}, except that this
* method increased the {@code readerIndex} of the source buffer by
* the number of the transferred bytes while
* {@link #getBytes(int, ChannelBuffer, int, int)} doesn't.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + src.readableBytes} is greater than
* {@code this.capacity}
*/
void setBytes(int index, ChannelBuffer src);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index}.
*
* @param srcIndex the first index of the source
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code srcIndex} is less than {@code 0},
* if {@code index + length} is greater than
* {@code this.capacity}, or
* if {@code srcIndex + length} is greater than
* {@code src.capacity}
*/
void setBytes(int index, ChannelBuffer src, int srcIndex, int length);
/**
* Transfers the specified source array's data to this buffer starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + src.length} is greater than
* {@code this.capacity}
*/
void setBytes(int index, byte[] src);
/**
* Transfers the specified source array's data to this buffer starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code srcIndex} is less than {@code 0},
* if {@code index + length} is greater than
* {@code this.capacity}, or
* if {@code srcIndex + length} is greater than {@code src.length}
*/
void setBytes(int index, byte[] src, int srcIndex, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index} until the source buffer's position
* reaches to its limit.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + src.remaining()} is greater than
* {@code this.capacity}
*/
void setBytes(int index, ByteBuffer src);
/**
* Transfers the content of the specified source stream to this buffer
* starting at the specified absolute {@code index}.
*
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code this.capacity}
* @throws IOException
* if the specified stream threw an exception during I/O
*/
void setBytes(int index, InputStream in, int length) throws IOException;
/**
* Transfers the content of the specified source channel to this buffer
* starting at the specified absolute {@code index}.
*
* @param length the maximum number of bytes to transfer
*
* @return the actual number of bytes read in from the specified channel
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code this.capacity}
* @throws IOException
* if the specified channel threw an exception during I/O
*/
int setBytes(int index, ScatteringByteChannel in, int length) throws IOException;
/**
* Fills this buffer with <tt>NUL (0x00)</tt> starting at the specified
* absolute {@code index}.
*
* @param length the number of <tt>NUL</tt>s to write to the buffer
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code this.capacity}
*/
void setZero(int index, int length);
/**
* Gets a byte at the current {@code readerIndex} and increases
* the {@code readerIndex} by {@code 1} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 1} is greater than
* {@code this.writerIndex}
*/
byte readByte();
/**
* Gets a unsigned byte at the current {@code readerIndex} and increases
* the {@code readerIndex} by {@code 1} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 1} is greater than
* {@code this.writerIndex}
*/
short readUnsignedByte();
/**
* Gets a 16-bit short integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 2} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 2} is greater than
* {@code this.writerIndex}
*/
short readShort();
/**
* Gets a unsigned 16-bit short integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 2} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 2} is greater than
* {@code this.writerIndex}
*/
int readUnsignedShort();
/**
* Gets a 24-bit medium integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 3} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 3} is greater than
* {@code this.writerIndex}
*/
int readMedium();
/**
* Gets a unsigned 24-bit medium integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 3} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 3} is greater than
* {@code this.writerIndex}
*/
int readUnsignedMedium();
/**
* Gets a 32-bit integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 4} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 4} is greater than
* {@code this.writerIndex}
*/
int readInt();
/**
* Gets a unsigned 32-bit integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 4} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 4} is greater than
* {@code this.writerIndex}
*/
long readUnsignedInt();
/**
* Gets a 64-bit integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 8} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + 8} is greater than
* {@code this.writerIndex}
*/
long readLong();
ChannelBuffer readBytes(int length);
ChannelBuffer readBytes(ChannelBufferIndexFinder endIndexFinder);
ChannelBuffer readSlice(int length);
ChannelBuffer readSlice(ChannelBufferIndexFinder endIndexFinder);
/**
* Transfers this buffer's data to the specified destination starting at
* the current {@code readerIndex} until the destination becomes
* unwritable, and increases the {@code readerIndex} by the number of the
* transferred bytes. This method is basically same with
* {@link #readBytes(ChannelBuffer, int, int)}, except that this method
* increases the {@code writerIndex} of the destination by the number of
* the transferred bytes while {@link #readBytes(ChannelBuffer, int, int)}
* doesn't.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + dst.writableBytes} is greater than
* {@code this.writerIndex}
*/
void readBytes(ChannelBuffer dst);
/**
* Transfers this buffer's data to the specified destination starting at
* the current {@code readerIndex} and increases the {@code readerIndex}
* by the number of the transferred bytes (= {@code length}). This method
* is basically same with {@link #readBytes(ChannelBuffer, int, int)},
* except that this method increases the {@code writerIndex} of the
* destination by the number of the transferred bytes (= {@code length})
* while {@link #readBytes(ChannelBuffer, int, int)} doesn't.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + length} is greater than
* {@code this.writerIndex} or
* if {@code dst.writerIndex + length} is greater than
* {@code dst.capacity}
*/
void readBytes(ChannelBuffer dst, int length);
/**
* Transfers this buffer's data to the specified destination starting at
* the current {@code readerIndex} and increases the {@code readerIndex}
* by the number of the transferred bytes (= {@code length}).
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code dstIndex} is less than {@code 0},
* if {@code this.readerIndex + length} is greater than
* {@code this.writerIndex}, or
* if {@code dstIndex + length} is greater than
* {@code dst.capacity}
*/
void readBytes(ChannelBuffer dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at
* the current {@code readerIndex} and increases the {@code readerIndex}
* by the number of the transferred bytes (= {@code dst.length}).
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + dst.length} is greater than
* {@code this.writerIndex} or
* if {@code this.readableBytes} is greater than
* {@code dst.length}
*/
void readBytes(byte[] dst);
/**
* Transfers this buffer's data to the specified destination starting at
* the current {@code readerIndex} and increases the {@code readerIndex}
* by the number of the transferred bytes (= {@code length}).
*
* @param dstIndex the first index of the destination
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code dstIndex} is less than {@code 0},
* if {@code this.readerIndex + length} is greater than
* {@code this.writerIndex}, or
* if {@code dstIndex + length} is greater than {@code dst.length}
*/
void readBytes(byte[] dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at
* the current {@code readerIndex} until the destination's position
* reaches to its limit, and increases the {@code readerIndex} by the
* number of the transferred bytes.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + dst.remaining()} is greater than
* {@code this.capacity} or
* if {@code this.readableBytes} is greater than
* {@code dst.remaining}
*
*/
void readBytes(ByteBuffer dst);
/**
* Transfers this buffer's data to the specified stream starting at the
* current {@code readerIndex}.
*
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + length} is greater than
* {@code this.capacity}
* @throws IOException
* if the specified stream threw an exception during I/O
*/
void readBytes(OutputStream out, int length) throws IOException;
/**
* Transfers this buffer's data to the specified stream starting at the
* current {@code readerIndex}.
*
* @param length the maximum number of bytes to transfer
*
* @return the actual number of bytes written out to the specified channel
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + length} is greater than
* {@code this.capacity}
* @throws IOException
* if the specified channel threw an exception during I/O
*/
int readBytes(GatheringByteChannel out, int length) throws IOException;
/**
* Increases the current {@code readerIndex} by the specified
* {@code length} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.readerIndex + length} is greater than
* {@code this.writerIndex}
*/
void skipBytes(int length);
/**
* Increases the current {@code readerIndex} until the specified
* {@code firstIndexFinder} returns {@code true} in this buffer.
*
* @return the number of skipped bytes
*
* @throws NoSuchElementException
* if {@code firstIndexFinder} didn't return {@code true} at all
*/
int skipBytes(ChannelBufferIndexFinder firstIndexFinder);
/**
* Sets the specified byte at the current {@code writerIndex}
* and increases the {@code writerIndex} by {@code 1} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + 1} is greater than
* {@code this.capacity}
*/
void writeByte(byte value);
/**
* Sets the specified 16-bit short integer at the current
* {@code writerIndex} and increases the {@code writerIndex} by {@code 2}
* in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + 2} is greater than
* {@code this.capacity}
*/
void writeShort(short value);
/**
* Sets the specified 24-bit medium integer at the current
* {@code writerIndex} and increases the {@code writerIndex} by {@code 3}
* in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + 3} is greater than
* {@code this.capacity}
*/
void writeMedium(int value);
/**
* Sets the specified 32-bit integer at the current {@code writerIndex}
* and increases the {@code writerIndex} by {@code 4} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + 4} is greater than
* {@code this.capacity}
*/
void writeInt(int value);
/**
* Sets the specified 64-bit long integer at the current
* {@code writerIndex} and increases the {@code writerIndex} by {@code 8}
* in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + 8} is greater than
* {@code this.capacity}
*/
void writeLong(long value);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} until the source buffer becomes
* unreadable, and increases the {@code writerIndex} by the number of
* the transferred bytes. This method is basically same with
* {@link #writeBytes(ChannelBuffer, int, int)}, except that this method
* increases the {@code readerIndex} of the source buffer by the number of
* the transferred bytes while {@link #writeBytes(ChannelBuffer, int, int)}
* doesn't.
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + src.readableBytes} is greater than
* {@code this.capacity}
*/
void writeBytes(ChannelBuffer src);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex}
* by the number of the transferred bytes (= {@code length}). This method
* is basically same with {@link #writeBytes(ChannelBuffer, int, int)},
* except that this method increases the {@code readerIndex} of the source
* buffer by the number of the transferred bytes (= {@code length}) while
* {@link #writeBytes(ChannelBuffer, int, int)} doesn't.
*
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + length} is greater than
* {@code this.capacity}
*/
void writeBytes(ChannelBuffer src, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex}
* by the number of the transferred bytes (= {@code length}).
*
* @param srcIndex the first index of the source
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code srcIndex} is less than {@code 0},
* if {@code srcIndex + length} is greater than
* {@code src.capacity}, or
* if {@code this.writerIndex + length} is greater than
* {@code this.capacity}
*/
void writeBytes(ChannelBuffer src, int srcIndex, int length);
/**
* Transfers the specified source array's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex}
* by the number of the transferred bytes (= {@code src.length}).
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + src.length} is greater than
* {@code this.capacity}
*/
void writeBytes(byte[] src);
/**
* Transfers the specified source array's data to this buffer starting at
* the current {@code writerIndex} and increases the {@code writerIndex}
* by the number of the transferred bytes (= {@code length}).
*
* @param srcIndex the first index of the source
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if the specified {@code srcIndex} is less than {@code 0},
* if {@code srcIndex + length} is greater than
* {@code src.length}, or
* if {@code this.writerIndex + length} is greater than
* {@code this.capacity}
*/
void writeBytes(byte[] src, int srcIndex, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the current {@code writerIndex} until the source buffer's position
* reaches to its limit, and increases the {@code writerIndex} by the
* number of the transferred bytes.
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + src.remaining()} is greater than
* {@code this.capacity}
*/
void writeBytes(ByteBuffer src);
/**
* Transfers the content of the specified stream to this buffer
* starting at the current {@code writerIndex} and increases the
* {@code writerIndex} by the number of the transferred bytes.
*
* @param length the number of bytes to transfer
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + length} is greater than
* {@code this.capacity}
* @throws IOException
* if the specified stream threw an exception during I/O
*/
void writeBytes(InputStream in, int length) throws IOException;
/**
* Transfers the content of the specified channel to this buffer
* starting at the current {@code writerIndex} and increases the
* {@code writerIndex} by the number of the transferred bytes.
*
* @param length the maximum number of bytes to transfer
*
* @return the actual number of bytes read in from the specified channel
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + length} is greater than
* {@code this.capacity}
* @throws IOException
* if the specified channel threw an exception during I/O
*/
int writeBytes(ScatteringByteChannel in, int length) throws IOException;
/**
* Fills this buffer with <tt>NUL (0x00)</tt> starting at the current
* {@code writerIndex} and increases the {@code writerIndex} by the
* specified {@code length}.
*
* @param length the number of <tt>NUL</tt>s to write to the buffer
*
* @throws IndexOutOfBoundsException
* if {@code this.writerIndex + length} is greater than
* {@code this.capacity}
*/
void writeZero(int length);
int indexOf(int fromIndex, int toIndex, byte value);
int indexOf(int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder);
/**
* Returns a copy of this buffer's readable bytes. Modifying the content
* of the returned buffer or this buffer doesn't affect each other at all.
* This method is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}.
*/
ChannelBuffer copy();
/**
* Returns a copy of this buffer's sub-region. Modifying the content of
* the returned buffer or this buffer doesn't affect each other at all.
*/
ChannelBuffer copy(int index, int length);
/**
* Returns a slice of this buffer's readable bytes. Modifying the content
* of the returned buffer or this buffer affects each other's content
* while they maintain separate indexes and marks. This method is
* identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}.
*/
ChannelBuffer slice();
/**
* Returns a slice of this buffer's sub-region. Modifying the content of
* the returned buffer or this buffer affects each other's content while
* they maintain separate indexes and marks. This method is identical to
* {@code buf.slice(buf.readerIndex(), buf.readableBytes())}.
*/
ChannelBuffer slice(int index, int length);
/**
* Returns a buffer which shares the whole region of this buffer.
* Modifying the content of the returned buffer or this buffer affects
* each other's content while they maintain separate indexes and marks.
* This method is identical to {@code buf.slice(0, buf.capacity())}.
*/
ChannelBuffer duplicate();
/**
* Converts this buffer's readable bytes into a NIO buffer. The returned
* buffer might or might not share the content with this buffer, while
* they have separate indexes and marks. This method is identical to
* {@code buf.toByteBuffer(buf.readerIndex(), buf.readableBytes())}.
*/
ByteBuffer toByteBuffer();
/**
* Converts this buffer's sub-region into a NIO buffer. The returned
* buffer might or might not share the content with this buffer, while
* they have separate indexes and marks.
*/
ByteBuffer toByteBuffer(int index, int length);
/**
* Converts this buffer's readable bytes into an array of NIO buffers.
* The returned buffers might or might not share the content with this
* buffer, while they have separate indexes and marks. This method is
* identical to {@code buf.toByteBuffers(buf.readerIndex(), buf.readableBytes())}.
*/
ByteBuffer[] toByteBuffers();
/**
* Converts this buffer's sub-region into an array of NIO buffers.
* The returned buffers might or might not share the content with this
* buffer, while they have separate indexes and marks.
*/
ByteBuffer[] toByteBuffers(int index, int length);
/**
* Decodes this buffer's readable bytes into a string with the specified
* character set name. This method is identical to
* {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}.
*
* @throws UnsupportedCharsetException
* if the specified character set name is not supported by the
* current VM
*/
String toString(String charsetName);
/**
* Decodes this buffer's readable bytes into a string until the specified
* {@code terminatorFinder} returns {@code true} with the specified
* character set name. This method is identical to
* {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName, terminatorFinder)}.
*
* @throws UnsupportedCharsetException
* if the specified character set name is not supported by the
* current VM
*/
String toString(
String charsetName, ChannelBufferIndexFinder terminatorFinder);
/**
* Decodes this buffer's sub-region into a string with the specified
* character set name.
*
* @throws UnsupportedCharsetException
* if the specified character set name is not supported by the
* current VM
*/
String toString(int index, int length, String charsetName);
/**
* Decodes this buffer's readable bytes into a string until the specified
* {@code terminatorFinder} returns {@code true} with the specified
* character set name.
*
* @throws UnsupportedCharsetException
* if the specified character set name is not supported by the
* current VM
*/
String toString(
int index, int length, String charsetName,
ChannelBufferIndexFinder terminatorFinder);
/**
* Returns a hash code which was calculated from the content of this
* buffer. If there's a byte array which is
* {@linkplain #equals(Object) equal to} this array, both arrays should
* return the same value.
*/
int hashCode();
/**
* Determines if the content of the specified buffer is identical to the
* content of this array. 'Identical' here means:
* <ul>
* <li>the size of the contents of the two buffers are same and</li>
* <li>every single byte of the content of the two buffers are same.</li>
* </ul>
* Please note that it doesn't compare {@link #readerIndex()} nor
* {@link #writerIndex()}. This method also returns {@code false} for
* {@code null} and an object which is not an instance of
* {@link ChannelBuffer} type.
*/
boolean equals(Object obj);
/**
* Compares the content of the specified buffer to the content of this
* buffer. Comparison is performed in the same manner with the string
* comparison functions of various languages such as {@code strcmp},
* {@code memcmp} and {@link String#compareTo(String)}.
*/
int compareTo(ChannelBuffer buffer);
/**
* Returns the string representation of this buffer. This method doesn't
* necessarily return the whole content of the buffer but returns
* the values of the key properties such as {@link #readerIndex()},
* {@link #writerIndex()} and {@link #capacity()}..
*/
String toString();
}
| src/main/java/org/jboss/netty/buffer/ChannelBuffer.java | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @author tags. See the COPYRIGHT.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.netty.buffer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
/**
* Random and sequential accessible sequence of zero or more bytes (octets).
* This interface provides an abstract view for one or more primitive byte
* arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}.
*
* <h3>Creation of a buffer</h3>
*
* It is common for a user to create a new buffer using {@link ChannelBuffers}
* utility class rather than calling an individual implementation's constructor.
*
* <h3>Random Access Indexing</h3>
*
* Just like an ordinary primitive byte array, {@link ChannelBuffer} uses
* <a href="http://en.wikipedia.org/wiki/Index_(information_technology)#Array_element_identifier">zero-based indexing</a>.
* It means the index of the first byte is always {@code 0} and the index of
* the last byte is always {@link #capacity() capacity - 1}. For example, to
* iterate all bytes of a buffer, you can do the following, regardless of
* its internal implementation:
*
* <pre>
* ChannelBuffer buffer = ...;
* for (int i = 0; i < buffer.capacity(); i ++</strong>) {
* byte b = array.getByte(i);
* System.out.println((char) b);
* }
* </pre>
*
* <h3>Sequential Access Indexing</h3>
*
* {@link ChannelBuffer} provides two pointer variables to support sequential
* read and write operations - {@link #readerIndex() readerIndex} for a read
* operation and {@link #writerIndex() writerIndex} for a write operation
* respectively. The following diagram shows how a buffer is segmented into
* three areas by the two pointers:
*
* <pre>
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable space |
* | | (CONTENT) | |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
* </pre>
*
* <h4>Readable bytes (the actual 'content' of the buffer)</h4>
*
* This segment, so called 'the <strong>content</strong> of a buffer', is where
* the actual data is stored. Any operation whose name starts with
* {@code read} or {@code skip} will get or skip the data at the current
* {@link #readerIndex() readerIndex} and increase it by the number of read
* bytes. If the argument of the read operation is also a {@link ChannelBuffer}
* and no start index is specified, the specified buffer's
* {@link #readerIndex() readerIndex} is increased together.
* <p>
* If there's not enough content left, {@link IndexOutOfBoundsException} is
* raised. The default value of newly allocated, wrapped or copied buffer's
* {@link #readerIndex() readerIndex} is {@code 0}.
*
* <pre>
* // Iterates the readable bytes of a buffer.
* ChannelBuffer buffer = ...;
* while (buffer.readable()) {
* System.out.println(buffer.readByte());
* }
* </pre>
*
* <h4>Writable space</h4>
*
* This segment is a undefined space which needs to be filled. Any operation
* whose name ends with {@code write} will write the data at the current
* {@link #writerIndex() writerIndex} and increase it by the number of written
* bytes. If the argument of the write operation is also a {@link ChannelBuffer},
* and no start index is specified, the specified buffer's
* {@link #readerIndex() readerIndex} is increased together.
* <p>
* If there's not enough writable space left, {@link IndexOutOfBoundsException}
* is raised. The default value of newly allocated buffer's
* {@link #writerIndex() writerIndex} is {@code 0}. The default value of
* wrapped or copied buffer's {@link #writerIndex() writerIndex} is the
* {@link #capacity() capacity} of the buffer.
*
* <pre>
* // Fills the writable space of a buffer with random integers.
* ChannelBuffer buffer = ...;
* while (buffer.writableBytes() >= 4) {
* buffer.writeInt(random.nextInt());
* }
* </pre>
*
* <h4>Discardable bytes</h4>
*
* This segment contains the bytes which were read already by a read operation.
* Initially, the size of this segment is {@code 0}, but its size increases up
* to the {@link #writerIndex() writerIndex} as read operations are executed.
* The read bytes can be discarded by calling {@link #discardReadBytes()} to
* reclaim unused area as depicted by the following diagram:
*
* <pre>
* BEFORE discardReadBytes()
*
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable space |
* | | (CONTENT) | |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
*
*
* AFTER discardReadBytes()
*
* +------------------+--------------------------------------+
* | readable bytes | writable space (got more space) |
* | (CONTENT) | |
* +------------------+--------------------------------------+
* | | |
* readerIndex (0) <= writerIndex (decreased) <= capacity
* </pre>
*
* <h4>Clearing the buffer indexes</h4>
*
* You can set both {@link #readerIndex() readerIndex} and
* {@link #writerIndex() writerIndex} to {@code 0} by calling {@link #clear()}.
* It doesn't clear the buffer content (e.g. filling with {@code 0}) but just
* clears the two pointers. Please also note that the semantic of this
* operation is different from {@link ByteBuffer#clear()}.
*
* <pre>
* BEFORE clear()
*
* +-------------------+------------------+------------------+
* | discardable bytes | readable bytes | writable space |
* | | (CONTENT) | |
* +-------------------+------------------+------------------+
* | | | |
* 0 <= readerIndex <= writerIndex <= capacity
*
*
* AFTER clear()
*
* +---------------------------------------------------------+
* | writable space (got more space) |
* +---------------------------------------------------------+
* | |
* 0 = readerIndex = writerIndex <= capacity
* </pre>
*
* <h3>Search operations</h3>
*
* Various {@code indexOf()} methods help you locate an index of a value which
* meets a certain criteria. Complicated dynamic sequential search can be done
* with {@link ChannelBufferIndexFinder} as well as simple static single byte
* search.
*
* <h3>Mark and reset</h3>
*
* There are two marker indexes in every buffer. One is for storing
* {@link #readerIndex() readerIndex} and the other is for storing
* {@link #writerIndex() writerIndex}. You can always reposition one of the
* two indexes by calling a reset method. It works in a similar fashion to
* the mark and reset methods in {@link InputStream} except that there's no
* {@code readlimit}.
*
* <h3>Derived buffers</h3>
*
* You can create a view of an existing buffer by calling either
* {@link #duplicate()}, {@link #slice()} or {@link #slice(int, int)}.
* A derived buffer will have an independent {@link #readerIndex() readerIndex},
* {@link #writerIndex() writerIndex} and marker indexes, while it shares
* other internal data representation, just like a NIO {@link ByteBuffer} does.
* <p>
* In case a completely fresh copy of an existing buffer is required, please
* call {@link #copy()} method instead.
*
* <h3>Conversion to existing JDK types</h3>
*
* <h4>NIO {@link ByteBuffer}</h4>
*
* Various {@link #toByteBuffer()} and {@link #toByteBuffers()} methods convert
* a {@link ChannelBuffer} into one or more NIO buffers. These methods avoid
* buffer allocation and memory copy whenever possible, but there's no
* guarantee that memory copy will not be involved or that an explicit memory
* copy will be involved.
*
* <h4>{@link String}</h4>
*
* Various {@link #toString(String)} methods convert a {@link ChannelBuffer}
* into a {@link String}. Plesae note that {@link #toString()} is not a
* conversion method.
*
* <h4>{@link InputStream} and {@link OutputStream}</h4>
*
* Please refer to {@link ChannelBufferInputStream} and
* {@link ChannelBufferOutputStream}.
*
* @author The Netty Project ([email protected])
* @author Trustin Lee ([email protected])
*
* @version $Rev$, $Date$
*
* @apiviz.landmark
*/
public interface ChannelBuffer extends Comparable<ChannelBuffer> {
/**
* A buffer whose capacity is {@code 0}.
*/
static ChannelBuffer EMPTY_BUFFER = new BigEndianHeapChannelBuffer(0);
/**
* Returns the number of bytes (octets) this buffer can contain.
*/
int capacity();
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Endianness">endianness</a>
* of this buffer.
*/
ByteOrder order();
/**
* Returns the {@code readerIndex} of this buffer.
*/
int readerIndex();
/**
* Sets the {@code readerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code readerIndex} is less than 0 or
* greater than {@code writerIndex}
*/
void readerIndex(int readerIndex);
/**
* Returns the {@code writerIndex} of this buffer.
*/
int writerIndex();
/**
* Sets the {@code writerIndex} of this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code writerIndex} is less than
* {@code readerIndex} or greater than {@code capacity}
*/
void writerIndex(int writerIndex);
/**
* Sets the {@code readerIndex} and {@code writerIndex} of this buffer
* in one shot. This method is useful because you don't need to worry
* about the invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)}
* methods. For example, the following code will fail:
*
* <pre>
* // Create a buffer whose readerIndex, writerIndex and capacity are
* // 0, 0 and 8 respectively.
* ChannelBuffer buf = ChannelBuffers.buffer(8);
*
* // IndexOutOfBoundsException is thrown because the specified
* // readerIndex (2) cannot be greater than the current writerIndex (0).
* buf.readerIndex(2);
* buf.writerIndex(4);
* </pre>
*
* The following code will also fail:
*
* <pre>
* // Create a buffer whose readerIndex, writerIndex and capacity are
* // 0, 8 and 8 respectively.
* ChannelBuffer buf = ChannelBuffers.wrappedBuffer(new byte[8]);
*
* // readerIndex becomes 8.
* buf.readLong();
*
* // IndexOutOfBoundsException is thrown because the specified
* // writerIndex (4) cannot be less than the current readerIndex (8).
* buf.writerIndex(4);
* buf.readerIndex(2);
* </pre>
*
* By contrast, {@link #setIndex(int, int)} guarantees that it never
* throws an {@link IndexOutOfBoundsException} as long as the specified
* indexes meets all constraints, regardless what the current index values
* of the buffer are:
*
* <pre>
* // No matter what the current state of the buffer is, the following
* // call always succeeds as long as the capacity of the buffer is not
* // less than 4.
* buf.setIndex(2, 4);
* </pre>
*
* @throws IndexOutOfBoundsException
* if the specified {@code readerIndex} is less than 0,
* if the specified {@code writerIndex} is less than the specified
* {@code readerIndex} or if the specified {@code writerIndex} is
* greater than {@code capacity}
*/
void setIndex(int readerIndex, int writerIndex);
/**
* Returns the number of readable bytes which equals to
* {@code (writerIndex - readerIndex)}.
*/
int readableBytes();
/**
* Returns the number of writable bytes which equals to
* {@code (capacity - writerIndex)}.
*/
int writableBytes();
/**
* Returns {@code true} if and only if {@link #readableBytes() readableBytes}
* if greater than {@code 0}.
*/
boolean readable();
/**
* Returns {@code true} if and only if {@link #writableBytes() writableBytes}
* if greater than {@code 0}.
*/
boolean writable();
/**
* Sets the {@code readerIndex} and {@code writerIndex} of this buffer to
* {@code 0}.
* This method is identical to {@link #setIndex(int, int) setIndex(0, 0)}.
* <p>
* Please note that the behavior of this method is different
* from that of NIO {@link ByteBuffer}, which sets the {@code limit} to
* the {@code capacity}.
*/
void clear();
/**
* Marks the current {@code readerIndex} in this buffer. You can restore
* the marked {@code readerIndex} by calling {@link #resetReaderIndex()}.
* The initial value of the marked {@code readerIndex} is always {@code 0}.
*/
void markReaderIndex();
/**
* Repositions the current {@code readerIndex} to the marked {@code readerIndex}
* in this buffer.
*
* @throws IndexOutOfBoundsException
* if the current {@code writerIndex} is less than the marked
* {@code readerIndex}
*/
void resetReaderIndex();
/**
* Marks the current {@code writerIndex} in this buffer. You can restore
* the marked {@code writerIndex} by calling {@link #resetWriterIndex()}.
* The initial value of the marked {@code writerIndex} is always {@code 0}.
*/
void markWriterIndex();
/**
* Repositions the current {@code writerIndex} to the marked {@code writerIndex}
* in this buffer.
*
* @throws IndexOutOfBoundsException
* if the current {@code readerIndex} is greater than the marked
* {@code writerIndex}
*/
void resetWriterIndex();
/**
* Discards the bytes between the 0th index and {@code readerIndex}.
* It moves the bytes between {@code readerIndex} and {@code writerIndex}
* to the 0th index, and sets {@code readerIndex} and {@code writerIndex}
* to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively.
* <p>
* Please refer to the class documentation for more detailed explanation
* with a diagram.
*/
void discardReadBytes();
/**
* Gets a byte at the specified absolute {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 1} is greater than {@code capacity}
*/
byte getByte(int index);
/**
* Gets a unsigned byte at the specified absolute {@code index} in this
* buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 1} is greater than {@code capacity}
*/
short getUnsignedByte(int index);
/**
* Gets a 16-bit short integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 2} is greater than {@code capacity}
*/
short getShort(int index);
/**
* Gets a unsigned 16-bit short integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 2} is greater than {@code capacity}
*/
int getUnsignedShort(int index);
/**
* Gets a 24-bit medium integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 3} is greater than {@code capacity}
*/
int getMedium(int index);
/**
* Gets a unsigned 24-bit medium integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 3} is greater than {@code capacity}
*/
int getUnsignedMedium(int index);
/**
* Gets a 32-bit integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 4} is greater than {@code capacity}
*/
int getInt(int index);
/**
* Gets a unsigned 32-bit integer at the specified absolute {@code index}
* in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 4} is greater than {@code capacity}
*/
long getUnsignedInt(int index);
/**
* Gets a 64-bit long integer at the specified absolute {@code index} in
* this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 8} is greater than {@code capacity}
*/
long getLong(int index);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index} until the destination becomes
* unwritable. This method is basically same with {@link #getBytes(int, ChannelBuffer, int, int)},
* except that this method advances the {@code writerIndex} of the
* destination while {@link #getBytes(int, ChannelBuffer, int, int)}
* doesn't.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + dst.writableBytes} is greater than {@code capacity}
*/
void getBytes(int index, ChannelBuffer dst);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code dstIndex} is less than {@code 0},
* if {@code index + length} is greater than {@code capacity}, or
* if {@code dstIndex + length} is greater than {@code dst.capacity}
*/
void getBytes(int index, ChannelBuffer dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + dst.length} is greater than {@code capacity}
*/
void getBytes(int index, byte[] dst);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code dstIndex} is less than {@code 0},
* if {@code index + length} is greater than {@code capacity}, or
* if {@code dstIndex + length} is greater than {@code dst.lenggth}
*/
void getBytes(int index, byte[] dst, int dstIndex, int length);
/**
* Transfers this buffer's data to the specified destination starting at
* the specified absolute {@code index} until the destination's position
* reaches to its limit.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + dst.remaining()} is greater than {@code capacity}
*/
void getBytes(int index, ByteBuffer dst);
/**
* Transfers this buffer's data to the specified stream starting at the
* specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code capacity}
* @throws IOException
* if the specified stream threw an exception during I/O
*/
void getBytes(int index, OutputStream out, int length) throws IOException;
/**
* Transfers this buffer's data to the specified channel starting at the
* specified absolute {@code index}.
*
* @return the number of bytes written out to the specified channel
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code capacity}
* @throws IOException
* if the specified channel threw an exception during I/O
*/
int getBytes(int index, GatheringByteChannel out, int length) throws IOException;
/**
* Sets the specified byte at the specified absolute {@code index} in this
* buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 1} is greater than {@code capacity}
*/
void setByte(int index, byte value);
/**
* Sets the specified 16-bit short integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 2} is greater than {@code capacity}
*/
void setShort(int index, short value);
/**
* Sets the specified 24-bit medium integer at the specified absolute
* {@code index} in this buffer. Please note that the most significant
* byte is ignored in the specified value.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 3} is greater than {@code capacity}
*/
void setMedium(int index, int value);
/**
* Sets the specified 32-bit integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 4} is greater than {@code capacity}
*/
void setInt(int index, int value);
/**
* Sets the specified 64-bit long integer at the specified absolute
* {@code index} in this buffer.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* {@code index + 8} is greater than {@code capacity}
*/
void setLong(int index, long value);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index} until the destination becomes
* unreadable. This method is basically same with {@link #setBytes(int, ChannelBuffer, int, int)},
* except that this method advances the {@code readerIndex} of the source
* buffer while {@link #getBytes(int, ChannelBuffer, int, int)} doesn't.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + dst.writableBytes} is greater than {@code capacity}
*/
void setBytes(int index, ChannelBuffer src);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code srcIndex} is less than {@code 0},
* if {@code index + length} is greater than {@code capacity}, or
* if {@code srcIndex + length} is greater than {@code src.capacity}
*/
void setBytes(int index, ChannelBuffer src, int srcIndex, int length);
/**
* Transfers the specified source array's data to this buffer starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + src.length} is greater than {@code capacity}
*/
void setBytes(int index, byte[] src);
/**
* Transfers the specified source array's data to this buffer starting at
* the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0},
* if the specified {@code srcIndex} is less than {@code 0},
* if {@code index + length} is greater than {@code capacity}, or
* if {@code srcIndex + length} is greater than {@code src.lenggth}
*/
void setBytes(int index, byte[] src, int srcIndex, int length);
/**
* Transfers the specified source buffer's data to this buffer starting at
* the specified absolute {@code index} until the source buffer's position
* reaches to its limit.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + src.remaining()} is greater than {@code capacity}
*/
void setBytes(int index, ByteBuffer src);
/**
* Transfers the content of the specified source stream to this buffer
* starting at the specified absolute {@code index}.
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code capacity}
* @throws IOException
* if the specified stream threw an exception during I/O
*/
void setBytes(int index, InputStream in, int length) throws IOException;
/**
* Transfers the content of the specified source channel to this buffer
* starting at the specified absolute {@code index}.
*
* @return the number of bytes read from the specified channel
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code capacity}
* @throws IOException
* if the specified channel threw an exception during I/O
*/
int setBytes(int index, ScatteringByteChannel in, int length) throws IOException;
/**
* Fills this buffer with <tt>NUL (0x00)</tt> starting at the specified
* absolute {@code index}.
*
* @param length the number of <tt>NUL</tt>s to write to the buffer
*
* @throws IndexOutOfBoundsException
* if the specified {@code index} is less than {@code 0} or
* if {@code index + length} is greater than {@code capacity}
*/
void setZero(int index, int length);
/**
* Gets a byte at the current {@code readerIndex} and increases
* the {@code readerIndex} by {@code 1} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex} is not less than {@code writerIndex}
*/
byte readByte();
/**
* Gets a unsigned byte at the current {@code readerIndex} and increases
* the {@code readerIndex} by {@code 1} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 1} is greater than {@code writerIndex}
*/
short readUnsignedByte();
/**
* Gets a 16-bit short integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 2} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 2} is greater than {@code writerIndex}
*/
short readShort();
/**
* Gets a unsigned 16-bit short integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 2} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 2} is greater than {@code writerIndex}
*/
int readUnsignedShort();
/**
* Gets a 24-bit medium integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 3} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 3} is greater than {@code writerIndex}
*/
int readMedium();
/**
* Gets a unsigned 24-bit medium integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 3} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 3} is greater than {@code writerIndex}
*/
int readUnsignedMedium();
/**
* Gets a 32-bit integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 4} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 4} is greater than {@code writerIndex}
*/
int readInt();
/**
* Gets a unsigned 32-bit integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 4} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 4} is greater than {@code writerIndex}
*/
long readUnsignedInt();
/**
* Gets a 64-bit integer at the current {@code readerIndex}
* and increases the {@code readerIndex} by {@code 8} in this buffer.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + 8} is greater than {@code writerIndex}
*/
long readLong();
ChannelBuffer readBytes(int length);
ChannelBuffer readBytes(ChannelBufferIndexFinder endIndexFinder);
ChannelBuffer readSlice(int length);
ChannelBuffer readSlice(ChannelBufferIndexFinder endIndexFinder);
void readBytes(ChannelBuffer dst);
void readBytes(ChannelBuffer dst, int length);
void readBytes(ChannelBuffer dst, int dstIndex, int length);
void readBytes(byte[] dst);
void readBytes(byte[] dst, int dstIndex, int length);
void readBytes(ByteBuffer dst);
void readBytes(OutputStream out, int length) throws IOException;
int readBytes(GatheringByteChannel out, int length) throws IOException;
void skipBytes(int length);
int skipBytes(ChannelBufferIndexFinder firstIndexFinder);
void writeByte(byte value);
void writeShort(short value);
void writeMedium(int value);
void writeInt(int value);
void writeLong(long value);
void writeBytes(ChannelBuffer src);
void writeBytes(ChannelBuffer src, int length);
void writeBytes(ChannelBuffer src, int srcIndex, int length);
void writeBytes(byte[] src);
void writeBytes(byte[] src, int srcIndex, int length);
void writeBytes(ByteBuffer src);
void writeBytes(InputStream in, int length) throws IOException;
int writeBytes(ScatteringByteChannel in, int length) throws IOException;
void writeZero(int length);
int indexOf(int fromIndex, int toIndex, byte value);
int indexOf(int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder);
ChannelBuffer copy();
ChannelBuffer copy(int index, int length);
ChannelBuffer slice();
ChannelBuffer slice(int index, int length);
ChannelBuffer duplicate();
ByteBuffer toByteBuffer();
ByteBuffer toByteBuffer(int index, int length);
ByteBuffer[] toByteBuffers();
ByteBuffer[] toByteBuffers(int index, int length);
String toString(String charsetName);
String toString(
String charsetName, ChannelBufferIndexFinder terminatorFinder);
String toString(int index, int length, String charsetName);
String toString(
int index, int length, String charsetName,
ChannelBufferIndexFinder terminatorFinder);
/**
* Returns a hash code which was calculated from the content of this
* buffer. If there's a byte array which is
* {@linkplain #equals(Object) equal to} this array, both arrays should
* return the same value.
*/
int hashCode();
/**
* Determines if the content of the specified buffer is identical to the
* content of this array. 'Identical' here means:
* <ul>
* <li>the size of the contents of the two buffers are same and</li>
* <li>every single byte of the content of the two buffers are same.</li>
* </ul>
* Please note that it doesn't compare {@link #readerIndex()} nor
* {@link #writerIndex()}. This method also returns {@code false} for
* {@code null} and an object which is not an instance of
* {@link ChannelBuffer} type.
*/
boolean equals(Object obj);
/**
* Compares the content of the specified buffer to the content of this
* buffer. Comparison is performed in the same manner with the string
* comparison functions of various languages such as {@code strcmp},
* {@code memcmp} and {@link String#compareTo(String)}.
*/
int compareTo(ChannelBuffer buffer);
/**
* Returns the string representation of this buffer. This method doesn't
* necessarily return the whole content of the buffer but returns
* the values of the key properties such as {@link #readerIndex()},
* {@link #writerIndex()} and {@link #capacity()}..
*/
String toString();
}
| Added even more JavaDoc
| src/main/java/org/jboss/netty/buffer/ChannelBuffer.java | Added even more JavaDoc | <ide><path>rc/main/java/org/jboss/netty/buffer/ChannelBuffer.java
<ide> import java.nio.ByteOrder;
<ide> import java.nio.channels.GatheringByteChannel;
<ide> import java.nio.channels.ScatteringByteChannel;
<add>import java.nio.charset.UnsupportedCharsetException;
<add>import java.util.NoSuchElementException;
<ide>
<ide> /**
<ide> * Random and sequential accessible sequence of zero or more bytes (octets).
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code readerIndex} is less than 0 or
<del> * greater than {@code writerIndex}
<add> * greater than {@code this.writerIndex}
<ide> */
<ide> void readerIndex(int readerIndex);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code writerIndex} is less than
<del> * {@code readerIndex} or greater than {@code capacity}
<add> * {@code this.readerIndex} or greater than {@code this.capacity}
<ide> */
<ide> void writerIndex(int writerIndex);
<ide>
<ide> /**
<ide> * Sets the {@code readerIndex} and {@code writerIndex} of this buffer
<del> * in one shot. This method is useful because you don't need to worry
<del> * about the invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)}
<add> * in one shot. This method is useful when you have to worry about the
<add> * invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)}
<ide> * methods. For example, the following code will fail:
<ide> *
<ide> * <pre>
<ide> *
<ide> * By contrast, {@link #setIndex(int, int)} guarantees that it never
<ide> * throws an {@link IndexOutOfBoundsException} as long as the specified
<del> * indexes meets all constraints, regardless what the current index values
<add> * indexes meet all constraints, regardless what the current index values
<ide> * of the buffer are:
<ide> *
<ide> * <pre>
<ide> * if the specified {@code readerIndex} is less than 0,
<ide> * if the specified {@code writerIndex} is less than the specified
<ide> * {@code readerIndex} or if the specified {@code writerIndex} is
<del> * greater than {@code capacity}
<add> * greater than {@code this.capacity}
<ide> */
<ide> void setIndex(int readerIndex, int writerIndex);
<ide>
<ide> /**
<ide> * Returns the number of readable bytes which equals to
<del> * {@code (writerIndex - readerIndex)}.
<add> * {@code (this.writerIndex - this.readerIndex)}.
<ide> */
<ide> int readableBytes();
<ide>
<ide> /**
<ide> * Returns the number of writable bytes which equals to
<del> * {@code (capacity - writerIndex)}.
<add> * {@code (this.capacity - this.writerIndex)}.
<ide> */
<ide> int writableBytes();
<ide>
<ide> /**
<del> * Returns {@code true} if and only if {@link #readableBytes() readableBytes}
<del> * if greater than {@code 0}.
<add> * Returns {@code true}
<add> * if and only if {@code (this.writerIndex - this.readerIndex)} is greater
<add> * than {@code 0}.
<ide> */
<ide> boolean readable();
<ide>
<ide> /**
<del> * Returns {@code true} if and only if {@link #writableBytes() writableBytes}
<del> * if greater than {@code 0}.
<add> * Returns {@code true}
<add> * if and only if {@code (this.capacity - this.writerIndex)} is greater
<add> * than {@code 0}.
<ide> */
<ide> boolean writable();
<ide>
<ide> * <p>
<ide> * Please note that the behavior of this method is different
<ide> * from that of NIO {@link ByteBuffer}, which sets the {@code limit} to
<del> * the {@code capacity}.
<add> * the {@code capacity} of the buffer.
<ide> */
<ide> void clear();
<ide>
<ide> /**
<del> * Marks the current {@code readerIndex} in this buffer. You can restore
<del> * the marked {@code readerIndex} by calling {@link #resetReaderIndex()}.
<del> * The initial value of the marked {@code readerIndex} is always {@code 0}.
<add> * Marks the current {@code readerIndex} in this buffer. You can
<add> * reposition the current {@code readerIndex} to the marked
<add> * {@code readerIndex} by calling {@link #resetReaderIndex()}.
<add> * The initial value of the marked {@code readerIndex} is {@code 0}.
<ide> */
<ide> void markReaderIndex();
<ide>
<ide> /**
<del> * Repositions the current {@code readerIndex} to the marked {@code readerIndex}
<del> * in this buffer.
<add> * Repositions the current {@code readerIndex} to the marked
<add> * {@code readerIndex} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the current {@code writerIndex} is less than the marked
<ide> void resetReaderIndex();
<ide>
<ide> /**
<del> * Marks the current {@code writerIndex} in this buffer. You can restore
<del> * the marked {@code writerIndex} by calling {@link #resetWriterIndex()}.
<del> * The initial value of the marked {@code writerIndex} is always {@code 0}.
<add> * Marks the current {@code writerIndex} in this buffer. You can
<add> * reposition the current {@code writerIndex} to the marked
<add> * {@code writerIndex} by calling {@link #resetWriterIndex()}.
<add> * The initial value of the marked {@code writerIndex} is {@code 0}.
<ide> */
<ide> void markWriterIndex();
<ide>
<ide> /**
<del> * Repositions the current {@code writerIndex} to the marked {@code writerIndex}
<del> * in this buffer.
<add> * Repositions the current {@code writerIndex} to the marked
<add> * {@code writerIndex} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the current {@code readerIndex} is greater than the marked
<ide> * to the 0th index, and sets {@code readerIndex} and {@code writerIndex}
<ide> * to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively.
<ide> * <p>
<del> * Please refer to the class documentation for more detailed explanation
<del> * with a diagram.
<add> * Please refer to the class documentation for more detailed explanation.
<ide> */
<ide> void discardReadBytes();
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 1} is greater than {@code capacity}
<add> * {@code index + 1} is greater than {@code this.capacity}
<ide> */
<ide> byte getByte(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 1} is greater than {@code capacity}
<add> * {@code index + 1} is greater than {@code this.capacity}
<ide> */
<ide> short getUnsignedByte(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 2} is greater than {@code capacity}
<add> * {@code index + 2} is greater than {@code this.capacity}
<ide> */
<ide> short getShort(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 2} is greater than {@code capacity}
<add> * {@code index + 2} is greater than {@code this.capacity}
<ide> */
<ide> int getUnsignedShort(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 3} is greater than {@code capacity}
<add> * {@code index + 3} is greater than {@code this.capacity}
<ide> */
<ide> int getMedium(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 3} is greater than {@code capacity}
<add> * {@code index + 3} is greater than {@code this.capacity}
<ide> */
<ide> int getUnsignedMedium(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 4} is greater than {@code capacity}
<add> * {@code index + 4} is greater than {@code this.capacity}
<ide> */
<ide> int getInt(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 4} is greater than {@code capacity}
<add> * {@code index + 4} is greater than {@code this.capacity}
<ide> */
<ide> long getUnsignedInt(int index);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 8} is greater than {@code capacity}
<add> * {@code index + 8} is greater than {@code this.capacity}
<ide> */
<ide> long getLong(int index);
<ide>
<ide> /**
<ide> * Transfers this buffer's data to the specified destination starting at
<ide> * the specified absolute {@code index} until the destination becomes
<del> * unwritable. This method is basically same with {@link #getBytes(int, ChannelBuffer, int, int)},
<del> * except that this method advances the {@code writerIndex} of the
<del> * destination while {@link #getBytes(int, ChannelBuffer, int, int)}
<del> * doesn't.
<del> *
<del> * @throws IndexOutOfBoundsException
<del> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + dst.writableBytes} is greater than {@code capacity}
<add> * unwritable. This method is basically same with
<add> * {@link #getBytes(int, ChannelBuffer, int, int)}, except that this
<add> * method increases the {@code writerIndex} of the destination by the
<add> * number of the transferred bytes while
<add> * {@link #getBytes(int, ChannelBuffer, int, int)} doesn't.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code index} is less than {@code 0} or
<add> * if {@code index + dst.writableBytes} is greater than
<add> * {@code this.capacity}
<ide> */
<ide> void getBytes(int index, ChannelBuffer dst);
<ide>
<ide> * Transfers this buffer's data to the specified destination starting at
<ide> * the specified absolute {@code index}.
<ide> *
<add> * @param dstIndex the first index of the destination
<add> * @param length the number of bytes to transfer
<add> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0},
<ide> * if the specified {@code dstIndex} is less than {@code 0},
<del> * if {@code index + length} is greater than {@code capacity}, or
<del> * if {@code dstIndex + length} is greater than {@code dst.capacity}
<add> * if {@code index + length} is greater than
<add> * {@code this.capacity}, or
<add> * if {@code dstIndex + length} is greater than
<add> * {@code dst.capacity}
<ide> */
<ide> void getBytes(int index, ChannelBuffer dst, int dstIndex, int length);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + dst.length} is greater than {@code capacity}
<add> * if {@code index + dst.length} is greater than
<add> * {@code this.capacity}
<ide> */
<ide> void getBytes(int index, byte[] dst);
<ide>
<ide> * Transfers this buffer's data to the specified destination starting at
<ide> * the specified absolute {@code index}.
<ide> *
<add> * @param dstIndex the first index of the destination
<add> * @param length the number of bytes to transfer
<add> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0},
<ide> * if the specified {@code dstIndex} is less than {@code 0},
<del> * if {@code index + length} is greater than {@code capacity}, or
<del> * if {@code dstIndex + length} is greater than {@code dst.lenggth}
<add> * if {@code index + length} is greater than
<add> * {@code this.capacity}, or
<add> * if {@code dstIndex + length} is greater than
<add> * {@code dst.length}
<ide> */
<ide> void getBytes(int index, byte[] dst, int dstIndex, int length);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + dst.remaining()} is greater than {@code capacity}
<add> * if {@code index + dst.remaining()} is greater than
<add> * {@code this.capacity}
<ide> */
<ide> void getBytes(int index, ByteBuffer dst);
<ide>
<ide> * Transfers this buffer's data to the specified stream starting at the
<ide> * specified absolute {@code index}.
<ide> *
<del> * @throws IndexOutOfBoundsException
<del> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + length} is greater than {@code capacity}
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code index} is less than {@code 0} or
<add> * if {@code index + length} is greater than
<add> * {@code this.capacity}
<ide> * @throws IOException
<ide> * if the specified stream threw an exception during I/O
<ide> */
<ide> * Transfers this buffer's data to the specified channel starting at the
<ide> * specified absolute {@code index}.
<ide> *
<del> * @return the number of bytes written out to the specified channel
<del> *
<del> * @throws IndexOutOfBoundsException
<del> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + length} is greater than {@code capacity}
<add> * @param length the maximum number of bytes to transfer
<add> *
<add> * @return the actual number of bytes written out to the specified channel
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code index} is less than {@code 0} or
<add> * if {@code index + length} is greater than
<add> * {@code this.capacity}
<ide> * @throws IOException
<ide> * if the specified channel threw an exception during I/O
<ide> */
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 1} is greater than {@code capacity}
<add> * {@code index + 1} is greater than {@code this.capacity}
<ide> */
<ide> void setByte(int index, byte value);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 2} is greater than {@code capacity}
<add> * {@code index + 2} is greater than {@code this.capacity}
<ide> */
<ide> void setShort(int index, short value);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 3} is greater than {@code capacity}
<add> * {@code index + 3} is greater than {@code this.capacity}
<ide> */
<ide> void setMedium(int index, int value);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 4} is greater than {@code capacity}
<add> * {@code index + 4} is greater than {@code this.capacity}
<ide> */
<ide> void setInt(int index, int value);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * {@code index + 8} is greater than {@code capacity}
<add> * {@code index + 8} is greater than {@code this.capacity}
<ide> */
<ide> void setLong(int index, long value);
<ide>
<ide> /**
<ide> * Transfers the specified source buffer's data to this buffer starting at
<ide> * the specified absolute {@code index} until the destination becomes
<del> * unreadable. This method is basically same with {@link #setBytes(int, ChannelBuffer, int, int)},
<del> * except that this method advances the {@code readerIndex} of the source
<del> * buffer while {@link #getBytes(int, ChannelBuffer, int, int)} doesn't.
<del> *
<del> * @throws IndexOutOfBoundsException
<del> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + dst.writableBytes} is greater than {@code capacity}
<add> * unreadable. This method is basically same with
<add> * {@link #setBytes(int, ChannelBuffer, int, int)}, except that this
<add> * method increased the {@code readerIndex} of the source buffer by
<add> * the number of the transferred bytes while
<add> * {@link #getBytes(int, ChannelBuffer, int, int)} doesn't.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code index} is less than {@code 0} or
<add> * if {@code index + src.readableBytes} is greater than
<add> * {@code this.capacity}
<ide> */
<ide> void setBytes(int index, ChannelBuffer src);
<ide>
<ide> * Transfers the specified source buffer's data to this buffer starting at
<ide> * the specified absolute {@code index}.
<ide> *
<add> * @param srcIndex the first index of the source
<add> * @param length the number of bytes to transfer
<add> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0},
<ide> * if the specified {@code srcIndex} is less than {@code 0},
<del> * if {@code index + length} is greater than {@code capacity}, or
<del> * if {@code srcIndex + length} is greater than {@code src.capacity}
<add> * if {@code index + length} is greater than
<add> * {@code this.capacity}, or
<add> * if {@code srcIndex + length} is greater than
<add> * {@code src.capacity}
<ide> */
<ide> void setBytes(int index, ChannelBuffer src, int srcIndex, int length);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + src.length} is greater than {@code capacity}
<add> * if {@code index + src.length} is greater than
<add> * {@code this.capacity}
<ide> */
<ide> void setBytes(int index, byte[] src);
<ide>
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0},
<ide> * if the specified {@code srcIndex} is less than {@code 0},
<del> * if {@code index + length} is greater than {@code capacity}, or
<del> * if {@code srcIndex + length} is greater than {@code src.lenggth}
<add> * if {@code index + length} is greater than
<add> * {@code this.capacity}, or
<add> * if {@code srcIndex + length} is greater than {@code src.length}
<ide> */
<ide> void setBytes(int index, byte[] src, int srcIndex, int length);
<ide>
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + src.remaining()} is greater than {@code capacity}
<add> * if {@code index + src.remaining()} is greater than
<add> * {@code this.capacity}
<ide> */
<ide> void setBytes(int index, ByteBuffer src);
<ide>
<ide> * Transfers the content of the specified source stream to this buffer
<ide> * starting at the specified absolute {@code index}.
<ide> *
<del> * @throws IndexOutOfBoundsException
<del> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + length} is greater than {@code capacity}
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code index} is less than {@code 0} or
<add> * if {@code index + length} is greater than {@code this.capacity}
<ide> * @throws IOException
<ide> * if the specified stream threw an exception during I/O
<ide> */
<ide> * Transfers the content of the specified source channel to this buffer
<ide> * starting at the specified absolute {@code index}.
<ide> *
<del> * @return the number of bytes read from the specified channel
<del> *
<del> * @throws IndexOutOfBoundsException
<del> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + length} is greater than {@code capacity}
<add> * @param length the maximum number of bytes to transfer
<add> *
<add> * @return the actual number of bytes read in from the specified channel
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code index} is less than {@code 0} or
<add> * if {@code index + length} is greater than {@code this.capacity}
<ide> * @throws IOException
<ide> * if the specified channel threw an exception during I/O
<ide> */
<ide> *
<ide> * @throws IndexOutOfBoundsException
<ide> * if the specified {@code index} is less than {@code 0} or
<del> * if {@code index + length} is greater than {@code capacity}
<add> * if {@code index + length} is greater than {@code this.capacity}
<ide> */
<ide> void setZero(int index, int length);
<ide>
<ide> * the {@code readerIndex} by {@code 1} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex} is not less than {@code writerIndex}
<add> * if {@code this.readerIndex + 1} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> byte readByte();
<ide>
<ide> * the {@code readerIndex} by {@code 1} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 1} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 1} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> short readUnsignedByte();
<ide>
<ide> * and increases the {@code readerIndex} by {@code 2} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 2} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 2} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> short readShort();
<ide>
<ide> * and increases the {@code readerIndex} by {@code 2} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 2} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 2} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> int readUnsignedShort();
<ide>
<ide> * and increases the {@code readerIndex} by {@code 3} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 3} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 3} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> int readMedium();
<ide>
<ide> * and increases the {@code readerIndex} by {@code 3} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 3} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 3} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> int readUnsignedMedium();
<ide>
<ide> * and increases the {@code readerIndex} by {@code 4} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 4} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 4} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> int readInt();
<ide>
<ide> * and increases the {@code readerIndex} by {@code 4} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 4} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 4} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> long readUnsignedInt();
<ide>
<ide> * and increases the {@code readerIndex} by {@code 8} in this buffer.
<ide> *
<ide> * @throws IndexOutOfBoundsException
<del> * if {@code readerIndex + 8} is greater than {@code writerIndex}
<add> * if {@code this.readerIndex + 8} is greater than
<add> * {@code this.writerIndex}
<ide> */
<ide> long readLong();
<ide>
<ide> ChannelBuffer readBytes(ChannelBufferIndexFinder endIndexFinder);
<ide> ChannelBuffer readSlice(int length);
<ide> ChannelBuffer readSlice(ChannelBufferIndexFinder endIndexFinder);
<add>
<add> /**
<add> * Transfers this buffer's data to the specified destination starting at
<add> * the current {@code readerIndex} until the destination becomes
<add> * unwritable, and increases the {@code readerIndex} by the number of the
<add> * transferred bytes. This method is basically same with
<add> * {@link #readBytes(ChannelBuffer, int, int)}, except that this method
<add> * increases the {@code writerIndex} of the destination by the number of
<add> * the transferred bytes while {@link #readBytes(ChannelBuffer, int, int)}
<add> * doesn't.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.readerIndex + dst.writableBytes} is greater than
<add> * {@code this.writerIndex}
<add> */
<ide> void readBytes(ChannelBuffer dst);
<add>
<add> /**
<add> * Transfers this buffer's data to the specified destination starting at
<add> * the current {@code readerIndex} and increases the {@code readerIndex}
<add> * by the number of the transferred bytes (= {@code length}). This method
<add> * is basically same with {@link #readBytes(ChannelBuffer, int, int)},
<add> * except that this method increases the {@code writerIndex} of the
<add> * destination by the number of the transferred bytes (= {@code length})
<add> * while {@link #readBytes(ChannelBuffer, int, int)} doesn't.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.readerIndex + length} is greater than
<add> * {@code this.writerIndex} or
<add> * if {@code dst.writerIndex + length} is greater than
<add> * {@code dst.capacity}
<add> */
<ide> void readBytes(ChannelBuffer dst, int length);
<add>
<add> /**
<add> * Transfers this buffer's data to the specified destination starting at
<add> * the current {@code readerIndex} and increases the {@code readerIndex}
<add> * by the number of the transferred bytes (= {@code length}).
<add> *
<add> * @param dstIndex the first index of the destination
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code dstIndex} is less than {@code 0},
<add> * if {@code this.readerIndex + length} is greater than
<add> * {@code this.writerIndex}, or
<add> * if {@code dstIndex + length} is greater than
<add> * {@code dst.capacity}
<add> */
<ide> void readBytes(ChannelBuffer dst, int dstIndex, int length);
<add>
<add> /**
<add> * Transfers this buffer's data to the specified destination starting at
<add> * the current {@code readerIndex} and increases the {@code readerIndex}
<add> * by the number of the transferred bytes (= {@code dst.length}).
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.readerIndex + dst.length} is greater than
<add> * {@code this.writerIndex} or
<add> * if {@code this.readableBytes} is greater than
<add> * {@code dst.length}
<add> */
<ide> void readBytes(byte[] dst);
<add>
<add> /**
<add> * Transfers this buffer's data to the specified destination starting at
<add> * the current {@code readerIndex} and increases the {@code readerIndex}
<add> * by the number of the transferred bytes (= {@code length}).
<add> *
<add> * @param dstIndex the first index of the destination
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code dstIndex} is less than {@code 0},
<add> * if {@code this.readerIndex + length} is greater than
<add> * {@code this.writerIndex}, or
<add> * if {@code dstIndex + length} is greater than {@code dst.length}
<add> */
<ide> void readBytes(byte[] dst, int dstIndex, int length);
<add>
<add> /**
<add> * Transfers this buffer's data to the specified destination starting at
<add> * the current {@code readerIndex} until the destination's position
<add> * reaches to its limit, and increases the {@code readerIndex} by the
<add> * number of the transferred bytes.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.readerIndex + dst.remaining()} is greater than
<add> * {@code this.capacity} or
<add> * if {@code this.readableBytes} is greater than
<add> * {@code dst.remaining}
<add> *
<add> */
<ide> void readBytes(ByteBuffer dst);
<add>
<add> /**
<add> * Transfers this buffer's data to the specified stream starting at the
<add> * current {@code readerIndex}.
<add> *
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.readerIndex + length} is greater than
<add> * {@code this.capacity}
<add> * @throws IOException
<add> * if the specified stream threw an exception during I/O
<add> */
<ide> void readBytes(OutputStream out, int length) throws IOException;
<add>
<add> /**
<add> * Transfers this buffer's data to the specified stream starting at the
<add> * current {@code readerIndex}.
<add> *
<add> * @param length the maximum number of bytes to transfer
<add> *
<add> * @return the actual number of bytes written out to the specified channel
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.readerIndex + length} is greater than
<add> * {@code this.capacity}
<add> * @throws IOException
<add> * if the specified channel threw an exception during I/O
<add> */
<ide> int readBytes(GatheringByteChannel out, int length) throws IOException;
<ide>
<add> /**
<add> * Increases the current {@code readerIndex} by the specified
<add> * {@code length} in this buffer.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.readerIndex + length} is greater than
<add> * {@code this.writerIndex}
<add> */
<ide> void skipBytes(int length);
<add>
<add> /**
<add> * Increases the current {@code readerIndex} until the specified
<add> * {@code firstIndexFinder} returns {@code true} in this buffer.
<add> *
<add> * @return the number of skipped bytes
<add> *
<add> * @throws NoSuchElementException
<add> * if {@code firstIndexFinder} didn't return {@code true} at all
<add> */
<ide> int skipBytes(ChannelBufferIndexFinder firstIndexFinder);
<ide>
<add> /**
<add> * Sets the specified byte at the current {@code writerIndex}
<add> * and increases the {@code writerIndex} by {@code 1} in this buffer.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + 1} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeByte(byte value);
<add>
<add> /**
<add> * Sets the specified 16-bit short integer at the current
<add> * {@code writerIndex} and increases the {@code writerIndex} by {@code 2}
<add> * in this buffer.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + 2} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeShort(short value);
<add>
<add> /**
<add> * Sets the specified 24-bit medium integer at the current
<add> * {@code writerIndex} and increases the {@code writerIndex} by {@code 3}
<add> * in this buffer.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + 3} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeMedium(int value);
<add>
<add> /**
<add> * Sets the specified 32-bit integer at the current {@code writerIndex}
<add> * and increases the {@code writerIndex} by {@code 4} in this buffer.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + 4} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeInt(int value);
<add>
<add> /**
<add> * Sets the specified 64-bit long integer at the current
<add> * {@code writerIndex} and increases the {@code writerIndex} by {@code 8}
<add> * in this buffer.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + 8} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeLong(long value);
<ide>
<add> /**
<add> * Transfers the specified source buffer's data to this buffer starting at
<add> * the current {@code writerIndex} until the source buffer becomes
<add> * unreadable, and increases the {@code writerIndex} by the number of
<add> * the transferred bytes. This method is basically same with
<add> * {@link #writeBytes(ChannelBuffer, int, int)}, except that this method
<add> * increases the {@code readerIndex} of the source buffer by the number of
<add> * the transferred bytes while {@link #writeBytes(ChannelBuffer, int, int)}
<add> * doesn't.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + src.readableBytes} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeBytes(ChannelBuffer src);
<add>
<add> /**
<add> * Transfers the specified source buffer's data to this buffer starting at
<add> * the current {@code writerIndex} and increases the {@code writerIndex}
<add> * by the number of the transferred bytes (= {@code length}). This method
<add> * is basically same with {@link #writeBytes(ChannelBuffer, int, int)},
<add> * except that this method increases the {@code readerIndex} of the source
<add> * buffer by the number of the transferred bytes (= {@code length}) while
<add> * {@link #writeBytes(ChannelBuffer, int, int)} doesn't.
<add> *
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + length} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeBytes(ChannelBuffer src, int length);
<add>
<add> /**
<add> * Transfers the specified source buffer's data to this buffer starting at
<add> * the current {@code writerIndex} and increases the {@code writerIndex}
<add> * by the number of the transferred bytes (= {@code length}).
<add> *
<add> * @param srcIndex the first index of the source
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code srcIndex} is less than {@code 0},
<add> * if {@code srcIndex + length} is greater than
<add> * {@code src.capacity}, or
<add> * if {@code this.writerIndex + length} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeBytes(ChannelBuffer src, int srcIndex, int length);
<add>
<add> /**
<add> * Transfers the specified source array's data to this buffer starting at
<add> * the current {@code writerIndex} and increases the {@code writerIndex}
<add> * by the number of the transferred bytes (= {@code src.length}).
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + src.length} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeBytes(byte[] src);
<add>
<add> /**
<add> * Transfers the specified source array's data to this buffer starting at
<add> * the current {@code writerIndex} and increases the {@code writerIndex}
<add> * by the number of the transferred bytes (= {@code length}).
<add> *
<add> * @param srcIndex the first index of the source
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if the specified {@code srcIndex} is less than {@code 0},
<add> * if {@code srcIndex + length} is greater than
<add> * {@code src.length}, or
<add> * if {@code this.writerIndex + length} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeBytes(byte[] src, int srcIndex, int length);
<add>
<add> /**
<add> * Transfers the specified source buffer's data to this buffer starting at
<add> * the current {@code writerIndex} until the source buffer's position
<add> * reaches to its limit, and increases the {@code writerIndex} by the
<add> * number of the transferred bytes.
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + src.remaining()} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeBytes(ByteBuffer src);
<add>
<add> /**
<add> * Transfers the content of the specified stream to this buffer
<add> * starting at the current {@code writerIndex} and increases the
<add> * {@code writerIndex} by the number of the transferred bytes.
<add> *
<add> * @param length the number of bytes to transfer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + length} is greater than
<add> * {@code this.capacity}
<add> * @throws IOException
<add> * if the specified stream threw an exception during I/O
<add> */
<ide> void writeBytes(InputStream in, int length) throws IOException;
<add>
<add> /**
<add> * Transfers the content of the specified channel to this buffer
<add> * starting at the current {@code writerIndex} and increases the
<add> * {@code writerIndex} by the number of the transferred bytes.
<add> *
<add> * @param length the maximum number of bytes to transfer
<add> *
<add> * @return the actual number of bytes read in from the specified channel
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + length} is greater than
<add> * {@code this.capacity}
<add> * @throws IOException
<add> * if the specified channel threw an exception during I/O
<add> */
<ide> int writeBytes(ScatteringByteChannel in, int length) throws IOException;
<ide>
<add> /**
<add> * Fills this buffer with <tt>NUL (0x00)</tt> starting at the current
<add> * {@code writerIndex} and increases the {@code writerIndex} by the
<add> * specified {@code length}.
<add> *
<add> * @param length the number of <tt>NUL</tt>s to write to the buffer
<add> *
<add> * @throws IndexOutOfBoundsException
<add> * if {@code this.writerIndex + length} is greater than
<add> * {@code this.capacity}
<add> */
<ide> void writeZero(int length);
<ide>
<ide> int indexOf(int fromIndex, int toIndex, byte value);
<ide> int indexOf(int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder);
<ide>
<add> /**
<add> * Returns a copy of this buffer's readable bytes. Modifying the content
<add> * of the returned buffer or this buffer doesn't affect each other at all.
<add> * This method is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}.
<add> */
<ide> ChannelBuffer copy();
<add>
<add> /**
<add> * Returns a copy of this buffer's sub-region. Modifying the content of
<add> * the returned buffer or this buffer doesn't affect each other at all.
<add> */
<ide> ChannelBuffer copy(int index, int length);
<add>
<add> /**
<add> * Returns a slice of this buffer's readable bytes. Modifying the content
<add> * of the returned buffer or this buffer affects each other's content
<add> * while they maintain separate indexes and marks. This method is
<add> * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}.
<add> */
<ide> ChannelBuffer slice();
<add>
<add> /**
<add> * Returns a slice of this buffer's sub-region. Modifying the content of
<add> * the returned buffer or this buffer affects each other's content while
<add> * they maintain separate indexes and marks. This method is identical to
<add> * {@code buf.slice(buf.readerIndex(), buf.readableBytes())}.
<add> */
<ide> ChannelBuffer slice(int index, int length);
<add>
<add> /**
<add> * Returns a buffer which shares the whole region of this buffer.
<add> * Modifying the content of the returned buffer or this buffer affects
<add> * each other's content while they maintain separate indexes and marks.
<add> * This method is identical to {@code buf.slice(0, buf.capacity())}.
<add> */
<ide> ChannelBuffer duplicate();
<ide>
<add> /**
<add> * Converts this buffer's readable bytes into a NIO buffer. The returned
<add> * buffer might or might not share the content with this buffer, while
<add> * they have separate indexes and marks. This method is identical to
<add> * {@code buf.toByteBuffer(buf.readerIndex(), buf.readableBytes())}.
<add> */
<ide> ByteBuffer toByteBuffer();
<add>
<add> /**
<add> * Converts this buffer's sub-region into a NIO buffer. The returned
<add> * buffer might or might not share the content with this buffer, while
<add> * they have separate indexes and marks.
<add> */
<ide> ByteBuffer toByteBuffer(int index, int length);
<add>
<add> /**
<add> * Converts this buffer's readable bytes into an array of NIO buffers.
<add> * The returned buffers might or might not share the content with this
<add> * buffer, while they have separate indexes and marks. This method is
<add> * identical to {@code buf.toByteBuffers(buf.readerIndex(), buf.readableBytes())}.
<add> */
<ide> ByteBuffer[] toByteBuffers();
<add>
<add> /**
<add> * Converts this buffer's sub-region into an array of NIO buffers.
<add> * The returned buffers might or might not share the content with this
<add> * buffer, while they have separate indexes and marks.
<add> */
<ide> ByteBuffer[] toByteBuffers(int index, int length);
<ide>
<add> /**
<add> * Decodes this buffer's readable bytes into a string with the specified
<add> * character set name. This method is identical to
<add> * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}.
<add> *
<add> * @throws UnsupportedCharsetException
<add> * if the specified character set name is not supported by the
<add> * current VM
<add> */
<ide> String toString(String charsetName);
<add>
<add> /**
<add> * Decodes this buffer's readable bytes into a string until the specified
<add> * {@code terminatorFinder} returns {@code true} with the specified
<add> * character set name. This method is identical to
<add> * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName, terminatorFinder)}.
<add> *
<add> * @throws UnsupportedCharsetException
<add> * if the specified character set name is not supported by the
<add> * current VM
<add> */
<ide> String toString(
<ide> String charsetName, ChannelBufferIndexFinder terminatorFinder);
<add>
<add> /**
<add> * Decodes this buffer's sub-region into a string with the specified
<add> * character set name.
<add> *
<add> * @throws UnsupportedCharsetException
<add> * if the specified character set name is not supported by the
<add> * current VM
<add> */
<ide> String toString(int index, int length, String charsetName);
<add>
<add> /**
<add> * Decodes this buffer's readable bytes into a string until the specified
<add> * {@code terminatorFinder} returns {@code true} with the specified
<add> * character set name.
<add> *
<add> * @throws UnsupportedCharsetException
<add> * if the specified character set name is not supported by the
<add> * current VM
<add> */
<ide> String toString(
<ide> int index, int length, String charsetName,
<ide> ChannelBufferIndexFinder terminatorFinder); |
|
Java | apache-2.0 | 67ccc1bc7ea0e714a4b8f66f8b05559ecdd3c6e8 | 0 | project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform,project-asap/IReS-Platform | package gr.ntua.cslab.asap.operators;
import gr.ntua.cslab.asap.rest.beans.OperatorDescription;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.*;
import org.apache.log4j.Logger;
public class SpecTree {
public TreeMap<String,SpecTreeNode> tree;
private static Logger logger = Logger.getLogger( SpecTree.class.getName());
public SpecTree() {
tree= new TreeMap<String,SpecTreeNode>();
}
public void add(String key, String value) {
String curname = key.substring(0, key.indexOf("."));
SpecTreeNode s = tree.get(curname);
if(s!=null){
String nextKey = key.substring(key.indexOf(".")+1);
s.add(nextKey, value);
}
else{
SpecTreeNode temp = new SpecTreeNode(key, value);
tree.put(temp.getName(),temp);
}
}
public void addRegex(NodeName key, String value) {
if(key.isRegex){
SpecTreeNode temp = new SpecTreeNode(key, value);
tree.put(temp.getName(),temp);
}
else{
String curname = key.name.substring(0, key.name.indexOf("."));
SpecTreeNode s = tree.get(curname);
if(s!=null){
String nextKey = key.name.substring(key.name.indexOf(".")+1);
NodeName nextNodeName = new NodeName(nextKey, key.nextName, false);
s.addRegex(nextNodeName, value);
}
else{
SpecTreeNode temp = new SpecTreeNode(key, value);
tree.put(temp.getName(),temp);
}
}
}
@Override
public String toString() {
String ret = "{";
int i=0;
for(SpecTreeNode n : tree.values()){
if(i>=1){
ret+=", ";
}
ret += n.toString();
i++;
}
ret+="}";
return ret;
}
public void writeToPropertiesFile(String curentPath, Properties props) {
for(SpecTreeNode n : tree.values()){
n.writeToPropertiesFile(curentPath, props);
}
}
public String toKeyValues(String curentPath, String ret, String separator) {
for(SpecTreeNode n : tree.values()){
ret =n.toKeyValues(curentPath, ret, separator);
}
return ret;
}
public void toOperatorDescription(OperatorDescription ret) {
for(SpecTreeNode n : tree.values()){
n.toOperatorDescription(ret);
}
}
public String getOpName(){
/* vpapa: return the name of the corresponding operator which expected to have this
form OpSpecification{Algorithm{(name, operator_name)}
*/
String value = "No_Operator_Name_Found";
for(SpecTreeNode n : tree.values()){
if( n.toString().startsWith( "OpSpecification")){
//ommit the 'OpSpecification{Algorithm{(name,' part
value = n.toString().split( ",")[ 1];
//ommit the ')}'
value = value.split( ",")[ 0];
//now only the 'operator_name' part should be with some leading or trailing
//whitespaces
if( value.equals( "")){
//no operator name has been specified
value = "No_Operator_Name_Found";
}
return value.trim();
}
}
return value;
}
public boolean checkMatch(SpecTree optree2) {
//materialized operator optree2
logger.info( "\n\nChecking " + tree.getOpName() + " and " + optree2.getOpName() + "for matching\n");
logger.info( tree.getOpName() + " " + tree);
logger.info( optree2.getOpName() + " " + optree2);
Pattern p = null;
for(SpecTreeNode n : tree.values()){
logger.info( "SPECTREE: " + n.getName() + " " + "VALUE:\n" + n);
if(n.getName().equals("*")){
return optree2.tree.size()>0;
}
else{
//verify that properties of the same group get checked e.g. Constraints with
//Constraints
p = Pattern.compile( n.getName());
boolean found =false;
for( SpecTreeNode n1 : optree2.tree.values()){
logger.info( "OPTREE: " + n1.getName() + " " + "VALUE:\n" + n1);
Matcher m = p.matcher( n1.getName());
logger.info( "checking: "+n.getName()+" "+n1.getName());
if( m.matches()){
found =true;
logger.info( "found match: "+n.getName()+" "+n1.getName());
//check that the properties themselves match
if(!n.checkMatch(n1)){
return false;
}
}
}
if(!found){
return false;
}
/*SpecTreeNode n1 = optree2.tree.get(n.getName());
if(n1!=null){
if(!n.checkMatch(n1))
return false;
}
else{
return false;
}*/
}
}
return true;
}
public SpecTree copyInputToOpSubTree(String prefix, String inout) {
SpecTree ret = new SpecTree();
//System.out.println("adding key: "+prefix);
if (prefix.contains(".")){
String curname = prefix.substring(0, prefix.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = prefix.substring(prefix.indexOf(".")+1);
SpecTreeNode temp = s.copyInputToOpSubTree(nextKey,inout);
if(temp==null)
return null;
ret.tree.put(temp.getName(), temp);
}
else{
return null;
}
}
else{//leaf
//add Input{i} node
SpecTreeNode s = tree.get(prefix);
if(s!=null){
SpecTreeNode temp = s.copyInputToOpSubTree(null,inout);
SpecTreeNode ret1 = new SpecTreeNode(inout);
for(SpecTreeNode n : temp.children.values()){
ret1.children.put(n.getName(), n);
}
temp.children = new TreeMap<String, SpecTreeNode>();
temp.children.put(ret1.getName(), ret1);
ret.tree.put(temp.getName(), temp);
}
else{
//not found
return null;
}
}
return ret;
}
public SpecTree clone() throws CloneNotSupportedException {
SpecTree ret = new SpecTree();
ret.tree = new TreeMap<String, SpecTreeNode>();
for(Entry<String, SpecTreeNode> e: tree.entrySet()){
ret.tree.put(new String(e.getKey()), e.getValue().clone());
}
return ret;
}
public SpecTree copyInputSubTree(String prefix) {
SpecTree ret = new SpecTree();
//System.out.println("adding key: "+prefix);
if (prefix.contains(".")){
String curname = prefix.substring(0, prefix.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = prefix.substring(prefix.indexOf(".")+1);
SpecTreeNode temp = s.copyInputSubTree(nextKey);
if(temp==null)
return null;
ret.tree.put(temp.getName(), temp);
}
else{
return null;
}
}
else{//leaf
SpecTreeNode s = tree.get(prefix);
if(s!=null){
SpecTreeNode temp = s.copyInputSubTree(null);
ret.tree.put(temp.getName(), temp);
}
else{
return null;
}
}
return ret;
}
public SpecTreeNode getNode(String key) {
if (key.contains(".")){
String curname = key.substring(0, key.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = key.substring(key.indexOf(".")+1);
return s.getNode(nextKey);
}
else{
return null;
}
}
return tree.get(key);
}
public String getParameter(String key) {
if (key.contains(".")){
String curname = key.substring(0, key.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = key.substring(key.indexOf(".")+1);
return s.getParameter(nextKey);
}
else{
return null;
}
}
return null;
}
public void addAll(SpecTree f) {
for(Entry<String, SpecTreeNode> k : f.tree.entrySet()){
SpecTreeNode v = this.tree.get(k.getKey());
if(v!=null){
v.addAll(k.getValue());
}
else{
this.tree.put(k.getKey(), k.getValue());
}
}
}
}
| asap-platform/asap-beans/src/main/java/gr/ntua/cslab/asap/operators/SpecTree.java | package gr.ntua.cslab.asap.operators;
import gr.ntua.cslab.asap.rest.beans.OperatorDescription;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.*;
import org.apache.log4j.Logger;
public class SpecTree {
public TreeMap<String,SpecTreeNode> tree;
private static Logger logger = Logger.getLogger( SpecTree.class.getName());
public SpecTree() {
tree= new TreeMap<String,SpecTreeNode>();
}
public void add(String key, String value) {
String curname = key.substring(0, key.indexOf("."));
SpecTreeNode s = tree.get(curname);
if(s!=null){
String nextKey = key.substring(key.indexOf(".")+1);
s.add(nextKey, value);
}
else{
SpecTreeNode temp = new SpecTreeNode(key, value);
tree.put(temp.getName(),temp);
}
}
public void addRegex(NodeName key, String value) {
if(key.isRegex){
SpecTreeNode temp = new SpecTreeNode(key, value);
tree.put(temp.getName(),temp);
}
else{
String curname = key.name.substring(0, key.name.indexOf("."));
SpecTreeNode s = tree.get(curname);
if(s!=null){
String nextKey = key.name.substring(key.name.indexOf(".")+1);
NodeName nextNodeName = new NodeName(nextKey, key.nextName, false);
s.addRegex(nextNodeName, value);
}
else{
SpecTreeNode temp = new SpecTreeNode(key, value);
tree.put(temp.getName(),temp);
}
}
}
@Override
public String toString() {
String ret = "{";
int i=0;
for(SpecTreeNode n : tree.values()){
if(i>=1){
ret+=", ";
}
ret += n.toString();
i++;
}
ret+="}";
return ret;
}
public void writeToPropertiesFile(String curentPath, Properties props) {
for(SpecTreeNode n : tree.values()){
n.writeToPropertiesFile(curentPath, props);
}
}
public String toKeyValues(String curentPath, String ret, String separator) {
for(SpecTreeNode n : tree.values()){
ret =n.toKeyValues(curentPath, ret, separator);
}
return ret;
}
public void toOperatorDescription(OperatorDescription ret) {
for(SpecTreeNode n : tree.values()){
n.toOperatorDescription(ret);
}
}
public boolean checkMatch(SpecTree optree2) {
//materialized operator optree2
logger.info( "\n\nChecking " + tree.getOpName() + " and " + optree2.getOpName() + "for matching\n");
logger.info( tree.getOpName() + " " + tree);
logger.info( optree2.getOpName() + " " + optree2);
Pattern p = null;
for(SpecTreeNode n : tree.values()){
logger.info( "SPECTREE: " + n.getName() + " " + "VALUE:\n" + n);
if(n.getName().equals("*")){
return optree2.tree.size()>0;
}
else{
//verify that properties of the same group get checked e.g. Constraints with
//Constraints
p = Pattern.compile( n.getName());
boolean found =false;
for( SpecTreeNode n1 : optree2.tree.values()){
logger.info( "OPTREE: " + n1.getName() + " " + "VALUE:\n" + n1);
Matcher m = p.matcher( n1.getName());
logger.info( "checking: "+n.getName()+" "+n1.getName());
if( m.matches()){
found =true;
logger.info( "found match: "+n.getName()+" "+n1.getName());
//check that the properties themselves match
if(!n.checkMatch(n1)){
return false;
}
}
}
if(!found){
return false;
}
/*SpecTreeNode n1 = optree2.tree.get(n.getName());
if(n1!=null){
if(!n.checkMatch(n1))
return false;
}
else{
return false;
}*/
}
}
return true;
}
public String getOpName(){
/* vpapa: return the name of the corresponding operator which expected to have this
form OpSpecification{Algorithm{(name, operator_name)}
*/
String value = "No_Operator_Name_Found";
for(SpecTreeNode n : tree.values()){
if( n.toString().startsWith( "OpSpecification")){
//ommit the 'OpSpecification{Algorithm{(name,' part
value = n.toString().split( ",")[ 1];
//ommit the ')}'
value = value.split( ",")[ 0];
//now only the 'operator_name' part should be with some leading or trailing
//whitespaces
if( value.equals( "")){
//no operator name has been specified
value = "No_Operator_Name_Found";
}
return value.trim();
}
}
return value;
}
public SpecTree copyInputToOpSubTree(String prefix, String inout) {
SpecTree ret = new SpecTree();
//System.out.println("adding key: "+prefix);
if (prefix.contains(".")){
String curname = prefix.substring(0, prefix.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = prefix.substring(prefix.indexOf(".")+1);
SpecTreeNode temp = s.copyInputToOpSubTree(nextKey,inout);
if(temp==null)
return null;
ret.tree.put(temp.getName(), temp);
}
else{
return null;
}
}
else{//leaf
//add Input{i} node
SpecTreeNode s = tree.get(prefix);
if(s!=null){
SpecTreeNode temp = s.copyInputToOpSubTree(null,inout);
SpecTreeNode ret1 = new SpecTreeNode(inout);
for(SpecTreeNode n : temp.children.values()){
ret1.children.put(n.getName(), n);
}
temp.children = new TreeMap<String, SpecTreeNode>();
temp.children.put(ret1.getName(), ret1);
ret.tree.put(temp.getName(), temp);
}
else{
//not found
return null;
}
}
return ret;
}
public SpecTree clone() throws CloneNotSupportedException {
SpecTree ret = new SpecTree();
ret.tree = new TreeMap<String, SpecTreeNode>();
for(Entry<String, SpecTreeNode> e: tree.entrySet()){
ret.tree.put(new String(e.getKey()), e.getValue().clone());
}
return ret;
}
public SpecTree copyInputSubTree(String prefix) {
SpecTree ret = new SpecTree();
//System.out.println("adding key: "+prefix);
if (prefix.contains(".")){
String curname = prefix.substring(0, prefix.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = prefix.substring(prefix.indexOf(".")+1);
SpecTreeNode temp = s.copyInputSubTree(nextKey);
if(temp==null)
return null;
ret.tree.put(temp.getName(), temp);
}
else{
return null;
}
}
else{//leaf
SpecTreeNode s = tree.get(prefix);
if(s!=null){
SpecTreeNode temp = s.copyInputSubTree(null);
ret.tree.put(temp.getName(), temp);
}
else{
return null;
}
}
return ret;
}
public SpecTreeNode getNode(String key) {
if (key.contains(".")){
String curname = key.substring(0, key.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = key.substring(key.indexOf(".")+1);
return s.getNode(nextKey);
}
else{
return null;
}
}
return tree.get(key);
}
public String getParameter(String key) {
if (key.contains(".")){
String curname = key.substring(0, key.indexOf("."));
//System.out.println("Checking name: "+curname);
SpecTreeNode s = tree.get(curname);
if(s!=null){
//System.out.println("Found!!");
String nextKey = key.substring(key.indexOf(".")+1);
return s.getParameter(nextKey);
}
else{
return null;
}
}
return null;
}
public void addAll(SpecTree f) {
for(Entry<String, SpecTreeNode> k : f.tree.entrySet()){
SpecTreeNode v = this.tree.get(k.getKey());
if(v!=null){
v.addAll(k.getValue());
}
else{
this.tree.put(k.getKey(), k.getValue());
}
}
}
}
| Update big workflows for wind
| asap-platform/asap-beans/src/main/java/gr/ntua/cslab/asap/operators/SpecTree.java | Update big workflows for wind | <ide><path>sap-platform/asap-beans/src/main/java/gr/ntua/cslab/asap/operators/SpecTree.java
<ide> for(SpecTreeNode n : tree.values()){
<ide> n.toOperatorDescription(ret);
<ide> }
<add> }
<add>
<add> public String getOpName(){
<add> /* vpapa: return the name of the corresponding operator which expected to have this
<add> form OpSpecification{Algorithm{(name, operator_name)}
<add> */
<add> String value = "No_Operator_Name_Found";
<add> for(SpecTreeNode n : tree.values()){
<add> if( n.toString().startsWith( "OpSpecification")){
<add> //ommit the 'OpSpecification{Algorithm{(name,' part
<add> value = n.toString().split( ",")[ 1];
<add> //ommit the ')}'
<add> value = value.split( ",")[ 0];
<add> //now only the 'operator_name' part should be with some leading or trailing
<add> //whitespaces
<add> if( value.equals( "")){
<add> //no operator name has been specified
<add> value = "No_Operator_Name_Found";
<add> }
<add> return value.trim();
<add> }
<add> }
<add> return value;
<ide> }
<ide>
<ide> public boolean checkMatch(SpecTree optree2) {
<ide> return true;
<ide> }
<ide>
<del> public String getOpName(){
<del> /* vpapa: return the name of the corresponding operator which expected to have this
<del> form OpSpecification{Algorithm{(name, operator_name)}
<del> */
<del> String value = "No_Operator_Name_Found";
<del> for(SpecTreeNode n : tree.values()){
<del> if( n.toString().startsWith( "OpSpecification")){
<del> //ommit the 'OpSpecification{Algorithm{(name,' part
<del> value = n.toString().split( ",")[ 1];
<del> //ommit the ')}'
<del> value = value.split( ",")[ 0];
<del> //now only the 'operator_name' part should be with some leading or trailing
<del> //whitespaces
<del> if( value.equals( "")){
<del> //no operator name has been specified
<del> value = "No_Operator_Name_Found";
<del> }
<del> return value.trim();
<del> }
<del> }
<del> return value;
<del> }
<del>
<ide> public SpecTree copyInputToOpSubTree(String prefix, String inout) {
<ide> SpecTree ret = new SpecTree();
<ide> |
|
Java | mit | 462e1cba355b51dd91c57b7aa16cb1c5d6072c17 | 0 | loxal/FreeEthereum,loxal/FreeEthereum,loxal/FreeEthereum,loxal/ethereumj | package org.ethereum.core;
import org.apache.commons.collections4.map.LRUMap;
import org.ethereum.config.SystemProperties;
import org.ethereum.db.BlockStore;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.db.TransactionStore;
import org.ethereum.listener.EthereumListener;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import static org.ethereum.config.SystemProperties.CONFIG;
import static org.ethereum.util.BIUtil.toBI;
/**
* Keeps logic providing pending state management
*
* @author Mikhail Kalinin
* @since 28.09.2015
*/
@Component
public class PendingStateImpl implements PendingState {
public static class TransactionSortedSet extends TreeSet<Transaction> {
public TransactionSortedSet() {
super(new Comparator<Transaction>() {
@Override
public int compare(Transaction tx1, Transaction tx2) {
long nonceDiff = ByteUtil.byteArrayToLong(tx1.getNonce()) -
ByteUtil.byteArrayToLong(tx2.getNonce());
if (nonceDiff != 0) {
return nonceDiff > 0 ? 1 : -1;
}
return FastByteComparisons.compareTo(tx1.getHash(), 0, 32, tx2.getHash(), 0, 32);
}
});
}
}
private static final Logger logger = LoggerFactory.getLogger("state");
@Autowired
private EthereumListener listener;
@Autowired @Qualifier("repository")
private Repository repository;
@Autowired
private Blockchain blockchain;
@Autowired
private BlockStore blockStore;
@Autowired
private TransactionStore transactionStore;
@Autowired
private ProgramInvokeFactory programInvokeFactory;
@Autowired
private SystemProperties config = SystemProperties.CONFIG;
private final List<PendingTransaction> pendingTransactions = new ArrayList<>();
// to filter out the transactions we have already processed
// transactions could be sent by peers even if they were already included into blocks
private final Map<ByteArrayWrapper, Object> redceivedTxs = new LRUMap<>(500000);
private final Object dummyObject = new Object();
private Repository pendingState;
private Block best = null;
public PendingStateImpl() {
}
public PendingStateImpl(EthereumListener listener, BlockchainImpl blockchain) {
this.listener = listener;
this.blockchain = blockchain;
this.repository = blockchain.getRepository();
this.blockStore = blockchain.getBlockStore();
this.programInvokeFactory = blockchain.getProgramInvokeFactory();
this.transactionStore = blockchain.getTransactionStore();
}
@PostConstruct
public void init() {
this.pendingState = repository.startTracking();
}
@Override
public Repository getRepository() {
return pendingState;
}
@Override
public synchronized List<Transaction> getPendingTransactions() {
List<Transaction> txs = new ArrayList<>();
for (PendingTransaction tx : pendingTransactions) {
txs.add(tx.getTransaction());
}
return txs;
}
public Block getBestBlock() {
if (best == null) {
best = blockchain.getBestBlock();
}
return best;
}
private boolean addNewTxIfNotExist(Transaction tx) {
synchronized (redceivedTxs) {
return redceivedTxs.put(new ByteArrayWrapper(tx.getHash()), dummyObject) == null;
}
}
@Override
public void addPendingTransaction(Transaction tx) {
addPendingTransactions(Collections.singletonList(tx));
}
@Override
public void addPendingTransactions(List<Transaction> transactions) {
int unknownTx = 0;
List<Transaction> newPending = new ArrayList<>();
for (Transaction tx : transactions) {
if (addNewTxIfNotExist(tx)) {
unknownTx++;
if (addPendingTransactionImpl(tx)) {
newPending.add(tx);
}
}
}
logger.info("Wire transaction list added: total: {}, new: {}, valid (added to pending): {} (current #of known txs: {})",
transactions.size(), unknownTx, newPending, redceivedTxs.size());
if (!newPending.isEmpty()) {
listener.onPendingTransactionsReceived(newPending);
listener.onPendingStateChanged(PendingStateImpl.this);
}
}
private synchronized boolean addPendingTransactionImpl(final Transaction tx) {
String err = validate(tx);
TransactionReceipt txReceipt;
if (err != null) {
txReceipt = createDroppedReceipt(tx, err);
} else {
txReceipt = executeTx(tx);
}
if (!txReceipt.isValid()) {
listener.onPendingTransactionUpdate(txReceipt, EthereumListener.PendingTransactionState.DROPPED, getBestBlock());
} else {
pendingTransactions.add(new PendingTransaction(tx, getBestBlock().getNumber()));
listener.onPendingTransactionUpdate(txReceipt, EthereumListener.PendingTransactionState.PENDING, getBestBlock());
}
return txReceipt.isValid();
}
private TransactionReceipt createDroppedReceipt(Transaction tx, String error) {
TransactionReceipt txReceipt = new TransactionReceipt();
txReceipt.setTransaction(tx);
txReceipt.setError(error);
return txReceipt;
}
// validations which are not performed within executeTx
private String validate(Transaction tx) {
if (config.getMineMinGasPrice().compareTo(ByteUtil.bytesToBigInteger(tx.gasPrice)) > 0) {
return "Too low gas price for transaction: " + ByteUtil.bytesToBigInteger(tx.gasPrice);
}
return null;
}
private Block findCommonAncestor(Block b1, Block b2) {
while(!b1.isEqual(b2)) {
if (b1.getNumber() >= b2.getNumber()) {
b1 = blockchain.getBlockByHash(b1.getParentHash());
}
if (b1.getNumber() < b2.getNumber()) {
b2 = blockchain.getBlockByHash(b2.getParentHash());
}
if (b1 == null || b2 == null) {
// shouldn't happen
throw new RuntimeException("Pending state can't find common ancestor: one of blocks has a gap");
}
}
return b1;
}
@Override
public synchronized void processBest(Block newBlock, List<TransactionReceipt> receipts) {
if (getBestBlock() != null && !getBestBlock().isParentOf(newBlock)) {
// need to switch the state to another fork
Block commonAncestor = findCommonAncestor(getBestBlock(), newBlock);
if (logger.isDebugEnabled()) logger.debug("New best block from another fork: "
+ newBlock.getShortDescr() + ", old best: " + getBestBlock().getShortDescr()
+ ", ancestor: " + commonAncestor.getShortDescr());
// first return back the transactions from forked blocks
Block rollback = getBestBlock();
while(!rollback.isEqual(commonAncestor)) {
List<PendingTransaction> blockTxs = new ArrayList<>();
for (Transaction tx : rollback.getTransactionsList()) {
logger.debug("Returning transaction back to pending: " + tx);
blockTxs.add(new PendingTransaction(tx, commonAncestor.getNumber()));
}
pendingTransactions.addAll(0, blockTxs);
rollback = blockchain.getBlockByHash(rollback.getParentHash());
}
// rollback the state snapshot to the ancestor
pendingState = repository.getSnapshotTo(commonAncestor.getStateRoot()).startTracking();
// next process blocks from new fork
Block main = newBlock;
List<Block> mainFork = new ArrayList<>();
while(!main.isEqual(commonAncestor)) {
mainFork.add(main);
main = blockchain.getBlockByHash(main.getParentHash());
}
// processing blocks from ancestor to new block
for (int i = mainFork.size() - 1; i >= 0; i--) {
processBestInternal(mainFork.get(i), null);
}
} else {
logger.debug("PendingStateImpl.processBest: " + newBlock.getShortDescr());
processBestInternal(newBlock, receipts);
}
best = newBlock;
updateState(newBlock);
listener.onPendingStateChanged(PendingStateImpl.this);
}
private void processBestInternal(Block block, List<TransactionReceipt> receipts) {
clearWire(block, receipts);
clearOutdated(block.getNumber());
}
private void clearOutdated(final long blockNumber) {
List<PendingTransaction> outdated = new ArrayList<>();
synchronized (pendingTransactions) {
for (PendingTransaction tx : pendingTransactions)
if (blockNumber - tx.getBlockNumber() > config.txOutdatedThreshold()) {
outdated.add(tx);
listener.onPendingTransactionUpdate(
createDroppedReceipt(tx.getTransaction(), "Tx was not included into last " + CONFIG.txOutdatedThreshold() + " blocks"),
EthereumListener.PendingTransactionState.DROPPED, getBestBlock());
}
}
if (outdated.isEmpty()) return;
if (logger.isInfoEnabled())
for (PendingTransaction tx : outdated)
logger.info(
"Clear outdated wire transaction, block.number: [{}] hash: [{}]",
tx.getBlockNumber(),
Hex.toHexString(tx.getHash())
);
pendingTransactions.removeAll(outdated);
}
private void clearWire(Block block, List<TransactionReceipt> receipts) {
for (int i = 0; i < block.getTransactionsList().size(); i++) {
Transaction tx = block.getTransactionsList().get(i);
PendingTransaction pend = new PendingTransaction(tx);
if (pendingTransactions.remove(pend)) {
try {
logger.info("Clear pending transaction, hash: [{}]", Hex.toHexString(tx.getHash()));
TransactionReceipt receipt;
if (receipts != null) {
receipt = receipts.get(i);
} else {
TransactionInfo info = transactionStore.get(tx.getHash(), block.getHash());
receipt = info.getReceipt();
}
listener.onPendingTransactionUpdate(receipt, EthereumListener.PendingTransactionState.INCLUDED, block);
} catch (Exception e) {
logger.error("Exception creating onPendingTransactionUpdate (block: " + block.getShortDescr() + ", tx: " + i, e);
}
}
}
}
private void updateState(Block block) {
pendingState = repository.startTracking();
for (PendingTransaction tx : pendingTransactions) {
TransactionReceipt receipt = executeTx(tx.getTransaction());
listener.onPendingTransactionUpdate(receipt, EthereumListener.PendingTransactionState.PENDING, block);
}
}
private TransactionReceipt executeTx(Transaction tx) {
logger.info("Apply pending state tx: {}", Hex.toHexString(tx.getHash()));
Block best = getBestBlock();
TransactionExecutor executor = new TransactionExecutor(
tx, best.getCoinbase(), pendingState,
blockStore, programInvokeFactory, best
);
executor.init();
executor.execute();
executor.go();
executor.finalization();
return executor.getReceipt();
}
public void setBlockchain(Blockchain blockchain) {
this.blockchain = blockchain;
}
}
| ethereumj-core/src/main/java/org/ethereum/core/PendingStateImpl.java | package org.ethereum.core;
import org.apache.commons.collections4.map.LRUMap;
import org.ethereum.config.SystemProperties;
import org.ethereum.db.BlockStore;
import org.ethereum.db.ByteArrayWrapper;
import org.ethereum.db.TransactionStore;
import org.ethereum.listener.EthereumListener;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.ethereum.vm.program.invoke.ProgramInvokeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import static org.ethereum.config.SystemProperties.CONFIG;
import static org.ethereum.util.BIUtil.toBI;
/**
* Keeps logic providing pending state management
*
* @author Mikhail Kalinin
* @since 28.09.2015
*/
@Component
public class PendingStateImpl implements PendingState {
public static class TransactionSortedSet extends TreeSet<Transaction> {
public TransactionSortedSet() {
super(new Comparator<Transaction>() {
@Override
public int compare(Transaction tx1, Transaction tx2) {
long nonceDiff = ByteUtil.byteArrayToLong(tx1.getNonce()) -
ByteUtil.byteArrayToLong(tx2.getNonce());
if (nonceDiff != 0) {
return nonceDiff > 0 ? 1 : -1;
}
return FastByteComparisons.compareTo(tx1.getHash(), 0, 32, tx2.getHash(), 0, 32);
}
});
}
}
private static final Logger logger = LoggerFactory.getLogger("state");
@Autowired
private EthereumListener listener;
@Autowired @Qualifier("repository")
private Repository repository;
@Autowired
private Blockchain blockchain;
@Autowired
private BlockStore blockStore;
@Autowired
private TransactionStore transactionStore;
@Autowired
private ProgramInvokeFactory programInvokeFactory;
@Autowired
private SystemProperties config = SystemProperties.CONFIG;
private final List<PendingTransaction> pendingTransactions = new ArrayList<>();
// to filter out the transactions we have already processed
// transactions could be sent by peers even if they were already included into blocks
private final Map<ByteArrayWrapper, Object> redceivedTxs = new LRUMap<>(500000);
private final Object dummyObject = new Object();
@Resource
@Qualifier("pendingStateTransactions")
private Repository pendingState;
private Block best = null;
public PendingStateImpl() {
}
public PendingStateImpl(EthereumListener listener, BlockchainImpl blockchain) {
this.listener = listener;
this.blockchain = blockchain;
this.repository = blockchain.getRepository();
this.blockStore = blockchain.getBlockStore();
this.programInvokeFactory = blockchain.getProgramInvokeFactory();
this.transactionStore = blockchain.getTransactionStore();
}
@PostConstruct
public void init() {
this.pendingState = repository.startTracking();
}
@Override
public Repository getRepository() {
return pendingState;
}
@Override
public synchronized List<Transaction> getPendingTransactions() {
List<Transaction> txs = new ArrayList<>();
for (PendingTransaction tx : pendingTransactions) {
txs.add(tx.getTransaction());
}
return txs;
}
public Block getBestBlock() {
if (best == null) {
best = blockchain.getBestBlock();
}
return best;
}
private boolean addNewTxIfNotExist(Transaction tx) {
synchronized (redceivedTxs) {
return redceivedTxs.put(new ByteArrayWrapper(tx.getHash()), dummyObject) == null;
}
}
@Override
public void addPendingTransaction(Transaction tx) {
addPendingTransactions(Collections.singletonList(tx));
}
@Override
public void addPendingTransactions(List<Transaction> transactions) {
int unknownTx = 0;
List<Transaction> newPending = new ArrayList<>();
for (Transaction tx : transactions) {
if (addNewTxIfNotExist(tx)) {
unknownTx++;
if (addPendingTransactionImpl(tx)) {
newPending.add(tx);
}
}
}
logger.info("Wire transaction list added: total: {}, new: {}, valid (added to pending): {} (current #of known txs: {})",
transactions.size(), unknownTx, newPending, redceivedTxs.size());
if (!newPending.isEmpty()) {
listener.onPendingTransactionsReceived(newPending);
listener.onPendingStateChanged(PendingStateImpl.this);
}
}
private synchronized boolean addPendingTransactionImpl(final Transaction tx) {
String err = validate(tx);
TransactionReceipt txReceipt;
if (err != null) {
txReceipt = createDroppedReceipt(tx, err);
} else {
txReceipt = executeTx(tx);
}
if (!txReceipt.isValid()) {
listener.onPendingTransactionUpdate(txReceipt, EthereumListener.PendingTransactionState.DROPPED, getBestBlock());
} else {
pendingTransactions.add(new PendingTransaction(tx, getBestBlock().getNumber()));
listener.onPendingTransactionUpdate(txReceipt, EthereumListener.PendingTransactionState.PENDING, getBestBlock());
}
return txReceipt.isValid();
}
private TransactionReceipt createDroppedReceipt(Transaction tx, String error) {
TransactionReceipt txReceipt = new TransactionReceipt();
txReceipt.setTransaction(tx);
txReceipt.setError(error);
return txReceipt;
}
// validations which are not performed within executeTx
private String validate(Transaction tx) {
if (config.getMineMinGasPrice().compareTo(ByteUtil.bytesToBigInteger(tx.gasPrice)) >= 0) {
return "Too low gas price for transaction: " + ByteUtil.bytesToBigInteger(tx.gasPrice);
}
return null;
}
private Block findCommonAncestor(Block b1, Block b2) {
while(!b1.isEqual(b2)) {
if (b1.getNumber() >= b2.getNumber()) {
b1 = blockchain.getBlockByHash(b1.getParentHash());
}
if (b1.getNumber() < b2.getNumber()) {
b2 = blockchain.getBlockByHash(b2.getParentHash());
}
if (b1 == null || b2 == null) {
// shouldn't happen
throw new RuntimeException("Pending state can't find common ancestor: one of blocks has a gap");
}
}
return b1;
}
@Override
public synchronized void processBest(Block newBlock, List<TransactionReceipt> receipts) {
if (getBestBlock() != null && !getBestBlock().isParentOf(newBlock)) {
// need to switch the state to another fork
Block commonAncestor = findCommonAncestor(getBestBlock(), newBlock);
if (logger.isDebugEnabled()) logger.debug("New best block from another fork: "
+ newBlock.getShortDescr() + ", old best: " + getBestBlock().getShortDescr()
+ ", ancestor: " + commonAncestor.getShortDescr());
// first return back the transactions from forked blocks
Block rollback = getBestBlock();
while(!rollback.isEqual(commonAncestor)) {
List<PendingTransaction> blockTxs = new ArrayList<>();
for (Transaction tx : rollback.getTransactionsList()) {
logger.debug("Returning transaction back to pending: " + tx);
blockTxs.add(new PendingTransaction(tx, commonAncestor.getNumber()));
}
pendingTransactions.addAll(0, blockTxs);
rollback = blockchain.getBlockByHash(rollback.getParentHash());
}
// rollback the state snapshot to the ancestor
pendingState = repository.getSnapshotTo(commonAncestor.getStateRoot()).startTracking();
// next process blocks from new fork
Block main = newBlock;
List<Block> mainFork = new ArrayList<>();
while(!main.isEqual(commonAncestor)) {
mainFork.add(main);
main = blockchain.getBlockByHash(main.getParentHash());
}
// processing blocks from ancestor to new block
for (int i = mainFork.size() - 1; i >= 0; i--) {
processBestInternal(mainFork.get(i), null);
}
} else {
logger.debug("PendingStateImpl.processBest: " + newBlock.getShortDescr());
processBestInternal(newBlock, receipts);
}
best = newBlock;
updateState(newBlock);
listener.onPendingStateChanged(PendingStateImpl.this);
}
private void processBestInternal(Block block, List<TransactionReceipt> receipts) {
clearWire(block, receipts);
clearOutdated(block.getNumber());
}
private void clearOutdated(final long blockNumber) {
List<PendingTransaction> outdated = new ArrayList<>();
synchronized (pendingTransactions) {
for (PendingTransaction tx : pendingTransactions)
if (blockNumber - tx.getBlockNumber() > config.txOutdatedThreshold()) {
outdated.add(tx);
listener.onPendingTransactionUpdate(
createDroppedReceipt(tx.getTransaction(), "Tx was not included into last " + CONFIG.txOutdatedThreshold() + " blocks"),
EthereumListener.PendingTransactionState.DROPPED, getBestBlock());
}
}
if (outdated.isEmpty()) return;
if (logger.isInfoEnabled())
for (PendingTransaction tx : outdated)
logger.info(
"Clear outdated wire transaction, block.number: [{}] hash: [{}]",
tx.getBlockNumber(),
Hex.toHexString(tx.getHash())
);
pendingTransactions.removeAll(outdated);
}
private void clearWire(Block block, List<TransactionReceipt> receipts) {
for (int i = 0; i < block.getTransactionsList().size(); i++) {
Transaction tx = block.getTransactionsList().get(i);
PendingTransaction pend = new PendingTransaction(tx);
if (pendingTransactions.remove(pend)) {
try {
logger.info("Clear pending transaction, hash: [{}]", Hex.toHexString(tx.getHash()));
TransactionReceipt receipt;
if (receipts != null) {
receipt = receipts.get(i);
} else {
TransactionInfo info = transactionStore.get(tx.getHash(), block.getHash());
receipt = info.getReceipt();
}
listener.onPendingTransactionUpdate(receipt, EthereumListener.PendingTransactionState.INCLUDED, block);
} catch (Exception e) {
logger.error("Exception creating onPendingTransactionUpdate (block: " + block.getShortDescr() + ", tx: " + i, e);
}
}
}
}
private void updateState(Block block) {
pendingState = repository.startTracking();
for (PendingTransaction tx : pendingTransactions) {
TransactionReceipt receipt = executeTx(tx.getTransaction());
listener.onPendingTransactionUpdate(receipt, EthereumListener.PendingTransactionState.PENDING, block);
}
}
private TransactionReceipt executeTx(Transaction tx) {
logger.info("Apply pending state tx: {}", Hex.toHexString(tx.getHash()));
Block best = getBestBlock();
TransactionExecutor executor = new TransactionExecutor(
tx, best.getCoinbase(), pendingState,
blockStore, programInvokeFactory, best
);
executor.init();
executor.execute();
executor.go();
executor.finalization();
return executor.getReceipt();
}
public void setBlockchain(Blockchain blockchain) {
this.blockchain = blockchain;
}
}
| Min gasPrice is also allowed
| ethereumj-core/src/main/java/org/ethereum/core/PendingStateImpl.java | Min gasPrice is also allowed | <ide><path>thereumj-core/src/main/java/org/ethereum/core/PendingStateImpl.java
<ide> private final Map<ByteArrayWrapper, Object> redceivedTxs = new LRUMap<>(500000);
<ide> private final Object dummyObject = new Object();
<ide>
<del> @Resource
<del> @Qualifier("pendingStateTransactions")
<del>
<ide> private Repository pendingState;
<ide>
<ide> private Block best = null;
<ide> // validations which are not performed within executeTx
<ide> private String validate(Transaction tx) {
<ide>
<del> if (config.getMineMinGasPrice().compareTo(ByteUtil.bytesToBigInteger(tx.gasPrice)) >= 0) {
<add> if (config.getMineMinGasPrice().compareTo(ByteUtil.bytesToBigInteger(tx.gasPrice)) > 0) {
<ide> return "Too low gas price for transaction: " + ByteUtil.bytesToBigInteger(tx.gasPrice);
<ide> }
<ide> |
|
Java | mit | c85072c4219cf8ae6c3d159c21b1b6f00e13f677 | 0 | aoguren/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,mhcrnl/java-swing-tips,aoguren/java-swing-tips,mhcrnl/java-swing-tips,aoguren/java-swing-tips,mhcrnl/java-swing-tips | package example;
//-*- mode:java; encoding:utf8n; coding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.table.*;
public class MainPanel extends JPanel {
private final JCheckBox modelCheck = new JCheckBox("isCellEditable return false");
private final JCheckBox objectCheck = new JCheckBox("setDefaultEditor(Object.class, null)");
private final JCheckBox editableCheck = new JCheckBox("setEnabled(false)");
private final JTable table;
public MainPanel() {
super(new BorderLayout());
TestModel model = new TestModel() {
@Override public boolean isCellEditable(int row, int col) {
return !modelCheck.isSelected();
}
};
model.addTest(new Test("Name 1", "Comment"));
model.addTest(new Test("Name 2", "Test"));
model.addTest(new Test("Name d", ""));
model.addTest(new Test("Name c", "Test cc"));
model.addTest(new Test("Name b", "Test bb"));
model.addTest(new Test("Name a", ""));
model.addTest(new Test("Name 0", "Test aa"));
model.addTest(new Test("Name 0", ""));
table = new JTable(model);
TableColumn col = table.getColumnModel().getColumn(0);
col.setMinWidth(50);
col.setMaxWidth(50);
col.setResizable(false);
ActionListener al = new ActionListener() {
private final DefaultCellEditor dce = new DefaultCellEditor(new JTextField());
@Override public void actionPerformed(ActionEvent e) {
table.clearSelection();
if(table.isEditing()) table.getCellEditor().stopCellEditing();
table.setDefaultEditor(Object.class, (objectCheck.isSelected())?null:dce);
table.setEnabled(!editableCheck.isSelected());
}
};
JPanel p = new JPanel(new GridLayout(3,1));
for(JCheckBox cb: Arrays.asList(modelCheck, objectCheck, editableCheck)) {
cb.addActionListener(al);
p.add(cb);
}
add(p, BorderLayout.NORTH);
add(new JScrollPane(table));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TestModel extends DefaultTableModel {
private static final ColumnContext[] columnArray = {
new ColumnContext("No.", Integer.class, false),
new ColumnContext("Name", String.class, true),
new ColumnContext("Comment", String.class, true)
};
private int number = 0;
public void addTest(Test t) {
Object[] obj = {number, t.getName(), t.getComment()};
super.addRow(obj);
number++;
}
@Override public boolean isCellEditable(int row, int col) {
return columnArray[col].isEditable;
}
@Override public Class<?> getColumnClass(int modelIndex) {
return columnArray[modelIndex].columnClass;
}
@Override public int getColumnCount() {
return columnArray.length;
}
@Override public String getColumnName(int modelIndex) {
return columnArray[modelIndex].columnName;
}
private static class ColumnContext {
public final String columnName;
public final Class columnClass;
public final boolean isEditable;
public ColumnContext(String columnName, Class columnClass, boolean isEditable) {
this.columnName = columnName;
this.columnClass = columnClass;
this.isEditable = isEditable;
}
}
}
class Test{
private String name, comment;
public Test(String name, String comment) {
this.name = name;
this.comment = comment;
}
public void setName(String str) {
name = str;
}
public void setComment(String str) {
comment = str;
}
public String getName() {
return name;
}
public String getComment() {
return comment;
}
}
| CellEditor/src/java/example/MainPanel.java | package example;
//-*- mode:java; encoding:utf8n; coding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class MainPanel extends JPanel {
private final JCheckBox modelCheck = new JCheckBox("isCellEditable return false");
private final JCheckBox objectCheck = new JCheckBox("setDefaultEditor(Object.class, null)");
private final JCheckBox editableCheck = new JCheckBox("setEnabled(false)");
private final JTable table;
public MainPanel() {
super(new BorderLayout());
TestModel model = new TestModel() {
@Override public boolean isCellEditable(int row, int col) {
return (col==0)?false:!modelCheck.isSelected();
}
};
model.addTest(new Test("Name 1", "Comment"));
model.addTest(new Test("Name 2", "Test"));
model.addTest(new Test("Name d", ""));
model.addTest(new Test("Name c", "Test cc"));
model.addTest(new Test("Name b", "Test bb"));
model.addTest(new Test("Name a", ""));
model.addTest(new Test("Name 0", "Test aa"));
model.addTest(new Test("Name 0", ""));
table = new JTable(model) {
private final Color evenColor = new Color(250, 250, 250);
@Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
Component c = super.prepareRenderer(tcr, row, column);
if(isRowSelected(row)) {
c.setForeground(getSelectionForeground());
c.setBackground(getSelectionBackground());
}else{
c.setForeground(getForeground());
c.setBackground((row%2==0)?evenColor:table.getBackground());
}
return c;
}
};
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JTableHeader tableHeader = table.getTableHeader();
tableHeader.setReorderingAllowed(false);
TableColumn col = table.getColumnModel().getColumn(0);
col.setMinWidth(50);
col.setMaxWidth(50);
col.setResizable(false);
ActionListener al = new ActionListener() {
private final DefaultCellEditor dce = new DefaultCellEditor(new JTextField());
@Override public void actionPerformed(ActionEvent e) {
table.clearSelection();
if(table.isEditing()) table.getCellEditor().stopCellEditing();
table.setDefaultEditor(Object.class, (objectCheck.isSelected())?null:dce);
table.setEnabled(!editableCheck.isSelected());
}
};
modelCheck.addActionListener(al);
objectCheck.addActionListener(al);
editableCheck.addActionListener(al);
JPanel p = new JPanel(new GridLayout(3,1));
p.add(modelCheck);
p.add(objectCheck);
p.add(editableCheck);
add(p, BorderLayout.NORTH);
add(new JScrollPane(table));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TestModel extends DefaultTableModel {
private static final ColumnContext[] columnArray = {
new ColumnContext("No.", Integer.class, false),
new ColumnContext("Name", String.class, true),
new ColumnContext("Comment", String.class, true)
};
private int number = 0;
public void addTest(Test t) {
Object[] obj = {number, t.getName(), t.getComment()};
super.addRow(obj);
number++;
}
@Override public boolean isCellEditable(int row, int col) {
return columnArray[col].isEditable;
}
@Override public Class<?> getColumnClass(int modelIndex) {
return columnArray[modelIndex].columnClass;
}
@Override public int getColumnCount() {
return columnArray.length;
}
@Override public String getColumnName(int modelIndex) {
return columnArray[modelIndex].columnName;
}
private static class ColumnContext {
public final String columnName;
public final Class columnClass;
public final boolean isEditable;
public ColumnContext(String columnName, Class columnClass, boolean isEditable) {
this.columnName = columnName;
this.columnClass = columnClass;
this.isEditable = isEditable;
}
}
}
class Test{
private String name, comment;
public Test(String name, String comment) {
this.name = name;
this.comment = comment;
}
public void setName(String str) {
name = str;
}
public void setComment(String str) {
comment = str;
}
public String getName() {
return name;
}
public String getComment() {
return comment;
}
}
| Arrays.asList | CellEditor/src/java/example/MainPanel.java | Arrays.asList | <ide><path>ellEditor/src/java/example/MainPanel.java
<ide> //@homepage@
<ide> import java.awt.*;
<ide> import java.awt.event.*;
<add>import java.util.Arrays;
<ide> import javax.swing.*;
<ide> import javax.swing.table.*;
<ide>
<ide> super(new BorderLayout());
<ide> TestModel model = new TestModel() {
<ide> @Override public boolean isCellEditable(int row, int col) {
<del> return (col==0)?false:!modelCheck.isSelected();
<add> return !modelCheck.isSelected();
<ide> }
<ide> };
<ide> model.addTest(new Test("Name 1", "Comment"));
<ide> model.addTest(new Test("Name 0", "Test aa"));
<ide> model.addTest(new Test("Name 0", ""));
<ide>
<del> table = new JTable(model) {
<del> private final Color evenColor = new Color(250, 250, 250);
<del> @Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column) {
<del> Component c = super.prepareRenderer(tcr, row, column);
<del> if(isRowSelected(row)) {
<del> c.setForeground(getSelectionForeground());
<del> c.setBackground(getSelectionBackground());
<del> }else{
<del> c.setForeground(getForeground());
<del> c.setBackground((row%2==0)?evenColor:table.getBackground());
<del> }
<del> return c;
<del> }
<del> };
<del> table.setRowSelectionAllowed(true);
<del> table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
<del>
<del> JTableHeader tableHeader = table.getTableHeader();
<del> tableHeader.setReorderingAllowed(false);
<add> table = new JTable(model);
<ide>
<ide> TableColumn col = table.getColumnModel().getColumn(0);
<ide> col.setMinWidth(50);
<ide> table.setEnabled(!editableCheck.isSelected());
<ide> }
<ide> };
<del> modelCheck.addActionListener(al);
<del> objectCheck.addActionListener(al);
<del> editableCheck.addActionListener(al);
<ide>
<ide> JPanel p = new JPanel(new GridLayout(3,1));
<del> p.add(modelCheck);
<del> p.add(objectCheck);
<del> p.add(editableCheck);
<del>
<add> for(JCheckBox cb: Arrays.asList(modelCheck, objectCheck, editableCheck)) {
<add> cb.addActionListener(al);
<add> p.add(cb);
<add> }
<ide> add(p, BorderLayout.NORTH);
<ide> add(new JScrollPane(table));
<ide> setPreferredSize(new Dimension(320, 240)); |
|
Java | mit | f5f7b0bb5d921b348b63bb9799460c91fe44ef88 | 0 | MJ10/Cosmo | package io.mokshjn.cosmo.helpers;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import io.mokshjn.cosmo.provider.LibraryProvider;
import static io.mokshjn.cosmo.helpers.MediaIDHelper.MEDIA_ID_MUSICS_BY_ALBUM;
import static io.mokshjn.cosmo.helpers.MediaIDHelper.MEDIA_ID_MUSICS_BY_SEARCH;
import static io.mokshjn.cosmo.helpers.MediaIDHelper.MEDIA_ID_ROOT;
/**
* Created by moksh on 19/3/17.
*/
public class QueueHelper {
private static final String TAG = LogHelper.makeLogTag(QueueHelper.class);
private static final int RANDOM_QUEUE_SIZE = 10;
public static List<MediaSessionCompat.QueueItem> getPlayingQueue(String mediaId,
LibraryProvider musicProvider) {
// extract the browsing hierarchy from the media ID:
String[] hierarchy = MediaIDHelper.getHierarchy(mediaId);
if (hierarchy.length > 2) {
LogHelper.e(TAG, "Could not build a playing queue for this mediaId: ", mediaId);
return null;
}
String categoryValue = "";
String categoryType = hierarchy[0];
if (hierarchy.length == 2) {
categoryValue = hierarchy[1];
}
LogHelper.d(TAG, "Creating playing queue for ", categoryType, ", ", categoryValue);
Iterable<MediaMetadataCompat> tracks = null;
// This sample only supports genre and by_search category types.
if (categoryType.equals(MEDIA_ID_MUSICS_BY_SEARCH)) {
tracks = musicProvider.searchMusicBySongTitle(categoryValue);
} else if (categoryType.equals(MEDIA_ID_ROOT)) {
tracks = musicProvider.getTracks();
} else if (categoryType.equals(MEDIA_ID_MUSICS_BY_ALBUM)) {
tracks = musicProvider.searchMusicByAlbum(categoryValue);
}
if (tracks == null) {
LogHelper.e(TAG, "Unrecognized category type: ", categoryType, " for media ", mediaId, "hahahah");
return null;
}
if (hierarchy.length == 2) {
return convertToQueue(tracks, hierarchy[0], hierarchy[1]);
} else {
return convertToQueue(tracks, hierarchy[0]);
}
}
public static List<MediaSessionCompat.QueueItem> getPlayingQueueFromAlbum(String album, LibraryProvider musicProvider) {
LogHelper.d(TAG, "Creating playing queue for musics from album: ", album);
ArrayList<MediaMetadataCompat> tracks = new ArrayList<>();
Iterable<MediaMetadataCompat> result;
result = musicProvider.searchMusicByAlbum(album);
for (MediaMetadataCompat m : result) {
tracks.add(m);
}
tracks.sort(new Comparator<MediaMetadataCompat>() {
@Override
public int compare(MediaMetadataCompat o1, MediaMetadataCompat o2) {
return (int) (o1.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER) - o2.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER));
}
});
return convertToQueue(tracks, MEDIA_ID_MUSICS_BY_ALBUM, album);
}
public static List<MediaSessionCompat.QueueItem> getPlayingQueueFromSearch(String query,
Bundle queryParams, LibraryProvider musicProvider) {
LogHelper.d(TAG, "Creating playing queue for musics from search: ", query,
" params=", queryParams);
VoiceSearchParams params = new VoiceSearchParams(query, queryParams);
LogHelper.d(TAG, "VoiceSearchParams: ", params);
if (params.isAny) {
// If isAny is true, we will play anything. This is app-dependent, and can be,
// for example, favorite playlists, "I'm feeling lucky", most recent, etc.
return getRandomQueue(musicProvider);
}
Iterable<MediaMetadataCompat> result = null;
if (params.isAlbumFocus) {
result = musicProvider.searchMusicByAlbum(params.album);
} else if (params.isArtistFocus) {
result = musicProvider.searchMusicByArtist(params.artist);
} else if (params.isSongFocus) {
result = musicProvider.searchMusicBySongTitle(params.song);
}
// If there was no results using media focus parameter, we do an unstructured query.
// This is useful when the user is searching for something that looks like an artist
// to Google, for example, but is not. For example, a user searching for Madonna on
// a PodCast application wouldn't get results if we only looked at the
// Artist (podcast author). Then, we can instead do an unstructured search.
if (params.isUnstructured || result == null || !result.iterator().hasNext()) {
// To keep it simple for this example, we do unstructured searches on the
// song title only. A real world application could search on other fields as well.
result = musicProvider.searchMusicBySongTitle(query);
}
return convertToQueue(result, MEDIA_ID_MUSICS_BY_SEARCH, query);
}
public static int getMusicIndexOnQueue(Iterable<MediaSessionCompat.QueueItem> queue,
String mediaId) {
int index = 0;
for (MediaSessionCompat.QueueItem item : queue) {
if (mediaId.equals(item.getDescription().getMediaId())) {
return index;
}
index++;
}
return -1;
}
public static int getMusicIndexOnQueue(Iterable<MediaSessionCompat.QueueItem> queue,
long queueId) {
int index = 0;
for (MediaSessionCompat.QueueItem item : queue) {
if (queueId == item.getQueueId()) {
return index;
}
index++;
}
return -1;
}
private static List<MediaSessionCompat.QueueItem> convertToQueue(
Iterable<MediaMetadataCompat> tracks, String... categories) {
List<MediaSessionCompat.QueueItem> queue = new ArrayList<>();
int count = 0;
for (MediaMetadataCompat track : tracks) {
// We create a hierarchy-aware mediaID, so we know what the queue is about by looking
// at the QueueItem media IDs.
String hierarchyAwareMediaID = MediaIDHelper.createMediaID(
track.getDescription().getMediaId(), categories);
MediaMetadataCompat trackCopy = new MediaMetadataCompat.Builder(track)
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, hierarchyAwareMediaID)
.build();
// We don't expect queues to change after created, so we use the item index as the
// queueId. Any other number unique in the queue would work.
MediaSessionCompat.QueueItem item = new MediaSessionCompat.QueueItem(
trackCopy.getDescription(), count++);
queue.add(item);
}
return queue;
}
/**
* Create a random queue with at most {@link #RANDOM_QUEUE_SIZE} elements.
*
* @param musicProvider the provider used for fetching music.
* @return list containing {@link MediaSessionCompat.QueueItem}'s
*/
public static List<MediaSessionCompat.QueueItem> getRandomQueue(LibraryProvider musicProvider) {
List<MediaMetadataCompat> result = new ArrayList<>(RANDOM_QUEUE_SIZE);
Iterable<MediaMetadataCompat> shuffled = musicProvider.getShuffledMusic();
for (MediaMetadataCompat metadata: shuffled) {
if (result.size() == RANDOM_QUEUE_SIZE) {
break;
}
result.add(metadata);
}
LogHelper.d(TAG, "getRandomQueue: result.size=", result.size());
return convertToQueue(result, MEDIA_ID_MUSICS_BY_SEARCH, "random");
}
public static boolean isIndexPlayable(int index, List<MediaSessionCompat.QueueItem> queue) {
return (queue != null && index >= 0 && index < queue.size());
}
/**
* Determine if two queues contain identical media id's in order.
*
* @param list1 containing {@link MediaSessionCompat.QueueItem}'s
* @param list2 containing {@link MediaSessionCompat.QueueItem}'s
* @return boolean indicating whether the queue's match
*/
public static boolean equals(List<MediaSessionCompat.QueueItem> list1,
List<MediaSessionCompat.QueueItem> list2) {
if (list1 == list2) {
return true;
}
if (list1 == null || list2 == null) {
return false;
}
if (list1.size() != list2.size()) {
return false;
}
for (int i=0; i<list1.size(); i++) {
if (list1.get(i).getQueueId() != list2.get(i).getQueueId()) {
return false;
}
if (!TextUtils.equals(list1.get(i).getDescription().getMediaId(),
list2.get(i).getDescription().getMediaId())) {
return false;
}
}
return true;
}
/**
* Determine if queue item matches the currently playing queue item
*
* @param context for retrieving the {@link MediaControllerCompat}
* @param queueItem to compare to currently playing {@link MediaSessionCompat.QueueItem}
* @return boolean indicating whether queue item matches currently playing queue item
*/
public static boolean isQueueItemPlaying(Context context,
MediaSessionCompat.QueueItem queueItem) {
// Queue item is considered to be playing or paused based on both the controller's
// current media id and the controller's active queue item id
MediaControllerCompat controller = ((FragmentActivity) context).getSupportMediaController();
if (controller != null && controller.getPlaybackState() != null) {
long currentPlayingQueueId = controller.getPlaybackState().getActiveQueueItemId();
String currentPlayingMediaId = controller.getMetadata().getDescription()
.getMediaId();
String itemMusicId = MediaIDHelper.extractMusicIDFromMediaID(
queueItem.getDescription().getMediaId());
if (queueItem.getQueueId() == currentPlayingQueueId
&& currentPlayingMediaId != null
&& TextUtils.equals(currentPlayingMediaId, itemMusicId)) {
return true;
}
}
return false;
}
}
| app/src/main/java/io/mokshjn/cosmo/helpers/QueueHelper.java | package io.mokshjn.cosmo.helpers;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
import io.mokshjn.cosmo.provider.LibraryProvider;
import static io.mokshjn.cosmo.helpers.MediaIDHelper.MEDIA_ID_MUSICS_BY_ALBUM;
import static io.mokshjn.cosmo.helpers.MediaIDHelper.MEDIA_ID_MUSICS_BY_SEARCH;
import static io.mokshjn.cosmo.helpers.MediaIDHelper.MEDIA_ID_ROOT;
/**
* Created by moksh on 19/3/17.
*/
public class QueueHelper {
private static final String TAG = LogHelper.makeLogTag(QueueHelper.class);
private static final int RANDOM_QUEUE_SIZE = 10;
public static List<MediaSessionCompat.QueueItem> getPlayingQueue(String mediaId,
LibraryProvider musicProvider) {
// extract the browsing hierarchy from the media ID:
String[] hierarchy = MediaIDHelper.getHierarchy(mediaId);
if (hierarchy.length > 2) {
LogHelper.e(TAG, "Could not build a playing queue for this mediaId: ", mediaId);
return null;
}
String categoryValue = "";
String categoryType = hierarchy[0];
if (hierarchy.length == 2) {
categoryValue = hierarchy[1];
}
LogHelper.d(TAG, "Creating playing queue for ", categoryType, ", ", categoryValue);
Iterable<MediaMetadataCompat> tracks = null;
// This sample only supports genre and by_search category types.
if (categoryType.equals(MEDIA_ID_MUSICS_BY_SEARCH)) {
tracks = musicProvider.searchMusicBySongTitle(categoryValue);
} else if (categoryType.equals(MEDIA_ID_ROOT)) {
tracks = musicProvider.getTracks();
} else if (categoryType.equals(MEDIA_ID_MUSICS_BY_ALBUM)) {
tracks = musicProvider.searchMusicByAlbum(categoryValue);
}
if (tracks == null) {
LogHelper.e(TAG, "Unrecognized category type: ", categoryType, " for media ", mediaId, "hahahah");
return null;
}
if (hierarchy.length == 2) {
return convertToQueue(tracks, hierarchy[0], hierarchy[1]);
} else {
return convertToQueue(tracks, hierarchy[0]);
}
}
public static List<MediaSessionCompat.QueueItem> getPlayingQueueFromAlbum(String album, LibraryProvider musicProvider) {
LogHelper.d(TAG, "Creating playing queue for musics from album: ", album);
Iterable<MediaMetadataCompat> result;
result = musicProvider.searchMusicByAlbum(album);
return convertToQueue(result, MEDIA_ID_MUSICS_BY_ALBUM, album);
}
public static List<MediaSessionCompat.QueueItem> getPlayingQueueFromSearch(String query,
Bundle queryParams, LibraryProvider musicProvider) {
LogHelper.d(TAG, "Creating playing queue for musics from search: ", query,
" params=", queryParams);
VoiceSearchParams params = new VoiceSearchParams(query, queryParams);
LogHelper.d(TAG, "VoiceSearchParams: ", params);
if (params.isAny) {
// If isAny is true, we will play anything. This is app-dependent, and can be,
// for example, favorite playlists, "I'm feeling lucky", most recent, etc.
return getRandomQueue(musicProvider);
}
Iterable<MediaMetadataCompat> result = null;
if (params.isAlbumFocus) {
result = musicProvider.searchMusicByAlbum(params.album);
} else if (params.isArtistFocus) {
result = musicProvider.searchMusicByArtist(params.artist);
} else if (params.isSongFocus) {
result = musicProvider.searchMusicBySongTitle(params.song);
}
// If there was no results using media focus parameter, we do an unstructured query.
// This is useful when the user is searching for something that looks like an artist
// to Google, for example, but is not. For example, a user searching for Madonna on
// a PodCast application wouldn't get results if we only looked at the
// Artist (podcast author). Then, we can instead do an unstructured search.
if (params.isUnstructured || result == null || !result.iterator().hasNext()) {
// To keep it simple for this example, we do unstructured searches on the
// song title only. A real world application could search on other fields as well.
result = musicProvider.searchMusicBySongTitle(query);
}
return convertToQueue(result, MEDIA_ID_MUSICS_BY_SEARCH, query);
}
public static int getMusicIndexOnQueue(Iterable<MediaSessionCompat.QueueItem> queue,
String mediaId) {
int index = 0;
for (MediaSessionCompat.QueueItem item : queue) {
if (mediaId.equals(item.getDescription().getMediaId())) {
return index;
}
index++;
}
return -1;
}
public static int getMusicIndexOnQueue(Iterable<MediaSessionCompat.QueueItem> queue,
long queueId) {
int index = 0;
for (MediaSessionCompat.QueueItem item : queue) {
if (queueId == item.getQueueId()) {
return index;
}
index++;
}
return -1;
}
private static List<MediaSessionCompat.QueueItem> convertToQueue(
Iterable<MediaMetadataCompat> tracks, String... categories) {
List<MediaSessionCompat.QueueItem> queue = new ArrayList<>();
int count = 0;
for (MediaMetadataCompat track : tracks) {
// We create a hierarchy-aware mediaID, so we know what the queue is about by looking
// at the QueueItem media IDs.
String hierarchyAwareMediaID = MediaIDHelper.createMediaID(
track.getDescription().getMediaId(), categories);
MediaMetadataCompat trackCopy = new MediaMetadataCompat.Builder(track)
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, hierarchyAwareMediaID)
.build();
// We don't expect queues to change after created, so we use the item index as the
// queueId. Any other number unique in the queue would work.
MediaSessionCompat.QueueItem item = new MediaSessionCompat.QueueItem(
trackCopy.getDescription(), count++);
queue.add(item);
}
return queue;
}
/**
* Create a random queue with at most {@link #RANDOM_QUEUE_SIZE} elements.
*
* @param musicProvider the provider used for fetching music.
* @return list containing {@link MediaSessionCompat.QueueItem}'s
*/
public static List<MediaSessionCompat.QueueItem> getRandomQueue(LibraryProvider musicProvider) {
List<MediaMetadataCompat> result = new ArrayList<>(RANDOM_QUEUE_SIZE);
Iterable<MediaMetadataCompat> shuffled = musicProvider.getShuffledMusic();
for (MediaMetadataCompat metadata: shuffled) {
if (result.size() == RANDOM_QUEUE_SIZE) {
break;
}
result.add(metadata);
}
LogHelper.d(TAG, "getRandomQueue: result.size=", result.size());
return convertToQueue(result, MEDIA_ID_MUSICS_BY_SEARCH, "random");
}
public static boolean isIndexPlayable(int index, List<MediaSessionCompat.QueueItem> queue) {
return (queue != null && index >= 0 && index < queue.size());
}
/**
* Determine if two queues contain identical media id's in order.
*
* @param list1 containing {@link MediaSessionCompat.QueueItem}'s
* @param list2 containing {@link MediaSessionCompat.QueueItem}'s
* @return boolean indicating whether the queue's match
*/
public static boolean equals(List<MediaSessionCompat.QueueItem> list1,
List<MediaSessionCompat.QueueItem> list2) {
if (list1 == list2) {
return true;
}
if (list1 == null || list2 == null) {
return false;
}
if (list1.size() != list2.size()) {
return false;
}
for (int i=0; i<list1.size(); i++) {
if (list1.get(i).getQueueId() != list2.get(i).getQueueId()) {
return false;
}
if (!TextUtils.equals(list1.get(i).getDescription().getMediaId(),
list2.get(i).getDescription().getMediaId())) {
return false;
}
}
return true;
}
/**
* Determine if queue item matches the currently playing queue item
*
* @param context for retrieving the {@link MediaControllerCompat}
* @param queueItem to compare to currently playing {@link MediaSessionCompat.QueueItem}
* @return boolean indicating whether queue item matches currently playing queue item
*/
public static boolean isQueueItemPlaying(Context context,
MediaSessionCompat.QueueItem queueItem) {
// Queue item is considered to be playing or paused based on both the controller's
// current media id and the controller's active queue item id
MediaControllerCompat controller = ((FragmentActivity) context).getSupportMediaController();
if (controller != null && controller.getPlaybackState() != null) {
long currentPlayingQueueId = controller.getPlaybackState().getActiveQueueItemId();
String currentPlayingMediaId = controller.getMetadata().getDescription()
.getMediaId();
String itemMusicId = MediaIDHelper.extractMusicIDFromMediaID(
queueItem.getDescription().getMediaId());
if (queueItem.getQueueId() == currentPlayingQueueId
&& currentPlayingMediaId != null
&& TextUtils.equals(currentPlayingMediaId, itemMusicId)) {
return true;
}
}
return false;
}
}
| improve album track listing
| app/src/main/java/io/mokshjn/cosmo/helpers/QueueHelper.java | improve album track listing | <ide><path>pp/src/main/java/io/mokshjn/cosmo/helpers/QueueHelper.java
<ide> import android.text.TextUtils;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.Comparator;
<ide> import java.util.List;
<ide>
<ide> import io.mokshjn.cosmo.provider.LibraryProvider;
<ide> public static List<MediaSessionCompat.QueueItem> getPlayingQueueFromAlbum(String album, LibraryProvider musicProvider) {
<ide>
<ide> LogHelper.d(TAG, "Creating playing queue for musics from album: ", album);
<del>
<add> ArrayList<MediaMetadataCompat> tracks = new ArrayList<>();
<ide> Iterable<MediaMetadataCompat> result;
<ide> result = musicProvider.searchMusicByAlbum(album);
<del> return convertToQueue(result, MEDIA_ID_MUSICS_BY_ALBUM, album);
<add> for (MediaMetadataCompat m : result) {
<add> tracks.add(m);
<add> }
<add> tracks.sort(new Comparator<MediaMetadataCompat>() {
<add> @Override
<add> public int compare(MediaMetadataCompat o1, MediaMetadataCompat o2) {
<add> return (int) (o1.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER) - o2.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER));
<add> }
<add> });
<add> return convertToQueue(tracks, MEDIA_ID_MUSICS_BY_ALBUM, album);
<ide> }
<ide>
<ide> public static List<MediaSessionCompat.QueueItem> getPlayingQueueFromSearch(String query, |
|
Java | agpl-3.0 | 4f142cea10bf4ff5a4013aeefc18580bedc92120 | 0 | JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio | /*
* RCompletionManager.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.console.shell.assist;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.inject.Inject;
import org.rstudio.core.client.HandlerRegistrations;
import org.rstudio.core.client.Invalidation;
import org.rstudio.core.client.Rectangle;
import org.rstudio.core.client.RegexUtil;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardHelper;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.events.SelectionCommitEvent;
import org.rstudio.core.client.events.SelectionCommitHandler;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.GlobalProgressDelayer;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations;
import org.rstudio.studio.client.common.codetools.RCompletionType;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.codesearch.model.FunctionDefinition;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.snippets.SnippetHelper;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.CompletionResult;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.QualifiedName;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorLineWithCursorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorUtil;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay;
import org.rstudio.studio.client.workbench.views.source.editors.text.NavigableSourceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.RCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeFunction;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.CodeModel;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.DplyrJoinContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.RInfixData;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Token;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.TokenCursor;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.PasteEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.r.RCompletionToolTip;
import org.rstudio.studio.client.workbench.views.source.editors.text.r.SignatureToolTipManager;
import org.rstudio.studio.client.workbench.views.source.events.CodeBrowserNavigationEvent;
import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RCompletionManager implements CompletionManager
{
// globally suppress F1 and F2 so no default browser behavior takes those
// keystrokes (e.g. Help in Chrome)
static
{
Event.addNativePreviewHandler(new NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
if (event.getTypeInt() == Event.ONKEYDOWN)
{
int keyCode = event.getNativeEvent().getKeyCode();
if ((keyCode == 112 || keyCode == 113) &&
KeyboardShortcut.NONE ==
KeyboardShortcut.getModifierValue(event.getNativeEvent()))
{
event.getNativeEvent().preventDefault();
}
}
}
});
}
public void onPaste(PasteEvent event)
{
popup_.hide();
}
public RCompletionManager(InputEditorDisplay input,
NavigableSourceEditor navigableSourceEditor,
CompletionPopupDisplay popup,
CodeToolsServerOperations server,
InitCompletionFilter initFilter,
RCompletionContext rContext,
RnwCompletionContext rnwContext,
DocDisplay docDisplay,
boolean isConsole)
{
RStudioGinjector.INSTANCE.injectMembers(this);
input_ = input ;
navigableSourceEditor_ = navigableSourceEditor;
popup_ = popup ;
server_ = server ;
rContext_ = rContext;
initFilter_ = initFilter ;
rnwContext_ = rnwContext;
docDisplay_ = docDisplay;
isConsole_ = isConsole;
sigTipManager_ = new SignatureToolTipManager(docDisplay_);
suggestTimer_ = new SuggestionTimer(this, uiPrefs_);
snippets_ = new SnippetHelper((AceEditor) docDisplay, getSourceDocumentPath());
requester_ = new CompletionRequester(rnwContext, navigableSourceEditor, snippets_);
handlers_ = new HandlerRegistrations();
handlers_.add(input_.addBlurHandler(new BlurHandler() {
public void onBlur(BlurEvent event)
{
if (!ignoreNextInputBlur_)
invalidatePendingRequests() ;
ignoreNextInputBlur_ = false ;
}
}));
handlers_.add(input_.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
invalidatePendingRequests();
}
}));
handlers_.add(popup_.addSelectionCommitHandler(new SelectionCommitHandler<QualifiedName>() {
public void onSelectionCommit(SelectionCommitEvent<QualifiedName> event)
{
assert context_ != null : "onSelection called but handler is null" ;
if (context_ != null)
context_.onSelection(event.getSelectedItem()) ;
}
}));
handlers_.add(popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
public void onSelection(SelectionEvent<QualifiedName> event)
{
lastSelectedItem_ = event.getSelectedItem();
if (popup_.isHelpVisible())
context_.showHelp(lastSelectedItem_);
else
showHelpDeferred(context_, lastSelectedItem_, 600);
}
}));
handlers_.add(popup_.addMouseDownHandler(new MouseDownHandler() {
public void onMouseDown(MouseDownEvent event)
{
ignoreNextInputBlur_ = true ;
}
}));
handlers_.add(popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
@Override
public void onSelection(SelectionEvent<QualifiedName> event)
{
docDisplay_.setPopupVisible(true);
}
}));
handlers_.add(popup_.addCloseHandler(new CloseHandler<PopupPanel>()
{
@Override
public void onClose(CloseEvent<PopupPanel> event)
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
docDisplay_.setPopupVisible(false);
}
});
}
}));
handlers_.add(popup_.addAttachHandler(new AttachEvent.Handler()
{
private boolean wasSigtipShowing_ = false;
@Override
public void onAttachOrDetach(AttachEvent event)
{
RCompletionToolTip toolTip = sigTipManager_.getToolTip();
if (event.isAttached())
{
if (toolTip != null && toolTip.isShowing())
{
wasSigtipShowing_ = true;
toolTip.setVisible(false);
}
else
{
wasSigtipShowing_ = false;
}
}
else
{
if (toolTip != null && wasSigtipShowing_)
toolTip.setVisible(true);
}
}
}));
}
@Inject
public void initialize(GlobalDisplay globalDisplay,
FileTypeRegistry fileTypeRegistry,
EventBus eventBus,
HelpStrategy helpStrategy,
UIPrefs uiPrefs)
{
globalDisplay_ = globalDisplay;
fileTypeRegistry_ = fileTypeRegistry;
eventBus_ = eventBus;
helpStrategy_ = helpStrategy;
uiPrefs_ = uiPrefs;
}
public void detach()
{
handlers_.removeHandler();
sigTipManager_.detach();
snippets_.detach();
popup_.hide();
}
public void close()
{
popup_.hide();
}
public void codeCompletion()
{
if (initFilter_ == null || initFilter_.shouldComplete(null))
beginSuggest(true, false, true);
}
public void goToHelp()
{
InputEditorLineWithCursorPosition linePos =
InputEditorUtil.getLineWithCursorPosition(input_);
server_.getHelpAtCursor(
linePos.getLine(), linePos.getPosition(),
new SimpleRequestCallback<Void>("Help"));
}
public void goToFunctionDefinition()
{
// check for a file-local definition (intra-file navigation -- using
// the active scope tree)
AceEditor editor = (AceEditor) docDisplay_;
if (editor != null)
{
TokenCursor cursor = editor.getSession().getMode().getRCodeModel().getTokenCursor();
if (cursor.moveToPosition(editor.getCursorPosition(), true))
{
// if the cursor is 'on' a left bracket, move back to the associated
// token (obstensibly a funciton name)
if (cursor.isLeftBracket())
cursor.moveToPreviousToken();
// if the previous token is an extraction operator, we shouldn't
// navigate (as this isn't the 'full' function name)
if (cursor.moveToPreviousToken())
{
if (cursor.isExtractionOperator())
return;
cursor.moveToNextToken();
}
// if this is a string, try resolving that string as a file name
if (cursor.hasType("string"))
{
String tokenValue = cursor.currentValue();
String path = tokenValue.substring(1, tokenValue.length() - 1);
FileSystemItem filePath = FileSystemItem.createFile(path);
// This will show a dialog error if no such file exists; this
// seems the most appropriate action in such a case.
fileTypeRegistry_.editFile(filePath);
}
String functionName = cursor.currentValue();
JsArray<ScopeFunction> scopes =
editor.getAllFunctionScopes();
for (int i = 0; i < scopes.length(); i++)
{
ScopeFunction scope = scopes.get(i);
if (scope.getFunctionName().equals(functionName))
{
navigableSourceEditor_.navigateToPosition(
SourcePosition.create(scope.getPreamble().getRow(),
scope.getPreamble().getColumn()),
true);
return;
}
}
}
}
// intra-file navigation failed -- hit the server and find a definition
// in the project index
// determine current line and cursor position
InputEditorLineWithCursorPosition lineWithPos =
InputEditorUtil.getLineWithCursorPosition(input_);
// delayed progress indicator
final GlobalProgressDelayer progress = new GlobalProgressDelayer(
globalDisplay_, 1000, "Searching for function definition...");
server_.getFunctionDefinition(
lineWithPos.getLine(),
lineWithPos.getPosition(),
new ServerRequestCallback<FunctionDefinition>() {
@Override
public void onResponseReceived(FunctionDefinition def)
{
// dismiss progress
progress.dismiss();
// if we got a hit
if (def.getFunctionName() != null)
{
// search locally if a function navigator was provided
if (navigableSourceEditor_ != null)
{
// try to search for the function locally
SourcePosition position =
navigableSourceEditor_.findFunctionPositionFromCursor(
def.getFunctionName());
if (position != null)
{
navigableSourceEditor_.navigateToPosition(position,
true);
return; // we're done
}
}
// if we didn't satisfy the request using a function
// navigator and we got a file back from the server then
// navigate to the file/loc
if (def.getFile() != null)
{
fileTypeRegistry_.editFile(def.getFile(),
def.getPosition());
}
// if we didn't get a file back see if we got a
// search path definition
else if (def.getSearchPathFunctionDefinition() != null)
{
eventBus_.fireEvent(new CodeBrowserNavigationEvent(
def.getSearchPathFunctionDefinition()));
}
}
}
@Override
public void onError(ServerError error)
{
progress.dismiss();
globalDisplay_.showErrorMessage("Error Searching for Function",
error.getUserMessage());
}
});
}
public boolean previewKeyDown(NativeEvent event)
{
suggestTimer_.cancel();
if (sigTipManager_.previewKeyDown(event))
return true;
/**
* KEYS THAT MATTER
*
* When popup not showing:
* Tab - attempt completion (handled in Console.java)
*
* When popup showing:
* Esc - dismiss popup
* Enter/Tab - accept current selection
* Up-arrow/Down-arrow - change selected item
* [identifier] - narrow suggestions--or if we're lame, just dismiss
* All others - dismiss popup
*/
nativeEvent_ = event;
int keycode = event.getKeyCode();
int modifier = KeyboardShortcut.getModifierValue(event);
if (!popup_.isShowing())
{
// don't allow ctrl + space for completions in Emacs mode
if (docDisplay_.isEmacsModeOn() && event.getKeyCode() == KeyCodes.KEY_SPACE)
return false;
if (CompletionUtils.isCompletionRequest(event, modifier))
{
if (initFilter_ == null || initFilter_.shouldComplete(event))
{
// If we're in markdown mode, only autocomplete in '```{r',
// '[](', or '`r |' contexts
if (DocumentMode.isCursorInMarkdownMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!(Pattern.create("^```{[rR]").test(currentLine) ||
Pattern.create(".*\\[.*\\]\\(").test(currentLine) ||
(Pattern.create(".*`r").test(currentLine) &&
StringUtil.countMatches(currentLine, '`') % 2 == 1)))
return false;
}
// If we're in tex mode, only provide completions in chunks
if (DocumentMode.isCursorInTexMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!Pattern.create("^<<").test(currentLine))
return false;
}
return beginSuggest(true, false, true);
}
}
else if (event.getKeyCode() == KeyCodes.KEY_TAB &&
modifier == KeyboardShortcut.SHIFT)
{
return snippets_.attemptSnippetInsertion(true);
}
else if (keycode == 112 // F1
&& modifier == KeyboardShortcut.NONE)
{
goToHelp();
return true;
}
else if (keycode == 113 // F2
&& modifier == KeyboardShortcut.NONE)
{
goToFunctionDefinition();
return true;
}
}
else
{
switch (keycode)
{
// chrome on ubuntu now sends this before every keydown
// so we need to explicitly ignore it. see:
// https://github.com/ivaynberg/select2/issues/2482
case KeyCodes.KEY_WIN_IME:
return false ;
case KeyCodes.KEY_SHIFT:
case KeyCodes.KEY_CTRL:
case KeyCodes.KEY_ALT:
case KeyCodes.KEY_MAC_FF_META:
case KeyCodes.KEY_WIN_KEY_LEFT_META:
return false ; // bare modifiers should do nothing
}
if (modifier == KeyboardShortcut.CTRL)
{
switch (keycode)
{
case KeyCodes.KEY_P: return popup_.selectPrev();
case KeyCodes.KEY_N: return popup_.selectNext();
}
}
else if (modifier == KeyboardShortcut.NONE)
{
if (keycode == KeyCodes.KEY_ESCAPE)
{
invalidatePendingRequests() ;
return true ;
}
// NOTE: It is possible for the popup to still be showing, but
// showing offscreen with no values. We only grab these keys
// when the popup is both showing, and has completions.
// This functionality is here to ensure backspace works properly;
// e.g "stats::rna" -> "stats::rn" brings completions if the user
// had originally requested completions at e.g. "stats::".
if (popup_.hasCompletions() && !popup_.isOffscreen())
{
if (keycode == KeyCodes.KEY_ENTER)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
context_.onSelection(value) ;
return true ;
}
}
else if (keycode == KeyCodes.KEY_TAB)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
if (value.type == RCompletionType.DIRECTORY)
context_.suggestOnAccept_ = true;
context_.onSelection(value);
return true;
}
}
else if (keycode == KeyCodes.KEY_UP)
return popup_.selectPrev() ;
else if (keycode == KeyCodes.KEY_DOWN)
return popup_.selectNext() ;
else if (keycode == KeyCodes.KEY_PAGEUP)
return popup_.selectPrevPage() ;
else if (keycode == KeyCodes.KEY_PAGEDOWN)
return popup_.selectNextPage() ;
else if (keycode == KeyCodes.KEY_HOME)
return popup_.selectFirst();
else if (keycode == KeyCodes.KEY_END)
return popup_.selectLast();
if (keycode == 112) // F1
{
context_.showHelpTopic() ;
return true ;
}
else if (keycode == 113) // F2
{
goToFunctionDefinition();
return true;
}
}
}
if (canContinueCompletions(event))
return false;
// if we insert a '/', we're probably forming a directory --
// pop up completions
if (keycode == 191 && modifier == KeyboardShortcut.NONE)
{
input_.insertCode("/");
return beginSuggest(true, true, false);
}
// continue showing completions on backspace
if (keycode == KeyCodes.KEY_BACKSPACE && modifier == KeyboardShortcut.NONE &&
!docDisplay_.inMultiSelectMode())
{
int cursorColumn = input_.getCursorPosition().getColumn();
String currentLine = docDisplay_.getCurrentLine();
// only suggest if the character previous to the cursor is an R identifier
// also halt suggestions if we're about to remove the only character on the line
if (cursorColumn > 0)
{
char ch = currentLine.charAt(cursorColumn - 2);
char prevCh = currentLine.charAt(cursorColumn - 3);
boolean isAcceptableCharSequence = isValidForRIdentifier(ch) ||
(ch == ':' && prevCh == ':') ||
ch == '$' ||
ch == '@' ||
ch == '/'; // for file completions
if (currentLine.length() > 0 &&
cursorColumn > 0 &&
isAcceptableCharSequence)
{
// manually remove the previous character
InputEditorSelection selection = input_.getSelection();
InputEditorPosition start = selection.getStart().movePosition(-1, true);
InputEditorPosition end = selection.getStart();
if (currentLine.charAt(cursorColumn) == ')' && currentLine.charAt(cursorColumn - 1) == '(')
{
// flush cache as old completions no longer relevant
requester_.flushCache();
end = selection.getStart().movePosition(1, true);
}
input_.setSelection(new InputEditorSelection(start, end));
input_.replaceSelection("", false);
return beginSuggest(false, false, false);
}
}
else
{
invalidatePendingRequests();
return true;
}
}
invalidatePendingRequests();
return false ;
}
return false ;
}
private boolean isValidForRIdentifier(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '.') ||
(c == '_');
}
private boolean checkCanAutoPopup(char c, int lookbackLimit)
{
if (docDisplay_.isVimModeOn() &&
!docDisplay_.isVimInInsertMode())
return false;
String currentLine = docDisplay_.getCurrentLine();
Position cursorPos = input_.getCursorPosition();
int cursorColumn = cursorPos.getColumn();
// Don't auto-popup when the cursor is within a string
if (docDisplay_.isCursorInSingleLineString())
return false;
// Don't auto-popup if there is a character following the cursor
// (this implies an in-line edit and automatic popups are likely to
// be annoying)
if (isValidForRIdentifier(docDisplay_.getCharacterAtCursor()))
return false;
boolean canAutoPopup =
(currentLine.length() > lookbackLimit - 1 && isValidForRIdentifier(c));
if (isConsole_ && !uiPrefs_.alwaysCompleteInConsole().getValue())
canAutoPopup = false;
if (canAutoPopup)
{
for (int i = 0; i < lookbackLimit; i++)
{
if (!isValidForRIdentifier(currentLine.charAt(cursorColumn - i - 1)))
{
canAutoPopup = false;
break;
}
}
}
return canAutoPopup;
}
public boolean previewKeyPress(char c)
{
suggestTimer_.cancel();
if (popup_.isShowing())
{
// If insertion of this character completes an available suggestion,
// and is not a prefix match of any other suggestion, then implicitly
// apply that.
QualifiedName selectedItem =
popup_.getSelectedValue();
// NOTE: We should strip off trailing colons so that in-line edits of
// package completions, e.g.
//
// <foo>::
//
// can also dismiss the popup on a perfect match of <foo>.
if (selectedItem != null &&
selectedItem.name.replaceAll(":", "").equals(token_ + c))
{
String fullToken = token_ + c;
// Find prefix matches -- there should only be one if we really
// want this behaviour (ie the current selection)
int prefixMatchCount = 0;
QualifiedName[] items = popup_.getItems();
for (int i = 0; i < items.length; i++)
{
if (items[i].name.startsWith(fullToken))
{
++prefixMatchCount;
if (prefixMatchCount > 1)
break;
}
}
if (prefixMatchCount == 1)
{
// We place the completion list offscreen to ensure that
// backspace events are handled later.
popup_.placeOffscreen();
return false;
}
}
if (c == ':')
{
suggestTimer_.schedule(false, true, false);
return false;
}
if (c == ' ')
return false;
// Always update the current set of completions following
// a key insertion. Defer execution so the key insertion can
// enter the document.
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(false, true, false);
}
});
return false;
}
else
{
// Bail if we're not in R mode
if (!DocumentMode.isCursorInRMode(docDisplay_))
return false;
// Bail if we're in a single-line string
if (docDisplay_.isCursorInSingleLineString())
return false;
// if there's a selection, bail
if (input_.hasSelection())
return false;
// Bail if there is an alpha-numeric character
// following the cursor
if (isValidForRIdentifier(docDisplay_.getCharacterAtCursor()))
return false;
// Perform an auto-popup if a set number of R identifier characters
// have been inserted (but only if the user has allowed it in prefs)
boolean autoPopupEnabled = uiPrefs_.codeComplete().getValue().equals(
UIPrefsAccessor.COMPLETION_ALWAYS);
if (!autoPopupEnabled)
return false;
// Immediately display completions after '$', '::', etc.
char prevChar = docDisplay_.getCurrentLine().charAt(
input_.getCursorPosition().getColumn() - 1);
if (
(c == ':' && prevChar == ':') ||
(c == '$') ||
(c == '@')
)
{
// Bail if we're in Vim but not in insert mode
if (docDisplay_.isVimModeOn() &&
!docDisplay_.isVimInInsertMode())
{
return false;
}
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(true, true, false);
}
});
return false;
}
// Check for a valid number of R identifier characters for autopopup
boolean canAutoPopup = checkCanAutoPopup(c, uiPrefs_.alwaysCompleteCharacters().getValue() - 1);
// Attempt to pop up completions immediately after a function call.
if (c == '(' && !isLineInComment(docDisplay_.getCurrentLine()))
{
String token = StringUtil.getToken(
docDisplay_.getCurrentLine(),
input_.getCursorPosition().getColumn(),
"[" + RegexUtil.wordCharacter() + "._]",
false,
true);
if (token.matches("^(library|require|requireNamespace|data)\\s*$"))
canAutoPopup = true;
sigTipManager_.resolveActiveFunctionAndDisplayToolTip();
}
if (
(canAutoPopup) ||
isSweaveCompletion(c))
{
// Delay suggestion to avoid auto-popup while the user is typing
suggestTimer_.schedule(true, true, false);
}
}
return false ;
}
@SuppressWarnings("unused")
private boolean isRoxygenTagValidHere()
{
if (input_.getText().matches("\\s*#+'.*"))
{
String linePart = input_.getText().substring(0, input_.getSelection().getStart().getPosition());
if (linePart.matches("\\s*#+'\\s*"))
return true;
}
return false;
}
private boolean isSweaveCompletion(char c)
{
if (rnwContext_ == null || (c != ',' && c != ' ' && c != '='))
return false;
int optionsStart = rnwContext_.getRnwOptionsStart(
input_.getText(),
input_.getSelection().getStart().getPosition());
if (optionsStart < 0)
{
return false;
}
String linePart = input_.getText().substring(
optionsStart,
input_.getSelection().getStart().getPosition());
return c != ' ' || linePart.matches(".*,\\s*");
}
private static boolean canContinueCompletions(NativeEvent event)
{
if (event.getAltKey()
|| event.getCtrlKey()
|| event.getMetaKey())
{
return false ;
}
int keyCode = event.getKeyCode() ;
if (keyCode >= 'a' && keyCode <= 'z')
return true ;
else if (keyCode >= 'A' && keyCode <= 'Z')
return true ;
else if (keyCode == ' ')
return true ;
else if (KeyboardHelper.isHyphen(event))
return true ;
else if (KeyboardHelper.isUnderscore(event))
return true;
if (event.getShiftKey())
return false ;
if (keyCode >= '0' && keyCode <= '9')
return true ;
if (keyCode == 190) // period
return true ;
return false ;
}
private void invalidatePendingRequests()
{
invalidatePendingRequests(true, true);
}
private void invalidatePendingRequests(boolean flushCache,
boolean hidePopup)
{
invalidation_.invalidate();
if (hidePopup && popup_.isShowing())
{
popup_.hide();
popup_.clearHelp(false);
}
if (flushCache)
requester_.flushCache() ;
}
// Things we need to form an appropriate autocompletion:
//
// 1. The token to the left of the cursor,
// 2. The associated function call (if any -- for arguments),
// 3. The associated data for a `[` call (if any -- completions from data object),
// 4. The associated data for a `[[` call (if any -- completions from data object)
class AutocompletionContext {
// Be sure to sync these with 'SessionCodeTools.R'!
public static final int TYPE_UNKNOWN = 0;
public static final int TYPE_FUNCTION = 1;
public static final int TYPE_SINGLE_BRACKET = 2;
public static final int TYPE_DOUBLE_BRACKET = 3;
public static final int TYPE_NAMESPACE_EXPORTED = 4;
public static final int TYPE_NAMESPACE_ALL = 5;
public static final int TYPE_DOLLAR = 6;
public static final int TYPE_AT = 7;
public static final int TYPE_FILE = 8;
public static final int TYPE_CHUNK = 9;
public static final int TYPE_ROXYGEN = 10;
public static final int TYPE_HELP = 11;
public static final int TYPE_ARGUMENT = 12;
public static final int TYPE_PACKAGE = 13;
public AutocompletionContext(
String token,
List<String> assocData,
List<Integer> dataType,
List<Integer> numCommas,
String functionCallString)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = numCommas;
functionCallString_ = functionCallString;
}
public AutocompletionContext(
String token,
ArrayList<String> assocData,
ArrayList<Integer> dataType)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
String assocData,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList(assocData);
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList("");
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext()
{
token_ = "";
assocData_ = new ArrayList<String>();
dataType_ = new ArrayList<Integer>();
numCommas_ = new ArrayList<Integer>();
functionCallString_ = "";
}
public String getToken()
{
return token_;
}
public void setToken(String token)
{
this.token_ = token;
}
public List<String> getAssocData()
{
return assocData_;
}
public void setAssocData(List<String> assocData)
{
this.assocData_ = assocData;
}
public List<Integer> getDataType()
{
return dataType_;
}
public void setDataType(List<Integer> dataType)
{
this.dataType_ = dataType;
}
public List<Integer> getNumCommas()
{
return numCommas_;
}
public void setNumCommas(List<Integer> numCommas)
{
this.numCommas_ = numCommas;
}
public String getFunctionCallString()
{
return functionCallString_;
}
public void setFunctionCallString(String functionCallString)
{
this.functionCallString_ = functionCallString;
}
public void add(String assocData, Integer dataType, Integer numCommas)
{
assocData_.add(assocData);
dataType_.add(dataType);
numCommas_.add(numCommas);
}
public void add(String assocData, Integer dataType)
{
add(assocData, dataType, 0);
}
public void add(String assocData)
{
add(assocData, AutocompletionContext.TYPE_UNKNOWN, 0);
}
private String token_;
private List<String> assocData_;
private List<Integer> dataType_;
private List<Integer> numCommas_;
private String functionCallString_;
}
private boolean isLineInRoxygenComment(String line)
{
return line.matches("^\\s*#+'\\s*[^\\s].*");
}
private boolean isLineInComment(String line)
{
return StringUtil.stripBalancedQuotes(line).contains("#");
}
/**
* If false, the suggest operation was aborted
*/
private boolean beginSuggest(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
suggestTimer_.cancel();
if (!input_.isSelectionCollapsed())
return false ;
invalidatePendingRequests(flushCache, false);
InputEditorSelection selection = input_.getSelection() ;
if (selection == null)
return false;
int cursorCol = selection.getStart().getPosition();
String firstLine = input_.getText().substring(0, cursorCol);
// never autocomplete in (non-roxygen) comments, or at the start
// of roxygen comments (e.g. at "#' |")
if (isLineInComment(firstLine) && !isLineInRoxygenComment(firstLine))
return false;
// don't auto-complete with tab on lines with only whitespace,
// if the insertion character was a tab (unless the user has opted in)
if (!uiPrefs_.allowTabMultilineCompletion().getValue())
{
if (nativeEvent_ != null &&
nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB)
if (firstLine.matches("^\\s*$"))
return false;
}
AutocompletionContext context = getAutocompletionContext();
// Fix up the context token for non-file completions -- e.g. in
//
// foo<-rn
//
// we erroneously capture '-' as part of the token name. This is awkward
// but is effectively a bandaid until the autocompletion revamp.
if (context.getToken().startsWith("-"))
context.setToken(context.getToken().substring(1));
// fix up roxygen autocompletion for case where '@' is snug against
// the comment marker
if (context.getToken().equals("'@"))
context.setToken(context.getToken().substring(1));
context_ = new CompletionRequestContext(invalidation_.getInvalidationToken(),
selection,
canAutoInsert);
RInfixData infixData = RInfixData.create();
AceEditor editor = (AceEditor) docDisplay_;
if (editor != null)
{
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
TokenCursor cursor = codeModel.getTokenCursor();
if (cursor.moveToPosition(input_.getCursorPosition()))
{
String token = "";
if (cursor.hasType("identifier"))
token = cursor.currentValue();
String cursorPos = "left";
if (cursor.currentValue() == "=")
cursorPos = "right";
TokenCursor clone = cursor.cloneCursor();
if (clone.moveToPreviousToken())
if (clone.currentValue() == "=")
cursorPos = "right";
// Try to get a dplyr join completion
DplyrJoinContext joinContext =
codeModel.getDplyrJoinContextFromInfixChain(cursor);
// If that failed, try a non-infix lookup
if (joinContext == null)
{
String joinString =
getDplyrJoinString(editor, cursor);
if (!StringUtil.isNullOrEmpty(joinString))
{
requester_.getDplyrJoinCompletionsString(
token,
joinString,
cursorPos,
implicit,
context_);
return true;
}
}
else
{
requester_.getDplyrJoinCompletions(
joinContext,
implicit,
context_);
return true;
}
// Try to see if there's an object name we should use to supplement
// completions
if (cursor.moveToPosition(input_.getCursorPosition()))
infixData = codeModel.getDataFromInfixChain(cursor);
}
}
String filePath = getSourceDocumentPath();
String docId = getSourceDocumentId();
requester_.getCompletions(
context.getToken(),
context.getAssocData(),
context.getDataType(),
context.getNumCommas(),
context.getFunctionCallString(),
infixData.getDataName(),
infixData.getAdditionalArgs(),
infixData.getExcludeArgs(),
infixData.getExcludeArgsFromObject(),
filePath,
docId,
implicit,
context_);
return true ;
}
private String getDplyrJoinString(
AceEditor editor,
TokenCursor cursor)
{
while (true)
{
int commaCount = cursor.findOpeningBracketCountCommas("(", true);
if (commaCount == -1)
break;
if (!cursor.moveToPreviousToken())
return "";
if (!cursor.currentValue().matches(".*join$"))
continue;
if (commaCount < 2)
return "";
Position start = cursor.currentPosition();
if (!cursor.moveToNextToken())
return "";
if (!cursor.fwdToMatchingToken())
return "";
Position end = cursor.currentPosition();
end.setColumn(end.getColumn() + 1);
return editor.getTextForRange(Range.fromPoints(
start, end));
}
return "";
}
private void addAutocompletionContextForFile(AutocompletionContext context,
String line)
{
int index = Math.max(line.lastIndexOf('"'), line.lastIndexOf('\''));
String token = line.substring(index + 1);
context.add(token, AutocompletionContext.TYPE_FILE);
context.setToken(token);
}
private AutocompletionContext getAutocompletionContextForFileMarkdownLink(
String line)
{
int index = line.lastIndexOf('(');
String token = line.substring(index + 1);
AutocompletionContext result = new AutocompletionContext(
token,
token,
AutocompletionContext.TYPE_FILE);
// NOTE: we overload the meaning of the function call string for file
// completions, to signal whether we should generate files relative to
// the current working directory, or to the file being used for
// completions
result.setFunctionCallString("useFile");
return result;
}
private void addAutocompletionContextForNamespace(
String token,
AutocompletionContext context)
{
String[] splat = token.split(":{2,3}");
String left = "";
if (splat.length <= 0)
{
left = "";
}
else
{
left = splat[0];
}
int type = token.contains(":::") ?
AutocompletionContext.TYPE_NAMESPACE_ALL :
AutocompletionContext.TYPE_NAMESPACE_EXPORTED;
context.add(left, type);
}
private boolean addAutocompletionContextForDollar(AutocompletionContext context)
{
// Establish an evaluation context by looking backwards
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return false;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
codeModel.tokenizeUpToRow(input_.getCursorPosition().getRow());
TokenCursor cursor = codeModel.getTokenCursor();
if (!cursor.moveToPosition(input_.getCursorPosition()))
return false;
// Move back to the '$'
while (cursor.currentValue() != "$" && cursor.currentValue() != "@")
if (!cursor.moveToPreviousToken())
return false;
int type = cursor.currentValue() == "$" ?
AutocompletionContext.TYPE_DOLLAR :
AutocompletionContext.TYPE_AT;
// Put a cursor here
TokenCursor contextEndCursor = cursor.cloneCursor();
// We allow for arbitrary elements previous, so we want to get e.g.
//
// env::foo()$bar()[1]$baz
// Get the string forming the context
//
//
// If this fails, we still want to report an empty evaluation context
// (the completion is still occurring in a '$' context, so we do want
// to exclude completions from other scopes)
String data = "";
if (cursor.moveToPreviousToken() && cursor.findStartOfEvaluationContext())
{
data = editor.getTextForRange(Range.fromPoints(
cursor.currentPosition(),
contextEndCursor.currentPosition()));
}
context.add(data, type);
return true;
}
private AutocompletionContext getAutocompletionContext()
{
AutocompletionContext context = new AutocompletionContext();
String firstLine = input_.getText();
int row = input_.getCursorPosition().getRow();
// trim to cursor position
firstLine = firstLine.substring(0, input_.getCursorPosition().getColumn());
// If we're in Markdown mode and have an appropriate string, try to get
// file completions
if (DocumentMode.isCursorInMarkdownMode(docDisplay_) &&
firstLine.matches(".*\\[.*\\]\\(.*"))
return getAutocompletionContextForFileMarkdownLink(firstLine);
// Get the token at the cursor position.
String tokenRegex = ".*[^" +
RegexUtil.wordCharacter() +
"._:$@'\"`-]";
String token = firstLine.replaceAll(tokenRegex, "");
// If we're completing an object within a string, assume it's a
// file-system completion. Note that we may need other contextual information
// to decide if e.g. we only want directories.
String firstLineStripped = StringUtil.stripBalancedQuotes(
StringUtil.stripRComment(firstLine));
boolean isFileCompletion = false;
if (firstLineStripped.indexOf('\'') != -1 ||
firstLineStripped.indexOf('"') != -1)
{
isFileCompletion = true;
addAutocompletionContextForFile(context, firstLine);
}
// If this line starts with '```{', then we're completing chunk options
// pass the whole line as a token
if (firstLine.startsWith("```{") || firstLine.startsWith("<<"))
return new AutocompletionContext(firstLine, AutocompletionContext.TYPE_CHUNK);
// If this line starts with a '?', assume it's a help query
if (firstLine.matches("^\\s*[?].*"))
return new AutocompletionContext(token, AutocompletionContext.TYPE_HELP);
// escape early for roxygen
if (firstLine.matches("\\s*#+'.*"))
return new AutocompletionContext(
token, AutocompletionContext.TYPE_ROXYGEN);
// If the token has '$' or '@', add in the autocompletion context --
// note that we still need parent contexts to give more information
// about the appropriate completion
if (token.contains("$") || token.contains("@"))
addAutocompletionContextForDollar(context);
// If the token has '::' or ':::', add that context. Note that
// we still need outer contexts (so that e.g., if we try
// 'debug(stats::rnorm)' we know not to auto-insert parens)
if (token.contains("::"))
addAutocompletionContextForNamespace(token, context);
// If this is not a file completion, we need to further strip and
// then set the token. Note that the token will have already been
// set if this is a file completion.
token = token.replaceAll(".*[$@:]", "");
if (!isFileCompletion)
context.setToken(token);
// access to the R Code model
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return context;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
// We might need to grab content from further up in the document than
// the current cursor position -- so tokenize ahead.
codeModel.tokenizeUpToRow(row + 100);
// Make a token cursor and place it at the first token previous
// to the cursor.
TokenCursor tokenCursor = codeModel.getTokenCursor();
if (!tokenCursor.moveToPosition(input_.getCursorPosition()))
return context;
// Check to see if the token following the cursor is a `::` or `:::`.
// If that's the case, then we probably only want to complete package
// names.
if (tokenCursor.moveToNextToken())
{
if (tokenCursor.currentValue() == ":" ||
tokenCursor.currentValue() == "::" ||
tokenCursor.currentValue() == ":::")
{
return new AutocompletionContext(
token,
AutocompletionContext.TYPE_PACKAGE);
}
tokenCursor.moveToPreviousToken();
}
TokenCursor startCursor = tokenCursor.cloneCursor();
// Find an opening '(' or '[' -- this provides the function or object
// for completion.
int initialNumCommas = 0;
if (tokenCursor.currentValue() != "(" && tokenCursor.currentValue() != "[")
{
int commaCount = tokenCursor.findOpeningBracketCountCommas(
new String[]{ "[", "(" }, true);
// commaCount == -1 implies we failed to find an opening bracket
if (commaCount == -1)
{
commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
return context;
else
initialNumCommas = commaCount;
}
else
{
initialNumCommas = commaCount;
}
}
// Figure out whether we're looking at '(', '[', or '[[',
// and place the token cursor on the first token preceding.
TokenCursor endOfDecl = tokenCursor.cloneCursor();
int initialDataType = AutocompletionContext.TYPE_UNKNOWN;
if (tokenCursor.currentValue() == "(")
{
initialDataType = AutocompletionContext.TYPE_FUNCTION;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else if (tokenCursor.currentValue() == "[")
{
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!endOfDecl.moveToPreviousToken())
return context;
initialDataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
initialDataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
}
// Get the string marking the function or data
if (!tokenCursor.findStartOfEvaluationContext())
return context;
// Try to get the function call string -- either there's
// an associated closing paren we can use, or we should just go up
// to the current cursor position.
// First, attempt to determine where the closing paren is located. If
// this fails, we'll just use the start cursor's position (and later
// attempt to finish the expression to make it parsable)
Position endPos = startCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + startCursor.currentValue().length());
// try to look forward for closing paren
if (endOfDecl.currentValue() == "(")
{
TokenCursor closingParenCursor = endOfDecl.cloneCursor();
if (closingParenCursor.fwdToMatchingToken())
{
endPos = closingParenCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + 1);
}
}
// We can now set the function call string.
//
// We strip out the current statement under the cursor, so that
// match.call() can later properly resolve the current argument.
//
// Attempt to find the start of the current statement.
TokenCursor clone = startCursor.cloneCursor();
do
{
String value = clone.currentValue();
if (value.indexOf(",") != -1 || value.equals("("))
break;
if (clone.bwdToMatchingToken())
continue;
} while (clone.moveToPreviousToken());
Position startPosition = clone.currentPosition();
// Include the opening paren if that's what we found
if (clone.currentValue().equals("("))
startPosition.setColumn(startPosition.getColumn() + 1);
String beforeText = editor.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
startPosition));
// Now, attempt to find the end of the current statement.
// Look for the ',' or ')' that ends the statement for the
// currently active argument.
boolean lookupSucceeded = false;
while (clone.moveToNextToken())
{
String value = clone.currentValue();
if (value.indexOf(",") != -1 || value.equals(")"))
{
lookupSucceeded = true;
break;
}
// Bail if we find a closing paren (we should walk over matched
// pairs properly, so finding one implies that we have a parse error).
if (value.equals("]") || value.equals("}"))
break;
if (clone.fwdToMatchingToken())
continue;
}
String afterText = "";
if (lookupSucceeded)
{
afterText = editor.getTextForRange(Range.fromPoints(
clone.currentPosition(),
endPos));
}
context.setFunctionCallString(
(beforeText + afterText).trim());
// Try to identify whether we're producing autocompletions for
// a _named_ function argument; if so, produce completions tuned to
// that argument.
TokenCursor argsCursor = startCursor.cloneCursor();
do
{
String argsValue = argsCursor.currentValue();
// Bail if we encounter tokens that we don't expect as part
// of the current expression -- this implies we're not really
// within a named argument, although this isn't perfect.
if (argsValue.equals(",") ||
argsValue.equals("(") ||
argsValue.equals("$") ||
argsValue.equals("@") ||
argsValue.equals("::") ||
argsValue.equals(":::") ||
argsValue.equals("]") ||
argsValue.equals(")") ||
argsValue.equals("}"))
{
break;
}
// If we encounter an '=', we assume that this is
// a function argument.
if (argsValue.equals("=") && argsCursor.moveToPreviousToken())
{
if (!isFileCompletion)
context.setToken(token);
context.add(
argsCursor.currentValue(),
AutocompletionContext.TYPE_ARGUMENT,
0);
return context;
}
} while (argsCursor.moveToPreviousToken());
String initialData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
endOfDecl.currentPosition())).trim();
// And the first context
context.add(initialData, initialDataType, initialNumCommas);
// Get the rest of the single-bracket contexts for completions as well
String assocData;
int dataType;
int numCommas;
while (true)
{
int commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
break;
numCommas = commaCount;
TokenCursor declEnd = tokenCursor.cloneCursor();
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!declEnd.moveToPreviousToken())
return context;
dataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
dataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
tokenCursor.findStartOfEvaluationContext();
assocData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
declEnd.currentPosition())).trim();
context.add(assocData, dataType, numCommas);
}
return context;
}
private void showSnippetHelp(QualifiedName item,
CompletionPopupDisplay popup)
{
popup.displaySnippetHelp(
snippets_.getSnippetContents(item.name));
}
/**
* It's important that we create a new instance of this each time.
* It maintains state that is associated with a completion request.
*/
private final class CompletionRequestContext extends
ServerRequestCallback<CompletionResult>
{
public CompletionRequestContext(Invalidation.Token token,
InputEditorSelection selection,
boolean canAutoAccept)
{
invalidationToken_ = token ;
selection_ = selection ;
canAutoAccept_ = canAutoAccept;
}
public void showHelp(QualifiedName selectedItem)
{
if (selectedItem.type == RCompletionType.SNIPPET)
showSnippetHelp(selectedItem, popup_);
else
helpStrategy_.showHelp(selectedItem, popup_);
}
public void showHelpTopic()
{
QualifiedName selectedItem = popup_.getSelectedValue();
// TODO: Show help should navigate to snippet file?
if (selectedItem.type != RCompletionType.SNIPPET)
helpStrategy_.showHelpTopic(selectedItem);
}
@Override
public void onError(ServerError error)
{
if (invalidationToken_.isInvalid())
return ;
RCompletionManager.this.popup_.showErrorMessage(
error.getUserMessage(),
new PopupPositioner(input_.getCursorBounds(), popup_)) ;
}
@Override
public void onResponseReceived(CompletionResult completions)
{
if (invalidationToken_.isInvalid())
return ;
// Only display the top completions
final QualifiedName[] results =
completions.completions.toArray(new QualifiedName[0]);
if (results.length == 0)
{
popup_.clearCompletions();
boolean lastInputWasTab =
(nativeEvent_ != null && nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB);
boolean lineIsWhitespace = docDisplay_.getCurrentLine().matches("^\\s*$");
if (lastInputWasTab && lineIsWhitespace)
{
docDisplay_.insertCode("\t");
return;
}
if (canAutoAccept_)
{
popup_.showErrorMessage(
"(No matches)",
new PopupPositioner(input_.getCursorBounds(), popup_));
}
else
{
// Show an empty popup message offscreen -- this is a hack to
// ensure that we can get completion results on backspace after a
// failed completion, e.g. 'stats::rna' -> 'stats::rn'
popup_.placeOffscreen();
}
return ;
}
// If there is only one result and the name is identical to the
// current token, then implicitly accept that completion. we hide
// the popup to ensure that backspace can re-load completions from
// the cache
if (results.length == 1 &&
completions.token.equals(results[0].name.replaceAll(":*", "")))
{
// For snippets we need to apply the completion if explicitly requested
if (results[0].type == RCompletionType.SNIPPET && canAutoAccept_)
{
snippets_.applySnippet(completions.token, results[0].name);
return;
}
popup_.placeOffscreen();
return;
}
// Move range to beginning of token; we want to place the popup there.
final String token = completions.token ;
Rectangle rect = input_.getPositionBounds(
selection_.getStart().movePosition(-token.length(), true));
token_ = token;
suggestOnAccept_ = completions.suggestOnAccept;
overrideInsertParens_ = completions.dontInsertParens;
if (results.length == 1
&& canAutoAccept_
&& results[0].type != RCompletionType.DIRECTORY)
{
onSelection(results[0]);
}
else
{
popup_.showCompletionValues(
results,
new PopupPositioner(rect, popup_),
false);
}
}
private void onSelection(QualifiedName qname)
{
suggestTimer_.cancel();
final String value = qname.name ;
if (invalidationToken_.isInvalid())
return;
requester_.flushCache() ;
helpStrategy_.clearCache();
if (value == null)
{
assert false : "Selected comp value is null" ;
return ;
}
applyValue(qname);
// For in-line edits, we don't want to auto-popup after replacement
if (suggestOnAccept_ ||
(qname.name.endsWith(":") &&
docDisplay_.getCharacterAtCursor() != ':'))
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(true, true, false);
}
});
}
else
{
popup_.hide() ;
popup_.clearHelp(false);
popup_.setHelpVisible(false);
docDisplay_.setFocus(true);
}
}
// For input of the form 'something$foo' or 'something@bar', quote the
// element following '@' if it's a non-syntactic R symbol; otherwise
// return as is
private String quoteIfNotSyntacticNameCompletion(String string)
{
if (RegexUtil.isSyntacticRIdentifier(string))
return string;
else
return "`" + string + "`";
}
private void applyValueRmdOption(final String value)
{
suggestTimer_.cancel();
// If there is no token but spaces have been inserted, then compensate
// for that. This is necessary as we allow for spaces in the completion,
// and completions auto-popup after ',' so e.g. on
//
// ```{r, |}
// ^ -- automatically triggered completion
// ^ -- user inserted spaces
//
// if we accept a completion in that position, we should keep the
// spaces the user inserted. (After the user has inserted a character,
// it becomes part of the token and hence this is unnecessary.
if (token_ == "")
{
int startPos = selection_.getStart().getPosition();
String currentLine = docDisplay_.getCurrentLine();
while (startPos < currentLine.length() &&
currentLine.charAt(startPos) == ' ')
++startPos;
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(startPos, false),
input_.getSelection().getEnd()));
}
else
{
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(-token_.length(), true),
input_.getSelection().getEnd()));
}
input_.replaceSelection(value, true);
token_ = value;
selection_ = input_.getSelection();
}
private void applyValue(final QualifiedName qualifiedName)
{
String completionToken = getCurrentCompletionToken();
// Strip off the quotes for string completions.
if (completionToken.startsWith("'") || completionToken.startsWith("\""))
completionToken = completionToken.substring(1);
if (qualifiedName.source.equals("`chunk-option`"))
{
applyValueRmdOption(qualifiedName.name);
return;
}
if (qualifiedName.type == RCompletionType.SNIPPET)
{
snippets_.applySnippet(completionToken, qualifiedName.name);
return;
}
boolean insertParen =
uiPrefs_.insertParensAfterFunctionCompletion().getValue() &&
RCompletionType.isFunctionType(qualifiedName.type);
// Don't insert a paren if there is already a '(' following
// the cursor
AceEditor editor = (AceEditor) input_;
boolean textFollowingCursorIsOpenParen = false;
boolean textFollowingCursorIsClosingParen = false;
boolean textFollowingCursorIsColon = false;
if (editor != null)
{
TokenCursor cursor =
editor.getSession().getMode().getRCodeModel().getTokenCursor();
cursor.moveToPosition(editor.getCursorPosition());
if (cursor.moveToNextToken())
{
textFollowingCursorIsOpenParen =
cursor.currentValue() == "(";
textFollowingCursorIsClosingParen =
cursor.currentValue() == ")" && !cursor.bwdToMatchingToken();
textFollowingCursorIsColon =
cursor.currentValue() == ":" ||
cursor.currentValue() == "::" ||
cursor.currentValue() == ":::";
}
}
String value = qualifiedName.name;
String source = qualifiedName.source;
boolean shouldQuote = qualifiedName.shouldQuote;
// Don't insert the `::` following a package completion if there is
// already a `:` following the cursor
if (textFollowingCursorIsColon)
value = value.replaceAll(":", "");
if (qualifiedName.type == RCompletionType.DIRECTORY)
value = value + "/";
if (!RCompletionType.isFileType(qualifiedName.type))
{
if (value == ":=")
value = quoteIfNotSyntacticNameCompletion(value);
else if (!value.matches(".*[=:]\\s*$") &&
!value.matches("^\\s*([`'\"]).*\\1\\s*$") &&
source != "<file>" &&
source != "<directory>" &&
source != "`chunk-option`" &&
!value.startsWith("@") &&
!shouldQuote)
value = quoteIfNotSyntacticNameCompletion(value);
}
/* In some cases, applyValue can be called more than once
* as part of the same completion instance--specifically,
* if there's only one completion candidate and it is in
* a package. To make sure that the selection movement
* logic works the second time, we need to reset the
* selection.
*/
// There might be multiple cursors. Get the position of each cursor.
Range[] ranges = editor.getNativeSelection().getAllRanges();
// Determine the replacement value.
boolean shouldInsertParens = insertParen &&
!overrideInsertParens_ &&
!textFollowingCursorIsOpenParen;
boolean insertMatching = uiPrefs_.insertMatching().getValue();
boolean needToMoveCursorInsideParens = false;
if (shouldInsertParens)
{
// Munge the value -- determine whether we want to append '()'
// for e.g. function completions, and so on.
if (textFollowingCursorIsClosingParen || !insertMatching)
{
value = value + "(";
}
else
{
value = value + "()";
needToMoveCursorInsideParens = true;
}
}
else
{
if (shouldQuote)
value = "\"" + value + "\"";
// don't add spaces around equals if requested
final String kSpaceEquals = " = ";
if (!uiPrefs_.insertSpacesAroundEquals().getValue() &&
value.endsWith(kSpaceEquals))
{
value = value.substring(0, value.length() - kSpaceEquals.length()) + "=";
}
}
// Loop over all of the active cursors, and replace.
for (Range range : ranges)
{
// We should be typing, and so each range should just define a
// cursor position. Take those positions, construct ranges, replace
// text in those ranges, and proceed.
Position replaceEnd = range.getEnd();
Position replaceStart = Position.create(
replaceEnd.getRow(),
replaceEnd.getColumn() - completionToken.length());
editor.replaceRange(
Range.fromPoints(replaceStart, replaceEnd),
value);
}
// Set the active selection, and update the token.
token_ = value;
selection_ = input_.getSelection();
// Move the cursor(s) back inside parens if necessary.
if (needToMoveCursorInsideParens)
editor.moveCursorLeft();
if (RCompletionType.isFunctionType(qualifiedName.type))
sigTipManager_.displayToolTip(qualifiedName.name, qualifiedName.source);
}
private final Invalidation.Token invalidationToken_ ;
private InputEditorSelection selection_ ;
private final boolean canAutoAccept_;
private boolean suggestOnAccept_;
private boolean overrideInsertParens_;
}
private String getSourceDocumentPath()
{
if (rContext_ == null)
return "";
else
return StringUtil.notNull(rContext_.getPath());
}
private String getSourceDocumentId()
{
if (rContext_ != null)
return StringUtil.notNull(rContext_.getId());
else
return "";
}
public void showHelpDeferred(final CompletionRequestContext context,
final QualifiedName item,
int milliseconds)
{
if (helpRequest_ != null && helpRequest_.isRunning())
helpRequest_.cancel();
helpRequest_ = new Timer() {
@Override
public void run()
{
if (item.equals(lastSelectedItem_) && popup_.isShowing())
context.showHelp(item);
}
};
helpRequest_.schedule(milliseconds);
}
String getCurrentCompletionToken()
{
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return "";
// TODO: Better handling of completions within markdown mode, e.g.
// `r foo`
if (DocumentMode.isCursorInMarkdownMode(docDisplay_))
return token_;
Position cursorPos = editor.getCursorPosition();
Token currentToken = editor.getSession().getTokenAt(cursorPos);
if (currentToken == null)
return "";
// Exclude non-string and non-identifier tokens.
if (currentToken.hasType("operator", "comment", "numeric", "text", "punctuation"))
return "";
String tokenValue = currentToken.getValue();
String subsetted = tokenValue.substring(0, cursorPos.getColumn() - currentToken.getColumn());
return subsetted;
}
private GlobalDisplay globalDisplay_;
private FileTypeRegistry fileTypeRegistry_;
private EventBus eventBus_;
private HelpStrategy helpStrategy_;
private UIPrefs uiPrefs_;
private final CodeToolsServerOperations server_;
private final InputEditorDisplay input_ ;
private final NavigableSourceEditor navigableSourceEditor_;
private final CompletionPopupDisplay popup_ ;
private final CompletionRequester requester_ ;
private final InitCompletionFilter initFilter_ ;
// Prevents completion popup from being dismissed when you merely
// click on it to scroll.
private boolean ignoreNextInputBlur_ = false;
private String token_ ;
private final DocDisplay docDisplay_;
private final SnippetHelper snippets_;
private final boolean isConsole_;
private final Invalidation invalidation_ = new Invalidation();
private CompletionRequestContext context_ ;
private final RCompletionContext rContext_;
private final RnwCompletionContext rnwContext_;
private final SignatureToolTipManager sigTipManager_;
private NativeEvent nativeEvent_;
private QualifiedName lastSelectedItem_;
private Timer helpRequest_;
private final SuggestionTimer suggestTimer_;
private static class SuggestionTimer
{
SuggestionTimer(RCompletionManager manager, UIPrefs uiPrefs)
{
manager_ = manager;
uiPrefs_ = uiPrefs;
timer_ = new Timer()
{
@Override
public void run()
{
manager_.beginSuggest(
flushCache_,
implicit_,
canAutoInsert_);
}
};
}
public void schedule(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
flushCache_ = flushCache;
implicit_ = implicit;
canAutoInsert_ = canAutoInsert;
timer_.schedule(uiPrefs_.alwaysCompleteDelayMs().getValue());
}
public void cancel()
{
timer_.cancel();
}
private final RCompletionManager manager_;
private final UIPrefs uiPrefs_;
private final Timer timer_;
private boolean flushCache_;
private boolean implicit_;
private boolean canAutoInsert_;
}
private final HandlerRegistrations handlers_;
}
| src/gwt/src/org/rstudio/studio/client/workbench/views/console/shell/assist/RCompletionManager.java | /*
* RCompletionManager.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.console.shell.assist;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.inject.Inject;
import org.rstudio.core.client.HandlerRegistrations;
import org.rstudio.core.client.Invalidation;
import org.rstudio.core.client.Rectangle;
import org.rstudio.core.client.RegexUtil;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardHelper;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.events.SelectionCommitEvent;
import org.rstudio.core.client.events.SelectionCommitHandler;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.GlobalProgressDelayer;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations;
import org.rstudio.studio.client.common.codetools.RCompletionType;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.codesearch.model.FunctionDefinition;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.snippets.SnippetHelper;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.CompletionResult;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionRequester.QualifiedName;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorLineWithCursorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorUtil;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay;
import org.rstudio.studio.client.workbench.views.source.editors.text.NavigableSourceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.RCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeFunction;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.CodeModel;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.DplyrJoinContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.RInfixData;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Token;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.TokenCursor;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.PasteEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.r.RCompletionToolTip;
import org.rstudio.studio.client.workbench.views.source.editors.text.r.SignatureToolTipManager;
import org.rstudio.studio.client.workbench.views.source.events.CodeBrowserNavigationEvent;
import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RCompletionManager implements CompletionManager
{
// globally suppress F1 and F2 so no default browser behavior takes those
// keystrokes (e.g. Help in Chrome)
static
{
Event.addNativePreviewHandler(new NativePreviewHandler() {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
if (event.getTypeInt() == Event.ONKEYDOWN)
{
int keyCode = event.getNativeEvent().getKeyCode();
if ((keyCode == 112 || keyCode == 113) &&
KeyboardShortcut.NONE ==
KeyboardShortcut.getModifierValue(event.getNativeEvent()))
{
event.getNativeEvent().preventDefault();
}
}
}
});
}
public void onPaste(PasteEvent event)
{
popup_.hide();
}
public RCompletionManager(InputEditorDisplay input,
NavigableSourceEditor navigableSourceEditor,
CompletionPopupDisplay popup,
CodeToolsServerOperations server,
InitCompletionFilter initFilter,
RCompletionContext rContext,
RnwCompletionContext rnwContext,
DocDisplay docDisplay,
boolean isConsole)
{
RStudioGinjector.INSTANCE.injectMembers(this);
input_ = input ;
navigableSourceEditor_ = navigableSourceEditor;
popup_ = popup ;
server_ = server ;
rContext_ = rContext;
initFilter_ = initFilter ;
rnwContext_ = rnwContext;
docDisplay_ = docDisplay;
isConsole_ = isConsole;
sigTipManager_ = new SignatureToolTipManager(docDisplay_);
suggestTimer_ = new SuggestionTimer(this, uiPrefs_);
snippets_ = new SnippetHelper((AceEditor) docDisplay, getSourceDocumentPath());
requester_ = new CompletionRequester(rnwContext, navigableSourceEditor, snippets_);
handlers_ = new HandlerRegistrations();
handlers_.add(input_.addBlurHandler(new BlurHandler() {
public void onBlur(BlurEvent event)
{
if (!ignoreNextInputBlur_)
invalidatePendingRequests() ;
ignoreNextInputBlur_ = false ;
}
}));
handlers_.add(input_.addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
invalidatePendingRequests();
}
}));
handlers_.add(popup_.addSelectionCommitHandler(new SelectionCommitHandler<QualifiedName>() {
public void onSelectionCommit(SelectionCommitEvent<QualifiedName> event)
{
assert context_ != null : "onSelection called but handler is null" ;
if (context_ != null)
context_.onSelection(event.getSelectedItem()) ;
}
}));
handlers_.add(popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
public void onSelection(SelectionEvent<QualifiedName> event)
{
lastSelectedItem_ = event.getSelectedItem();
if (popup_.isHelpVisible())
context_.showHelp(lastSelectedItem_);
else
showHelpDeferred(context_, lastSelectedItem_, 600);
}
}));
handlers_.add(popup_.addMouseDownHandler(new MouseDownHandler() {
public void onMouseDown(MouseDownEvent event)
{
ignoreNextInputBlur_ = true ;
}
}));
handlers_.add(popup_.addSelectionHandler(new SelectionHandler<QualifiedName>() {
@Override
public void onSelection(SelectionEvent<QualifiedName> event)
{
docDisplay_.setPopupVisible(true);
}
}));
handlers_.add(popup_.addCloseHandler(new CloseHandler<PopupPanel>()
{
@Override
public void onClose(CloseEvent<PopupPanel> event)
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
docDisplay_.setPopupVisible(false);
}
});
}
}));
handlers_.add(popup_.addAttachHandler(new AttachEvent.Handler()
{
private boolean wasSigtipShowing_ = false;
@Override
public void onAttachOrDetach(AttachEvent event)
{
RCompletionToolTip toolTip = sigTipManager_.getToolTip();
if (event.isAttached())
{
if (toolTip != null && toolTip.isShowing())
{
wasSigtipShowing_ = true;
toolTip.setVisible(false);
}
else
{
wasSigtipShowing_ = false;
}
}
else
{
if (toolTip != null && wasSigtipShowing_)
toolTip.setVisible(true);
}
}
}));
}
@Inject
public void initialize(GlobalDisplay globalDisplay,
FileTypeRegistry fileTypeRegistry,
EventBus eventBus,
HelpStrategy helpStrategy,
UIPrefs uiPrefs)
{
globalDisplay_ = globalDisplay;
fileTypeRegistry_ = fileTypeRegistry;
eventBus_ = eventBus;
helpStrategy_ = helpStrategy;
uiPrefs_ = uiPrefs;
}
public void detach()
{
handlers_.removeHandler();
sigTipManager_.detach();
snippets_.detach();
popup_.hide();
}
public void close()
{
popup_.hide();
}
public void codeCompletion()
{
if (initFilter_ == null || initFilter_.shouldComplete(null))
beginSuggest(true, false, true);
}
public void goToHelp()
{
InputEditorLineWithCursorPosition linePos =
InputEditorUtil.getLineWithCursorPosition(input_);
server_.getHelpAtCursor(
linePos.getLine(), linePos.getPosition(),
new SimpleRequestCallback<Void>("Help"));
}
public void goToFunctionDefinition()
{
// check for a file-local definition (intra-file navigation -- using
// the active scope tree)
AceEditor editor = (AceEditor) docDisplay_;
if (editor != null)
{
TokenCursor cursor = editor.getSession().getMode().getRCodeModel().getTokenCursor();
if (cursor.moveToPosition(editor.getCursorPosition(), true))
{
// if the cursor is 'on' a left bracket, move back to the associated
// token (obstensibly a funciton name)
if (cursor.isLeftBracket())
cursor.moveToPreviousToken();
// if the previous token is an extraction operator, we shouldn't
// navigate (as this isn't the 'full' function name)
if (cursor.moveToPreviousToken())
{
if (cursor.isExtractionOperator())
return;
cursor.moveToNextToken();
}
// if this is a string, try resolving that string as a file name
if (cursor.hasType("string"))
{
String tokenValue = cursor.currentValue();
String path = tokenValue.substring(1, tokenValue.length() - 1);
FileSystemItem filePath = FileSystemItem.createFile(path);
// This will show a dialog error if no such file exists; this
// seems the most appropriate action in such a case.
fileTypeRegistry_.editFile(filePath);
}
String functionName = cursor.currentValue();
JsArray<ScopeFunction> scopes =
editor.getAllFunctionScopes();
for (int i = 0; i < scopes.length(); i++)
{
ScopeFunction scope = scopes.get(i);
if (scope.getFunctionName().equals(functionName))
{
navigableSourceEditor_.navigateToPosition(
SourcePosition.create(scope.getPreamble().getRow(),
scope.getPreamble().getColumn()),
true);
return;
}
}
}
}
// intra-file navigation failed -- hit the server and find a definition
// in the project index
// determine current line and cursor position
InputEditorLineWithCursorPosition lineWithPos =
InputEditorUtil.getLineWithCursorPosition(input_);
// delayed progress indicator
final GlobalProgressDelayer progress = new GlobalProgressDelayer(
globalDisplay_, 1000, "Searching for function definition...");
server_.getFunctionDefinition(
lineWithPos.getLine(),
lineWithPos.getPosition(),
new ServerRequestCallback<FunctionDefinition>() {
@Override
public void onResponseReceived(FunctionDefinition def)
{
// dismiss progress
progress.dismiss();
// if we got a hit
if (def.getFunctionName() != null)
{
// search locally if a function navigator was provided
if (navigableSourceEditor_ != null)
{
// try to search for the function locally
SourcePosition position =
navigableSourceEditor_.findFunctionPositionFromCursor(
def.getFunctionName());
if (position != null)
{
navigableSourceEditor_.navigateToPosition(position,
true);
return; // we're done
}
}
// if we didn't satisfy the request using a function
// navigator and we got a file back from the server then
// navigate to the file/loc
if (def.getFile() != null)
{
fileTypeRegistry_.editFile(def.getFile(),
def.getPosition());
}
// if we didn't get a file back see if we got a
// search path definition
else if (def.getSearchPathFunctionDefinition() != null)
{
eventBus_.fireEvent(new CodeBrowserNavigationEvent(
def.getSearchPathFunctionDefinition()));
}
}
}
@Override
public void onError(ServerError error)
{
progress.dismiss();
globalDisplay_.showErrorMessage("Error Searching for Function",
error.getUserMessage());
}
});
}
public boolean previewKeyDown(NativeEvent event)
{
suggestTimer_.cancel();
if (sigTipManager_.previewKeyDown(event))
return true;
/**
* KEYS THAT MATTER
*
* When popup not showing:
* Tab - attempt completion (handled in Console.java)
*
* When popup showing:
* Esc - dismiss popup
* Enter/Tab - accept current selection
* Up-arrow/Down-arrow - change selected item
* [identifier] - narrow suggestions--or if we're lame, just dismiss
* All others - dismiss popup
*/
nativeEvent_ = event;
int keycode = event.getKeyCode();
int modifier = KeyboardShortcut.getModifierValue(event);
if (!popup_.isShowing())
{
// don't allow ctrl + space for completions in Emacs mode
if (docDisplay_.isEmacsModeOn() && event.getKeyCode() == KeyCodes.KEY_SPACE)
return false;
if (CompletionUtils.isCompletionRequest(event, modifier))
{
if (initFilter_ == null || initFilter_.shouldComplete(event))
{
// If we're in markdown mode, only autocomplete in '```{r',
// '[](', or '`r |' contexts
if (DocumentMode.isCursorInMarkdownMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!(Pattern.create("^```{[rR]").test(currentLine) ||
Pattern.create(".*\\[.*\\]\\(").test(currentLine) ||
(Pattern.create(".*`r").test(currentLine) &&
StringUtil.countMatches(currentLine, '`') % 2 == 1)))
return false;
}
// If we're in tex mode, only provide completions in chunks
if (DocumentMode.isCursorInTexMode(docDisplay_))
{
String currentLine = docDisplay_.getCurrentLineUpToCursor();
if (!Pattern.create("^<<").test(currentLine))
return false;
}
return beginSuggest(true, false, true);
}
}
else if (event.getKeyCode() == KeyCodes.KEY_TAB &&
modifier == KeyboardShortcut.SHIFT)
{
return snippets_.attemptSnippetInsertion(true);
}
else if (keycode == 112 // F1
&& modifier == KeyboardShortcut.NONE)
{
goToHelp();
return true;
}
else if (keycode == 113 // F2
&& modifier == KeyboardShortcut.NONE)
{
goToFunctionDefinition();
return true;
}
}
else
{
switch (keycode)
{
// chrome on ubuntu now sends this before every keydown
// so we need to explicitly ignore it. see:
// https://github.com/ivaynberg/select2/issues/2482
case KeyCodes.KEY_WIN_IME:
return false ;
case KeyCodes.KEY_SHIFT:
case KeyCodes.KEY_CTRL:
case KeyCodes.KEY_ALT:
case KeyCodes.KEY_MAC_FF_META:
case KeyCodes.KEY_WIN_KEY_LEFT_META:
return false ; // bare modifiers should do nothing
}
if (modifier == KeyboardShortcut.CTRL)
{
switch (keycode)
{
case KeyCodes.KEY_P: return popup_.selectPrev();
case KeyCodes.KEY_N: return popup_.selectNext();
}
}
else if (modifier == KeyboardShortcut.NONE)
{
if (keycode == KeyCodes.KEY_ESCAPE)
{
invalidatePendingRequests() ;
return true ;
}
// NOTE: It is possible for the popup to still be showing, but
// showing offscreen with no values. We only grab these keys
// when the popup is both showing, and has completions.
// This functionality is here to ensure backspace works properly;
// e.g "stats::rna" -> "stats::rn" brings completions if the user
// had originally requested completions at e.g. "stats::".
if (popup_.hasCompletions() && !popup_.isOffscreen())
{
if (keycode == KeyCodes.KEY_ENTER)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
context_.onSelection(value) ;
return true ;
}
}
else if (keycode == KeyCodes.KEY_TAB)
{
QualifiedName value = popup_.getSelectedValue() ;
if (value != null)
{
if (value.type == RCompletionType.DIRECTORY)
context_.suggestOnAccept_ = true;
context_.onSelection(value);
return true;
}
}
else if (keycode == KeyCodes.KEY_UP)
return popup_.selectPrev() ;
else if (keycode == KeyCodes.KEY_DOWN)
return popup_.selectNext() ;
else if (keycode == KeyCodes.KEY_PAGEUP)
return popup_.selectPrevPage() ;
else if (keycode == KeyCodes.KEY_PAGEDOWN)
return popup_.selectNextPage() ;
else if (keycode == KeyCodes.KEY_HOME)
return popup_.selectFirst();
else if (keycode == KeyCodes.KEY_END)
return popup_.selectLast();
if (keycode == 112) // F1
{
context_.showHelpTopic() ;
return true ;
}
else if (keycode == 113) // F2
{
goToFunctionDefinition();
return true;
}
}
}
if (canContinueCompletions(event))
return false;
// if we insert a '/', we're probably forming a directory --
// pop up completions
if (keycode == 191 && modifier == KeyboardShortcut.NONE)
{
input_.insertCode("/");
return beginSuggest(true, true, false);
}
// continue showing completions on backspace
if (keycode == KeyCodes.KEY_BACKSPACE && modifier == KeyboardShortcut.NONE &&
!docDisplay_.inMultiSelectMode())
{
int cursorColumn = input_.getCursorPosition().getColumn();
String currentLine = docDisplay_.getCurrentLine();
// only suggest if the character previous to the cursor is an R identifier
// also halt suggestions if we're about to remove the only character on the line
if (cursorColumn > 0)
{
char ch = currentLine.charAt(cursorColumn - 2);
char prevCh = currentLine.charAt(cursorColumn - 3);
boolean isAcceptableCharSequence = isValidForRIdentifier(ch) ||
(ch == ':' && prevCh == ':') ||
ch == '$' ||
ch == '@' ||
ch == '/'; // for file completions
if (currentLine.length() > 0 &&
cursorColumn > 0 &&
isAcceptableCharSequence)
{
// manually remove the previous character
InputEditorSelection selection = input_.getSelection();
InputEditorPosition start = selection.getStart().movePosition(-1, true);
InputEditorPosition end = selection.getStart();
if (currentLine.charAt(cursorColumn) == ')' && currentLine.charAt(cursorColumn - 1) == '(')
{
// flush cache as old completions no longer relevant
requester_.flushCache();
end = selection.getStart().movePosition(1, true);
}
input_.setSelection(new InputEditorSelection(start, end));
input_.replaceSelection("", false);
return beginSuggest(false, false, false);
}
}
else
{
invalidatePendingRequests();
return true;
}
}
invalidatePendingRequests();
return false ;
}
return false ;
}
private boolean isValidForRIdentifier(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '.') ||
(c == '_');
}
private boolean checkCanAutoPopup(char c, int lookbackLimit)
{
if (docDisplay_.isVimModeOn() &&
!docDisplay_.isVimInInsertMode())
return false;
String currentLine = docDisplay_.getCurrentLine();
Position cursorPos = input_.getCursorPosition();
int cursorColumn = cursorPos.getColumn();
// Don't auto-popup when the cursor is within a string
if (docDisplay_.isCursorInSingleLineString())
return false;
// Don't auto-popup if there is a character following the cursor
// (this implies an in-line edit and automatic popups are likely to
// be annoying)
if (isValidForRIdentifier(docDisplay_.getCharacterAtCursor()))
return false;
boolean canAutoPopup =
(currentLine.length() > lookbackLimit - 1 && isValidForRIdentifier(c));
if (isConsole_ && !uiPrefs_.alwaysCompleteInConsole().getValue())
canAutoPopup = false;
if (canAutoPopup)
{
for (int i = 0; i < lookbackLimit; i++)
{
if (!isValidForRIdentifier(currentLine.charAt(cursorColumn - i - 1)))
{
canAutoPopup = false;
break;
}
}
}
return canAutoPopup;
}
public boolean previewKeyPress(char c)
{
suggestTimer_.cancel();
if (popup_.isShowing())
{
// If insertion of this character completes an available suggestion,
// and is not a prefix match of any other suggestion, then implicitly
// apply that.
QualifiedName selectedItem =
popup_.getSelectedValue();
// NOTE: We should strip off trailing colons so that in-line edits of
// package completions, e.g.
//
// <foo>::
//
// can also dismiss the popup on a perfect match of <foo>.
if (selectedItem != null &&
selectedItem.name.replaceAll(":", "").equals(token_ + c))
{
String fullToken = token_ + c;
// Find prefix matches -- there should only be one if we really
// want this behaviour (ie the current selection)
int prefixMatchCount = 0;
QualifiedName[] items = popup_.getItems();
for (int i = 0; i < items.length; i++)
{
if (items[i].name.startsWith(fullToken))
{
++prefixMatchCount;
if (prefixMatchCount > 1)
break;
}
}
if (prefixMatchCount == 1)
{
// We place the completion list offscreen to ensure that
// backspace events are handled later.
popup_.placeOffscreen();
return false;
}
}
if (c == ':')
{
suggestTimer_.schedule(false, true, false);
return false;
}
if (c == ' ')
return false;
// Always update the current set of completions following
// a key insertion. Defer execution so the key insertion can
// enter the document.
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(false, true, false);
}
});
return false;
}
else
{
// Bail if we're not in R mode
if (!DocumentMode.isCursorInRMode(docDisplay_))
return false;
// Bail if we're in a single-line string
if (docDisplay_.isCursorInSingleLineString())
return false;
// if there's a selection, bail
if (input_.hasSelection())
return false;
// Bail if there is an alpha-numeric character
// following the cursor
if (isValidForRIdentifier(docDisplay_.getCharacterAtCursor()))
return false;
// Perform an auto-popup if a set number of R identifier characters
// have been inserted (but only if the user has allowed it in prefs)
boolean autoPopupEnabled = uiPrefs_.codeComplete().getValue().equals(
UIPrefsAccessor.COMPLETION_ALWAYS);
if (!autoPopupEnabled)
return false;
// Immediately display completions after '$', '::', etc.
char prevChar = docDisplay_.getCurrentLine().charAt(
input_.getCursorPosition().getColumn() - 1);
if (
(c == ':' && prevChar == ':') ||
(c == '$') ||
(c == '@')
)
{
// Bail if we're in Vim but not in insert mode
if (docDisplay_.isVimModeOn() &&
!docDisplay_.isVimInInsertMode())
{
return false;
}
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(true, true, false);
}
});
return false;
}
// Check for a valid number of R identifier characters for autopopup
boolean canAutoPopup = checkCanAutoPopup(c, uiPrefs_.alwaysCompleteCharacters().getValue() - 1);
// Attempt to pop up completions immediately after a function call.
if (c == '(' && !isLineInComment(docDisplay_.getCurrentLine()))
{
String token = StringUtil.getToken(
docDisplay_.getCurrentLine(),
input_.getCursorPosition().getColumn(),
"[" + RegexUtil.wordCharacter() + "._]",
false,
true);
if (token.matches("^(library|require|requireNamespace|data)\\s*$"))
canAutoPopup = true;
sigTipManager_.resolveActiveFunctionAndDisplayToolTip();
}
if (
(canAutoPopup) ||
isSweaveCompletion(c))
{
// Delay suggestion to avoid auto-popup while the user is typing
suggestTimer_.schedule(true, true, false);
}
}
return false ;
}
@SuppressWarnings("unused")
private boolean isRoxygenTagValidHere()
{
if (input_.getText().matches("\\s*#+'.*"))
{
String linePart = input_.getText().substring(0, input_.getSelection().getStart().getPosition());
if (linePart.matches("\\s*#+'\\s*"))
return true;
}
return false;
}
private boolean isSweaveCompletion(char c)
{
if (rnwContext_ == null || (c != ',' && c != ' ' && c != '='))
return false;
int optionsStart = rnwContext_.getRnwOptionsStart(
input_.getText(),
input_.getSelection().getStart().getPosition());
if (optionsStart < 0)
{
return false;
}
String linePart = input_.getText().substring(
optionsStart,
input_.getSelection().getStart().getPosition());
return c != ' ' || linePart.matches(".*,\\s*");
}
private static boolean canContinueCompletions(NativeEvent event)
{
if (event.getAltKey()
|| event.getCtrlKey()
|| event.getMetaKey())
{
return false ;
}
int keyCode = event.getKeyCode() ;
if (keyCode >= 'a' && keyCode <= 'z')
return true ;
else if (keyCode >= 'A' && keyCode <= 'Z')
return true ;
else if (keyCode == ' ')
return true ;
else if (KeyboardHelper.isHyphen(event))
return true ;
else if (KeyboardHelper.isUnderscore(event))
return true;
if (event.getShiftKey())
return false ;
if (keyCode >= '0' && keyCode <= '9')
return true ;
if (keyCode == 190) // period
return true ;
return false ;
}
private void invalidatePendingRequests()
{
invalidatePendingRequests(true, true);
}
private void invalidatePendingRequests(boolean flushCache,
boolean hidePopup)
{
invalidation_.invalidate();
if (hidePopup && popup_.isShowing())
{
popup_.hide();
popup_.clearHelp(false);
}
if (flushCache)
requester_.flushCache() ;
}
// Things we need to form an appropriate autocompletion:
//
// 1. The token to the left of the cursor,
// 2. The associated function call (if any -- for arguments),
// 3. The associated data for a `[` call (if any -- completions from data object),
// 4. The associated data for a `[[` call (if any -- completions from data object)
class AutocompletionContext {
// Be sure to sync these with 'SessionCodeTools.R'!
public static final int TYPE_UNKNOWN = 0;
public static final int TYPE_FUNCTION = 1;
public static final int TYPE_SINGLE_BRACKET = 2;
public static final int TYPE_DOUBLE_BRACKET = 3;
public static final int TYPE_NAMESPACE_EXPORTED = 4;
public static final int TYPE_NAMESPACE_ALL = 5;
public static final int TYPE_DOLLAR = 6;
public static final int TYPE_AT = 7;
public static final int TYPE_FILE = 8;
public static final int TYPE_CHUNK = 9;
public static final int TYPE_ROXYGEN = 10;
public static final int TYPE_HELP = 11;
public static final int TYPE_ARGUMENT = 12;
public static final int TYPE_PACKAGE = 13;
public AutocompletionContext(
String token,
List<String> assocData,
List<Integer> dataType,
List<Integer> numCommas,
String functionCallString)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = numCommas;
functionCallString_ = functionCallString;
}
public AutocompletionContext(
String token,
ArrayList<String> assocData,
ArrayList<Integer> dataType)
{
token_ = token;
assocData_ = assocData;
dataType_ = dataType;
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
String assocData,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList(assocData);
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext(
String token,
int dataType)
{
token_ = token;
assocData_ = Arrays.asList("");
dataType_ = Arrays.asList(dataType);
numCommas_ = Arrays.asList(0);
functionCallString_ = "";
}
public AutocompletionContext()
{
token_ = "";
assocData_ = new ArrayList<String>();
dataType_ = new ArrayList<Integer>();
numCommas_ = new ArrayList<Integer>();
functionCallString_ = "";
}
public String getToken()
{
return token_;
}
public void setToken(String token)
{
this.token_ = token;
}
public List<String> getAssocData()
{
return assocData_;
}
public void setAssocData(List<String> assocData)
{
this.assocData_ = assocData;
}
public List<Integer> getDataType()
{
return dataType_;
}
public void setDataType(List<Integer> dataType)
{
this.dataType_ = dataType;
}
public List<Integer> getNumCommas()
{
return numCommas_;
}
public void setNumCommas(List<Integer> numCommas)
{
this.numCommas_ = numCommas;
}
public String getFunctionCallString()
{
return functionCallString_;
}
public void setFunctionCallString(String functionCallString)
{
this.functionCallString_ = functionCallString;
}
public void add(String assocData, Integer dataType, Integer numCommas)
{
assocData_.add(assocData);
dataType_.add(dataType);
numCommas_.add(numCommas);
}
public void add(String assocData, Integer dataType)
{
add(assocData, dataType, 0);
}
public void add(String assocData)
{
add(assocData, AutocompletionContext.TYPE_UNKNOWN, 0);
}
private String token_;
private List<String> assocData_;
private List<Integer> dataType_;
private List<Integer> numCommas_;
private String functionCallString_;
}
private boolean isLineInRoxygenComment(String line)
{
return line.matches("^\\s*#+'\\s*[^\\s].*");
}
private boolean isLineInComment(String line)
{
return StringUtil.stripBalancedQuotes(line).contains("#");
}
/**
* If false, the suggest operation was aborted
*/
private boolean beginSuggest(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
suggestTimer_.cancel();
if (!input_.isSelectionCollapsed())
return false ;
invalidatePendingRequests(flushCache, false);
InputEditorSelection selection = input_.getSelection() ;
if (selection == null)
return false;
int cursorCol = selection.getStart().getPosition();
String firstLine = input_.getText().substring(0, cursorCol);
// never autocomplete in (non-roxygen) comments, or at the start
// of roxygen comments (e.g. at "#' |")
if (isLineInComment(firstLine) && !isLineInRoxygenComment(firstLine))
return false;
// don't auto-complete with tab on lines with only whitespace,
// if the insertion character was a tab (unless the user has opted in)
if (!uiPrefs_.allowTabMultilineCompletion().getValue())
{
if (nativeEvent_ != null &&
nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB)
if (firstLine.matches("^\\s*$"))
return false;
}
AutocompletionContext context = getAutocompletionContext();
// Fix up the context token for non-file completions -- e.g. in
//
// foo<-rn
//
// we erroneously capture '-' as part of the token name. This is awkward
// but is effectively a bandaid until the autocompletion revamp.
if (context.getToken().startsWith("-"))
context.setToken(context.getToken().substring(1));
context_ = new CompletionRequestContext(invalidation_.getInvalidationToken(),
selection,
canAutoInsert);
RInfixData infixData = RInfixData.create();
AceEditor editor = (AceEditor) docDisplay_;
if (editor != null)
{
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
TokenCursor cursor = codeModel.getTokenCursor();
if (cursor.moveToPosition(input_.getCursorPosition()))
{
String token = "";
if (cursor.hasType("identifier"))
token = cursor.currentValue();
String cursorPos = "left";
if (cursor.currentValue() == "=")
cursorPos = "right";
TokenCursor clone = cursor.cloneCursor();
if (clone.moveToPreviousToken())
if (clone.currentValue() == "=")
cursorPos = "right";
// Try to get a dplyr join completion
DplyrJoinContext joinContext =
codeModel.getDplyrJoinContextFromInfixChain(cursor);
// If that failed, try a non-infix lookup
if (joinContext == null)
{
String joinString =
getDplyrJoinString(editor, cursor);
if (!StringUtil.isNullOrEmpty(joinString))
{
requester_.getDplyrJoinCompletionsString(
token,
joinString,
cursorPos,
implicit,
context_);
return true;
}
}
else
{
requester_.getDplyrJoinCompletions(
joinContext,
implicit,
context_);
return true;
}
// Try to see if there's an object name we should use to supplement
// completions
if (cursor.moveToPosition(input_.getCursorPosition()))
infixData = codeModel.getDataFromInfixChain(cursor);
}
}
String filePath = getSourceDocumentPath();
String docId = getSourceDocumentId();
requester_.getCompletions(
context.getToken(),
context.getAssocData(),
context.getDataType(),
context.getNumCommas(),
context.getFunctionCallString(),
infixData.getDataName(),
infixData.getAdditionalArgs(),
infixData.getExcludeArgs(),
infixData.getExcludeArgsFromObject(),
filePath,
docId,
implicit,
context_);
return true ;
}
private String getDplyrJoinString(
AceEditor editor,
TokenCursor cursor)
{
while (true)
{
int commaCount = cursor.findOpeningBracketCountCommas("(", true);
if (commaCount == -1)
break;
if (!cursor.moveToPreviousToken())
return "";
if (!cursor.currentValue().matches(".*join$"))
continue;
if (commaCount < 2)
return "";
Position start = cursor.currentPosition();
if (!cursor.moveToNextToken())
return "";
if (!cursor.fwdToMatchingToken())
return "";
Position end = cursor.currentPosition();
end.setColumn(end.getColumn() + 1);
return editor.getTextForRange(Range.fromPoints(
start, end));
}
return "";
}
private void addAutocompletionContextForFile(AutocompletionContext context,
String line)
{
int index = Math.max(line.lastIndexOf('"'), line.lastIndexOf('\''));
String token = line.substring(index + 1);
context.add(token, AutocompletionContext.TYPE_FILE);
context.setToken(token);
}
private AutocompletionContext getAutocompletionContextForFileMarkdownLink(
String line)
{
int index = line.lastIndexOf('(');
String token = line.substring(index + 1);
AutocompletionContext result = new AutocompletionContext(
token,
token,
AutocompletionContext.TYPE_FILE);
// NOTE: we overload the meaning of the function call string for file
// completions, to signal whether we should generate files relative to
// the current working directory, or to the file being used for
// completions
result.setFunctionCallString("useFile");
return result;
}
private void addAutocompletionContextForNamespace(
String token,
AutocompletionContext context)
{
String[] splat = token.split(":{2,3}");
String left = "";
if (splat.length <= 0)
{
left = "";
}
else
{
left = splat[0];
}
int type = token.contains(":::") ?
AutocompletionContext.TYPE_NAMESPACE_ALL :
AutocompletionContext.TYPE_NAMESPACE_EXPORTED;
context.add(left, type);
}
private boolean addAutocompletionContextForDollar(AutocompletionContext context)
{
// Establish an evaluation context by looking backwards
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return false;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
codeModel.tokenizeUpToRow(input_.getCursorPosition().getRow());
TokenCursor cursor = codeModel.getTokenCursor();
if (!cursor.moveToPosition(input_.getCursorPosition()))
return false;
// Move back to the '$'
while (cursor.currentValue() != "$" && cursor.currentValue() != "@")
if (!cursor.moveToPreviousToken())
return false;
int type = cursor.currentValue() == "$" ?
AutocompletionContext.TYPE_DOLLAR :
AutocompletionContext.TYPE_AT;
// Put a cursor here
TokenCursor contextEndCursor = cursor.cloneCursor();
// We allow for arbitrary elements previous, so we want to get e.g.
//
// env::foo()$bar()[1]$baz
// Get the string forming the context
//
//
// If this fails, we still want to report an empty evaluation context
// (the completion is still occurring in a '$' context, so we do want
// to exclude completions from other scopes)
String data = "";
if (cursor.moveToPreviousToken() && cursor.findStartOfEvaluationContext())
{
data = editor.getTextForRange(Range.fromPoints(
cursor.currentPosition(),
contextEndCursor.currentPosition()));
}
context.add(data, type);
return true;
}
private AutocompletionContext getAutocompletionContext()
{
AutocompletionContext context = new AutocompletionContext();
String firstLine = input_.getText();
int row = input_.getCursorPosition().getRow();
// trim to cursor position
firstLine = firstLine.substring(0, input_.getCursorPosition().getColumn());
// If we're in Markdown mode and have an appropriate string, try to get
// file completions
if (DocumentMode.isCursorInMarkdownMode(docDisplay_) &&
firstLine.matches(".*\\[.*\\]\\(.*"))
return getAutocompletionContextForFileMarkdownLink(firstLine);
// Get the token at the cursor position.
String tokenRegex = ".*[^" +
RegexUtil.wordCharacter() +
"._:$@'\"`-]";
String token = firstLine.replaceAll(tokenRegex, "");
// If we're completing an object within a string, assume it's a
// file-system completion. Note that we may need other contextual information
// to decide if e.g. we only want directories.
String firstLineStripped = StringUtil.stripBalancedQuotes(
StringUtil.stripRComment(firstLine));
boolean isFileCompletion = false;
if (firstLineStripped.indexOf('\'') != -1 ||
firstLineStripped.indexOf('"') != -1)
{
isFileCompletion = true;
addAutocompletionContextForFile(context, firstLine);
}
// If this line starts with '```{', then we're completing chunk options
// pass the whole line as a token
if (firstLine.startsWith("```{") || firstLine.startsWith("<<"))
return new AutocompletionContext(firstLine, AutocompletionContext.TYPE_CHUNK);
// If this line starts with a '?', assume it's a help query
if (firstLine.matches("^\\s*[?].*"))
return new AutocompletionContext(token, AutocompletionContext.TYPE_HELP);
// escape early for roxygen
if (firstLine.matches("\\s*#+'.*"))
return new AutocompletionContext(
token, AutocompletionContext.TYPE_ROXYGEN);
// If the token has '$' or '@', add in the autocompletion context --
// note that we still need parent contexts to give more information
// about the appropriate completion
if (token.contains("$") || token.contains("@"))
addAutocompletionContextForDollar(context);
// If the token has '::' or ':::', add that context. Note that
// we still need outer contexts (so that e.g., if we try
// 'debug(stats::rnorm)' we know not to auto-insert parens)
if (token.contains("::"))
addAutocompletionContextForNamespace(token, context);
// If this is not a file completion, we need to further strip and
// then set the token. Note that the token will have already been
// set if this is a file completion.
token = token.replaceAll(".*[$@:]", "");
if (!isFileCompletion)
context.setToken(token);
// access to the R Code model
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return context;
CodeModel codeModel = editor.getSession().getMode().getRCodeModel();
// We might need to grab content from further up in the document than
// the current cursor position -- so tokenize ahead.
codeModel.tokenizeUpToRow(row + 100);
// Make a token cursor and place it at the first token previous
// to the cursor.
TokenCursor tokenCursor = codeModel.getTokenCursor();
if (!tokenCursor.moveToPosition(input_.getCursorPosition()))
return context;
// Check to see if the token following the cursor is a `::` or `:::`.
// If that's the case, then we probably only want to complete package
// names.
if (tokenCursor.moveToNextToken())
{
if (tokenCursor.currentValue() == ":" ||
tokenCursor.currentValue() == "::" ||
tokenCursor.currentValue() == ":::")
{
return new AutocompletionContext(
token,
AutocompletionContext.TYPE_PACKAGE);
}
tokenCursor.moveToPreviousToken();
}
TokenCursor startCursor = tokenCursor.cloneCursor();
// Find an opening '(' or '[' -- this provides the function or object
// for completion.
int initialNumCommas = 0;
if (tokenCursor.currentValue() != "(" && tokenCursor.currentValue() != "[")
{
int commaCount = tokenCursor.findOpeningBracketCountCommas(
new String[]{ "[", "(" }, true);
// commaCount == -1 implies we failed to find an opening bracket
if (commaCount == -1)
{
commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
return context;
else
initialNumCommas = commaCount;
}
else
{
initialNumCommas = commaCount;
}
}
// Figure out whether we're looking at '(', '[', or '[[',
// and place the token cursor on the first token preceding.
TokenCursor endOfDecl = tokenCursor.cloneCursor();
int initialDataType = AutocompletionContext.TYPE_UNKNOWN;
if (tokenCursor.currentValue() == "(")
{
initialDataType = AutocompletionContext.TYPE_FUNCTION;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else if (tokenCursor.currentValue() == "[")
{
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!endOfDecl.moveToPreviousToken())
return context;
initialDataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
initialDataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
}
// Get the string marking the function or data
if (!tokenCursor.findStartOfEvaluationContext())
return context;
// Try to get the function call string -- either there's
// an associated closing paren we can use, or we should just go up
// to the current cursor position.
// First, attempt to determine where the closing paren is located. If
// this fails, we'll just use the start cursor's position (and later
// attempt to finish the expression to make it parsable)
Position endPos = startCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + startCursor.currentValue().length());
// try to look forward for closing paren
if (endOfDecl.currentValue() == "(")
{
TokenCursor closingParenCursor = endOfDecl.cloneCursor();
if (closingParenCursor.fwdToMatchingToken())
{
endPos = closingParenCursor.currentPosition();
endPos.setColumn(endPos.getColumn() + 1);
}
}
// We can now set the function call string.
//
// We strip out the current statement under the cursor, so that
// match.call() can later properly resolve the current argument.
//
// Attempt to find the start of the current statement.
TokenCursor clone = startCursor.cloneCursor();
do
{
String value = clone.currentValue();
if (value.indexOf(",") != -1 || value.equals("("))
break;
if (clone.bwdToMatchingToken())
continue;
} while (clone.moveToPreviousToken());
Position startPosition = clone.currentPosition();
// Include the opening paren if that's what we found
if (clone.currentValue().equals("("))
startPosition.setColumn(startPosition.getColumn() + 1);
String beforeText = editor.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
startPosition));
// Now, attempt to find the end of the current statement.
// Look for the ',' or ')' that ends the statement for the
// currently active argument.
boolean lookupSucceeded = false;
while (clone.moveToNextToken())
{
String value = clone.currentValue();
if (value.indexOf(",") != -1 || value.equals(")"))
{
lookupSucceeded = true;
break;
}
// Bail if we find a closing paren (we should walk over matched
// pairs properly, so finding one implies that we have a parse error).
if (value.equals("]") || value.equals("}"))
break;
if (clone.fwdToMatchingToken())
continue;
}
String afterText = "";
if (lookupSucceeded)
{
afterText = editor.getTextForRange(Range.fromPoints(
clone.currentPosition(),
endPos));
}
context.setFunctionCallString(
(beforeText + afterText).trim());
// Try to identify whether we're producing autocompletions for
// a _named_ function argument; if so, produce completions tuned to
// that argument.
TokenCursor argsCursor = startCursor.cloneCursor();
do
{
String argsValue = argsCursor.currentValue();
// Bail if we encounter tokens that we don't expect as part
// of the current expression -- this implies we're not really
// within a named argument, although this isn't perfect.
if (argsValue.equals(",") ||
argsValue.equals("(") ||
argsValue.equals("$") ||
argsValue.equals("@") ||
argsValue.equals("::") ||
argsValue.equals(":::") ||
argsValue.equals("]") ||
argsValue.equals(")") ||
argsValue.equals("}"))
{
break;
}
// If we encounter an '=', we assume that this is
// a function argument.
if (argsValue.equals("=") && argsCursor.moveToPreviousToken())
{
if (!isFileCompletion)
context.setToken(token);
context.add(
argsCursor.currentValue(),
AutocompletionContext.TYPE_ARGUMENT,
0);
return context;
}
} while (argsCursor.moveToPreviousToken());
String initialData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
endOfDecl.currentPosition())).trim();
// And the first context
context.add(initialData, initialDataType, initialNumCommas);
// Get the rest of the single-bracket contexts for completions as well
String assocData;
int dataType;
int numCommas;
while (true)
{
int commaCount = tokenCursor.findOpeningBracketCountCommas("[", false);
if (commaCount == -1)
break;
numCommas = commaCount;
TokenCursor declEnd = tokenCursor.cloneCursor();
if (!tokenCursor.moveToPreviousToken())
return context;
if (tokenCursor.currentValue() == "[")
{
if (!declEnd.moveToPreviousToken())
return context;
dataType = AutocompletionContext.TYPE_DOUBLE_BRACKET;
if (!tokenCursor.moveToPreviousToken())
return context;
}
else
{
dataType = AutocompletionContext.TYPE_SINGLE_BRACKET;
}
tokenCursor.findStartOfEvaluationContext();
assocData =
docDisplay_.getTextForRange(Range.fromPoints(
tokenCursor.currentPosition(),
declEnd.currentPosition())).trim();
context.add(assocData, dataType, numCommas);
}
return context;
}
private void showSnippetHelp(QualifiedName item,
CompletionPopupDisplay popup)
{
popup.displaySnippetHelp(
snippets_.getSnippetContents(item.name));
}
/**
* It's important that we create a new instance of this each time.
* It maintains state that is associated with a completion request.
*/
private final class CompletionRequestContext extends
ServerRequestCallback<CompletionResult>
{
public CompletionRequestContext(Invalidation.Token token,
InputEditorSelection selection,
boolean canAutoAccept)
{
invalidationToken_ = token ;
selection_ = selection ;
canAutoAccept_ = canAutoAccept;
}
public void showHelp(QualifiedName selectedItem)
{
if (selectedItem.type == RCompletionType.SNIPPET)
showSnippetHelp(selectedItem, popup_);
else
helpStrategy_.showHelp(selectedItem, popup_);
}
public void showHelpTopic()
{
QualifiedName selectedItem = popup_.getSelectedValue();
// TODO: Show help should navigate to snippet file?
if (selectedItem.type != RCompletionType.SNIPPET)
helpStrategy_.showHelpTopic(selectedItem);
}
@Override
public void onError(ServerError error)
{
if (invalidationToken_.isInvalid())
return ;
RCompletionManager.this.popup_.showErrorMessage(
error.getUserMessage(),
new PopupPositioner(input_.getCursorBounds(), popup_)) ;
}
@Override
public void onResponseReceived(CompletionResult completions)
{
if (invalidationToken_.isInvalid())
return ;
// Only display the top completions
final QualifiedName[] results =
completions.completions.toArray(new QualifiedName[0]);
if (results.length == 0)
{
popup_.clearCompletions();
boolean lastInputWasTab =
(nativeEvent_ != null && nativeEvent_.getKeyCode() == KeyCodes.KEY_TAB);
boolean lineIsWhitespace = docDisplay_.getCurrentLine().matches("^\\s*$");
if (lastInputWasTab && lineIsWhitespace)
{
docDisplay_.insertCode("\t");
return;
}
if (canAutoAccept_)
{
popup_.showErrorMessage(
"(No matches)",
new PopupPositioner(input_.getCursorBounds(), popup_));
}
else
{
// Show an empty popup message offscreen -- this is a hack to
// ensure that we can get completion results on backspace after a
// failed completion, e.g. 'stats::rna' -> 'stats::rn'
popup_.placeOffscreen();
}
return ;
}
// If there is only one result and the name is identical to the
// current token, then implicitly accept that completion. we hide
// the popup to ensure that backspace can re-load completions from
// the cache
if (results.length == 1 &&
completions.token.equals(results[0].name.replaceAll(":*", "")))
{
// For snippets we need to apply the completion if explicitly requested
if (results[0].type == RCompletionType.SNIPPET && canAutoAccept_)
{
snippets_.applySnippet(completions.token, results[0].name);
return;
}
popup_.placeOffscreen();
return;
}
// Move range to beginning of token; we want to place the popup there.
final String token = completions.token ;
Rectangle rect = input_.getPositionBounds(
selection_.getStart().movePosition(-token.length(), true));
token_ = token;
suggestOnAccept_ = completions.suggestOnAccept;
overrideInsertParens_ = completions.dontInsertParens;
if (results.length == 1
&& canAutoAccept_
&& results[0].type != RCompletionType.DIRECTORY)
{
onSelection(results[0]);
}
else
{
popup_.showCompletionValues(
results,
new PopupPositioner(rect, popup_),
false);
}
}
private void onSelection(QualifiedName qname)
{
suggestTimer_.cancel();
final String value = qname.name ;
if (invalidationToken_.isInvalid())
return;
requester_.flushCache() ;
helpStrategy_.clearCache();
if (value == null)
{
assert false : "Selected comp value is null" ;
return ;
}
applyValue(qname);
// For in-line edits, we don't want to auto-popup after replacement
if (suggestOnAccept_ ||
(qname.name.endsWith(":") &&
docDisplay_.getCharacterAtCursor() != ':'))
{
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
beginSuggest(true, true, false);
}
});
}
else
{
popup_.hide() ;
popup_.clearHelp(false);
popup_.setHelpVisible(false);
docDisplay_.setFocus(true);
}
}
// For input of the form 'something$foo' or 'something@bar', quote the
// element following '@' if it's a non-syntactic R symbol; otherwise
// return as is
private String quoteIfNotSyntacticNameCompletion(String string)
{
if (RegexUtil.isSyntacticRIdentifier(string))
return string;
else
return "`" + string + "`";
}
private void applyValueRmdOption(final String value)
{
suggestTimer_.cancel();
// If there is no token but spaces have been inserted, then compensate
// for that. This is necessary as we allow for spaces in the completion,
// and completions auto-popup after ',' so e.g. on
//
// ```{r, |}
// ^ -- automatically triggered completion
// ^ -- user inserted spaces
//
// if we accept a completion in that position, we should keep the
// spaces the user inserted. (After the user has inserted a character,
// it becomes part of the token and hence this is unnecessary.
if (token_ == "")
{
int startPos = selection_.getStart().getPosition();
String currentLine = docDisplay_.getCurrentLine();
while (startPos < currentLine.length() &&
currentLine.charAt(startPos) == ' ')
++startPos;
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(startPos, false),
input_.getSelection().getEnd()));
}
else
{
input_.setSelection(new InputEditorSelection(
selection_.getStart().movePosition(-token_.length(), true),
input_.getSelection().getEnd()));
}
input_.replaceSelection(value, true);
token_ = value;
selection_ = input_.getSelection();
}
private void applyValue(final QualifiedName qualifiedName)
{
String completionToken = getCurrentCompletionToken();
// Strip off the quotes for string completions.
if (completionToken.startsWith("'") || completionToken.startsWith("\""))
completionToken = completionToken.substring(1);
if (qualifiedName.source.equals("`chunk-option`"))
{
applyValueRmdOption(qualifiedName.name);
return;
}
if (qualifiedName.type == RCompletionType.SNIPPET)
{
snippets_.applySnippet(completionToken, qualifiedName.name);
return;
}
boolean insertParen =
uiPrefs_.insertParensAfterFunctionCompletion().getValue() &&
RCompletionType.isFunctionType(qualifiedName.type);
// Don't insert a paren if there is already a '(' following
// the cursor
AceEditor editor = (AceEditor) input_;
boolean textFollowingCursorIsOpenParen = false;
boolean textFollowingCursorIsClosingParen = false;
boolean textFollowingCursorIsColon = false;
if (editor != null)
{
TokenCursor cursor =
editor.getSession().getMode().getRCodeModel().getTokenCursor();
cursor.moveToPosition(editor.getCursorPosition());
if (cursor.moveToNextToken())
{
textFollowingCursorIsOpenParen =
cursor.currentValue() == "(";
textFollowingCursorIsClosingParen =
cursor.currentValue() == ")" && !cursor.bwdToMatchingToken();
textFollowingCursorIsColon =
cursor.currentValue() == ":" ||
cursor.currentValue() == "::" ||
cursor.currentValue() == ":::";
}
}
String value = qualifiedName.name;
String source = qualifiedName.source;
boolean shouldQuote = qualifiedName.shouldQuote;
// Don't insert the `::` following a package completion if there is
// already a `:` following the cursor
if (textFollowingCursorIsColon)
value = value.replaceAll(":", "");
if (qualifiedName.type == RCompletionType.DIRECTORY)
value = value + "/";
if (!RCompletionType.isFileType(qualifiedName.type))
{
if (value == ":=")
value = quoteIfNotSyntacticNameCompletion(value);
else if (!value.matches(".*[=:]\\s*$") &&
!value.matches("^\\s*([`'\"]).*\\1\\s*$") &&
source != "<file>" &&
source != "<directory>" &&
source != "`chunk-option`" &&
!value.startsWith("@") &&
!shouldQuote)
value = quoteIfNotSyntacticNameCompletion(value);
}
/* In some cases, applyValue can be called more than once
* as part of the same completion instance--specifically,
* if there's only one completion candidate and it is in
* a package. To make sure that the selection movement
* logic works the second time, we need to reset the
* selection.
*/
// There might be multiple cursors. Get the position of each cursor.
Range[] ranges = editor.getNativeSelection().getAllRanges();
// Determine the replacement value.
boolean shouldInsertParens = insertParen &&
!overrideInsertParens_ &&
!textFollowingCursorIsOpenParen;
boolean insertMatching = uiPrefs_.insertMatching().getValue();
boolean needToMoveCursorInsideParens = false;
if (shouldInsertParens)
{
// Munge the value -- determine whether we want to append '()'
// for e.g. function completions, and so on.
if (textFollowingCursorIsClosingParen || !insertMatching)
{
value = value + "(";
}
else
{
value = value + "()";
needToMoveCursorInsideParens = true;
}
}
else
{
if (shouldQuote)
value = "\"" + value + "\"";
// don't add spaces around equals if requested
final String kSpaceEquals = " = ";
if (!uiPrefs_.insertSpacesAroundEquals().getValue() &&
value.endsWith(kSpaceEquals))
{
value = value.substring(0, value.length() - kSpaceEquals.length()) + "=";
}
}
// Loop over all of the active cursors, and replace.
for (Range range : ranges)
{
// We should be typing, and so each range should just define a
// cursor position. Take those positions, construct ranges, replace
// text in those ranges, and proceed.
Position replaceEnd = range.getEnd();
Position replaceStart = Position.create(
replaceEnd.getRow(),
replaceEnd.getColumn() - completionToken.length());
editor.replaceRange(
Range.fromPoints(replaceStart, replaceEnd),
value);
}
// Set the active selection, and update the token.
token_ = value;
selection_ = input_.getSelection();
// Move the cursor(s) back inside parens if necessary.
if (needToMoveCursorInsideParens)
editor.moveCursorLeft();
if (RCompletionType.isFunctionType(qualifiedName.type))
sigTipManager_.displayToolTip(qualifiedName.name, qualifiedName.source);
}
private final Invalidation.Token invalidationToken_ ;
private InputEditorSelection selection_ ;
private final boolean canAutoAccept_;
private boolean suggestOnAccept_;
private boolean overrideInsertParens_;
}
private String getSourceDocumentPath()
{
if (rContext_ == null)
return "";
else
return StringUtil.notNull(rContext_.getPath());
}
private String getSourceDocumentId()
{
if (rContext_ != null)
return StringUtil.notNull(rContext_.getId());
else
return "";
}
public void showHelpDeferred(final CompletionRequestContext context,
final QualifiedName item,
int milliseconds)
{
if (helpRequest_ != null && helpRequest_.isRunning())
helpRequest_.cancel();
helpRequest_ = new Timer() {
@Override
public void run()
{
if (item.equals(lastSelectedItem_) && popup_.isShowing())
context.showHelp(item);
}
};
helpRequest_.schedule(milliseconds);
}
String getCurrentCompletionToken()
{
AceEditor editor = (AceEditor) docDisplay_;
if (editor == null)
return "";
// TODO: Better handling of completions within markdown mode, e.g.
// `r foo`
if (DocumentMode.isCursorInMarkdownMode(docDisplay_))
return token_;
Position cursorPos = editor.getCursorPosition();
Token currentToken = editor.getSession().getTokenAt(cursorPos);
if (currentToken == null)
return "";
// Exclude non-string and non-identifier tokens.
if (currentToken.hasType("operator", "comment", "numeric", "text", "punctuation"))
return "";
String tokenValue = currentToken.getValue();
String subsetted = tokenValue.substring(0, cursorPos.getColumn() - currentToken.getColumn());
return subsetted;
}
private GlobalDisplay globalDisplay_;
private FileTypeRegistry fileTypeRegistry_;
private EventBus eventBus_;
private HelpStrategy helpStrategy_;
private UIPrefs uiPrefs_;
private final CodeToolsServerOperations server_;
private final InputEditorDisplay input_ ;
private final NavigableSourceEditor navigableSourceEditor_;
private final CompletionPopupDisplay popup_ ;
private final CompletionRequester requester_ ;
private final InitCompletionFilter initFilter_ ;
// Prevents completion popup from being dismissed when you merely
// click on it to scroll.
private boolean ignoreNextInputBlur_ = false;
private String token_ ;
private final DocDisplay docDisplay_;
private final SnippetHelper snippets_;
private final boolean isConsole_;
private final Invalidation invalidation_ = new Invalidation();
private CompletionRequestContext context_ ;
private final RCompletionContext rContext_;
private final RnwCompletionContext rnwContext_;
private final SignatureToolTipManager sigTipManager_;
private NativeEvent nativeEvent_;
private QualifiedName lastSelectedItem_;
private Timer helpRequest_;
private final SuggestionTimer suggestTimer_;
private static class SuggestionTimer
{
SuggestionTimer(RCompletionManager manager, UIPrefs uiPrefs)
{
manager_ = manager;
uiPrefs_ = uiPrefs;
timer_ = new Timer()
{
@Override
public void run()
{
manager_.beginSuggest(
flushCache_,
implicit_,
canAutoInsert_);
}
};
}
public void schedule(boolean flushCache,
boolean implicit,
boolean canAutoInsert)
{
flushCache_ = flushCache;
implicit_ = implicit;
canAutoInsert_ = canAutoInsert;
timer_.schedule(uiPrefs_.alwaysCompleteDelayMs().getValue());
}
public void cancel()
{
timer_.cancel();
}
private final RCompletionManager manager_;
private final UIPrefs uiPrefs_;
private final Timer timer_;
private boolean flushCache_;
private boolean implicit_;
private boolean canAutoInsert_;
}
private final HandlerRegistrations handlers_;
}
| bandaid for roxygen autocompletion case
| src/gwt/src/org/rstudio/studio/client/workbench/views/console/shell/assist/RCompletionManager.java | bandaid for roxygen autocompletion case | <ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/console/shell/assist/RCompletionManager.java
<ide> if (context.getToken().startsWith("-"))
<ide> context.setToken(context.getToken().substring(1));
<ide>
<add> // fix up roxygen autocompletion for case where '@' is snug against
<add> // the comment marker
<add> if (context.getToken().equals("'@"))
<add> context.setToken(context.getToken().substring(1));
<add>
<ide> context_ = new CompletionRequestContext(invalidation_.getInvalidationToken(),
<ide> selection,
<ide> canAutoInsert); |
|
Java | apache-2.0 | 9a708d9a9ef8e5975a668f272b0f7f51b339d360 | 0 | sitb-software/ReactNativeComponents,sitb-software/ReactNativeComponents,sitb-software/react-native-components,sitb-software/react-native-components | package software.sitb.react.media;
import android.content.Intent;
import android.provider.MediaStore;
import android.util.Log;
import com.facebook.react.bridge.*;
import software.sitb.react.DefaultReactContextBaseJavaModule;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import static android.app.Activity.RESULT_OK;
/**
* @author 田尘殇Sean [email protected]
*/
public class MediaManager extends DefaultReactContextBaseJavaModule {
private static final String TAG = "MediaManager";
private static final int OPEN_IMAGE_LIBRARY_REQUEST_CODE = 777_0;
private static final int OPEN_CAMERA_REQUEST_CODE = 777_1;
private ReactApplicationContext reactContext;
private ActivityEventListener openImageListener;
private ActivityEventListener openCameraListener;
public MediaManager(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "SitbRCTMediaManager";
}
@Nullable
@Override
public Map<String, Object> getConstants() {
HashMap<String, Object> sourceType = new HashMap<>();
sourceType.put("photoLibrary", 0);
sourceType.put("savedPhotosAlbum", 1);
HashMap<String, Object> mediaType = new HashMap<>();
mediaType.put("Image", 0);
mediaType.put("Video", 1);
HashMap<String, Object> constants = new HashMap<>();
constants.put("sourceType", sourceType);
constants.put("mediaType", mediaType);
return constants;
}
@ReactMethod
public void launchImageLibrary(final ReadableMap options, final Promise promise) {
openImageListener = new ActivityEventListener() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (OPEN_IMAGE_LIBRARY_REQUEST_CODE == requestCode) {
if (resultCode == RESULT_OK) {
Log.d(TAG, "处理成功");
WritableMap response = new WritableNativeMap();
response.putString("path", data.getData().toString());
promise.resolve(response);
} else {
Log.d(TAG, "取消");
promise.reject("CANCEL", "用户取消");
}
reactContext.removeActivityEventListener(openImageListener);
}
}
};
this.reactContext.addActivityEventListener(openImageListener);
// 打开相册
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
this.reactContext.startActivityForResult(intent, OPEN_IMAGE_LIBRARY_REQUEST_CODE, null);
}
@ReactMethod
public void launchCamera(final ReadableMap options, final Promise promise) {
openCameraListener = new ActivityEventListener() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (OPEN_CAMERA_REQUEST_CODE == requestCode) {
if (RESULT_OK == resultCode) {
Log.d(TAG, "拍照成功");
String path = data.getData().toString();
WritableMap response = new WritableNativeMap();
response.putString("path", data.getData().toString());
promise.resolve(response);
} else {
Log.d(TAG, "拍照取消");
promise.reject("CANCEL", "用户取消");
}
reactContext.removeActivityEventListener(openCameraListener);
}
}
};
this.reactContext.addActivityEventListener(openCameraListener);
// 打开相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
this.reactContext.startActivityForResult(intent, OPEN_CAMERA_REQUEST_CODE, null);
}
}
| android/src/main/java/software/sitb/react/media/MediaManager.java | package software.sitb.react.media;
import android.content.Intent;
import android.provider.MediaStore;
import android.util.Log;
import com.facebook.react.bridge.*;
import software.sitb.react.DefaultReactContextBaseJavaModule;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import static android.app.Activity.RESULT_OK;
/**
* @author 田尘殇Sean [email protected]
*/
public class MediaManager extends DefaultReactContextBaseJavaModule {
private static final String TAG = "MediaManager";
private static final int OPEN_IMAGE_LIBRARY_REQUEST_CODE = 777_0;
private static final int OPEN_CAMERA_REQUEST_CODE = 777_1;
private ReactApplicationContext reactContext;
private ActivityEventListener openImageListener;
private ActivityEventListener openCameraListener;
public MediaManager(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "SitbRCTMediaManager";
}
@Nullable
@Override
public Map<String, Object> getConstants() {
HashMap<String, Object> sourceType = new HashMap<>();
sourceType.put("photoLibrary", 0);
sourceType.put("savedPhotosAlbum", 1);
HashMap<String, Object> mediaType = new HashMap<>();
mediaType.put("Image", 0);
mediaType.put("Video", 1);
HashMap<String, Object> constants = new HashMap<>();
constants.put("sourceType", sourceType);
constants.put("mediaType", mediaType);
return constants;
}
@ReactMethod
public void launchImageLibrary(final ReadableMap options, final Promise promise) {
openImageListener = new ActivityEventListener() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (OPEN_IMAGE_LIBRARY_REQUEST_CODE == requestCode) {
if (resultCode == RESULT_OK) {
Log.d(TAG, "处理成功");
WritableMap response = new WritableNativeMap();
response.putString("path", data.getData().toString());
promise.resolve(response);
} else {
Log.d(TAG, "取消");
promise.reject("CANCEL", "用户取消");
}
reactContext.removeActivityEventListener(openImageListener);
}
}
};
this.reactContext.addActivityEventListener(openImageListener);
// 打开相册
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
this.reactContext.startActivityForResult(intent, OPEN_IMAGE_LIBRARY_REQUEST_CODE, null);
}
@ReactMethod
public void launchCamera(final ReadableMap options, final Promise promise) {
openCameraListener = new ActivityEventListener() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (OPEN_CAMERA_REQUEST_CODE == requestCode) {
if (RESULT_OK == resultCode) {
Log.d(TAG, "拍照成功");
} else {
Log.d(TAG, "拍照取消");
}
reactContext.removeActivityEventListener(openCameraListener);
}
}
};
this.reactContext.addActivityEventListener(openCameraListener);
// 打开相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
this.reactContext.startActivityForResult(intent, OPEN_CAMERA_REQUEST_CODE, null);
}
}
| 拍摄照片以后返回值
| android/src/main/java/software/sitb/react/media/MediaManager.java | 拍摄照片以后返回值 | <ide><path>ndroid/src/main/java/software/sitb/react/media/MediaManager.java
<ide> if (OPEN_CAMERA_REQUEST_CODE == requestCode) {
<ide> if (RESULT_OK == resultCode) {
<ide> Log.d(TAG, "拍照成功");
<add> String path = data.getData().toString();
<add>
<add> WritableMap response = new WritableNativeMap();
<add> response.putString("path", data.getData().toString());
<add> promise.resolve(response);
<ide> } else {
<ide> Log.d(TAG, "拍照取消");
<add> promise.reject("CANCEL", "用户取消");
<ide> }
<ide> reactContext.removeActivityEventListener(openCameraListener);
<ide> } |
|
Java | lgpl-2.1 | e972ae8459d98f308020fdd62f1a8b01e1a9a7a8 | 0 | ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror | /*
$Log$
Revision 1.39 1999/03/15 15:20:33 rimassa
Added automatic sender setting when no one is specified.
Revision 1.38 1999/03/10 06:55:05 rimassa
Removed a useless import clause.
Revision 1.37 1999/03/03 16:14:19 rimassa
Used split synchronization locks for different agent parts
(suspending, waiting for events, message queue handling, ...).
Rewritten Agen Platform Life Cycle state transition methods: now each
one of them can be called both from the agent and from the Agent
Platform. Besides, each methods guards itself against being invoked
whan the agent is not in the correct state.
Revision 1.36 1999/03/01 23:23:55 rimassa
Completed Javadoc comments for Agent class.
Changed addCommListener() and removeCommListener() methods from public
to package scoped.
Revision 1.35 1999/03/01 13:09:53 rimassa
Started to write Javadoc comments for Agent class.
Revision 1.34 1999/02/25 08:12:35 rimassa
Instance variables 'myName' and 'myAddress' made private.
Made variable 'myAPState' volatile.
Made join() work without timeout, after resolving termination
problems.
Handled InterruptedIOException correctly.
Removed doFipaRequestClientNB() and made all System Agents Access API
blocking again.
Revision 1.33 1999/02/15 11:41:46 rimassa
Changed some code to use getXXX() naming methods.
Revision 1.32 1999/02/14 23:06:15 rimassa
Changed agent name handling: now getName() returns the GUID, whereas
getLocalName() yields only the agent name.
Fixed a problem with erroneous throwing of AgentDeathError during
agent destruction.
deregisterWithDF() now is again a blocking call.
Revision 1.31 1999/02/03 09:48:05 rimassa
Added a timestamp to 'failure' and 'refuse' messages.
Added a non blocking 'doFipaRequestClientNB()' method, as a temporary
hack for agent management actions, and made non blocking API for DF
registration, deregistration and modification
Revision 1.30 1998/12/07 23:42:35 rimassa
Added a getAddress() method.
Fixed by-hand parsing of message content beginning "( action ams ";
now this is embedded within a suitable AgentManagementOntology inner
class.
Revision 1.29 1998/12/01 23:35:55 rimassa
Changed a method name from 'modifyDFRegistration()' to
'modifyDFData()'.
Added a clause to insert a ':df-depth Exactly 1' search constraint
when no one is given.
Revision 1.28 1998/11/30 00:15:34 rimassa
Completed API to use FIPA system agents: now all 'refuse' and
'failure' reply messages are unmarshaled into Java exceptions.
Revision 1.27 1998/11/15 23:00:20 rimassa
Added a new private inner class, named AgentDeathError. Now when an
Agent is killed from the AgentPlatform while in waiting state, a new
AgentDeathError is raised, and the Agent thread can unblock and
terminate.
Revision 1.26 1998/11/09 00:02:25 rimassa
Modified doWait() method to avoid missing notifications.
A 'finally' clause is used to execute user-specific and JADE system
cleanup both when an agent terminates naturally and when it is killed
from RMA.
Revision 1.25 1998/11/08 23:57:50 rimassa
Added a join() method to allow AgentContainer objects to wait for all
their agents to terminate before exiting.
Revision 1.24 1998/11/05 23:31:20 rimassa
Added a protected takeDown() method as a placeholder for
agent-specific destruction actions.
Added automatic AMS deregistration on agent exit.
Revision 1.23 1998/11/01 19:11:19 rimassa
Made doWake() activate all blocked behaviours.
Revision 1.22 1998/10/31 16:27:36 rimassa
Completed doDelete() method: now an Agent can be explicitly terminated
from outside or end implicitly when one of its Behaviours calls
doDelete(). Besides, when an agent dies informs its CommListeners.
Revision 1.21 1998/10/25 23:54:30 rimassa
Added an 'implements Serializable' clause to support Agent code
downloading through RMI.
Revision 1.20 1998/10/18 15:50:08 rimassa
Method parse() is now deprecated, since ACLMessage class provides a
fromText() static method.
Removed any usage of deprecated ACLMessage default constructor.
Revision 1.19 1998/10/11 19:11:13 rimassa
Written methods to access Directory Facilitator and removed some dead
code.
Revision 1.18 1998/10/07 22:13:12 Giovanni
Added a correct prototype to DF access methods in Agent class.
Revision 1.17 1998/10/05 20:09:02 Giovanni
Fixed comment indentation.
Revision 1.16 1998/10/05 20:07:53 Giovanni
Removed System.exit() in parse() method. Now it simply prints
exception stack trace on failure.
Revision 1.15 1998/10/04 18:00:55 rimassa
Added a 'Log:' field to every source file.
revision 1.14
date: 1998/09/28 22:33:10; author: Giovanni; state: Exp; lines: +154 -40
Changed registerWithAMS() method to take advantage of new
AgentManagementOntology class.
Added public methods to access ACC, AMS and DF agents without explicit
message passing.
revision 1.13
date: 1998/09/28 00:13:41; author: rimassa; state: Exp; lines: +20 -16
Added a name for the embedded thread (same name as the agent).
Changed parameters ordering and ACL message format to comply with new
FIPA 98 AMS.
revision 1.12
date: 1998/09/23 22:59:47; author: Giovanni; state: Exp; lines: +3 -1
*** empty log message ***
revision 1.11
date: 1998/09/16 20:05:20; author: Giovanni; state: Exp; lines: +2 -2
Changed code to reflect a name change in Behaviour class from
execute() to action().
revision 1.10
date: 1998/09/09 01:37:04; author: rimassa; state: Exp; lines: +30 -10
Added support for Behaviour blocking and restarting. Now when a
behaviour blocks it is removed from the Scheduler and put into a
blocked behaviour queue (actually a Vector). When a message arrives,
postMessage() method puts all blocked behaviours back in the Scheduler
and calls restart() on each one of them.
Since when the Scheduler is empty the agent thread is blocked, the
outcome is that an agent whose behaviours are all waiting for messages
(e.g. the AMS) does not waste CPU cycles.
revision 1.9
date: 1998/09/02 23:56:02; author: rimassa; state: Exp; lines: +4 -1
Added a 'Thread.yield() call in Agent.mainLoop() to improve fairness
among different agents and thus application responsiveness.
revision 1.8
date: 1998/09/02 00:30:22; author: rimassa; state: Exp; lines: +61 -38
Now using jade.domain.AgentManagementOntology class to map AP
Life-Cycle states to their names.
AP Life-Cycle states now made public. Changed protection level for
some instance variables. Better error handling during AMS registration.
revision 1.7
date: 1998/08/30 23:57:10; author: rimassa; state: Exp; lines: +8 -1
Fixed a bug in Agent.registerWithAMS() method, where reply messages
from AMS were ignored. Now the agent receives the replies, but still
does not do a complete error checking.
revision 1.6
date: 1998/08/30 22:52:18; author: rimassa; state: Exp; lines: +71 -9
Improved Agent Platform Life-Cycle management. Added constants for
Domain Life-Cycle. Added support for IIOP address. Added automatic
registration with platform AMS.
revision 1.5
date: 1998/08/25 18:08:43; author: Giovanni; state: Exp; lines: +5 -1
Added Agent.putBack() method to insert a received message back in the
message queue.
revision 1.4
date: 1998/08/16 12:34:56; author: rimassa; state: Exp; lines: +26 -7
Communication event broadcasting is now done in a separate
broadcastEvent() method. Added a multicast send() method using
AgentGroup class.
revision 1.3
date: 1998/08/16 10:30:15; author: rimassa; state: Exp; lines: +48 -18
Added AP_DELETED state to Agent Platform life cycle, and made
Agent.mainLoop() exit only when the state is AP_DELETED.
Agent.doWake() is now synchronized, and so are all kinds of receive
operations.
Agent class now has two kinds of message receive operations: 'get
first available message' and 'get first message matching a particular
template'; both kinds come in blocking and nonblocking
flavour. Blocking receives mplementations rely on nonblocking
versions.
revision 1.2
date: 1998/08/08 17:23:31; author: rimassa; state: Exp; lines: +3 -3
Changed 'fipa' to 'jade' in package and import directives.
revision 1.1
date: 1998/08/08 14:27:50; author: rimassa; state: Exp;
Renamed 'fipa' to 'jade'.
*/
package jade.core;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Serializable;
import java.io.InterruptedIOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import jade.lang.acl.*;
import jade.domain.AgentManagementOntology;
import jade.domain.FIPAException;
/**
The <code>Agent</code> class is the common superclass for user
defined software agents. It provides methods to perform basic agent
tasks, such as:
<ul>
<li> <b> Message passing using <code>ACLMessage</code> objects,
both unicast and multicast with optional pattern matching. </b>
<li> <b> Complete Agent Platform life cycle support, including
starting, suspending and killing an agent. </b>
<li> <b> Scheduling and execution of multiple concurrent activities. </b>
<li> <b> Simplified interaction with <em>FIPA</em> system agents
for automating common agent tasks (DF registration, etc.). </b>
</ul>
Application programmers must write their own agents as
<code>Agent</code> subclasses, adding specific behaviours as needed
and exploiting <code>Agent</code> class capabilities.
*/
public class Agent implements Runnable, Serializable, CommBroadcaster {
// This inner class is used to force agent termination when a signal
// from the outside is received
private class AgentDeathError extends Error {
AgentDeathError() {
super("Agent " + Thread.currentThread().getName() + " has been terminated.");
}
}
/**
Out of band value for Agent Platform Life Cycle states.
*/
public static final int AP_MIN = 0; // Hand-made type checking
/**
Represents the <em>initiated</em> agent state.
*/
public static final int AP_INITIATED = 1;
/**
Represents the <em>active</em> agent state.
*/
public static final int AP_ACTIVE = 2;
/**
Represents the <em>suspended</em> agent state.
*/
public static final int AP_SUSPENDED = 3;
/**
Represents the <em>waiting</em> agent state.
*/
public static final int AP_WAITING = 4;
/**
Represents the <em>deleted</em> agent state.
*/
public static final int AP_DELETED = 5;
/**
Out of band value for Agent Platform Life Cycle states.
*/
public static final int AP_MAX = 6; // Hand-made type checking
/**
These constants represent the various Domain Life Cycle states
*/
/**
Out of band value for Domain Life Cycle states.
*/
public static final int D_MIN = 9; // Hand-made type checking
/**
Represents the <em>active</em> agent state.
*/
public static final int D_ACTIVE = 10;
/**
Represents the <em>suspended</em> agent state.
*/
public static final int D_SUSPENDED = 20;
/**
Represents the <em>retired</em> agent state.
*/
public static final int D_RETIRED = 30;
/**
Represents the <em>unknown</em> agent state.
*/
public static final int D_UNKNOWN = 40;
/**
Out of band value for Domain Life Cycle states.
*/
public static final int D_MAX = 41; // Hand-made type checking
protected Vector msgQueue = new Vector();
protected Vector listeners = new Vector();
private String myName = null;
private String myAddress = null;
private Object stateLock = new Object(); // Used to make state transitions atomic
private Object waitLock = new Object(); // Used for agent waiting
private Object suspendLock = new Object(); // Used for agent suspension
protected Thread myThread;
protected Scheduler myScheduler;
protected Behaviour currentBehaviour;
protected ACLMessage currentMessage;
// This variable is 'volatile' because is used as a latch to signal
// agent suspension and termination from outside world.
private volatile int myAPState;
private int myDomainState;
private Vector blockedBehaviours = new Vector();
protected ACLParser myParser = ACLParser.create();
/**
Default constructor.
*/
public Agent() {
myAPState = AP_INITIATED;
myDomainState = D_UNKNOWN;
myScheduler = new Scheduler(this);
}
/**
Method to query the agent local name.
@return A <code>String</code> containing the local agent name
(e.g. <em>peter</em>).
*/
public String getLocalName() {
return myName;
}
/**
Method to query the agent complete name (<em><b>GUID</b></em>).
@return A <code>String</code> containing the complete agent name
(e.g. <em>peter@iiop://fipa.org:50/acc</em>).
*/
public String getName() {
return myName + '@' + myAddress;
}
/**
Method to query the agent home address. This is the address of
the platform where the agent was created, and will never change
during the whole lifetime of the agent.
@return A <code>String</code> containing the agent home address
(e.g. <em>iiop://fipa.org:50/acc</em>).
*/
public String getAddress() {
return myAddress;
}
// This is used by the agent container to wait for agent termination
void join() {
try {
myThread.join();
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
}
// State transition methods for Agent Platform Life-Cycle
// FIXME: Some race conditions still present in the middle of the methods
/**
Make a state transition from <em>initiated</em> to
<em>active</em> within Agent Platform Life Cycle. This method is
called automatically by JADE on agent startup and should not be
used by application developers, unless creating some kind of
agent factory. This method starts the embedded thread of the agent.
@param name The local name of the agent.
@param platformAddress The home address of the agent.
@param myGroup The <code>ThreadGroup</code> the agent will run within.
*/
public void doStart(String name, String platformAddress, ThreadGroup myGroup) {
// Set this agent's name and address and start its embedded thread
if(myAPState == AP_INITIATED) {
myAPState = AP_ACTIVE;
myName = new String(name);
myAddress = new String(platformAddress);
myThread = new Thread(myGroup, this);
myThread.setName(myName);
myThread.start();
}
}
/**
Make a state transition from <em>active</em> to
<em>initiated</em> within Agent Platform Life Cycle. This method
is intended to support agent mobility and is called either by the
Agent Platform or by the agent itself to start migration process.
<em>This method is currently not implemented.</em>
*/
public void doMove() {
// myAPState = AP_INITIATED;
// FIXME: Should do something more
}
/**
Make a state transition from <em>active</em> to
<em>suspended</em> within Agent Platform Life Cycle. This method
can be called from the Agent Platform or from the agent iself and
stops all agent activities. Incoming messages for a suspended
agent are buffered by the Agent Platform and are delivered as
soon as the agent resumes. Calling <code>doSuspend()</code> on a
suspended or waiting agent has no effect.
@see jade.core.Agent#doActivate()
*/
public void doSuspend() {
synchronized(stateLock) {
if(myAPState == AP_ACTIVE)
myAPState = AP_SUSPENDED;
}
if(myAPState == AP_SUSPENDED) {
if(myThread.equals(Thread.currentThread())) {
waitUntilActivate();
}
}
}
/**
Make a state transition from <em>suspended</em> to
<em>active</em> within Agent Platform Life Cycle. This method is
called from the Agent Platform and resumes agent
execution. Calling <code>doActivate()</code> when the agent is
not suspended has no effect.
@see jade.core.Agent#doSuspend()
*/
public void doActivate() {
synchronized(stateLock) {
if(myAPState == AP_SUSPENDED)
myAPState = AP_ACTIVE;
}
if(myAPState == AP_ACTIVE) {
synchronized(suspendLock) {
suspendLock.notify();
}
}
}
/**
Make a state transition from <em>active</em> to <em>waiting</em>
within Agent Platform Life Cycle. This method can be called by
the Agent Platform or by the agent itself and causes the agent to
block, stopping all its activities until some event happens. A
waiting agent wakes up as soon as a message arrives or when
<code>doWake()</code> is called. Calling <code>doWait()</code> on
a suspended or waiting agent has no effect.
@see jade.core.Agent#doWake()
*/
public void doWait() {
synchronized(stateLock) {
if(myAPState == AP_ACTIVE)
myAPState = AP_WAITING;
}
if(myAPState == AP_WAITING) {
if(myThread.equals(Thread.currentThread())) {
waitUntilWake();
}
}
}
/**
Make a state transition from <em>waiting</em> to <em>active</em>
within Agent Platform Life Cycle. This method is called from
Agent Platform and resumes agent execution. Calling
<code>doWake()</code> when an agent is not waiting has no effect.
@see jade.core.Agent#doWait()
*/
public void doWake() {
synchronized(stateLock) {
if(myAPState == AP_WAITING) {
myAPState = AP_ACTIVE;
}
}
if(myAPState == AP_ACTIVE) {
activateAllBehaviours();
synchronized(waitLock) {
waitLock.notify(); // Wakes up the embedded thread
}
}
}
// This method handles both the case when the agents decides to exit
// and the case in which someone else kills him from outside.
/**
Make a state transition from <em>active</em>, <em>suspended</em>
or <em>waiting</em> to <em>deleted</em> state within Agent
Platform Life Cycle, thereby destroying the agent. This method
can be called either from the Agent Platform or from the agent
itself. Calling <code>doDelete()</code> on an already deleted
agent has no effect.
*/
public void doDelete() {
if(myAPState != AP_DELETED) {
myAPState = AP_DELETED;
if(!myThread.equals(Thread.currentThread()))
myThread.interrupt();
}
}
/**
This method is the main body of every agent. It can handle
automatically <b>AMS</b> registration and deregistration and
provides startup and cleanup hooks for application programmers to
put their specific code into.
@see jade.core.Agent#setup()
@see jade.core.Agent#takeDown()
*/
public final void run() {
try{
registerWithAMS(null,Agent.AP_ACTIVE,null,null,null);
setup();
mainLoop();
}
catch(InterruptedException ie) {
// Do Nothing, since this is a killAgent from outside
}
catch(InterruptedIOException iioe) {
// Do nothing, since this is a killAgent from outside
}
catch(Exception e) {
System.err.println("*** Uncaught Exception for agent " + myName + " ***");
e.printStackTrace();
}
catch(AgentDeathError ade) {
// Do Nothing, since this is a killAgent from outside
}
finally {
takeDown();
destroy();
}
}
/**
This protected method is an empty placeholder for application
specific startup code. Agent developers can override it to
provide necessary behaviour. When this method is called the agent
has been already registered with the Agent Platform <b>AMS</b>
and is able to send and receive messages. However, the agent
execution model is still sequential and no behaviour scheduling
is active yet.
This method can be used for ordinary startup tasks such as
<b>DF</b> registration, but is essential to add at least a
<code>Behaviour</code> object to the agent, in order for it to be
able to do anything.
@see jade.core.Agent#addBehaviour(Behaviour b)
@see jade.core.Behaviour
*/
protected void setup() {}
/**
This protected method is an empty placeholder for application
specific cleanup code. Agent developers can override it to
provide necessary behaviour. When this method is called the agent
has not deregistered itself with the Agent Platform <b>AMS</b>
and is still able to exchange messages with other
agents. However, no behaviour scheduling is active anymore and
the Agent Platform Life Cycle state is already set to
<em>deleted</em>.
This method can be used for ordinary cleanup tasks such as
<b>DF</b> deregistration, but explicit removal of all agent
behaviours is not needed.
*/
protected void takeDown() {}
private void mainLoop() throws InterruptedException, InterruptedIOException {
while(myAPState != AP_DELETED) {
// Select the next behaviour to execute
currentBehaviour = myScheduler.schedule();
// Just do it!
currentBehaviour.action();
// Check for Agent state changes
switch(myAPState) {
case AP_WAITING:
waitUntilWake();
break;
case AP_SUSPENDED:
waitUntilActivate();
break;
case AP_DELETED:
return;
}
// When it is needed no more, delete it from the behaviours queue
if(currentBehaviour.done()) {
myScheduler.remove(currentBehaviour);
currentBehaviour = null;
}
else if(!currentBehaviour.isRunnable()) {
// Remove blocked behaviours from scheduling queue and put it
// in blocked behaviours queue
myScheduler.remove(currentBehaviour);
blockedBehaviours.addElement(currentBehaviour);
currentBehaviour = null;
}
// Now give CPU control to other agents
Thread.yield();
}
}
private void waitUntilWake() {
synchronized(waitLock) {
while(myAPState == AP_WAITING) {
try {
waitLock.wait(); // Blocks on waiting state monitor
}
catch(InterruptedException ie) {
myAPState = AP_DELETED;
throw new AgentDeathError();
}
}
}
}
private void waitUntilActivate() {
synchronized(suspendLock) {
while(myAPState == AP_SUSPENDED) {
try {
suspendLock.wait(); // Blocks on suspended state monitor
}
catch(InterruptedException ie) {
myAPState = AP_DELETED;
throw new AgentDeathError();
}
}
}
}
private void destroy() {
try {
deregisterWithAMS();
}
catch(FIPAException fe) {
fe.printStackTrace();
}
notifyDestruction();
}
/**
This method adds a new behaviour to the agent. This behaviour
will be executed concurrently with all the others, using a
cooperative round robin scheduling. This method is typically
called from an agent <code>setup()</code> to fire off some
initial behaviour, but can also be used to spawn new behaviours
dynamically.
@param b The new behaviour to add to the agent.
@see jade.core.Agent#setup()
@see jade.core.Behaviour
*/
public void addBehaviour(Behaviour b) {
myScheduler.add(b);
}
/**
This method removes a given behaviour from the agent. This method
is called automatically when a top level behaviour terminates,
but can also be called from a behaviour to terminate itself or
some other behaviour.
@param b The behaviour to remove.
@see jade.core.Behaviour
*/
public void removeBehaviour(Behaviour b) {
myScheduler.remove(b);
}
/**
Send an <b>ACL</b> message to another agent. This methods sends
a message to the agent specified in <code>:receiver</code>
message field (more than one agent can be specified as message
receiver).
@param msg An ACL message object containing the actual message to
send.
@see jade.lang.acl.ACLMessage
*/
public final void send(ACLMessage msg) {
if(msg.getSource() == null)
msg.setSource(getLocalName());
CommEvent event = new CommEvent(this, msg);
broadcastEvent(event);
}
/**
Send an <b>ACL</b> message to the agent contained in a given
<code>AgentGroup</code>. This method allows simple message
multicast to be done. A similar result can be obtained putting
many agent names in <code>:receiver</code> message field; the
difference is that in that case every receiver agent can read all
other receivers' names, whereas this method hides multicasting to
receivers.
@param msg An ACL message object containing the actual message to
send.
@param g An agent group object holding all receivers names.
@see jade.lang.acl.ACLMessage
@see jade.core.AgentGroup
*/
public final void send(ACLMessage msg, AgentGroup g) {
if(msg.getSource() == null)
msg.setSource(getLocalName());
CommEvent event = new CommEvent(this, msg, g);
broadcastEvent(event);
}
/**
Receives an <b>ACL</b> message from the agent message
queue. This method is non-blocking and returns the first message
in the queue, if any. Therefore, polling and busy waiting is
required to wait for the next message sent using this method.
@return A new ACL message, or <code>null</code> if no message is
present.
@see jade.lang.acl.ACLMessage
*/
public final ACLMessage receive() {
// synchronized(waitLock) {
if(msgQueue.isEmpty()) {
return null;
}
else {
ACLMessage msg = (ACLMessage)msgQueue.firstElement();
currentMessage = msg;
msgQueue.removeElementAt(0);
return msg;
}
// }
}
/**
Receives an <b>ACL</b> message matching a given template. This
method is non-blocking and returns the first matching message in
the queue, if any. Therefore, polling and busy waiting is
required to wait for a specific kind of message using this method.
@param pattern A message template to match received messages
against.
@return A new ACL message matching the given template, or
<code>null</code> if no such message is present.
@see jade.lang.acl.ACLMessage
@see jade.lang.acl.MessageTemplate
*/
public final ACLMessage receive(MessageTemplate pattern) {
ACLMessage msg = null;
synchronized(waitLock) {
Enumeration messages = msgQueue.elements();
while(messages.hasMoreElements()) {
ACLMessage cursor = (ACLMessage)messages.nextElement();
if(pattern.match(cursor)) {
msg = cursor;
currentMessage = cursor;
msgQueue.removeElement(cursor);
break; // Exit while loop
}
}
}
return msg;
}
/**
Receives an <b>ACL</b> message from the agent message
queue. This method is blocking and suspends the whole agent until
a message is available in the queue. JADE provides a special
behaviour named <code>ReceiverBehaviour</code> to wait for a
message within a behaviour without suspending all the others and
without wasting CPU time doing busy waiting.
@return A new ACL message, blocking the agent until one is
available.
@see jade.lang.acl.ACLMessage
@see jade.core.ReceiverBehaviour
*/
public final ACLMessage blockingReceive() {
ACLMessage msg = receive();
while(msg == null) {
doWait();
msg = receive();
}
return msg;
}
/**
Receives an <b>ACL</b> message matching a given message
template. This method is blocking and suspends the whole agent
until a message is available in the queue. JADE provides a
special behaviour named <code>ReceiverBehaviour</code> to wait
for a specific kind of message within a behaviour without
suspending all the others and without wasting CPU time doing busy
waiting.
@param pattern A message template to match received messages
against.
@return A new ACL message matching the given template, blocking
until such a message is available.
@see jade.lang.acl.ACLMessage
@see jade.lang.acl.MessageTemplate
@see jade.core.ReceiverBehaviour
*/
public final ACLMessage blockingReceive(MessageTemplate pattern) {
ACLMessage msg = receive(pattern);
while(msg == null) {
doWait();
msg = receive(pattern);
}
return msg;
}
/**
Puts a received <b>ACL</b> message back into the message
queue. This method can be used from an agent behaviour when it
realizes it read a message of interest for some other
behaviour. The message is put in front of the message queue, so
it will be the first returned by a <code>receive()</code> call.
@see jade.core.Agent#receive()
*/
public final void putBack(ACLMessage msg) {
synchronized(waitLock) {
msgQueue.insertElementAt(msg,0);
}
}
/**
@deprecated Builds an ACL message from a character stream. Now
<code>ACLMessage</code> class has this capabilities itself,
through <code>fromText()</code> method.
@see jade.lang.acl.ACLMessage#fromText(Reader r)
*/
public ACLMessage parse(Reader text) {
ACLMessage msg = null;
try {
msg = myParser.parse(text);
}
catch(ParseException pe) {
pe.printStackTrace();
}
catch(TokenMgrError tme) {
tme.printStackTrace();
}
return msg;
}
private ACLMessage FipaRequestMessage(String dest, String replyString) {
ACLMessage request = new ACLMessage("request");
request.setSource(myName);
request.setDest(dest);
request.setLanguage("SL0");
request.setOntology("fipa-agent-management");
request.setProtocol("fipa-request");
request.setReplyWith(replyString);
return request;
}
private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException {
send(request);
ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString));
if(reply.getType().equalsIgnoreCase("agree")) {
reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString));
if(!reply.getType().equalsIgnoreCase("inform")) {
String content = reply.getContent();
StringReader text = new StringReader(content);
throw FIPAException.fromText(text);
}
else {
String content = reply.getContent();
return content;
}
}
else {
String content = reply.getContent();
StringReader text = new StringReader(content);
throw FIPAException.fromText(text);
}
}
/**
Register this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty. However, since <b>AMS</b> registration and
deregistration are automatic in JADE, this method should not be
used by application programmers.
Some parameters here are optional, and <code>null</code> can
safely be passed for them.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void registerWithAMS(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
String replyString = myName + "-ams-registration-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
amsd.setAddress(getAddress());
amsd.setAPState(APState);
amsd.setDelegateAgentName(delegateAgent);
amsd.setForwardAddress(forwardAddress);
amsd.setOwnership(ownership);
a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Authenticate this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty.
Some parameters here are optional, and <code>null</code> can
safely be passed for them.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
<em>This method is currently not implemented.</em>
*/
public void authenticateWithAMS(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
// FIXME: Not implemented
}
/**
Deregister this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty. However, since <b>AMS</b> registration and
deregistration are automatic in JADE, this method should not be
used by application programmers.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void deregisterWithAMS() throws FIPAException {
String replyString = myName + "-ams-deregistration-" + (new Date()).getTime();
// Get a semi-complete request message
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Modifies the data about this agent kept by Agent Platform
<b>AMS</b>. While this task can be accomplished with regular
message passing according to <b>FIPA</b> protocols, this method
is meant to ease this common duty. Some parameters here are
optional, and <code>null</code> can safely be passed for them.
When a non null parameter is passed, it replaces the value
currently stored inside <b>AMS</b> agent.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void modifyAMSRegistration(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
String replyString = myName + "-ams-modify-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
amsd.setAddress(getAddress());
amsd.setAPState(APState);
amsd.setDelegateAgentName(delegateAgent);
amsd.setForwardAddress(forwardAddress);
amsd.setOwnership(ownership);
a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
This method uses Agent Platform <b>ACC</b> agent to forward an
ACL message. Calling this method is exactly the same as calling
<code>send()</code>, only slower, since the message is first sent
to the ACC using a <code>fipa-request</code> standard protocol,
and then bounced to actual destination agent.
@param msg The ACL message to send.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the ACC to indicate some error condition.
@see jade.core.Agent#send(ACLMessage msg)
*/
public void forwardWithACC(ACLMessage msg) throws FIPAException {
String replyString = myName + "-acc-forward-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("acc", replyString);
// Build an ACC action object for the request
AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction();
a.setName(AgentManagementOntology.ACCAction.FORWARD);
a.setArg(msg);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Register this agent with a <b>DF</b> agent. While this task can
be accomplished with regular message passing according to
<b>FIPA</b> protocols, this method is meant to ease this common
duty.
@param dfName The GUID of the <b>DF</b> agent to register with.
@param dfd A <code>DFAgentDescriptor</code> object containing all
data necessary to the registration.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-register-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.REGISTER);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply, in a separate Behaviour
doFipaRequestClient(request, replyString);
}
/**
Deregister this agent from a <b>DF</b> agent. While this task can
be accomplished with regular message passing according to
<b>FIPA</b> protocols, this method is meant to ease this common
duty.
@param dfName The GUID of the <b>DF</b> agent to deregister from.
@param dfd A <code>DFAgentDescriptor</code> object containing all
data necessary to the deregistration.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-deregister-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.DEREGISTER);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Modifies data about this agent contained within a <b>DF</b>
agent. While this task can be accomplished with regular message
passing according to <b>FIPA</b> protocols, this method is
meant to ease this common duty.
@param dfName The GUID of the <b>DF</b> agent holding the data
to be changed.
@param dfd A <code>DFAgentDescriptor</code> object containing all
new data values; every non null slot value replaces the
corresponding value held inside the <b>DF</b> agent.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-modify-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.MODIFY);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Searches for data contained within a <b>DF</b> agent. While
this task can be accomplished with regular message passing
according to <b>FIPA</b> protocols, this method is meant to
ease this common duty. Nevertheless, a complete, powerful search
interface is provided; search constraints can be given and
recursive searches are possible. The only shortcoming is that
this method blocks the whole agent until the search terminates. A
special <code>SearchDFBehaviour</code> can be used to perform
<b>DF</b> searches without blocking.
@param dfName The GUID of the <b>DF</b> agent to start search from.
@param dfd A <code>DFAgentDescriptor</code> object containing
data to search for; this parameter is used as a template to match
data against.
@param constraints A <code>Vector</code> that must be filled with
all <code>Constraint</code> objects to apply to the current
search. This can be <code>null</code> if no search constraints
are required.
@return A <code>DFSearchResult</code> object containing all found
<code>DFAgentDescriptor</code> objects matching the given
descriptor, subject to given search constraints for search depth
and result size.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
@see java.util.Vector
@see jade.domain.AgentManaementOntology.Constraint
@see jade.domain.AgentManagementOntology.DFSearchResult
*/
public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException {
String replyString = myName + "-df-search-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction();
a.setName(AgentManagementOntology.DFAction.SEARCH);
a.setActor(dfName);
a.setArg(dfd);
if(constraints == null) {
AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint();
c.setName(AgentManagementOntology.Constraint.DFDEPTH);
c.setFn(AgentManagementOntology.Constraint.EXACTLY);
c.setArg(1);
a.addConstraint(c);
}
else {
// Put constraints into action
Enumeration e = constraints.elements();
while(e.hasMoreElements()) {
AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)e.nextElement();
a.addConstraint(c);
}
}
// Convert it to a String and write it in content field of the request
StringWriter textOut = new StringWriter();
a.toText(textOut);
request.setContent(textOut.toString());
// Send message and collect reply
String content = doFipaRequestClient(request, replyString);
// Extract agent descriptors from reply message
AgentManagementOntology.DFSearchResult found = null;
StringReader textIn = new StringReader(content);
try {
found = AgentManagementOntology.DFSearchResult.fromText(textIn);
}
catch(jade.domain.ParseException jdpe) {
jdpe.printStackTrace();
}
catch(jade.domain.TokenMgrError jdtme) {
jdtme.printStackTrace();
}
return found;
}
// Event handling methods
// Broadcast communication event to registered listeners
private void broadcastEvent(CommEvent event) {
Enumeration e = listeners.elements();
while(e.hasMoreElements()) {
CommListener l = (CommListener)e.nextElement();
l.CommHandle(event);
}
}
// Register a new listener
public final void addCommListener(CommListener l) {
listeners.addElement(l);
}
// Remove a registered listener
public final void removeCommListener(CommListener l) {
listeners.removeElement(l);
}
// Notify listeners of the destruction of the current agent
private void notifyDestruction() {
Enumeration e = listeners.elements();
while(e.hasMoreElements()) {
CommListener l = (CommListener)e.nextElement();
l.endSource(myName);
}
}
private void activateAllBehaviours() {
// Put all blocked behaviours back in ready queue
while(!blockedBehaviours.isEmpty()) {
Behaviour b = (Behaviour)blockedBehaviours.lastElement();
blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1);
b.restart();
myScheduler.add(b);
}
}
/**
Put a received message into the agent message queue. The mesage
is put at the back end of the queue. This method is called by
JADE runtime system when a message arrives, but can also be used
by an agent, and is just the same as sending a message to oneself
(though slightly faster).
@param msg The ACL message to put in the queue.
@see jade.core.Agent#send(ACLMessage msg)
*/
public final void postMessage (ACLMessage msg) {
synchronized(waitLock) {
if(msg != null) msgQueue.addElement(msg);
doWake();
}
}
}
| src/jade/core/Agent.java | /*
$Log$
Revision 1.38 1999/03/10 06:55:05 rimassa
Removed a useless import clause.
Revision 1.37 1999/03/03 16:14:19 rimassa
Used split synchronization locks for different agent parts
(suspending, waiting for events, message queue handling, ...).
Rewritten Agen Platform Life Cycle state transition methods: now each
one of them can be called both from the agent and from the Agent
Platform. Besides, each methods guards itself against being invoked
whan the agent is not in the correct state.
Revision 1.36 1999/03/01 23:23:55 rimassa
Completed Javadoc comments for Agent class.
Changed addCommListener() and removeCommListener() methods from public
to package scoped.
Revision 1.35 1999/03/01 13:09:53 rimassa
Started to write Javadoc comments for Agent class.
Revision 1.34 1999/02/25 08:12:35 rimassa
Instance variables 'myName' and 'myAddress' made private.
Made variable 'myAPState' volatile.
Made join() work without timeout, after resolving termination
problems.
Handled InterruptedIOException correctly.
Removed doFipaRequestClientNB() and made all System Agents Access API
blocking again.
Revision 1.33 1999/02/15 11:41:46 rimassa
Changed some code to use getXXX() naming methods.
Revision 1.32 1999/02/14 23:06:15 rimassa
Changed agent name handling: now getName() returns the GUID, whereas
getLocalName() yields only the agent name.
Fixed a problem with erroneous throwing of AgentDeathError during
agent destruction.
deregisterWithDF() now is again a blocking call.
Revision 1.31 1999/02/03 09:48:05 rimassa
Added a timestamp to 'failure' and 'refuse' messages.
Added a non blocking 'doFipaRequestClientNB()' method, as a temporary
hack for agent management actions, and made non blocking API for DF
registration, deregistration and modification
Revision 1.30 1998/12/07 23:42:35 rimassa
Added a getAddress() method.
Fixed by-hand parsing of message content beginning "( action ams ";
now this is embedded within a suitable AgentManagementOntology inner
class.
Revision 1.29 1998/12/01 23:35:55 rimassa
Changed a method name from 'modifyDFRegistration()' to
'modifyDFData()'.
Added a clause to insert a ':df-depth Exactly 1' search constraint
when no one is given.
Revision 1.28 1998/11/30 00:15:34 rimassa
Completed API to use FIPA system agents: now all 'refuse' and
'failure' reply messages are unmarshaled into Java exceptions.
Revision 1.27 1998/11/15 23:00:20 rimassa
Added a new private inner class, named AgentDeathError. Now when an
Agent is killed from the AgentPlatform while in waiting state, a new
AgentDeathError is raised, and the Agent thread can unblock and
terminate.
Revision 1.26 1998/11/09 00:02:25 rimassa
Modified doWait() method to avoid missing notifications.
A 'finally' clause is used to execute user-specific and JADE system
cleanup both when an agent terminates naturally and when it is killed
from RMA.
Revision 1.25 1998/11/08 23:57:50 rimassa
Added a join() method to allow AgentContainer objects to wait for all
their agents to terminate before exiting.
Revision 1.24 1998/11/05 23:31:20 rimassa
Added a protected takeDown() method as a placeholder for
agent-specific destruction actions.
Added automatic AMS deregistration on agent exit.
Revision 1.23 1998/11/01 19:11:19 rimassa
Made doWake() activate all blocked behaviours.
Revision 1.22 1998/10/31 16:27:36 rimassa
Completed doDelete() method: now an Agent can be explicitly terminated
from outside or end implicitly when one of its Behaviours calls
doDelete(). Besides, when an agent dies informs its CommListeners.
Revision 1.21 1998/10/25 23:54:30 rimassa
Added an 'implements Serializable' clause to support Agent code
downloading through RMI.
Revision 1.20 1998/10/18 15:50:08 rimassa
Method parse() is now deprecated, since ACLMessage class provides a
fromText() static method.
Removed any usage of deprecated ACLMessage default constructor.
Revision 1.19 1998/10/11 19:11:13 rimassa
Written methods to access Directory Facilitator and removed some dead
code.
Revision 1.18 1998/10/07 22:13:12 Giovanni
Added a correct prototype to DF access methods in Agent class.
Revision 1.17 1998/10/05 20:09:02 Giovanni
Fixed comment indentation.
Revision 1.16 1998/10/05 20:07:53 Giovanni
Removed System.exit() in parse() method. Now it simply prints
exception stack trace on failure.
Revision 1.15 1998/10/04 18:00:55 rimassa
Added a 'Log:' field to every source file.
revision 1.14
date: 1998/09/28 22:33:10; author: Giovanni; state: Exp; lines: +154 -40
Changed registerWithAMS() method to take advantage of new
AgentManagementOntology class.
Added public methods to access ACC, AMS and DF agents without explicit
message passing.
revision 1.13
date: 1998/09/28 00:13:41; author: rimassa; state: Exp; lines: +20 -16
Added a name for the embedded thread (same name as the agent).
Changed parameters ordering and ACL message format to comply with new
FIPA 98 AMS.
revision 1.12
date: 1998/09/23 22:59:47; author: Giovanni; state: Exp; lines: +3 -1
*** empty log message ***
revision 1.11
date: 1998/09/16 20:05:20; author: Giovanni; state: Exp; lines: +2 -2
Changed code to reflect a name change in Behaviour class from
execute() to action().
revision 1.10
date: 1998/09/09 01:37:04; author: rimassa; state: Exp; lines: +30 -10
Added support for Behaviour blocking and restarting. Now when a
behaviour blocks it is removed from the Scheduler and put into a
blocked behaviour queue (actually a Vector). When a message arrives,
postMessage() method puts all blocked behaviours back in the Scheduler
and calls restart() on each one of them.
Since when the Scheduler is empty the agent thread is blocked, the
outcome is that an agent whose behaviours are all waiting for messages
(e.g. the AMS) does not waste CPU cycles.
revision 1.9
date: 1998/09/02 23:56:02; author: rimassa; state: Exp; lines: +4 -1
Added a 'Thread.yield() call in Agent.mainLoop() to improve fairness
among different agents and thus application responsiveness.
revision 1.8
date: 1998/09/02 00:30:22; author: rimassa; state: Exp; lines: +61 -38
Now using jade.domain.AgentManagementOntology class to map AP
Life-Cycle states to their names.
AP Life-Cycle states now made public. Changed protection level for
some instance variables. Better error handling during AMS registration.
revision 1.7
date: 1998/08/30 23:57:10; author: rimassa; state: Exp; lines: +8 -1
Fixed a bug in Agent.registerWithAMS() method, where reply messages
from AMS were ignored. Now the agent receives the replies, but still
does not do a complete error checking.
revision 1.6
date: 1998/08/30 22:52:18; author: rimassa; state: Exp; lines: +71 -9
Improved Agent Platform Life-Cycle management. Added constants for
Domain Life-Cycle. Added support for IIOP address. Added automatic
registration with platform AMS.
revision 1.5
date: 1998/08/25 18:08:43; author: Giovanni; state: Exp; lines: +5 -1
Added Agent.putBack() method to insert a received message back in the
message queue.
revision 1.4
date: 1998/08/16 12:34:56; author: rimassa; state: Exp; lines: +26 -7
Communication event broadcasting is now done in a separate
broadcastEvent() method. Added a multicast send() method using
AgentGroup class.
revision 1.3
date: 1998/08/16 10:30:15; author: rimassa; state: Exp; lines: +48 -18
Added AP_DELETED state to Agent Platform life cycle, and made
Agent.mainLoop() exit only when the state is AP_DELETED.
Agent.doWake() is now synchronized, and so are all kinds of receive
operations.
Agent class now has two kinds of message receive operations: 'get
first available message' and 'get first message matching a particular
template'; both kinds come in blocking and nonblocking
flavour. Blocking receives mplementations rely on nonblocking
versions.
revision 1.2
date: 1998/08/08 17:23:31; author: rimassa; state: Exp; lines: +3 -3
Changed 'fipa' to 'jade' in package and import directives.
revision 1.1
date: 1998/08/08 14:27:50; author: rimassa; state: Exp;
Renamed 'fipa' to 'jade'.
*/
package jade.core;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Serializable;
import java.io.InterruptedIOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import jade.lang.acl.*;
import jade.domain.AgentManagementOntology;
import jade.domain.FIPAException;
/**
The <code>Agent</code> class is the common superclass for user
defined software agents. It provides methods to perform basic agent
tasks, such as:
<ul>
<li> <b> Message passing using <code>ACLMessage</code> objects,
both unicast and multicast with optional pattern matching. </b>
<li> <b> Complete Agent Platform life cycle support, including
starting, suspending and killing an agent. </b>
<li> <b> Scheduling and execution of multiple concurrent activities. </b>
<li> <b> Simplified interaction with <em>FIPA</em> system agents
for automating common agent tasks (DF registration, etc.). </b>
</ul>
Application programmers must write their own agents as
<code>Agent</code> subclasses, adding specific behaviours as needed
and exploiting <code>Agent</code> class capabilities.
*/
public class Agent implements Runnable, Serializable, CommBroadcaster {
// This inner class is used to force agent termination when a signal
// from the outside is received
private class AgentDeathError extends Error {
AgentDeathError() {
super("Agent " + Thread.currentThread().getName() + " has been terminated.");
}
}
/**
Out of band value for Agent Platform Life Cycle states.
*/
public static final int AP_MIN = 0; // Hand-made type checking
/**
Represents the <em>initiated</em> agent state.
*/
public static final int AP_INITIATED = 1;
/**
Represents the <em>active</em> agent state.
*/
public static final int AP_ACTIVE = 2;
/**
Represents the <em>suspended</em> agent state.
*/
public static final int AP_SUSPENDED = 3;
/**
Represents the <em>waiting</em> agent state.
*/
public static final int AP_WAITING = 4;
/**
Represents the <em>deleted</em> agent state.
*/
public static final int AP_DELETED = 5;
/**
Out of band value for Agent Platform Life Cycle states.
*/
public static final int AP_MAX = 6; // Hand-made type checking
/**
These constants represent the various Domain Life Cycle states
*/
/**
Out of band value for Domain Life Cycle states.
*/
public static final int D_MIN = 9; // Hand-made type checking
/**
Represents the <em>active</em> agent state.
*/
public static final int D_ACTIVE = 10;
/**
Represents the <em>suspended</em> agent state.
*/
public static final int D_SUSPENDED = 20;
/**
Represents the <em>retired</em> agent state.
*/
public static final int D_RETIRED = 30;
/**
Represents the <em>unknown</em> agent state.
*/
public static final int D_UNKNOWN = 40;
/**
Out of band value for Domain Life Cycle states.
*/
public static final int D_MAX = 41; // Hand-made type checking
protected Vector msgQueue = new Vector();
protected Vector listeners = new Vector();
private String myName = null;
private String myAddress = null;
private Object stateLock = new Object(); // Used to make state transitions atomic
private Object waitLock = new Object(); // Used for agent waiting
private Object suspendLock = new Object(); // Used for agent suspension
protected Thread myThread;
protected Scheduler myScheduler;
protected Behaviour currentBehaviour;
protected ACLMessage currentMessage;
// This variable is 'volatile' because is used as a latch to signal
// agent suspension and termination from outside world.
private volatile int myAPState;
private int myDomainState;
private Vector blockedBehaviours = new Vector();
protected ACLParser myParser = ACLParser.create();
/**
Default constructor.
*/
public Agent() {
myAPState = AP_INITIATED;
myDomainState = D_UNKNOWN;
myScheduler = new Scheduler(this);
}
/**
Method to query the agent local name.
@return A <code>String</code> containing the local agent name
(e.g. <em>peter</em>).
*/
public String getLocalName() {
return myName;
}
/**
Method to query the agent complete name (<em><b>GUID</b></em>).
@return A <code>String</code> containing the complete agent name
(e.g. <em>peter@iiop://fipa.org:50/acc</em>).
*/
public String getName() {
return myName + '@' + myAddress;
}
/**
Method to query the agent home address. This is the address of
the platform where the agent was created, and will never change
during the whole lifetime of the agent.
@return A <code>String</code> containing the agent home address
(e.g. <em>iiop://fipa.org:50/acc</em>).
*/
public String getAddress() {
return myAddress;
}
// This is used by the agent container to wait for agent termination
void join() {
try {
myThread.join();
}
catch(InterruptedException ie) {
ie.printStackTrace();
}
}
// State transition methods for Agent Platform Life-Cycle
// FIXME: Some race conditions still present in the middle of the methods
/**
Make a state transition from <em>initiated</em> to
<em>active</em> within Agent Platform Life Cycle. This method is
called automatically by JADE on agent startup and should not be
used by application developers, unless creating some kind of
agent factory. This method starts the embedded thread of the agent.
@param name The local name of the agent.
@param platformAddress The home address of the agent.
@param myGroup The <code>ThreadGroup</code> the agent will run within.
*/
public void doStart(String name, String platformAddress, ThreadGroup myGroup) {
// Set this agent's name and address and start its embedded thread
if(myAPState == AP_INITIATED) {
myAPState = AP_ACTIVE;
myName = new String(name);
myAddress = new String(platformAddress);
myThread = new Thread(myGroup, this);
myThread.setName(myName);
myThread.start();
}
}
/**
Make a state transition from <em>active</em> to
<em>initiated</em> within Agent Platform Life Cycle. This method
is intended to support agent mobility and is called either by the
Agent Platform or by the agent itself to start migration process.
<em>This method is currently not implemented.</em>
*/
public void doMove() {
// myAPState = AP_INITIATED;
// FIXME: Should do something more
}
/**
Make a state transition from <em>active</em> to
<em>suspended</em> within Agent Platform Life Cycle. This method
can be called from the Agent Platform or from the agent iself and
stops all agent activities. Incoming messages for a suspended
agent are buffered by the Agent Platform and are delivered as
soon as the agent resumes. Calling <code>doSuspend()</code> on a
suspended or waiting agent has no effect.
@see jade.core.Agent#doActivate()
*/
public void doSuspend() {
synchronized(stateLock) {
if(myAPState == AP_ACTIVE)
myAPState = AP_SUSPENDED;
}
if(myAPState == AP_SUSPENDED) {
if(myThread.equals(Thread.currentThread())) {
waitUntilActivate();
}
}
}
/**
Make a state transition from <em>suspended</em> to
<em>active</em> within Agent Platform Life Cycle. This method is
called from the Agent Platform and resumes agent
execution. Calling <code>doActivate()</code> when the agent is
not suspended has no effect.
@see jade.core.Agent#doSuspend()
*/
public void doActivate() {
synchronized(stateLock) {
if(myAPState == AP_SUSPENDED)
myAPState = AP_ACTIVE;
}
if(myAPState == AP_ACTIVE) {
synchronized(suspendLock) {
suspendLock.notify();
}
}
}
/**
Make a state transition from <em>active</em> to <em>waiting</em>
within Agent Platform Life Cycle. This method can be called by
the Agent Platform or by the agent itself and causes the agent to
block, stopping all its activities until some event happens. A
waiting agent wakes up as soon as a message arrives or when
<code>doWake()</code> is called. Calling <code>doWait()</code> on
a suspended or waiting agent has no effect.
@see jade.core.Agent#doWake()
*/
public void doWait() {
synchronized(stateLock) {
if(myAPState == AP_ACTIVE)
myAPState = AP_WAITING;
}
if(myAPState == AP_WAITING) {
if(myThread.equals(Thread.currentThread())) {
waitUntilWake();
}
}
}
/**
Make a state transition from <em>waiting</em> to <em>active</em>
within Agent Platform Life Cycle. This method is called from
Agent Platform and resumes agent execution. Calling
<code>doWake()</code> when an agent is not waiting has no effect.
@see jade.core.Agent#doWait()
*/
public void doWake() {
synchronized(stateLock) {
if(myAPState == AP_WAITING) {
myAPState = AP_ACTIVE;
}
}
if(myAPState == AP_ACTIVE) {
activateAllBehaviours();
synchronized(waitLock) {
waitLock.notify(); // Wakes up the embedded thread
}
}
}
// This method handles both the case when the agents decides to exit
// and the case in which someone else kills him from outside.
/**
Make a state transition from <em>active</em>, <em>suspended</em>
or <em>waiting</em> to <em>deleted</em> state within Agent
Platform Life Cycle, thereby destroying the agent. This method
can be called either from the Agent Platform or from the agent
itself. Calling <code>doDelete()</code> on an already deleted
agent has no effect.
*/
public void doDelete() {
if(myAPState != AP_DELETED) {
myAPState = AP_DELETED;
if(!myThread.equals(Thread.currentThread()))
myThread.interrupt();
}
}
/**
This method is the main body of every agent. It can handle
automatically <b>AMS</b> registration and deregistration and
provides startup and cleanup hooks for application programmers to
put their specific code into.
@see jade.core.Agent#setup()
@see jade.core.Agent#takeDown()
*/
public final void run() {
try{
registerWithAMS(null,Agent.AP_ACTIVE,null,null,null);
setup();
mainLoop();
}
catch(InterruptedException ie) {
// Do Nothing, since this is a killAgent from outside
}
catch(InterruptedIOException iioe) {
// Do nothing, since this is a killAgent from outside
}
catch(Exception e) {
System.err.println("*** Uncaught Exception for agent " + myName + " ***");
e.printStackTrace();
}
catch(AgentDeathError ade) {
// Do Nothing, since this is a killAgent from outside
}
finally {
takeDown();
destroy();
}
}
/**
This protected method is an empty placeholder for application
specific startup code. Agent developers can override it to
provide necessary behaviour. When this method is called the agent
has been already registered with the Agent Platform <b>AMS</b>
and is able to send and receive messages. However, the agent
execution model is still sequential and no behaviour scheduling
is active yet.
This method can be used for ordinary startup tasks such as
<b>DF</b> registration, but is essential to add at least a
<code>Behaviour</code> object to the agent, in order for it to be
able to do anything.
@see jade.core.Agent#addBehaviour(Behaviour b)
@see jade.core.Behaviour
*/
protected void setup() {}
/**
This protected method is an empty placeholder for application
specific cleanup code. Agent developers can override it to
provide necessary behaviour. When this method is called the agent
has not deregistered itself with the Agent Platform <b>AMS</b>
and is still able to exchange messages with other
agents. However, no behaviour scheduling is active anymore and
the Agent Platform Life Cycle state is already set to
<em>deleted</em>.
This method can be used for ordinary cleanup tasks such as
<b>DF</b> deregistration, but explicit removal of all agent
behaviours is not needed.
*/
protected void takeDown() {}
private void mainLoop() throws InterruptedException, InterruptedIOException {
while(myAPState != AP_DELETED) {
// Select the next behaviour to execute
currentBehaviour = myScheduler.schedule();
// Just do it!
currentBehaviour.action();
// Check for Agent state changes
switch(myAPState) {
case AP_WAITING:
waitUntilWake();
break;
case AP_SUSPENDED:
waitUntilActivate();
break;
case AP_DELETED:
return;
}
// When it is needed no more, delete it from the behaviours queue
if(currentBehaviour.done()) {
myScheduler.remove(currentBehaviour);
currentBehaviour = null;
}
else if(!currentBehaviour.isRunnable()) {
// Remove blocked behaviours from scheduling queue and put it
// in blocked behaviours queue
myScheduler.remove(currentBehaviour);
blockedBehaviours.addElement(currentBehaviour);
currentBehaviour = null;
}
// Now give CPU control to other agents
Thread.yield();
}
}
private void waitUntilWake() {
synchronized(waitLock) {
while(myAPState == AP_WAITING) {
try {
waitLock.wait(); // Blocks on waiting state monitor
}
catch(InterruptedException ie) {
myAPState = AP_DELETED;
throw new AgentDeathError();
}
}
}
}
private void waitUntilActivate() {
synchronized(suspendLock) {
while(myAPState == AP_SUSPENDED) {
try {
suspendLock.wait(); // Blocks on suspended state monitor
}
catch(InterruptedException ie) {
myAPState = AP_DELETED;
throw new AgentDeathError();
}
}
}
}
private void destroy() {
try {
deregisterWithAMS();
}
catch(FIPAException fe) {
fe.printStackTrace();
}
notifyDestruction();
}
/**
This method adds a new behaviour to the agent. This behaviour
will be executed concurrently with all the others, using a
cooperative round robin scheduling. This method is typically
called from an agent <code>setup()</code> to fire off some
initial behaviour, but can also be used to spawn new behaviours
dynamically.
@param b The new behaviour to add to the agent.
@see jade.core.Agent#setup()
@see jade.core.Behaviour
*/
public void addBehaviour(Behaviour b) {
myScheduler.add(b);
}
/**
This method removes a given behaviour from the agent. This method
is called automatically when a top level behaviour terminates,
but can also be called from a behaviour to terminate itself or
some other behaviour.
@param b The behaviour to remove.
@see jade.core.Behaviour
*/
public void removeBehaviour(Behaviour b) {
myScheduler.remove(b);
}
/**
Send an <b>ACL</b> message to another agent. This methods sends
a message to the agent specified in <code>:receiver</code>
message field (more than one agent can be specified as message
receiver).
@param msg An ACL message object containing the actual message to
send.
@see jade.lang.acl.ACLMessage
*/
public final void send(ACLMessage msg) {
CommEvent event = new CommEvent(this, msg);
broadcastEvent(event);
}
/**
Send an <b>ACL</b> message to the agent contained in a given
<code>AgentGroup</code>. This method allows simple message
multicast to be done. A similar result can be obtained putting
many agent names in <code>:receiver</code> message field; the
difference is that in that case every receiver agent can read all
other receivers' names, whereas this method hides multicasting to
receivers.
@param msg An ACL message object containing the actual message to
send.
@param g An agent group object holding all receivers names.
@see jade.lang.acl.ACLMessage
@see jade.core.AgentGroup
*/
public final void send(ACLMessage msg, AgentGroup g) {
CommEvent event = new CommEvent(this, msg, g);
broadcastEvent(event);
}
/**
Receives an <b>ACL</b> message from the agent message
queue. This method is non-blocking and returns the first message
in the queue, if any. Therefore, polling and busy waiting is
required to wait for the next message sent using this method.
@return A new ACL message, or <code>null</code> if no message is
present.
@see jade.lang.acl.ACLMessage
*/
public final ACLMessage receive() {
// synchronized(waitLock) {
if(msgQueue.isEmpty()) {
return null;
}
else {
ACLMessage msg = (ACLMessage)msgQueue.firstElement();
currentMessage = msg;
msgQueue.removeElementAt(0);
return msg;
}
// }
}
/**
Receives an <b>ACL</b> message matching a given template. This
method is non-blocking and returns the first matching message in
the queue, if any. Therefore, polling and busy waiting is
required to wait for a specific kind of message using this method.
@param pattern A message template to match received messages
against.
@return A new ACL message matching the given template, or
<code>null</code> if no such message is present.
@see jade.lang.acl.ACLMessage
@see jade.lang.acl.MessageTemplate
*/
public final ACLMessage receive(MessageTemplate pattern) {
ACLMessage msg = null;
synchronized(waitLock) {
Enumeration messages = msgQueue.elements();
while(messages.hasMoreElements()) {
ACLMessage cursor = (ACLMessage)messages.nextElement();
if(pattern.match(cursor)) {
msg = cursor;
currentMessage = cursor;
msgQueue.removeElement(cursor);
break; // Exit while loop
}
}
}
return msg;
}
/**
Receives an <b>ACL</b> message from the agent message
queue. This method is blocking and suspends the whole agent until
a message is available in the queue. JADE provides a special
behaviour named <code>ReceiverBehaviour</code> to wait for a
message within a behaviour without suspending all the others and
without wasting CPU time doing busy waiting.
@return A new ACL message, blocking the agent until one is
available.
@see jade.lang.acl.ACLMessage
@see jade.core.ReceiverBehaviour
*/
public final ACLMessage blockingReceive() {
ACLMessage msg = receive();
while(msg == null) {
doWait();
msg = receive();
}
return msg;
}
/**
Receives an <b>ACL</b> message matching a given message
template. This method is blocking and suspends the whole agent
until a message is available in the queue. JADE provides a
special behaviour named <code>ReceiverBehaviour</code> to wait
for a specific kind of message within a behaviour without
suspending all the others and without wasting CPU time doing busy
waiting.
@param pattern A message template to match received messages
against.
@return A new ACL message matching the given template, blocking
until such a message is available.
@see jade.lang.acl.ACLMessage
@see jade.lang.acl.MessageTemplate
@see jade.core.ReceiverBehaviour
*/
public final ACLMessage blockingReceive(MessageTemplate pattern) {
ACLMessage msg = receive(pattern);
while(msg == null) {
doWait();
msg = receive(pattern);
}
return msg;
}
/**
Puts a received <b>ACL</b> message back into the message
queue. This method can be used from an agent behaviour when it
realizes it read a message of interest for some other
behaviour. The message is put in front of the message queue, so
it will be the first returned by a <code>receive()</code> call.
@see jade.core.Agent#receive()
*/
public final void putBack(ACLMessage msg) {
synchronized(waitLock) {
msgQueue.insertElementAt(msg,0);
}
}
/**
@deprecated Builds an ACL message from a character stream. Now
<code>ACLMessage</code> class has this capabilities itself,
through <code>fromText()</code> method.
@see jade.lang.acl.ACLMessage#fromText(Reader r)
*/
public ACLMessage parse(Reader text) {
ACLMessage msg = null;
try {
msg = myParser.parse(text);
}
catch(ParseException pe) {
pe.printStackTrace();
}
catch(TokenMgrError tme) {
tme.printStackTrace();
}
return msg;
}
private ACLMessage FipaRequestMessage(String dest, String replyString) {
ACLMessage request = new ACLMessage("request");
request.setSource(myName);
request.setDest(dest);
request.setLanguage("SL0");
request.setOntology("fipa-agent-management");
request.setProtocol("fipa-request");
request.setReplyWith(replyString);
return request;
}
private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException {
send(request);
ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString));
if(reply.getType().equalsIgnoreCase("agree")) {
reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString));
if(!reply.getType().equalsIgnoreCase("inform")) {
String content = reply.getContent();
StringReader text = new StringReader(content);
throw FIPAException.fromText(text);
}
else {
String content = reply.getContent();
return content;
}
}
else {
String content = reply.getContent();
StringReader text = new StringReader(content);
throw FIPAException.fromText(text);
}
}
/**
Register this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty. However, since <b>AMS</b> registration and
deregistration are automatic in JADE, this method should not be
used by application programmers.
Some parameters here are optional, and <code>null</code> can
safely be passed for them.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void registerWithAMS(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
String replyString = myName + "-ams-registration-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
amsd.setAddress(getAddress());
amsd.setAPState(APState);
amsd.setDelegateAgentName(delegateAgent);
amsd.setForwardAddress(forwardAddress);
amsd.setOwnership(ownership);
a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Authenticate this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty.
Some parameters here are optional, and <code>null</code> can
safely be passed for them.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
<em>This method is currently not implemented.</em>
*/
public void authenticateWithAMS(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
// FIXME: Not implemented
}
/**
Deregister this agent with Agent Platform <b>AMS</b>. While this
task can be accomplished with regular message passing according
to <b>FIPA</b> protocols, this method is meant to ease this
common duty. However, since <b>AMS</b> registration and
deregistration are automatic in JADE, this method should not be
used by application programmers.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void deregisterWithAMS() throws FIPAException {
String replyString = myName + "-ams-deregistration-" + (new Date()).getTime();
// Get a semi-complete request message
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Modifies the data about this agent kept by Agent Platform
<b>AMS</b>. While this task can be accomplished with regular
message passing according to <b>FIPA</b> protocols, this method
is meant to ease this common duty. Some parameters here are
optional, and <code>null</code> can safely be passed for them.
When a non null parameter is passed, it replaces the value
currently stored inside <b>AMS</b> agent.
@param signature An optional signature string, used for security reasons.
@param APState The Agent Platform state of the agent; must be a
valid state value (typically, <code>Agent.AP_ACTIVE</code>
constant is passed).
@param delegateAgent An optional delegate agent name.
@param forwardAddress An optional forward address.
@param ownership An optional ownership string.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the AMS to indicate some error condition.
*/
public void modifyAMSRegistration(String signature, int APState, String delegateAgent,
String forwardAddress, String ownership) throws FIPAException {
String replyString = myName + "-ams-modify-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("ams", replyString);
// Build an AMS action object for the request
AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction();
AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor();
amsd.setName(getName());
amsd.setAddress(getAddress());
amsd.setAPState(APState);
amsd.setDelegateAgentName(delegateAgent);
amsd.setForwardAddress(forwardAddress);
amsd.setOwnership(ownership);
a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT);
a.setArg(amsd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
This method uses Agent Platform <b>ACC</b> agent to forward an
ACL message. Calling this method is exactly the same as calling
<code>send()</code>, only slower, since the message is first sent
to the ACC using a <code>fipa-request</code> standard protocol,
and then bounced to actual destination agent.
@param msg The ACL message to send.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the ACC to indicate some error condition.
@see jade.core.Agent#send(ACLMessage msg)
*/
public void forwardWithACC(ACLMessage msg) throws FIPAException {
String replyString = myName + "-acc-forward-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage("acc", replyString);
// Build an ACC action object for the request
AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction();
a.setName(AgentManagementOntology.ACCAction.FORWARD);
a.setArg(msg);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Register this agent with a <b>DF</b> agent. While this task can
be accomplished with regular message passing according to
<b>FIPA</b> protocols, this method is meant to ease this common
duty.
@param dfName The GUID of the <b>DF</b> agent to register with.
@param dfd A <code>DFAgentDescriptor</code> object containing all
data necessary to the registration.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-register-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.REGISTER);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply, in a separate Behaviour
doFipaRequestClient(request, replyString);
}
/**
Deregister this agent from a <b>DF</b> agent. While this task can
be accomplished with regular message passing according to
<b>FIPA</b> protocols, this method is meant to ease this common
duty.
@param dfName The GUID of the <b>DF</b> agent to deregister from.
@param dfd A <code>DFAgentDescriptor</code> object containing all
data necessary to the deregistration.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-deregister-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.DEREGISTER);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Modifies data about this agent contained within a <b>DF</b>
agent. While this task can be accomplished with regular message
passing according to <b>FIPA</b> protocols, this method is
meant to ease this common duty.
@param dfName The GUID of the <b>DF</b> agent holding the data
to be changed.
@param dfd A <code>DFAgentDescriptor</code> object containing all
new data values; every non null slot value replaces the
corresponding value held inside the <b>DF</b> agent.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
*/
public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException {
String replyString = myName + "-df-modify-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction();
a.setName(AgentManagementOntology.DFAction.MODIFY);
a.setActor(dfName);
a.setArg(dfd);
// Convert it to a String and write it in content field of the request
StringWriter text = new StringWriter();
a.toText(text);
request.setContent(text.toString());
// Send message and collect reply
doFipaRequestClient(request, replyString);
}
/**
Searches for data contained within a <b>DF</b> agent. While
this task can be accomplished with regular message passing
according to <b>FIPA</b> protocols, this method is meant to
ease this common duty. Nevertheless, a complete, powerful search
interface is provided; search constraints can be given and
recursive searches are possible. The only shortcoming is that
this method blocks the whole agent until the search terminates. A
special <code>SearchDFBehaviour</code> can be used to perform
<b>DF</b> searches without blocking.
@param dfName The GUID of the <b>DF</b> agent to start search from.
@param dfd A <code>DFAgentDescriptor</code> object containing
data to search for; this parameter is used as a template to match
data against.
@param constraints A <code>Vector</code> that must be filled with
all <code>Constraint</code> objects to apply to the current
search. This can be <code>null</code> if no search constraints
are required.
@return A <code>DFSearchResult</code> object containing all found
<code>DFAgentDescriptor</code> objects matching the given
descriptor, subject to given search constraints for search depth
and result size.
@exception FIPAException A suitable exception can be thrown when
a <code>refuse</code> or <code>failure</code> messages are
received from the DF to indicate some error condition.
@see jade.domain.AgentManagementOntology.DFAgentDescriptor
@see java.util.Vector
@see jade.domain.AgentManaementOntology.Constraint
@see jade.domain.AgentManagementOntology.DFSearchResult
*/
public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException {
String replyString = myName + "-df-search-" + (new Date()).getTime();
ACLMessage request = FipaRequestMessage(dfName, replyString);
// Build a DF action object for the request
AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction();
a.setName(AgentManagementOntology.DFAction.SEARCH);
a.setActor(dfName);
a.setArg(dfd);
if(constraints == null) {
AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint();
c.setName(AgentManagementOntology.Constraint.DFDEPTH);
c.setFn(AgentManagementOntology.Constraint.EXACTLY);
c.setArg(1);
a.addConstraint(c);
}
else {
// Put constraints into action
Enumeration e = constraints.elements();
while(e.hasMoreElements()) {
AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)e.nextElement();
a.addConstraint(c);
}
}
// Convert it to a String and write it in content field of the request
StringWriter textOut = new StringWriter();
a.toText(textOut);
request.setContent(textOut.toString());
// Send message and collect reply
String content = doFipaRequestClient(request, replyString);
// Extract agent descriptors from reply message
AgentManagementOntology.DFSearchResult found = null;
StringReader textIn = new StringReader(content);
try {
found = AgentManagementOntology.DFSearchResult.fromText(textIn);
}
catch(jade.domain.ParseException jdpe) {
jdpe.printStackTrace();
}
catch(jade.domain.TokenMgrError jdtme) {
jdtme.printStackTrace();
}
return found;
}
// Event handling methods
// Broadcast communication event to registered listeners
private void broadcastEvent(CommEvent event) {
Enumeration e = listeners.elements();
while(e.hasMoreElements()) {
CommListener l = (CommListener)e.nextElement();
l.CommHandle(event);
}
}
// Register a new listener
public final void addCommListener(CommListener l) {
listeners.addElement(l);
}
// Remove a registered listener
public final void removeCommListener(CommListener l) {
listeners.removeElement(l);
}
// Notify listeners of the destruction of the current agent
private void notifyDestruction() {
Enumeration e = listeners.elements();
while(e.hasMoreElements()) {
CommListener l = (CommListener)e.nextElement();
l.endSource(myName);
}
}
private void activateAllBehaviours() {
// Put all blocked behaviours back in ready queue
while(!blockedBehaviours.isEmpty()) {
Behaviour b = (Behaviour)blockedBehaviours.lastElement();
blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1);
b.restart();
myScheduler.add(b);
}
}
/**
Put a received message into the agent message queue. The mesage
is put at the back end of the queue. This method is called by
JADE runtime system when a message arrives, but can also be used
by an agent, and is just the same as sending a message to oneself
(though slightly faster).
@param msg The ACL message to put in the queue.
@see jade.core.Agent#send(ACLMessage msg)
*/
public final void postMessage (ACLMessage msg) {
synchronized(waitLock) {
if(msg != null) msgQueue.addElement(msg);
doWake();
}
}
}
| Added automatic sender setting when no one is specified.
| src/jade/core/Agent.java | Added automatic sender setting when no one is specified. | <ide><path>rc/jade/core/Agent.java
<ide> /*
<ide> $Log$
<add> Revision 1.39 1999/03/15 15:20:33 rimassa
<add> Added automatic sender setting when no one is specified.
<add>
<ide> Revision 1.38 1999/03/10 06:55:05 rimassa
<ide> Removed a useless import clause.
<ide>
<ide> @see jade.lang.acl.ACLMessage
<ide> */
<ide> public final void send(ACLMessage msg) {
<add> if(msg.getSource() == null)
<add> msg.setSource(getLocalName());
<ide> CommEvent event = new CommEvent(this, msg);
<ide> broadcastEvent(event);
<ide> }
<ide> @see jade.core.AgentGroup
<ide> */
<ide> public final void send(ACLMessage msg, AgentGroup g) {
<add> if(msg.getSource() == null)
<add> msg.setSource(getLocalName());
<ide> CommEvent event = new CommEvent(this, msg, g);
<ide> broadcastEvent(event);
<ide> } |
|
Java | mit | 732daab647ad91f0fd2a8fad6263b8b7246c10ce | 0 | blackuy/react-native-twilio-video-webrtc,blackuy/react-native-twilio-video-webrtc,gaston23/react-native-twilio-video-webrtc,blackuy/react-native-twilio-video-webrtc | /**
* Component to orchestrate the Twilio Video connection and the various video
* views.
* <p>
* Authors:
* Ralph Pina <[email protected]>
* Jonathan Chang <[email protected]>
*/
package com.twiliorn.library;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.StringDef;
import android.util.Log;
import android.view.View;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.twilio.video.BaseTrackStats;
import com.twilio.video.CameraCapturer;
import com.twilio.video.ConnectOptions;
import com.twilio.video.LocalAudioTrack;
import com.twilio.video.LocalAudioTrackStats;
import com.twilio.video.LocalParticipant;
import com.twilio.video.LocalTrackStats;
import com.twilio.video.LocalVideoTrack;
import com.twilio.video.LocalVideoTrackStats;
import com.twilio.video.Participant;
import com.twilio.video.RemoteAudioTrack;
import com.twilio.video.RemoteAudioTrackPublication;
import com.twilio.video.RemoteAudioTrackStats;
import com.twilio.video.RemoteDataTrack;
import com.twilio.video.RemoteDataTrackPublication;
import com.twilio.video.RemoteParticipant;
import com.twilio.video.RemoteTrackStats;
import com.twilio.video.RemoteVideoTrack;
import com.twilio.video.RemoteVideoTrackPublication;
import com.twilio.video.RemoteVideoTrackStats;
import com.twilio.video.Room;
import com.twilio.video.Room.State;
import com.twilio.video.StatsListener;
import com.twilio.video.StatsReport;
import com.twilio.video.TrackPublication;
import com.twilio.video.TwilioException;
import com.twilio.video.Video;
import com.twilio.video.VideoConstraints;
import com.twilio.video.VideoDimensions;
import com.twilio.video.VideoView;
import org.webrtc.voiceengine.WebRtcAudioManager;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_AUDIO_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CAMERA_SWITCHED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECT_FAILURE;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_STATS_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_VIDEO_CHANGED;
public class CustomTwilioVideoView extends View implements LifecycleEventListener, AudioManager.OnAudioFocusChangeListener {
private static final String TAG = "CustomTwilioVideoView";
@Retention(RetentionPolicy.SOURCE)
@StringDef({Events.ON_CAMERA_SWITCHED,
Events.ON_VIDEO_CHANGED,
Events.ON_AUDIO_CHANGED,
Events.ON_CONNECTED,
Events.ON_CONNECT_FAILURE,
Events.ON_DISCONNECTED,
Events.ON_PARTICIPANT_CONNECTED,
Events.ON_PARTICIPANT_DISCONNECTED,
Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK,
Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK,
Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK,
Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK,
Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK,
Events.ON_STATS_RECEIVED})
public @interface Events {
String ON_CAMERA_SWITCHED = "onCameraSwitched";
String ON_VIDEO_CHANGED = "onVideoChanged";
String ON_AUDIO_CHANGED = "onAudioChanged";
String ON_CONNECTED = "onRoomDidConnect";
String ON_CONNECT_FAILURE = "onRoomDidFailToConnect";
String ON_DISCONNECTED = "onRoomDidDisconnect";
String ON_PARTICIPANT_CONNECTED = "onRoomParticipantDidConnect";
String ON_PARTICIPANT_DISCONNECTED = "onRoomParticipantDidDisconnect";
String ON_PARTICIPANT_ADDED_VIDEO_TRACK = "onParticipantAddedVideoTrack";
String ON_PARTICIPANT_REMOVED_VIDEO_TRACK = "onParticipantRemovedVideoTrack";
String ON_PARTICIPANT_ADDED_AUDIO_TRACK = "onParticipantAddedAudioTrack";
String ON_PARTICIPANT_REMOVED_AUDIO_TRACK = "onParticipantRemovedAudioTrack";
String ON_PARTICIPANT_ENABLED_VIDEO_TRACK = "onParticipantEnabledVideoTrack";
String ON_PARTICIPANT_DISABLED_VIDEO_TRACK = "onParticipantDisabledVideoTrack";
String ON_PARTICIPANT_ENABLED_AUDIO_TRACK = "onParticipantEnabledAudioTrack";
String ON_PARTICIPANT_DISABLED_AUDIO_TRACK = "onParticipantDisabledAudioTrack";
String ON_STATS_RECEIVED = "onStatsReceived";
}
private final ThemedReactContext themedReactContext;
private final RCTEventEmitter eventEmitter;
private AudioFocusRequest audioFocusRequest;
private AudioAttributes playbackAttributes;
private Handler handler = new Handler();
/*
* A Room represents communication between the client and one or more participants.
*/
private static Room room;
private String roomName = null;
private String accessToken = null;
private LocalParticipant localParticipant;
/*
* A VideoView receives frames from a local or remote video track and renders them
* to an associated view.
*/
private static VideoView thumbnailVideoView;
private static LocalVideoTrack localVideoTrack;
private static CameraCapturer cameraCapturer;
private LocalAudioTrack localAudioTrack;
private AudioManager audioManager;
private int previousAudioMode;
private boolean disconnectedFromOnDestroy;
private IntentFilter intentFilter;
private BecomingNoisyReceiver myNoisyAudioStreamReceiver;
public CustomTwilioVideoView(ThemedReactContext context) {
super(context);
this.themedReactContext = context;
this.eventEmitter = themedReactContext.getJSModule(RCTEventEmitter.class);
// add lifecycle for onResume and on onPause
themedReactContext.addLifecycleEventListener(this);
/*
* Enable changing the volume using the up/down keys during a conversation
*/
if (themedReactContext.getCurrentActivity() != null) {
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
/*
* Needed for setting/abandoning audio focus during call
*/
audioManager = (AudioManager) themedReactContext.getSystemService(Context.AUDIO_SERVICE);
myNoisyAudioStreamReceiver = new BecomingNoisyReceiver();
intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
createLocalMedia();
}
// ===== SETUP =================================================================================
private VideoConstraints buildVideoConstraints() {
return new VideoConstraints.Builder()
.minVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.maxVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.minFps(5)
.maxFps(15)
.build();
}
private void createLocalMedia() {
// Share your microphone
localAudioTrack = LocalAudioTrack.create(getContext(), true);
Log.i("CustomTwilioVideoView", "Create local media");
// Share your camera
cameraCapturer = new CameraCapturer(
getContext(),
CameraCapturer.CameraSource.FRONT_CAMERA,
new CameraCapturer.Listener() {
@Override
public void onFirstFrameAvailable() {
Log.i("CustomTwilioVideoView", "Got a local camera track");
}
@Override
public void onCameraSwitched() {
}
@Override
public void onError(int i) {
Log.i("CustomTwilioVideoView", "Error getting camera");
}
}
);
if (cameraCapturer.getSupportedFormats().size() > 0) {
localVideoTrack = LocalVideoTrack.create(getContext(), true, cameraCapturer, buildVideoConstraints());
if (thumbnailVideoView != null && localVideoTrack != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
setThumbnailMirror();
}
}
// ===== LIFECYCLE EVENTS ======================================================================
@Override
public void onHostResume() {
/*
* In case it wasn't set.
*/
if (themedReactContext.getCurrentActivity() != null) {
/*
* If the local video track was released when the app was put in the background, recreate.
*/
if (cameraCapturer != null && localVideoTrack == null) {
localVideoTrack = LocalVideoTrack.create(getContext(), true, cameraCapturer, buildVideoConstraints());
}
if (localVideoTrack != null) {
if (thumbnailVideoView != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
/*
* If connected to a Room then share the local video track.
*/
if (localParticipant != null) {
localParticipant.publishTrack(localVideoTrack);
}
}
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
}
@Override
public void onHostPause() {
Log.i("CustomTwilioVideoView", "Host pause");
/*
* Release the local video track before going in the background. This ensures that the
* camera can be used by other applications while this app is in the background.
*/
if (localVideoTrack != null) {
/*
* If this local video track is being shared in a Room, remove from local
* participant before releasing the video track. Participants will be notified that
* the track has been removed.
*/
if (localParticipant != null) {
localParticipant.unpublishTrack(localVideoTrack);
}
localVideoTrack.release();
localVideoTrack = null;
}
}
@Override
public void onHostDestroy() {
/*
* Always disconnect from the room before leaving the Activity to
* ensure any memory allocated to the Room resource is freed.
*/
if (room != null && room.getState() != Room.State.DISCONNECTED) {
room.disconnect();
disconnectedFromOnDestroy = true;
}
/*
* Release the local media ensuring any memory allocated to audio or video is freed.
*/
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
}
@Override
public void onAudioFocusChange(int focusChange) {
Log.e(TAG, "onAudioFocusChange: focuschange: " + focusChange);
}
// ====== CONNECTING ===========================================================================
public void connectToRoomWrapper(String roomName, String accessToken) {
this.roomName = roomName;
this.accessToken = accessToken;
Log.i("CustomTwilioVideoView", "Starting connect flow");
if (cameraCapturer == null) {
createLocalMedia();
} else {
localAudioTrack = LocalAudioTrack.create(getContext(), true);
}
connectToRoom();
}
public void connectToRoom() {
/*
* Create a VideoClient allowing you to connect to a Room
*/
setAudioFocus(true);
ConnectOptions.Builder connectOptionsBuilder = new ConnectOptions.Builder(this.accessToken);
if (this.roomName != null) {
connectOptionsBuilder.roomName(this.roomName);
}
if (localAudioTrack != null) {
connectOptionsBuilder.audioTracks(Collections.singletonList(localAudioTrack));
}
if (localVideoTrack != null) {
connectOptionsBuilder.videoTracks(Collections.singletonList(localVideoTrack));
}
room = Video.connect(getContext(), connectOptionsBuilder.build(), roomListener());
}
private void setAudioFocus(boolean focus) {
if (focus) {
previousAudioMode = audioManager.getMode();
// Request audio focus before making any device switch.
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.requestAudioFocus(this,
AudioManager.STREAM_VOICE_CALL,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
} else {
playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
audioFocusRequest = new AudioFocusRequest
.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(this, handler)
.build();
audioManager.requestAudioFocus(audioFocusRequest);
}
/*
* Use MODE_IN_COMMUNICATION as the default audio mode. It is required
* to be in this mode when playout and/or recording starts for the best
* possible VoIP performance. Some devices have difficulties with
* speaker mode if this is not set.
*/
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
getContext().registerReceiver(myNoisyAudioStreamReceiver, intentFilter);
} else {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.abandonAudioFocus(this);
} else {
if (audioFocusRequest != null) {
audioManager.abandonAudioFocusRequest(audioFocusRequest);
}
}
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(previousAudioMode);
try {
getContext().unregisterReceiver(myNoisyAudioStreamReceiver);
} catch (Exception e) {
// already registered
}
}
}
private class BecomingNoisyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
}
}
}
// ====== DISCONNECTING ========================================================================
public void disconnect() {
if (room != null) {
room.disconnect();
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
setAudioFocus(false);
}
// ===== BUTTON LISTENERS ======================================================================
private static void setThumbnailMirror() {
if (cameraCapturer != null) {
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = (cameraSource == CameraCapturer.CameraSource.BACK_CAMERA);
if (thumbnailVideoView != null && thumbnailVideoView.getVisibility() == View.VISIBLE) {
thumbnailVideoView.setMirror(isBackCamera);
}
}
}
public void switchCamera() {
if (cameraCapturer != null) {
cameraCapturer.switchCamera();
setThumbnailMirror();
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = cameraSource == CameraCapturer.CameraSource.BACK_CAMERA;
WritableMap event = new WritableNativeMap();
event.putBoolean("isBackCamera", isBackCamera);
pushEvent(CustomTwilioVideoView.this, ON_CAMERA_SWITCHED, event);
}
}
public void toggleVideo(boolean enabled) {
if (localVideoTrack != null) {
localVideoTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("videoEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_VIDEO_CHANGED, event);
}
}
public void toggleSoundSetup(boolean speaker){
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if(speaker){
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
}
}
public void toggleAudio(boolean enabled) {
if (localAudioTrack != null) {
localAudioTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("audioEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_AUDIO_CHANGED, event);
}
}
private void convertBaseTrackStats(BaseTrackStats bs, WritableMap result) {
result.putString("codec", bs.codec);
result.putInt("packetsLost", bs.packetsLost);
result.putString("ssrc", bs.ssrc);
result.putDouble("timestamp", bs.timestamp);
result.putString("trackSid", bs.trackSid);
}
private void convertLocalTrackStats(LocalTrackStats ts, WritableMap result) {
result.putDouble("bytesSent", ts.bytesSent);
result.putInt("packetsSent", ts.packetsSent);
result.putDouble("roundTripTime", ts.roundTripTime);
}
private void convertRemoteTrackStats(RemoteTrackStats ts, WritableMap result) {
result.putDouble("bytesReceived", ts.bytesReceived);
result.putInt("packetsReceived", ts.packetsReceived);
}
private WritableMap convertAudioTrackStats(RemoteAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertRemoteTrackStats(as, result);
return result;
}
private WritableMap convertLocalAudioTrackStats(LocalAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertLocalTrackStats(as, result);
return result;
}
private WritableMap convertVideoTrackStats(RemoteVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertRemoteTrackStats(vs, result);
return result;
}
private WritableMap convertLocalVideoTrackStats(LocalVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertLocalTrackStats(vs, result);
return result;
}
public void getStats() {
if (room != null) {
room.getStats(new StatsListener() {
@Override
public void onStats(List<StatsReport> statsReports) {
WritableMap event = new WritableNativeMap();
for (StatsReport sr : statsReports) {
WritableMap connectionStats = new WritableNativeMap();
WritableArray as = new WritableNativeArray();
for (RemoteAudioTrackStats s : sr.getRemoteAudioTrackStats()) {
as.pushMap(convertAudioTrackStats(s));
}
connectionStats.putArray("remoteAudioTrackStats", as);
WritableArray vs = new WritableNativeArray();
for (RemoteVideoTrackStats s : sr.getRemoteVideoTrackStats()) {
vs.pushMap(convertVideoTrackStats(s));
}
connectionStats.putArray("remoteVideoTrackStats", vs);
WritableArray las = new WritableNativeArray();
for (LocalAudioTrackStats s : sr.getLocalAudioTrackStats()) {
las.pushMap(convertLocalAudioTrackStats(s));
}
connectionStats.putArray("localAudioTrackStats", las);
WritableArray lvs = new WritableNativeArray();
for (LocalVideoTrackStats s : sr.getLocalVideoTrackStats()) {
lvs.pushMap(convertLocalVideoTrackStats(s));
}
connectionStats.putArray("localVideoTrackStats", lvs);
event.putMap(sr.getPeerConnectionId(), connectionStats);
}
pushEvent(CustomTwilioVideoView.this, ON_STATS_RECEIVED, event);
}
});
}
}
public void disableOpenSLES() {
WebRtcAudioManager.setBlacklistDeviceForOpenSLESUsage(true);
}
// ====== ROOM LISTENER ========================================================================
/*
* Room events listener
*/
private Room.Listener roomListener() {
return new Room.Listener() {
@Override
public void onConnected(Room room) {
localParticipant = room.getLocalParticipant();
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
List<RemoteParticipant> participants = room.getRemoteParticipants();
WritableArray participantsArray = new WritableNativeArray();
for (RemoteParticipant participant : participants) {
participantsArray.pushMap(buildParticipant(participant));
}
event.putArray("participants", participantsArray);
pushEvent(CustomTwilioVideoView.this, ON_CONNECTED, event);
for (RemoteParticipant participant : participants) {
addParticipant(room, participant);
}
}
@Override
public void onConnectFailure(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putString("reason", e.getExplanation());
pushEvent(CustomTwilioVideoView.this, ON_CONNECT_FAILURE, event);
}
@Override
public void onDisconnected(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
if (localParticipant != null) {
event.putString("participant", localParticipant.getIdentity());
}
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
pushEvent(CustomTwilioVideoView.this, ON_DISCONNECTED, event);
localParticipant = null;
roomName = null;
accessToken = null;
CustomTwilioVideoView.room = null;
// Only reinitialize the UI if disconnect was not called from onDestroy()
if (!disconnectedFromOnDestroy) {
setAudioFocus(false);
}
}
@Override
public void onParticipantConnected(Room room, RemoteParticipant participant) {
addParticipant(room, participant);
}
@Override
public void onParticipantDisconnected(Room room, RemoteParticipant participant) {
removeParticipant(room, participant);
}
@Override
public void onRecordingStarted(Room room) {
}
@Override
public void onRecordingStopped(Room room) {
}
};
}
/*
* Called when participant joins the room
*/
private void addParticipant(Room room, RemoteParticipant participant) {
Log.i("CustomTwilioVideoView", "ADD PARTICIPANT ");
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(participant));
pushEvent(this, ON_PARTICIPANT_CONNECTED, event);
/*
* Add participant renderer
*/
if (participant.getRemoteVideoTracks().size() > 0) {
Log.i("CustomTwilioVideoView", "Participant DOES HAVE VIDEO TRACKS");
} else {
Log.i("CustomTwilioVideoView", "Participant DOES NOT HAVE VIDEO TRACKS");
}
/*
* Start listening for participant media events
*/
participant.setListener(mediaListener());
}
/*
* Called when participant leaves the room
*/
private void removeParticipant(Room room, RemoteParticipant participant) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(participant));
pushEvent(this, ON_PARTICIPANT_DISCONNECTED, event);
//something about this breaking.
//participant.setListener(null);
}
// ====== MEDIA LISTENER =======================================================================
private RemoteParticipant.Listener mediaListener() {
return new RemoteParticipant.Listener() {
@Override
public void onAudioTrackSubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackUnsubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackSubscriptionFailed(RemoteParticipant participant, RemoteAudioTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onAudioTrackPublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onAudioTrackUnpublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onDataTrackSubscribed(RemoteParticipant participant, RemoteDataTrackPublication publication, RemoteDataTrack dataTrack) {
}
@Override
public void onDataTrackUnsubscribed(RemoteParticipant participant, RemoteDataTrackPublication publication, RemoteDataTrack dataTrack) {
}
@Override
public void onDataTrackSubscriptionFailed(RemoteParticipant participant, RemoteDataTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onDataTrackPublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onDataTrackUnpublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onVideoTrackSubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
Log.i("CustomTwilioVideoView", "Participant ADDED TRACK");
addParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackUnsubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
Log.i("CustomTwilioVideoView", "Participant REMOVED TRACK");
removeParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackSubscriptionFailed(RemoteParticipant participant, RemoteVideoTrackPublication publication, TwilioException twilioException) {
Log.i("CustomTwilioVideoView", "Participant Video Track Subscription Failed");
}
@Override
public void onVideoTrackPublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onVideoTrackUnpublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onAudioTrackEnabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackDisabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_AUDIO_TRACK, event);
}
@Override
public void onVideoTrackEnabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_VIDEO_TRACK, event);
}
@Override
public void onVideoTrackDisabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_VIDEO_TRACK, event);
}
};
}
private WritableMap buildParticipant(Participant participant) {
WritableMap participantMap = new WritableNativeMap();
participantMap.putString("identity", participant.getIdentity());
participantMap.putString("sid", participant.getSid());
return participantMap;
}
private WritableMap buildParticipantVideoEvent(Participant participant, TrackPublication publication) {
WritableMap participantMap = buildParticipant(participant);
WritableMap trackMap = new WritableNativeMap();
trackMap.putString("trackSid", publication.getTrackSid());
trackMap.putString("trackName", publication.getTrackName());
trackMap.putBoolean("enabled", publication.isTrackEnabled());
WritableMap event = new WritableNativeMap();
event.putMap("participant", participantMap);
event.putMap("track", trackMap);
return event;
}
private void addParticipantVideo(Participant participant, RemoteVideoTrackPublication publication) {
Log.i("CustomTwilioVideoView", "add Participant Video");
WritableMap event = this.buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_VIDEO_TRACK, event);
}
private void removeParticipantVideo(Participant participant, RemoteVideoTrackPublication deleteVideoTrack) {
Log.i("CustomTwilioVideoView", "Remove participant");
WritableMap event = this.buildParticipantVideoEvent(participant, deleteVideoTrack);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_VIDEO_TRACK, event);
}
// ===== EVENTS TO RN ==========================================================================
void pushEvent(View view, String name, WritableMap data) {
eventEmitter.receiveEvent(view.getId(), name, data);
}
public static void registerPrimaryVideoView(VideoView v, String trackSid) {
Log.i("CustomTwilioVideoView", "register Primary Video");
Log.i("CustomTwilioVideoView", trackSid);
if (room != null) {
Log.i("CustomTwilioVideoView", "Found Participant tracks");
for (RemoteParticipant participant : room.getRemoteParticipants()) {
for (RemoteVideoTrackPublication publication : participant.getRemoteVideoTracks()) {
Log.i("CustomTwilioVideoView", publication.getTrackSid());
RemoteVideoTrack track = publication.getRemoteVideoTrack();
if (track == null) {
Log.i("CustomTwilioVideoView", "SKIPPING UNSUBSCRIBED TRACK");
continue;
}
if (publication.getTrackSid().equals(trackSid)) {
Log.i("CustomTwilioVideoView", "FOUND THE MATCHING TRACK");
track.addRenderer(v);
} else {
track.removeRenderer(v);
}
}
}
}
}
public static void registerThumbnailVideoView(VideoView v) {
thumbnailVideoView = v;
if (localVideoTrack != null) {
localVideoTrack.addRenderer(v);
}
setThumbnailMirror();
}
}
| android/src/main/java/com/twiliorn/library/CustomTwilioVideoView.java | /**
* Component to orchestrate the Twilio Video connection and the various video
* views.
* <p>
* Authors:
* Ralph Pina <[email protected]>
* Jonathan Chang <[email protected]>
*/
package com.twiliorn.library;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.StringDef;
import android.util.Log;
import android.view.View;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.twilio.video.BaseTrackStats;
import com.twilio.video.CameraCapturer;
import com.twilio.video.ConnectOptions;
import com.twilio.video.LocalAudioTrack;
import com.twilio.video.LocalAudioTrackStats;
import com.twilio.video.LocalParticipant;
import com.twilio.video.LocalTrackStats;
import com.twilio.video.LocalVideoTrack;
import com.twilio.video.LocalVideoTrackStats;
import com.twilio.video.Participant;
import com.twilio.video.RemoteAudioTrack;
import com.twilio.video.RemoteAudioTrackPublication;
import com.twilio.video.RemoteAudioTrackStats;
import com.twilio.video.RemoteDataTrack;
import com.twilio.video.RemoteDataTrackPublication;
import com.twilio.video.RemoteParticipant;
import com.twilio.video.RemoteTrackStats;
import com.twilio.video.RemoteVideoTrack;
import com.twilio.video.RemoteVideoTrackPublication;
import com.twilio.video.RemoteVideoTrackStats;
import com.twilio.video.Room;
import com.twilio.video.Room.State;
import com.twilio.video.StatsListener;
import com.twilio.video.StatsReport;
import com.twilio.video.TrackPublication;
import com.twilio.video.TwilioException;
import com.twilio.video.Video;
import com.twilio.video.VideoConstraints;
import com.twilio.video.VideoDimensions;
import com.twilio.video.VideoView;
import org.webrtc.voiceengine.WebRtcAudioManager;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.List;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_AUDIO_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CAMERA_SWITCHED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECT_FAILURE;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_STATS_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_VIDEO_CHANGED;
public class CustomTwilioVideoView extends View implements LifecycleEventListener, AudioManager.OnAudioFocusChangeListener {
private static final String TAG = "CustomTwilioVideoView";
@Retention(RetentionPolicy.SOURCE)
@StringDef({Events.ON_CAMERA_SWITCHED,
Events.ON_VIDEO_CHANGED,
Events.ON_AUDIO_CHANGED,
Events.ON_CONNECTED,
Events.ON_CONNECT_FAILURE,
Events.ON_DISCONNECTED,
Events.ON_PARTICIPANT_CONNECTED,
Events.ON_PARTICIPANT_DISCONNECTED,
Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK,
Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK,
Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK,
Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK,
Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK,
Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK,
Events.ON_STATS_RECEIVED})
public @interface Events {
String ON_CAMERA_SWITCHED = "onCameraSwitched";
String ON_VIDEO_CHANGED = "onVideoChanged";
String ON_AUDIO_CHANGED = "onAudioChanged";
String ON_CONNECTED = "onRoomDidConnect";
String ON_CONNECT_FAILURE = "onRoomDidFailToConnect";
String ON_DISCONNECTED = "onRoomDidDisconnect";
String ON_PARTICIPANT_CONNECTED = "onRoomParticipantDidConnect";
String ON_PARTICIPANT_DISCONNECTED = "onRoomParticipantDidDisconnect";
String ON_PARTICIPANT_ADDED_VIDEO_TRACK = "onParticipantAddedVideoTrack";
String ON_PARTICIPANT_REMOVED_VIDEO_TRACK = "onParticipantRemovedVideoTrack";
String ON_PARTICIPANT_ADDED_AUDIO_TRACK = "onParticipantAddedAudioTrack";
String ON_PARTICIPANT_REMOVED_AUDIO_TRACK = "onParticipantRemovedAudioTrack";
String ON_PARTICIPANT_ENABLED_VIDEO_TRACK = "onParticipantEnabledVideoTrack";
String ON_PARTICIPANT_DISABLED_VIDEO_TRACK = "onParticipantDisabledVideoTrack";
String ON_PARTICIPANT_ENABLED_AUDIO_TRACK = "onParticipantEnabledAudioTrack";
String ON_PARTICIPANT_DISABLED_AUDIO_TRACK = "onParticipantDisabledAudioTrack";
String ON_STATS_RECEIVED = "onStatsReceived";
}
private final ThemedReactContext themedReactContext;
private final RCTEventEmitter eventEmitter;
private AudioFocusRequest audioFocusRequest;
private AudioAttributes playbackAttributes;
private Handler handler = new Handler();
/*
* A Room represents communication between the client and one or more participants.
*/
private static Room room;
private String roomName = null;
private String accessToken = null;
private LocalParticipant localParticipant;
/*
* A VideoView receives frames from a local or remote video track and renders them
* to an associated view.
*/
private static VideoView thumbnailVideoView;
private static LocalVideoTrack localVideoTrack;
private static CameraCapturer cameraCapturer;
private LocalAudioTrack localAudioTrack;
private AudioManager audioManager;
private int previousAudioMode;
private boolean disconnectedFromOnDestroy;
private IntentFilter intentFilter;
private BecomingNoisyReceiver myNoisyAudioStreamReceiver;
public CustomTwilioVideoView(ThemedReactContext context) {
super(context);
this.themedReactContext = context;
this.eventEmitter = themedReactContext.getJSModule(RCTEventEmitter.class);
// add lifecycle for onResume and on onPause
themedReactContext.addLifecycleEventListener(this);
/*
* Enable changing the volume using the up/down keys during a conversation
*/
if (themedReactContext.getCurrentActivity() != null) {
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
/*
* Needed for setting/abandoning audio focus during call
*/
audioManager = (AudioManager) themedReactContext.getSystemService(Context.AUDIO_SERVICE);
myNoisyAudioStreamReceiver = new BecomingNoisyReceiver();
intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
}
// ===== SETUP =================================================================================
private VideoConstraints buildVideoConstraints() {
return new VideoConstraints.Builder()
.minVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.maxVideoDimensions(VideoDimensions.CIF_VIDEO_DIMENSIONS)
.minFps(5)
.maxFps(15)
.build();
}
private void createLocalMedia() {
// Share your microphone
localAudioTrack = LocalAudioTrack.create(getContext(), true);
Log.i("CustomTwilioVideoView", "Create local media");
// Share your camera
cameraCapturer = new CameraCapturer(
getContext(),
CameraCapturer.CameraSource.FRONT_CAMERA,
new CameraCapturer.Listener() {
@Override
public void onFirstFrameAvailable() {
Log.i("CustomTwilioVideoView", "Got a local camera track");
}
@Override
public void onCameraSwitched() {
}
@Override
public void onError(int i) {
Log.i("CustomTwilioVideoView", "Error getting camera");
}
}
);
if (cameraCapturer.getSupportedFormats().size() > 0) {
localVideoTrack = LocalVideoTrack.create(getContext(), true, cameraCapturer, buildVideoConstraints());
if (thumbnailVideoView != null && localVideoTrack != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
setThumbnailMirror();
}
connectToRoom();
}
// ===== LIFECYCLE EVENTS ======================================================================
@Override
public void onHostResume() {
/*
* In case it wasn't set.
*/
if (themedReactContext.getCurrentActivity() != null) {
/*
* If the local video track was released when the app was put in the background, recreate.
*/
if (cameraCapturer != null && localVideoTrack == null) {
localVideoTrack = LocalVideoTrack.create(getContext(), true, cameraCapturer, buildVideoConstraints());
}
if (localVideoTrack != null) {
if (thumbnailVideoView != null) {
localVideoTrack.addRenderer(thumbnailVideoView);
}
/*
* If connected to a Room then share the local video track.
*/
if (localParticipant != null) {
localParticipant.publishTrack(localVideoTrack);
}
}
themedReactContext.getCurrentActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
}
@Override
public void onHostPause() {
Log.i("CustomTwilioVideoView", "Host pause");
/*
* Release the local video track before going in the background. This ensures that the
* camera can be used by other applications while this app is in the background.
*/
if (localVideoTrack != null) {
/*
* If this local video track is being shared in a Room, remove from local
* participant before releasing the video track. Participants will be notified that
* the track has been removed.
*/
if (localParticipant != null) {
localParticipant.unpublishTrack(localVideoTrack);
}
localVideoTrack.release();
localVideoTrack = null;
}
}
@Override
public void onHostDestroy() {
/*
* Always disconnect from the room before leaving the Activity to
* ensure any memory allocated to the Room resource is freed.
*/
if (room != null && room.getState() != Room.State.DISCONNECTED) {
room.disconnect();
disconnectedFromOnDestroy = true;
}
/*
* Release the local media ensuring any memory allocated to audio or video is freed.
*/
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
}
@Override
public void onAudioFocusChange(int focusChange) {
Log.e(TAG, "onAudioFocusChange: focuschange: " + focusChange);
}
// ====== CONNECTING ===========================================================================
public void connectToRoomWrapper(String roomName, String accessToken) {
this.roomName = roomName;
this.accessToken = accessToken;
Log.i("CustomTwilioVideoView", "Starting connect flow");
if (cameraCapturer == null) {
createLocalMedia();
} else {
localAudioTrack = LocalAudioTrack.create(getContext(), true);
connectToRoom();
}
}
public void connectToRoom() {
/*
* Create a VideoClient allowing you to connect to a Room
*/
setAudioFocus(true);
ConnectOptions.Builder connectOptionsBuilder = new ConnectOptions.Builder(this.accessToken);
if (this.roomName != null) {
connectOptionsBuilder.roomName(this.roomName);
}
if (localAudioTrack != null) {
connectOptionsBuilder.audioTracks(Collections.singletonList(localAudioTrack));
}
if (localVideoTrack != null) {
connectOptionsBuilder.videoTracks(Collections.singletonList(localVideoTrack));
}
room = Video.connect(getContext(), connectOptionsBuilder.build(), roomListener());
}
private void setAudioFocus(boolean focus) {
if (focus) {
previousAudioMode = audioManager.getMode();
// Request audio focus before making any device switch.
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.requestAudioFocus(this,
AudioManager.STREAM_VOICE_CALL,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
} else {
playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
audioFocusRequest = new AudioFocusRequest
.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(this, handler)
.build();
audioManager.requestAudioFocus(audioFocusRequest);
}
/*
* Use MODE_IN_COMMUNICATION as the default audio mode. It is required
* to be in this mode when playout and/or recording starts for the best
* possible VoIP performance. Some devices have difficulties with
* speaker mode if this is not set.
*/
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
getContext().registerReceiver(myNoisyAudioStreamReceiver, intentFilter);
} else {
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
audioManager.abandonAudioFocus(this);
} else {
if (audioFocusRequest != null) {
audioManager.abandonAudioFocusRequest(audioFocusRequest);
}
}
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(previousAudioMode);
try {
getContext().unregisterReceiver(myNoisyAudioStreamReceiver);
} catch (Exception e) {
// already registered
}
}
}
private class BecomingNoisyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn());
}
}
}
// ====== DISCONNECTING ========================================================================
public void disconnect() {
if (room != null) {
room.disconnect();
}
if (localAudioTrack != null) {
localAudioTrack.release();
localAudioTrack = null;
}
if (localVideoTrack != null) {
localVideoTrack.release();
localVideoTrack = null;
}
setAudioFocus(false);
}
// ===== BUTTON LISTENERS ======================================================================
private static void setThumbnailMirror() {
if (cameraCapturer != null) {
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = (cameraSource == CameraCapturer.CameraSource.BACK_CAMERA);
if (thumbnailVideoView != null && thumbnailVideoView.getVisibility() == View.VISIBLE) {
thumbnailVideoView.setMirror(isBackCamera);
}
}
}
public void switchCamera() {
if (cameraCapturer != null) {
cameraCapturer.switchCamera();
setThumbnailMirror();
CameraCapturer.CameraSource cameraSource = cameraCapturer.getCameraSource();
final boolean isBackCamera = cameraSource == CameraCapturer.CameraSource.BACK_CAMERA;
WritableMap event = new WritableNativeMap();
event.putBoolean("isBackCamera", isBackCamera);
pushEvent(CustomTwilioVideoView.this, ON_CAMERA_SWITCHED, event);
}
}
public void toggleVideo(boolean enabled) {
if (localVideoTrack != null) {
localVideoTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("videoEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_VIDEO_CHANGED, event);
}
}
public void toggleSoundSetup(boolean speaker){
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if(speaker){
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
}
}
public void toggleAudio(boolean enabled) {
if (localAudioTrack != null) {
localAudioTrack.enable(enabled);
WritableMap event = new WritableNativeMap();
event.putBoolean("audioEnabled", enabled);
pushEvent(CustomTwilioVideoView.this, ON_AUDIO_CHANGED, event);
}
}
private void convertBaseTrackStats(BaseTrackStats bs, WritableMap result) {
result.putString("codec", bs.codec);
result.putInt("packetsLost", bs.packetsLost);
result.putString("ssrc", bs.ssrc);
result.putDouble("timestamp", bs.timestamp);
result.putString("trackSid", bs.trackSid);
}
private void convertLocalTrackStats(LocalTrackStats ts, WritableMap result) {
result.putDouble("bytesSent", ts.bytesSent);
result.putInt("packetsSent", ts.packetsSent);
result.putDouble("roundTripTime", ts.roundTripTime);
}
private void convertRemoteTrackStats(RemoteTrackStats ts, WritableMap result) {
result.putDouble("bytesReceived", ts.bytesReceived);
result.putInt("packetsReceived", ts.packetsReceived);
}
private WritableMap convertAudioTrackStats(RemoteAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertRemoteTrackStats(as, result);
return result;
}
private WritableMap convertLocalAudioTrackStats(LocalAudioTrackStats as) {
WritableMap result = new WritableNativeMap();
result.putInt("audioLevel", as.audioLevel);
result.putInt("jitter", as.jitter);
convertBaseTrackStats(as, result);
convertLocalTrackStats(as, result);
return result;
}
private WritableMap convertVideoTrackStats(RemoteVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertRemoteTrackStats(vs, result);
return result;
}
private WritableMap convertLocalVideoTrackStats(LocalVideoTrackStats vs) {
WritableMap result = new WritableNativeMap();
WritableMap dimensions = new WritableNativeMap();
dimensions.putInt("height", vs.dimensions.height);
dimensions.putInt("width", vs.dimensions.width);
result.putMap("dimensions", dimensions);
result.putInt("frameRate", vs.frameRate);
convertBaseTrackStats(vs, result);
convertLocalTrackStats(vs, result);
return result;
}
public void getStats() {
if (room != null) {
room.getStats(new StatsListener() {
@Override
public void onStats(List<StatsReport> statsReports) {
WritableMap event = new WritableNativeMap();
for (StatsReport sr : statsReports) {
WritableMap connectionStats = new WritableNativeMap();
WritableArray as = new WritableNativeArray();
for (RemoteAudioTrackStats s : sr.getRemoteAudioTrackStats()) {
as.pushMap(convertAudioTrackStats(s));
}
connectionStats.putArray("remoteAudioTrackStats", as);
WritableArray vs = new WritableNativeArray();
for (RemoteVideoTrackStats s : sr.getRemoteVideoTrackStats()) {
vs.pushMap(convertVideoTrackStats(s));
}
connectionStats.putArray("remoteVideoTrackStats", vs);
WritableArray las = new WritableNativeArray();
for (LocalAudioTrackStats s : sr.getLocalAudioTrackStats()) {
las.pushMap(convertLocalAudioTrackStats(s));
}
connectionStats.putArray("localAudioTrackStats", las);
WritableArray lvs = new WritableNativeArray();
for (LocalVideoTrackStats s : sr.getLocalVideoTrackStats()) {
lvs.pushMap(convertLocalVideoTrackStats(s));
}
connectionStats.putArray("localVideoTrackStats", lvs);
event.putMap(sr.getPeerConnectionId(), connectionStats);
}
pushEvent(CustomTwilioVideoView.this, ON_STATS_RECEIVED, event);
}
});
}
}
public void disableOpenSLES() {
WebRtcAudioManager.setBlacklistDeviceForOpenSLESUsage(true);
}
// ====== ROOM LISTENER ========================================================================
/*
* Room events listener
*/
private Room.Listener roomListener() {
return new Room.Listener() {
@Override
public void onConnected(Room room) {
localParticipant = room.getLocalParticipant();
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
List<RemoteParticipant> participants = room.getRemoteParticipants();
WritableArray participantsArray = new WritableNativeArray();
for (RemoteParticipant participant : participants) {
participantsArray.pushMap(buildParticipant(participant));
}
event.putArray("participants", participantsArray);
pushEvent(CustomTwilioVideoView.this, ON_CONNECTED, event);
for (RemoteParticipant participant : participants) {
addParticipant(room, participant);
}
}
@Override
public void onConnectFailure(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putString("reason", e.getExplanation());
pushEvent(CustomTwilioVideoView.this, ON_CONNECT_FAILURE, event);
}
@Override
public void onDisconnected(Room room, TwilioException e) {
WritableMap event = new WritableNativeMap();
if (localParticipant != null) {
event.putString("participant", localParticipant.getIdentity());
}
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
pushEvent(CustomTwilioVideoView.this, ON_DISCONNECTED, event);
localParticipant = null;
roomName = null;
accessToken = null;
CustomTwilioVideoView.room = null;
// Only reinitialize the UI if disconnect was not called from onDestroy()
if (!disconnectedFromOnDestroy) {
setAudioFocus(false);
}
}
@Override
public void onParticipantConnected(Room room, RemoteParticipant participant) {
addParticipant(room, participant);
}
@Override
public void onParticipantDisconnected(Room room, RemoteParticipant participant) {
removeParticipant(room, participant);
}
@Override
public void onRecordingStarted(Room room) {
}
@Override
public void onRecordingStopped(Room room) {
}
};
}
/*
* Called when participant joins the room
*/
private void addParticipant(Room room, RemoteParticipant participant) {
Log.i("CustomTwilioVideoView", "ADD PARTICIPANT ");
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(participant));
pushEvent(this, ON_PARTICIPANT_CONNECTED, event);
/*
* Add participant renderer
*/
if (participant.getRemoteVideoTracks().size() > 0) {
Log.i("CustomTwilioVideoView", "Participant DOES HAVE VIDEO TRACKS");
} else {
Log.i("CustomTwilioVideoView", "Participant DOES NOT HAVE VIDEO TRACKS");
}
/*
* Start listening for participant media events
*/
participant.setListener(mediaListener());
}
/*
* Called when participant leaves the room
*/
private void removeParticipant(Room room, RemoteParticipant participant) {
WritableMap event = new WritableNativeMap();
event.putString("roomName", room.getName());
event.putString("roomSid", room.getSid());
event.putMap("participant", buildParticipant(participant));
pushEvent(this, ON_PARTICIPANT_DISCONNECTED, event);
//something about this breaking.
//participant.setListener(null);
}
// ====== MEDIA LISTENER =======================================================================
private RemoteParticipant.Listener mediaListener() {
return new RemoteParticipant.Listener() {
@Override
public void onAudioTrackSubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackUnsubscribed(RemoteParticipant participant, RemoteAudioTrackPublication publication, RemoteAudioTrack audioTrack) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackSubscriptionFailed(RemoteParticipant participant, RemoteAudioTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onAudioTrackPublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onAudioTrackUnpublished(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
}
@Override
public void onDataTrackSubscribed(RemoteParticipant participant, RemoteDataTrackPublication publication, RemoteDataTrack dataTrack) {
}
@Override
public void onDataTrackUnsubscribed(RemoteParticipant participant, RemoteDataTrackPublication publication, RemoteDataTrack dataTrack) {
}
@Override
public void onDataTrackSubscriptionFailed(RemoteParticipant participant, RemoteDataTrackPublication publication, TwilioException twilioException) {
}
@Override
public void onDataTrackPublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onDataTrackUnpublished(RemoteParticipant participant, RemoteDataTrackPublication publication) {
}
@Override
public void onVideoTrackSubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
Log.i("CustomTwilioVideoView", "Participant ADDED TRACK");
addParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackUnsubscribed(RemoteParticipant participant, RemoteVideoTrackPublication publication, RemoteVideoTrack videoTrack) {
Log.i("CustomTwilioVideoView", "Participant REMOVED TRACK");
removeParticipantVideo(participant, publication);
}
@Override
public void onVideoTrackSubscriptionFailed(RemoteParticipant participant, RemoteVideoTrackPublication publication, TwilioException twilioException) {
Log.i("CustomTwilioVideoView", "Participant Video Track Subscription Failed");
}
@Override
public void onVideoTrackPublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onVideoTrackUnpublished(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
}
@Override
public void onAudioTrackEnabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_AUDIO_TRACK, event);
}
@Override
public void onAudioTrackDisabled(RemoteParticipant participant, RemoteAudioTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_AUDIO_TRACK, event);
}
@Override
public void onVideoTrackEnabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ENABLED_VIDEO_TRACK, event);
}
@Override
public void onVideoTrackDisabled(RemoteParticipant participant, RemoteVideoTrackPublication publication) {
WritableMap event = buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_DISABLED_VIDEO_TRACK, event);
}
};
}
private WritableMap buildParticipant(Participant participant) {
WritableMap participantMap = new WritableNativeMap();
participantMap.putString("identity", participant.getIdentity());
participantMap.putString("sid", participant.getSid());
return participantMap;
}
private WritableMap buildParticipantVideoEvent(Participant participant, TrackPublication publication) {
WritableMap participantMap = buildParticipant(participant);
WritableMap trackMap = new WritableNativeMap();
trackMap.putString("trackSid", publication.getTrackSid());
trackMap.putString("trackName", publication.getTrackName());
trackMap.putBoolean("enabled", publication.isTrackEnabled());
WritableMap event = new WritableNativeMap();
event.putMap("participant", participantMap);
event.putMap("track", trackMap);
return event;
}
private void addParticipantVideo(Participant participant, RemoteVideoTrackPublication publication) {
Log.i("CustomTwilioVideoView", "add Participant Video");
WritableMap event = this.buildParticipantVideoEvent(participant, publication);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_ADDED_VIDEO_TRACK, event);
}
private void removeParticipantVideo(Participant participant, RemoteVideoTrackPublication deleteVideoTrack) {
Log.i("CustomTwilioVideoView", "Remove participant");
WritableMap event = this.buildParticipantVideoEvent(participant, deleteVideoTrack);
pushEvent(CustomTwilioVideoView.this, ON_PARTICIPANT_REMOVED_VIDEO_TRACK, event);
}
// ===== EVENTS TO RN ==========================================================================
void pushEvent(View view, String name, WritableMap data) {
eventEmitter.receiveEvent(view.getId(), name, data);
}
public static void registerPrimaryVideoView(VideoView v, String trackSid) {
Log.i("CustomTwilioVideoView", "register Primary Video");
Log.i("CustomTwilioVideoView", trackSid);
if (room != null) {
Log.i("CustomTwilioVideoView", "Found Participant tracks");
for (RemoteParticipant participant : room.getRemoteParticipants()) {
for (RemoteVideoTrackPublication publication : participant.getRemoteVideoTracks()) {
Log.i("CustomTwilioVideoView", publication.getTrackSid());
RemoteVideoTrack track = publication.getRemoteVideoTrack();
if (track == null) {
Log.i("CustomTwilioVideoView", "SKIPPING UNSUBSCRIBED TRACK");
continue;
}
if (publication.getTrackSid().equals(trackSid)) {
Log.i("CustomTwilioVideoView", "FOUND THE MATCHING TRACK");
track.addRenderer(v);
} else {
track.removeRenderer(v);
}
}
}
}
}
public static void registerThumbnailVideoView(VideoView v) {
thumbnailVideoView = v;
if (localVideoTrack != null) {
localVideoTrack.addRenderer(v);
}
setThumbnailMirror();
}
}
| [android] init local video view when initializing native view (#207)
| android/src/main/java/com/twiliorn/library/CustomTwilioVideoView.java | [android] init local video view when initializing native view (#207) | <ide><path>ndroid/src/main/java/com/twiliorn/library/CustomTwilioVideoView.java
<ide> audioManager = (AudioManager) themedReactContext.getSystemService(Context.AUDIO_SERVICE);
<ide> myNoisyAudioStreamReceiver = new BecomingNoisyReceiver();
<ide> intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
<add>
<add> createLocalMedia();
<ide> }
<ide>
<ide> // ===== SETUP =================================================================================
<ide> }
<ide> setThumbnailMirror();
<ide> }
<del> connectToRoom();
<ide> }
<ide>
<ide> // ===== LIFECYCLE EVENTS ======================================================================
<ide> createLocalMedia();
<ide> } else {
<ide> localAudioTrack = LocalAudioTrack.create(getContext(), true);
<del> connectToRoom();
<del> }
<add> }
<add> connectToRoom();
<ide> }
<ide>
<ide> public void connectToRoom() { |
|
Java | apache-2.0 | b0a7d7a1b2936065cb7ffd2b1e184a17b9133db0 | 0 | cache2k/cache2k,cache2k/cache2k,cache2k/cache2k | package org.cache2k.configuration;
/*
* #%L
* cache2k API
* %%
* Copyright (C) 2000 - 2016 headissue GmbH, Munich
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Container for configuration objects. The container preserves the order of the sections
* and checks that one type is only added once.
*
* @author Jens Wilke
*/
public class ConfigurationSectionContainer implements Iterable<ConfigurationSection> {
private List<ConfigurationSection> sections = new ArrayList<ConfigurationSection>();
/**
* Add a new configuration section to the container.
*
* @throws IllegalArgumentException if same type is already present and a singleton
*/
public void add(ConfigurationSection section) {
if (section instanceof SingletonConfigurationSection) {
if (getSection(section.getClass()) != null) {
throw new IllegalArgumentException("Section of same type already inserted: " + section.getClass().getName());
}
}
sections.add(section);
}
/**
* Retrieve a single section from the container.
*/
public <T extends ConfigurationSection> T getSection(Class<T> sectionType) {
for (ConfigurationSection s : sections) {
if (sectionType.equals(s.getClass())) {
return (T) s;
}
}
return null;
}
@Override
public Iterator<ConfigurationSection> iterator() {
return sections.iterator();
}
}
| api/src/main/java/org/cache2k/configuration/ConfigurationSectionContainer.java | package org.cache2k.configuration;
/*
* #%L
* cache2k API
* %%
* Copyright (C) 2000 - 2016 headissue GmbH, Munich
* %%
* 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.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Container for configuration objects. The container preserves the order of the sections
* and checks that one type is only added once.
*
* @author Jens Wilke
*/
public class ConfigurationSectionContainer implements Iterable<ConfigurationSection> {
private List<ConfigurationSection> sections = new ArrayList<ConfigurationSection>();
/**
* Add a new configuration section to the container.
*
* @throws IllegalArgumentException if same type is already present and a singleton
*/
public void add(ConfigurationSection section) {
if (section instanceof SingletonConfigurationSection) {
if (getSection(section.getClass()) != null) {
throw new IllegalArgumentException("Section of same type already inserted: " + section.getClass().getName());
}
}
sections.add(section);
}
/**
* Retrieve a single section from the container.
*/
public <T> T getSection(Class<T> sectionType) {
for (ConfigurationSection s : sections) {
if (sectionType.isAssignableFrom(s.getClass())) {
return (T) s;
}
}
return null;
}
@Override
public Iterator<ConfigurationSection> iterator() {
return sections.iterator();
}
}
| exact match on type
| api/src/main/java/org/cache2k/configuration/ConfigurationSectionContainer.java | exact match on type | <ide><path>pi/src/main/java/org/cache2k/configuration/ConfigurationSectionContainer.java
<ide> /**
<ide> * Retrieve a single section from the container.
<ide> */
<del> public <T> T getSection(Class<T> sectionType) {
<add> public <T extends ConfigurationSection> T getSection(Class<T> sectionType) {
<ide> for (ConfigurationSection s : sections) {
<del> if (sectionType.isAssignableFrom(s.getClass())) {
<add> if (sectionType.equals(s.getClass())) {
<ide> return (T) s;
<ide> }
<ide> } |
|
Java | mit | ccefdcda923ca6ed76f900d1ae793e1f8e460671 | 0 | codistmonk/IMJ | package imj.apps.modules;
import static imj.IMJTools.alpha;
import static imj.IMJTools.argb;
import static imj.IMJTools.blue;
import static imj.IMJTools.brightness;
import static imj.IMJTools.channelValue;
import static imj.IMJTools.green;
import static imj.IMJTools.hue;
import static imj.IMJTools.red;
import static imj.IMJTools.saturation;
import static imj.MorphologicalOperations.StructuringElement.newDisk;
import static imj.MorphologicalOperations.StructuringElement.newRing;
import static imj.apps.modules.ViewFilter.Channel.Primitive.ALPHA;
import static imj.apps.modules.ViewFilter.Channel.Primitive.BLUE;
import static imj.apps.modules.ViewFilter.Channel.Primitive.GREEN;
import static imj.apps.modules.ViewFilter.Channel.Primitive.RED;
import static imj.apps.modules.ViewFilter.Channel.Synthetic.BRIGHTNESS;
import static imj.apps.modules.ViewFilter.Channel.Synthetic.HUE;
import static imj.apps.modules.ViewFilter.Channel.Synthetic.SATURATION;
import static java.lang.Double.parseDouble;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static net.sourceforge.aprog.af.AFTools.fireUpdate;
import static net.sourceforge.aprog.tools.Tools.cast;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import static net.sourceforge.aprog.tools.Tools.ignore;
import imj.Image;
import imj.Labeling.NeighborhoodShape.Distance;
import imj.apps.modules.FilteredImage.ChannelFilter;
import imj.apps.modules.FilteredImage.Filter;
import imj.apps.modules.FilteredImage.StructuringElementFilter;
import imj.apps.modules.ViewFilter.Channel.Primitive;
import imj.apps.modules.ViewFilter.Channel.Synthetic;
import java.awt.Color;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Locale;
import net.sourceforge.aprog.context.Context;
import net.sourceforge.aprog.events.Variable;
import net.sourceforge.aprog.events.Variable.Listener;
import net.sourceforge.aprog.events.Variable.ValueChangedEvent;
/**
* @author codistmonk (creation 2013-02-18)
*/
public abstract class ViewFilter extends Plugin implements Filter {
/**
* @author codistmonk (creation 2013-03-07)
*/
public final class ComplexFilter {
private Collection<Channel> inputChannels;
private Class<? extends Channel> inputChannelClass;
private final int[] buffer;
public ComplexFilter() {
this.buffer = new int[4];
this.inputChannelClass = Primitive.class;
}
public final Collection<Channel> getInputChannels() {
return this.inputChannels;
}
public final void setInputChannels(final Collection<Channel> inputChannels) {
this.inputChannels = inputChannels;
}
public final Class<? extends Channel> getInputChannelClass() {
return this.inputChannelClass;
}
public final void setInputChannelClass(final Class<? extends Channel> inputChannelClass) {
this.inputChannelClass = inputChannelClass;
}
public final int[] getBuffer() {
return this.buffer;
}
public final int getNewValue(final int index, final int oldValue) {
if (!ViewFilter.this.splitInputChannels()) {
return ViewFilter.this.getNewValue(index, oldValue, Channel.Primitive.INT);
}
if (this.getInputChannelClass() == Primitive.class) {
for (int i = 0; i < 4; ++i) {
this.getBuffer()[i] = channelValue(oldValue, i);
}
int value = 0;
for (final Channel channel : this.getInputChannels()) {
value = max(0, min(255, ViewFilter.this.getNewValue(index, oldValue, channel)));
this.getBuffer()[channel.getIndex()] = value;
}
if (ViewFilter.this.isOutputMonochannel() && this.getInputChannels().size() == 1) {
return argb(255, value, value, value);
}
return argb(this.getBuffer()[ALPHA.getIndex()],
this.getBuffer()[RED.getIndex()], this.getBuffer()[GREEN.getIndex()], this.getBuffer()[BLUE.getIndex()]);
} else if (this.getInputChannelClass() == Synthetic.class) {
this.getBuffer()[0] = hue(oldValue);
this.getBuffer()[1] = saturation(oldValue);
this.getBuffer()[2] = brightness(oldValue);
int value = 0;
for (final Channel channel : this.getInputChannels()) {
value = max(0, min(255, ViewFilter.this.getNewValue(index, oldValue, channel)));
this.getBuffer()[channel.getIndex()] = value;
}
if (ViewFilter.this.isOutputMonochannel() && this.getInputChannels().size() == 1) {
return argb(255, value, value, value);
}
return Color.HSBtoRGB(this.getBuffer()[HUE.getIndex()] / 255F,
this.getBuffer()[SATURATION.getIndex()] / 255F, this.getBuffer()[BRIGHTNESS.getIndex()] / 255F);
}
return 0;
}
}
private final ComplexFilter complexFilter;
private ViewFilter backup;
private boolean backingUp;
protected ViewFilter(final Context context) {
super(context);
this.complexFilter = this.new ComplexFilter();
this.getParameters().put(PARAMETER_CHANNELS, "red green blue");
context.getVariable("image").addListener(new Listener<Object>() {
@Override
public final void valueChanged(final ValueChangedEvent<Object, ?> event) {
if (event.getOldValue() == event.getNewValue()) {
return;
}
final boolean thisViewFilterIsApplying = context.get("viewFilter") == ViewFilter.this;
if (thisViewFilterIsApplying) {
ViewFilter.this.cancel();
}
if (ViewFilter.this.isBackingUp()) {
ViewFilter.this.clearBackup();
ViewFilter.this.backup();
}
if (thisViewFilterIsApplying) {
ViewFilter.this.initialize();
ViewFilter.this.apply();
}
}
});
}
protected boolean isOutputMonochannel() {
return false;
}
@Override
public final int getNewValue(final int index, final int oldValue) {
return this.complexFilter.getNewValue(index, oldValue);
}
public abstract int getNewValue(final int index, final int oldValue, final Channel channel);
public final void initialize() {
if (this.splitInputChannels()) {
final String[] inputChannelAsStrings = this.getParameters().get(PARAMETER_CHANNELS).split("\\s+");
final int n = inputChannelAsStrings.length;
final Collection<Channel> newInputChannels = new LinkedHashSet<Channel>();
Class<? extends Channel> newInputChannelClass = Channel.class;
for (int i = 0; i < n; ++i) {
final Channel channel = parseChannel(inputChannelAsStrings[i].toUpperCase());
if (!newInputChannelClass.isAssignableFrom(channel.getClass())) {
debugPrint(newInputChannelClass, channel.getClass());
throw new IllegalArgumentException("All input channels must be of the same type (primitive xor synthetic)");
}
newInputChannels.add(channel);
newInputChannelClass = (Class<? extends Channel>) channel.getClass().getSuperclass();
}
this.complexFilter.setInputChannels(newInputChannels);
this.complexFilter.setInputChannelClass(newInputChannelClass);
} else {
this.complexFilter.setInputChannels(null);
this.complexFilter.setInputChannelClass(null);
}
this.doInitialize();
}
protected void doInitialize() {
// NOP
}
@Override
public final void apply() {
final Context context = this.getContext();
context.set("viewFilter", null);
context.set("viewFilter", this);
fireUpdate(this.getContext(), "image");
}
@Override
public final void backup() {
this.backup = this.getContext().get("viewFilter");
this.backingUp = true;
}
@Override
public final void cancel() {
this.getContext().set("viewFilter", this.backup);
fireUpdate(this.getContext(), "image");
}
@Override
public final void clearBackup() {
this.backup = null;
this.backingUp = false;
}
public final boolean isBackingUp() {
return this.backingUp;
}
protected boolean splitInputChannels() {
return true;
}
/**
* @author codistmonk (creation 2013-02-20)
*/
public static interface Channel {
public abstract int getIndex();
public abstract int getValue(final int rgba);
/**
* @author codistmonk (creation 2013-02-20)
*/
public static enum Primitive implements Channel {
RED {
@Override
public final int getIndex() {
return 0;
}
@Override
public final int getValue(final int rgba) {
return red(rgba);
}
}, GREEN {
@Override
public final int getIndex() {
return 1;
}
@Override
public final int getValue(final int rgba) {
return green(rgba);
}
}, BLUE {
@Override
public final int getIndex() {
return 2;
}
@Override
public final int getValue(final int rgba) {
return blue(rgba);
}
}, ALPHA {
@Override
public final int getIndex() {
return 3;
}
@Override
public final int getValue(final int rgba) {
return alpha(rgba);
}
}, INT {
@Override
public final int getIndex() {
return 0;
}
@Override
public final int getValue(final int rgba) {
return rgba;
}
};
}
/**
* @author codistmonk (creation 2013-02-20)
*/
public static enum Synthetic implements Channel {
HUE {
@Override
public final int getIndex() {
return 0;
}
@Override
public final int getValue(final int rgba) {
return hue(rgba);
}
}, SATURATION {
@Override
public final int getIndex() {
return 1;
}
@Override
public final int getValue(final int rgba) {
return saturation(rgba);
}
}, BRIGHTNESS {
@Override
public final int getIndex() {
return 2;
}
@Override
public final int getValue(final int rgba) {
return brightness(rgba);
}
};
}
}
/**
* {@value}.
*/
public static final String PARAMETER_CHANNELS = "channels";
public static final Channel parseChannel(final String string) {
try {
return Channel.Primitive.valueOf(string);
} catch (final Exception exception) {
ignore(exception);
return Channel.Synthetic.valueOf(string);
}
}
public static final int[] parseStructuringElement(final String structuringElementParametersAsString) {
final String[] structuringElementParameters = structuringElementParametersAsString.trim().split("\\s+");
final String shape = structuringElementParameters[0];
if ("ring".equals(shape)) {
final double innerRadius = parseDouble(structuringElementParameters[1]);
final double outerRadius = parseDouble(structuringElementParameters[2]);
final Distance distance = Distance.valueOf(structuringElementParameters[3].toUpperCase(Locale.ENGLISH));
return newRing(innerRadius, outerRadius, distance);
}
if ("disk".equals(shape)) {
final double radius = parseDouble(structuringElementParameters[1]);
final Distance distance = Distance.valueOf(structuringElementParameters[2].toUpperCase(Locale.ENGLISH));
return newDisk(radius, distance);
}
throw new IllegalArgumentException("Invalid structuring element shape: " + shape);
}
/**
* @author codistmonk (creation 2013-02-19)
*/
public static abstract class FromFilter extends ViewFilter {
private ChannelFilter filter;
protected FromFilter(final Context context) {
super(context);
this.getParameters().put("structuringElement", "disk 1 chessboard");
final Variable<Image> imageVariable = context.getVariable("image");
imageVariable.addListener(new Listener<Image>() {
@Override
public final void valueChanged(final ValueChangedEvent<Image, ?> event) {
FromFilter.this.setFilter(FromFilter.this.getFilter());
}
});
}
public final ChannelFilter getFilter() {
return this.filter;
}
public final void setFilter(final ChannelFilter filter) {
this.filter = filter;
if (filter instanceof StructuringElementFilter) {
final Image image = this.getContext().get("image");
final FilteredImage filteredImage = cast(FilteredImage.class, image);
((StructuringElementFilter) filter).setImage(filteredImage != null ? filteredImage.getSource() : image);
}
}
@Override
public final int getNewValue(final int index, final int oldValue, final Channel channel) {
return this.getFilter().getNewValue(index, oldValue, channel);
}
public final int[] parseStructuringElement() {
return ViewFilter.parseStructuringElement(this.getParameters().get("structuringElement"));
}
}
}
| IMJ/src/imj/apps/modules/ViewFilter.java | package imj.apps.modules;
import static imj.IMJTools.alpha;
import static imj.IMJTools.argb;
import static imj.IMJTools.blue;
import static imj.IMJTools.brightness;
import static imj.IMJTools.channelValue;
import static imj.IMJTools.green;
import static imj.IMJTools.hue;
import static imj.IMJTools.red;
import static imj.IMJTools.saturation;
import static imj.MorphologicalOperations.StructuringElement.newDisk;
import static imj.MorphologicalOperations.StructuringElement.newRing;
import static imj.apps.modules.ViewFilter.Channel.Primitive.ALPHA;
import static imj.apps.modules.ViewFilter.Channel.Primitive.BLUE;
import static imj.apps.modules.ViewFilter.Channel.Primitive.GREEN;
import static imj.apps.modules.ViewFilter.Channel.Primitive.RED;
import static imj.apps.modules.ViewFilter.Channel.Synthetic.BRIGHTNESS;
import static imj.apps.modules.ViewFilter.Channel.Synthetic.HUE;
import static imj.apps.modules.ViewFilter.Channel.Synthetic.SATURATION;
import static java.lang.Double.parseDouble;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static net.sourceforge.aprog.af.AFTools.fireUpdate;
import static net.sourceforge.aprog.tools.Tools.cast;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import static net.sourceforge.aprog.tools.Tools.ignore;
import imj.Image;
import imj.Labeling.NeighborhoodShape.Distance;
import imj.apps.modules.FilteredImage.ChannelFilter;
import imj.apps.modules.FilteredImage.Filter;
import imj.apps.modules.FilteredImage.StructuringElementFilter;
import imj.apps.modules.ViewFilter.Channel.Primitive;
import imj.apps.modules.ViewFilter.Channel.Synthetic;
import java.awt.Color;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Locale;
import net.sourceforge.aprog.context.Context;
import net.sourceforge.aprog.events.Variable;
import net.sourceforge.aprog.events.Variable.Listener;
import net.sourceforge.aprog.events.Variable.ValueChangedEvent;
/**
* @author codistmonk (creation 2013-02-18)
*/
public abstract class ViewFilter extends Plugin implements Filter {
/**
* @author codistmonk (creation 2013-03-07)
*/
public static final class ComplexFilter {
private Collection<Channel> inputChannels;
private Class<? extends Channel> inputChannelClass;
private final int[] buffer;
public ComplexFilter() {
this.buffer = new int[4];
this.inputChannelClass = Primitive.class;
}
public final Collection<Channel> getInputChannels() {
return this.inputChannels;
}
public final void setInputChannels(final Collection<Channel> inputChannels) {
this.inputChannels = inputChannels;
}
public final Class<? extends Channel> getInputChannelClass() {
return this.inputChannelClass;
}
public final void setInputChannelClass(final Class<? extends Channel> inputChannelClass) {
this.inputChannelClass = inputChannelClass;
}
public final int[] getBuffer() {
return this.buffer;
}
}
private final ComplexFilter complexFilter;
private ViewFilter backup;
private boolean backingUp;
protected ViewFilter(final Context context) {
super(context);
this.complexFilter = new ComplexFilter();
this.getParameters().put(PARAMETER_CHANNELS, "red green blue");
context.getVariable("image").addListener(new Listener<Object>() {
@Override
public final void valueChanged(final ValueChangedEvent<Object, ?> event) {
if (event.getOldValue() == event.getNewValue()) {
return;
}
final boolean thisViewFilterIsApplying = context.get("viewFilter") == ViewFilter.this;
if (thisViewFilterIsApplying) {
ViewFilter.this.cancel();
}
if (ViewFilter.this.isBackingUp()) {
ViewFilter.this.clearBackup();
ViewFilter.this.backup();
}
if (thisViewFilterIsApplying) {
ViewFilter.this.initialize();
ViewFilter.this.apply();
}
}
});
}
protected boolean isOutputMonochannel() {
return false;
}
@Override
public final int getNewValue(final int index, final int oldValue) {
if (!this.splitInputChannels()) {
return this.getNewValue(index, oldValue, Channel.Primitive.INT);
}
if (this.complexFilter.getInputChannelClass() == Primitive.class) {
for (int i = 0; i < 4; ++i) {
this.complexFilter.getBuffer()[i] = channelValue(oldValue, i);
}
int value = 0;
for (final Channel channel : this.complexFilter.getInputChannels()) {
value = max(0, min(255, this.getNewValue(index, oldValue, channel)));
this.complexFilter.getBuffer()[channel.getIndex()] = value;
}
if (this.isOutputMonochannel() && this.complexFilter.getInputChannels().size() == 1) {
return argb(255, value, value, value);
}
return argb(this.complexFilter.getBuffer()[ALPHA.getIndex()],
this.complexFilter.getBuffer()[RED.getIndex()], this.complexFilter.getBuffer()[GREEN.getIndex()], this.complexFilter.getBuffer()[BLUE.getIndex()]);
} else if (this.complexFilter.getInputChannelClass() == Synthetic.class) {
this.complexFilter.getBuffer()[0] = hue(oldValue);
this.complexFilter.getBuffer()[1] = saturation(oldValue);
this.complexFilter.getBuffer()[2] = brightness(oldValue);
int value = 0;
for (final Channel channel : this.complexFilter.getInputChannels()) {
value = max(0, min(255, this.getNewValue(index, oldValue, channel)));
this.complexFilter.getBuffer()[channel.getIndex()] = value;
}
if (this.isOutputMonochannel() && this.complexFilter.getInputChannels().size() == 1) {
return argb(255, value, value, value);
}
return Color.HSBtoRGB(this.complexFilter.getBuffer()[HUE.getIndex()] / 255F,
this.complexFilter.getBuffer()[SATURATION.getIndex()] / 255F, this.complexFilter.getBuffer()[BRIGHTNESS.getIndex()] / 255F);
}
return 0;
}
public abstract int getNewValue(final int index, final int oldValue, final Channel channel);
public final void initialize() {
if (this.splitInputChannels()) {
final String[] inputChannelAsStrings = this.getParameters().get(PARAMETER_CHANNELS).split("\\s+");
final int n = inputChannelAsStrings.length;
final Collection<Channel> newInputChannels = new LinkedHashSet<Channel>();
Class<? extends Channel> newInputChannelClass = Channel.class;
for (int i = 0; i < n; ++i) {
final Channel channel = parseChannel(inputChannelAsStrings[i].toUpperCase());
if (!newInputChannelClass.isAssignableFrom(channel.getClass())) {
debugPrint(newInputChannelClass, channel.getClass());
throw new IllegalArgumentException("All input channels must be of the same type (primitive xor synthetic)");
}
newInputChannels.add(channel);
newInputChannelClass = (Class<? extends Channel>) channel.getClass().getSuperclass();
}
this.complexFilter.setInputChannels(newInputChannels);
this.complexFilter.setInputChannelClass(newInputChannelClass);
} else {
this.complexFilter.setInputChannels(null);
this.complexFilter.setInputChannelClass(null);
}
this.doInitialize();
}
protected void doInitialize() {
// NOP
}
@Override
public final void apply() {
final Context context = this.getContext();
context.set("viewFilter", null);
context.set("viewFilter", this);
fireUpdate(this.getContext(), "image");
}
@Override
public final void backup() {
this.backup = this.getContext().get("viewFilter");
this.backingUp = true;
}
@Override
public final void cancel() {
this.getContext().set("viewFilter", this.backup);
fireUpdate(this.getContext(), "image");
}
@Override
public final void clearBackup() {
this.backup = null;
this.backingUp = false;
}
public final boolean isBackingUp() {
return this.backingUp;
}
protected boolean splitInputChannels() {
return true;
}
/**
* @author codistmonk (creation 2013-02-20)
*/
public static interface Channel {
public abstract int getIndex();
public abstract int getValue(final int rgba);
/**
* @author codistmonk (creation 2013-02-20)
*/
public static enum Primitive implements Channel {
RED {
@Override
public final int getIndex() {
return 0;
}
@Override
public final int getValue(final int rgba) {
return red(rgba);
}
}, GREEN {
@Override
public final int getIndex() {
return 1;
}
@Override
public final int getValue(final int rgba) {
return green(rgba);
}
}, BLUE {
@Override
public final int getIndex() {
return 2;
}
@Override
public final int getValue(final int rgba) {
return blue(rgba);
}
}, ALPHA {
@Override
public final int getIndex() {
return 3;
}
@Override
public final int getValue(final int rgba) {
return alpha(rgba);
}
}, INT {
@Override
public final int getIndex() {
return 0;
}
@Override
public final int getValue(final int rgba) {
return rgba;
}
};
}
/**
* @author codistmonk (creation 2013-02-20)
*/
public static enum Synthetic implements Channel {
HUE {
@Override
public final int getIndex() {
return 0;
}
@Override
public final int getValue(final int rgba) {
return hue(rgba);
}
}, SATURATION {
@Override
public final int getIndex() {
return 1;
}
@Override
public final int getValue(final int rgba) {
return saturation(rgba);
}
}, BRIGHTNESS {
@Override
public final int getIndex() {
return 2;
}
@Override
public final int getValue(final int rgba) {
return brightness(rgba);
}
};
}
}
/**
* {@value}.
*/
public static final String PARAMETER_CHANNELS = "channels";
public static final Channel parseChannel(final String string) {
try {
return Channel.Primitive.valueOf(string);
} catch (final Exception exception) {
ignore(exception);
return Channel.Synthetic.valueOf(string);
}
}
public static final int[] parseStructuringElement(final String structuringElementParametersAsString) {
final String[] structuringElementParameters = structuringElementParametersAsString.trim().split("\\s+");
final String shape = structuringElementParameters[0];
if ("ring".equals(shape)) {
final double innerRadius = parseDouble(structuringElementParameters[1]);
final double outerRadius = parseDouble(structuringElementParameters[2]);
final Distance distance = Distance.valueOf(structuringElementParameters[3].toUpperCase(Locale.ENGLISH));
return newRing(innerRadius, outerRadius, distance);
}
if ("disk".equals(shape)) {
final double radius = parseDouble(structuringElementParameters[1]);
final Distance distance = Distance.valueOf(structuringElementParameters[2].toUpperCase(Locale.ENGLISH));
return newDisk(radius, distance);
}
throw new IllegalArgumentException("Invalid structuring element shape: " + shape);
}
/**
* @author codistmonk (creation 2013-02-19)
*/
public static abstract class FromFilter extends ViewFilter {
private ChannelFilter filter;
protected FromFilter(final Context context) {
super(context);
this.getParameters().put("structuringElement", "disk 1 chessboard");
final Variable<Image> imageVariable = context.getVariable("image");
imageVariable.addListener(new Listener<Image>() {
@Override
public final void valueChanged(final ValueChangedEvent<Image, ?> event) {
FromFilter.this.setFilter(FromFilter.this.getFilter());
}
});
}
public final ChannelFilter getFilter() {
return this.filter;
}
public final void setFilter(final ChannelFilter filter) {
this.filter = filter;
if (filter instanceof StructuringElementFilter) {
final Image image = this.getContext().get("image");
final FilteredImage filteredImage = cast(FilteredImage.class, image);
((StructuringElementFilter) filter).setImage(filteredImage != null ? filteredImage.getSource() : image);
}
}
@Override
public final int getNewValue(final int index, final int oldValue, final Channel channel) {
return this.getFilter().getNewValue(index, oldValue, channel);
}
public final int[] parseStructuringElement() {
return ViewFilter.parseStructuringElement(this.getParameters().get("structuringElement"));
}
}
}
| [IMJ]
Refactoring.
| IMJ/src/imj/apps/modules/ViewFilter.java | [IMJ] Refactoring. | <ide><path>MJ/src/imj/apps/modules/ViewFilter.java
<ide> /**
<ide> * @author codistmonk (creation 2013-03-07)
<ide> */
<del> public static final class ComplexFilter {
<add> public final class ComplexFilter {
<ide>
<ide> private Collection<Channel> inputChannels;
<ide>
<ide> return this.buffer;
<ide> }
<ide>
<add> public final int getNewValue(final int index, final int oldValue) {
<add> if (!ViewFilter.this.splitInputChannels()) {
<add> return ViewFilter.this.getNewValue(index, oldValue, Channel.Primitive.INT);
<add> }
<add>
<add> if (this.getInputChannelClass() == Primitive.class) {
<add> for (int i = 0; i < 4; ++i) {
<add> this.getBuffer()[i] = channelValue(oldValue, i);
<add> }
<add>
<add> int value = 0;
<add>
<add> for (final Channel channel : this.getInputChannels()) {
<add> value = max(0, min(255, ViewFilter.this.getNewValue(index, oldValue, channel)));
<add> this.getBuffer()[channel.getIndex()] = value;
<add> }
<add>
<add> if (ViewFilter.this.isOutputMonochannel() && this.getInputChannels().size() == 1) {
<add> return argb(255, value, value, value);
<add> }
<add>
<add> return argb(this.getBuffer()[ALPHA.getIndex()],
<add> this.getBuffer()[RED.getIndex()], this.getBuffer()[GREEN.getIndex()], this.getBuffer()[BLUE.getIndex()]);
<add> } else if (this.getInputChannelClass() == Synthetic.class) {
<add> this.getBuffer()[0] = hue(oldValue);
<add> this.getBuffer()[1] = saturation(oldValue);
<add> this.getBuffer()[2] = brightness(oldValue);
<add>
<add> int value = 0;
<add>
<add> for (final Channel channel : this.getInputChannels()) {
<add> value = max(0, min(255, ViewFilter.this.getNewValue(index, oldValue, channel)));
<add> this.getBuffer()[channel.getIndex()] = value;
<add> }
<add>
<add> if (ViewFilter.this.isOutputMonochannel() && this.getInputChannels().size() == 1) {
<add> return argb(255, value, value, value);
<add> }
<add>
<add> return Color.HSBtoRGB(this.getBuffer()[HUE.getIndex()] / 255F,
<add> this.getBuffer()[SATURATION.getIndex()] / 255F, this.getBuffer()[BRIGHTNESS.getIndex()] / 255F);
<add> }
<add>
<add> return 0;
<add> }
<add>
<ide> }
<ide>
<ide> private final ComplexFilter complexFilter;
<ide>
<ide> protected ViewFilter(final Context context) {
<ide> super(context);
<del> this.complexFilter = new ComplexFilter();
<add> this.complexFilter = this.new ComplexFilter();
<ide>
<ide> this.getParameters().put(PARAMETER_CHANNELS, "red green blue");
<ide>
<ide>
<ide> @Override
<ide> public final int getNewValue(final int index, final int oldValue) {
<del> if (!this.splitInputChannels()) {
<del> return this.getNewValue(index, oldValue, Channel.Primitive.INT);
<del> }
<del>
<del> if (this.complexFilter.getInputChannelClass() == Primitive.class) {
<del> for (int i = 0; i < 4; ++i) {
<del> this.complexFilter.getBuffer()[i] = channelValue(oldValue, i);
<del> }
<del>
<del> int value = 0;
<del>
<del> for (final Channel channel : this.complexFilter.getInputChannels()) {
<del> value = max(0, min(255, this.getNewValue(index, oldValue, channel)));
<del> this.complexFilter.getBuffer()[channel.getIndex()] = value;
<del> }
<del>
<del> if (this.isOutputMonochannel() && this.complexFilter.getInputChannels().size() == 1) {
<del> return argb(255, value, value, value);
<del> }
<del>
<del> return argb(this.complexFilter.getBuffer()[ALPHA.getIndex()],
<del> this.complexFilter.getBuffer()[RED.getIndex()], this.complexFilter.getBuffer()[GREEN.getIndex()], this.complexFilter.getBuffer()[BLUE.getIndex()]);
<del> } else if (this.complexFilter.getInputChannelClass() == Synthetic.class) {
<del> this.complexFilter.getBuffer()[0] = hue(oldValue);
<del> this.complexFilter.getBuffer()[1] = saturation(oldValue);
<del> this.complexFilter.getBuffer()[2] = brightness(oldValue);
<del>
<del> int value = 0;
<del>
<del> for (final Channel channel : this.complexFilter.getInputChannels()) {
<del> value = max(0, min(255, this.getNewValue(index, oldValue, channel)));
<del> this.complexFilter.getBuffer()[channel.getIndex()] = value;
<del> }
<del>
<del> if (this.isOutputMonochannel() && this.complexFilter.getInputChannels().size() == 1) {
<del> return argb(255, value, value, value);
<del> }
<del>
<del> return Color.HSBtoRGB(this.complexFilter.getBuffer()[HUE.getIndex()] / 255F,
<del> this.complexFilter.getBuffer()[SATURATION.getIndex()] / 255F, this.complexFilter.getBuffer()[BRIGHTNESS.getIndex()] / 255F);
<del> }
<del>
<del> return 0;
<add> return this.complexFilter.getNewValue(index, oldValue);
<ide> }
<ide>
<ide> public abstract int getNewValue(final int index, final int oldValue, final Channel channel); |
|
JavaScript | mit | 1711a698ead6dc33f4e5170b98ef25758089636f | 0 | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | const Exchange = require ('./base/Exchange');
const { TICK_SIZE } = require ('./base/functions/number');
const Precise = require ('./base/Precise');
const { BadSymbol, BadRequest, OnMaintenance, AccountSuspended, PermissionDenied, ExchangeError, RateLimitExceeded, ExchangeNotAvailable, OrderNotFound, InsufficientFunds, InvalidOrder, AuthenticationError } = require ('./base/errors');
module.exports = class hitbtc3 extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'hitbtc3',
'name': 'HitBTC',
'countries': [ 'HK' ],
'rateLimit': 100, // TODO: optimize https://api.hitbtc.com/#rate-limiting
'version': '3',
'pro': true,
'has': {
'cancelOrder': true,
'CORS': false,
'createOrder': true,
'editOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDeposits': false,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrder': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': false,
'fetchOrderTrades': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTrades': true,
'fetchTradingFee': true,
'fetchTransactions': true,
'fetchWithdrawals': false,
'withdraw': true,
'transfer': true,
},
'precisionMode': TICK_SIZE,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'test': {
'public': 'https://api.demo.hitbtc.com',
'private': 'https://api.demo.hitbtc.com',
},
'api': {
'public': 'https://api.hitbtc.com/api/3',
'private': 'https://api.hitbtc.com/api/3',
},
'www': 'https://hitbtc.com',
'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
'doc': [
'https://api.hitbtc.com',
'https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md',
],
'fees': [
'https://hitbtc.com/fees-and-limits',
'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
],
},
'api': {
'public': {
'get': [
'public/currency',
'public/symbol',
'public/ticker',
'public/price/rate',
'public/trades',
'public/orderbook',
'public/candles',
'public/futures/info',
'public/futures/history/funding',
'public/futures/candles/index_price',
'public/futures/candles/mark_price',
'public/futures/candles/premium_index',
'public/futures/candles/open_interest',
],
},
'private': {
'get': [
'spot/balance',
'spot/order',
'spot/order/{client_order_id}',
'spot/fee',
'spot/fee/{symbol}',
'spot/history/order',
'spot/history/trade',
'margin/account',
'margin/account/isolated/{symbol}',
'margin/order',
'margin/order/{client_order_id}',
'margin/history/order',
'margin/history/trade',
'futures/balance',
'futures/account',
'futures/account/isolated/{symbol}',
'futures/order',
'futures/order/{client_order_id}',
'futures/fee',
'futures/fee/{symbol}',
'futures/history/order',
'futures/history/trade',
'wallet/balance',
'wallet/crypto/address',
'wallet/crypto/address/recent-deposit',
'wallet/crypto/address/recent-withdraw',
'wallet/crypto/address/check-mine',
'wallet/transactions',
'wallet/crypto/check-offchain-available',
'wallet/crypto/fee/estimate',
'sub-account',
'sub-account/acl',
'sub-account/balance/{subAccID}',
'sub-account/crypto/address/{subAccID}/{currency}',
],
'post': [
'spot/order',
'margin/order',
'futures/order',
'wallet/convert',
'wallet/crypto/withdraw',
'wallet/transfer',
'sub-account/freeze',
'sub-account/activate',
'sub-account/transfer',
'sub-account/acl',
],
'patch': [
'spot/order/{client_order_id}',
'margin/order/{client_order_id}',
'futures/order/{client_order_id}',
],
'delete': [
'spot/order',
'spot/order/{client_order_id}',
'margin/position',
'margin/position/isolated/{symbol}',
'margin/order',
'margin/order/{client_order_id}',
'futures/position',
'futures/position/isolated/{symbol}',
'futures/order',
'futures/order/{client_order_id}',
'wallet/crypto/withdraw/{id}',
],
'put': [
'margin/account/isolated/{symbol}',
'futures/account/isolated/{symbol}',
'wallet/crypto/withdraw/{id}',
],
},
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0009'),
'maker': this.parseNumber ('0.0009'),
'tiers': {
'maker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0002') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0001') ],
[ this.parseNumber ('20000'), this.parseNumber ('0') ],
[ this.parseNumber ('50000'), this.parseNumber ('-0.0001') ],
[ this.parseNumber ('100000'), this.parseNumber ('-0.0001') ],
],
'taker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0008') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('20000'), this.parseNumber ('0.0004') ],
[ this.parseNumber ('50000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('100000'), this.parseNumber ('0.0002') ],
],
},
},
},
'timeframes': {
'1m': 'M1',
'3m': 'M3',
'5m': 'M5',
'15m': 'M15',
'30m': 'M30', // default
'1h': 'H1',
'4h': 'H4',
'1d': 'D1',
'1w': 'D7',
'1M': '1M',
},
'exceptions': {
'429': RateLimitExceeded,
'500': ExchangeError,
'503': ExchangeNotAvailable,
'504': ExchangeNotAvailable,
'600': PermissionDenied,
'800': ExchangeError,
'1002': AuthenticationError,
'1003': PermissionDenied,
'1004': AuthenticationError,
'1005': AuthenticationError,
'2001': BadSymbol,
'2002': BadRequest,
'2003': BadRequest,
'2010': BadRequest,
'2011': BadRequest,
'2012': BadRequest,
'2020': BadRequest,
'2022': BadRequest,
'10001': BadRequest,
'10021': AccountSuspended,
'10022': BadRequest,
'20001': InsufficientFunds,
'20002': OrderNotFound,
'20003': ExchangeError,
'20004': ExchangeError,
'20005': ExchangeError,
'20006': ExchangeError,
'20007': ExchangeError,
'20008': InvalidOrder,
'20009': InvalidOrder,
'20010': OnMaintenance,
'20011': ExchangeError,
'20012': ExchangeError,
'20014': ExchangeError,
'20016': ExchangeError,
'20031': ExchangeError,
'20032': ExchangeError,
'20033': ExchangeError,
'20034': ExchangeError,
'20040': ExchangeError,
'20041': ExchangeError,
'20042': ExchangeError,
'20043': ExchangeError,
'20044': PermissionDenied,
'20045': ExchangeError,
'20080': ExchangeError,
'21001': ExchangeError,
'21003': AccountSuspended,
'21004': AccountSuspended,
},
'options': {
'networks': {
'ETH': '20',
'ERC20': '20',
'TRX': 'RX',
'TRC20': 'RX',
'OMNI': '',
},
'accountsByType': {
'spot': 'spot',
'wallet': 'wallet',
'derivatives': 'derivatives',
},
},
});
}
nonce () {
return this.milliseconds ();
}
async fetchMarkets (params = {}) {
const request = {};
const response = await this.publicGetPublicSymbol (this.extend (request, params));
//
// fetches both spot and future markets
//
// {
// "ETHBTC": {
// "type": "spot",
// "base_currency": "ETH",
// "quote_currency": "BTC",
// "quantity_increment": "0.001",
// "tick_size": "0.000001",
// "take_rate": "0.001",
// "make_rate": "-0.0001",
// "fee_currency": "BTC",
// "margin_trading": true,
// "max_initial_leverage": "10.00"
// }
// }
//
const marketIds = Object.keys (response);
const result = [];
for (let i = 0; i < marketIds.length; i++) {
const id = marketIds[i];
const entry = response[id];
const baseId = this.safeString (entry, 'base_currency');
const quoteId = this.safeString (entry, 'quote_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const maker = this.safeNumber (entry, 'make_rate');
const taker = this.safeNumber (entry, 'take_rate');
const feeCurrency = this.safeString (entry, 'fee_currency');
const feeSide = (feeCurrency === quoteId) ? 'quote' : 'base';
const margin = this.safeValue (entry, 'margin_trading', false);
const type = this.safeString (entry, 'type');
const spot = (type === 'spot');
const futures = (type === 'futures');
const priceIncrement = this.safeNumber (entry, 'tick_size');
const amountIncrement = this.safeNumber (entry, 'quantity_increment');
const precision = {
'price': priceIncrement,
'amount': amountIncrement,
};
const limits = {
'amount': {
'min': undefined,
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': undefined,
'max': undefined,
},
};
result.push ({
'info': entry,
'symbol': symbol,
'id': id,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'spot': spot,
'margin': margin,
'futures': futures,
'type': type,
'feeSide': feeSide,
'maker': maker,
'taker': taker,
'precision': precision,
'limits': limits,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.publicGetPublicCurrency (params);
//
// {
// "WEALTH": {
// "full_name": "ConnectWealth",
// "payin_enabled": false,
// "payout_enabled": false,
// "transfer_enabled": true,
// "precision_transfer": "0.001",
// "networks": [
// {
// "network": "ETH",
// "protocol": "ERC20",
// "default": true,
// "payin_enabled": false,
// "payout_enabled": false,
// "precision_payout": "0.001",
// "payout_fee": "0.016800000000",
// "payout_is_payment_id": false,
// "payin_payment_id": false,
// "payin_confirmations": "2"
// }
// ]
// }
// }
//
const result = {};
const currencies = Object.keys (response);
for (let i = 0; i < currencies.length; i++) {
const currencyId = currencies[i];
const code = this.safeCurrencyCode (currencyId);
const entry = response[currencyId];
const name = this.safeString (entry, 'full_name');
const precision = this.safeNumber (entry, 'precision_transfer');
const payinEnabled = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabled = this.safeValue (entry, 'payout_enabled', false);
const transferEnabled = this.safeValue (entry, 'transfer_enabled', false);
const active = payinEnabled && payoutEnabled && transferEnabled;
const rawNetworks = this.safeValue (entry, 'networks', []);
const networks = {};
let fee = undefined;
for (let j = 0; j < rawNetworks.length; j++) {
const rawNetwork = rawNetworks[j];
let networkId = this.safeString (rawNetwork, 'protocol');
if (networkId.length === 0) {
networkId = this.safeString (rawNetwork, 'network');
}
const network = this.safeNetwork (networkId);
fee = this.safeNumber (rawNetwork, 'payout_fee');
const precision = this.safeNumber (rawNetwork, 'precision_payout');
const payinEnabledNetwork = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabledNetwork = this.safeValue (entry, 'payout_enabled', false);
const transferEnabledNetwork = this.safeValue (entry, 'transfer_enabled', false);
const active = payinEnabledNetwork && payoutEnabledNetwork && transferEnabledNetwork;
networks[network] = {
'info': rawNetwork,
'id': networkId,
'network': network,
'fee': fee,
'active': active,
'precision': precision,
'limits': {
'withdraw': {
'min': undefined,
'max': undefined,
},
},
};
}
const networksKeys = Object.keys (networks);
const networksLength = networksKeys.length;
result[code] = {
'info': entry,
'code': code,
'id': currencyId,
'precision': precision,
'name': name,
'active': active,
'networks': networks,
'fee': (networksLength <= 1) ? fee : undefined,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
},
};
}
return result;
}
safeNetwork (networkId) {
const networksById = {
};
return this.safeString (networksById, networkId, networkId);
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const network = this.safeString (params, 'network');
if ((network !== undefined) && (code === 'USDT')) {
params = this.omit (params, 'network');
const networks = this.safeValue (this.options, 'networks');
const endpart = this.safeString (networks, network, network);
request['currency'] += endpart;
}
const response = await this.privateGetWalletCryptoAddress (this.extend (request, params));
//
// [{"currency":"ETH","address":"0xd0d9aea60c41988c3e68417e2616065617b7afd3"}]
//
const firstAddress = this.safeValue (response, 0);
const address = this.safeString (firstAddress, 'address');
const currencyId = this.safeString (firstAddress, 'currency');
const tag = this.safeString (firstAddress, 'payment_id');
const parsedCode = this.safeCurrencyCode (currencyId);
return {
'info': response,
'address': address,
'tag': tag,
'code': parsedCode,
};
}
async fetchBalance (params) {
const response = await this.privateGetSpotBalance ();
//
// [
// {
// "currency": "PAXG",
// "available": "0",
// "reserved": "0",
// "reserved_margin": "0",
// },
// ...
// ]
//
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const currencyId = this.safeString (entry, 'currency');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (entry, 'available');
account['used'] = this.safeString (entry, 'reserved');
result[code] = account;
}
return this.parseBalance (result);
}
async fetchTicker (symbol, params = {}) {
const response = await this.fetchTickers ([ symbol ], params);
return this.safeValue (response, symbol);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
const delimited = marketIds.join (',');
request['symbols'] = delimited;
}
const response = await this.publicGetPublicTicker (this.extend (request, params));
//
// {
// "BTCUSDT": {
// "ask": "63049.06",
// "bid": "63046.41",
// "last": "63048.36",
// "low": "62010.00",
// "high": "66657.99",
// "open": "64839.75",
// "volume": "15272.13278",
// "volume_quote": "976312127.6277998",
// "timestamp": "2021-10-22T04:25:47.573Z"
// }
// }
//
const result = {};
const keys = Object.keys (response);
for (let i = 0; i < keys.length; i++) {
const marketId = keys[i];
const market = this.safeMarket (marketId);
const symbol = market['symbol'];
const entry = response[marketId];
result[symbol] = this.parseTicker (entry, market);
}
return this.filterByArray (result, 'symbol', symbols);
}
parseTicker (ticker, market = undefined) {
//
// {
// "ask": "62756.01",
// "bid": "62754.09",
// "last": "62755.87",
// "low": "62010.00",
// "high": "66657.99",
// "open": "65089.27",
// "volume": "16719.50366",
// "volume_quote": "1063422878.8156828",
// "timestamp": "2021-10-22T07:29:14.585Z"
// }
//
const timestamp = this.parse8601 (ticker['timestamp']);
const symbol = this.safeSymbol (undefined, market);
const baseVolume = this.safeNumber (ticker, 'volume');
const quoteVolume = this.safeNumber (ticker, 'volumeQuote');
const open = this.safeNumber (ticker, 'open');
const last = this.safeNumber (ticker, 'last');
const vwap = this.vwap (baseVolume, quoteVolume);
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeNumber (ticker, 'high'),
'low': this.safeNumber (ticker, 'low'),
'bid': this.safeNumber (ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeNumber (ticker, 'ask'),
'askVolume': undefined,
'vwap': vwap,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
// symbol is optional for hitbtc fetchTrades
request['symbols'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['since'] = since;
}
const response = await this.publicGetPublicTrades (this.extend (request, params));
const marketIds = Object.keys (response);
let trades = [];
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const market = this.market (marketId);
const rawTrades = response[marketId];
const parsed = this.parseTrades (rawTrades, market);
trades = trades.concat (parsed);
}
return trades;
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['since'] = since;
}
const response = await this.privateGetSpotHistoryTrade (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
parseTrade (trade, market = undefined) {
// createMarketOrder
//
// { fee: "0.0004644",
// id: 386394956,
// price: "0.4644",
// quantity: "1",
// timestamp: "2018-10-25T16:41:44.780Z" }
//
// fetchTrades
//
// { id: 974786185,
// price: '0.032462',
// quantity: '0.3673',
// side: 'buy',
// timestamp: '2020-10-16T12:57:39.846Z' }
//
// fetchMyTrades
//
// { id: 277210397,
// clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
// orderId: 28102855393,
// symbol: 'ETHBTC',
// side: 'sell',
// quantity: '0.002',
// price: '0.073365',
// fee: '0.000000147',
// timestamp: '2018-04-28T18:39:55.345Z',
// taker: true }
//
const timestamp = this.parse8601 (trade['timestamp']);
const marketId = this.safeString (trade, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let fee = undefined;
const feeCost = this.safeNumber (trade, 'fee');
const taker = this.safeValue (trade, 'taker');
let takerOrMaker = undefined;
if (taker !== undefined) {
takerOrMaker = taker ? 'taker' : 'maker';
}
if (feeCost !== undefined) {
const info = this.safeValue (market, 'info', {});
const feeCurrency = this.safeString (info, 'fee_currency');
const feeCurrencyCode = this.safeCurrencyCode (feeCurrency);
fee = {
'cost': feeCost,
'currency': feeCurrencyCode,
};
}
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const orderId = this.safeString (trade, 'clientOrderId');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'quantity');
const price = this.parseNumber (priceString);
const amount = this.parseNumber (amountString);
const cost = this.parseNumber (Precise.stringMul (priceString, amountString));
const side = this.safeString (trade, 'side');
const id = this.safeString (trade, 'id');
return {
'info': trade,
'id': id,
'order': orderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': side,
'takerOrMaker': takerOrMaker,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchTransactionsHelper (types, code, since, limit, params) {
await this.loadMarkets ();
const request = {
'types': types,
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currencies'] = currency['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetWalletTransactions (this.extend (request, params));
//
// [
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
// ]
//
return this.parseTransactions (response, currency, since, limit, params);
}
parseTransactionStatus (status) {
const statuses = {
'PENDING': 'pending',
'FAILED': 'failed',
'SUCCESS': 'ok',
};
return this.safeString (statuses, status, status);
}
parseTransactionType (type) {
const types = {
'DEPOSIT': 'deposit',
'WITHDRAW': 'withdrawal',
};
return this.safeString (types, type, type);
}
parseTransaction (transaction, currency = undefined) {
//
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
//
// {
// "id": "102703545",
// "created_at": "2018-03-30T21:39:17.854Z",
// "updated_at": "2018-03-31T00:23:19.067Z",
// "status": "SUCCESS",
// "type": "WITHDRAW",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "5ecd7a85-ce5d-4d52-a916-b8b755e20926",
// "index": "918286359",
// "currency": "OMG",
// "amount": "2.45",
// "fee": "1.22",
// "hash": "0x1c621d89e7a0841342d5fb3b3587f60b95351590161e078c4a1daee353da4ca9",
// "address": "0x50227da7644cea0a43258a2e2d7444d01b43dcca",
// "confirmations": "0"
// }
// }
//
const id = this.safeString (transaction, 'id');
const timestamp = this.parse8601 (this.safeString (transaction, 'created_at'));
const updated = this.parse8601 (this.safeString (transaction, 'updated_at'));
const type = this.parseTransactionType (this.safeString (transaction, 'type'));
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const native = this.safeValue (transaction, 'native');
const currencyId = this.safeString (native, 'currency');
const code = this.safeCurrencyCode (currencyId);
const txhash = this.safeString (native, 'hash');
const address = this.safeString (native, 'address');
const addressTo = address;
const tag = this.safeString (native, 'payment_id');
const tagTo = tag;
const sender = this.safeValue (native, 'senders');
const addressFrom = this.safeString (sender, 0);
const amount = this.safeNumber (native, 'amount');
let fee = undefined;
const feeCost = this.safeNumber (native, 'fee');
if (feeCost !== undefined) {
fee = {
'code': code,
'cost': feeCost,
};
}
return {
'info': transaction,
'id': id,
'txid': txhash,
'code': code,
'amount': amount,
'address': address,
'addressFrom': addressFrom,
'addressTo': addressTo,
'tag': tag,
'tagFrom': undefined,
'tagTo': tagTo,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'updated': updated,
'status': status,
'type': type,
'fee': fee,
};
}
async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT,WITHDRAW', code, since, limit, params);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT', code, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('WITHDRAW', code, since, limit, params);
}
async fetchOrderBooks (symbols = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
request['symbols'] = marketIds.join (',');
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicOrderbook (this.extend (request, params));
const result = {};
const marketIds = Object.keys (response);
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const orderbook = response[marketId];
const symbol = this.safeSymbol (marketId);
const timestamp = this.parse8601 (this.safeString (orderbook, 'timestamp'));
result[symbol] = this.parseOrderBook (response[marketId], symbol, timestamp, 'bid', 'ask');
}
return result;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
const result = await this.fetchOrderBooks ([ symbol ], limit, params);
return result[symbol];
}
async fetchTradingFee (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const response = await this.privateGetSpotFeeSymbol (this.extend (request, params));
// {"take_rate":"0.0009","make_rate":"0.0009"}
const taker = this.safeNumber (response, 'take_rate');
const maker = this.safeNumber (response, 'make_rate');
return {
'info': response,
'symbol': symbol,
'taker': taker,
'maker': maker,
};
}
async fetchTradingFees (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.privateGetSpotFee (params);
// [{"symbol":"ARVUSDT","take_rate":"0.0009","make_rate":"0.0009"}]
const result = {};
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const symbol = this.safeSymbol (this.safeString (entry, 'symbol'));
const taker = this.safeNumber (entry, 'take_rate');
const maker = this.safeNumber (entry, 'make_rate');
result[symbol] = {
'info': entry,
'symbol': symbol,
'taker': taker,
'maker': maker,
};
}
return result;
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbols': market['id'],
'period': this.timeframes[timeframe],
};
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicCandles (this.extend (request, params));
//
// {
// "ETHUSDT": [
// {
// "timestamp": "2021-10-25T07:38:00.000Z",
// "open": "4173.391",
// "close": "4170.923",
// "min": "4170.923",
// "max": "4173.986",
// "volume": "0.1879",
// "volume_quote": "784.2517846"
// }
// ]
// }
//
const ohlcvs = this.safeValue (response, market['id']);
return this.parseOHLCVs (ohlcvs, market, timeframe, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// "timestamp":"2015-08-20T19:01:00.000Z",
// "open":"0.006",
// "close":"0.006",
// "min":"0.006",
// "max":"0.006",
// "volume":"0.003",
// "volume_quote":"0.000018"
// }
//
return [
this.parse8601 (this.safeString (ohlcv, 'timestamp')),
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'max'),
this.safeNumber (ohlcv, 'min'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber (ohlcv, 'volume'),
];
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetSpotHistoryOrder (this.extend (request, params));
const parsed = this.parseOrders (response, market, since, limit);
return this.filterByArray (parsed, 'status', [ 'closed', 'canceled' ], false);
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const request = {
'client_order_id': id,
};
const response = await this.privateGetSpotHistoryOrder (this.extend (request, params));
//
// [
// {
// "id": "685965182082",
// "client_order_id": "B3CBm9uGg9oYQlw96bBSEt38-6gbgBO0",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00010",
// "quantity_cumulative": "0",
// "price": "50000.00",
// "price_average": "0",
// "created_at": "2021-10-26T11:40:09.287Z",
// "updated_at": "2021-10-26T11:40:09.287Z"
// }
// ]
//
const order = this.safeValue (response, 0);
return this.parseOrder (order, market);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const response = await this.privateGetSpotOrder (this.extend (request, params));
//
// [
// {
// "id": "488953123149",
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
// ]
//
return this.parseOrders (response, market, since, limit);
}
async fetchOpenOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const request = {
'client_order_id': id,
};
const response = await this.privateGetSpotOrderClientOrderId (this.extend (request, params));
return this.parseOrder (response, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const response = await this.privateDeleteSpotOrder (this.extend (request, params));
return this.parseOrders (response, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
};
if (symbol !== undefined) {
market = this.market (symbol);
}
const response = await this.privateDeleteSpotOrderClientOrderId (this.extend (request, params));
return this.parseOrder (response, market);
}
async editOrder (id, symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
'quantity': this.amountToPrecision (symbol, amount),
};
if ((type === 'limit') || (type === 'stopLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' limit order requires price');
}
request['price'] = this.priceToPrecision (symbol, price);
}
if (symbol !== undefined) {
market = this.market (symbol);
}
const response = await this.privatePatchSpotOrderClientOrderId (this.extend (request, params));
return this.parseOrder (response, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'type': type,
'side': side,
'quantity': this.amountToPrecision (symbol, amount),
'symbol': market['id'],
};
if ((type === 'limit') || (type === 'stopLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' limit order requires price');
}
request['price'] = this.priceToPrecision (symbol, price);
}
const response = await this.privatePostSpotOrder (this.extend (request, params));
return this.parseOrder (response, market);
}
parseOrderStatus (status) {
const statuses = {
'new': 'open',
'suspended': 'open',
'partiallyFilled': 'open',
'filled': 'closed',
'canceled': 'canceled',
'expired': 'failed',
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// limit
// {
// "id": 488953123149,
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "price_average": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
//
// market
// {
// "id": "685877626834",
// "client_order_id": "Yshl7G-EjaREyXQYaGbsmdtVbW-nzQwu",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "filled",
// "type": "market",
// "time_in_force": "GTC",
// "quantity": "0.00010",
// "quantity_cumulative": "0.00010",
// "post_only": false,
// "created_at": "2021-10-26T08:55:55.1Z",
// "updated_at": "2021-10-26T08:55:55.1Z",
// "trades": [
// {
// "id": "1437229630",
// "position_id": "0",
// "quantity": "0.00010",
// "price": "62884.78",
// "fee": "0.005659630200",
// "timestamp": "2021-10-26T08:55:55.1Z",
// "taker": true
// }
// ]
// }
//
const id = this.safeString (order, 'client_order_id');
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const side = this.safeString (order, 'side');
const type = this.safeString (order, 'type');
const amount = this.safeString (order, 'quantity');
const price = this.safeString (order, 'price');
const average = this.safeString (order, 'price_average');
const created = this.safeString (order, 'created_at');
const timestamp = this.parse8601 (created);
const updated = this.safeString (order, 'updated_at');
let lastTradeTimestamp = undefined;
if (updated !== created) {
lastTradeTimestamp = this.parse8601 (updated);
}
const filled = this.safeString (order, 'quantity_cumulative');
const status = this.parseOrderStatus (this.safeString (order, 'status'));
const marketId = this.safeString (order, 'marketId');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
const postOnly = this.safeValue (order, 'post_only');
const timeInForce = this.safeString (order, 'time_in_force');
const rawTrades = this.safeValue (order, 'trades');
return this.safeOrder2 ({
'info': order,
'id': id,
'clientOrderId': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'price': price,
'amount': amount,
'type': type,
'side': side,
'timeInForce': timeInForce,
'postOnly': postOnly,
'filled': filled,
'remaining': undefined,
'cost': undefined,
'status': status,
'average': average,
'trades': rawTrades,
'fee': undefined,
}, market);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
// account can be "spot", "wallet", or "derivatives"
await this.loadMarkets ();
const currency = this.currency (code);
const requestAmount = this.currencyToPrecision (code, amount);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
fromAccount = fromAccount.toLowerCase ();
toAccount = toAccount.toLowerCase ();
const fromId = this.safeString (accountsByType, fromAccount);
const toId = this.safeString (accountsByType, toAccount);
const keys = Object.keys (accountsByType);
if (fromId === undefined) {
throw new ExchangeError (this.id + ' fromAccount must be one of ' + keys.join (', ') + ' instead of ' + fromId);
}
if (toId === undefined) {
throw new ExchangeError (this.id + ' toAccount must be one of ' + keys.join (', ') + ' instead of ' + toId);
}
if (fromId === toId) {
throw new ExchangeError (this.id + ' from and to cannot be the same account');
}
const request = {
'currency': currency['id'],
'amount': requestAmount,
'source': fromId,
'destination': toId,
};
const response = await this.privatePostWalletTransfer (this.extend (request, params));
// [ '2db6ebab-fb26-4537-9ef8-1a689472d236' ]
const id = this.safeString (response, 0);
return {
'info': response,
'id': id,
'timestamp': undefined,
'datetime': undefined,
'amount': this.parseNumber (requestAmount),
'currency': code,
'fromAccount': fromAccount,
'toAccount': toAccount,
'status': undefined,
};
}
async convertCurrencyNetwork (code, amount, fromNetwork, toNetwork, params) {
await this.loadMarkets ();
const currency = this.currency (code);
const networks = this.safeValue (this.options, 'networks', {});
fromNetwork = fromNetwork.toUpperCase ();
toNetwork = toNetwork.toUpperCase ();
fromNetwork = this.safeString (networks, fromNetwork, fromNetwork); // handle ETH>ERC20 alias
toNetwork = this.safeString (networks, toNetwork, toNetwork); // handle ETH>ERC20 alias
if (fromNetwork === toNetwork) {
throw new ExchangeError (this.id + ' fromNetwork cannot be the same as toNetwork');
}
const request = {
'from_currency': currency['id'] + fromNetwork,
'to_currency': currency['id'] + toNetwork,
'amount': this.currencyToPrecision (code, amount),
};
const response = await this.privatePostWalletConvert (this.extend (request, params));
// {"result":["587a1868-e62d-4d8e-b27c-dbdb2ee96149","e168df74-c041-41f2-b76c-e43e4fed5bc7"]}
return {
'info': response,
};
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
await this.loadMarkets ();
this.checkAddress (address);
const currency = this.currency (code);
const request = {
'currency': currency['id'],
'amount': amount,
'address': address,
};
if (tag !== undefined) {
request['payment_id'] = tag;
}
const networks = this.safeValue (this.options, 'networks', {});
let network = this.safeStringUpper (params, 'network');
network = this.safeString (networks, network, network);
if (network !== undefined) {
request['currency'] += network; // when network the currency need to be changed to currency + network
params = this.omit (params, 'network');
}
const response = await this.privatePostWalletCryptoWithdraw (this.extend (request, params));
// {"id":"084cfcd5-06b9-4826-882e-fdb75ec3625d"}
const id = this.safeString (response, 'id');
return {
'info': response,
'id': id,
};
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
//
// {
// "error": {
// "code": 20001,
// "message": "Insufficient funds",
// "description": "Check that the funds are sufficient, given commissions"
// }
// }
//
const error = this.safeValue (response, 'error');
const errorCode = this.safeString (error, 'code');
if (errorCode !== undefined) {
const description = this.safeString (error, 'description', '');
const ExceptionClass = this.safeValue (this.exceptions, errorCode);
if (ExceptionClass !== undefined) {
throw new ExceptionClass (this.id + ' ' + description);
} else {
throw new ExchangeError (this.id + ' ' + description);
}
}
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const query = this.omit (params, this.extractParams (path));
const implodedPath = this.implodeParams (path, params);
let url = this.urls['api'][api] + '/' + implodedPath;
let getRequest = undefined;
const keys = Object.keys (query);
const queryLength = keys.length;
headers = {
'Content-Type': 'application/json',
};
if (method === 'GET') {
if (queryLength) {
getRequest = '?' + this.urlencode (query);
url = url + getRequest;
}
} else {
body = this.json (params);
}
if (api === 'private') {
this.checkRequiredCredentials ();
const timestamp = this.nonce ().toString ();
const payload = [ method, '/api/3/' + implodedPath ];
if (method === 'GET') {
if (getRequest !== undefined) {
payload.push (getRequest);
}
} else {
payload.push (body);
}
payload.push (timestamp);
const payloadString = payload.join ('');
const signature = this.hmac (this.encode (payloadString), this.encode (this.secret), 'sha256', 'hex');
const secondPayload = this.apiKey + ':' + signature + ':' + timestamp;
const encoded = this.stringToBase64 (secondPayload);
headers['Authorization'] = 'HS256 ' + encoded;
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
};
| js/hitbtc3.js | const Exchange = require ('./base/Exchange');
const { TICK_SIZE } = require ('./base/functions/number');
const Precise = require ('./base/Precise');
const { BadSymbol, BadRequest, OnMaintenance, AccountSuspended, PermissionDenied, ExchangeError, RateLimitExceeded, ExchangeNotAvailable, OrderNotFound, InsufficientFunds, InvalidOrder, AuthenticationError } = require ('./base/errors');
module.exports = class hitbtc3 extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'hitbtc3',
'name': 'HitBTC',
'countries': [ 'HK' ],
'rateLimit': 100, // TODO: optimize https://api.hitbtc.com/#rate-limiting
'version': '3',
'pro': true,
'has': {
'cancelOrder': true,
'CORS': false,
'createOrder': true,
'editOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDeposits': false,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrder': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': false,
'fetchOrderTrades': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTrades': true,
'fetchTradingFee': true,
'fetchTransactions': true,
'fetchWithdrawals': false,
'withdraw': true,
'transfer': true,
},
'precisionMode': TICK_SIZE,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'test': {
'public': 'https://api.demo.hitbtc.com',
'private': 'https://api.demo.hitbtc.com',
},
'api': {
'public': 'https://api.hitbtc.com/api/3',
'private': 'https://api.hitbtc.com/api/3',
},
'www': 'https://hitbtc.com',
'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
'doc': [
'https://api.hitbtc.com',
'https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md',
],
'fees': [
'https://hitbtc.com/fees-and-limits',
'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
],
},
'api': {
'public': {
'get': [
'public/currency',
'public/symbol',
'public/ticker',
'public/price/rate',
'public/trades',
'public/orderbook',
'public/candles',
'public/futures/info',
'public/futures/history/funding',
'public/futures/candles/index_price',
'public/futures/candles/mark_price',
'public/futures/candles/premium_index',
'public/futures/candles/open_interest',
],
},
'private': {
'get': [
'spot/balance',
'spot/order',
'spot/order/{client_order_id}',
'spot/fee',
'spot/fee/{symbol}',
'spot/history/order',
'spot/history/trade',
'margin/account',
'margin/account/isolated/{symbol}',
'margin/order',
'margin/order/{client_order_id}',
'margin/history/order',
'margin/history/trade',
'futures/balance',
'futures/account',
'futures/account/isolated/{symbol}',
'futures/order',
'futures/order/{client_order_id}',
'futures/fee',
'futures/fee/{symbol}',
'futures/history/order',
'futures/history/trade',
'wallet/balance',
'wallet/crypto/address',
'wallet/crypto/address/recent-deposit',
'wallet/crypto/address/recent-withdraw',
'wallet/crypto/address/check-mine',
'wallet/transactions',
'wallet/crypto/check-offchain-available',
'wallet/crypto/fee/estimate',
'sub-account',
'sub-account/acl',
'sub-account/balance/{subAccID}',
'sub-account/crypto/address/{subAccID}/{currency}',
],
'post': [
'spot/order',
'margin/order',
'futures/order',
'wallet/convert',
'wallet/crypto/withdraw',
'wallet/transfer',
'sub-account/freeze',
'sub-account/activate',
'sub-account/transfer',
'sub-account/acl',
],
'patch': [
'spot/order/{client_order_id}',
'margin/order/{client_order_id}',
'futures/order/{client_order_id}',
],
'delete': [
'spot/order',
'spot/order/{client_order_id}',
'margin/position',
'margin/position/isolated/{symbol}',
'margin/order',
'margin/order/{client_order_id}',
'futures/position',
'futures/position/isolated/{symbol}',
'futures/order',
'futures/order/{client_order_id}',
'wallet/crypto/withdraw/{id}',
],
'put': [
'margin/account/isolated/{symbol}',
'futures/account/isolated/{symbol}',
'wallet/crypto/withdraw/{id}',
],
},
},
'fees': {
'trading': {
'tierBased': true,
'percentage': true,
'taker': this.parseNumber ('0.0009'),
'maker': this.parseNumber ('0.0009'),
'tiers': {
'maker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0002') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0001') ],
[ this.parseNumber ('20000'), this.parseNumber ('0') ],
[ this.parseNumber ('50000'), this.parseNumber ('-0.0001') ],
[ this.parseNumber ('100000'), this.parseNumber ('-0.0001') ],
],
'taker': [
[ this.parseNumber ('0'), this.parseNumber ('0.0009') ],
[ this.parseNumber ('10'), this.parseNumber ('0.0008') ],
[ this.parseNumber ('100'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('500'), this.parseNumber ('0.0007') ],
[ this.parseNumber ('1000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('5000'), this.parseNumber ('0.0006') ],
[ this.parseNumber ('10000'), this.parseNumber ('0.0005') ],
[ this.parseNumber ('20000'), this.parseNumber ('0.0004') ],
[ this.parseNumber ('50000'), this.parseNumber ('0.0003') ],
[ this.parseNumber ('100000'), this.parseNumber ('0.0002') ],
],
},
},
},
'timeframes': {
'1m': 'M1',
'3m': 'M3',
'5m': 'M5',
'15m': 'M15',
'30m': 'M30', // default
'1h': 'H1',
'4h': 'H4',
'1d': 'D1',
'1w': 'D7',
'1M': '1M',
},
'exceptions': {
'429': RateLimitExceeded,
'500': ExchangeError,
'503': ExchangeNotAvailable,
'504': ExchangeNotAvailable,
'600': PermissionDenied,
'800': ExchangeError,
'1002': AuthenticationError,
'1003': PermissionDenied,
'1004': AuthenticationError,
'1005': AuthenticationError,
'2001': BadSymbol,
'2002': BadRequest,
'2003': BadRequest,
'2010': BadRequest,
'2011': BadRequest,
'2012': BadRequest,
'2020': BadRequest,
'2022': BadRequest,
'10001': BadRequest,
'10021': AccountSuspended,
'10022': BadRequest,
'20001': InsufficientFunds,
'20002': OrderNotFound,
'20003': ExchangeError,
'20004': ExchangeError,
'20005': ExchangeError,
'20006': ExchangeError,
'20007': ExchangeError,
'20008': InvalidOrder,
'20009': InvalidOrder,
'20010': OnMaintenance,
'20011': ExchangeError,
'20012': ExchangeError,
'20014': ExchangeError,
'20016': ExchangeError,
'20031': ExchangeError,
'20032': ExchangeError,
'20033': ExchangeError,
'20034': ExchangeError,
'20040': ExchangeError,
'20041': ExchangeError,
'20042': ExchangeError,
'20043': ExchangeError,
'20044': PermissionDenied,
'20045': ExchangeError,
'20080': ExchangeError,
'21001': ExchangeError,
'21003': AccountSuspended,
'21004': AccountSuspended,
},
'options': {
'networks': {
'ETH': '20',
'ERC20': '20',
'TRX': 'RX',
'TRC20': 'RX',
'OMNI': '',
},
'accountsByType': {
'spot': 'spot',
'wallet': 'wallet',
'derivatives': 'derivatives',
},
},
});
}
nonce () {
return this.milliseconds ();
}
async fetchMarkets (params = {}) {
const request = {};
const response = await this.publicGetPublicSymbol (this.extend (request, params));
//
// fetches both spot and future markets
//
// {
// "ETHBTC": {
// "type": "spot",
// "base_currency": "ETH",
// "quote_currency": "BTC",
// "quantity_increment": "0.001",
// "tick_size": "0.000001",
// "take_rate": "0.001",
// "make_rate": "-0.0001",
// "fee_currency": "BTC",
// "margin_trading": true,
// "max_initial_leverage": "10.00"
// }
// }
//
const marketIds = Object.keys (response);
const result = [];
for (let i = 0; i < marketIds.length; i++) {
const id = marketIds[i];
const entry = response[id];
const baseId = this.safeString (entry, 'base_currency');
const quoteId = this.safeString (entry, 'quote_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const maker = this.safeNumber (entry, 'make_rate');
const taker = this.safeNumber (entry, 'take_rate');
const feeCurrency = this.safeString (entry, 'fee_currency');
const feeSide = (feeCurrency === quoteId) ? 'quote' : 'base';
const margin = this.safeValue (entry, 'margin_trading', false);
const type = this.safeString (entry, 'type');
const spot = (type === 'spot');
const futures = (type === 'futures');
const priceIncrement = this.safeNumber (entry, 'tick_size');
const amountIncrement = this.safeNumber (entry, 'quantity_increment');
const precision = {
'price': priceIncrement,
'amount': amountIncrement,
};
const limits = {
'amount': {
'min': undefined,
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': undefined,
'max': undefined,
},
};
result.push ({
'info': entry,
'symbol': symbol,
'id': id,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'spot': spot,
'margin': margin,
'futures': futures,
'type': type,
'feeSide': feeSide,
'maker': maker,
'taker': taker,
'precision': precision,
'limits': limits,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.publicGetPublicCurrency (params);
//
// {
// "WEALTH": {
// "full_name": "ConnectWealth",
// "payin_enabled": false,
// "payout_enabled": false,
// "transfer_enabled": true,
// "precision_transfer": "0.001",
// "networks": [
// {
// "network": "ETH",
// "protocol": "ERC20",
// "default": true,
// "payin_enabled": false,
// "payout_enabled": false,
// "precision_payout": "0.001",
// "payout_fee": "0.016800000000",
// "payout_is_payment_id": false,
// "payin_payment_id": false,
// "payin_confirmations": "2"
// }
// ]
// }
// }
//
const result = {};
const currencies = Object.keys (response);
for (let i = 0; i < currencies.length; i++) {
const currencyId = currencies[i];
const code = this.safeCurrencyCode (currencyId);
const entry = response[currencyId];
const name = this.safeString (entry, 'full_name');
const precision = this.safeNumber (entry, 'precision_transfer');
const payinEnabled = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabled = this.safeValue (entry, 'payout_enabled', false);
const transferEnabled = this.safeValue (entry, 'transfer_enabled', false);
const active = payinEnabled && payoutEnabled && transferEnabled;
const rawNetworks = this.safeValue (entry, 'networks', []);
const networks = {};
let fee = undefined;
for (let j = 0; j < rawNetworks.length; j++) {
const rawNetwork = rawNetworks[j];
let networkId = this.safeString (rawNetwork, 'protocol');
if (networkId.length === 0) {
networkId = this.safeString (rawNetwork, 'network');
}
const network = this.safeNetwork (networkId);
fee = this.safeNumber (rawNetwork, 'payout_fee');
const precision = this.safeNumber (rawNetwork, 'precision_payout');
const payinEnabledNetwork = this.safeValue (entry, 'payin_enabled', false);
const payoutEnabledNetwork = this.safeValue (entry, 'payout_enabled', false);
const transferEnabledNetwork = this.safeValue (entry, 'transfer_enabled', false);
const active = payinEnabledNetwork && payoutEnabledNetwork && transferEnabledNetwork;
networks[network] = {
'info': rawNetwork,
'id': networkId,
'network': network,
'fee': fee,
'active': active,
'precision': precision,
'limits': {
'withdraw': {
'min': undefined,
'max': undefined,
},
},
};
}
const networksKeys = Object.keys (networks);
const networksLength = networksKeys.length;
result[code] = {
'info': entry,
'code': code,
'id': currencyId,
'precision': precision,
'name': name,
'active': active,
'networks': networks,
'fee': (networksLength <= 1) ? fee : undefined,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
},
};
}
return result;
}
safeNetwork (networkId) {
const networksById = {
};
return this.safeString (networksById, networkId, networkId);
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const network = this.safeString (params, 'network');
if ((network !== undefined) && (code === 'USDT')) {
params = this.omit (params, 'network');
const networks = this.safeValue (this.options, 'networks');
const endpart = this.safeString (networks, network, network);
request['currency'] += endpart;
}
const response = await this.privateGetWalletCryptoAddress (this.extend (request, params));
//
// [{"currency":"ETH","address":"0xd0d9aea60c41988c3e68417e2616065617b7afd3"}]
//
const firstAddress = this.safeValue (response, 0);
const address = this.safeString (firstAddress, 'address');
const currencyId = this.safeString (firstAddress, 'currency');
const tag = this.safeString (firstAddress, 'payment_id');
const parsedCode = this.safeCurrencyCode (currencyId);
return {
'info': response,
'address': address,
'tag': tag,
'code': parsedCode,
};
}
async fetchBalance (params) {
const response = await this.privateGetSpotBalance ();
//
// [
// {
// "currency": "PAXG",
// "available": "0",
// "reserved": "0",
// "reserved_margin": "0",
// },
// ...
// ]
//
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const currencyId = this.safeString (entry, 'currency');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (entry, 'available');
account['used'] = this.safeString (entry, 'reserved');
result[code] = account;
}
return this.parseBalance (result);
}
async fetchTicker (symbol, params = {}) {
const response = await this.fetchTickers ([ symbol ], params);
return this.safeValue (response, symbol);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
const delimited = marketIds.join (',');
request['symbols'] = delimited;
}
const response = await this.publicGetPublicTicker (this.extend (request, params));
//
// {
// "BTCUSDT": {
// "ask": "63049.06",
// "bid": "63046.41",
// "last": "63048.36",
// "low": "62010.00",
// "high": "66657.99",
// "open": "64839.75",
// "volume": "15272.13278",
// "volume_quote": "976312127.6277998",
// "timestamp": "2021-10-22T04:25:47.573Z"
// }
// }
//
const result = {};
const keys = Object.keys (response);
for (let i = 0; i < keys.length; i++) {
const marketId = keys[i];
const market = this.safeMarket (marketId);
const symbol = market['symbol'];
const entry = response[marketId];
result[symbol] = this.parseTicker (entry, market);
}
return this.filterByArray (result, 'symbol', symbols);
}
parseTicker (ticker, market = undefined) {
//
// {
// "ask": "62756.01",
// "bid": "62754.09",
// "last": "62755.87",
// "low": "62010.00",
// "high": "66657.99",
// "open": "65089.27",
// "volume": "16719.50366",
// "volume_quote": "1063422878.8156828",
// "timestamp": "2021-10-22T07:29:14.585Z"
// }
//
const timestamp = this.parse8601 (ticker['timestamp']);
const symbol = this.safeSymbol (undefined, market);
const baseVolume = this.safeNumber (ticker, 'volume');
const quoteVolume = this.safeNumber (ticker, 'volumeQuote');
const open = this.safeNumber (ticker, 'open');
const last = this.safeNumber (ticker, 'last');
const vwap = this.vwap (baseVolume, quoteVolume);
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeNumber (ticker, 'high'),
'low': this.safeNumber (ticker, 'low'),
'bid': this.safeNumber (ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeNumber (ticker, 'ask'),
'askVolume': undefined,
'vwap': vwap,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
// symbol is optional for hitbtc fetchTrades
request['symbols'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['since'] = since;
}
const response = await this.publicGetPublicTrades (this.extend (request, params));
const marketIds = Object.keys (response);
let trades = [];
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const market = this.market (marketId);
const rawTrades = response[marketId];
const parsed = this.parseTrades (rawTrades, market);
trades = trades.concat (parsed);
}
return trades;
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (limit !== undefined) {
request['limit'] = limit;
}
if (since !== undefined) {
request['since'] = since;
}
const response = await this.privateGetSpotHistoryTrade (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
parseTrade (trade, market = undefined) {
// createMarketOrder
//
// { fee: "0.0004644",
// id: 386394956,
// price: "0.4644",
// quantity: "1",
// timestamp: "2018-10-25T16:41:44.780Z" }
//
// fetchTrades
//
// { id: 974786185,
// price: '0.032462',
// quantity: '0.3673',
// side: 'buy',
// timestamp: '2020-10-16T12:57:39.846Z' }
//
// fetchMyTrades
//
// { id: 277210397,
// clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a',
// orderId: 28102855393,
// symbol: 'ETHBTC',
// side: 'sell',
// quantity: '0.002',
// price: '0.073365',
// fee: '0.000000147',
// timestamp: '2018-04-28T18:39:55.345Z',
// taker: true }
//
const timestamp = this.parse8601 (trade['timestamp']);
const marketId = this.safeString (trade, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let fee = undefined;
const feeCost = this.safeNumber (trade, 'fee');
const taker = this.safeValue (trade, 'taker');
let takerOrMaker = undefined;
if (taker !== undefined) {
takerOrMaker = taker ? 'taker' : 'maker';
}
if (feeCost !== undefined) {
const info = this.safeValue (market, 'info', {});
const feeCurrency = this.safeString (info, 'fee_currency');
const feeCurrencyCode = this.safeCurrencyCode (feeCurrency);
fee = {
'cost': feeCost,
'currency': feeCurrencyCode,
};
}
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const orderId = this.safeString (trade, 'clientOrderId');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'quantity');
const price = this.parseNumber (priceString);
const amount = this.parseNumber (amountString);
const cost = this.parseNumber (Precise.stringMul (priceString, amountString));
const side = this.safeString (trade, 'side');
const id = this.safeString (trade, 'id');
return {
'info': trade,
'id': id,
'order': orderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': side,
'takerOrMaker': takerOrMaker,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchTransactionsHelper (types, code, since, limit, params) {
await this.loadMarkets ();
const request = {
'types': types,
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currencies'] = currency['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetWalletTransactions (this.extend (request, params));
//
// [
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
// ]
//
return this.parseTransactions (response, currency, since, limit, params);
}
parseTransactionStatus (status) {
const statuses = {
'PENDING': 'pending',
'FAILED': 'failed',
'SUCCESS': 'ok',
};
return this.safeString (statuses, status, status);
}
parseTransactionType (type) {
const types = {
'DEPOSIT': 'deposit',
'WITHDRAW': 'withdrawal',
};
return this.safeString (types, type, type);
}
parseTransaction (transaction, currency = undefined) {
//
// {
// "id": "101609495",
// "created_at": "2018-03-06T22:05:06.507Z",
// "updated_at": "2018-03-06T22:11:45.03Z",
// "status": "SUCCESS",
// "type": "DEPOSIT",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "e20b0965-4024-44d0-b63f-7fb8996a6706",
// "index": "881652766",
// "currency": "ETH",
// "amount": "0.01418088",
// "hash": "d95dbbff3f9234114f1211ab0ba2a94f03f394866fd5749d74a1edab80e6c5d3",
// "address": "0xd9259302c32c0a0295d86a39185c9e14f6ba0a0d",
// "confirmations": "20",
// "senders": [
// "0x243bec9256c9a3469da22103891465b47583d9f1"
// ]
// }
// }
//
// {
// "id": "102703545",
// "created_at": "2018-03-30T21:39:17.854Z",
// "updated_at": "2018-03-31T00:23:19.067Z",
// "status": "SUCCESS",
// "type": "WITHDRAW",
// "subtype": "BLOCKCHAIN",
// "native": {
// "tx_id": "5ecd7a85-ce5d-4d52-a916-b8b755e20926",
// "index": "918286359",
// "currency": "OMG",
// "amount": "2.45",
// "fee": "1.22",
// "hash": "0x1c621d89e7a0841342d5fb3b3587f60b95351590161e078c4a1daee353da4ca9",
// "address": "0x50227da7644cea0a43258a2e2d7444d01b43dcca",
// "confirmations": "0"
// }
// }
//
const id = this.safeString (transaction, 'id');
const timestamp = this.parse8601 (this.safeString (transaction, 'created_at'));
const updated = this.parse8601 (this.safeString (transaction, 'updated_at'));
const type = this.parseTransactionType (this.safeString (transaction, 'type'));
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const native = this.safeValue (transaction, 'native');
const currencyId = this.safeString (native, 'currency');
const code = this.safeCurrencyCode (currencyId);
const txhash = this.safeString (native, 'hash');
const address = this.safeString (native, 'address');
const addressTo = address;
const tag = this.safeString (native, 'payment_id');
const tagTo = tag;
const sender = this.safeValue (native, 'senders');
const addressFrom = this.safeString (sender, 0);
const amount = this.safeNumber (native, 'amount');
let fee = undefined;
const feeCost = this.safeNumber (native, 'fee');
if (feeCost !== undefined) {
fee = {
'code': code,
'cost': feeCost,
};
}
return {
'info': transaction,
'id': id,
'txid': txhash,
'code': code,
'amount': amount,
'address': address,
'addressFrom': addressFrom,
'addressTo': addressTo,
'tag': tag,
'tagFrom': undefined,
'tagTo': tagTo,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'updated': updated,
'status': status,
'type': type,
'fee': fee,
};
}
async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT,WITHDRAW', code, since, limit, params);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('DEPOSIT', code, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsHelper ('WITHDRAW', code, since, limit, params);
}
async fetchOrderBooks (symbols = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (symbols !== undefined) {
const marketIds = this.marketIds (symbols);
request['symbols'] = marketIds.join (',');
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicOrderbook (this.extend (request, params));
const result = {};
const marketIds = Object.keys (response);
for (let i = 0; i < marketIds.length; i++) {
const marketId = marketIds[i];
const orderbook = response[marketId];
const symbol = this.safeSymbol (marketId);
const timestamp = this.parse8601 (this.safeString (orderbook, 'timestamp'));
result[symbol] = this.parseOrderBook (response[marketId], symbol, timestamp, 'bid', 'ask');
}
return result;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
const result = await this.fetchOrderBooks ([ symbol ], limit, params);
return result[symbol];
}
async fetchTradingFee (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const response = await this.privateGetSpotFeeSymbol (this.extend (request, params));
// {"take_rate":"0.0009","make_rate":"0.0009"}
const taker = this.safeNumber (response, 'take_rate');
const maker = this.safeNumber (response, 'make_rate');
return {
'info': response,
'symbol': symbol,
'taker': taker,
'maker': maker,
};
}
async fetchTradingFees (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.privateGetSpotFee (params);
// [{"symbol":"ARVUSDT","take_rate":"0.0009","make_rate":"0.0009"}]
const result = {};
for (let i = 0; i < response.length; i++) {
const entry = response[i];
const symbol = this.safeSymbol (this.safeString (entry, 'symbol'));
const taker = this.safeNumber (entry, 'take_rate');
const maker = this.safeNumber (entry, 'make_rate');
result[symbol] = {
'info': entry,
'symbol': symbol,
'taker': taker,
'maker': maker,
};
}
return result;
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbols': market['id'],
'period': this.timeframes[timeframe],
};
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.publicGetPublicCandles (this.extend (request, params));
//
// {
// "ETHUSDT": [
// {
// "timestamp": "2021-10-25T07:38:00.000Z",
// "open": "4173.391",
// "close": "4170.923",
// "min": "4170.923",
// "max": "4173.986",
// "volume": "0.1879",
// "volume_quote": "784.2517846"
// }
// ]
// }
//
const ohlcvs = this.safeValue (response, market['id']);
return this.parseOHLCVs (ohlcvs, market, timeframe, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// "timestamp":"2015-08-20T19:01:00.000Z",
// "open":"0.006",
// "close":"0.006",
// "min":"0.006",
// "max":"0.006",
// "volume":"0.003",
// "volume_quote":"0.000018"
// }
//
return [
this.parse8601 (this.safeString (ohlcv, 'timestamp')),
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'max'),
this.safeNumber (ohlcv, 'min'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber (ohlcv, 'volume'),
];
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['from'] = this.iso8601 (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.privateGetSpotHistoryOrder (this.extend (request, params));
const parsed = this.parseOrders (response, market, since, limit);
return this.filterByArray (parsed, 'status', [ 'closed', 'canceled' ], false);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const response = await this.privateGetSpotOrder (this.extend (request, params));
//
// [
// {
// "id": "488953123149",
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
// ]
//
return this.parseOrders (response, market, since, limit);
}
async fetchOpenOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const request = {
'client_order_id': id,
};
const response = await this.privateGetSpotOrderClientOrderId (this.extend (request, params));
return this.parseOrder (response, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const response = await this.privateDeleteSpotOrder (this.extend (request, params));
return this.parseOrders (response, market);
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
};
if (symbol !== undefined) {
market = this.market (symbol);
}
const response = await this.privateDeleteSpotOrderClientOrderId (this.extend (request, params));
return this.parseOrder (response, market);
}
async editOrder (id, symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {
'client_order_id': id,
'quantity': this.amountToPrecision (symbol, amount),
};
if ((type === 'limit') || (type === 'stopLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' limit order requires price');
}
request['price'] = this.priceToPrecision (symbol, price);
}
if (symbol !== undefined) {
market = this.market (symbol);
}
const response = await this.privatePatchSpotOrderClientOrderId (this.extend (request, params));
return this.parseOrder (response, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'type': type,
'side': side,
'quantity': this.amountToPrecision (symbol, amount),
'symbol': market['id'],
};
if ((type === 'limit') || (type === 'stopLimit')) {
if (price === undefined) {
throw new ExchangeError (this.id + ' limit order requires price');
}
request['price'] = this.priceToPrecision (symbol, price);
}
const response = await this.privatePostSpotOrder (this.extend (request, params));
return this.parseOrder (response, market);
}
parseOrderStatus (status) {
const statuses = {
'new': 'open',
'suspended': 'open',
'partiallyFilled': 'open',
'filled': 'closed',
'canceled': 'canceled',
'expired': 'failed',
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// limit
// {
// "id": 488953123149,
// "client_order_id": "103ad305301e4c3590045b13de15b36e",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "new",
// "type": "limit",
// "time_in_force": "GTC",
// "quantity": "0.00001",
// "quantity_cumulative": "0",
// "price": "0.01",
// "price_average": "0.01",
// "post_only": false,
// "created_at": "2021-04-13T13:06:16.567Z",
// "updated_at": "2021-04-13T13:06:16.567Z"
// }
//
// market
// {
// "id": "685877626834",
// "client_order_id": "Yshl7G-EjaREyXQYaGbsmdtVbW-nzQwu",
// "symbol": "BTCUSDT",
// "side": "buy",
// "status": "filled",
// "type": "market",
// "time_in_force": "GTC",
// "quantity": "0.00010",
// "quantity_cumulative": "0.00010",
// "post_only": false,
// "created_at": "2021-10-26T08:55:55.1Z",
// "updated_at": "2021-10-26T08:55:55.1Z",
// "trades": [
// {
// "id": "1437229630",
// "position_id": "0",
// "quantity": "0.00010",
// "price": "62884.78",
// "fee": "0.005659630200",
// "timestamp": "2021-10-26T08:55:55.1Z",
// "taker": true
// }
// ]
// }
//
const id = this.safeString (order, 'client_order_id');
// we use clientOrderId as the order id with this exchange intentionally
// because most of their endpoints will require clientOrderId
// explained here: https://github.com/ccxt/ccxt/issues/5674
const side = this.safeString (order, 'side');
const type = this.safeString (order, 'type');
const amount = this.safeString (order, 'quantity');
const price = this.safeString (order, 'price');
const average = this.safeString (order, 'price_average');
const created = this.safeString (order, 'created_at');
const timestamp = this.parse8601 (created);
const updated = this.safeString (order, 'updated_at');
let lastTradeTimestamp = undefined;
if (updated !== created) {
lastTradeTimestamp = this.parse8601 (updated);
}
const filled = this.safeString (order, 'quantity_cumulative');
const status = this.parseOrderStatus (this.safeString (order, 'status'));
const marketId = this.safeString (order, 'marketId');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
const postOnly = this.safeValue (order, 'post_only');
const timeInForce = this.safeString (order, 'time_in_force');
const rawTrades = this.safeValue (order, 'trades');
return this.safeOrder2 ({
'info': order,
'id': id,
'clientOrderId': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'price': price,
'amount': amount,
'type': type,
'side': side,
'timeInForce': timeInForce,
'postOnly': postOnly,
'filled': filled,
'remaining': undefined,
'cost': undefined,
'status': status,
'average': average,
'trades': rawTrades,
'fee': undefined,
}, market);
}
async transfer (code, amount, fromAccount, toAccount, params = {}) {
// account can be "spot", "wallet", or "derivatives"
await this.loadMarkets ();
const currency = this.currency (code);
const requestAmount = this.currencyToPrecision (code, amount);
const accountsByType = this.safeValue (this.options, 'accountsByType', {});
fromAccount = fromAccount.toLowerCase ();
toAccount = toAccount.toLowerCase ();
const fromId = this.safeString (accountsByType, fromAccount);
const toId = this.safeString (accountsByType, toAccount);
const keys = Object.keys (accountsByType);
if (fromId === undefined) {
throw new ExchangeError (this.id + ' fromAccount must be one of ' + keys.join (', ') + ' instead of ' + fromId);
}
if (toId === undefined) {
throw new ExchangeError (this.id + ' toAccount must be one of ' + keys.join (', ') + ' instead of ' + toId);
}
if (fromId === toId) {
throw new ExchangeError (this.id + ' from and to cannot be the same account');
}
const request = {
'currency': currency['id'],
'amount': requestAmount,
'source': fromId,
'destination': toId,
};
const response = await this.privatePostWalletTransfer (this.extend (request, params));
// [ '2db6ebab-fb26-4537-9ef8-1a689472d236' ]
const id = this.safeString (response, 0);
return {
'info': response,
'id': id,
'timestamp': undefined,
'datetime': undefined,
'amount': this.parseNumber (requestAmount),
'currency': code,
'fromAccount': fromAccount,
'toAccount': toAccount,
'status': undefined,
};
}
async convertCurrencyNetwork (code, amount, fromNetwork, toNetwork, params) {
await this.loadMarkets ();
const currency = this.currency (code);
const networks = this.safeValue (this.options, 'networks', {});
fromNetwork = fromNetwork.toUpperCase ();
toNetwork = toNetwork.toUpperCase ();
fromNetwork = this.safeString (networks, fromNetwork, fromNetwork); // handle ETH>ERC20 alias
toNetwork = this.safeString (networks, toNetwork, toNetwork); // handle ETH>ERC20 alias
if (fromNetwork === toNetwork) {
throw new ExchangeError (this.id + ' fromNetwork cannot be the same as toNetwork');
}
const request = {
'from_currency': currency['id'] + fromNetwork,
'to_currency': currency['id'] + toNetwork,
'amount': this.currencyToPrecision (code, amount),
};
const response = await this.privatePostWalletConvert (this.extend (request, params));
// {"result":["587a1868-e62d-4d8e-b27c-dbdb2ee96149","e168df74-c041-41f2-b76c-e43e4fed5bc7"]}
return {
'info': response,
};
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
await this.loadMarkets ();
this.checkAddress (address);
const currency = this.currency (code);
const request = {
'currency': currency['id'],
'amount': amount,
'address': address,
};
if (tag !== undefined) {
request['payment_id'] = tag;
}
const networks = this.safeValue (this.options, 'networks', {});
let network = this.safeStringUpper (params, 'network');
network = this.safeString (networks, network, network);
if (network !== undefined) {
request['currency'] += network; // when network the currency need to be changed to currency + network
params = this.omit (params, 'network');
}
const response = await this.privatePostWalletCryptoWithdraw (this.extend (request, params));
// {"id":"084cfcd5-06b9-4826-882e-fdb75ec3625d"}
const id = this.safeString (response, 'id');
return {
'info': response,
'id': id,
};
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
//
// {
// "error": {
// "code": 20001,
// "message": "Insufficient funds",
// "description": "Check that the funds are sufficient, given commissions"
// }
// }
//
const error = this.safeValue (response, 'error');
const errorCode = this.safeString (error, 'code');
if (errorCode !== undefined) {
const description = this.safeString (error, 'description', '');
const ExceptionClass = this.safeValue (this.exceptions, errorCode);
if (ExceptionClass !== undefined) {
throw new ExceptionClass (this.id + ' ' + description);
} else {
throw new ExchangeError (this.id + ' ' + description);
}
}
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const query = this.omit (params, this.extractParams (path));
const implodedPath = this.implodeParams (path, params);
let url = this.urls['api'][api] + '/' + implodedPath;
let getRequest = undefined;
const keys = Object.keys (query);
const queryLength = keys.length;
headers = {
'Content-Type': 'application/json',
};
if (method === 'GET') {
if (queryLength) {
getRequest = '?' + this.urlencode (query);
url = url + getRequest;
}
} else {
body = this.json (params);
}
if (api === 'private') {
this.checkRequiredCredentials ();
const timestamp = this.nonce ().toString ();
const payload = [ method, '/api/3/' + implodedPath ];
if (method === 'GET') {
if (getRequest !== undefined) {
payload.push (getRequest);
}
} else {
payload.push (body);
}
payload.push (timestamp);
const payloadString = payload.join ('');
const signature = this.hmac (this.encode (payloadString), this.encode (this.secret), 'sha256', 'hex');
const secondPayload = this.apiKey + ':' + signature + ':' + timestamp;
const encoded = this.stringToBase64 (secondPayload);
headers['Authorization'] = 'HS256 ' + encoded;
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
};
| implement fetchOrder
| js/hitbtc3.js | implement fetchOrder | <ide><path>s/hitbtc3.js
<ide> return this.filterByArray (parsed, 'status', [ 'closed', 'canceled' ], false);
<ide> }
<ide>
<add> async fetchOrder (id, symbol = undefined, params = {}) {
<add> await this.loadMarkets ();
<add> let market = undefined;
<add> if (symbol !== undefined) {
<add> market = this.market (symbol);
<add> }
<add> const request = {
<add> 'client_order_id': id,
<add> };
<add> const response = await this.privateGetSpotHistoryOrder (this.extend (request, params));
<add> //
<add> // [
<add> // {
<add> // "id": "685965182082",
<add> // "client_order_id": "B3CBm9uGg9oYQlw96bBSEt38-6gbgBO0",
<add> // "symbol": "BTCUSDT",
<add> // "side": "buy",
<add> // "status": "new",
<add> // "type": "limit",
<add> // "time_in_force": "GTC",
<add> // "quantity": "0.00010",
<add> // "quantity_cumulative": "0",
<add> // "price": "50000.00",
<add> // "price_average": "0",
<add> // "created_at": "2021-10-26T11:40:09.287Z",
<add> // "updated_at": "2021-10-26T11:40:09.287Z"
<add> // }
<add> // ]
<add> //
<add> const order = this.safeValue (response, 0);
<add> return this.parseOrder (order, market);
<add> }
<add>
<ide> async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
<ide> await this.loadMarkets ();
<ide> let market = undefined; |
|
Java | bsd-3-clause | 9d604e8f412401235d7a6541d12e076029c2bd12 | 0 | APNIC-net/whois,APNIC-net/whois,APNIC-net/whois | package net.ripe.db.whois.api.whois.rdap;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import net.ripe.db.whois.api.AbstractRestClientTest;
import net.ripe.db.whois.api.httpserver.Audience;
import net.ripe.db.whois.api.whois.rdap.domain.*;
import net.ripe.db.whois.common.IntegrationTest;
import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.joda.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Collections;
import java.util.List;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.fail;
@Category(IntegrationTest.class)
public class WhoisRdapServiceTestIntegration extends AbstractRestClientTest {
private static final Audience AUDIENCE = Audience.PUBLIC;
@Before
public void setup() throws Exception {
databaseHelper.addObject("" +
"person: Test Person\n" +
"nic-hdl: TP1-TEST");
databaseHelper.addObject("" +
"mntner: OWNER-MNT\n" +
"descr: Owner Maintainer\n" +
"admin-c: TP1-TEST\n" +
"upd-to: [email protected]\n" +
"auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" +
"mnt-by: OWNER-MNT\n" +
"referral-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST");
databaseHelper.updateObject("" +
"person: Test Person\n" +
"address: Singel 258\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: TP1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"person: Test Person2\n" +
"address: Test Address\n" +
"phone: +61-1234-1234\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"nic-hdl: TP2-TEST\n" +
"changed: [email protected] 20120101\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"person: Pauleth Palthen\n" +
"address: Singel 258\n" +
"phone: +31-1234567890\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"nic-hdl: PP1-TEST\n" +
"changed: [email protected] 20120101\n" +
"changed: [email protected] 20120102\n" +
"changed: [email protected] 20120103\n" +
"remarks: remark\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"role: First Role\n" +
"address: Singel 258\n" +
"e-mail: [email protected]\n" +
"admin-c: PP1-TEST\n" +
"tech-c: PP1-TEST\n" +
"nic-hdl: FR1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121016\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"domain: 31.12.202.in-addr.arpa\n" +
"descr: Test domain\n" +
"admin-c: TP1-TEST\n" +
"tech-c: TP1-TEST\n" +
"zone-c: TP1-TEST\n" +
"notify: [email protected]\n" +
"nserver: ns1.test.com.au 10.0.0.1\n" +
"nserver: ns2.test.com.au 2001:10::2\n" +
"ds-rdata: 52151 1 1 13ee60f7499a70e5aadaf05828e7fc59e8e70bc1\n" +
"ds-rdata: 17881 5 1 2e58131e5fe28ec965a7b8e4efb52d0a028d7a78\n" +
"ds-rdata: 17881 5 2 8c6265733a73e5588bfac516a4fcfbe1103a544b95f254cb67a21e474079547e\n" +
"changed: [email protected] 20010816\n" +
"changed: [email protected] 20121121\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"aut-num: AS123\n" +
"as-name: AS-TEST\n" +
"descr: A single ASN\n" +
"admin-c: TP1-TEST\n" +
"tech-c: TP1-TEST\n" +
"changed: [email protected] 20010816\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"organisation: ORG-TEST1-TEST\n" +
"org-name: Test organisation\n" +
"org-type: OTHER\n" +
"descr: Drugs and gambling\n" +
"remarks: Nice to deal with generally\n" +
"address: 1 Fake St. Fauxville\n" +
"phone: +01-000-000-000\n" +
"fax-no: +01-000-000-000\n" +
"admin-c: PP1-TEST\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121121\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"as-block: AS100 - AS200\n" +
"descr: ARIN ASN block\n" +
"org: ORG-TEST1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121214\n" +
"source: TEST\n" +
"password: test\n");
ipTreeUpdater.rebuild();
}
@Before
@Override
public void setUpClient() throws Exception {
ClientConfig cc = new DefaultClientConfig();
cc.getSingletons().add(new JacksonJaxbJsonProvider());
client = Client.create(cc);
}
// inetnum
@Test
public void lookup_inetnum_range() {
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.255.255.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"country: NL\n" +
"language: en\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/192.0.0.0/8")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("192.0.0.0 - 192.255.255.255"));
assertThat(ip.getIpVersion(), is("v4"));
assertThat(ip.getLang(), is("en"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getStartAddress(), is("192.0.0.0/32"));
assertThat(ip.getEndAddress(), is("192.255.255.255/32"));
assertThat(ip.getName(), is("TEST-NET-NAME"));
assertThat(ip.getType(), is("OTHER"));
final List<Event> events = ip.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
final List<Notice> notices = ip.getNotices(); // TODO: [ES] values are dependant on rdap.properties
assertThat(notices, hasSize(3));
Collections.sort(notices);
assertThat(notices.get(0).getTitle(), is("Filtered"));
assertThat(notices.get(0).getDescription(), contains("This output has been filtered."));
assertThat(notices.get(0).getLinks(), is(nullValue()));
assertThat(notices.get(1).getTitle(), is("Source")); // TODO: [ES] should source be specified?
assertThat(notices.get(1).getDescription(), contains("Objects returned came from source", "TEST"));
assertThat(notices.get(1).getLinks(), is(nullValue()));
assertThat(notices.get(2).getTitle(), is("Terms and Conditions"));
assertThat(notices.get(2).getDescription(), contains("This is the RIPE Database query service. The objects are in RDAP format."));
// assertThat(notices.get(2).getLinks().getValue(), endsWith("/rdap/ip/192.0.0.0/8/ip/192.0.0.0 - 192.255.255.255")); // TODO: [ES] fix
assertThat(notices.get(2).getLinks().getRel(), is("terms-of-service"));
assertThat(notices.get(2).getLinks().getHref(), is("http://www.ripe.net/db/support/db-terms-conditions.pdf"));
}
@Test
public void lookup_inetnum_less_specific() {
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.255.255.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/192.0.0.255")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("192.0.0.0 - 192.255.255.255"));
assertThat(ip.getIpVersion(), is("v4"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getStartAddress(), is("192.0.0.0/32"));
assertThat(ip.getEndAddress(), is("192.255.255.255/32"));
assertThat(ip.getName(), is("TEST-NET-NAME"));
assertThat(ip.getLang(), is(nullValue()));
}
@Test
public void lookup_inetnum_not_found() {
try {
createResource(AUDIENCE, "ip/193.0.0.0")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
fail();
} catch (final UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
// inet6num
@Test
public void lookup_inet6num_with_prefix_length() throws Exception {
databaseHelper.addObject("" +
"inet6num: 2001:2002:2003::/48\n" +
"netname: RIPE-NCC\n" +
"descr: Private Network\n" +
"country: NL\n" +
"language: EN\n" +
"tech-c: TP1-TEST\n" +
"status: ASSIGNED PA\n" +
"mnt-by: OWNER-MNT\n" +
"mnt-lower: OWNER-MNT\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/2001:2002:2003::/48")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("2001:2002:2003::/48"));
assertThat(ip.getIpVersion(), is("v6"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getLang(), is("EN"));
assertThat(ip.getStartAddress(), is("2001:2002:2003::/128"));
assertThat(ip.getEndAddress(), is("2001:2002:2003:ffff:ffff:ffff:ffff:ffff/128"));
assertThat(ip.getName(), is("RIPE-NCC"));
assertThat(ip.getType(), is("ASSIGNED PA"));
final List<Event> events = ip.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
@Test
public void lookup_inet6num_less_specific() throws Exception {
databaseHelper.addObject("" +
"inet6num: 2001:2002:2003::/48\n" +
"netname: RIPE-NCC\n" +
"descr: Private Network\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: ASSIGNED PA\n" +
"mnt-by: OWNER-MNT\n" +
"mnt-lower: OWNER-MNT\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/2001:2002:2003:2004::")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("2001:2002:2003::/48"));
assertThat(ip.getIpVersion(), is("v6"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getStartAddress(), is("2001:2002:2003::/128"));
assertThat(ip.getEndAddress(), is("2001:2002:2003:ffff:ffff:ffff:ffff:ffff/128"));
assertThat(ip.getName(), is("RIPE-NCC"));
}
@Test
public void lookup_inet6num_not_found() {
try {
createResource(AUDIENCE, "ip/2001:2002:2003::/48")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
fail();
} catch (final UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
// person entity
@Test
public void lookup_person_entity() throws Exception {
final Entity entity = createResource(AUDIENCE, "entity/PP1-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("PP1-TEST"));
assertThat(entity.getRoles(), hasSize(0));
assertThat(entity.getPort43(), is("whois.ripe.net"));
assertThat(entity.getEntities(), hasSize(1));
assertThat(entity.getVCardArray().size(), is(2));
assertThat(entity.getVCardArray().get(0).toString(), is("vcard"));
assertThat(entity.getVCardArray().get(1).toString(), equalTo("" +
"[[version, {}, text, 4.0], " +
"[fn, {}, text, Pauleth Palthen], " +
"[kind, {}, text, individual], " +
"[adr, {label=Singel 258}, text, null], " +
"[tel, {type=voice}, text, +31-1234567890], " +
"[email, {}, text, [email protected]]]"));
assertThat(entity.getRdapConformance(), hasSize(1));
assertThat(entity.getRdapConformance().get(0), equalTo("rdap_level_0"));
final List<Event> events = entity.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
@Test
public void lookup_entity_not_found() throws Exception {
try {
createResource(AUDIENCE, "entity/nonexistant")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
} catch (final UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
@Test
public void lookup_entity_no_accept_header() {
final Entity entity = createResource(AUDIENCE, "entity/PP1-TEST")
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("PP1-TEST"));
assertThat(entity.getRdapConformance(), hasSize(1));
assertThat(entity.getRdapConformance().get(0), equalTo("rdap_level_0"));
}
// role entity
@Test
public void lookup_role_entity() throws Exception {
final Entity entity = createResource(AUDIENCE, "entity/FR1-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("FR1-TEST"));
assertThat(entity.getRoles(), hasSize(0));
assertThat(entity.getPort43(), is("whois.ripe.net"));
assertThat(entity.getVCardArray().size(), is(2));
assertThat(entity.getVCardArray().get(0).toString(), is("vcard"));
assertThat(entity.getVCardArray().get(1).toString(), equalTo("" +
"[[version, {}, text, 4.0], " +
"[fn, {}, text, First Role], " +
"[kind, {}, text, group], " +
"[adr, {label=Singel 258}, text, null], " +
"[email, {}, text, [email protected]]]"));
assertThat(entity.getEntities(), hasSize(2));
assertThat(entity.getEntities().get(0).getHandle(), is("OWNER-MNT"));
assertThat(entity.getEntities().get(0).getRoles(), contains("registrant"));
assertThat(entity.getEntities().get(1).getHandle(), is("PP1-TEST"));
assertThat(entity.getEntities().get(1).getRoles(), containsInAnyOrder("administrative", "technical"));
assertThat(entity.getRdapConformance(), hasSize(1));
assertThat(entity.getRdapConformance().get(0), equalTo("rdap_level_0"));
final List<Event> events = entity.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
// domain
@Test
public void lookup_domain_object() throws Exception {
final Domain domain = createResource(AUDIENCE, "domain/31.12.202.in-addr.arpa")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Domain.class);
assertThat(domain.getHandle(), equalTo("31.12.202.in-addr.arpa"));
assertThat(domain.getLdhName(), equalTo("31.12.202.in-addr.arpa"));
assertThat(domain.getRdapConformance(), hasSize(1));
assertThat(domain.getRdapConformance().get(0), equalTo("rdap_level_0"));
assertThat(domain.getPort43(), is("whois.ripe.net"));
final List<Event> events = domain.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
@Test
public void lookup_forward_domain() {
try {
createResource(AUDIENCE, "domain/ripe.net")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Domain.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
assertThat(e.getResponse().getEntity(String.class), is("RIPE NCC does not support forward domain queries."));
}
}
// autnum
@Test
public void autnum_not_found() throws Exception {
try {
createResource(AUDIENCE, "autnum/1")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
@Test
public void lookup_autnum_head_method() {
final ClientResponse response = createResource(AUDIENCE, "autnum/123").head();
assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
}
@Test
public void lookup_autnum_not_found_head_method() {
final ClientResponse response = createResource(AUDIENCE, "autnum/1").head();
assertThat(response.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
@Test
public void lookup_single_autnum() throws Exception {
final Autnum autnum = createResource(AUDIENCE, "autnum/123")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
assertThat(autnum.getHandle(), equalTo("AS123"));
assertThat(autnum.getStartAutnum(), is(nullValue()));
assertThat(autnum.getEndAutnum(), is(nullValue()));
assertThat(autnum.getName(), equalTo("AS-TEST"));
assertThat(autnum.getType(), equalTo("DIRECT ALLOCATION"));
final List<Event> events = autnum.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
final List<Entity> entities = autnum.getEntities();
assertThat(entities, hasSize(2));
assertThat(entities.get(0).getHandle(), is("OWNER-MNT"));
assertThat(entities.get(0).getRoles(), contains("registrant"));
assertThat(entities.get(1).getHandle(), is("TP1-TEST"));
assertThat(entities.get(1).getRoles(), containsInAnyOrder("administrative", "technical"));
final List<Link> links = autnum.getLinks();
assertThat(links, hasSize(2));
assertThat(links.get(0).getRel(), equalTo("self"));
assertThat(links.get(1).getRel(), equalTo("copyright"));
final List<Remark> remarks = autnum.getRemarks();
assertThat(remarks, hasSize(1));
assertThat(remarks.get(0).getDescription().get(0), is("A single ASN"));
}
@Test
public void lookup_autnum_with_rdap_json_content_type() {
final ClientResponse response = createResource(AUDIENCE, "autnum/123")
.accept("application/rdap+json")
.get(ClientResponse.class);
assertThat(response.getType(), is(new MediaType("application", "rdap+json")));
assertThat(response.getEntity(String.class), containsString("\"handle\":\"AS123\""));
}
@Test
public void lookup_autnum_within_block() throws Exception {
try {
createResource(AUDIENCE, "autnum/1500")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
@Test
public void lookup_autnum_has_abuse_contact() {
databaseHelper.addObject("" +
"role: Abuse Contact\n" +
"address: Singel 358\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: AB-TEST\n" +
"abuse-mailbox: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"organisation: ORG-TO2-TEST\n" +
"org-name: Test organisation\n" +
"org-type: OTHER\n" +
"abuse-c: AB-TEST\n" +
"descr: Drugs and gambling\n" +
"remarks: Nice to deal with generally\n" +
"address: 1 Fake St. Fauxville\n" +
"phone: +01-000-000-000\n" +
"fax-no: +01-000-000-000\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121121\n" +
"source: TEST\n");
databaseHelper.updateObject("" +
"aut-num: AS123\n" +
"as-name: AS-TEST\n" +
"descr: A single ASN\n" +
"org: ORG-TO2-TEST\n" +
"admin-c: TP1-TEST\n" +
"tech-c: TP1-TEST\n" +
"changed: [email protected] 20010816\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n");
final Autnum autnum = createResource(AUDIENCE, "autnum/123")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
assertThat(autnum.getEntities().get(0).getHandle(), is("OWNER-MNT"));
assertThat(autnum.getEntities().get(1).getHandle(), is("TP1-TEST"));
assertThat(autnum.getEntities().get(2).getHandle(), is("AB-TEST"));
assertThat(autnum.getEntities().get(2).getRoles(), contains("abuse"));
assertThat(autnum.getEntities().get(2).getVCardArray(), hasSize(2));
assertThat(autnum.getEntities().get(2).getVCardArray().get(0).toString(), is("vcard"));
assertThat(autnum.getEntities().get(2).getVCardArray().get(1).toString(), is("" +
"[[version, {}, text, 4.0], " +
"[fn, {}, text, Abuse Contact], " +
"[kind, {}, text, group], " +
"[adr, {label=Singel 358}, text, null], " +
"[tel, {type=voice}, text, +31 6 12345678]]"));
}
// general
@Test
public void multiple_modification_gives_correct_events() throws Exception {
final String rpslObject = "" +
"aut-num: AS123\n" +
"as-name: AS-TEST\n" +
"descr: Modified ASN\n" +
"admin-c: TP1-TEST\n" +
"tech-c: TP1-TEST\n" +
"changed: [email protected] 20010816\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n" +
"password: test\n";
final String response = syncupdate(rpslObject);
assertThat(response, containsString("Modify SUCCEEDED: [aut-num] AS123"));
final Autnum autnum = createResource(AUDIENCE, "autnum/123")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
final List<Event> events = autnum.getEvents();
assertThat(events, hasSize(1));
assertThat(events.get(0).getEventAction(), is("last changed"));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
}
@Test
public void lookup_inetnum_abuse_contact_as_vcard() {
databaseHelper.addObject("" +
"role: Abuse Contact\n" +
"address: Singel 258\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: AB-TEST\n" +
"abuse-mailbox: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"organisation: ORG-TO2-TEST\n" +
"org-name: Test organisation\n" +
"org-type: OTHER\n" +
"abuse-c: AB-TEST\n" +
"descr: Drugs and gambling\n" +
"remarks: Nice to deal with generally\n" +
"address: 1 Fake St. Fauxville\n" +
"phone: +01-000-000-000\n" +
"fax-no: +01-000-000-000\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121121\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.255.255.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"org: ORG-TO2-TEST\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.0.0.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/192.0.0.128")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getEntities().get(0).getHandle(), is("AB-TEST"));
assertThat(ip.getEntities().get(0).getRoles(), contains("abuse"));
assertThat(ip.getEntities().get(0).getVCardArray(), hasSize(2));
assertThat(ip.getEntities().get(0).getVCardArray().get(0).toString(), is("vcard"));
assertThat(ip.getEntities().get(0).getVCardArray().get(1).toString(), is("" +
"[[version, {}, text, 4.0], " +
"[fn, {}, text, Abuse Contact], " +
"[kind, {}, text, group], " +
"[adr, {label=Singel 258}, text, null], " +
"[tel, {type=voice}, text, +31 6 12345678]]"));
}
// organisation entity
@Test
public void lookup_org_entity_handle() throws Exception {
final Entity response = createResource(AUDIENCE, "entity/ORG-TEST1-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(response.getHandle(), equalTo("ORG-TEST1-TEST"));
}
@Test
public void lookup_org_not_found() throws Exception {
try {
createResource(AUDIENCE, "entity/ORG-NONE-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
@Test
public void lookup_org_entity() throws Exception {
databaseHelper.addObject("" +
"organisation: ORG-ONE-TEST\n" +
"org-name: Organisation One\n" +
"org-type: LIR\n" +
"descr: Test organisation\n" +
"address: One Org Street\n" +
"e-mail: [email protected]\n" +
"language: EN\n" +
"admin-c: TP2-TEST\n" +
"tech-c: TP1-TEST\n" +
"tech-c: TP2-TEST\n" +
"mnt-ref: OWNER-MNT\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20000228\n" +
"source: TEST\n");
final Entity entity = createResource(AUDIENCE, "entity/ORG-ONE-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("ORG-ONE-TEST"));
assertThat(entity.getRoles(), hasSize(0));
assertThat(entity.getPort43(), is("whois.ripe.net"));
assertThat(entity.getEvents().size(), equalTo(1));
final Event event = entity.getEvents().get(0);
assertTrue(event.getEventDate().isBefore(LocalDateTime.now()));
assertThat(event.getEventAction(), equalTo("last changed"));
assertThat(event.getEventActor(), is(nullValue()));
assertThat(entity.getEntities(), hasSize(3));
final List<Entity> entities = entity.getEntities();
Collections.sort(entities);
assertThat(entities.get(0).getHandle(), is("OWNER-MNT"));
assertThat(entities.get(0).getRoles(), contains("registrant"));
assertThat(entities.get(1).getHandle(), is("TP1-TEST"));
assertThat(entities.get(1).getRoles(), contains("technical"));
assertThat(entities.get(2).getHandle(), is("TP2-TEST"));
assertThat(entities.get(2).getRoles(), containsInAnyOrder("administrative", "technical"));
final List<Link> links = entity.getLinks();
assertThat(links, hasSize(2));
Collections.sort(links);
assertThat(links.get(0).getRel(), equalTo("self"));
final String orgLink = createResource(AUDIENCE, "entity/ORG-ONE-TEST").toString(); // TODO: implement
assertThat(links.get(0).getValue(), equalTo(orgLink));
assertThat(links.get(0).getHref(), equalTo(orgLink));
assertThat(links.get(1).getRel(), equalTo("copyright"));
assertThat(entity.getRemarks(), hasSize(1));
assertThat(entity.getRemarks().get(0).getDescription(), contains("Test organisation"));
// assertThat(entity.getLang(), is("EN")); TODO
}
@Override
protected WebResource createResource(final Audience audience, final String path) {
return client.resource(String.format("http://localhost:%s/rdap/%s", getPort(audience), path));
}
private String syncupdate(final String data) throws IOException {
return doPostOrPutRequest(getSyncupdatesUrl("test", ""), "POST", "DATA=" + encode(data), MediaType.APPLICATION_FORM_URLENCODED, HttpURLConnection.HTTP_OK);
}
private String getSyncupdatesUrl(final String instance, final String command) {
return "http://localhost:" + getPort(Audience.PUBLIC) + String.format("/whois/syncupdates/%s?%s", instance, command);
}
}
| whois-api/src/test/java/net/ripe/db/whois/api/whois/rdap/WhoisRdapServiceTestIntegration.java | package net.ripe.db.whois.api.whois.rdap;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import net.ripe.db.whois.api.AbstractRestClientTest;
import net.ripe.db.whois.api.httpserver.Audience;
import net.ripe.db.whois.api.whois.rdap.domain.*;
import net.ripe.db.whois.common.IntegrationTest;
import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.joda.time.LocalDateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Collections;
import java.util.List;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.fail;
@Category(IntegrationTest.class)
public class WhoisRdapServiceTestIntegration extends AbstractRestClientTest {
private static final Audience AUDIENCE = Audience.PUBLIC;
@Before
public void setup() throws Exception {
databaseHelper.addObject("" +
"person: Test Person\n" +
"nic-hdl: TP1-TEST");
databaseHelper.addObject("" +
"mntner: OWNER-MNT\n" +
"descr: Owner Maintainer\n" +
"admin-c: TP1-TEST\n" +
"upd-to: [email protected]\n" +
"auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" +
"mnt-by: OWNER-MNT\n" +
"referral-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST");
databaseHelper.updateObject("" +
"person: Test Person\n" +
"address: Singel 258\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: TP1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"person: Test Person2\n" +
"address: Test Address\n" +
"phone: +61-1234-1234\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"nic-hdl: TP2-TEST\n" +
"changed: [email protected] 20120101\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"person: Pauleth Palthen\n" +
"address: Singel 258\n" +
"phone: +31-1234567890\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"nic-hdl: PP1-TEST\n" +
"changed: [email protected] 20120101\n" +
"changed: [email protected] 20120102\n" +
"changed: [email protected] 20120103\n" +
"remarks: remark\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"role: First Role\n" +
"address: Singel 258\n" +
"e-mail: [email protected]\n" +
"admin-c: PP1-TEST\n" +
"tech-c: PP1-TEST\n" +
"nic-hdl: FR1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121016\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"domain: 31.12.202.in-addr.arpa\n" +
"descr: Test domain\n" +
"admin-c: TP1-TEST\n" +
"tech-c: TP1-TEST\n" +
"zone-c: TP1-TEST\n" +
"notify: [email protected]\n" +
"nserver: ns1.test.com.au 10.0.0.1\n" +
"nserver: ns2.test.com.au 2001:10::2\n" +
"ds-rdata: 52151 1 1 13ee60f7499a70e5aadaf05828e7fc59e8e70bc1\n" +
"ds-rdata: 17881 5 1 2e58131e5fe28ec965a7b8e4efb52d0a028d7a78\n" +
"ds-rdata: 17881 5 2 8c6265733a73e5588bfac516a4fcfbe1103a544b95f254cb67a21e474079547e\n" +
"changed: [email protected] 20010816\n" +
"changed: [email protected] 20121121\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"aut-num: AS123\n" +
"as-name: AS-TEST\n" +
"descr: A single ASN\n" +
"admin-c: TP1-TEST\n" +
"tech-c: TP1-TEST\n" +
"changed: [email protected] 20010816\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"organisation: ORG-TEST1-TEST\n" +
"org-name: Test organisation\n" +
"org-type: OTHER\n" +
"descr: Drugs and gambling\n" +
"remarks: Nice to deal with generally\n" +
"address: 1 Fake St. Fauxville\n" +
"phone: +01-000-000-000\n" +
"fax-no: +01-000-000-000\n" +
"admin-c: PP1-TEST\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121121\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"as-block: AS100 - AS200\n" +
"descr: ARIN ASN block\n" +
"org: ORG-TEST1-TEST\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121214\n" +
"source: TEST\n" +
"password: test\n");
ipTreeUpdater.rebuild();
}
@Before
@Override
public void setUpClient() throws Exception {
ClientConfig cc = new DefaultClientConfig();
cc.getSingletons().add(new JacksonJaxbJsonProvider());
client = Client.create(cc);
}
// inetnum
@Test
public void lookup_inetnum_range() {
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.255.255.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"country: NL\n" +
"language: en\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/192.0.0.0/8")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("192.0.0.0 - 192.255.255.255"));
assertThat(ip.getIpVersion(), is("v4"));
assertThat(ip.getLang(), is("en"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getStartAddress(), is("192.0.0.0/32"));
assertThat(ip.getEndAddress(), is("192.255.255.255/32"));
assertThat(ip.getName(), is("TEST-NET-NAME"));
assertThat(ip.getType(), is("OTHER"));
final List<Event> events = ip.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
final List<Notice> notices = ip.getNotices(); // TODO: [ES] values are dependant on rdap.properties
assertThat(notices, hasSize(3));
Collections.sort(notices);
assertThat(notices.get(0).getTitle(), is("Filtered"));
assertThat(notices.get(0).getDescription(), contains("This output has been filtered."));
assertThat(notices.get(0).getLinks(), is(nullValue()));
assertThat(notices.get(1).getTitle(), is("Source")); // TODO: [ES] should source be specified?
assertThat(notices.get(1).getDescription(), contains("Objects returned came from source", "TEST"));
assertThat(notices.get(1).getLinks(), is(nullValue()));
assertThat(notices.get(2).getTitle(), is("Terms and Conditions"));
assertThat(notices.get(2).getDescription(), contains("This is the RIPE Database query service. The objects are in RDAP format."));
// assertThat(notices.get(2).getLinks().getValue(), endsWith("/rdap/ip/192.0.0.0/8/ip/192.0.0.0 - 192.255.255.255")); // TODO: [ES] fix
assertThat(notices.get(2).getLinks().getRel(), is("terms-of-service"));
assertThat(notices.get(2).getLinks().getHref(), is("http://www.ripe.net/db/support/db-terms-conditions.pdf"));
}
@Test
public void lookup_inetnum_less_specific() {
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.255.255.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/192.0.0.255")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("192.0.0.0 - 192.255.255.255"));
assertThat(ip.getIpVersion(), is("v4"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getStartAddress(), is("192.0.0.0/32"));
assertThat(ip.getEndAddress(), is("192.255.255.255/32"));
assertThat(ip.getName(), is("TEST-NET-NAME"));
assertThat(ip.getLang(), is(nullValue()));
}
@Test
public void lookup_inetnum_not_found() {
try {
createResource(AUDIENCE, "ip/193.0.0.0")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
} catch (final UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
// inet6num
@Test
public void lookup_inet6num_with_prefix_length() throws Exception {
databaseHelper.addObject("" +
"inet6num: 2001:2002:2003::/48\n" +
"netname: RIPE-NCC\n" +
"descr: Private Network\n" +
"country: NL\n" +
"language: EN\n" +
"tech-c: TP1-TEST\n" +
"status: ASSIGNED PA\n" +
"mnt-by: OWNER-MNT\n" +
"mnt-lower: OWNER-MNT\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/2001:2002:2003::/48")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("2001:2002:2003::/48"));
assertThat(ip.getIpVersion(), is("v6"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getLang(), is("EN"));
assertThat(ip.getStartAddress(), is("2001:2002:2003::/128"));
assertThat(ip.getEndAddress(), is("2001:2002:2003:ffff:ffff:ffff:ffff:ffff/128"));
assertThat(ip.getName(), is("RIPE-NCC"));
assertThat(ip.getType(), is("ASSIGNED PA"));
final List<Event> events = ip.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
@Test
public void lookup_inet6num_less_specific() throws Exception {
databaseHelper.addObject("" +
"inet6num: 2001:2002:2003::/48\n" +
"netname: RIPE-NCC\n" +
"descr: Private Network\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: ASSIGNED PA\n" +
"mnt-by: OWNER-MNT\n" +
"mnt-lower: OWNER-MNT\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/2001:2002:2003:2004::")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getHandle(), is("2001:2002:2003::/48"));
assertThat(ip.getIpVersion(), is("v6"));
assertThat(ip.getCountry(), is("NL"));
assertThat(ip.getStartAddress(), is("2001:2002:2003::/128"));
assertThat(ip.getEndAddress(), is("2001:2002:2003:ffff:ffff:ffff:ffff:ffff/128"));
assertThat(ip.getName(), is("RIPE-NCC"));
}
// person entity
@Test
public void lookup_person_entity() throws Exception {
final Entity entity = createResource(AUDIENCE, "entity/PP1-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("PP1-TEST"));
assertThat(entity.getRoles(), hasSize(0));
assertThat(entity.getPort43(), is("whois.ripe.net"));
assertThat(entity.getEntities(), hasSize(1));
assertThat(entity.getVCardArray().size(), is(2));
assertThat(entity.getVCardArray().get(0).toString(), is("vcard"));
assertThat(entity.getVCardArray().get(1).toString(), equalTo("" +
"[[version, {}, text, 4.0], " +
"[fn, {}, text, Pauleth Palthen], " +
"[kind, {}, text, individual], " +
"[adr, {label=Singel 258}, text, null], " +
"[tel, {type=voice}, text, +31-1234567890], " +
"[email, {}, text, [email protected]]]"));
assertThat(entity.getRdapConformance(), hasSize(1));
assertThat(entity.getRdapConformance().get(0), equalTo("rdap_level_0"));
final List<Event> events = entity.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
@Test
public void lookup_entity_not_found() throws Exception {
try {
createResource(AUDIENCE, "entity/nonexistant")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
} catch (final UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
@Test
public void lookup_entity_no_accept_header() {
final Entity entity = createResource(AUDIENCE, "entity/PP1-TEST")
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("PP1-TEST"));
assertThat(entity.getRdapConformance(), hasSize(1));
assertThat(entity.getRdapConformance().get(0), equalTo("rdap_level_0"));
}
// role entity
@Test
public void lookup_role_entity() throws Exception {
final Entity entity = createResource(AUDIENCE, "entity/FR1-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("FR1-TEST"));
assertThat(entity.getRoles(), hasSize(0));
assertThat(entity.getPort43(), is("whois.ripe.net"));
assertThat(entity.getVCardArray().size(), is(2));
assertThat(entity.getVCardArray().get(0).toString(), is("vcard"));
assertThat(entity.getVCardArray().get(1).toString(), equalTo("" +
"[[version, {}, text, 4.0], " +
"[fn, {}, text, First Role], " +
"[kind, {}, text, group], " +
"[adr, {label=Singel 258}, text, null], " +
"[email, {}, text, [email protected]]]"));
assertThat(entity.getEntities(), hasSize(2));
assertThat(entity.getEntities().get(0).getHandle(), is("OWNER-MNT"));
assertThat(entity.getEntities().get(0).getRoles(), contains("registrant"));
assertThat(entity.getEntities().get(1).getHandle(), is("PP1-TEST"));
assertThat(entity.getEntities().get(1).getRoles(), containsInAnyOrder("administrative", "technical"));
assertThat(entity.getRdapConformance(), hasSize(1));
assertThat(entity.getRdapConformance().get(0), equalTo("rdap_level_0"));
final List<Event> events = entity.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
// domain
@Test
public void lookup_domain_object() throws Exception {
final Domain domain = createResource(AUDIENCE, "domain/31.12.202.in-addr.arpa")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Domain.class);
assertThat(domain.getHandle(), equalTo("31.12.202.in-addr.arpa"));
assertThat(domain.getLdhName(), equalTo("31.12.202.in-addr.arpa"));
assertThat(domain.getRdapConformance(), hasSize(1));
assertThat(domain.getRdapConformance().get(0), equalTo("rdap_level_0"));
assertThat(domain.getPort43(), is("whois.ripe.net"));
final List<Event> events = domain.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
}
@Test
public void lookup_forward_domain() {
try {
createResource(AUDIENCE, "domain/ripe.net")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Domain.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode()));
assertThat(e.getResponse().getEntity(String.class), is("RIPE NCC does not support forward domain queries."));
}
}
// autnum
@Test
public void autnum_not_found() throws Exception {
try {
createResource(AUDIENCE, "autnum/1")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
@Test
public void lookup_autnum_head_method() {
final ClientResponse response = createResource(AUDIENCE, "autnum/123").head();
assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));
}
@Test
public void lookup_autnum_not_found_head_method() {
final ClientResponse response = createResource(AUDIENCE, "autnum/1").head();
assertThat(response.getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
@Test
public void lookup_single_autnum() throws Exception {
final Autnum autnum = createResource(AUDIENCE, "autnum/123")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
assertThat(autnum.getHandle(), equalTo("AS123"));
assertThat(autnum.getStartAutnum(), is(nullValue()));
assertThat(autnum.getEndAutnum(), is(nullValue()));
assertThat(autnum.getName(), equalTo("AS-TEST"));
assertThat(autnum.getType(), equalTo("DIRECT ALLOCATION"));
final List<Event> events = autnum.getEvents();
assertThat(events, hasSize(1));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
assertThat(events.get(0).getEventAction(), is("last changed"));
final List<Entity> entities = autnum.getEntities();
assertThat(entities, hasSize(2));
assertThat(entities.get(0).getHandle(), is("OWNER-MNT"));
assertThat(entities.get(0).getRoles(), contains("registrant"));
assertThat(entities.get(1).getHandle(), is("TP1-TEST"));
assertThat(entities.get(1).getRoles(), containsInAnyOrder("administrative", "technical"));
final List<Link> links = autnum.getLinks();
assertThat(links, hasSize(2));
assertThat(links.get(0).getRel(), equalTo("self"));
assertThat(links.get(1).getRel(), equalTo("copyright"));
final List<Remark> remarks = autnum.getRemarks();
assertThat(remarks, hasSize(1));
assertThat(remarks.get(0).getDescription().get(0), is("A single ASN"));
}
@Test
public void lookup_autnum_with_rdap_json_content_type() {
final ClientResponse response = createResource(AUDIENCE, "autnum/123")
.accept("application/rdap+json")
.get(ClientResponse.class);
assertThat(response.getType(), is(new MediaType("application", "rdap+json")));
assertThat(response.getEntity(String.class), containsString("\"handle\":\"AS123\""));
}
@Test
public void lookup_autnum_within_block() throws Exception {
try {
createResource(AUDIENCE, "autnum/1500")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
// general
@Test
public void multiple_modification_gives_correct_events() throws Exception {
final String rpslObject = "" +
"aut-num: AS123\n" +
"as-name: AS-TEST\n" +
"descr: Modified ASN\n" +
"admin-c: TP1-TEST\n" +
"tech-c: TP1-TEST\n" +
"changed: [email protected] 20010816\n" +
"mnt-by: OWNER-MNT\n" +
"source: TEST\n" +
"password: test\n";
final String response = syncupdate(rpslObject);
assertThat(response, containsString("Modify SUCCEEDED: [aut-num] AS123"));
final Autnum autnum = createResource(AUDIENCE, "autnum/123")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Autnum.class);
final List<Event> events = autnum.getEvents();
assertThat(events, hasSize(1));
assertThat(events.get(0).getEventAction(), is("last changed"));
assertTrue(events.get(0).getEventDate().isBefore(LocalDateTime.now()));
}
@Test
public void lookup_inetnum_abuse_contact_as_vcard() {
databaseHelper.addObject("" +
"role: Abuse Contact\n" +
"address: Singel 258\n" +
"phone: +31 6 12345678\n" +
"nic-hdl: AB-TEST\n" +
"abuse-mailbox: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20120101\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"organisation: ORG-TO2-TEST\n" +
"org-name: Test organisation\n" +
"org-type: OTHER\n" +
"abuse-c: AB-TEST\n" +
"descr: Drugs and gambling\n" +
"remarks: Nice to deal with generally\n" +
"address: 1 Fake St. Fauxville\n" +
"phone: +01-000-000-000\n" +
"fax-no: +01-000-000-000\n" +
"e-mail: [email protected]\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20121121\n" +
"source: TEST\n");
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.255.255.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"org: ORG-TO2-TEST\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
databaseHelper.addObject("" +
"inetnum: 192.0.0.0 - 192.0.0.255\n" +
"netname: TEST-NET-NAME\n" +
"descr: TEST network\n" +
"country: NL\n" +
"tech-c: TP1-TEST\n" +
"status: OTHER\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20020101\n" +
"source: TEST");
ipTreeUpdater.rebuild();
final Ip ip = createResource(AUDIENCE, "ip/192.0.0.128")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Ip.class);
assertThat(ip.getEntities().get(0).getHandle(), is("AB-TEST"));
assertThat(ip.getEntities().get(0).getRoles(), contains("abuse"));
assertThat(ip.getEntities().get(0).getVCardArray(), hasSize(2));
assertThat(ip.getEntities().get(0).getVCardArray().get(0).toString(), is("vcard"));
assertThat(ip.getEntities().get(0).getVCardArray().get(1).toString(), is("" +
"[[version, {}, text, 4.0], " +
"[fn, {}, text, Abuse Contact], " +
"[kind, {}, text, group], " +
"[adr, {label=Singel 258}, text, null], " +
"[tel, {type=voice}, text, +31 6 12345678]]"));
}
// organisation entity
@Test
public void lookup_org_entity_handle() throws Exception {
final Entity response = createResource(AUDIENCE, "entity/ORG-TEST1-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(response.getHandle(), equalTo("ORG-TEST1-TEST"));
}
@Test
public void lookup_org_not_found() throws Exception {
try {
createResource(AUDIENCE, "entity/ORG-NONE-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
fail();
} catch (UniformInterfaceException e) {
assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
}
}
@Test
public void lookup_org_entity() throws Exception {
databaseHelper.addObject("" +
"organisation: ORG-ONE-TEST\n" +
"org-name: Organisation One\n" +
"org-type: LIR\n" +
"descr: Test organisation\n" +
"address: One Org Street\n" +
"e-mail: [email protected]\n" +
"language: EN\n" +
"admin-c: TP2-TEST\n" +
"tech-c: TP1-TEST\n" +
"tech-c: TP2-TEST\n" +
"mnt-ref: OWNER-MNT\n" +
"mnt-by: OWNER-MNT\n" +
"changed: [email protected] 20000228\n" +
"source: TEST\n");
final Entity entity = createResource(AUDIENCE, "entity/ORG-ONE-TEST")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(Entity.class);
assertThat(entity.getHandle(), equalTo("ORG-ONE-TEST"));
assertThat(entity.getRoles(), hasSize(0));
assertThat(entity.getPort43(), is("whois.ripe.net"));
assertThat(entity.getEvents().size(), equalTo(1));
final Event event = entity.getEvents().get(0);
assertTrue(event.getEventDate().isBefore(LocalDateTime.now()));
assertThat(event.getEventAction(), equalTo("last changed"));
assertThat(event.getEventActor(), is(nullValue()));
assertThat(entity.getEntities(), hasSize(3));
final List<Entity> entities = entity.getEntities();
Collections.sort(entities);
assertThat(entities.get(0).getHandle(), is("OWNER-MNT"));
assertThat(entities.get(0).getRoles(), contains("registrant"));
assertThat(entities.get(1).getHandle(), is("TP1-TEST"));
assertThat(entities.get(1).getRoles(), contains("technical"));
assertThat(entities.get(2).getHandle(), is("TP2-TEST"));
assertThat(entities.get(2).getRoles(), containsInAnyOrder("administrative", "technical"));
final List<Link> links = entity.getLinks();
assertThat(links, hasSize(2));
Collections.sort(links);
assertThat(links.get(0).getRel(), equalTo("self"));
final String orgLink = createResource(AUDIENCE, "entity/ORG-ONE-TEST").toString(); // TODO: implement
assertThat(links.get(0).getValue(), equalTo(orgLink));
assertThat(links.get(0).getHref(), equalTo(orgLink));
assertThat(links.get(1).getRel(), equalTo("copyright"));
assertThat(entity.getRemarks(), hasSize(1));
assertThat(entity.getRemarks().get(0).getDescription(), contains("Test organisation"));
// assertThat(entity.getLang(), is("EN")); TODO
}
@Override
protected WebResource createResource(final Audience audience, final String path) {
return client.resource(String.format("http://localhost:%s/rdap/%s", getPort(audience), path));
}
private String syncupdate(final String data) throws IOException {
return doPostOrPutRequest(getSyncupdatesUrl("test", ""), "POST", "DATA=" + encode(data), MediaType.APPLICATION_FORM_URLENCODED, HttpURLConnection.HTTP_OK);
}
private String getSyncupdatesUrl(final String instance, final String command) {
return "http://localhost:" + getPort(Audience.PUBLIC) + String.format("/whois/syncupdates/%s?%s", instance, command);
}
}
| some more test cases
| whois-api/src/test/java/net/ripe/db/whois/api/whois/rdap/WhoisRdapServiceTestIntegration.java | some more test cases | <ide><path>hois-api/src/test/java/net/ripe/db/whois/api/whois/rdap/WhoisRdapServiceTestIntegration.java
<ide> createResource(AUDIENCE, "ip/193.0.0.0")
<ide> .accept(MediaType.APPLICATION_JSON_TYPE)
<ide> .get(Ip.class);
<add> fail();
<ide> } catch (final UniformInterfaceException e) {
<ide> assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
<ide> }
<ide> assertThat(ip.getStartAddress(), is("2001:2002:2003::/128"));
<ide> assertThat(ip.getEndAddress(), is("2001:2002:2003:ffff:ffff:ffff:ffff:ffff/128"));
<ide> assertThat(ip.getName(), is("RIPE-NCC"));
<add> }
<add>
<add> @Test
<add> public void lookup_inet6num_not_found() {
<add> try {
<add> createResource(AUDIENCE, "ip/2001:2002:2003::/48")
<add> .accept(MediaType.APPLICATION_JSON_TYPE)
<add> .get(Ip.class);
<add> fail();
<add> } catch (final UniformInterfaceException e) {
<add> assertThat(e.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode()));
<add> }
<ide> }
<ide>
<ide> // person entity
<ide> }
<ide> }
<ide>
<add> @Test
<add> public void lookup_autnum_has_abuse_contact() {
<add> databaseHelper.addObject("" +
<add> "role: Abuse Contact\n" +
<add> "address: Singel 358\n" +
<add> "phone: +31 6 12345678\n" +
<add> "nic-hdl: AB-TEST\n" +
<add> "abuse-mailbox: [email protected]\n" +
<add> "mnt-by: OWNER-MNT\n" +
<add> "changed: [email protected] 20120101\n" +
<add> "source: TEST\n");
<add> databaseHelper.addObject("" +
<add> "organisation: ORG-TO2-TEST\n" +
<add> "org-name: Test organisation\n" +
<add> "org-type: OTHER\n" +
<add> "abuse-c: AB-TEST\n" +
<add> "descr: Drugs and gambling\n" +
<add> "remarks: Nice to deal with generally\n" +
<add> "address: 1 Fake St. Fauxville\n" +
<add> "phone: +01-000-000-000\n" +
<add> "fax-no: +01-000-000-000\n" +
<add> "e-mail: [email protected]\n" +
<add> "mnt-by: OWNER-MNT\n" +
<add> "changed: [email protected] 20121121\n" +
<add> "source: TEST\n");
<add> databaseHelper.updateObject("" +
<add> "aut-num: AS123\n" +
<add> "as-name: AS-TEST\n" +
<add> "descr: A single ASN\n" +
<add> "org: ORG-TO2-TEST\n" +
<add> "admin-c: TP1-TEST\n" +
<add> "tech-c: TP1-TEST\n" +
<add> "changed: [email protected] 20010816\n" +
<add> "mnt-by: OWNER-MNT\n" +
<add> "source: TEST\n");
<add>
<add> final Autnum autnum = createResource(AUDIENCE, "autnum/123")
<add> .accept(MediaType.APPLICATION_JSON_TYPE)
<add> .get(Autnum.class);
<add>
<add> assertThat(autnum.getEntities().get(0).getHandle(), is("OWNER-MNT"));
<add> assertThat(autnum.getEntities().get(1).getHandle(), is("TP1-TEST"));
<add> assertThat(autnum.getEntities().get(2).getHandle(), is("AB-TEST"));
<add> assertThat(autnum.getEntities().get(2).getRoles(), contains("abuse"));
<add> assertThat(autnum.getEntities().get(2).getVCardArray(), hasSize(2));
<add> assertThat(autnum.getEntities().get(2).getVCardArray().get(0).toString(), is("vcard"));
<add> assertThat(autnum.getEntities().get(2).getVCardArray().get(1).toString(), is("" +
<add> "[[version, {}, text, 4.0], " +
<add> "[fn, {}, text, Abuse Contact], " +
<add> "[kind, {}, text, group], " +
<add> "[adr, {label=Singel 358}, text, null], " +
<add> "[tel, {type=voice}, text, +31 6 12345678]]"));
<add> }
<add>
<ide> // general
<ide>
<ide> @Test |
|
Java | bsd-3-clause | 0a7e4067c4f8497a5cd1b71978eebb8851eab4e9 | 0 | broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected,broadinstitute/gatk-protected | package org.broadinstitute.hellbender.tools.exome;
import org.broadinstitute.hellbender.cmdline.*;
import org.broadinstitute.hellbender.cmdline.programgroups.CopyNumberProgramGroup;
import org.broadinstitute.hellbender.utils.segmenter.RCBSSegmenter;
import java.io.File;
@CommandLineProgramProperties(
summary = "Segment genomic data into regions of constant copy-ratio",
oneLineSummary = "Segment genomic data into regions of constant copy-ratio",
programGroup = CopyNumberProgramGroup.class
)
public final class PerformSegmentation extends CommandLineProgram {
public static final String TARGET_WEIGHT_FILE_LONG_NAME= "targetWeights";
public static final String TARGET_WEIGHT_FILE_SHORT_NAME = "tw";
public final static String ALPHA_LONG_NAME="alpha";
public final static String ALPHA_SHORT_NAME="alpha";
public final static String NPERM_LONG_NAME="nperm";
public final static String NPERM_SHORT_NAME="nperm";
public final static String PMETHOD_LONG_NAME="pmethod";
public final static String PMETHOD_SHORT_NAME="pmethod";
public final static String MINWIDTH_LONG_NAME="minWidth";
public final static String MINWIDTH_SHORT_NAME="minWidth";
public final static String KMAX_LONG_NAME="kmax";
public final static String KMAX_SHORT_NAME="kmax";
public final static String NMIN_LONG_NAME="nmin";
public final static String NMIN_SHORT_NAME="nmin";
public final static String ETA_LONG_NAME="eta";
public final static String ETA_SHORT_NAME="eta";
public final static String TRIM_LONG_NAME="trim";
public final static String TRIM_SHORT_NAME="trim";
public final static String UNDOSPLITS_LONG_NAME="undoSplits";
public final static String UNDOSPLITS_SHORT_NAME="undoSplits";
public final static String UNDOPRUNE_LONG_NAME="undoPrune";
public final static String UNDOPRUNE_SHORT_NAME="undoPrune";
public final static String UNDOSD_LONG_NAME="undoSD";
public final static String UNDOSD_SHORT_NAME="undoSD";
@Argument(
doc = "Name of the sample being segmented",
fullName = ExomeStandardArgumentDefinitions.SAMPLE_LONG_NAME,
optional = false
)
protected String sampleName;
@Argument(
doc = "Genomic targets file",
shortName = ExomeStandardArgumentDefinitions.TARGET_FILE_SHORT_NAME,
fullName = ExomeStandardArgumentDefinitions.TARGET_FILE_LONG_NAME,
optional = false
)
protected String tangentFile;
@Argument(
doc = "Full path to the outputted segment file",
shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME,
fullName = StandardArgumentDefinitions.OUTPUT_LONG_NAME,
optional = false
)
protected String outFile;
@Argument(
doc = "If input data has had a log2 transform applied",
shortName = ExomeStandardArgumentDefinitions.LOG2_SHORT_NAME,
fullName = ExomeStandardArgumentDefinitions.LOG2_LONG_NAME,
optional = true
)
protected Boolean log = false;
@Argument(
doc = "File with target weights. This is the 1/var(post-projected targets for each normal). " +
"Listed one value per line in plain text. Values of zero or less, Nan, Inf, and -Inf are not " +
"acceptable. Must have the same number of values as there are in the tangentFile.",
shortName = TARGET_WEIGHT_FILE_SHORT_NAME,
fullName = TARGET_WEIGHT_FILE_LONG_NAME,
optional = true
)
protected File weightFile = null;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = ALPHA_SHORT_NAME,
fullName = ALPHA_LONG_NAME,
optional = true
)
protected Double alpha = 0.01;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = NPERM_SHORT_NAME,
fullName = NPERM_LONG_NAME,
optional = true
)
protected Integer nperm = 10000;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = PMETHOD_SHORT_NAME,
fullName = PMETHOD_LONG_NAME,
optional = true
)
protected RCBSSegmenter.PMethod pmethod = RCBSSegmenter.PMethod.HYBRID;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = MINWIDTH_SHORT_NAME,
fullName = MINWIDTH_LONG_NAME,
optional = true
)
protected Integer minWidth = 2;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = KMAX_SHORT_NAME,
fullName = KMAX_LONG_NAME,
optional = true
)
protected Integer kmax = 25;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = NMIN_SHORT_NAME,
fullName = NMIN_LONG_NAME,
optional = true
)
protected Integer nmin = 200;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = ETA_SHORT_NAME,
fullName = ETA_LONG_NAME,
optional = true
)
protected Double eta = 0.05;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = TRIM_SHORT_NAME,
fullName = TRIM_LONG_NAME,
optional = true
)
protected Double trim = 0.025;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = UNDOSPLITS_SHORT_NAME,
fullName = UNDOSPLITS_LONG_NAME,
optional = true
)
protected RCBSSegmenter.UndoSplits undoSplits = RCBSSegmenter.UndoSplits.NONE;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = UNDOPRUNE_SHORT_NAME,
fullName = UNDOPRUNE_LONG_NAME,
optional = true
)
protected Double undoPrune = 0.05;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = UNDOSD_SHORT_NAME,
fullName = UNDOSD_LONG_NAME,
optional = true
)
protected Integer undoSD = 3;
@Override
protected Object doWork() {
applySegmentation(sampleName, tangentFile, outFile);
return "Success";
}
private void applySegmentation(String sampleName, String tangentFile, String outFile) {
RCBSSegmenter.writeSegmentFile(sampleName, tangentFile, outFile, log, weightFile, alpha, nperm, pmethod,
minWidth, kmax, nmin, eta, trim, undoSplits, undoPrune, undoSD);
}
}
| src/main/java/org/broadinstitute/hellbender/tools/exome/PerformSegmentation.java | package org.broadinstitute.hellbender.tools.exome;
import org.broadinstitute.hellbender.cmdline.*;
import org.broadinstitute.hellbender.cmdline.programgroups.CopyNumberProgramGroup;
import org.broadinstitute.hellbender.utils.segmenter.RCBSSegmenter;
import java.io.File;
@CommandLineProgramProperties(
summary = "Segment genomic data into regions of constant copy-ratio",
oneLineSummary = "Segment genomic data into regions of constant copy-ratio",
programGroup = CopyNumberProgramGroup.class
)
public final class PerformSegmentation extends CommandLineProgram {
public static final String TARGET_WEIGHT_FILE_LONG_NAME= "targetWeights";
public static final String TARGET_WEIGHT_FILE_SHORT_NAME = "tw";
public final static String ALPHA_LONG_NAME="alpha";
public final static String ALPHA_SHORT_NAME="alpha";
public final static String NPERM_LONG_NAME="nperm";
public final static String NPERM_SHORT_NAME="nperm";
public final static String PMETHOD_LONG_NAME="pmethod";
public final static String PMETHOD_SHORT_NAME="pmethod";
public final static String MINWIDTH_LONG_NAME="minWidth";
public final static String MINWIDTH_SHORT_NAME="minWidth";
public final static String KMAX_LONG_NAME="kmax";
public final static String KMAX_SHORT_NAME="kmax";
public final static String NMIN_LONG_NAME="nmin";
public final static String NMIN_SHORT_NAME="nmin";
public final static String ETA_LONG_NAME="eta";
public final static String ETA_SHORT_NAME="eta";
public final static String TRIM_LONG_NAME="trim";
public final static String TRIM_SHORT_NAME="trim";
public final static String UNDOSPLITS_LONG_NAME="undoSplits";
public final static String UNDOSPLITS_SHORT_NAME="undoSplits";
public final static String UNDOPRUNE_LONG_NAME="undoPrune";
public final static String UNDOPRUNE_SHORT_NAME="undoPrune";
public final static String UNDOSD_LONG_NAME="undoSD";
public final static String UNDOSD_SHORT_NAME="undoSD";
@Argument(
doc = "Name of the sample being segmented",
fullName = ExomeStandardArgumentDefinitions.SAMPLE_LONG_NAME,
optional = false
)
protected String sampleName;
@Argument(
doc = "Genomic targets file",
shortName = ExomeStandardArgumentDefinitions.TARGET_FILE_SHORT_NAME,
fullName = ExomeStandardArgumentDefinitions.TARGET_FILE_LONG_NAME,
optional = false
)
protected String tangentFile;
@Argument(
doc = "Full path to the outputted segment file",
shortName = StandardArgumentDefinitions.OUTPUT_SHORT_NAME,
fullName = StandardArgumentDefinitions.OUTPUT_LONG_NAME,
optional = false
)
protected String outFile;
@Argument(
doc = "If input data has had a log2 transform applied",
shortName = ExomeStandardArgumentDefinitions.LOG2_SHORT_NAME,
fullName = ExomeStandardArgumentDefinitions.LOG2_LONG_NAME,
optional = true
)
protected Boolean log = false;
@Argument(
doc = "File with target weights. This is the 1/var(post-projected targets for each normal). " +
"Listed one value per line in plain text. Values of zero or less, Nan, Inf, and -Inf are not " +
"acceptable. Must have the same number of values as there are in the tangentFile.",
shortName = TARGET_WEIGHT_FILE_SHORT_NAME,
fullName = TARGET_WEIGHT_FILE_LONG_NAME,
optional = true
)
protected File weightFile = null;
@Argument(
doc = "Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = ALPHA_SHORT_NAME,
fullName = ALPHA_LONG_NAME,
optional = true
)
protected Double alpha = 0.01;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = NPERM_SHORT_NAME,
fullName = NPERM_LONG_NAME,
optional = true
)
protected Integer nperm = 10000;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = PMETHOD_SHORT_NAME,
fullName = PMETHOD_LONG_NAME,
optional = true
)
protected RCBSSegmenter.PMethod pmethod = RCBSSegmenter.PMethod.HYBRID;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = MINWIDTH_SHORT_NAME,
fullName = MINWIDTH_LONG_NAME,
optional = true
)
protected Integer minWidth = 2;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = KMAX_SHORT_NAME,
fullName = KMAX_LONG_NAME,
optional = true
)
protected Integer kmax = 25;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = NMIN_SHORT_NAME,
fullName = NMIN_LONG_NAME,
optional = true
)
protected Integer nmin = 200;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = ETA_SHORT_NAME,
fullName = ETA_LONG_NAME,
optional = true
)
protected Double eta = 0.05;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = TRIM_SHORT_NAME,
fullName = TRIM_LONG_NAME,
optional = true
)
protected Double trim = 0.025;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = UNDOSPLITS_SHORT_NAME,
fullName = UNDOSPLITS_LONG_NAME,
optional = true
)
protected RCBSSegmenter.UndoSplits undoSplits = RCBSSegmenter.UndoSplits.NONE;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = UNDOPRUNE_SHORT_NAME,
fullName = UNDOPRUNE_LONG_NAME,
optional = true
)
protected Double undoPrune = 0.05;
@Argument(
doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
shortName = UNDOSD_SHORT_NAME,
fullName = UNDOSD_LONG_NAME,
optional = true
)
protected Integer undoSD = 3;
@Override
protected Object doWork() {
applySegmentation(sampleName, tangentFile, outFile);
return "Success";
}
private void applySegmentation(String sampleName, String tangentFile, String outFile) {
RCBSSegmenter.writeSegmentFile(sampleName, tangentFile, outFile, log, weightFile, alpha, nperm, pmethod,
minWidth, kmax, nmin, eta, trim, undoSplits, undoPrune, undoSD);
}
}
| Changes based on PR comments
| src/main/java/org/broadinstitute/hellbender/tools/exome/PerformSegmentation.java | Changes based on PR comments | <ide><path>rc/main/java/org/broadinstitute/hellbender/tools/exome/PerformSegmentation.java
<ide> protected File weightFile = null;
<ide>
<ide> @Argument(
<del> doc = "Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
<add> doc = "(Advanced) Please see https://www.bioconductor.org/packages/release/bioc/manuals/DNAcopy/man/DNAcopy.pdf",
<ide> shortName = ALPHA_SHORT_NAME,
<ide> fullName = ALPHA_LONG_NAME,
<ide> optional = true |
|
Java | apache-2.0 | bdd1ccd15eb2c58cd27da4878f568124333ea015 | 0 | wschaeferB/autopsy,millmanorama/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,esaunders/autopsy,APriestman/autopsy,rcordovano/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,esaunders/autopsy,wschaeferB/autopsy,APriestman/autopsy,wschaeferB/autopsy,APriestman/autopsy,wschaeferB/autopsy,millmanorama/autopsy,rcordovano/autopsy,millmanorama/autopsy,rcordovano/autopsy,APriestman/autopsy,millmanorama/autopsy,rcordovano/autopsy,rcordovano/autopsy,APriestman/autopsy,esaunders/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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 org.sleuthkit.autopsy.experimental.autoingest;
import java.io.Serializable;
import org.sleuthkit.autopsy.events.AutopsyEvent;
/**
* Event published when an automated ingest manager deprioritizes all or part of
* a case.
*/
final class AutoIngestCaseDeprioritizedEvent extends AutopsyEvent implements Serializable {
private static final long serialVersionUID = 1L;
private final String caseName;
private final String nodeName;
/**
* Constructs an event published when an automated ingest manager
* deprioritizes all or part of a case.
*
* @param caseName The name of the case.
* @param nodeName The host name of the node that deprioritized the case.
*/
AutoIngestCaseDeprioritizedEvent(String nodeName, String caseName) {
super(AutoIngestManager.Event.CASE_DEPRIORITIZED.toString(), null, null);
this.caseName = caseName;
this.nodeName = nodeName;
}
/**
* Gets the name of the deprioritized case.
*
* @return The case name.
*/
String getCaseName() {
return caseName;
}
/**
* Gets the host name of the node that deprioritized the case.
*
* @return The host name of the node.
*/
String getNodeName() {
return nodeName;
}
}
| Experimental/src/org/sleuthkit/autopsy/experimental/autoingest/AutoIngestCaseDeprioritizedEvent.java | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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 org.sleuthkit.autopsy.experimental.autoingest;
import java.io.Serializable;
import org.sleuthkit.autopsy.events.AutopsyEvent;
/**
* Event published when an automated ingest manager deprioritizes all or part of
* a case.
*/
final class AutoIngestCaseDeprioritizedEvent extends AutopsyEvent implements Serializable {
private static final long serialVersionUID = 1L;
private final String caseName;
private final String nodeName;
/**
* Constructs an event published when an automated ingest manager
* deprioritizes all or part of a case.
*
* @param caseName The name of the case.
* @param nodeName The host name of the node that deprioritized the case.
*/
public AutoIngestCaseDeprioritizedEvent(String nodeName, String caseName) {
super(AutoIngestManager.Event.CASE_DEPRIORITIZED.toString(), null, null);
this.caseName = caseName;
this.nodeName = nodeName;
}
/**
* Gets the name of the deprioritized case.
*
* @return The case name.
*/
public String getCaseName() {
return caseName;
}
/**
* Gets the host name of the node that deprioritized the case.
*
* @return The host name of the node.
*/
public String getNodeName() {
return nodeName;
}
}
| Minor fix.
| Experimental/src/org/sleuthkit/autopsy/experimental/autoingest/AutoIngestCaseDeprioritizedEvent.java | Minor fix. | <ide><path>xperimental/src/org/sleuthkit/autopsy/experimental/autoingest/AutoIngestCaseDeprioritizedEvent.java
<ide> * @param caseName The name of the case.
<ide> * @param nodeName The host name of the node that deprioritized the case.
<ide> */
<del> public AutoIngestCaseDeprioritizedEvent(String nodeName, String caseName) {
<add> AutoIngestCaseDeprioritizedEvent(String nodeName, String caseName) {
<ide> super(AutoIngestManager.Event.CASE_DEPRIORITIZED.toString(), null, null);
<ide> this.caseName = caseName;
<ide> this.nodeName = nodeName;
<ide> *
<ide> * @return The case name.
<ide> */
<del> public String getCaseName() {
<add> String getCaseName() {
<ide> return caseName;
<ide> }
<ide>
<ide> *
<ide> * @return The host name of the node.
<ide> */
<del> public String getNodeName() {
<add> String getNodeName() {
<ide> return nodeName;
<ide> }
<ide> |
|
Java | apache-2.0 | 1356642ff09875067641a9d5cf1c78d79caf3abb | 0 | consulo/consulo,consulo/consulo,pwoodworth/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,signed/intellij-community,blademainer/intellij-community,FHannes/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,supersven/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,kdwink/intellij-community,blademainer/intellij-community,kool79/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,diorcety/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,caot/intellij-community,signed/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,da1z/intellij-community,kdwink/intellij-community,clumsy/intellij-community,blademainer/intellij-community,fnouama/intellij-community,apixandru/intellij-community,petteyg/intellij-community,clumsy/intellij-community,samthor/intellij-community,signed/intellij-community,vladmm/intellij-community,caot/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,petteyg/intellij-community,supersven/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,joewalnes/idea-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,holmes/intellij-community,holmes/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,kool79/intellij-community,amith01994/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,signed/intellij-community,hurricup/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,allotria/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,consulo/consulo,asedunov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,fitermay/intellij-community,consulo/consulo,slisson/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,izonder/intellij-community,apixandru/intellij-community,petteyg/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,ryano144/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,kdwink/intellij-community,robovm/robovm-studio,fitermay/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fitermay/intellij-community,jagguli/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,adedayo/intellij-community,hurricup/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,ryano144/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,da1z/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,vladmm/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,kdwink/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,signed/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,xfournet/intellij-community,samthor/intellij-community,adedayo/intellij-community,semonte/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,FHannes/intellij-community,ibinti/intellij-community,holmes/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,ernestp/consulo,consulo/consulo,michaelgallacher/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,kool79/intellij-community,diorcety/intellij-community,signed/intellij-community,da1z/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,FHannes/intellij-community,samthor/intellij-community,dslomov/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,diorcety/intellij-community,Distrotech/intellij-community,semonte/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,kool79/intellij-community,izonder/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,holmes/intellij-community,samthor/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,Lekanich/intellij-community,supersven/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,signed/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,clumsy/intellij-community,samthor/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ahb0327/intellij-community,allotria/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,samthor/intellij-community,holmes/intellij-community,jagguli/intellij-community,xfournet/intellij-community,xfournet/intellij-community,semonte/intellij-community,caot/intellij-community,ryano144/intellij-community,robovm/robovm-studio,semonte/intellij-community,caot/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,caot/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,kool79/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,fnouama/intellij-community,ernestp/consulo,slisson/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,caot/intellij-community,ibinti/intellij-community,retomerz/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,slisson/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,slisson/intellij-community,retomerz/intellij-community,allotria/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,caot/intellij-community,signed/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,clumsy/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,allotria/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,caot/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,hurricup/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,diorcety/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,izonder/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,joewalnes/idea-community,fnouama/intellij-community,vladmm/intellij-community,holmes/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,semonte/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,ernestp/consulo,supersven/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,consulo/consulo,alphafoobar/intellij-community,slisson/intellij-community,allotria/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,signed/intellij-community,petteyg/intellij-community,fitermay/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,petteyg/intellij-community,supersven/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,semonte/intellij-community,robovm/robovm-studio,xfournet/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ernestp/consulo,apixandru/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,FHannes/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,petteyg/intellij-community,kool79/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,caot/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,supersven/intellij-community,xfournet/intellij-community,hurricup/intellij-community,kool79/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,adedayo/intellij-community,clumsy/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,allotria/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,akosyakov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,signed/intellij-community,samthor/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,allotria/intellij-community,signed/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,izonder/intellij-community,vladmm/intellij-community,diorcety/intellij-community,adedayo/intellij-community,da1z/intellij-community,vvv1559/intellij-community,supersven/intellij-community,dslomov/intellij-community,robovm/robovm-studio,amith01994/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,fnouama/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,xfournet/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,semonte/intellij-community,FHannes/intellij-community,amith01994/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,fnouama/intellij-community,samthor/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,samthor/intellij-community,adedayo/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community | /*
* Copyright (c) 2005 Your Corporation. All Rights Reserved.
*/
package com.intellij.psi.impl.search;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.search.SearchRequestCollector;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.UsageSearchContext;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.Processor;
/**
* @author max
*/
public class MethodUsagesSearcher extends QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters> {
@Override
public void processQuery(MethodReferencesSearch.SearchParameters p, Processor<PsiReference> consumer) {
final PsiMethod method = p.getMethod();
final SearchRequestCollector collector = p.getOptimizer();
final SearchScope searchScope = p.getScope();
final PsiManager psiManager = PsiManager.getInstance(method.getProject());
final PsiClass aClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {
public PsiClass compute() {
return method.isValid() ? method.getContainingClass() : null;
}
});
if (aClass == null) return;
final boolean strictSignatureSearch = p.isStrictSignatureSearch();
if (method.isConstructor()) {
collector.searchCustom(new Processor<Processor<PsiReference>>() {
public boolean process(Processor<PsiReference> consumer) {
return new ConstructorReferencesSearchHelper(psiManager).
processConstructorReferences(consumer, method, searchScope, !strictSignatureSearch, strictSignatureSearch);
}
});
}
boolean needStrictSignatureSearch = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
public Boolean compute() {
return method.isValid() && strictSignatureSearch && (aClass instanceof PsiAnonymousClass
|| aClass.hasModifierProperty(PsiModifier.FINAL)
|| method.hasModifierProperty(PsiModifier.STATIC)
|| method.hasModifierProperty(PsiModifier.FINAL)
|| method.hasModifierProperty(PsiModifier.PRIVATE));
}
});
if (needStrictSignatureSearch) {
ReferencesSearch.search(new ReferencesSearch.SearchParameters(method, searchScope, false, collector)).forEach(consumer);
return;
}
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
if (!method.isValid()) return;
final String textToSearch = method.getName();
final PsiMethod[] methods = strictSignatureSearch ? new PsiMethod[]{method} : aClass.findMethodsByName(textToSearch, false);
SearchScope accessScope = methods[0].getUseScope();
for (int i = 1; i < methods.length; i++) {
PsiMethod method1 = methods[i];
accessScope = accessScope.union(method1.getUseScope());
}
final SearchScope restrictedByAccess = searchScope.intersectWith(accessScope);
short searchContext = UsageSearchContext.IN_CODE | UsageSearchContext.IN_COMMENTS | UsageSearchContext.IN_FOREIGN_LANGUAGES;
collector.searchWord(textToSearch, restrictedByAccess, searchContext, true,
new MethodTextOccurrenceProcessor(aClass, strictSignatureSearch, methods));
SimpleAccessorReferenceSearcher.addPropertyAccessUsages(method, restrictedByAccess, collector);
}
});
}
}
| java/java-impl/src/com/intellij/psi/impl/search/MethodUsagesSearcher.java | /*
* Copyright (c) 2005 Your Corporation. All Rights Reserved.
*/
package com.intellij.psi.impl.search;
import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.psi.*;
import com.intellij.psi.search.SearchRequestCollector;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.UsageSearchContext;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.Processor;
/**
* @author max
*/
public class MethodUsagesSearcher extends QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters> {
public MethodUsagesSearcher() {
super(true);
}
@Override
public void processQuery(MethodReferencesSearch.SearchParameters p, Processor<PsiReference> consumer) {
final PsiMethod method = p.getMethod();
final SearchRequestCollector collector = p.getOptimizer();
final SearchScope searchScope = p.getScope();
final PsiManager psiManager = PsiManager.getInstance(method.getProject());
final PsiClass aClass = method.getContainingClass();
if (aClass == null) return;
final boolean strictSignatureSearch = p.isStrictSignatureSearch();
if (method.isConstructor()) {
collector.searchCustom(new Processor<Processor<PsiReference>>() {
public boolean process(Processor<PsiReference> consumer) {
return new ConstructorReferencesSearchHelper(psiManager).
processConstructorReferences(consumer, method, searchScope, !strictSignatureSearch, strictSignatureSearch);
}
});
}
boolean needStrictSignatureSearch = method.isValid() && strictSignatureSearch && (aClass instanceof PsiAnonymousClass
|| aClass.hasModifierProperty(PsiModifier.FINAL)
|| method.hasModifierProperty(PsiModifier.STATIC)
|| method.hasModifierProperty(PsiModifier.FINAL)
|| method.hasModifierProperty(PsiModifier.PRIVATE));
if (needStrictSignatureSearch) {
ReferencesSearch.search(new ReferencesSearch.SearchParameters(method, searchScope, false, collector)).forEach(consumer);
return;
}
final String textToSearch = method.getName();
final PsiMethod[] methods = strictSignatureSearch ? new PsiMethod[]{method} : aClass.findMethodsByName(textToSearch, false);
SearchScope accessScope = methods[0].getUseScope();
for (int i = 1; i < methods.length; i++) {
PsiMethod method1 = methods[i];
accessScope = accessScope.union(method1.getUseScope());
}
final SearchScope restrictedByAccess = searchScope.intersectWith(accessScope);
short searchContext = UsageSearchContext.IN_CODE | UsageSearchContext.IN_COMMENTS | UsageSearchContext.IN_FOREIGN_LANGUAGES;
collector.searchWord(textToSearch, restrictedByAccess, searchContext, true, new MethodTextOccurrenceProcessor(aClass, strictSignatureSearch, methods));
SimpleAccessorReferenceSearcher.addPropertyAccessUsages(method, restrictedByAccess, collector);
}
}
| don't take a potentially long read action
| java/java-impl/src/com/intellij/psi/impl/search/MethodUsagesSearcher.java | don't take a potentially long read action | <ide><path>ava/java-impl/src/com/intellij/psi/impl/search/MethodUsagesSearcher.java
<ide> */
<ide> package com.intellij.psi.impl.search;
<ide>
<add>import com.intellij.openapi.application.ApplicationManager;
<ide> import com.intellij.openapi.application.QueryExecutorBase;
<add>import com.intellij.openapi.util.Computable;
<ide> import com.intellij.psi.*;
<ide> import com.intellij.psi.search.SearchRequestCollector;
<ide> import com.intellij.psi.search.SearchScope;
<ide> */
<ide> public class MethodUsagesSearcher extends QueryExecutorBase<PsiReference, MethodReferencesSearch.SearchParameters> {
<ide>
<del> public MethodUsagesSearcher() {
<del> super(true);
<del> }
<del>
<ide> @Override
<ide> public void processQuery(MethodReferencesSearch.SearchParameters p, Processor<PsiReference> consumer) {
<ide> final PsiMethod method = p.getMethod();
<ide>
<ide> final PsiManager psiManager = PsiManager.getInstance(method.getProject());
<ide>
<del> final PsiClass aClass = method.getContainingClass();
<add> final PsiClass aClass = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass>() {
<add> public PsiClass compute() {
<add> return method.isValid() ? method.getContainingClass() : null;
<add> }
<add> });
<ide> if (aClass == null) return;
<ide>
<ide> final boolean strictSignatureSearch = p.isStrictSignatureSearch();
<ide> });
<ide> }
<ide>
<del> boolean needStrictSignatureSearch = method.isValid() && strictSignatureSearch && (aClass instanceof PsiAnonymousClass
<del> || aClass.hasModifierProperty(PsiModifier.FINAL)
<del> || method.hasModifierProperty(PsiModifier.STATIC)
<del> || method.hasModifierProperty(PsiModifier.FINAL)
<del> || method.hasModifierProperty(PsiModifier.PRIVATE));
<add> boolean needStrictSignatureSearch = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
<add> public Boolean compute() {
<add> return method.isValid() && strictSignatureSearch && (aClass instanceof PsiAnonymousClass
<add> || aClass.hasModifierProperty(PsiModifier.FINAL)
<add> || method.hasModifierProperty(PsiModifier.STATIC)
<add> || method.hasModifierProperty(PsiModifier.FINAL)
<add> || method.hasModifierProperty(PsiModifier.PRIVATE));
<add> }
<add> });
<ide> if (needStrictSignatureSearch) {
<ide> ReferencesSearch.search(new ReferencesSearch.SearchParameters(method, searchScope, false, collector)).forEach(consumer);
<ide> return;
<ide> }
<ide>
<del> final String textToSearch = method.getName();
<del> final PsiMethod[] methods = strictSignatureSearch ? new PsiMethod[]{method} : aClass.findMethodsByName(textToSearch, false);
<add> ApplicationManager.getApplication().runReadAction(new Runnable() {
<add> public void run() {
<add> if (!method.isValid()) return;
<ide>
<del> SearchScope accessScope = methods[0].getUseScope();
<del> for (int i = 1; i < methods.length; i++) {
<del> PsiMethod method1 = methods[i];
<del> accessScope = accessScope.union(method1.getUseScope());
<del> }
<add> final String textToSearch = method.getName();
<add> final PsiMethod[] methods = strictSignatureSearch ? new PsiMethod[]{method} : aClass.findMethodsByName(textToSearch, false);
<ide>
<del> final SearchScope restrictedByAccess = searchScope.intersectWith(accessScope);
<add> SearchScope accessScope = methods[0].getUseScope();
<add> for (int i = 1; i < methods.length; i++) {
<add> PsiMethod method1 = methods[i];
<add> accessScope = accessScope.union(method1.getUseScope());
<add> }
<ide>
<del> short searchContext = UsageSearchContext.IN_CODE | UsageSearchContext.IN_COMMENTS | UsageSearchContext.IN_FOREIGN_LANGUAGES;
<del> collector.searchWord(textToSearch, restrictedByAccess, searchContext, true, new MethodTextOccurrenceProcessor(aClass, strictSignatureSearch, methods));
<add> final SearchScope restrictedByAccess = searchScope.intersectWith(accessScope);
<ide>
<del> SimpleAccessorReferenceSearcher.addPropertyAccessUsages(method, restrictedByAccess, collector);
<add> short searchContext = UsageSearchContext.IN_CODE | UsageSearchContext.IN_COMMENTS | UsageSearchContext.IN_FOREIGN_LANGUAGES;
<add> collector.searchWord(textToSearch, restrictedByAccess, searchContext, true,
<add> new MethodTextOccurrenceProcessor(aClass, strictSignatureSearch, methods));
<add>
<add> SimpleAccessorReferenceSearcher.addPropertyAccessUsages(method, restrictedByAccess, collector);
<add> }
<add> });
<add>
<ide> }
<ide>
<ide> } |
|
Java | mit | 40793e54ca9b2123a2c98ef7eee072d99abecd1e | 0 | MatthewSH/spigot-VPNGuard | package com.matthewhatcher.vpnguard.Utils;
import java.util.ArrayList;
import java.util.List;
import com.matthewhatcher.vpnguard.VPNGuard;
public class FileUtils
{
private VPNGuard plugin;
public List<String> cachedIPs = new ArrayList<String>();
public FileUtils(VPNGuard plugin) {
this.plugin = plugin;
}
}
| src/main/java/com/matthewhatcher/vpnguard/Utils/FileUtils.java | package com.matthewhatcher.vpnguard.Utils;
import com.matthewhatcher.vpnguard.VPNGuard;
public class FileUtils
{
private VPNGuard plugin;
public FileUtils(VPNGuard plugin) {
this.plugin = plugin;
}
}
| Adding cached IPs list.
| src/main/java/com/matthewhatcher/vpnguard/Utils/FileUtils.java | Adding cached IPs list. | <ide><path>rc/main/java/com/matthewhatcher/vpnguard/Utils/FileUtils.java
<ide> package com.matthewhatcher.vpnguard.Utils;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide>
<ide> import com.matthewhatcher.vpnguard.VPNGuard;
<ide>
<ide> public class FileUtils
<ide> {
<ide> private VPNGuard plugin;
<add> public List<String> cachedIPs = new ArrayList<String>();
<ide>
<ide> public FileUtils(VPNGuard plugin) {
<ide> this.plugin = plugin; |
|
Java | apache-2.0 | a40b261d0cb77420fca6eed17952677aa49c788b | 0 | zjureel/flink,clarkyzl/flink,aljoscha/flink,xccui/flink,gyfora/flink,xccui/flink,lincoln-lil/flink,godfreyhe/flink,rmetzger/flink,xccui/flink,zjureel/flink,kl0u/flink,StephanEwen/incubator-flink,apache/flink,twalthr/flink,wwjiang007/flink,zjureel/flink,tony810430/flink,apache/flink,kl0u/flink,zentol/flink,tillrohrmann/flink,wwjiang007/flink,aljoscha/flink,tony810430/flink,godfreyhe/flink,twalthr/flink,twalthr/flink,zentol/flink,aljoscha/flink,StephanEwen/incubator-flink,gyfora/flink,rmetzger/flink,gyfora/flink,clarkyzl/flink,twalthr/flink,xccui/flink,aljoscha/flink,lincoln-lil/flink,kl0u/flink,gyfora/flink,tony810430/flink,zentol/flink,xccui/flink,apache/flink,clarkyzl/flink,tillrohrmann/flink,wwjiang007/flink,wwjiang007/flink,apache/flink,kl0u/flink,gyfora/flink,lincoln-lil/flink,zjureel/flink,tony810430/flink,twalthr/flink,tony810430/flink,apache/flink,godfreyhe/flink,twalthr/flink,lincoln-lil/flink,gyfora/flink,zjureel/flink,kl0u/flink,apache/flink,wwjiang007/flink,lincoln-lil/flink,wwjiang007/flink,gyfora/flink,twalthr/flink,tillrohrmann/flink,lincoln-lil/flink,tillrohrmann/flink,rmetzger/flink,kl0u/flink,StephanEwen/incubator-flink,lincoln-lil/flink,aljoscha/flink,godfreyhe/flink,tillrohrmann/flink,StephanEwen/incubator-flink,wwjiang007/flink,StephanEwen/incubator-flink,tillrohrmann/flink,zjureel/flink,tony810430/flink,rmetzger/flink,rmetzger/flink,godfreyhe/flink,zentol/flink,xccui/flink,godfreyhe/flink,zentol/flink,apache/flink,tony810430/flink,zentol/flink,aljoscha/flink,xccui/flink,clarkyzl/flink,godfreyhe/flink,clarkyzl/flink,rmetzger/flink,zjureel/flink,zentol/flink,tillrohrmann/flink,rmetzger/flink,StephanEwen/incubator-flink | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.flink.connectors.hive;
import org.apache.flink.table.HiveVersionTestUtil;
import org.apache.flink.table.api.SqlDialect;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.constraints.UniqueConstraint;
import org.apache.flink.table.api.internal.TableImpl;
import org.apache.flink.table.catalog.CatalogBaseTable;
import org.apache.flink.table.catalog.ObjectPath;
import org.apache.flink.table.catalog.hive.HiveCatalog;
import org.apache.flink.table.catalog.hive.HiveTestUtils;
import org.apache.flink.table.catalog.hive.client.HiveMetastoreClientFactory;
import org.apache.flink.table.catalog.hive.client.HiveMetastoreClientWrapper;
import org.apache.flink.table.catalog.hive.client.HiveShimLoader;
import org.apache.flink.types.Row;
import org.apache.flink.util.CollectionUtil;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.Table;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Test hive connector with table API.
*/
public class TableEnvHiveConnectorITCase {
private static HiveCatalog hiveCatalog;
private static HiveMetastoreClientWrapper hmsClient;
@BeforeClass
public static void setup() {
hiveCatalog = HiveTestUtils.createHiveCatalog();
hiveCatalog.open();
hmsClient = HiveMetastoreClientFactory.create(hiveCatalog.getHiveConf(), HiveShimLoader.getHiveVersion());
}
@Test
public void testDefaultPartitionName() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
tableEnv.executeSql("create table db1.src (x int, y int)");
tableEnv.executeSql("create table db1.part (x int) partitioned by (y int)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "src").addRow(new Object[]{1, 1}).addRow(new Object[]{2, null}).commit();
// test generating partitions with default name
tableEnv.executeSql("insert into db1.part select * from db1.src").await();
HiveConf hiveConf = hiveCatalog.getHiveConf();
String defaultPartName = hiveConf.getVar(HiveConf.ConfVars.DEFAULTPARTITIONNAME);
Table hiveTable = hmsClient.getTable("db1", "part");
Path defaultPartPath = new Path(hiveTable.getSd().getLocation(), "y=" + defaultPartName);
FileSystem fs = defaultPartPath.getFileSystem(hiveConf);
assertTrue(fs.exists(defaultPartPath));
TableImpl flinkTable = (TableImpl) tableEnv.sqlQuery("select y, x from db1.part order by x");
List<Row> rows = CollectionUtil.iteratorToList(flinkTable.execute().collect());
assertEquals(Arrays.toString(new String[]{"1,1", "null,2"}), rows.toString());
tableEnv.executeSql("drop database db1 cascade");
}
@Test
public void testGetNonExistingFunction() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
tableEnv.executeSql("create table db1.src (d double, s string)");
tableEnv.executeSql("create table db1.dest (x bigint)");
// just make sure the query runs through, no need to verify result
tableEnv.executeSql("insert into db1.dest select count(d) from db1.src").await();
tableEnv.executeSql("drop database db1 cascade");
}
@Test
public void testDateTimestampPartitionColumns() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.part(x int) partitioned by (dt date,ts timestamp)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part")
.addRow(new Object[]{1})
.addRow(new Object[]{2})
.commit("dt='2019-12-23',ts='2019-12-23 00:00:00'");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part")
.addRow(new Object[]{3})
.commit("dt='2019-12-25',ts='2019-12-25 16:23:43.012'");
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.part order by x").execute().collect());
assertEquals("[1,2019-12-23,2019-12-23T00:00, 2,2019-12-23,2019-12-23T00:00, 3,2019-12-25,2019-12-25T16:23:43.012]", results.toString());
results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select x from db1.part where dt=cast('2019-12-25' as date)").execute().collect());
assertEquals("[3]", results.toString());
tableEnv.executeSql("insert into db1.part select 4,cast('2019-12-31' as date),cast('2019-12-31 12:00:00.0' as timestamp)")
.await();
results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select max(dt) from db1.part").execute().collect());
assertEquals("[2019-12-31]", results.toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testUDTF() throws Exception {
// W/o https://issues.apache.org/jira/browse/HIVE-11878 Hive registers the App classloader as the classloader
// for the UDTF and closes the App classloader when we tear down the session. This causes problems for JUnit code
// and shutdown hooks that have to run after the test finishes, because App classloader can no longer load new
// classes. And will crash the forked JVM, thus failing the test phase.
// Therefore disable such tests for older Hive versions.
String hiveVersion = HiveShimLoader.getHiveVersion();
Assume.assumeTrue(hiveVersion.compareTo("2.0.0") >= 0 || hiveVersion.compareTo("1.3.0") >= 0);
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.simple (i int,a array<int>)");
tableEnv.executeSql("create table db1.nested (a array<map<int, string>>)");
tableEnv.executeSql("create function hiveudtf as 'org.apache.hadoop.hive.ql.udf.generic.GenericUDTFExplode'");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "simple")
.addRow(new Object[]{3, Arrays.asList(1, 2, 3)})
.commit();
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "a");
map1.put(2, "b");
Map<Integer, String> map2 = new HashMap<>();
map2.put(3, "c");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "nested")
.addRow(new Object[]{Arrays.asList(map1, map2)})
.commit();
List<Row> results = CollectionUtil.iteratorToList(
tableEnv.sqlQuery("select x from db1.simple, lateral table(hiveudtf(a)) as T(x)").execute().collect());
assertEquals("[1, 2, 3]", results.toString());
results = CollectionUtil.iteratorToList(
tableEnv.sqlQuery("select x from db1.nested, lateral table(hiveudtf(a)) as T(x)").execute().collect());
assertEquals("[{1=a, 2=b}, {3=c}]", results.toString());
tableEnv.executeSql("create table db1.ts (a array<timestamp>)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "ts").addRow(new Object[]{
new Object[]{Timestamp.valueOf("2015-04-28 15:23:00"), Timestamp.valueOf("2016-06-03 17:05:52")}})
.commit();
results = CollectionUtil.iteratorToList(
tableEnv.sqlQuery("select x from db1.ts, lateral table(hiveudtf(a)) as T(x)").execute().collect());
assertEquals("[2015-04-28T15:23, 2016-06-03T17:05:52]", results.toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
tableEnv.executeSql("drop function hiveudtf");
}
}
@Test
public void testNotNullConstraints() throws Exception {
Assume.assumeTrue(HiveVersionTestUtil.HIVE_310_OR_LATER);
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.tbl (x int,y bigint not null enable rely,z string not null enable norely)");
CatalogBaseTable catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl"));
TableSchema tableSchema = catalogTable.getSchema();
assertTrue("By default columns should be nullable",
tableSchema.getFieldDataTypes()[0].getLogicalType().isNullable());
assertFalse("NOT NULL columns should be reflected in table schema",
tableSchema.getFieldDataTypes()[1].getLogicalType().isNullable());
assertTrue("NOT NULL NORELY columns should be considered nullable",
tableSchema.getFieldDataTypes()[2].getLogicalType().isNullable());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testPKConstraint() throws Exception {
// While PK constraints are supported since Hive 2.1.0, the constraints cannot be RELY in 2.x versions.
// So let's only test for 3.x.
Assume.assumeTrue(HiveVersionTestUtil.HIVE_310_OR_LATER);
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
// test rely PK constraints
tableEnv.executeSql("create table db1.tbl1 (x tinyint,y smallint,z int, primary key (x,z) disable novalidate rely)");
CatalogBaseTable catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl1"));
TableSchema tableSchema = catalogTable.getSchema();
assertTrue(tableSchema.getPrimaryKey().isPresent());
UniqueConstraint pk = tableSchema.getPrimaryKey().get();
assertEquals(2, pk.getColumns().size());
assertTrue(pk.getColumns().containsAll(Arrays.asList("x", "z")));
// test norely PK constraints
tableEnv.executeSql("create table db1.tbl2 (x tinyint,y smallint, primary key (x) disable norely)");
catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl2"));
tableSchema = catalogTable.getSchema();
assertFalse(tableSchema.getPrimaryKey().isPresent());
// test table w/o PK
tableEnv.executeSql("create table db1.tbl3 (x tinyint)");
catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl3"));
tableSchema = catalogTable.getSchema();
assertFalse(tableSchema.getPrimaryKey().isPresent());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testRegexSerDe() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.src (x int,y string) " +
"row format serde 'org.apache.hadoop.hive.serde2.RegexSerDe' " +
"with serdeproperties ('input.regex'='([\\\\d]+)\\u0001([\\\\S]+)')");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "src")
.addRow(new Object[]{1, "a"})
.addRow(new Object[]{2, "ab"})
.commit();
assertEquals("[1,a, 2,ab]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.src order by x").execute().collect()).toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testUpdatePartitionSD() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.dest (x int) partitioned by (p string) stored as rcfile");
tableEnv.executeSql("insert overwrite db1.dest partition (p='1') select 1").await();
tableEnv.executeSql("alter table db1.dest set fileformat sequencefile");
tableEnv.executeSql("insert overwrite db1.dest partition (p='1') select 1").await();
assertEquals("[1,1]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.dest").execute().collect()).toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testParquetNameMapping() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.t1 (x int,y int) stored as parquet");
tableEnv.executeSql("insert into table db1.t1 values (1,10),(2,20)").await();
Table hiveTable = hiveCatalog.getHiveTable(new ObjectPath("db1", "t1"));
String location = hiveTable.getSd().getLocation();
tableEnv.executeSql(String.format("create table db1.t2 (y int,x int) stored as parquet location '%s'", location));
tableEnv.getConfig().getConfiguration().setBoolean(HiveOptions.TABLE_EXEC_HIVE_FALLBACK_MAPRED_READER, true);
assertEquals("[1, 2]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select x from db1.t1").execute().collect()).toString());
assertEquals("[1, 2]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select x from db1.t2").execute().collect()).toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testNonExistingPartitionFolder() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.part (x int) partitioned by (p int)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part").addRow(new Object[]{1}).commit("p=1");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part").addRow(new Object[]{2}).commit("p=2");
tableEnv.executeSql("alter table db1.part add partition (p=3)");
// remove one partition
Path toRemove = new Path(hiveCatalog.getHiveTable(new ObjectPath("db1", "part")).getSd().getLocation(), "p=2");
FileSystem fs = toRemove.getFileSystem(hiveCatalog.getHiveConf());
fs.delete(toRemove, true);
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.part").execute().collect());
assertEquals("[1,1]", results.toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testInsertPartitionWithStarSource() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create table src (x int,y string)");
HiveTestUtils.createTextTableInserter(
hiveCatalog,
"default",
"src")
.addRow(new Object[]{1, "a"})
.commit();
tableEnv.executeSql("create table dest (x int) partitioned by (p1 int,p2 string)");
tableEnv.executeSql("insert into dest partition (p1=1) select * from src").await();
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from dest").execute().collect());
assertEquals("[1,1,a]", results.toString());
tableEnv.executeSql("drop table if exists src");
tableEnv.executeSql("drop table if exists dest");
}
@Test
public void testInsertPartitionWithValuesSource() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create table dest (x int) partitioned by (p1 int,p2 string)");
tableEnv.executeSql("insert into dest partition (p1=1) values(1, 'a')").await();
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from dest").execute().collect());
assertEquals("[1,1,a]", results.toString());
tableEnv.executeSql("drop table if exists dest");
}
@Test
public void testDynamicPartWithOrderBy() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create table src(x int,y int)");
tableEnv.executeSql("create table dest(x int) partitioned by (p int)");
try {
HiveTestUtils.createTextTableInserter(hiveCatalog, "default", "src")
.addRow(new Object[]{2, 0})
.addRow(new Object[]{1, 0})
.commit();
// some hive feature relies on the results being sorted, e.g. bucket table
tableEnv.executeSql("insert into dest partition(p) select * from src order by x").await();
List<Row> results = CollectionUtil.iteratorToList(tableEnv.executeSql("select * from dest").collect());
assertEquals("[1,0, 2,0]", results.toString());
} finally {
tableEnv.executeSql("drop table src");
tableEnv.executeSql("drop table dest");
}
}
private TableEnvironment getTableEnvWithHiveCatalog() {
TableEnvironment tableEnv = HiveTestUtils.createTableEnvWithBlinkPlannerBatchMode(SqlDialect.HIVE);
tableEnv.registerCatalog(hiveCatalog.getName(), hiveCatalog);
tableEnv.useCatalog(hiveCatalog.getName());
return tableEnv;
}
}
| flink-connectors/flink-connector-hive/src/test/java/org/apache/flink/connectors/hive/TableEnvHiveConnectorITCase.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.flink.connectors.hive;
import org.apache.flink.table.HiveVersionTestUtil;
import org.apache.flink.table.api.SqlDialect;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.constraints.UniqueConstraint;
import org.apache.flink.table.api.internal.TableImpl;
import org.apache.flink.table.catalog.CatalogBaseTable;
import org.apache.flink.table.catalog.ObjectPath;
import org.apache.flink.table.catalog.hive.HiveCatalog;
import org.apache.flink.table.catalog.hive.HiveTestUtils;
import org.apache.flink.table.catalog.hive.client.HiveMetastoreClientFactory;
import org.apache.flink.table.catalog.hive.client.HiveMetastoreClientWrapper;
import org.apache.flink.table.catalog.hive.client.HiveShimLoader;
import org.apache.flink.types.Row;
import org.apache.flink.util.CollectionUtil;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.Table;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Test hive connector with table API.
*/
public class TableEnvHiveConnectorITCase {
private static HiveCatalog hiveCatalog;
private static HiveMetastoreClientWrapper hmsClient;
@BeforeClass
public static void setup() {
hiveCatalog = HiveTestUtils.createHiveCatalog();
hiveCatalog.open();
hmsClient = HiveMetastoreClientFactory.create(hiveCatalog.getHiveConf(), HiveShimLoader.getHiveVersion());
}
@Test
public void testDefaultPartitionName() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
tableEnv.executeSql("create table db1.src (x int, y int)");
tableEnv.executeSql("create table db1.part (x int) partitioned by (y int)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "src").addRow(new Object[]{1, 1}).addRow(new Object[]{2, null}).commit();
// test generating partitions with default name
tableEnv.executeSql("insert into db1.part select * from db1.src").await();
HiveConf hiveConf = hiveCatalog.getHiveConf();
String defaultPartName = hiveConf.getVar(HiveConf.ConfVars.DEFAULTPARTITIONNAME);
Table hiveTable = hmsClient.getTable("db1", "part");
Path defaultPartPath = new Path(hiveTable.getSd().getLocation(), "y=" + defaultPartName);
FileSystem fs = defaultPartPath.getFileSystem(hiveConf);
assertTrue(fs.exists(defaultPartPath));
TableImpl flinkTable = (TableImpl) tableEnv.sqlQuery("select y, x from db1.part order by x");
List<Row> rows = CollectionUtil.iteratorToList(flinkTable.execute().collect());
assertEquals(Arrays.toString(new String[]{"1,1", "null,2"}), rows.toString());
tableEnv.executeSql("drop database db1 cascade");
}
@Test
public void testGetNonExistingFunction() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
tableEnv.executeSql("create table db1.src (d double, s string)");
tableEnv.executeSql("create table db1.dest (x bigint)");
// just make sure the query runs through, no need to verify result
tableEnv.executeSql("insert into db1.dest select count(d) from db1.src").await();
tableEnv.executeSql("drop database db1 cascade");
}
@Test
public void testDateTimestampPartitionColumns() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.part(x int) partitioned by (dt date,ts timestamp)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part")
.addRow(new Object[]{1})
.addRow(new Object[]{2})
.commit("dt='2019-12-23',ts='2019-12-23 00:00:00'");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part")
.addRow(new Object[]{3})
.commit("dt='2019-12-25',ts='2019-12-25 16:23:43.012'");
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.part order by x").execute().collect());
assertEquals("[1,2019-12-23,2019-12-23T00:00, 2,2019-12-23,2019-12-23T00:00, 3,2019-12-25,2019-12-25T16:23:43.012]", results.toString());
results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select x from db1.part where dt=cast('2019-12-25' as date)").execute().collect());
assertEquals("[3]", results.toString());
tableEnv.executeSql("insert into db1.part select 4,cast('2019-12-31' as date),cast('2019-12-31 12:00:00.0' as timestamp)")
.await();
results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select max(dt) from db1.part").execute().collect());
assertEquals("[2019-12-31]", results.toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testUDTF() throws Exception {
// W/o https://issues.apache.org/jira/browse/HIVE-11878 Hive registers the App classloader as the classloader
// for the UDTF and closes the App classloader when we tear down the session. This causes problems for JUnit code
// and shutdown hooks that have to run after the test finishes, because App classloader can no longer load new
// classes. And will crash the forked JVM, thus failing the test phase.
// Therefore disable such tests for older Hive versions.
String hiveVersion = HiveShimLoader.getHiveVersion();
Assume.assumeTrue(hiveVersion.compareTo("2.0.0") >= 0 || hiveVersion.compareTo("1.3.0") >= 0);
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.simple (i int,a array<int>)");
tableEnv.executeSql("create table db1.nested (a array<map<int, string>>)");
tableEnv.executeSql("create function hiveudtf as 'org.apache.hadoop.hive.ql.udf.generic.GenericUDTFExplode'");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "simple")
.addRow(new Object[]{3, Arrays.asList(1, 2, 3)})
.commit();
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "a");
map1.put(2, "b");
Map<Integer, String> map2 = new HashMap<>();
map2.put(3, "c");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "nested")
.addRow(new Object[]{Arrays.asList(map1, map2)})
.commit();
List<Row> results = CollectionUtil.iteratorToList(
tableEnv.sqlQuery("select x from db1.simple, lateral table(hiveudtf(a)) as T(x)").execute().collect());
assertEquals("[1, 2, 3]", results.toString());
results = CollectionUtil.iteratorToList(
tableEnv.sqlQuery("select x from db1.nested, lateral table(hiveudtf(a)) as T(x)").execute().collect());
assertEquals("[{1=a, 2=b}, {3=c}]", results.toString());
tableEnv.executeSql("create table db1.ts (a array<timestamp>)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "ts").addRow(new Object[]{
new Object[]{Timestamp.valueOf("2015-04-28 15:23:00"), Timestamp.valueOf("2016-06-03 17:05:52")}})
.commit();
results = CollectionUtil.iteratorToList(
tableEnv.sqlQuery("select x from db1.ts, lateral table(hiveudtf(a)) as T(x)").execute().collect());
assertEquals("[2015-04-28T15:23, 2016-06-03T17:05:52]", results.toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
tableEnv.executeSql("drop function hiveudtf");
}
}
@Test
public void testNotNullConstraints() throws Exception {
Assume.assumeTrue(HiveVersionTestUtil.HIVE_310_OR_LATER);
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.tbl (x int,y bigint not null enable rely,z string not null enable norely)");
CatalogBaseTable catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl"));
TableSchema tableSchema = catalogTable.getSchema();
assertTrue("By default columns should be nullable",
tableSchema.getFieldDataTypes()[0].getLogicalType().isNullable());
assertFalse("NOT NULL columns should be reflected in table schema",
tableSchema.getFieldDataTypes()[1].getLogicalType().isNullable());
assertTrue("NOT NULL NORELY columns should be considered nullable",
tableSchema.getFieldDataTypes()[2].getLogicalType().isNullable());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testPKConstraint() throws Exception {
// While PK constraints are supported since Hive 2.1.0, the constraints cannot be RELY in 2.x versions.
// So let's only test for 3.x.
Assume.assumeTrue(HiveVersionTestUtil.HIVE_310_OR_LATER);
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
// test rely PK constraints
tableEnv.executeSql("create table db1.tbl1 (x tinyint,y smallint,z int, primary key (x,z) disable novalidate rely)");
CatalogBaseTable catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl1"));
TableSchema tableSchema = catalogTable.getSchema();
assertTrue(tableSchema.getPrimaryKey().isPresent());
UniqueConstraint pk = tableSchema.getPrimaryKey().get();
assertEquals(2, pk.getColumns().size());
assertTrue(pk.getColumns().containsAll(Arrays.asList("x", "z")));
// test norely PK constraints
tableEnv.executeSql("create table db1.tbl2 (x tinyint,y smallint, primary key (x) disable norely)");
catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl2"));
tableSchema = catalogTable.getSchema();
assertFalse(tableSchema.getPrimaryKey().isPresent());
// test table w/o PK
tableEnv.executeSql("create table db1.tbl3 (x tinyint)");
catalogTable = hiveCatalog.getTable(new ObjectPath("db1", "tbl3"));
tableSchema = catalogTable.getSchema();
assertFalse(tableSchema.getPrimaryKey().isPresent());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testRegexSerDe() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.src (x int,y string) " +
"row format serde 'org.apache.hadoop.hive.serde2.RegexSerDe' " +
"with serdeproperties ('input.regex'='([\\\\d]+)\\u0001([\\\\S]+)')");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "src")
.addRow(new Object[]{1, "a"})
.addRow(new Object[]{2, "ab"})
.commit();
assertEquals("[1,a, 2,ab]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.src order by x").execute().collect()).toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testUpdatePartitionSD() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.dest (x int) partitioned by (p string) stored as rcfile");
tableEnv.executeSql("insert overwrite db1.dest partition (p='1') select 1").await();
tableEnv.executeSql("alter table db1.dest set fileformat sequencefile");
tableEnv.executeSql("insert overwrite db1.dest partition (p='1') select 1").await();
assertEquals("[1,1]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.dest").execute().collect()).toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testParquetNameMapping() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.t1 (x int,y int) stored as parquet");
tableEnv.executeSql("insert into table db1.t1 values (1,10),(2,20)").await();
Table hiveTable = hiveCatalog.getHiveTable(new ObjectPath("db1", "t1"));
String location = hiveTable.getSd().getLocation();
tableEnv.executeSql(String.format("create table db1.t2 (y int,x int) stored as parquet location '%s'", location));
tableEnv.getConfig().getConfiguration().setBoolean(HiveOptions.TABLE_EXEC_HIVE_FALLBACK_MAPRED_READER, true);
assertEquals("[1, 2]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select x from db1.t1").execute().collect()).toString());
assertEquals("[1, 2]", CollectionUtil.iteratorToList(tableEnv.sqlQuery("select x from db1.t2").execute().collect()).toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testNonExistingPartitionFolder() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create database db1");
try {
tableEnv.executeSql("create table db1.part (x int) partitioned by (p int)");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part").addRow(new Object[]{1}).commit("p=1");
HiveTestUtils.createTextTableInserter(hiveCatalog, "db1", "part").addRow(new Object[]{2}).commit("p=2");
tableEnv.executeSql("alter table db1.part add partition (p=3)");
// remove one partition
Path toRemove = new Path(hiveCatalog.getHiveTable(new ObjectPath("db1", "part")).getSd().getLocation(), "p=2");
FileSystem fs = toRemove.getFileSystem(hiveCatalog.getHiveConf());
fs.delete(toRemove, true);
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from db1.part").execute().collect());
assertEquals("[1,1]", results.toString());
} finally {
tableEnv.executeSql("drop database db1 cascade");
}
}
@Test
public void testInsertPartitionWithStarSource() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create table src (x int,y string)");
HiveTestUtils.createTextTableInserter(
hiveCatalog,
"default",
"src")
.addRow(new Object[]{1, "a"})
.commit();
tableEnv.executeSql("create table dest (x int) partitioned by (p1 int,p2 string)");
tableEnv.executeSql("insert into dest partition (p1=1) select * from src").await();
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from dest").execute().collect());
assertEquals("[1,1,a]", results.toString());
tableEnv.executeSql("drop table if exists src");
tableEnv.executeSql("drop table if exists dest");
}
@Test
public void testInsertPartitionWithValuesSource() throws Exception {
TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
tableEnv.executeSql("create table dest (x int) partitioned by (p1 int,p2 string)");
tableEnv.executeSql("insert into dest partition (p1=1) values(1, 'a')").await();
List<Row> results = CollectionUtil.iteratorToList(tableEnv.sqlQuery("select * from dest").execute().collect());
assertEquals("[1,1,a]", results.toString());
tableEnv.executeSql("drop table if exists dest");
}
private TableEnvironment getTableEnvWithHiveCatalog() {
TableEnvironment tableEnv = HiveTestUtils.createTableEnvWithBlinkPlannerBatchMode(SqlDialect.HIVE);
tableEnv.registerCatalog(hiveCatalog.getName(), hiveCatalog);
tableEnv.useCatalog(hiveCatalog.getName());
return tableEnv;
}
}
| [FLINK-20419][hive] Add tests for dynamic partition with order by
This closes #14294
| flink-connectors/flink-connector-hive/src/test/java/org/apache/flink/connectors/hive/TableEnvHiveConnectorITCase.java | [FLINK-20419][hive] Add tests for dynamic partition with order by | <ide><path>link-connectors/flink-connector-hive/src/test/java/org/apache/flink/connectors/hive/TableEnvHiveConnectorITCase.java
<ide> tableEnv.executeSql("drop table if exists dest");
<ide> }
<ide>
<add> @Test
<add> public void testDynamicPartWithOrderBy() throws Exception {
<add> TableEnvironment tableEnv = getTableEnvWithHiveCatalog();
<add> tableEnv.executeSql("create table src(x int,y int)");
<add> tableEnv.executeSql("create table dest(x int) partitioned by (p int)");
<add> try {
<add> HiveTestUtils.createTextTableInserter(hiveCatalog, "default", "src")
<add> .addRow(new Object[]{2, 0})
<add> .addRow(new Object[]{1, 0})
<add> .commit();
<add> // some hive feature relies on the results being sorted, e.g. bucket table
<add> tableEnv.executeSql("insert into dest partition(p) select * from src order by x").await();
<add> List<Row> results = CollectionUtil.iteratorToList(tableEnv.executeSql("select * from dest").collect());
<add> assertEquals("[1,0, 2,0]", results.toString());
<add> } finally {
<add> tableEnv.executeSql("drop table src");
<add> tableEnv.executeSql("drop table dest");
<add> }
<add> }
<add>
<ide> private TableEnvironment getTableEnvWithHiveCatalog() {
<ide> TableEnvironment tableEnv = HiveTestUtils.createTableEnvWithBlinkPlannerBatchMode(SqlDialect.HIVE);
<ide> tableEnv.registerCatalog(hiveCatalog.getName(), hiveCatalog); |
|
Java | bsd-3-clause | f53adde576d5ad7da85ffb106810ae9629edf681 | 0 | NCIP/c3pr,NCIP/c3pr,NCIP/c3pr | package edu.duke.cabig.c3pr.utils.web.spring.tabbedflow;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject;
import edu.duke.cabig.c3pr.web.beans.DefaultObjectPropertyReader;
/**
* @author Rhett Sutphin
*/
public abstract class RowManagableTab<C> extends ReflexiveAjaxableTab<C>{
protected String getSoftDeleteParamName(){
return "softDelete";
}
protected String getDeleteIndexParamName(){
return "deleteIndex";
}
protected String getDeleteHashCodeParamName(){
return "deleteHashCode";
}
protected String getCollectionParamName(){
return "collection";
}
//override this method for soft deletes
protected boolean shouldDelete(HttpServletRequest request, Object command, Errors error) {
return !WebUtils.hasSubmitParameter(request, this.getSoftDeleteParamName());
}
public RowManagableTab(){
}
public RowManagableTab(String longTitle, String shortTitle, String viewName) {
super(longTitle, shortTitle, viewName, new Class[]{HttpServletRequest.class,Object.class, Errors.class});
}
public RowManagableTab(String longTitle, String shortTitle, String viewName, Class[] params) {
super(longTitle, shortTitle, viewName);
super.paramTypes=params;
}
public ModelAndView deleteRow(HttpServletRequest request, Object command, Errors error)throws Exception{
String listPath=request.getParameter(getCollectionParamName());
List col= (List) new DefaultObjectPropertyReader(command, listPath).getPropertyValueFromPath();
int hashCode=Integer.parseInt(request.getParameter(getDeleteHashCodeParamName()));
Integer index=null;
for(int i=0 ; i<col.size() ; i++){
if(col.get(i).hashCode()==hashCode){
index=i;
break;
}
}
Map<String, String> map=new HashMap<String, String>();
if(this.shouldDelete(request, command, error)){
if(index == null){
map.put(getFreeTextModelName(), "Unmatched hashCode="+hashCode);
}else {
col.remove(index.intValue());
map.put(getFreeTextModelName(), "deletedIndex="+request.getParameter(getDeleteIndexParamName())+"||hashCode="+request.getParameter(getDeleteHashCodeParamName())+"||");
}
}else{
//Enabling the retitred_indicator
AbstractMutableDeletableDomainObject obj=(AbstractMutableDeletableDomainObject)col.get(index);
obj.setRetiredIndicatorAsTrue();
}
return new ModelAndView("", map);
}
}
| codebase/projects/web/src/java/edu/duke/cabig/c3pr/utils/web/spring/tabbedflow/RowManagableTab.java | package edu.duke.cabig.c3pr.utils.web.spring.tabbedflow;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject;
import edu.duke.cabig.c3pr.web.beans.DefaultObjectPropertyReader;
/**
* @author Rhett Sutphin
*/
public abstract class RowManagableTab<C> extends ReflexiveAjaxableTab<C>{
protected String getSoftDeleteParamName(){
return "softDelete";
}
protected String getDeleteIndexParamName(){
return "deleteIndex";
}
protected String getDeleteHashCodeParamName(){
return "deleteHashCode";
}
protected String getCollectionParamName(){
return "collection";
}
//override this method for soft deletes
protected boolean shouldDelete(HttpServletRequest request, Object command, Errors error) {
return !WebUtils.hasSubmitParameter(request, this.getSoftDeleteParamName());
}
public RowManagableTab(){
}
public RowManagableTab(String longTitle, String shortTitle, String viewName) {
super(longTitle, shortTitle, viewName, new Class[]{HttpServletRequest.class,Object.class, Errors.class});
}
public RowManagableTab(String longTitle, String shortTitle, String viewName, Class[] params) {
super(longTitle, shortTitle, viewName);
super.paramTypes=params;
}
public ModelAndView deleteRow(HttpServletRequest request, Object command, Errors error)throws Exception{
String listPath=request.getParameter(getCollectionParamName());
List col= (List) new DefaultObjectPropertyReader(command, listPath).getPropertyValueFromPath();
int hashCode=Integer.parseInt(request.getParameter(getDeleteHashCodeParamName()));
Integer index=null;
for(int i=0 ; i<col.size() ; i++){
if(col.get(i).hashCode()==hashCode){
index=i;
break;
}
}
if(this.shouldDelete(request, command, error)){
col.remove(index.intValue());
}else{
//Enabling the retitred_indicator
AbstractMutableDeletableDomainObject obj=(AbstractMutableDeletableDomainObject)col.get(index);
obj.setRetiredIndicatorAsTrue();
}
Map<String, String> map=new HashMap<String, String>();
map.put(getFreeTextModelName(), "deletedIndex="+request.getParameter(getDeleteIndexParamName())+"||hashCode="+request.getParameter(getDeleteHashCodeParamName())+"||");
return new ModelAndView("", map);
}
}
| updated so it woint crash everytime it doesnt find the hascode to be deleted
| codebase/projects/web/src/java/edu/duke/cabig/c3pr/utils/web/spring/tabbedflow/RowManagableTab.java | updated so it woint crash everytime it doesnt find the hascode to be deleted | <ide><path>odebase/projects/web/src/java/edu/duke/cabig/c3pr/utils/web/spring/tabbedflow/RowManagableTab.java
<ide> break;
<ide> }
<ide> }
<add>
<add> Map<String, String> map=new HashMap<String, String>();
<ide> if(this.shouldDelete(request, command, error)){
<del> col.remove(index.intValue());
<add> if(index == null){
<add> map.put(getFreeTextModelName(), "Unmatched hashCode="+hashCode);
<add> }else {
<add> col.remove(index.intValue());
<add> map.put(getFreeTextModelName(), "deletedIndex="+request.getParameter(getDeleteIndexParamName())+"||hashCode="+request.getParameter(getDeleteHashCodeParamName())+"||");
<add> }
<ide> }else{
<ide> //Enabling the retitred_indicator
<ide> AbstractMutableDeletableDomainObject obj=(AbstractMutableDeletableDomainObject)col.get(index);
<ide> obj.setRetiredIndicatorAsTrue();
<ide> }
<del> Map<String, String> map=new HashMap<String, String>();
<del> map.put(getFreeTextModelName(), "deletedIndex="+request.getParameter(getDeleteIndexParamName())+"||hashCode="+request.getParameter(getDeleteHashCodeParamName())+"||");
<add>
<add>
<ide> return new ModelAndView("", map);
<ide> }
<ide> } |
|
Java | apache-2.0 | d2cb107d3edf5e8618b600b38c06737046829457 | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.util;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;
import com.annimon.stream.Stream;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.greenrobot.eventbus.EventBus;
import org.threeten.bp.Instant;
import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import javax.annotation.Nonnull;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.activities.ImageViewerActivity;
import me.devsaki.hentoid.activities.UnlockActivity;
import me.devsaki.hentoid.activities.bundles.BaseWebActivityBundle;
import me.devsaki.hentoid.activities.bundles.ImageViewerActivityBundle;
import me.devsaki.hentoid.database.CollectionDAO;
import me.devsaki.hentoid.database.ObjectBoxDAO;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.Group;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.database.domains.QueueRecord;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Grouping;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.events.DownloadEvent;
import me.devsaki.hentoid.json.JsonContent;
import me.devsaki.hentoid.json.JsonContentCollection;
import me.devsaki.hentoid.util.exception.ContentNotRemovedException;
import me.devsaki.hentoid.util.exception.FileNotRemovedException;
import timber.log.Timber;
import static com.annimon.stream.Collectors.toList;
/**
* Utility class for Content-related operations
*/
public final class ContentHelper {
private static final String UNAUTHORIZED_CHARS = "[^a-zA-Z0-9.-]";
private static final int[] libraryStatus = new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode(), StatusContent.EXTERNAL.getCode()};
// TODO empty this cache at some point
private static final Map<String, String> fileNameMatchCache = new HashMap<>();
private ContentHelper() {
throw new IllegalStateException("Utility class");
}
public static int[] getLibraryStatuses() {
return libraryStatus;
}
/**
* Open the app's web browser to view the given Content's gallery page
*
* @param context Context to use for the action
* @param content Content to view
*/
public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content) {
viewContentGalleryPage(context, content, false);
}
/**
* Open the app's web browser to view the given Content's gallery page
*
* @param context Context to use for the action
* @param content Content to view
* @param wrapPin True if the intent should be wrapped with PIN protection
*/
public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content, boolean wrapPin) {
if (content.getSite().equals(Site.NONE)) return;
Intent intent = new Intent(context, content.getWebActivityClass());
BaseWebActivityBundle.Builder builder = new BaseWebActivityBundle.Builder();
builder.setUrl(content.getGalleryUrl());
intent.putExtras(builder.getBundle());
if (wrapPin) intent = UnlockActivity.wrapIntent(context, intent);
context.startActivity(intent);
}
/**
* Update the given Content's JSON file with its current values
*
* @param context Context to use for the action
* @param content Content whose JSON file to update
*/
public static void updateContentJson(@NonNull Context context, @NonNull Content content) {
Helper.assertNonUiThread();
if (content.isArchive()) return;
DocumentFile file = FileHelper.getFileFromSingleUriString(context, content.getJsonUri());
if (null == file)
throw new InvalidParameterException("'" + content.getJsonUri() + "' does not refer to a valid file");
try {
JsonHelper.updateJson(context, JsonContent.fromEntity(content), JsonContent.class, file);
} catch (IOException e) {
Timber.e(e, "Error while writing to %s", content.getJsonUri());
}
}
/**
* Create the given Content's JSON file and populate it with its current values
*
* @param content Content whose JSON file to create
*/
public static void createContentJson(@NonNull Context context, @NonNull Content content) {
Helper.assertNonUiThread();
if (content.isArchive()) return;
DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri());
if (null == folder) return;
try {
JsonHelper.jsonToFile(context, JsonContent.fromEntity(content), JsonContent.class, folder);
} catch (IOException e) {
Timber.e(e, "Error while writing to %s", content.getStorageUri());
}
}
/**
* Update the JSON file that stores the queue with the current contents of the queue
*
* @param context Context to be used
* @param dao DAO to be used
* @return True if the queue JSON file has been updated properly; false instead
*/
public static boolean updateQueueJson(@NonNull Context context, @NonNull CollectionDAO dao) {
Helper.assertNonUiThread();
List<QueueRecord> queue = dao.selectQueue();
// Save current queue (to be able to restore it in case the app gets uninstalled)
List<Content> queuedContent = Stream.of(queue).map(qr -> qr.content.getTarget()).withoutNulls().toList();
JsonContentCollection contentCollection = new JsonContentCollection();
contentCollection.setQueue(queuedContent);
DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(context, Preferences.getStorageUri());
if (null == rootFolder) return false;
try {
JsonHelper.jsonToFile(context, contentCollection, JsonContentCollection.class, rootFolder, Consts.QUEUE_JSON_FILE_NAME);
} catch (IOException | IllegalArgumentException e) {
// NB : IllegalArgumentException might happen for an unknown reason on certain devices
// even though all the file existence checks are in place
// ("Failed to determine if primary:.Hentoid/queue.json is child of primary:.Hentoid: java.io.FileNotFoundException: Missing file for primary:.Hentoid/queue.json at /storage/emulated/0/.Hentoid/queue.json")
Timber.e(e);
FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
crashlytics.recordException(e);
return false;
}
return true;
}
/**
* Open the given Content in the built-in image viewer
*
* @param context Context to use for the action
* @param content Content to view
* @param searchParams Current search parameters (so that the next/previous book feature
* is faithful to the library screen's order)
*/
public static boolean openHentoidViewer(@NonNull Context context, @NonNull Content content, Bundle searchParams) {
// Check if the book has at least its own folder
if (content.getStorageUri().isEmpty()) return false;
Timber.d("Opening: %s from: %s", content.getTitle(), content.getStorageUri());
ImageViewerActivityBundle.Builder builder = new ImageViewerActivityBundle.Builder();
builder.setContentId(content.getId());
if (searchParams != null) builder.setSearchParams(searchParams);
Intent viewer = new Intent(context, ImageViewerActivity.class);
viewer.putExtras(builder.getBundle());
context.startActivity(viewer);
return true;
}
/**
* Update the given Content's number of reads in both DB and JSON file
*
* @param context Context to use for the action
* @param dao DAO to use for the action
* @param content Content to update
*/
public static void updateContentReads(@NonNull Context context, @Nonnull CollectionDAO dao, @NonNull Content content) {
content.increaseReads().setLastReadDate(Instant.now().toEpochMilli());
dao.insertContent(content);
if (!content.getJsonUri().isEmpty()) updateContentJson(context, content);
else createContentJson(context, content);
}
/**
* Find the picture files for the given Content
* NB1 : Pictures with non-supported formats are not included in the results
* NB2 : Cover picture is not included in the results
*
* @param content Content to retrieve picture files for
* @return List of picture files
*/
public static List<DocumentFile> getPictureFilesFromContent(@NonNull final Context context, @NonNull final Content content) {
Helper.assertNonUiThread();
String storageUri = content.getStorageUri();
Timber.d("Opening: %s from: %s", content.getTitle(), storageUri);
DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, storageUri);
if (null == folder) {
Timber.d("File not found!! Exiting method.");
return new ArrayList<>();
}
return FileHelper.listFoldersFilter(context,
folder,
displayName -> (displayName.toLowerCase().startsWith(Consts.THUMB_FILE_NAME)
&& ImageHelper.isImageExtensionSupported(FileHelper.getExtension(displayName))
)
);
}
/**
* Remove the given Content from the disk and the DB
*
* @param context Context to be used
* @param dao DAO to be used
* @param content Content to be removed
* @throws ContentNotRemovedException in case an issue prevents the content from being actually removed
*/
public static void removeContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException {
Helper.assertNonUiThread();
// Remove from DB
// NB : start with DB to have a LiveData feedback, because file removal can take much time
dao.deleteContent(content);
if (content.isArchive()) { // Remove an archive
DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri());
if (null == archive)
throw new FileNotRemovedException(content, "Failed to find archive " + content.getStorageUri());
if (archive.delete()) {
Timber.i("Archive removed : %s", content.getStorageUri());
} else {
throw new FileNotRemovedException(content, "Failed to delete archive " + content.getStorageUri());
}
// Remove the cover stored in the app's persistent folder
File appFolder = context.getFilesDir();
File[] images = appFolder.listFiles((dir, name) -> FileHelper.getFileNameWithoutExtension(name).equals(content.getId() + ""));
if (images != null)
for (File f : images) FileHelper.removeFile(f);
} else { // Remove a folder and its content
// If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete
DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri());
if (null == folder)
throw new FileNotRemovedException(content, "Failed to find directory " + content.getStorageUri());
if (folder.delete()) {
Timber.i("Directory removed : %s", content.getStorageUri());
} else {
throw new FileNotRemovedException(content, "Failed to delete directory " + content.getStorageUri());
}
}
}
// TODO doc
public static void removeAllExternalContent(@NonNull final Context context) {
// Remove all external books from DB
CollectionDAO dao = new ObjectBoxDAO(context);
try {
dao.deleteAllExternalBooks();
} finally {
dao.cleanup();
}
// Remove all images stored in the app's persistent folder (archive covers)
File appFolder = context.getFilesDir();
File[] images = appFolder.listFiles((dir, name) -> ImageHelper.isSupportedImage(name));
if (images != null)
for (File f : images) FileHelper.removeFile(f);
}
/**
* Remove the given Content from the queue, disk and the DB
*
* @param context Context to be used
* @param dao DAO to be used
* @param content Content to be removed
* @throws ContentNotRemovedException in case an issue prevents the content from being actually removed
*/
public static void removeQueuedContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException {
Helper.assertNonUiThread();
// Check if the content is on top of the queue; if so, send a CANCEL event
List<QueueRecord> queue = dao.selectQueue();
if (!queue.isEmpty() && queue.get(0).content.getTargetId() == content.getId())
EventBus.getDefault().post(new DownloadEvent(content, DownloadEvent.EV_CANCEL));
// Remove from queue
dao.deleteQueue(content);
// Remove content itself
removeContent(context, dao, content);
}
/**
* Add new content to the library
*
* @param dao DAO to be used
* @param content Content to add to the library
* @return ID of the newly added Content
*/
public static long addContent(
@NonNull final Context context,
@NonNull final CollectionDAO dao,
@NonNull final Content content) {
content.populateAuthor();
long newContentId = dao.insertContent(content);
content.setId(newContentId);
// Perform group operations only if
// - the book is in the library (i.e. not queued)
// - the book is linked to no group from the given grouping
if (Helper.getListFromPrimitiveArray(libraryStatus).contains(content.getStatus().getCode())) {
List<Grouping> staticGroupings = Stream.of(Grouping.values()).filter(Grouping::canReorderBooks).toList();
for (Grouping g : staticGroupings)
if (content.getGroupItems(g).isEmpty()) {
if (g.equals(Grouping.ARTIST)) {
int nbGroups = (int) dao.countGroupsFor(g);
AttributeMap attrs = content.getAttributeMap();
List<Attribute> artists = new ArrayList<>();
List<Attribute> sublist = attrs.get(AttributeType.ARTIST);
if (sublist != null)
artists.addAll(sublist);
sublist = attrs.get(AttributeType.CIRCLE);
if (sublist != null)
artists.addAll(sublist);
for (Attribute a : artists) {
Group group = a.getGroup().getTarget();
if (null == group) {
group = new Group(Grouping.ARTIST, a.getName(), ++nbGroups);
if (!a.contents.isEmpty())
group.picture.setTarget(a.contents.get(0).getCover());
}
GroupHelper.addContentToAttributeGroup(dao, group, a, content);
}
}
}
}
// Extract the cover to the app's persistent folder if the book is an archive
if (content.isArchive()) {
DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri());
if (archive != null) {
try {
List<Uri> outputFiles = ArchiveHelper.extractZipEntries(
context,
archive,
Stream.of(content.getCover().getFileUri().replace(content.getStorageUri() + File.separator, "")).toList(),
context.getFilesDir(),
Stream.of(newContentId + "").toList());
if (!outputFiles.isEmpty() && content.getImageFiles() != null) {
content.getCover().setFileUri(outputFiles.get(0).toString());
dao.replaceImageList(newContentId, content.getImageFiles());
}
} catch (IOException e) {
Timber.w(e);
}
}
}
return newContentId;
}
/**
* Remove the given pages from the disk and the DB
*
* @param images Pages to be removed
* @param dao DAO to be used
* @param context Context to be used
*/
public static void removePages(@NonNull List<ImageFile> images, @NonNull CollectionDAO dao, @NonNull final Context context) {
Helper.assertNonUiThread();
// Remove from DB
// NB : start with DB to have a LiveData feedback, because file removal can take much time
dao.deleteImageFiles(images);
// Remove the pages from disk
for (ImageFile image : images)
FileHelper.removeFile(context, Uri.parse(image.getFileUri()));
// Lists all relevant content
List<Long> contents = Stream.of(images).filter(i -> i.content != null).map(i -> i.content.getTargetId()).distinct().toList();
// Update content JSON if it exists (i.e. if book is not queued)
for (Long contentId : contents) {
Content content = dao.selectContent(contentId);
if (content != null && !content.getJsonUri().isEmpty())
updateContentJson(context, content);
}
}
/**
* Define a new cover among a Content's ImageFiles
*
* @param newCover ImageFile to be used as a cover for the Content it is related to
* @param dao DAO to be used
* @param context Context to be used
*/
public static void setContentCover(@NonNull ImageFile newCover, @NonNull CollectionDAO dao, @NonNull final Context context) {
Helper.assertNonUiThread();
// Get all images from the DB
Content content = dao.selectContent(newCover.content.getTargetId());
if (null == content) return;
List<ImageFile> images = content.getImageFiles();
if (null == images) return;
// Remove current cover from the set
for (int i = 0; i < images.size(); i++)
if (images.get(i).isCover()) {
images.remove(i);
break;
}
// Duplicate given picture and set it as a cover
ImageFile cover = ImageFile.newCover(newCover.getUrl(), newCover.getStatus()).setFileUri(newCover.getFileUri()).setMimeType(newCover.getMimeType());
images.add(0, cover);
// Update cover URL to "ping" the content to be updated too (useful for library screen that only detects "direct" content updates)
content.setCoverImageUrl(newCover.getUrl());
// Update the whole list
dao.insertContent(content);
// Update content JSON if it exists (i.e. if book is not queued)
if (!content.getJsonUri().isEmpty())
updateContentJson(context, content);
}
/**
* Create the download directory of the given content
*
* @param context Context
* @param content Content for which the directory to create
* @return Created directory
*/
@Nullable
public static DocumentFile createContentDownloadDir(@NonNull Context context, @NonNull Content content) {
DocumentFile siteDownloadDir = getOrCreateSiteDownloadDir(context, null, content.getSite());
if (null == siteDownloadDir) return null;
String bookFolderName = formatBookFolderName(content);
DocumentFile bookFolder = FileHelper.findFolder(context, siteDownloadDir, bookFolderName);
if (null == bookFolder) { // Create
return siteDownloadDir.createDirectory(bookFolderName);
} else return bookFolder;
}
/**
* Format the download directory path of the given content according to current user preferences
*
* @param content Content to get the path from
* @return Canonical download directory path of the given content, according to current user preferences
*/
public static String formatBookFolderName(@NonNull final Content content) {
String result = "";
String title = content.getTitle();
title = (null == title) ? "" : title.replaceAll(UNAUTHORIZED_CHARS, "_");
String author = content.getAuthor().toLowerCase().replaceAll(UNAUTHORIZED_CHARS, "_");
switch (Preferences.getFolderNameFormat()) {
case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_ID:
result += title;
break;
case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID:
result += author + " - " + title;
break;
case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_AUTH_ID:
result += title + " - " + author;
break;
}
result += " - ";
// Unique content ID
String suffix = formatBookId(content);
// Truncate folder dir to something manageable for Windows
// If we are to assume NTFS and Windows, then the fully qualified file, with it's drivename, path, filename, and extension, altogether is limited to 260 characters.
int truncLength = Preferences.getFolderTruncationNbChars();
int titleLength = result.length();
if (truncLength > 0 && titleLength + suffix.length() > truncLength)
result = result.substring(0, truncLength - suffix.length() - 1);
result += suffix;
return result;
}
/**
* Format the Content ID for folder naming purposes
*
* @param content Content whose ID to format
* @return Formatted Content ID
*/
@SuppressWarnings("squid:S2676") // Math.abs is used for formatting purposes only
public static String formatBookId(@NonNull final Content content) {
String id = content.getUniqueSiteId();
// For certain sources (8muses, fakku), unique IDs are strings that may be very long
// => shorten them by using their hashCode
if (id.length() > 10) id = Helper.formatIntAsStr(Math.abs(id.hashCode()), 10);
return "[" + id + "]";
}
/**
* Return the given site's download directory. Create it if it doesn't exist.
*
* @param context Context to use for the action
* @param site Site to get the download directory for
* @return Download directory of the given Site
*/
@Nullable
static DocumentFile getOrCreateSiteDownloadDir(@NonNull Context context, @Nullable ContentProviderClient client, @NonNull Site site) {
String appUriStr = Preferences.getStorageUri();
if (appUriStr.isEmpty()) {
Timber.e("No storage URI defined for the app");
return null;
}
DocumentFile appFolder = DocumentFile.fromTreeUri(context, Uri.parse(appUriStr));
if (null == appFolder || !appFolder.exists()) {
Timber.e("App folder %s does not exist", appUriStr);
return null;
}
String siteFolderName = site.getFolder();
DocumentFile siteFolder;
if (null == client)
siteFolder = FileHelper.findFolder(context, appFolder, siteFolderName);
else
siteFolder = FileHelper.findFolder(context, appFolder, client, siteFolderName);
if (null == siteFolder) // Create
return appFolder.createDirectory(siteFolderName);
else return siteFolder;
}
/**
* Open the "share with..." Android dialog for the given Content
*
* @param context Context to use for the action
* @param item Content to share
*/
public static void shareContent(@NonNull final Context context, @NonNull final Content item) {
String url = item.getGalleryUrl();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, item.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, url);
context.startActivity(Intent.createChooser(intent, context.getString(R.string.send_to)));
}
/**
* Parse the given download parameters string into a map of strings
*
* @param downloadParamsStr String representation of the download parameters to parse
* @return Map of strings describing the given download parameters
*/
public static Map<String, String> parseDownloadParams(final String downloadParamsStr) {
// Handle empty and {}
if (null == downloadParamsStr || downloadParamsStr.trim().length() <= 2)
return new HashMap<>();
try {
return JsonHelper.jsonToObject(downloadParamsStr, JsonHelper.MAP_STRINGS);
} catch (IOException e) {
Timber.w(e);
}
return new HashMap<>();
}
/**
* Remove the leading zeroes and the file extension of the given string
*
* @param s String to be cleaned
* @return Input string, without leading zeroes and extension
*/
private static String removeLeadingZeroesAndExtension(@Nullable String s) {
if (null == s) return "";
int beginIndex = 0;
if (s.startsWith("0")) beginIndex = -1;
for (int i = 0; i < s.length(); i++) {
if (-1 == beginIndex && s.charAt(i) != '0') beginIndex = i;
if ('.' == s.charAt(i)) return s.substring(beginIndex, i);
}
return (-1 == beginIndex) ? "0" : s.substring(beginIndex);
}
/**
* Remove the leading zeroes and the file extension of the given string using cached results
*
* @param s String to be cleaned
* @return Input string, without leading zeroes and extension
*/
private static String removeLeadingZeroesAndExtensionCached(String s) {
if (fileNameMatchCache.containsKey(s)) return fileNameMatchCache.get(s);
else {
String result = removeLeadingZeroesAndExtension(s);
fileNameMatchCache.put(s, result);
return result;
}
}
/**
* Matches the given files to the given ImageFiles according to their name (without leading zeroes nor file extension)
*
* @param files Files to be matched to the given ImageFiles
* @param images ImageFiles to be matched to the given files
* @return List of matched ImageFiles, with the Uri of the matching file
*/
public static List<ImageFile> matchFilesToImageList(@NonNull final List<DocumentFile> files, @NonNull final List<ImageFile> images) {
Map<String, ImmutablePair<String, Long>> fileNameProperties = new HashMap<>(files.size());
List<ImageFile> result = new ArrayList<>();
for (DocumentFile file : files)
fileNameProperties.put(removeLeadingZeroesAndExtensionCached(file.getName()), new ImmutablePair<>(file.getUri().toString(), file.length()));
for (ImageFile img : images) {
String imgName = removeLeadingZeroesAndExtensionCached(img.getName());
if (fileNameProperties.containsKey(imgName)) {
ImmutablePair<String, Long> property = fileNameProperties.get(imgName);
if (property != null)
result.add(img.setFileUri(property.left).setSize(property.right).setStatus(StatusContent.DOWNLOADED).setIsCover(imgName.equals(Consts.THUMB_FILE_NAME)));
} else
Timber.i(">> img dropped %s", imgName);
}
return result;
}
/**
* Create the list of ImageFiles from the given folder
*
* @param context Context to be used
* @param folder Folder to read the images from
* @return List of ImageFiles corresponding to all supported pictures inside the given folder, sorted numerically then alphabetically
*/
public static List<ImageFile> createImageListFromFolder(@NonNull final Context context, @NonNull final DocumentFile folder) {
List<DocumentFile> imageFiles = FileHelper.listFiles(context, folder, ImageHelper.getImageNamesFilter());
if (!imageFiles.isEmpty())
return createImageListFromFiles(imageFiles);
else return Collections.emptyList();
}
/**
* Create the list of ImageFiles from the given files
*
* @param files Files to find images into
* @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically
*/
public static List<ImageFile> createImageListFromFiles(@NonNull final List<DocumentFile> files) {
return createImageListFromFiles(files, StatusContent.DOWNLOADED, 0, "");
}
/**
* Create the list of ImageFiles from the given files
*
* @param files Files to find images into
* @param targetStatus Target status of the ImageFiles to create
* @param startingOrder Starting order of the ImageFiles to create
* @param namePrefix Prefix to add in front of the name of the ImageFiles to create
* @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically
*/
public static List<ImageFile> createImageListFromFiles(
@NonNull final List<DocumentFile> files,
@NonNull final StatusContent targetStatus,
int startingOrder,
@NonNull final String namePrefix) {
Helper.assertNonUiThread();
List<ImageFile> result = new ArrayList<>();
int order = startingOrder;
// Sort files by anything that resembles a number inside their names
List<DocumentFile> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberFileComparator()).collect(toList());
for (DocumentFile f : fileList) {
String name = namePrefix + ((f.getName() != null) ? f.getName() : "");
ImageFile img = new ImageFile();
if (name.startsWith(Consts.THUMB_FILE_NAME)) img.setIsCover(true);
else order++;
img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(f.getUri().toString()).setStatus(targetStatus).setFileUri(f.getUri().toString()).setSize(f.length());
img.setMimeType(FileHelper.getMimeTypeFromFileName(name));
result.add(img);
}
return result;
}
public static List<ImageFile> createImageListFromZipEntries(
@NonNull final Uri zipFileUri,
@NonNull final List<ZipEntry> files,
@NonNull final StatusContent targetStatus,
int startingOrder,
@NonNull final String namePrefix) {
Helper.assertNonUiThread();
List<ImageFile> result = new ArrayList<>();
int order = startingOrder;
// Sort files by anything that resembles a number inside their names (default entry order from ZipInputStream is chaotic)
List<ZipEntry> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberZipComparator()).collect(toList());
for (ZipEntry f : fileList) {
String name = namePrefix + f.getName();
String path = zipFileUri.toString() + File.separator + f.getName();
ImageFile img = new ImageFile();
if (name.startsWith(Consts.THUMB_FILE_NAME)) img.setIsCover(true);
else order++;
img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(path).setStatus(targetStatus).setFileUri(path).setSize(f.getSize());
img.setMimeType(FileHelper.getMimeTypeFromFileName(name));
result.add(img);
}
return result;
}
/**
* Comparator to be used to sort files according to their names :
* - Sort according to the concatenation of all its numerical characters, if any
* - If none, sort alphabetically (default string compare)
*/
private static class InnerNameNumberFileComparator implements Comparator<DocumentFile> {
@Override
public int compare(@NonNull DocumentFile o1, @NonNull DocumentFile o2) {
String name1 = o1.getName();
if (null == name1) name1 = "";
String name2 = o2.getName();
if (null == name2) name2 = "";
return new InnerNameNumberComparator().compare(name1, name2);
}
}
private static class InnerNameNumberZipComparator implements Comparator<ZipEntry> {
@Override
public int compare(@NonNull ZipEntry o1, @NonNull ZipEntry o2) {
return new ContentHelper.InnerNameNumberComparator().compare(o1.getName(), o2.getName());
}
}
public static class InnerNameNumberComparator implements Comparator<String> {
@Override
public int compare(@NonNull String name1, @NonNull String name2) {
long innerNumber1 = Helper.extractNumeric(name1);
if (-1 == innerNumber1) return name1.compareTo(name2);
long innerNumber2 = Helper.extractNumeric(name2);
if (-1 == innerNumber2) return name1.compareTo(name2);
return Long.compare(innerNumber1, innerNumber2);
}
}
}
| app/src/main/java/me/devsaki/hentoid/util/ContentHelper.java | package me.devsaki.hentoid.util;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;
import com.annimon.stream.Stream;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.greenrobot.eventbus.EventBus;
import org.threeten.bp.Instant;
import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import javax.annotation.Nonnull;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.activities.ImageViewerActivity;
import me.devsaki.hentoid.activities.UnlockActivity;
import me.devsaki.hentoid.activities.bundles.BaseWebActivityBundle;
import me.devsaki.hentoid.activities.bundles.ImageViewerActivityBundle;
import me.devsaki.hentoid.database.CollectionDAO;
import me.devsaki.hentoid.database.ObjectBoxDAO;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.Group;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.database.domains.QueueRecord;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Grouping;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.events.DownloadEvent;
import me.devsaki.hentoid.json.JsonContent;
import me.devsaki.hentoid.json.JsonContentCollection;
import me.devsaki.hentoid.util.exception.ContentNotRemovedException;
import me.devsaki.hentoid.util.exception.FileNotRemovedException;
import timber.log.Timber;
import static com.annimon.stream.Collectors.toList;
/**
* Utility class for Content-related operations
*/
public final class ContentHelper {
private static final String UNAUTHORIZED_CHARS = "[^a-zA-Z0-9.-]";
private static final int[] libraryStatus = new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode(), StatusContent.EXTERNAL.getCode()};
// TODO empty this cache at some point
private static final Map<String, String> fileNameMatchCache = new HashMap<>();
private ContentHelper() {
throw new IllegalStateException("Utility class");
}
public static int[] getLibraryStatuses() {
return libraryStatus;
}
/**
* Open the app's web browser to view the given Content's gallery page
*
* @param context Context to use for the action
* @param content Content to view
*/
public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content) {
viewContentGalleryPage(context, content, false);
}
/**
* Open the app's web browser to view the given Content's gallery page
*
* @param context Context to use for the action
* @param content Content to view
* @param wrapPin True if the intent should be wrapped with PIN protection
*/
public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content, boolean wrapPin) {
if (content.getSite().equals(Site.NONE)) return;
Intent intent = new Intent(context, content.getWebActivityClass());
BaseWebActivityBundle.Builder builder = new BaseWebActivityBundle.Builder();
builder.setUrl(content.getGalleryUrl());
intent.putExtras(builder.getBundle());
if (wrapPin) intent = UnlockActivity.wrapIntent(context, intent);
context.startActivity(intent);
}
/**
* Update the given Content's JSON file with its current values
*
* @param context Context to use for the action
* @param content Content whose JSON file to update
*/
public static void updateContentJson(@NonNull Context context, @NonNull Content content) {
Helper.assertNonUiThread();
if (content.isArchive()) return;
DocumentFile file = FileHelper.getFileFromSingleUriString(context, content.getJsonUri());
if (null == file)
throw new InvalidParameterException("'" + content.getJsonUri() + "' does not refer to a valid file");
try {
JsonHelper.updateJson(context, JsonContent.fromEntity(content), JsonContent.class, file);
} catch (IOException e) {
Timber.e(e, "Error while writing to %s", content.getJsonUri());
}
}
/**
* Create the given Content's JSON file and populate it with its current values
*
* @param content Content whose JSON file to create
*/
public static void createContentJson(@NonNull Context context, @NonNull Content content) {
Helper.assertNonUiThread();
if (content.isArchive()) return;
DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri());
if (null == folder) return;
try {
JsonHelper.jsonToFile(context, JsonContent.fromEntity(content), JsonContent.class, folder);
} catch (IOException e) {
Timber.e(e, "Error while writing to %s", content.getStorageUri());
}
}
/**
* Update the JSON file that stores the queue with the current contents of the queue
*
* @param context Context to be used
* @param dao DAO to be used
* @return True if the queue JSON file has been updated properly; false instead
*/
public static boolean updateQueueJson(@NonNull Context context, @NonNull CollectionDAO dao) {
Helper.assertNonUiThread();
List<QueueRecord> queue = dao.selectQueue();
// Save current queue (to be able to restore it in case the app gets uninstalled)
List<Content> queuedContent = Stream.of(queue).map(qr -> qr.content.getTarget()).withoutNulls().toList();
JsonContentCollection contentCollection = new JsonContentCollection();
contentCollection.setQueue(queuedContent);
DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(context, Preferences.getStorageUri());
if (null == rootFolder) return false;
try {
JsonHelper.jsonToFile(context, contentCollection, JsonContentCollection.class, rootFolder, Consts.QUEUE_JSON_FILE_NAME);
} catch (IOException | IllegalArgumentException e) {
// NB : IllegalArgumentException might happen for an unknown reason on certain devices
// even though all the file existence checks are in place
// ("Failed to determine if primary:.Hentoid/queue.json is child of primary:.Hentoid: java.io.FileNotFoundException: Missing file for primary:.Hentoid/queue.json at /storage/emulated/0/.Hentoid/queue.json")
Timber.e(e);
FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
crashlytics.recordException(e);
return false;
}
return true;
}
/**
* Open the given Content in the built-in image viewer
*
* @param context Context to use for the action
* @param content Content to view
* @param searchParams Current search parameters (so that the next/previous book feature
* is faithful to the library screen's order)
*/
public static boolean openHentoidViewer(@NonNull Context context, @NonNull Content content, Bundle searchParams) {
// Check if the book has at least its own folder
if (content.getStorageUri().isEmpty()) return false;
Timber.d("Opening: %s from: %s", content.getTitle(), content.getStorageUri());
ImageViewerActivityBundle.Builder builder = new ImageViewerActivityBundle.Builder();
builder.setContentId(content.getId());
if (searchParams != null) builder.setSearchParams(searchParams);
Intent viewer = new Intent(context, ImageViewerActivity.class);
viewer.putExtras(builder.getBundle());
context.startActivity(viewer);
return true;
}
/**
* Update the given Content's number of reads in both DB and JSON file
*
* @param context Context to use for the action
* @param dao DAO to use for the action
* @param content Content to update
*/
public static void updateContentReads(@NonNull Context context, @Nonnull CollectionDAO dao, @NonNull Content content) {
content.increaseReads().setLastReadDate(Instant.now().toEpochMilli());
dao.insertContent(content);
if (!content.getJsonUri().isEmpty()) updateContentJson(context, content);
else createContentJson(context, content);
}
/**
* Find the picture files for the given Content
* NB1 : Pictures with non-supported formats are not included in the results
* NB2 : Cover picture is not included in the results
*
* @param content Content to retrieve picture files for
* @return List of picture files
*/
public static List<DocumentFile> getPictureFilesFromContent(@NonNull final Context context, @NonNull final Content content) {
Helper.assertNonUiThread();
String storageUri = content.getStorageUri();
Timber.d("Opening: %s from: %s", content.getTitle(), storageUri);
DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, storageUri);
if (null == folder) {
Timber.d("File not found!! Exiting method.");
return new ArrayList<>();
}
return FileHelper.listFoldersFilter(context,
folder,
displayName -> (displayName.toLowerCase().startsWith(Consts.THUMB_FILE_NAME)
&& ImageHelper.isImageExtensionSupported(FileHelper.getExtension(displayName))
)
);
}
/**
* Remove the given Content from the disk and the DB
*
* @param context Context to be used
* @param dao DAO to be used
* @param content Content to be removed
* @throws ContentNotRemovedException in case an issue prevents the content from being actually removed
*/
public static void removeContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException {
Helper.assertNonUiThread();
// Remove from DB
// NB : start with DB to have a LiveData feedback, because file removal can take much time
dao.deleteContent(content);
if (content.isArchive()) { // Remove an archive
DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri());
if (null == archive)
throw new FileNotRemovedException(content, "Failed to find archive " + content.getStorageUri());
if (archive.delete()) {
Timber.i("Archive removed : %s", content.getStorageUri());
} else {
throw new FileNotRemovedException(content, "Failed to delete archive " + content.getStorageUri());
}
// Remove the cover stored in the app's persistent folder
File appFolder = context.getFilesDir();
File[] images = appFolder.listFiles((dir, name) -> FileHelper.getFileNameWithoutExtension(name).equals(content.getId() + ""));
for (File f : images) FileHelper.removeFile(f);
} else { // Remove a folder and its content
// If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete
DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri());
if (null == folder)
throw new FileNotRemovedException(content, "Failed to find directory " + content.getStorageUri());
if (folder.delete()) {
Timber.i("Directory removed : %s", content.getStorageUri());
} else {
throw new FileNotRemovedException(content, "Failed to delete directory " + content.getStorageUri());
}
}
}
// TODO doc
public static void removeAllExternalContent(@NonNull final Context context) {
// Remove all external books from DB
CollectionDAO dao = new ObjectBoxDAO(context);
try {
dao.deleteAllExternalBooks();
} finally {
dao.cleanup();
}
// Remove all images stored in the app's persistent folder (archive covers)
File appFolder = context.getFilesDir();
File[] images = appFolder.listFiles((dir, name) -> ImageHelper.isSupportedImage(name));
for (File f : images) FileHelper.removeFile(f);
}
/**
* Remove the given Content from the queue, disk and the DB
*
* @param context Context to be used
* @param dao DAO to be used
* @param content Content to be removed
* @throws ContentNotRemovedException in case an issue prevents the content from being actually removed
*/
public static void removeQueuedContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException {
Helper.assertNonUiThread();
// Check if the content is on top of the queue; if so, send a CANCEL event
List<QueueRecord> queue = dao.selectQueue();
if (!queue.isEmpty() && queue.get(0).content.getTargetId() == content.getId())
EventBus.getDefault().post(new DownloadEvent(content, DownloadEvent.EV_CANCEL));
// Remove from queue
dao.deleteQueue(content);
// Remove content itself
removeContent(context, dao, content);
}
/**
* Add new content to the library
*
* @param dao DAO to be used
* @param content Content to add to the library
* @return ID of the newly added Content
*/
public static long addContent(
@NonNull final Context context,
@NonNull final CollectionDAO dao,
@NonNull final Content content) {
content.populateAuthor();
long newContentId = dao.insertContent(content);
content.setId(newContentId);
// Perform group operations only if
// - the book is in the library (i.e. not queued)
// - the book is linked to no group from the given grouping
if (Helper.getListFromPrimitiveArray(libraryStatus).contains(content.getStatus().getCode())) {
List<Grouping> staticGroupings = Stream.of(Grouping.values()).filter(Grouping::canReorderBooks).toList();
for (Grouping g : staticGroupings)
if (content.getGroupItems(g).isEmpty()) {
if (g.equals(Grouping.ARTIST)) {
int nbGroups = (int) dao.countGroupsFor(g);
AttributeMap attrs = content.getAttributeMap();
List<Attribute> artists = new ArrayList<>();
List<Attribute> sublist = attrs.get(AttributeType.ARTIST);
if (sublist != null)
artists.addAll(sublist);
sublist = attrs.get(AttributeType.CIRCLE);
if (sublist != null)
artists.addAll(sublist);
for (Attribute a : artists) {
Group group = a.getGroup().getTarget();
if (null == group) {
group = new Group(Grouping.ARTIST, a.getName(), ++nbGroups);
if (!a.contents.isEmpty())
group.picture.setTarget(a.contents.get(0).getCover());
}
GroupHelper.addContentToAttributeGroup(dao, group, a, content);
}
}
}
}
// Extract the cover to the app's persistent folder if the book is an archive
if (content.isArchive()) {
DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri());
try {
List<Uri> outputFiles = ArchiveHelper.extractZipEntries(
context,
archive,
Stream.of(content.getCover().getFileUri().replace(content.getStorageUri() + File.separator, "")).toList(),
context.getFilesDir(),
Stream.of(newContentId + "").toList());
if (!outputFiles.isEmpty()) {
content.getCover().setFileUri(outputFiles.get(0).toString());
dao.replaceImageList(newContentId, content.getImageFiles());
}
} catch (IOException e) {
Timber.w(e);
}
}
return newContentId;
}
/**
* Remove the given pages from the disk and the DB
*
* @param images Pages to be removed
* @param dao DAO to be used
* @param context Context to be used
*/
public static void removePages(@NonNull List<ImageFile> images, @NonNull CollectionDAO dao, @NonNull final Context context) {
Helper.assertNonUiThread();
// Remove from DB
// NB : start with DB to have a LiveData feedback, because file removal can take much time
dao.deleteImageFiles(images);
// Remove the pages from disk
for (ImageFile image : images)
FileHelper.removeFile(context, Uri.parse(image.getFileUri()));
// Lists all relevant content
List<Long> contents = Stream.of(images).filter(i -> i.content != null).map(i -> i.content.getTargetId()).distinct().toList();
// Update content JSON if it exists (i.e. if book is not queued)
for (Long contentId : contents) {
Content content = dao.selectContent(contentId);
if (content != null && !content.getJsonUri().isEmpty())
updateContentJson(context, content);
}
}
/**
* Define a new cover among a Content's ImageFiles
*
* @param newCover ImageFile to be used as a cover for the Content it is related to
* @param dao DAO to be used
* @param context Context to be used
*/
public static void setContentCover(@NonNull ImageFile newCover, @NonNull CollectionDAO dao, @NonNull final Context context) {
Helper.assertNonUiThread();
// Get all images from the DB
Content content = dao.selectContent(newCover.content.getTargetId());
if (null == content) return;
List<ImageFile> images = content.getImageFiles();
if (null == images) return;
// Remove current cover from the set
for (int i = 0; i < images.size(); i++)
if (images.get(i).isCover()) {
images.remove(i);
break;
}
// Duplicate given picture and set it as a cover
ImageFile cover = ImageFile.newCover(newCover.getUrl(), newCover.getStatus()).setFileUri(newCover.getFileUri()).setMimeType(newCover.getMimeType());
images.add(0, cover);
// Update cover URL to "ping" the content to be updated too (useful for library screen that only detects "direct" content updates)
content.setCoverImageUrl(newCover.getUrl());
// Update the whole list
dao.insertContent(content);
// Update content JSON if it exists (i.e. if book is not queued)
if (!content.getJsonUri().isEmpty())
updateContentJson(context, content);
}
/**
* Create the download directory of the given content
*
* @param context Context
* @param content Content for which the directory to create
* @return Created directory
*/
@Nullable
public static DocumentFile createContentDownloadDir(@NonNull Context context, @NonNull Content content) {
DocumentFile siteDownloadDir = getOrCreateSiteDownloadDir(context, null, content.getSite());
if (null == siteDownloadDir) return null;
String bookFolderName = formatBookFolderName(content);
DocumentFile bookFolder = FileHelper.findFolder(context, siteDownloadDir, bookFolderName);
if (null == bookFolder) { // Create
return siteDownloadDir.createDirectory(bookFolderName);
} else return bookFolder;
}
/**
* Format the download directory path of the given content according to current user preferences
*
* @param content Content to get the path from
* @return Canonical download directory path of the given content, according to current user preferences
*/
public static String formatBookFolderName(@NonNull final Content content) {
String result = "";
String title = content.getTitle();
title = (null == title) ? "" : title.replaceAll(UNAUTHORIZED_CHARS, "_");
String author = content.getAuthor().toLowerCase().replaceAll(UNAUTHORIZED_CHARS, "_");
switch (Preferences.getFolderNameFormat()) {
case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_ID:
result += title;
break;
case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID:
result += author + " - " + title;
break;
case Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_AUTH_ID:
result += title + " - " + author;
break;
}
result += " - ";
// Unique content ID
String suffix = formatBookId(content);
// Truncate folder dir to something manageable for Windows
// If we are to assume NTFS and Windows, then the fully qualified file, with it's drivename, path, filename, and extension, altogether is limited to 260 characters.
int truncLength = Preferences.getFolderTruncationNbChars();
int titleLength = result.length();
if (truncLength > 0 && titleLength + suffix.length() > truncLength)
result = result.substring(0, truncLength - suffix.length() - 1);
result += suffix;
return result;
}
/**
* Format the Content ID for folder naming purposes
*
* @param content Content whose ID to format
* @return Formatted Content ID
*/
@SuppressWarnings("squid:S2676") // Math.abs is used for formatting purposes only
public static String formatBookId(@NonNull final Content content) {
String id = content.getUniqueSiteId();
// For certain sources (8muses, fakku), unique IDs are strings that may be very long
// => shorten them by using their hashCode
if (id.length() > 10) id = Helper.formatIntAsStr(Math.abs(id.hashCode()), 10);
return "[" + id + "]";
}
/**
* Return the given site's download directory. Create it if it doesn't exist.
*
* @param context Context to use for the action
* @param site Site to get the download directory for
* @return Download directory of the given Site
*/
@Nullable
static DocumentFile getOrCreateSiteDownloadDir(@NonNull Context context, @Nullable ContentProviderClient client, @NonNull Site site) {
String appUriStr = Preferences.getStorageUri();
if (appUriStr.isEmpty()) {
Timber.e("No storage URI defined for the app");
return null;
}
DocumentFile appFolder = DocumentFile.fromTreeUri(context, Uri.parse(appUriStr));
if (null == appFolder || !appFolder.exists()) {
Timber.e("App folder %s does not exist", appUriStr);
return null;
}
String siteFolderName = site.getFolder();
DocumentFile siteFolder;
if (null == client)
siteFolder = FileHelper.findFolder(context, appFolder, siteFolderName);
else
siteFolder = FileHelper.findFolder(context, appFolder, client, siteFolderName);
if (null == siteFolder) // Create
return appFolder.createDirectory(siteFolderName);
else return siteFolder;
}
/**
* Open the "share with..." Android dialog for the given Content
*
* @param context Context to use for the action
* @param item Content to share
*/
public static void shareContent(@NonNull final Context context, @NonNull final Content item) {
String url = item.getGalleryUrl();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, item.getTitle());
intent.putExtra(Intent.EXTRA_TEXT, url);
context.startActivity(Intent.createChooser(intent, context.getString(R.string.send_to)));
}
/**
* Parse the given download parameters string into a map of strings
*
* @param downloadParamsStr String representation of the download parameters to parse
* @return Map of strings describing the given download parameters
*/
public static Map<String, String> parseDownloadParams(final String downloadParamsStr) {
// Handle empty and {}
if (null == downloadParamsStr || downloadParamsStr.trim().length() <= 2)
return new HashMap<>();
try {
return JsonHelper.jsonToObject(downloadParamsStr, JsonHelper.MAP_STRINGS);
} catch (IOException e) {
Timber.w(e);
}
return new HashMap<>();
}
/**
* Remove the leading zeroes and the file extension of the given string
*
* @param s String to be cleaned
* @return Input string, without leading zeroes and extension
*/
private static String removeLeadingZeroesAndExtension(@Nullable String s) {
if (null == s) return "";
int beginIndex = 0;
if (s.startsWith("0")) beginIndex = -1;
for (int i = 0; i < s.length(); i++) {
if (-1 == beginIndex && s.charAt(i) != '0') beginIndex = i;
if ('.' == s.charAt(i)) return s.substring(beginIndex, i);
}
return (-1 == beginIndex) ? "0" : s.substring(beginIndex);
}
/**
* Remove the leading zeroes and the file extension of the given string using cached results
*
* @param s String to be cleaned
* @return Input string, without leading zeroes and extension
*/
private static String removeLeadingZeroesAndExtensionCached(String s) {
if (fileNameMatchCache.containsKey(s)) return fileNameMatchCache.get(s);
else {
String result = removeLeadingZeroesAndExtension(s);
fileNameMatchCache.put(s, result);
return result;
}
}
/**
* Matches the given files to the given ImageFiles according to their name (without leading zeroes nor file extension)
*
* @param files Files to be matched to the given ImageFiles
* @param images ImageFiles to be matched to the given files
* @return List of matched ImageFiles, with the Uri of the matching file
*/
public static List<ImageFile> matchFilesToImageList(@NonNull final List<DocumentFile> files, @NonNull final List<ImageFile> images) {
Map<String, ImmutablePair<String, Long>> fileNameProperties = new HashMap<>(files.size());
List<ImageFile> result = new ArrayList<>();
for (DocumentFile file : files)
fileNameProperties.put(removeLeadingZeroesAndExtensionCached(file.getName()), new ImmutablePair<>(file.getUri().toString(), file.length()));
for (ImageFile img : images) {
String imgName = removeLeadingZeroesAndExtensionCached(img.getName());
if (fileNameProperties.containsKey(imgName)) {
ImmutablePair<String, Long> property = fileNameProperties.get(imgName);
if (property != null)
result.add(img.setFileUri(property.left).setSize(property.right).setStatus(StatusContent.DOWNLOADED).setIsCover(imgName.equals(Consts.THUMB_FILE_NAME)));
} else
Timber.i(">> img dropped %s", imgName);
}
return result;
}
/**
* Create the list of ImageFiles from the given folder
*
* @param context Context to be used
* @param folder Folder to read the images from
* @return List of ImageFiles corresponding to all supported pictures inside the given folder, sorted numerically then alphabetically
*/
public static List<ImageFile> createImageListFromFolder(@NonNull final Context context, @NonNull final DocumentFile folder) {
List<DocumentFile> imageFiles = FileHelper.listFiles(context, folder, ImageHelper.getImageNamesFilter());
if (!imageFiles.isEmpty())
return createImageListFromFiles(imageFiles);
else return Collections.emptyList();
}
/**
* Create the list of ImageFiles from the given files
*
* @param files Files to find images into
* @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically
*/
public static List<ImageFile> createImageListFromFiles(@NonNull final List<DocumentFile> files) {
return createImageListFromFiles(files, StatusContent.DOWNLOADED, 0, "");
}
/**
* Create the list of ImageFiles from the given files
*
* @param files Files to find images into
* @param targetStatus Target status of the ImageFiles to create
* @param startingOrder Starting order of the ImageFiles to create
* @param namePrefix Prefix to add in front of the name of the ImageFiles to create
* @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically
*/
public static List<ImageFile> createImageListFromFiles(
@NonNull final List<DocumentFile> files,
@NonNull final StatusContent targetStatus,
int startingOrder,
@NonNull final String namePrefix) {
Helper.assertNonUiThread();
List<ImageFile> result = new ArrayList<>();
int order = startingOrder;
// Sort files by anything that resembles a number inside their names
List<DocumentFile> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberFileComparator()).collect(toList());
for (DocumentFile f : fileList) {
String name = namePrefix + ((f.getName() != null) ? f.getName() : "");
ImageFile img = new ImageFile();
if (name.startsWith(Consts.THUMB_FILE_NAME)) img.setIsCover(true);
else order++;
img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(f.getUri().toString()).setStatus(targetStatus).setFileUri(f.getUri().toString()).setSize(f.length());
img.setMimeType(FileHelper.getMimeTypeFromFileName(name));
result.add(img);
}
return result;
}
public static List<ImageFile> createImageListFromZipEntries(
@NonNull final Uri zipFileUri,
@NonNull final List<ZipEntry> files,
@NonNull final StatusContent targetStatus,
int startingOrder,
@NonNull final String namePrefix) {
Helper.assertNonUiThread();
List<ImageFile> result = new ArrayList<>();
int order = startingOrder;
// Sort files by anything that resembles a number inside their names (default entry order from ZipInputStream is chaotic)
List<ZipEntry> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberZipComparator()).collect(toList());
for (ZipEntry f : fileList) {
String name = namePrefix + f.getName();
String path = zipFileUri.toString() + File.separator + f.getName();
ImageFile img = new ImageFile();
if (name.startsWith(Consts.THUMB_FILE_NAME)) img.setIsCover(true);
else order++;
img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(path).setStatus(targetStatus).setFileUri(path).setSize(f.getSize());
img.setMimeType(FileHelper.getMimeTypeFromFileName(name));
result.add(img);
}
return result;
}
/**
* Comparator to be used to sort files according to their names :
* - Sort according to the concatenation of all its numerical characters, if any
* - If none, sort alphabetically (default string compare)
*/
private static class InnerNameNumberFileComparator implements Comparator<DocumentFile> {
@Override
public int compare(@NonNull DocumentFile o1, @NonNull DocumentFile o2) {
String name1 = o1.getName();
if (null == name1) name1 = "";
String name2 = o2.getName();
if (null == name2) name2 = "";
return new InnerNameNumberComparator().compare(name1, name2);
}
}
private static class InnerNameNumberZipComparator implements Comparator<ZipEntry> {
@Override
public int compare(@NonNull ZipEntry o1, @NonNull ZipEntry o2) {
return new ContentHelper.InnerNameNumberComparator().compare(o1.getName(), o2.getName());
}
}
public static class InnerNameNumberComparator implements Comparator<String> {
@Override
public int compare(@NonNull String name1, @NonNull String name2) {
long innerNumber1 = Helper.extractNumeric(name1);
if (-1 == innerNumber1) return name1.compareTo(name2);
long innerNumber2 = Helper.extractNumeric(name2);
if (-1 == innerNumber2) return name1.compareTo(name2);
return Long.compare(innerNumber1, innerNumber2);
}
}
}
| Cleanup
| app/src/main/java/me/devsaki/hentoid/util/ContentHelper.java | Cleanup | <ide><path>pp/src/main/java/me/devsaki/hentoid/util/ContentHelper.java
<ide> // Remove the cover stored in the app's persistent folder
<ide> File appFolder = context.getFilesDir();
<ide> File[] images = appFolder.listFiles((dir, name) -> FileHelper.getFileNameWithoutExtension(name).equals(content.getId() + ""));
<del> for (File f : images) FileHelper.removeFile(f);
<add> if (images != null)
<add> for (File f : images) FileHelper.removeFile(f);
<ide> } else { // Remove a folder and its content
<ide> // If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete
<ide> DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri());
<ide> // Remove all images stored in the app's persistent folder (archive covers)
<ide> File appFolder = context.getFilesDir();
<ide> File[] images = appFolder.listFiles((dir, name) -> ImageHelper.isSupportedImage(name));
<del> for (File f : images) FileHelper.removeFile(f);
<add> if (images != null)
<add> for (File f : images) FileHelper.removeFile(f);
<ide> }
<ide>
<ide> /**
<ide> // Extract the cover to the app's persistent folder if the book is an archive
<ide> if (content.isArchive()) {
<ide> DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri());
<del> try {
<del> List<Uri> outputFiles = ArchiveHelper.extractZipEntries(
<del> context,
<del> archive,
<del> Stream.of(content.getCover().getFileUri().replace(content.getStorageUri() + File.separator, "")).toList(),
<del> context.getFilesDir(),
<del> Stream.of(newContentId + "").toList());
<del> if (!outputFiles.isEmpty()) {
<del> content.getCover().setFileUri(outputFiles.get(0).toString());
<del> dao.replaceImageList(newContentId, content.getImageFiles());
<add> if (archive != null) {
<add> try {
<add> List<Uri> outputFiles = ArchiveHelper.extractZipEntries(
<add> context,
<add> archive,
<add> Stream.of(content.getCover().getFileUri().replace(content.getStorageUri() + File.separator, "")).toList(),
<add> context.getFilesDir(),
<add> Stream.of(newContentId + "").toList());
<add> if (!outputFiles.isEmpty() && content.getImageFiles() != null) {
<add> content.getCover().setFileUri(outputFiles.get(0).toString());
<add> dao.replaceImageList(newContentId, content.getImageFiles());
<add> }
<add> } catch (IOException e) {
<add> Timber.w(e);
<ide> }
<del> } catch (IOException e) {
<del> Timber.w(e);
<ide> }
<ide> }
<ide> |
|
JavaScript | bsd-3-clause | fc7fea686a7b209e9dc2e13d48b9fbd15cc91562 | 0 | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | var Validator = {};
(function(){
var validateAll = function(event)
{
var inputs = document.getElementsByClassName("new_custom_value_input");
var valuesAreValid = true;
for (var i = 0; i < inputs.length; i++){
if( !validateSingleInput( $(inputs[i]) ) )
valuesAreValid = false;
}
if(!valuesAreValid){
event.preventDefault();
event.stopPropagation();
}
}
var validateSingleInput = function(inputElement){
var currentInput = inputElement;
var errorMessage = currentInput.parents("tr").find(".error_message");
errorMessage.hide();
currentInput.css('border', '1px solid #ccc');
var currentType = currentInput.parents("tr").find(".type_meta").val().trim();
var currentAllowedValues = currentInput.parents("tr").find(".allowed_values_meta").val().trim();
if(!validateNewValue(currentInput.val(), currentType, currentAllowedValues)){
currentInput.css('border', '1px solid #ff0000');
errorMessage.show();
return false;
}
return true;
}
var validateNewValue = function(value, acceptableType, allowedValues){
if(value==''){
return true;
}
if (acceptableType=="string") {
return validateString(value, allowedValues)
}
if (acceptableType=="integer") {
try {
var bigVal = new BigNumber(value)
} catch (err) {
return false;
}
if(value.indexOf('.') !== -1)
return false;
return validateNumber(bigVal, allowedValues)
}
if (acceptableType=="float") {
if(value.indexOf('.') == -1)
return false;
try {
var bigVal = new BigNumber(value)
} catch (err) {
return false;
}
return validateNumber(bigVal, allowedValues)
}
if (acceptableType=="boolean") {
return true;
}
return false;
}
var validateNumber = function(value, allowedValues){
// var numericVal = +value;
if(value.isNaN())
return false;
if(allowedValues == "")
return true;
var allowedSet = allowedValues.split(/\s*[,]\s*/)
console.log(allowedSet)
for (var i in allowedSet) {
try{
var constraintVal = new BigNumber(allowedSet[i])
console.log("worked for value"+allowedSet[i])
if ( value.equals(constraintVal) ) {
return true;
}
} catch (err) {
console.log("failed for value"+allowedSet[i])
if( testNumberRange(value, allowedSet[i]) ){
return true;
}
}
}
return false;
}
var testNumberRange = function(value, range){
var nums = range.split(/\s*[:]\s*/)
var lowerLimit = new BigNumber( nums[0] )
if(nums[1] != ""){
var upperLimit = new BigNumber( nums[1] )
if( value.gte(lowerLimit) && value.lte(upperLimit) ){
return true;
}
}
else {
console.log(lowerLimit)
if( value.gte(lowerLimit) ){
return true;
}
}
return false;
}
var validateString = function(value, allowedValues){
if(allowedValues=="")
return true;
var allowedSet = allowedValues.split(/\s*[\s,]\s*/)
for (var i in allowedSet) {
if (value == allowedSet[i]) {
return true;
}
}
return false;
}
$.extend(
Validator,
{validateAll: validateAll},
{validateSingleInput: validateSingleInput})
})();
| dbaas/logical/static/js/parameters_validator.js | var Validator = {};
(function(){
var validateAll = function(event)
{
var inputs = document.getElementsByClassName("new_custom_value_input");
var valuesAreValid = true;
for (var i = 0; i < inputs.length; i++){
if( !validateSingleInput( $(inputs[i]) ) )
valuesAreValid = false;
}
if(!valuesAreValid){
event.preventDefault();
event.stopPropagation();
}
}
var validateSingleInput = function(inputElement){
var currentInput = inputElement;
var errorMessage = currentInput.parents("tr").find(".error_message");
errorMessage.hide();
currentInput.css('border', '1px solid #ccc');
var currentType = currentInput.parents("tr").find(".type_meta").val().trim();
var currentAllowedValues = currentInput.parents("tr").find(".allowed_values_meta").val().trim();
if(!validateNewValue(currentInput.val(), currentType, currentAllowedValues)){
currentInput.css('border', '1px solid #ff0000');
errorMessage.show();
return false;
}
return true;
}
var validateNewValue = function(value, acceptableType, allowedValues){
if(value==''){
return true;
}
if (acceptableType=="string") {
return validateString(value, allowedValues)
}
if (acceptableType=="integer") {
try {
var bigVal = new BigNumber(value)
} catch (err) {
return false;
}
if(value.indexOf('.') !== -1)
return false;
return validateNumber(bigVal, allowedValues)
}
if (acceptableType=="float") {
if(value.indexOf('.') == -1)
return false;
try {
var bigVal = new BigNumber(value)
} catch (err) {
return false;
}
return validateNumber(bigVal, allowedValues)
}
if (acceptableType=="boolean") {
return true;
}
return false;
}
var validateNumber = function(value, allowedValues){
// var numericVal = +value;
if(value.isNaN())
return false;
if(allowedValues == "")
return true;
var allowedSet = allowedValues.split(/\s*[\s,]\s*/)
for (var i in allowedSet) {
try{
var constraintVal = new BigNumber(allowedSet[i])
} catch (err) {
return testNumberRange(value, allowedSet[i])
}
if ( value.equals(constraintVal) ) {
return true;
}
}
return false;
}
var testNumberRange = function(value, range){
var nums = range.split(/\s*[\s:]\s*/)
var lowerLimit = new BigNumber( nums[0] )
if(nums[1] != ""){
var upperLimit = new BigNumber( nums[1] )
if( value.gte(lowerLimit) && value.lte(upperLimit) ){
return true;
}
}
else {
if( value.gte(lowerLimit) ){
return true;
}
}
return false;
}
var validateString = function(value, allowedValues){
if(allowedValues=="")
return true;
var allowedSet = allowedValues.split(/\s*[\s,]\s*/)
for (var i in allowedSet) {
if (value == allowedSet[i]) {
return true;
}
}
return false;
}
$.extend(
Validator,
{validateAll: validateAll},
{validateSingleInput: validateSingleInput})
})();
| Fix regex in javascript validator
| dbaas/logical/static/js/parameters_validator.js | Fix regex in javascript validator | <ide><path>baas/logical/static/js/parameters_validator.js
<ide> if(allowedValues == "")
<ide> return true;
<ide>
<del> var allowedSet = allowedValues.split(/\s*[\s,]\s*/)
<add> var allowedSet = allowedValues.split(/\s*[,]\s*/)
<add> console.log(allowedSet)
<ide> for (var i in allowedSet) {
<ide> try{
<ide> var constraintVal = new BigNumber(allowedSet[i])
<add> console.log("worked for value"+allowedSet[i])
<add>
<add> if ( value.equals(constraintVal) ) {
<add> return true;
<add> }
<add>
<ide> } catch (err) {
<del> return testNumberRange(value, allowedSet[i])
<del> }
<del> if ( value.equals(constraintVal) ) {
<del> return true;
<add> console.log("failed for value"+allowedSet[i])
<add> if( testNumberRange(value, allowedSet[i]) ){
<add> return true;
<add> }
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> var testNumberRange = function(value, range){
<del> var nums = range.split(/\s*[\s:]\s*/)
<add> var nums = range.split(/\s*[:]\s*/)
<ide> var lowerLimit = new BigNumber( nums[0] )
<ide> if(nums[1] != ""){
<ide> var upperLimit = new BigNumber( nums[1] )
<ide> }
<ide> }
<ide> else {
<add> console.log(lowerLimit)
<ide> if( value.gte(lowerLimit) ){
<ide> return true;
<ide> } |
|
Java | apache-2.0 | cd49a69d12b3b9ec29108f59cf49c2a26592c648 | 0 | Sw0rdstream/appium,appium/appium,appium/appium,appium/appium,appium/appium,appium/appium,appium/appium | package io.appium.android.bootstrap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Hashtable;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.core.UiObjectNotFoundException;
class AndroidCommandException extends Exception {
public AndroidCommandException(String msg) {
super(msg);
}
}
class InvalidStrategyException extends AndroidCommandException {
public InvalidStrategyException(String msg) {
super(msg);
}
}
class AndroidCommandHolder {
public static boolean click(Double x, Double y) {
Double[] xCoords = {x};
Double[] yCoords = {y};
ArrayList<Integer> posXVals = absXPosFromCoords(xCoords);
ArrayList<Integer> posYVals = absYPosFromCoords(yCoords);
return UiDevice.getInstance().click(posXVals.get(0), posYVals.get(1));
}
private static ArrayList<Integer> absPosFromCoords(Double[] coordVals, Double screenDim) {
ArrayList<Integer> retPos = new ArrayList<Integer>();
Integer curVal;
for (Double coord : coordVals) {
if (coord < 1) {
curVal = (int)(screenDim * coord);
} else {
curVal = coord.intValue();
}
retPos.add(curVal);
}
return retPos;
}
private static ArrayList<Integer> absXPosFromCoords(Double[] coordVals) {
UiDevice d = UiDevice.getInstance();
Double screenX = new Double(d.getDisplayWidth());
return absPosFromCoords(coordVals, screenX);
}
private static ArrayList<Integer> absYPosFromCoords(Double[] coordVals) {
UiDevice d = UiDevice.getInstance();
Double screenY = new Double(d.getDisplayHeight());
return absPosFromCoords(coordVals, screenY);
}
public static boolean swipe(Double startX, Double startY, Double endX, Double endY, Integer steps) {
UiDevice d = UiDevice.getInstance();
Double[] xCoords = {startX, endX};
Double[] yCoords = {startY, endY};
ArrayList<Integer> posXVals = absXPosFromCoords(xCoords);
ArrayList<Integer> posYVals = absYPosFromCoords(yCoords);
return d.swipe(posXVals.get(0), posYVals.get(0), posXVals.get(1), posYVals.get(1), steps);
}
public static boolean flick(Integer xSpeed, Integer ySpeed) {
UiDevice d = UiDevice.getInstance();
Integer screenX = d.getDisplayWidth();
Integer screenY = d.getDisplayHeight();
Integer startX = screenX / 2;
Integer startY = screenY / 2;
Double speedRatio = (double) xSpeed / ySpeed;
Integer xOff;
Integer yOff;
if (speedRatio < 1) {
yOff = screenY / 4;
xOff = (int)((double) screenX / 4 * speedRatio);
} else {
xOff = screenX / 4;
yOff = (int)((double) screenY / 4 / speedRatio);
}
Integer endX = startX + (Integer.signum(xSpeed) * xOff);
Integer endY = startY + (Integer.signum(ySpeed) * yOff);
Double speed = Math.max(1250, Math.sqrt((xSpeed*xSpeed)+(ySpeed*ySpeed)));
Integer steps = (1250 / speed.intValue()) + 1;
return d.swipe(startX, startY, endX, endY, steps);
}
public static JSONObject getDeviceSize() throws AndroidCommandException {
UiDevice d = UiDevice.getInstance();
JSONObject res = new JSONObject();
try {
res.put("width", d.getDisplayHeight());
res.put("height", d.getDisplayWidth());
} catch (JSONException e) {
throw new AndroidCommandException("Error serializing height/width data into JSON");
}
return res;
}
public static JSONObject findElement(String strategy, String selector, String contextId) throws UiObjectNotFoundException, AndroidCommandException, ElementNotFoundException {
UiSelector sel = selectorForFind(strategy, selector, false);
return findElementWithSelector(sel, contextId);
}
public static JSONObject findElementByXpath(JSONArray path, String attr, String constraint, boolean substr, String contextId) throws UiObjectNotFoundException, AndroidCommandException, ElementNotFoundException {
UiSelector sel = selectorForXpath(path, attr, constraint, substr);
return findElementWithSelector(sel, contextId);
}
private static JSONObject findElementWithSelector(UiSelector sel, String contextId) throws UiObjectNotFoundException, AndroidCommandException, ElementNotFoundException {
JSONObject res = new JSONObject();
String elId;
UiObject el;
AndroidElementsHash elHash = AndroidElementsHash.getInstance();
AndroidElement baseEl = contextElement(contextId);
if (baseEl == null) {
el = new UiObject(sel);
} else {
el = baseEl.getChild(sel);
}
if (el.exists()) {
elId = elHash.addElement(el);
try {
res.put("ELEMENT", elId);
} catch (JSONException e) {
throw new AndroidCommandException("Error serializing element ID into JSON");
}
return res;
} else {
throw new ElementNotFoundException();
}
}
public static JSONArray findElements(String strategy, String selector, String contextId) throws AndroidCommandException, UiObjectNotFoundException {
UiSelector sel = selectorForFind(strategy, selector, true);
return findElementsWithSelector(sel, contextId);
}
public static JSONArray findElementsByXpath(JSONArray path, String attr, String constraint, boolean substr, String contextId) throws AndroidCommandException, UiObjectNotFoundException {
UiSelector sel = selectorForXpath(path, attr, constraint, substr);
return findElementsWithSelector(sel, contextId);
}
private static JSONArray findElementsWithSelector(UiSelector sel, String contextId) throws AndroidCommandException, UiObjectNotFoundException {
ArrayList<String> elIds = new ArrayList<String>();
JSONArray res = new JSONArray();
UiObject lastFoundObj;
boolean keepSearching = true;
AndroidElementsHash elHash = AndroidElementsHash.getInstance();
AndroidElement baseEl = contextElement(contextId);
boolean useIndex = sel.toString().contains("CLASS_REGEX=");
UiSelector tmp = null;
int counter = 0;
while (keepSearching) {
if (baseEl == null) {
Logger.info("keep searching A " + counter + " useIndex? " + useIndex);
if (useIndex) {
tmp = sel.index(counter);
} else {
tmp = sel.instance(counter);
}
lastFoundObj = new UiObject(tmp);
} else {
Logger.info("keep searching B " + counter);
lastFoundObj = baseEl.getChild(sel.instance(counter));
}
counter++;
if (lastFoundObj != null && lastFoundObj.exists()) {
Logger.info("Found obj.");
elIds.add(elHash.addElement(lastFoundObj));
} else {
keepSearching = false;
}
}
for (String elId : elIds) {
JSONObject idObj = new JSONObject();
try {
idObj.put("ELEMENT", elId);
} catch (JSONException e) {
throw new AndroidCommandException("Error serializing element ID into JSON");
}
res.put(idObj);
}
return res;
}
private static AndroidElement contextElement(String contextId) throws AndroidCommandException {
AndroidElement baseEl = null;
AndroidElementsHash elHash = AndroidElementsHash.getInstance();
if (!contextId.isEmpty()) {
try {
baseEl = elHash.getElement(contextId);
} catch (ElementNotInHashException e) {
throw new AndroidCommandException(e.getMessage());
}
}
return baseEl;
}
private static UiSelector selectorForXpath(JSONArray path, String attr, String constraint, boolean substr) throws AndroidCommandException {
UiSelector s = new UiSelector();
JSONObject pathObj;
String nodeType;
String searchType;
String substrStr = substr ? "true" : "false";
Logger.info("Building xpath selector from attr " + attr + " and constraint " + constraint + " and substr " + substrStr);
String selOut = "s";
// $driver.find_element :xpath, %(//*[contains(@text, 'agree')])
// info: [ANDROID] [info] Building xpath selector from attr text and
// constraint agree and substr true
// info: [ANDROID] [info] s.className('*').textContains('agree')
try {
nodeType = path.getJSONObject(0).getString("node");
} catch (JSONException e) {
throw new AndroidCommandException(
"Error parsing xpath path obj from JSON");
}
if (attr.toLowerCase().contentEquals("text") && !constraint.isEmpty()
&& substr == true && nodeType.contentEquals("*") == true) {
selOut += ".textContains('" + constraint + "')";
s = s.textContains(constraint);
Logger.info(selOut);
return s;
}
// //*[contains(@tag, "button")]
if (attr.toLowerCase().contentEquals("tag") && !constraint.isEmpty()
&& substr == true && nodeType.contentEquals("*") == true) {
// (?i) = case insensitive match. Esape everything that isn't an alpha num.
// use .* to match on contains.
constraint = "(?i)^.*" + constraint.replaceAll("([^\\p{Alnum}])", "\\\\$1") + ".*$";
selOut += ".classNameMatches('" + constraint + "')";
s = s.classNameMatches(constraint);
Logger.info(selOut);
return s;
}
for (int i = 0; i < path.length(); i++) {
try {
pathObj = path.getJSONObject(i);
nodeType = pathObj.getString("node");
searchType = pathObj.getString("search");
} catch (JSONException e) {
throw new AndroidCommandException("Error parsing xpath path obj from JSON");
}
try {
nodeType = AndroidElementClassMap.match(nodeType);
} catch (UnallowedTagNameException e) {
throw new AndroidCommandException(e.getMessage());
}
if (searchType.equals("child")) {
s = s.childSelector(s);
selOut += ".childSelector(s)";
} else {
s = s.className(nodeType);
selOut += ".className('" + nodeType + "')";
}
}
if (attr.equals("desc") || attr.equals("name")) {
selOut += ".description";
if (substr) {
selOut += "Contains";
s = s.descriptionContains(constraint);
} else {
s = s.description(constraint);
}
selOut += "('" + constraint + "')";
} else if (attr.equals("text") || attr.equals("value")) {
selOut += ".text";
if (substr) {
selOut += "Contains";
s = s.textContains(constraint);
} else {
s = s.text(constraint);
}
selOut += "('" + constraint + "')";
}
Logger.info(selOut);
return s;
}
private static UiSelector selectorForFind(String strategy, String selector, Boolean many) throws InvalidStrategyException, AndroidCommandException {
UiSelector s = new UiSelector();
if (strategy.equals("tag name")) {
String androidClass = "";
try {
androidClass = AndroidElementClassMap.match(selector);
} catch (UnallowedTagNameException e) {
throw new AndroidCommandException(e.getMessage());
}
if (androidClass.contentEquals("android.widget.Button")) {
androidClass += "|android.widget.ImageButton";
androidClass = androidClass.replaceAll("([^\\p{Alnum}|])", "\\\\$1");
s = s.classNameMatches("^" + androidClass + "$");
} else {
s = s.className(androidClass);
}
Logger.info("Using class selector " + androidClass + " for find");
} else if (strategy.equals("name")) {
s = s.descriptionMatches("(?i).*" + selector.replaceAll("([^\\p{Alnum}])", "\\\\$1") + ".*");
} else {
throw new InvalidStrategyException(strategy + " is not a supported selector strategy");
}
if (!many) {
s = s.instance(0);
}
return s;
}
}
| uiautomator/bootstrap/src/io/appium/android/bootstrap/AndroidCommandHolder.java | package io.appium.android.bootstrap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Hashtable;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.core.UiObjectNotFoundException;
class AndroidCommandException extends Exception {
public AndroidCommandException(String msg) {
super(msg);
}
}
class InvalidStrategyException extends AndroidCommandException {
public InvalidStrategyException(String msg) {
super(msg);
}
}
class AndroidCommandHolder {
public static boolean click(Double x, Double y) {
Double[] xCoords = {x};
Double[] yCoords = {y};
ArrayList<Integer> posXVals = absXPosFromCoords(xCoords);
ArrayList<Integer> posYVals = absYPosFromCoords(yCoords);
return UiDevice.getInstance().click(posXVals.get(0), posYVals.get(1));
}
private static ArrayList<Integer> absPosFromCoords(Double[] coordVals, Double screenDim) {
ArrayList<Integer> retPos = new ArrayList<Integer>();
Integer curVal;
for (Double coord : coordVals) {
if (coord < 1) {
curVal = (int)(screenDim * coord);
} else {
curVal = coord.intValue();
}
retPos.add(curVal);
}
return retPos;
}
private static ArrayList<Integer> absXPosFromCoords(Double[] coordVals) {
UiDevice d = UiDevice.getInstance();
Double screenX = new Double(d.getDisplayWidth());
return absPosFromCoords(coordVals, screenX);
}
private static ArrayList<Integer> absYPosFromCoords(Double[] coordVals) {
UiDevice d = UiDevice.getInstance();
Double screenY = new Double(d.getDisplayHeight());
return absPosFromCoords(coordVals, screenY);
}
public static boolean swipe(Double startX, Double startY, Double endX, Double endY, Integer steps) {
UiDevice d = UiDevice.getInstance();
Double[] xCoords = {startX, endX};
Double[] yCoords = {startY, endY};
ArrayList<Integer> posXVals = absXPosFromCoords(xCoords);
ArrayList<Integer> posYVals = absYPosFromCoords(yCoords);
return d.swipe(posXVals.get(0), posYVals.get(0), posXVals.get(1), posYVals.get(1), steps);
}
public static boolean flick(Integer xSpeed, Integer ySpeed) {
UiDevice d = UiDevice.getInstance();
Integer screenX = d.getDisplayWidth();
Integer screenY = d.getDisplayHeight();
Integer startX = screenX / 2;
Integer startY = screenY / 2;
Double speedRatio = (double) xSpeed / ySpeed;
Integer xOff;
Integer yOff;
if (speedRatio < 1) {
yOff = screenY / 4;
xOff = (int)((double) screenX / 4 * speedRatio);
} else {
xOff = screenX / 4;
yOff = (int)((double) screenY / 4 / speedRatio);
}
Integer endX = startX + (Integer.signum(xSpeed) * xOff);
Integer endY = startY + (Integer.signum(ySpeed) * yOff);
Double speed = Math.max(1250, Math.sqrt((xSpeed*xSpeed)+(ySpeed*ySpeed)));
Integer steps = (1250 / speed.intValue()) + 1;
return d.swipe(startX, startY, endX, endY, steps);
}
public static JSONObject getDeviceSize() throws AndroidCommandException {
UiDevice d = UiDevice.getInstance();
JSONObject res = new JSONObject();
try {
res.put("width", d.getDisplayHeight());
res.put("height", d.getDisplayWidth());
} catch (JSONException e) {
throw new AndroidCommandException("Error serializing height/width data into JSON");
}
return res;
}
public static JSONObject findElement(String strategy, String selector, String contextId) throws UiObjectNotFoundException, AndroidCommandException, ElementNotFoundException {
UiSelector sel = selectorForFind(strategy, selector, false);
return findElementWithSelector(sel, contextId);
}
public static JSONObject findElementByXpath(JSONArray path, String attr, String constraint, boolean substr, String contextId) throws UiObjectNotFoundException, AndroidCommandException, ElementNotFoundException {
UiSelector sel = selectorForXpath(path, attr, constraint, substr);
return findElementWithSelector(sel, contextId);
}
private static JSONObject findElementWithSelector(UiSelector sel, String contextId) throws UiObjectNotFoundException, AndroidCommandException, ElementNotFoundException {
JSONObject res = new JSONObject();
String elId;
UiObject el;
AndroidElementsHash elHash = AndroidElementsHash.getInstance();
AndroidElement baseEl = contextElement(contextId);
if (baseEl == null) {
el = new UiObject(sel);
} else {
el = baseEl.getChild(sel);
}
if (el.exists()) {
elId = elHash.addElement(el);
try {
res.put("ELEMENT", elId);
} catch (JSONException e) {
throw new AndroidCommandException("Error serializing element ID into JSON");
}
return res;
} else {
throw new ElementNotFoundException();
}
}
public static JSONArray findElements(String strategy, String selector, String contextId) throws AndroidCommandException, UiObjectNotFoundException {
UiSelector sel = selectorForFind(strategy, selector, true);
return findElementsWithSelector(sel, contextId);
}
public static JSONArray findElementsByXpath(JSONArray path, String attr, String constraint, boolean substr, String contextId) throws AndroidCommandException, UiObjectNotFoundException {
UiSelector sel = selectorForXpath(path, attr, constraint, substr);
return findElementsWithSelector(sel, contextId);
}
private static JSONArray findElementsWithSelector(UiSelector sel, String contextId) throws AndroidCommandException, UiObjectNotFoundException {
ArrayList<String> elIds = new ArrayList<String>();
JSONArray res = new JSONArray();
UiObject lastFoundObj;
boolean keepSearching = true;
AndroidElementsHash elHash = AndroidElementsHash.getInstance();
AndroidElement baseEl = contextElement(contextId);
boolean useIndex = sel.toString().contains("CLASS_REGEX=");
UiSelector tmp = null;
int counter = 0;
while (keepSearching) {
if (baseEl == null) {
Logger.info("keep searching A " + counter + " useIndex? " + useIndex);
if (useIndex) {
tmp = sel.index(counter);
} else {
tmp = sel.instance(counter);
}
lastFoundObj = new UiObject(tmp);
} else {
Logger.info("keep searching B " + counter);
lastFoundObj = baseEl.getChild(sel.instance(counter));
}
counter++;
if (lastFoundObj != null && lastFoundObj.exists()) {
Logger.info("Found obj.");
elIds.add(elHash.addElement(lastFoundObj));
} else {
keepSearching = false;
}
}
for (String elId : elIds) {
JSONObject idObj = new JSONObject();
try {
idObj.put("ELEMENT", elId);
} catch (JSONException e) {
throw new AndroidCommandException("Error serializing element ID into JSON");
}
res.put(idObj);
}
return res;
}
private static AndroidElement contextElement(String contextId) throws AndroidCommandException {
AndroidElement baseEl = null;
AndroidElementsHash elHash = AndroidElementsHash.getInstance();
if (!contextId.isEmpty()) {
try {
baseEl = elHash.getElement(contextId);
} catch (ElementNotInHashException e) {
throw new AndroidCommandException(e.getMessage());
}
}
return baseEl;
}
private static UiSelector selectorForXpath(JSONArray path, String attr, String constraint, boolean substr) throws AndroidCommandException {
UiSelector s = new UiSelector();
JSONObject pathObj;
String nodeType;
String searchType;
String substrStr = substr ? "true" : "false";
Logger.info("Building xpath selector from attr " + attr + " and constraint " + constraint + " and substr " + substrStr);
String selOut = "s";
// $driver.find_element :xpath, %(//*[contains(@text, 'agree')])
// info: [ANDROID] [info] Building xpath selector from attr text and
// constraint agree and substr true
// info: [ANDROID] [info] s.className('*').textContains('agree')
try {
nodeType = path.getJSONObject(0).getString("node");
} catch (JSONException e) {
throw new AndroidCommandException(
"Error parsing xpath path obj from JSON");
}
if (attr.toLowerCase().contentEquals("text") && !constraint.isEmpty()
&& substr == true && nodeType.contentEquals("*") == true) {
selOut += ".textContains('" + constraint + "')";
s = s.textContains(constraint);
Logger.info(selOut);
return s;
}
// //*[contains(@tag, "button")]
if (attr.toLowerCase().contentEquals("tag") && !constraint.isEmpty()
&& substr == true && nodeType.contentEquals("*") == true) {
// (?i) = case insensitive match. Esape everything that isn't an alpha num.
// use .* to match on contains.
constraint = "(?i)^.*" + constraint.replaceAll("([^\\p{Alnum}])", "\\\\$1") + ".*$";
selOut += ".classNameMatches('" + constraint + "')";
s = s.classNameMatches(constraint);
Logger.info(selOut);
return s;
}
for (int i = 0; i < path.length(); i++) {
try {
pathObj = path.getJSONObject(i);
nodeType = pathObj.getString("node");
searchType = pathObj.getString("search");
} catch (JSONException e) {
throw new AndroidCommandException("Error parsing xpath path obj from JSON");
}
try {
nodeType = AndroidElementClassMap.match(nodeType);
} catch (UnallowedTagNameException e) {
throw new AndroidCommandException(e.getMessage());
}
if (searchType.equals("child")) {
s = s.childSelector(s);
selOut += ".childSelector(s)";
} else {
s = s.className(nodeType);
selOut += ".className('" + nodeType + "')";
}
}
if (attr.equals("desc") || attr.equals("name")) {
selOut += ".description";
if (substr) {
selOut += "Contains";
s = s.descriptionContains(constraint);
} else {
s = s.description(constraint);
}
selOut += "('" + constraint + "')";
} else if (attr.equals("text") || attr.equals("value")) {
selOut += ".text";
if (substr) {
selOut += "Contains";
s = s.textContains(constraint);
} else {
s = s.text(constraint);
}
selOut += "('" + constraint + "')";
}
Logger.info(selOut);
return s;
}
private static UiSelector selectorForFind(String strategy, String selector, Boolean many) throws InvalidStrategyException, AndroidCommandException {
UiSelector s = new UiSelector();
if (strategy.equals("tag name")) {
String androidClass = "";
try {
androidClass = AndroidElementClassMap.match(selector);
} catch (UnallowedTagNameException e) {
throw new AndroidCommandException(e.getMessage());
}
if (androidClass.contentEquals("android.widget.Button")) {
androidClass += "|android.widget.ImageButton";
androidClass = androidClass.replaceAll("([^\\p{Alnum}|])", "\\\\$1");
s = s.classNameMatches("^" + androidClass + "$");
} else {
s = s.className(androidClass);
}
Logger.info("Using class selector " + androidClass + " for find");
} else if (strategy.equals("name")) {
s = s.description(selector);
} else {
throw new InvalidStrategyException(strategy + " is not a supported selector strategy");
}
if (!many) {
s = s.instance(0);
}
return s;
}
}
| Make content desc case insensitive and partial
| uiautomator/bootstrap/src/io/appium/android/bootstrap/AndroidCommandHolder.java | Make content desc case insensitive and partial | <ide><path>iautomator/bootstrap/src/io/appium/android/bootstrap/AndroidCommandHolder.java
<ide> }
<ide> Logger.info("Using class selector " + androidClass + " for find");
<ide> } else if (strategy.equals("name")) {
<del> s = s.description(selector);
<add> s = s.descriptionMatches("(?i).*" + selector.replaceAll("([^\\p{Alnum}])", "\\\\$1") + ".*");
<ide> } else {
<ide> throw new InvalidStrategyException(strategy + " is not a supported selector strategy");
<ide> } |
|
Java | apache-2.0 | a8bbc5d29fc95bedcb179a9bdd1acd53357186d5 | 0 | apache/lenya,apache/lenya,apache/lenya,apache/lenya | /*
* Copyright 1999-2004 The Apache Software Foundation
*
* 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.
*
*/
/* $Id: LDAPUser.java,v 1.5 2004/08/16 08:20:26 andreas Exp $ */
package org.apache.lenya.ac.ldap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.lenya.ac.AccessControlException;
import org.apache.lenya.ac.file.FileUser;
import org.apache.log4j.Category;
import com.sun.jndi.ldap.LdapCtxFactory;
public class LDAPUser extends FileUser {
private static Properties defaultProperties = null;
private static Category log = Category.getInstance(LDAPUser.class);
public static final String LDAP_ID = "ldapid";
private static String PROVIDER_URL = "provider-url";
private static String MGR_DN = "mgr-dn";
private static String MGR_PW = "mgr-pw";
private static String PARTIAL_USER_DN = "partial-user-dn";
private static String KEY_STORE = "key-store";
private static String SECURITY_PROTOCOL = "security-protocol";
private static String SECURITY_AUTHENTICATION = "security-authentication";
private String ldapId;
private String ldapName;
/**
* Creates a new LDAPUser object.
*/
public LDAPUser() {
}
/**
* Creates a new LDAPUser object.
* @param configurationDirectory The configuration directory.
*/
public LDAPUser(File configurationDirectory) {
setConfigurationDirectory(configurationDirectory);
}
/**
* Create an LDAPUser
*
* @param configurationDirectory where the user will be attached to
* @param id user id of LDAPUser
* @param email of LDAPUser
* @param ldapId of LDAPUser
* @throws ConfigurationException if the properties could not be read
*/
public LDAPUser(File configurationDirectory, String id, String email, String ldapId)
throws ConfigurationException {
super(configurationDirectory, id, null, email, null);
this.ldapId = ldapId;
initialize();
}
/**
* Create a new LDAPUser from a configuration
*
* @param config the <code>Configuration</code> specifying the user details
* @throws ConfigurationException if the user could not be instantiated
*/
public void configure(Configuration config) throws ConfigurationException {
super.configure(config);
ldapId = config.getChild(LDAP_ID).getValue();
initialize();
}
/**
* Checks if a user exists.
* @param ldapId The LDAP id.
* @return A boolean value.
* @throws AccessControlException when an error occurs. FIXME: This method does not work.
*/
public boolean existsUser(String ldapId) throws AccessControlException {
boolean exists = false;
LdapContext context = null;
try {
readProperties();
context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties
.getProperty(MGR_PW));
String peopleName = "ou=People";
Attributes attributes = new BasicAttributes("uid", ldapId);
NamingEnumeration enumeration = context.search(peopleName, attributes);
exists = enumeration.hasMoreElements();
} catch (Exception e) {
throw new AccessControlException("Exception during search: ", e);
} finally {
try {
if (context != null) {
close(context);
}
} catch (NamingException e) {
throw new AccessControlException("Closing context failed: ", e);
}
}
return exists;
}
/**
* Initializes this user.
*
* @throws ConfigurationException when something went wrong.
*/
protected void initialize() throws ConfigurationException {
LdapContext context = null;
try {
readProperties();
String name = null;
context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties
.getProperty(MGR_PW));
String[] attrs = new String[1];
attrs[0] = "gecos"; /* users full name */
String searchString = "uid=" + ldapId + ",ou=People";
Attributes answer = context.getAttributes(searchString, attrs);
if (answer != null) {
Attribute attr = answer.get("gecos");
if (attr != null) {
for (NamingEnumeration enum = attr.getAll(); enum.hasMore(); enum.next()) {
name = (String) attr.get();
}
}
}
this.ldapName = name;
} catch (Exception e) {
throw new ConfigurationException("Could not read properties", e);
} finally {
try {
if (context != null) {
close(context);
}
} catch (NamingException e) {
throw new ConfigurationException("Closing context failed: ", e);
}
}
}
/**
* (non-Javadoc)
*
* @see org.apache.lenya.cms.ac.FileUser#createConfiguration()
*/
protected Configuration createConfiguration() {
DefaultConfiguration config = (DefaultConfiguration) super.createConfiguration();
// add ldap_id node
DefaultConfiguration child = new DefaultConfiguration(LDAP_ID);
child.setValue(ldapId);
config.addChild(child);
return config;
}
/**
* Get the ldap id
*
* @return the ldap id
*/
public String getLdapId() {
return ldapId;
}
/**
* Set the ldap id
*
* @param string the new ldap id
*/
public void setLdapId(String string) {
ldapId = string;
}
/**
* (non-Javadoc)
*
* @see org.apache.lenya.cms.ac.User#authenticate(java.lang.String)
*/
public boolean authenticate(String password) {
String principal = "uid=" + getLdapId() + ","
+ defaultProperties.getProperty(PARTIAL_USER_DN);
Context ctx = null;
if (log.isDebugEnabled()) {
log.debug("Authenticating with principal [" + principal + "]");
}
boolean authenticated = false;
try {
ctx = bind(principal, password);
authenticated = true;
close(ctx);
if (log.isDebugEnabled()) {
log.debug("Context closed.");
}
} catch (NamingException e) {
// log this failure
// StringWriter writer = new StringWriter();
// e.printStackTrace(new PrintWriter(writer));
if (log.isInfoEnabled()) {
log.info("Bind for user " + principal + " to Ldap server failed: ", e);
}
}
return authenticated;
}
/**
* @see org.apache.lenya.cms.ac.Item#getName()
*/
public String getName() {
return ldapName;
}
/**
* LDAP Users fetch their name information from the LDAP server, so we don't store it locally.
* Since we only have read access we basically can't set the name, i.e. any request to change
* the name is ignored.
*
* @param string is ignored
*/
public void setName(String string) {
// we do not have write access to LDAP, so we ignore
// change request to the name.
}
/**
* The LDAPUser doesn't store any passwords as they are handled by LDAP
*
* @param plainTextPassword is ignored
*/
public void setPassword(String plainTextPassword) {
setEncryptedPassword(null);
}
/**
* The LDAPUser doesn't store any passwords as they are handled by LDAP
*
* @param encryptedPassword is ignored
*/
protected void setEncryptedPassword(String encryptedPassword) {
encryptedPassword = null;
}
/**
* Connect to the LDAP server
*
* @param principal the principal string for the LDAP connection
* @param credentials the credentials for the LDAP connection
* @return a <code>LdapContext</code>
* @throws NamingException if there are problems establishing the Ldap connection
*/
private LdapContext bind(String principal, String credentials) throws NamingException {
log.info("Binding principal: [" + principal + "]");
Hashtable env = new Hashtable();
System.setProperty("javax.net.ssl.trustStore", getConfigurationDirectory()
.getAbsolutePath()
+ File.separator + defaultProperties.getProperty(KEY_STORE));
env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory.class.getName());
env.put(Context.PROVIDER_URL, defaultProperties.getProperty(PROVIDER_URL));
env.put(Context.SECURITY_PROTOCOL, defaultProperties.getProperty(SECURITY_PROTOCOL));
env.put(Context.SECURITY_AUTHENTICATION, defaultProperties
.getProperty(SECURITY_AUTHENTICATION));
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, credentials);
LdapContext ctx = new InitialLdapContext(env, null);
log.info("Finished binding principal.");
return ctx;
}
/**
* Close the connection to the LDAP server
*
* @param ctx the context that was returned from the bind
* @throws NamingException if there is a problem communicating to the LDAP server
*/
private void close(Context ctx) throws NamingException {
ctx.close();
}
/**
* Read the properties
*
* @throws IOException if the properties cannot be found.
*/
private void readProperties() throws IOException {
// create and load default properties
File propertiesFile = new File(getConfigurationDirectory(), "ldap.properties");
if (defaultProperties == null) {
defaultProperties = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(propertiesFile);
defaultProperties.load(in);
} finally {
if (in != null) {
in.close();
}
}
}
}
} | src/java/org/apache/lenya/ac/ldap/LDAPUser.java | /*
* Copyright 1999-2004 The Apache Software Foundation
*
* 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.
*
*/
/* $Id: LDAPUser.java,v 1.4 2004/03/03 12:56:33 gregor Exp $ */
package org.apache.lenya.ac.ldap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.lenya.ac.AccessControlException;
import org.apache.lenya.ac.file.FileUser;
import org.apache.log4j.Category;
import com.sun.jndi.ldap.LdapCtxFactory;
public class LDAPUser extends FileUser {
private static Properties defaultProperties = null;
private static Category log = Category.getInstance(LDAPUser.class);
public static final String LDAP_ID = "ldapid";
private static String PROVIDER_URL = "provider-url";
private static String MGR_DN = "mgr-dn";
private static String MGR_PW = "mgr-pw";
private static String PARTIAL_USER_DN = "partial-user-dn";
private static String KEY_STORE = "key-store";
private static String SECURITY_PROTOCOL = "security-protocol";
private static String SECURITY_AUTHENTICATION = "security-authentication";
private String ldapId;
private String ldapName;
/**
* Creates a new LDAPUser object.
*/
public LDAPUser() {
}
/**
* Creates a new LDAPUser object.
* @param configurationDirectory The configuration directory.
*/
public LDAPUser(File configurationDirectory) {
setConfigurationDirectory(configurationDirectory);
}
/**
* Create an LDAPUser
*
* @param configurationDirectory
* where the user will be attached to
* @param id
* user id of LDAPUser
* @param email
* of LDAPUser
* @param ldapId
* of LDAPUser
* @throws ConfigurationException
* if the properties could not be read
*/
public LDAPUser(File configurationDirectory, String id, String email, String ldapId)
throws ConfigurationException {
super(configurationDirectory, id, null, email, null);
this.ldapId = ldapId;
initialize();
}
/**
* Create a new LDAPUser from a configuration
*
* @param config
* the <code>Configuration</code> specifying the user details
* @throws ConfigurationException
* if the user could not be instantiated
*/
public void configure(Configuration config) throws ConfigurationException {
super.configure(config);
ldapId = config.getChild(LDAP_ID).getValue();
initialize();
}
/**
* Checks if a user exists.
* @param ldapId The LDAP id.
* @return A boolean value.
* @throws AccessControlException when an error occurs.
* FIXME: This method does not work.
*/
public boolean existsUser(String ldapId) throws AccessControlException {
boolean exists = false;
LdapContext context = null;
try {
readProperties();
context =
bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW));
String peopleName = "ou=People";
Attributes attributes = new BasicAttributes("uid", ldapId);
NamingEnumeration enumeration = context.search(peopleName, attributes);
exists = enumeration.hasMoreElements();
} catch (Exception e) {
throw new AccessControlException("Exception during search: ", e);
}
finally {
try {
if (context != null) {
close(context);
}
}
catch (NamingException e) {
throw new AccessControlException("Closing context failed: ", e);
}
}
return exists;
}
/**
* Initializes this user.
*
* @throws ConfigurationException
* when something went wrong.
*/
protected void initialize() throws ConfigurationException {
LdapContext context = null;
try {
readProperties();
String name = null;
context =
bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW));
String[] attrs = new String[1];
attrs[0] = "gecos"; /* users full name */
String searchString = "uid=" + ldapId + ",ou=People";
Attributes answer = context.getAttributes(searchString, attrs);
if (answer != null) {
Attribute attr = answer.get("gecos");
if (attr != null) {
for (NamingEnumeration enum = attr.getAll(); enum.hasMore(); enum.next()) {
name = (String) attr.get();
}
}
}
this.ldapName = name;
} catch (Exception e) {
throw new ConfigurationException("Could not read properties", e);
}
finally {
try {
if (context != null) {
close(context);
}
}
catch (NamingException e) {
throw new ConfigurationException("Closing context failed: ", e);
}
}
}
/**
* (non-Javadoc)
*
* @see org.apache.lenya.cms.ac.FileUser#createConfiguration()
*/
protected Configuration createConfiguration() {
DefaultConfiguration config = (DefaultConfiguration) super.createConfiguration();
// add ldap_id node
DefaultConfiguration child = new DefaultConfiguration(LDAP_ID);
child.setValue(ldapId);
config.addChild(child);
return config;
}
/**
* Get the ldap id
*
* @return the ldap id
*/
public String getLdapId() {
return ldapId;
}
/**
* Set the ldap id
*
* @param string
* the new ldap id
*/
public void setLdapId(String string) {
ldapId = string;
}
/**
* (non-Javadoc)
*
* @see org.apache.lenya.cms.ac.User#authenticate(java.lang.String)
*/
public boolean authenticate(String password) {
String principal =
"uid=" + getLdapId() + "," + defaultProperties.getProperty(PARTIAL_USER_DN);
Context ctx = null;
if (log.isDebugEnabled()) {
log.debug("Authenticating with principal [" + principal + "]");
}
boolean authenticated = false;
try {
ctx = bind(principal, password);
authenticated = true;
close(ctx);
if (log.isDebugEnabled()) {
log.debug("Context closed.");
}
} catch (NamingException e) {
// log this failure
// StringWriter writer = new StringWriter();
// e.printStackTrace(new PrintWriter(writer));
if (log.isInfoEnabled()) {
log.info("Bind for user " + principal + " to Ldap server failed: ", e);
}
}
return authenticated;
}
/**
* @see org.apache.lenya.cms.ac.Item#getName()
*/
public String getName() {
return ldapName;
}
/**
* LDAP Users fetch their name information from the LDAP server, so we don't store it locally.
* Since we only have read access we basically can't set the name, i.e. any request to change
* the name is ignored.
*
* @param string
* is ignored
*/
public void setName(String string) {
// we do not have write access to LDAP, so we ignore
// change request to the name.
}
/**
* The LDAPUser doesn't store any passwords as they are handled by LDAP
*
* @param plainTextPassword
* is ignored
*/
public void setPassword(String plainTextPassword) {
setEncryptedPassword(null);
}
/**
* The LDAPUser doesn't store any passwords as they are handled by LDAP
*
* @param encryptedPassword
* is ignored
*/
protected void setEncryptedPassword(String encryptedPassword) {
encryptedPassword = null;
}
/**
* Connect to the LDAP server
*
* @param principal
* the principal string for the LDAP connection
* @param credentials
* the credentials for the LDAP connection
* @return a <code>LdapContext</code>
* @throws NamingException
* if there are problems establishing the Ldap connection
*/
private LdapContext bind(String principal, String credentials) throws NamingException {
log.info("Binding principal: [" + principal + "]");
Hashtable env = new Hashtable();
System.setProperty(
"javax.net.ssl.trustStore",
getConfigurationDirectory().getAbsolutePath()
+ File.separator
+ defaultProperties.getProperty(KEY_STORE));
env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory.class.getName());
env.put(Context.PROVIDER_URL, defaultProperties.getProperty(PROVIDER_URL));
env.put(Context.SECURITY_PROTOCOL, defaultProperties.getProperty(SECURITY_PROTOCOL));
env.put(
Context.SECURITY_AUTHENTICATION,
defaultProperties.getProperty(SECURITY_AUTHENTICATION));
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, credentials);
LdapContext ctx = new InitialLdapContext(env, null);
log.info("Finished binding principal.");
return ctx;
}
/**
* Close the connection to the LDAP server
*
* @param ctx
* the context that was returned from the bind
* @throws NamingException
* if there is a problem communicating to the LDAP server
*/
private void close(Context ctx) throws NamingException {
ctx.close();
}
/**
* Read the properties
*
* @throws IOException
* if the properties cannot be found.
*/
private void readProperties() throws IOException {
// create and load default properties
File propertiesFile = new File(getConfigurationDirectory(), "ldap.properties");
if (defaultProperties == null) {
defaultProperties = new Properties();
FileInputStream in;
in = new FileInputStream(propertiesFile);
defaultProperties.load(in);
in.close();
}
}
}
| closing stream in finally block
git-svn-id: f6f45834fccde298d83fbef5743c9fd7982a26a3@43215 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/lenya/ac/ldap/LDAPUser.java | closing stream in finally block | <ide><path>rc/java/org/apache/lenya/ac/ldap/LDAPUser.java
<ide> /*
<del> * Copyright 1999-2004 The Apache Software Foundation
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> *
<add> * Copyright 1999-2004 The Apache Software Foundation
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
<add> * in compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License
<add> * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
<add> * or implied. See the License for the specific language governing permissions and limitations under
<add> * the License.
<add> *
<ide> */
<ide>
<del>/* $Id: LDAPUser.java,v 1.4 2004/03/03 12:56:33 gregor Exp $ */
<add>/* $Id: LDAPUser.java,v 1.5 2004/08/16 08:20:26 andreas Exp $ */
<ide>
<ide> package org.apache.lenya.ac.ldap;
<ide>
<ide> import com.sun.jndi.ldap.LdapCtxFactory;
<ide>
<ide> public class LDAPUser extends FileUser {
<del> private static Properties defaultProperties = null;
<del> private static Category log = Category.getInstance(LDAPUser.class);
<del>
<del> public static final String LDAP_ID = "ldapid";
<del> private static String PROVIDER_URL = "provider-url";
<del> private static String MGR_DN = "mgr-dn";
<del> private static String MGR_PW = "mgr-pw";
<del> private static String PARTIAL_USER_DN = "partial-user-dn";
<del> private static String KEY_STORE = "key-store";
<del> private static String SECURITY_PROTOCOL = "security-protocol";
<del> private static String SECURITY_AUTHENTICATION = "security-authentication";
<del> private String ldapId;
<del>
<del> private String ldapName;
<del>
<del> /**
<del> * Creates a new LDAPUser object.
<del> */
<del> public LDAPUser() {
<del> }
<del>
<del> /**
<del> * Creates a new LDAPUser object.
<del> * @param configurationDirectory The configuration directory.
<del> */
<del> public LDAPUser(File configurationDirectory) {
<del> setConfigurationDirectory(configurationDirectory);
<del> }
<del>
<del> /**
<del> * Create an LDAPUser
<del> *
<del> * @param configurationDirectory
<del> * where the user will be attached to
<del> * @param id
<del> * user id of LDAPUser
<del> * @param email
<del> * of LDAPUser
<del> * @param ldapId
<del> * of LDAPUser
<del> * @throws ConfigurationException
<del> * if the properties could not be read
<del> */
<del> public LDAPUser(File configurationDirectory, String id, String email, String ldapId)
<del> throws ConfigurationException {
<del> super(configurationDirectory, id, null, email, null);
<del> this.ldapId = ldapId;
<del>
<del> initialize();
<del> }
<del>
<del> /**
<del> * Create a new LDAPUser from a configuration
<del> *
<del> * @param config
<del> * the <code>Configuration</code> specifying the user details
<del> * @throws ConfigurationException
<del> * if the user could not be instantiated
<del> */
<del> public void configure(Configuration config) throws ConfigurationException {
<del> super.configure(config);
<del> ldapId = config.getChild(LDAP_ID).getValue();
<del>
<del> initialize();
<del> }
<del>
<del> /**
<del> * Checks if a user exists.
<del> * @param ldapId The LDAP id.
<del> * @return A boolean value.
<del> * @throws AccessControlException when an error occurs.
<del> * FIXME: This method does not work.
<del> */
<del> public boolean existsUser(String ldapId) throws AccessControlException {
<del>
<del> boolean exists = false;
<del> LdapContext context = null;
<del>
<del> try {
<del> readProperties();
<del>
<del> context =
<del> bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW));
<del>
<del> String peopleName = "ou=People";
<del> Attributes attributes = new BasicAttributes("uid", ldapId);
<del> NamingEnumeration enumeration = context.search(peopleName, attributes);
<del>
<del> exists = enumeration.hasMoreElements();
<del> } catch (Exception e) {
<del> throw new AccessControlException("Exception during search: ", e);
<del> }
<del> finally {
<del> try {
<del> if (context != null) {
<del> close(context);
<del> }
<del> }
<del> catch (NamingException e) {
<del> throw new AccessControlException("Closing context failed: ", e);
<del> }
<del> }
<del> return exists;
<del> }
<del>
<del> /**
<del> * Initializes this user.
<del> *
<del> * @throws ConfigurationException
<del> * when something went wrong.
<del> */
<del> protected void initialize() throws ConfigurationException {
<del> LdapContext context = null;
<del> try {
<del> readProperties();
<del>
<del> String name = null;
<del> context =
<del> bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW));
<del>
<del> String[] attrs = new String[1];
<del> attrs[0] = "gecos"; /* users full name */
<del>
<del> String searchString = "uid=" + ldapId + ",ou=People";
<del> Attributes answer = context.getAttributes(searchString, attrs);
<del>
<del> if (answer != null) {
<del> Attribute attr = answer.get("gecos");
<del>
<del> if (attr != null) {
<del> for (NamingEnumeration enum = attr.getAll(); enum.hasMore(); enum.next()) {
<del> name = (String) attr.get();
<del> }
<del> }
<del> }
<del>
<del> this.ldapName = name;
<del> } catch (Exception e) {
<del> throw new ConfigurationException("Could not read properties", e);
<del> }
<del> finally {
<del> try {
<del> if (context != null) {
<del> close(context);
<del> }
<del> }
<del> catch (NamingException e) {
<del> throw new ConfigurationException("Closing context failed: ", e);
<del> }
<del> }
<del> }
<del>
<del> /**
<del> * (non-Javadoc)
<del> *
<del> * @see org.apache.lenya.cms.ac.FileUser#createConfiguration()
<del> */
<del> protected Configuration createConfiguration() {
<del> DefaultConfiguration config = (DefaultConfiguration) super.createConfiguration();
<del>
<del> // add ldap_id node
<del> DefaultConfiguration child = new DefaultConfiguration(LDAP_ID);
<del> child.setValue(ldapId);
<del> config.addChild(child);
<del>
<del> return config;
<del> }
<del>
<del> /**
<del> * Get the ldap id
<del> *
<del> * @return the ldap id
<del> */
<del> public String getLdapId() {
<del> return ldapId;
<del> }
<del>
<del> /**
<del> * Set the ldap id
<del> *
<del> * @param string
<del> * the new ldap id
<del> */
<del> public void setLdapId(String string) {
<del> ldapId = string;
<del> }
<del>
<del> /**
<del> * (non-Javadoc)
<del> *
<del> * @see org.apache.lenya.cms.ac.User#authenticate(java.lang.String)
<del> */
<del> public boolean authenticate(String password) {
<del>
<del> String principal =
<del> "uid=" + getLdapId() + "," + defaultProperties.getProperty(PARTIAL_USER_DN);
<del> Context ctx = null;
<add> private static Properties defaultProperties = null;
<add> private static Category log = Category.getInstance(LDAPUser.class);
<add>
<add> public static final String LDAP_ID = "ldapid";
<add> private static String PROVIDER_URL = "provider-url";
<add> private static String MGR_DN = "mgr-dn";
<add> private static String MGR_PW = "mgr-pw";
<add> private static String PARTIAL_USER_DN = "partial-user-dn";
<add> private static String KEY_STORE = "key-store";
<add> private static String SECURITY_PROTOCOL = "security-protocol";
<add> private static String SECURITY_AUTHENTICATION = "security-authentication";
<add> private String ldapId;
<add>
<add> private String ldapName;
<add>
<add> /**
<add> * Creates a new LDAPUser object.
<add> */
<add> public LDAPUser() {
<add> }
<add>
<add> /**
<add> * Creates a new LDAPUser object.
<add> * @param configurationDirectory The configuration directory.
<add> */
<add> public LDAPUser(File configurationDirectory) {
<add> setConfigurationDirectory(configurationDirectory);
<add> }
<add>
<add> /**
<add> * Create an LDAPUser
<add> *
<add> * @param configurationDirectory where the user will be attached to
<add> * @param id user id of LDAPUser
<add> * @param email of LDAPUser
<add> * @param ldapId of LDAPUser
<add> * @throws ConfigurationException if the properties could not be read
<add> */
<add> public LDAPUser(File configurationDirectory, String id, String email, String ldapId)
<add> throws ConfigurationException {
<add> super(configurationDirectory, id, null, email, null);
<add> this.ldapId = ldapId;
<add>
<add> initialize();
<add> }
<add>
<add> /**
<add> * Create a new LDAPUser from a configuration
<add> *
<add> * @param config the <code>Configuration</code> specifying the user details
<add> * @throws ConfigurationException if the user could not be instantiated
<add> */
<add> public void configure(Configuration config) throws ConfigurationException {
<add> super.configure(config);
<add> ldapId = config.getChild(LDAP_ID).getValue();
<add>
<add> initialize();
<add> }
<add>
<add> /**
<add> * Checks if a user exists.
<add> * @param ldapId The LDAP id.
<add> * @return A boolean value.
<add> * @throws AccessControlException when an error occurs. FIXME: This method does not work.
<add> */
<add> public boolean existsUser(String ldapId) throws AccessControlException {
<add>
<add> boolean exists = false;
<add> LdapContext context = null;
<add>
<add> try {
<add> readProperties();
<add>
<add> context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties
<add> .getProperty(MGR_PW));
<add>
<add> String peopleName = "ou=People";
<add> Attributes attributes = new BasicAttributes("uid", ldapId);
<add> NamingEnumeration enumeration = context.search(peopleName, attributes);
<add>
<add> exists = enumeration.hasMoreElements();
<add> } catch (Exception e) {
<add> throw new AccessControlException("Exception during search: ", e);
<add> } finally {
<add> try {
<add> if (context != null) {
<add> close(context);
<add> }
<add> } catch (NamingException e) {
<add> throw new AccessControlException("Closing context failed: ", e);
<add> }
<add> }
<add> return exists;
<add> }
<add>
<add> /**
<add> * Initializes this user.
<add> *
<add> * @throws ConfigurationException when something went wrong.
<add> */
<add> protected void initialize() throws ConfigurationException {
<add> LdapContext context = null;
<add> try {
<add> readProperties();
<add>
<add> String name = null;
<add> context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties
<add> .getProperty(MGR_PW));
<add>
<add> String[] attrs = new String[1];
<add> attrs[0] = "gecos"; /* users full name */
<add>
<add> String searchString = "uid=" + ldapId + ",ou=People";
<add> Attributes answer = context.getAttributes(searchString, attrs);
<add>
<add> if (answer != null) {
<add> Attribute attr = answer.get("gecos");
<add>
<add> if (attr != null) {
<add> for (NamingEnumeration enum = attr.getAll(); enum.hasMore(); enum.next()) {
<add> name = (String) attr.get();
<add> }
<add> }
<add> }
<add>
<add> this.ldapName = name;
<add> } catch (Exception e) {
<add> throw new ConfigurationException("Could not read properties", e);
<add> } finally {
<add> try {
<add> if (context != null) {
<add> close(context);
<add> }
<add> } catch (NamingException e) {
<add> throw new ConfigurationException("Closing context failed: ", e);
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * (non-Javadoc)
<add> *
<add> * @see org.apache.lenya.cms.ac.FileUser#createConfiguration()
<add> */
<add> protected Configuration createConfiguration() {
<add> DefaultConfiguration config = (DefaultConfiguration) super.createConfiguration();
<add>
<add> // add ldap_id node
<add> DefaultConfiguration child = new DefaultConfiguration(LDAP_ID);
<add> child.setValue(ldapId);
<add> config.addChild(child);
<add>
<add> return config;
<add> }
<add>
<add> /**
<add> * Get the ldap id
<add> *
<add> * @return the ldap id
<add> */
<add> public String getLdapId() {
<add> return ldapId;
<add> }
<add>
<add> /**
<add> * Set the ldap id
<add> *
<add> * @param string the new ldap id
<add> */
<add> public void setLdapId(String string) {
<add> ldapId = string;
<add> }
<add>
<add> /**
<add> * (non-Javadoc)
<add> *
<add> * @see org.apache.lenya.cms.ac.User#authenticate(java.lang.String)
<add> */
<add> public boolean authenticate(String password) {
<add>
<add> String principal = "uid=" + getLdapId() + ","
<add> + defaultProperties.getProperty(PARTIAL_USER_DN);
<add> Context ctx = null;
<ide>
<ide> if (log.isDebugEnabled()) {
<ide> log.debug("Authenticating with principal [" + principal + "]");
<ide> }
<del>
<add>
<ide> boolean authenticated = false;
<ide>
<del> try {
<del> ctx = bind(principal, password);
<add> try {
<add> ctx = bind(principal, password);
<ide> authenticated = true;
<ide> close(ctx);
<ide> if (log.isDebugEnabled()) {
<ide> log.debug("Context closed.");
<ide> }
<del> } catch (NamingException e) {
<del> // log this failure
<del> // StringWriter writer = new StringWriter();
<del> // e.printStackTrace(new PrintWriter(writer));
<add> } catch (NamingException e) {
<add> // log this failure
<add> // StringWriter writer = new StringWriter();
<add> // e.printStackTrace(new PrintWriter(writer));
<ide> if (log.isInfoEnabled()) {
<ide> log.info("Bind for user " + principal + " to Ldap server failed: ", e);
<ide> }
<del> }
<del>
<del> return authenticated;
<del> }
<del>
<del> /**
<del> * @see org.apache.lenya.cms.ac.Item#getName()
<del> */
<del> public String getName() {
<del> return ldapName;
<del> }
<del>
<del> /**
<del> * LDAP Users fetch their name information from the LDAP server, so we don't store it locally.
<del> * Since we only have read access we basically can't set the name, i.e. any request to change
<del> * the name is ignored.
<del> *
<del> * @param string
<del> * is ignored
<del> */
<del> public void setName(String string) {
<del> // we do not have write access to LDAP, so we ignore
<del> // change request to the name.
<del> }
<del>
<del> /**
<del> * The LDAPUser doesn't store any passwords as they are handled by LDAP
<del> *
<del> * @param plainTextPassword
<del> * is ignored
<del> */
<del> public void setPassword(String plainTextPassword) {
<del> setEncryptedPassword(null);
<del> }
<del>
<del> /**
<del> * The LDAPUser doesn't store any passwords as they are handled by LDAP
<del> *
<del> * @param encryptedPassword
<del> * is ignored
<del> */
<del> protected void setEncryptedPassword(String encryptedPassword) {
<del> encryptedPassword = null;
<del> }
<del>
<del> /**
<del> * Connect to the LDAP server
<del> *
<del> * @param principal
<del> * the principal string for the LDAP connection
<del> * @param credentials
<del> * the credentials for the LDAP connection
<del> * @return a <code>LdapContext</code>
<del> * @throws NamingException
<del> * if there are problems establishing the Ldap connection
<del> */
<del> private LdapContext bind(String principal, String credentials) throws NamingException {
<del>
<del> log.info("Binding principal: [" + principal + "]");
<del>
<del> Hashtable env = new Hashtable();
<del>
<del> System.setProperty(
<del> "javax.net.ssl.trustStore",
<del> getConfigurationDirectory().getAbsolutePath()
<del> + File.separator
<del> + defaultProperties.getProperty(KEY_STORE));
<del>
<del> env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory.class.getName());
<del> env.put(Context.PROVIDER_URL, defaultProperties.getProperty(PROVIDER_URL));
<del> env.put(Context.SECURITY_PROTOCOL, defaultProperties.getProperty(SECURITY_PROTOCOL));
<del> env.put(
<del> Context.SECURITY_AUTHENTICATION,
<del> defaultProperties.getProperty(SECURITY_AUTHENTICATION));
<del> env.put(Context.SECURITY_PRINCIPAL, principal);
<del> env.put(Context.SECURITY_CREDENTIALS, credentials);
<del>
<del> LdapContext ctx = new InitialLdapContext(env, null);
<del>
<del> log.info("Finished binding principal.");
<del>
<del> return ctx;
<del> }
<del>
<del> /**
<del> * Close the connection to the LDAP server
<del> *
<del> * @param ctx
<del> * the context that was returned from the bind
<del> * @throws NamingException
<del> * if there is a problem communicating to the LDAP server
<del> */
<del> private void close(Context ctx) throws NamingException {
<del> ctx.close();
<del> }
<del>
<del> /**
<del> * Read the properties
<del> *
<del> * @throws IOException
<del> * if the properties cannot be found.
<del> */
<del> private void readProperties() throws IOException {
<del> // create and load default properties
<del> File propertiesFile = new File(getConfigurationDirectory(), "ldap.properties");
<del>
<del> if (defaultProperties == null) {
<del> defaultProperties = new Properties();
<del>
<del> FileInputStream in;
<del> in = new FileInputStream(propertiesFile);
<del> defaultProperties.load(in);
<del> in.close();
<del> }
<del> }
<add> }
<add>
<add> return authenticated;
<add> }
<add>
<add> /**
<add> * @see org.apache.lenya.cms.ac.Item#getName()
<add> */
<add> public String getName() {
<add> return ldapName;
<add> }
<add>
<add> /**
<add> * LDAP Users fetch their name information from the LDAP server, so we don't store it locally.
<add> * Since we only have read access we basically can't set the name, i.e. any request to change
<add> * the name is ignored.
<add> *
<add> * @param string is ignored
<add> */
<add> public void setName(String string) {
<add> // we do not have write access to LDAP, so we ignore
<add> // change request to the name.
<add> }
<add>
<add> /**
<add> * The LDAPUser doesn't store any passwords as they are handled by LDAP
<add> *
<add> * @param plainTextPassword is ignored
<add> */
<add> public void setPassword(String plainTextPassword) {
<add> setEncryptedPassword(null);
<add> }
<add>
<add> /**
<add> * The LDAPUser doesn't store any passwords as they are handled by LDAP
<add> *
<add> * @param encryptedPassword is ignored
<add> */
<add> protected void setEncryptedPassword(String encryptedPassword) {
<add> encryptedPassword = null;
<add> }
<add>
<add> /**
<add> * Connect to the LDAP server
<add> *
<add> * @param principal the principal string for the LDAP connection
<add> * @param credentials the credentials for the LDAP connection
<add> * @return a <code>LdapContext</code>
<add> * @throws NamingException if there are problems establishing the Ldap connection
<add> */
<add> private LdapContext bind(String principal, String credentials) throws NamingException {
<add>
<add> log.info("Binding principal: [" + principal + "]");
<add>
<add> Hashtable env = new Hashtable();
<add>
<add> System.setProperty("javax.net.ssl.trustStore", getConfigurationDirectory()
<add> .getAbsolutePath()
<add> + File.separator + defaultProperties.getProperty(KEY_STORE));
<add>
<add> env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory.class.getName());
<add> env.put(Context.PROVIDER_URL, defaultProperties.getProperty(PROVIDER_URL));
<add> env.put(Context.SECURITY_PROTOCOL, defaultProperties.getProperty(SECURITY_PROTOCOL));
<add> env.put(Context.SECURITY_AUTHENTICATION, defaultProperties
<add> .getProperty(SECURITY_AUTHENTICATION));
<add> env.put(Context.SECURITY_PRINCIPAL, principal);
<add> env.put(Context.SECURITY_CREDENTIALS, credentials);
<add>
<add> LdapContext ctx = new InitialLdapContext(env, null);
<add>
<add> log.info("Finished binding principal.");
<add>
<add> return ctx;
<add> }
<add>
<add> /**
<add> * Close the connection to the LDAP server
<add> *
<add> * @param ctx the context that was returned from the bind
<add> * @throws NamingException if there is a problem communicating to the LDAP server
<add> */
<add> private void close(Context ctx) throws NamingException {
<add> ctx.close();
<add> }
<add>
<add> /**
<add> * Read the properties
<add> *
<add> * @throws IOException if the properties cannot be found.
<add> */
<add> private void readProperties() throws IOException {
<add> // create and load default properties
<add> File propertiesFile = new File(getConfigurationDirectory(), "ldap.properties");
<add>
<add> if (defaultProperties == null) {
<add> defaultProperties = new Properties();
<add>
<add> FileInputStream in = null;
<add> try {
<add> in = new FileInputStream(propertiesFile);
<add> defaultProperties.load(in);
<add> } finally {
<add> if (in != null) {
<add> in.close();
<add> }
<add> }
<add> }
<add> }
<ide> } |
|
Java | mpl-2.0 | 7d3b539fffa74ddf5377b961466033247f8d18c6 | 0 | jentfoo/threadly,threadly/threadly | package org.threadly.util.debug;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.threadly.ThreadlyTester;
import org.threadly.concurrent.ConfigurableThreadFactory;
import org.threadly.concurrent.DoNothingRunnable;
import org.threadly.concurrent.PriorityScheduler;
import org.threadly.concurrent.SameThreadSubmitterExecutor;
import org.threadly.concurrent.SingleThreadScheduler;
import org.threadly.concurrent.StrictPriorityScheduler;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.concurrent.statistics.PrioritySchedulerStatisticTracker;
import org.threadly.test.concurrent.AsyncVerifier;
import org.threadly.test.concurrent.TestCondition;
import org.threadly.util.Clock;
import org.threadly.util.ExceptionHandler;
@SuppressWarnings("javadoc")
public class ProfilerTest extends ThreadlyTester {
private static final int POLL_INTERVAL = 1;
private static final int MIN_RESPONSE_LENGTH = 10;
protected Profiler profiler;
@Before
public void setup() {
profiler = new Profiler(POLL_INTERVAL);
}
@After
public void cleanup() {
profiler.stop();
profiler = null;
}
protected void profilingExecutor(@SuppressWarnings("unused") Executor executor) {
// ignored by default, overriden in other cases
}
protected void blockForProfilerSample() {
int startCount = profiler.getCollectedSampleQty();
new TestCondition(() -> profiler.getCollectedSampleQty() > startCount).blockTillTrue(1000 * 20);
}
@Test
public void constructorTest() {
int testPollInterval = Profiler.DEFAULT_POLL_INTERVAL_IN_MILLIS * 10;
Profiler p;
p = new Profiler();
assertNotNull(p.pStore.threadTraces);
assertEquals(0, p.pStore.threadTraces.size());
assertEquals(Profiler.DEFAULT_POLL_INTERVAL_IN_MILLIS, p.pStore.pollIntervalInMs);
assertNull(p.pStore.collectorThread.get());
assertNull(p.pStore.dumpingThread);
assertNotNull(p.startStopLock);
p = new Profiler(testPollInterval);
assertNotNull(p.pStore.threadTraces);
assertEquals(0, p.pStore.threadTraces.size());
assertEquals(testPollInterval, p.pStore.pollIntervalInMs);
assertNull(p.pStore.collectorThread.get());
assertNull(p.pStore.dumpingThread);
assertNotNull(p.startStopLock);
}
@Test
public void getProfileThreadsIteratorTest() {
Iterator<?> it = profiler.pStore.getProfileThreadsIterator();
assertNotNull(it);
assertTrue(it.hasNext());
assertNotNull(it.next());
}
@Test (expected = NoSuchElementException.class)
public void profileThreadsIteratorNextFail() {
Iterator<?> it = profiler.pStore.getProfileThreadsIterator();
while (it.hasNext()) {
assertNotNull(it.next());
}
it.next();
fail("Exception should have thrown");
}
@Test (expected = UnsupportedOperationException.class)
public void profileThreadsIteratorRemoveFail() {
Iterator<?> it = profiler.pStore.getProfileThreadsIterator();
it.next();
// not currently supported
it.remove();
}
@SuppressWarnings("unused")
@Test (expected = IllegalArgumentException.class)
public void constructorFail() {
new Profiler(-1);
}
@Test
public void isRunningTest() {
assertFalse(profiler.isRunning());
/* verification of isRunning after start happens in
* startWithoutExecutorTest and startWitExecutorTest
*/
}
@Test
public void startWithoutExecutorTest() {
profiler.start(null);
assertTrue(profiler.isRunning());
blockForProfilerSample();
}
@Test
public void startWithExecutorTest() {
PrioritySchedulerStatisticTracker e = new PrioritySchedulerStatisticTracker(1);
try {
assertEquals(0, e.getActiveTaskCount());
profiler.start(e);
assertTrue(profiler.isRunning());
assertEquals(1, e.getActiveTaskCount());
blockForProfilerSample();
} finally {
profiler.stop();
e.shutdownNow();
}
}
@Test
public void startWithSameThreadExecutorTest() throws InterruptedException, TimeoutException {
AsyncVerifier av = new AsyncVerifier();
PrioritySchedulerStatisticTracker s = new PrioritySchedulerStatisticTracker(1);
try {
s.schedule(() -> {
av.assertTrue(profiler.isRunning());
try {
blockForProfilerSample();
profiler.stop(); // this should unblock the test thread
} catch (Exception e) {
av.fail(e);
}
av.signalComplete();
}, 200);
profiler.start(SameThreadSubmitterExecutor.instance()); // will block while profile runs
av.waitForTest(); // test already completed, just check result
} finally {
s.shutdownNow();
}
}
@Test
public void startWithSameThreadExecutorAndTimeoutTest() {
profiler.start(SameThreadSubmitterExecutor.instance(), 200);
assertFalse(profiler.isRunning());
assertTrue(profiler.getCollectedSampleQty() > 0);
}
@Test
public void startWithTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
long start = Clock.accurateForwardProgressingMillis();
ListenableFuture<String> lf = profiler.start(DELAY_TIME);
String result = lf.get(DELAY_TIME + (10 * 1000), TimeUnit.MILLISECONDS);
long end = Clock.accurateForwardProgressingMillis();
// profiler should be stopped now
assertFalse(profiler.isRunning());
assertTrue(end - start >= DELAY_TIME);
assertNotNull(result);
}
@Test
public void startWitExecutorAndTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
StrictPriorityScheduler ps = new StrictPriorityScheduler(2);
try {
long start = Clock.accurateForwardProgressingMillis();
ListenableFuture<String> lf = profiler.start(ps, DELAY_TIME);
String result = lf.get(10 * 1000, TimeUnit.MILLISECONDS);
long end = Clock.accurateForwardProgressingMillis();
// profiler should be stopped now
assertFalse(profiler.isRunning());
assertTrue(end - start >= DELAY_TIME);
assertNotNull(result);
} finally {
ps.shutdownNow();
}
}
@Test
public void stopTwiceTest() {
ListenableFuture<String> lf = profiler.start(20_000);
profiler.stop();
assertTrue(lf.isDone());
lf = profiler.start(20_000);
profiler.stop();
assertTrue(lf.isDone());
}
@Test
public void getAndSetProfileIntervalTest() {
int TEST_VAL = 100;
profiler.setPollInterval(TEST_VAL);
assertEquals(TEST_VAL, profiler.getPollInterval());
}
@Test (expected = IllegalArgumentException.class)
public void setProfileIntervalFail() {
profiler.setPollInterval(-1);
}
@Test
public void resetTest() {
profiler.start();
// verify there are some samples
blockForProfilerSample();
final Thread runningThread = profiler.pStore.collectorThread.get();
profiler.stop();
// verify stopped
new TestCondition(() -> ! runningThread.isAlive()).blockTillTrue(1000 * 20);
profiler.reset();
assertEquals(0, profiler.pStore.threadTraces.size());
assertEquals(0, profiler.getCollectedSampleQty());
}
@Test
public void dumpStoppedStringTest() {
profiler.start();
blockForProfilerSample();
profiler.stop();
String resultStr = profiler.dump();
verifyDumpStr(resultStr);
}
@Test
public void dumpStoppedOutputStreamTest() {
profiler.start();
blockForProfilerSample();
profiler.stop();
ByteArrayOutputStream out = new ByteArrayOutputStream();
profiler.dump(out);
String resultStr = out.toString();
verifyDumpStr(resultStr);
}
@Test
public void dumpStringTest() {
profiler.start();
blockForProfilerSample();
String resultStr = profiler.dump();
verifyDumpStr(resultStr);
}
@Test
public void dumpOutputStreamTest() {
profiler.start();
blockForProfilerSample();
ByteArrayOutputStream out = new ByteArrayOutputStream();
profiler.dump(out);
String resultStr = out.toString();
verifyDumpStr(resultStr);
}
@Test
public void dumpStringOnlySummaryTest() {
profiler.start();
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.startsWith("Combined profile for all threads"));
}
protected static void verifyDumpStr(String resultStr) {
assertTrue(resultStr.length() > MIN_RESPONSE_LENGTH);
assertTrue(resultStr.contains(Profiler.FUNCTION_BY_COUNT_HEADER));
assertTrue(resultStr.contains(Profiler.FUNCTION_BY_NET_HEADER));
}
@Test
public void idlePrioritySchedulerTest() {
PriorityScheduler ps = new PriorityScheduler(2);
profilingExecutor(ps);
ps.prestartAllThreads();
profiler.start();
blockForProfilerSample();
new TestCondition(() -> {
String resultStr = profiler.dump(false);
return resultStr.contains("PriorityScheduler idle thread (stack 1)") &&
resultStr.contains("PriorityScheduler idle thread (stack 2)");
}).blockTillTrue();
}
@Test
public void idleSingleThreadSchedulerTest() throws InterruptedException, ExecutionException {
SingleThreadScheduler sts = new SingleThreadScheduler();
profilingExecutor(sts);
sts.prestartExecutionThread(true);
profiler.start();
blockForProfilerSample();
sts.schedule(DoNothingRunnable.instance(), 600_000);
sts.submit(DoNothingRunnable.instance()).get();
blockForProfilerSample();
new TestCondition(() -> {
String resultStr = profiler.dump(false);
return resultStr.contains("SingleThreadScheduler idle thread (stack 1)") &&
resultStr.contains("SingleThreadScheduler idle thread (stack 2)");
}).blockTillTrue();
}
@Test
public void idlePrioritySchedulerWithExceptionHandlerTest() {
PriorityScheduler ps = new PriorityScheduler(2, null, 100,
new ConfigurableThreadFactory(ExceptionHandler.PRINT_STACKTRACE_HANDLER));
profilingExecutor(ps);
ps.prestartAllThreads();
profiler.start();
blockForProfilerSample();
new TestCondition(() -> {
String resultStr = profiler.dump(false);
return resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 1)") &&
resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 2)");
}).blockTillTrue();
}
@Test
public void idleSingleThreadSchedulerWithExceptionHandlerTest() throws InterruptedException, ExecutionException {
SingleThreadScheduler sts = new SingleThreadScheduler(new ConfigurableThreadFactory(ExceptionHandler.PRINT_STACKTRACE_HANDLER));
profilingExecutor(sts);
sts.prestartExecutionThread(true);
profiler.start();
blockForProfilerSample();
sts.schedule(DoNothingRunnable.instance(), 600_000);
sts.submit(DoNothingRunnable.instance()).get();
blockForProfilerSample();
new TestCondition(() -> {
String resultStr = profiler.dump(false);
return resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 1)") &&
resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 2)");
}).blockTillTrue();
}
@Test
public void idleThreadPoolExecutorSynchronousQueueTest() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 100, TimeUnit.MILLISECONDS,
new SynchronousQueue<>());
profilingExecutor(tpe);
tpe.prestartCoreThread();
profiler.start();
blockForProfilerSample();
new TestCondition(() -> profiler.dump(false)
.contains("ThreadPoolExecutor SynchronousQueue idle thread"))
.blockTillTrue();
}
@Test
public void idleThreadPoolExecutorArrayBlockingQueueTest() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 100, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1));
profilingExecutor(tpe);
tpe.prestartCoreThread();
profiler.start();
blockForProfilerSample();
new TestCondition(() -> profiler.dump(false)
.contains("ThreadPoolExecutor ArrayBlockingQueue idle thread"))
.blockTillTrue();
}
@Test
public void idleThreadPoolExecutorLinkedBlockingQueueTest() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 100, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
profilingExecutor(tpe);
tpe.prestartCoreThread();
profiler.start();
blockForProfilerSample();
new TestCondition(() -> profiler.dump(false)
.contains("ThreadPoolExecutor LinkedBlockingQueue idle thread"))
.blockTillTrue();
}
@Test
public void idleScheduledThreadPoolExecutorTest() {
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1);
profilingExecutor(stpe);
stpe.prestartCoreThread();
profiler.start();
blockForProfilerSample();
new TestCondition(() -> profiler.dump(false)
.contains("ScheduledThreadPoolExecutor idle thread"))
.blockTillTrue();
}
}
| src/test/java/org/threadly/util/debug/ProfilerTest.java | package org.threadly.util.debug;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.threadly.ThreadlyTester;
import org.threadly.concurrent.ConfigurableThreadFactory;
import org.threadly.concurrent.DoNothingRunnable;
import org.threadly.concurrent.PriorityScheduler;
import org.threadly.concurrent.SameThreadSubmitterExecutor;
import org.threadly.concurrent.SingleThreadScheduler;
import org.threadly.concurrent.StrictPriorityScheduler;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.concurrent.statistics.PrioritySchedulerStatisticTracker;
import org.threadly.test.concurrent.AsyncVerifier;
import org.threadly.test.concurrent.TestCondition;
import org.threadly.test.concurrent.TestUtils;
import org.threadly.util.Clock;
import org.threadly.util.ExceptionHandler;
@SuppressWarnings("javadoc")
public class ProfilerTest extends ThreadlyTester {
private static final int POLL_INTERVAL = 1;
private static final int MIN_RESPONSE_LENGTH = 10;
protected Profiler profiler;
@Before
public void setup() {
profiler = new Profiler(POLL_INTERVAL);
}
@After
public void cleanup() {
profiler.stop();
profiler = null;
}
protected void profilingExecutor(@SuppressWarnings("unused") Executor executor) {
// ignored by default, overriden in other cases
}
protected void blockForProfilerSample() {
int startCount = profiler.getCollectedSampleQty();
new TestCondition(() -> profiler.getCollectedSampleQty() > startCount).blockTillTrue(1000 * 20);
}
@Test
public void constructorTest() {
int testPollInterval = Profiler.DEFAULT_POLL_INTERVAL_IN_MILLIS * 10;
Profiler p;
p = new Profiler();
assertNotNull(p.pStore.threadTraces);
assertEquals(0, p.pStore.threadTraces.size());
assertEquals(Profiler.DEFAULT_POLL_INTERVAL_IN_MILLIS, p.pStore.pollIntervalInMs);
assertNull(p.pStore.collectorThread.get());
assertNull(p.pStore.dumpingThread);
assertNotNull(p.startStopLock);
p = new Profiler(testPollInterval);
assertNotNull(p.pStore.threadTraces);
assertEquals(0, p.pStore.threadTraces.size());
assertEquals(testPollInterval, p.pStore.pollIntervalInMs);
assertNull(p.pStore.collectorThread.get());
assertNull(p.pStore.dumpingThread);
assertNotNull(p.startStopLock);
}
@Test
public void getProfileThreadsIteratorTest() {
Iterator<?> it = profiler.pStore.getProfileThreadsIterator();
assertNotNull(it);
assertTrue(it.hasNext());
assertNotNull(it.next());
}
@Test (expected = NoSuchElementException.class)
public void profileThreadsIteratorNextFail() {
Iterator<?> it = profiler.pStore.getProfileThreadsIterator();
while (it.hasNext()) {
assertNotNull(it.next());
}
it.next();
fail("Exception should have thrown");
}
@Test (expected = UnsupportedOperationException.class)
public void profileThreadsIteratorRemoveFail() {
Iterator<?> it = profiler.pStore.getProfileThreadsIterator();
it.next();
// not currently supported
it.remove();
}
@SuppressWarnings("unused")
@Test (expected = IllegalArgumentException.class)
public void constructorFail() {
new Profiler(-1);
}
@Test
public void isRunningTest() {
assertFalse(profiler.isRunning());
/* verification of isRunning after start happens in
* startWithoutExecutorTest and startWitExecutorTest
*/
}
@Test
public void startWithoutExecutorTest() {
profiler.start(null);
assertTrue(profiler.isRunning());
blockForProfilerSample();
}
@Test
public void startWithExecutorTest() {
PrioritySchedulerStatisticTracker e = new PrioritySchedulerStatisticTracker(1);
try {
assertEquals(0, e.getActiveTaskCount());
profiler.start(e);
assertTrue(profiler.isRunning());
assertEquals(1, e.getActiveTaskCount());
blockForProfilerSample();
} finally {
profiler.stop();
e.shutdownNow();
}
}
@Test
public void startWithSameThreadExecutorTest() throws InterruptedException, TimeoutException {
AsyncVerifier av = new AsyncVerifier();
PrioritySchedulerStatisticTracker s = new PrioritySchedulerStatisticTracker(1);
try {
s.schedule(() -> {
av.assertTrue(profiler.isRunning());
try {
blockForProfilerSample();
profiler.stop(); // this should unblock the test thread
} catch (Exception e) {
av.fail(e);
}
av.signalComplete();
}, 200);
profiler.start(SameThreadSubmitterExecutor.instance()); // will block while profile runs
av.waitForTest(); // test already completed, just check result
} finally {
s.shutdownNow();
}
}
@Test
public void startWithSameThreadExecutorAndTimeoutTest() {
profiler.start(SameThreadSubmitterExecutor.instance(), 200);
assertFalse(profiler.isRunning());
assertTrue(profiler.getCollectedSampleQty() > 0);
}
@Test
public void startWithTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
long start = Clock.accurateForwardProgressingMillis();
ListenableFuture<String> lf = profiler.start(DELAY_TIME);
String result = lf.get(DELAY_TIME + (10 * 1000), TimeUnit.MILLISECONDS);
long end = Clock.accurateForwardProgressingMillis();
// profiler should be stopped now
assertFalse(profiler.isRunning());
assertTrue(end - start >= DELAY_TIME);
assertNotNull(result);
}
@Test
public void startWitExecutorAndTimeoutTest() throws InterruptedException, ExecutionException, TimeoutException {
StrictPriorityScheduler ps = new StrictPriorityScheduler(2);
try {
long start = Clock.accurateForwardProgressingMillis();
ListenableFuture<String> lf = profiler.start(ps, DELAY_TIME);
String result = lf.get(10 * 1000, TimeUnit.MILLISECONDS);
long end = Clock.accurateForwardProgressingMillis();
// profiler should be stopped now
assertFalse(profiler.isRunning());
assertTrue(end - start >= DELAY_TIME);
assertNotNull(result);
} finally {
ps.shutdownNow();
}
}
@Test
public void stopTwiceTest() {
ListenableFuture<String> lf = profiler.start(20_000);
profiler.stop();
assertTrue(lf.isDone());
lf = profiler.start(20_000);
profiler.stop();
assertTrue(lf.isDone());
}
@Test
public void getAndSetProfileIntervalTest() {
int TEST_VAL = 100;
profiler.setPollInterval(TEST_VAL);
assertEquals(TEST_VAL, profiler.getPollInterval());
}
@Test (expected = IllegalArgumentException.class)
public void setProfileIntervalFail() {
profiler.setPollInterval(-1);
}
@Test
public void resetTest() {
profiler.start();
// verify there are some samples
blockForProfilerSample();
final Thread runningThread = profiler.pStore.collectorThread.get();
profiler.stop();
// verify stopped
new TestCondition(() -> ! runningThread.isAlive()).blockTillTrue(1000 * 20);
profiler.reset();
assertEquals(0, profiler.pStore.threadTraces.size());
assertEquals(0, profiler.getCollectedSampleQty());
}
@Test
public void dumpStoppedStringTest() {
profiler.start();
blockForProfilerSample();
profiler.stop();
String resultStr = profiler.dump();
verifyDumpStr(resultStr);
}
@Test
public void dumpStoppedOutputStreamTest() {
profiler.start();
blockForProfilerSample();
profiler.stop();
ByteArrayOutputStream out = new ByteArrayOutputStream();
profiler.dump(out);
String resultStr = out.toString();
verifyDumpStr(resultStr);
}
@Test
public void dumpStringTest() {
profiler.start();
blockForProfilerSample();
String resultStr = profiler.dump();
verifyDumpStr(resultStr);
}
@Test
public void dumpOutputStreamTest() {
profiler.start();
blockForProfilerSample();
ByteArrayOutputStream out = new ByteArrayOutputStream();
profiler.dump(out);
String resultStr = out.toString();
verifyDumpStr(resultStr);
}
@Test
public void dumpStringOnlySummaryTest() {
profiler.start();
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.startsWith("Combined profile for all threads"));
}
protected static void verifyDumpStr(String resultStr) {
assertTrue(resultStr.length() > MIN_RESPONSE_LENGTH);
assertTrue(resultStr.contains(Profiler.FUNCTION_BY_COUNT_HEADER));
assertTrue(resultStr.contains(Profiler.FUNCTION_BY_NET_HEADER));
}
@Test
public void idlePrioritySchedulerTest() {
PriorityScheduler ps = new PriorityScheduler(2);
profilingExecutor(ps);
ps.prestartAllThreads();
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("PriorityScheduler idle thread (stack 1)"));
assertTrue(resultStr.contains("PriorityScheduler idle thread (stack 2)"));
}
@Test
public void idleSingleThreadSchedulerTest() throws InterruptedException, ExecutionException {
SingleThreadScheduler sts = new SingleThreadScheduler();
profilingExecutor(sts);
sts.prestartExecutionThread(true);
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
sts.schedule(DoNothingRunnable.instance(), 600_000);
sts.submit(DoNothingRunnable.instance()).get();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("SingleThreadScheduler idle thread (stack 1)"));
assertTrue(resultStr.contains("SingleThreadScheduler idle thread (stack 2)"));
}
@Test
public void idlePrioritySchedulerWithExceptionHandlerTest() {
PriorityScheduler ps = new PriorityScheduler(2, null, 100,
new ConfigurableThreadFactory(ExceptionHandler.PRINT_STACKTRACE_HANDLER));
profilingExecutor(ps);
ps.prestartAllThreads();
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 1)"));
assertTrue(resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 2)"));
}
@Test
public void idleSingleThreadSchedulerWithExceptionHandlerTest() throws InterruptedException, ExecutionException {
SingleThreadScheduler sts = new SingleThreadScheduler(new ConfigurableThreadFactory(ExceptionHandler.PRINT_STACKTRACE_HANDLER));
profilingExecutor(sts);
sts.prestartExecutionThread(true);
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
sts.schedule(DoNothingRunnable.instance(), 600_000);
sts.submit(DoNothingRunnable.instance()).get();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 1)"));
assertTrue(resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 2)"));
}
@Test
public void idleThreadPoolExecutorSynchronousQueueTest() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 100, TimeUnit.MILLISECONDS,
new SynchronousQueue<>());
profilingExecutor(tpe);
tpe.prestartCoreThread();
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("ThreadPoolExecutor SynchronousQueue idle thread"));
}
@Test
public void idleThreadPoolExecutorArrayBlockingQueueTest() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 100, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1));
profilingExecutor(tpe);
tpe.prestartCoreThread();
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("ThreadPoolExecutor ArrayBlockingQueue idle thread"));
}
@Test
public void idleThreadPoolExecutorLinkedBlockingQueueTest() {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 100, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
profilingExecutor(tpe);
tpe.prestartCoreThread();
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("ThreadPoolExecutor LinkedBlockingQueue idle thread"));
}
@Test
public void idleScheduledThreadPoolExecutorTest() {
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1);
profilingExecutor(stpe);
stpe.prestartCoreThread();
profiler.start();
TestUtils.sleep(10);
blockForProfilerSample();
String resultStr = profiler.dump(false);
assertTrue(resultStr.contains("ScheduledThreadPoolExecutor idle thread"));
}
}
| ProfilerTest: Remove sleep's in new tests and instead use TestCondition
These seemed to be slightly flakey, this should correct that.
| src/test/java/org/threadly/util/debug/ProfilerTest.java | ProfilerTest: Remove sleep's in new tests and instead use TestCondition | <ide><path>rc/test/java/org/threadly/util/debug/ProfilerTest.java
<ide> import org.threadly.concurrent.statistics.PrioritySchedulerStatisticTracker;
<ide> import org.threadly.test.concurrent.AsyncVerifier;
<ide> import org.threadly.test.concurrent.TestCondition;
<del>import org.threadly.test.concurrent.TestUtils;
<ide> import org.threadly.util.Clock;
<ide> import org.threadly.util.ExceptionHandler;
<ide>
<ide> profilingExecutor(ps);
<ide> ps.prestartAllThreads();
<ide> profiler.start();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("PriorityScheduler idle thread (stack 1)"));
<del> assertTrue(resultStr.contains("PriorityScheduler idle thread (stack 2)"));
<add> blockForProfilerSample();
<add>
<add> new TestCondition(() -> {
<add> String resultStr = profiler.dump(false);
<add>
<add> return resultStr.contains("PriorityScheduler idle thread (stack 1)") &&
<add> resultStr.contains("PriorityScheduler idle thread (stack 2)");
<add> }).blockTillTrue();
<ide> }
<ide>
<ide> @Test
<ide> profilingExecutor(sts);
<ide> sts.prestartExecutionThread(true);
<ide> profiler.start();
<del> TestUtils.sleep(10);
<ide> blockForProfilerSample();
<ide>
<ide> sts.schedule(DoNothingRunnable.instance(), 600_000);
<ide> sts.submit(DoNothingRunnable.instance()).get();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("SingleThreadScheduler idle thread (stack 1)"));
<del> assertTrue(resultStr.contains("SingleThreadScheduler idle thread (stack 2)"));
<add> blockForProfilerSample();
<add>
<add>
<add> new TestCondition(() -> {
<add> String resultStr = profiler.dump(false);
<add>
<add> return resultStr.contains("SingleThreadScheduler idle thread (stack 1)") &&
<add> resultStr.contains("SingleThreadScheduler idle thread (stack 2)");
<add> }).blockTillTrue();
<ide> }
<ide>
<ide> @Test
<ide> profilingExecutor(ps);
<ide> ps.prestartAllThreads();
<ide> profiler.start();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 1)"));
<del> assertTrue(resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 2)"));
<add> blockForProfilerSample();
<add>
<add> new TestCondition(() -> {
<add> String resultStr = profiler.dump(false);
<add>
<add> return resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 1)") &&
<add> resultStr.contains("PriorityScheduler with ExceptionHandler idle thread (stack 2)");
<add> }).blockTillTrue();
<ide> }
<ide>
<ide> @Test
<ide> profilingExecutor(sts);
<ide> sts.prestartExecutionThread(true);
<ide> profiler.start();
<del> TestUtils.sleep(10);
<ide> blockForProfilerSample();
<ide>
<ide> sts.schedule(DoNothingRunnable.instance(), 600_000);
<ide> sts.submit(DoNothingRunnable.instance()).get();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 1)"));
<del> assertTrue(resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 2)"));
<add> blockForProfilerSample();
<add>
<add> new TestCondition(() -> {
<add> String resultStr = profiler.dump(false);
<add>
<add> return resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 1)") &&
<add> resultStr.contains("SingleThreadScheduler with ExceptionHandler idle thread (stack 2)");
<add> }).blockTillTrue();
<ide> }
<ide>
<ide> @Test
<ide> profilingExecutor(tpe);
<ide> tpe.prestartCoreThread();
<ide> profiler.start();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("ThreadPoolExecutor SynchronousQueue idle thread"));
<add> blockForProfilerSample();
<add>
<add> new TestCondition(() -> profiler.dump(false)
<add> .contains("ThreadPoolExecutor SynchronousQueue idle thread"))
<add> .blockTillTrue();
<ide> }
<ide>
<ide> @Test
<ide> profilingExecutor(tpe);
<ide> tpe.prestartCoreThread();
<ide> profiler.start();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("ThreadPoolExecutor ArrayBlockingQueue idle thread"));
<add> blockForProfilerSample();
<add>
<add> new TestCondition(() -> profiler.dump(false)
<add> .contains("ThreadPoolExecutor ArrayBlockingQueue idle thread"))
<add> .blockTillTrue();
<ide> }
<ide>
<ide> @Test
<ide> profilingExecutor(tpe);
<ide> tpe.prestartCoreThread();
<ide> profiler.start();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("ThreadPoolExecutor LinkedBlockingQueue idle thread"));
<add> blockForProfilerSample();
<add>
<add> new TestCondition(() -> profiler.dump(false)
<add> .contains("ThreadPoolExecutor LinkedBlockingQueue idle thread"))
<add> .blockTillTrue();
<ide> }
<ide>
<ide> @Test
<ide> profilingExecutor(stpe);
<ide> stpe.prestartCoreThread();
<ide> profiler.start();
<del> TestUtils.sleep(10);
<del> blockForProfilerSample();
<del>
<del> String resultStr = profiler.dump(false);
<del>
<del> assertTrue(resultStr.contains("ScheduledThreadPoolExecutor idle thread"));
<add> blockForProfilerSample();
<add>
<add> new TestCondition(() -> profiler.dump(false)
<add> .contains("ScheduledThreadPoolExecutor idle thread"))
<add> .blockTillTrue();
<ide> }
<ide> } |
|
JavaScript | agpl-3.0 | da350ce24b1e6c87c79aa4908d4cd46bfa9e40d8 | 0 | Miserlou/jsntp | /*
Schedule things to happen at certain times
By Thomas Levine, standing on the substantial shoulders
of his group at the HTML5 Hackathon at Google Kirkland
----
Copyright 2011, Thomas Levine
Distributed under the terms of the GNU Affero General Public License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
at = {
//The queue
'atq':{}
, 'DEFAULTS':{
'PRECISION':8
}
, 'dateToString':function(date) {
return date.getTime()+'';
}
//Low-level interface for saving the function in the queue
, '_set':function(func,time,signedprecision){
time.setTime(time.getTime()+signedprecision);
var d = this.dateToString(time);
this.atq[d] = func;
}
//User interface for saving the function in the queue
, 'at':function (func, time, options) {
//If a timestamp is given instead of a Date
if (!time.getSeconds) {
var tmp = new Date();
tmp.setTime(time);
time = tmp;
}
if (typeof(options.precision)==='undefined'){
//How far away from the exact time is acceptable?
//Use a number in milliseconds
options.precision=this.DEFAULTS.PRECISION;
}
if (typeof(options.log)==='undefined'){
options.log=false;
}
//Add to the queue
/* Daemon
var p=0-Math.abs(precision);
var p_end=Math.abs(precision);
for (p;p<=precision;p++){
this._set(func,time,p);
}
*/
//No daemon
setTimeout(function(){
var wrongness=time.getTime()-new Date().getTime());
if (options.log){
if (wrongness>0) {
console.log('Running '+wrongness+' milliseconds early');
} else if (wrongness<0) {
console.log('Running '+(-1*wrongness)+' milliseconds late');
} else {
console.log('Running perfectly on time');
}
}
func();
},time.getTime()-new Date().getTime());
}
, 'atd': function(thisAT) { //Daemon
//thisAT just sends this to atd when it's run with setTimeout
if (typeof(thisAT)==='undefined'){
var thisAT=this;
}
var date = new Date();
var d = thisAT.dateToString(date);
var alarm = thisAT.atq[d];
if (alarm) {
alarm();
}
// Run again
setTimeout(function(){
thisAT.atd(thisAT);
},1);
}
}
//at.atd();
| static/at.js | /*
Schedule things to happen at certain times
By Thomas Levine, standing on the substantial shoulders
of his group at the HTML5 Hackathon at Google Kirkland
----
Copyright 2011, Thomas Levine
Distributed under the terms of the GNU Affero General Public License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
at = {
//The queue
'atq':{}
, 'DEFAULTS':{
'PRECISION':8
}
, 'dateToString':function(date) {
return date.getTime()+'';
}
//Low-level interface for saving the function in the queue
, '_set':function(func,time,signedprecision){
time.setTime(time.getTime()+signedprecision);
var d = this.dateToString(time);
this.atq[d] = func;
}
//User interface for saving the function in the queue
, 'at':function (func, time, options) {
//If a timestamp is given instead of a Date
if (!time.getSeconds) {
var tmp = new Date();
tmp.setTime(time);
time = tmp;
}
if (typeof(options.precision)==='undefined'){
//How far away from the exact time is acceptable?
//Use a number in milliseconds
var options.precision=this.DEFAULTS.PRECISION;
}
if (typeof(options.log)==='undefined'){
var options.log=false;
}
//Add to the queue
/* Daemon
var p=0-Math.abs(precision);
var p_end=Math.abs(precision);
for (p;p<=precision;p++){
this._set(func,time,p);
}
*/
//No daemon
setTimeout(function(){
var wrongness=time.getTime()-new Date().getTime());
if (options.log){
if (wrongness>0) {
console.log('Running '+wrongness+' milliseconds early');
} else if (wrongness<0) {
console.log('Running '+(-1*wrongness)+' milliseconds late');
} else {
console.log('Running perfectly on time');
}
}
func();
},time.getTime()-new Date().getTime());
}
, 'atd': function(thisAT) { //Daemon
//thisAT just sends this to atd when it's run with setTimeout
if (typeof(thisAT)==='undefined'){
var thisAT=this;
}
var date = new Date();
var d = thisAT.dateToString(date);
var alarm = thisAT.atq[d];
if (alarm) {
alarm();
}
// Run again
setTimeout(function(){
thisAT.atd(thisAT);
},1);
}
}
//at.atd();
| remove vars
| static/at.js | remove vars | <ide><path>tatic/at.js
<ide> if (typeof(options.precision)==='undefined'){
<ide> //How far away from the exact time is acceptable?
<ide> //Use a number in milliseconds
<del> var options.precision=this.DEFAULTS.PRECISION;
<add> options.precision=this.DEFAULTS.PRECISION;
<ide> }
<ide> if (typeof(options.log)==='undefined'){
<del> var options.log=false;
<add> options.log=false;
<ide> }
<ide>
<ide> //Add to the queue |
|
Java | apache-2.0 | e9556bbbf0c17152e12b1214e18415ef7efd2a3e | 0 | hansjoachim/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,stevespringett/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,colezlaw/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,stefanneuhaus/DependencyCheck,stevespringett/DependencyCheck,stevespringett/DependencyCheck,hansjoachim/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,stevespringett/DependencyCheck,stevespringett/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,colezlaw/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
/**
* @author Jeremy Long
*/
public class JarAnalyzerTest extends BaseTest {
// private static final Logger LOGGER = LoggerFactory.getLogger(JarAnalyzerTest.class);
/**
* Test of inspect method, of class JarAnalyzer.
*
* @throws Exception is thrown when an exception occurs.
*/
@Test
public void testAnalyze() throws Exception {
//File file = new File(this.getClass().getClassLoader().getResource("struts2-core-2.1.2.jar").getPath());
File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar");
Dependency result = new Dependency(file);
JarAnalyzer instance = new JarAnalyzer();
instance.initializeFileTypeAnalyzer();
instance.analyze(result, null);
assertTrue(result.getVendorEvidence().toString().toLowerCase().contains("apache"));
assertTrue(result.getVendorEvidence().getWeighting().contains("apache"));
file = BaseTest.getResourceAsFile(this, "dwr.jar");
result = new Dependency(file);
instance.analyze(result, null);
boolean found = false;
for (Evidence e : result.getVendorEvidence()) {
if (e.getName().equals("url")) {
assertEquals("Project url was not as expected in dwr.jar", e.getValue(), "http://getahead.ltd.uk/dwr");
found = true;
break;
}
}
assertTrue("Project url was not found in dwr.jar", found);
//file = new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath());
file = BaseTest.getResourceAsFile(this, "org.mortbay.jetty.jar");
result = new Dependency(file);
instance.analyze(result, null);
found = false;
for (Evidence e : result.getProductEvidence()) {
if (e.getName().equalsIgnoreCase("package-title")
&& e.getValue().equalsIgnoreCase("org.mortbay.http")) {
found = true;
break;
}
}
assertTrue("package-title of org.mortbay.http not found in org.mortbay.jetty.jar", found);
found = false;
for (Evidence e : result.getVendorEvidence()) {
if (e.getName().equalsIgnoreCase("implementation-url")
&& e.getValue().equalsIgnoreCase("http://jetty.mortbay.org")) {
found = true;
break;
}
}
assertTrue("implementation-url of http://jetty.mortbay.org not found in org.mortbay.jetty.jar", found);
found = false;
for (Evidence e : result.getVersionEvidence()) {
if (e.getName().equalsIgnoreCase("Implementation-Version")
&& e.getValue().equalsIgnoreCase("4.2.27")) {
found = true;
break;
}
}
assertTrue("implementation-version of 4.2.27 not found in org.mortbay.jetty.jar", found);
//file = new File(this.getClass().getClassLoader().getResource("org.mortbay.jmx.jar").getPath());
file = BaseTest.getResourceAsFile(this, "org.mortbay.jmx.jar");
result = new Dependency(file);
instance.analyze(result, null);
assertEquals("org.mortbar.jmx.jar has version evidence?", result.getVersionEvidence().size(), 0);
}
/**
* Test of getSupportedExtensions method, of class JarAnalyzer.
*/
@Test
public void testAcceptSupportedExtensions() throws Exception {
JarAnalyzer instance = new JarAnalyzer();
instance.initialize();
instance.setEnabled(true);
String[] files = {"test.jar", "test.war"};
for (String name : files) {
assertTrue(name, instance.accept(new File(name)));
}
}
/**
* Test of getName method, of class JarAnalyzer.
*/
@Test
public void testGetName() {
JarAnalyzer instance = new JarAnalyzer();
String expResult = "Jar Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
}
@Test
public void testParseManifest() throws Exception {
File file = BaseTest.getResourceAsFile(this, "xalan-2.7.0.jar");
Dependency result = new Dependency(file);
JarAnalyzer instance = new JarAnalyzer();
List<JarAnalyzer.ClassNameInformation> cni = new ArrayList<JarAnalyzer.ClassNameInformation>();
instance.parseManifest(result, cni);
assertTrue(result.getVersionEvidence().getEvidence("manifest: org/apache/xalan/").size() > 0);
}
}
| dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
/**
* @author Jeremy Long
*/
public class JarAnalyzerTest extends BaseTest {
// private static final Logger LOGGER = LoggerFactory.getLogger(JarAnalyzerTest.class);
/**
* Test of inspect method, of class JarAnalyzer.
*
* @throws Exception is thrown when an exception occurs.
*/
@Test
public void testAnalyze() throws Exception {
//File file = new File(this.getClass().getClassLoader().getResource("struts2-core-2.1.2.jar").getPath());
File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar");
Dependency result = new Dependency(file);
JarAnalyzer instance = new JarAnalyzer();
instance.analyze(result, null);
assertTrue(result.getVendorEvidence().toString().toLowerCase().contains("apache"));
assertTrue(result.getVendorEvidence().getWeighting().contains("apache"));
file = BaseTest.getResourceAsFile(this, "dwr.jar");
result = new Dependency(file);
instance.analyze(result, null);
boolean found = false;
for (Evidence e : result.getVendorEvidence()) {
if (e.getName().equals("url")) {
assertEquals("Project url was not as expected in dwr.jar", e.getValue(), "http://getahead.ltd.uk/dwr");
found = true;
break;
}
}
assertTrue("Project url was not found in dwr.jar", found);
//file = new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath());
file = BaseTest.getResourceAsFile(this, "org.mortbay.jetty.jar");
result = new Dependency(file);
instance.analyze(result, null);
found = false;
for (Evidence e : result.getProductEvidence()) {
if (e.getName().equalsIgnoreCase("package-title")
&& e.getValue().equalsIgnoreCase("org.mortbay.http")) {
found = true;
break;
}
}
assertTrue("package-title of org.mortbay.http not found in org.mortbay.jetty.jar", found);
found = false;
for (Evidence e : result.getVendorEvidence()) {
if (e.getName().equalsIgnoreCase("implementation-url")
&& e.getValue().equalsIgnoreCase("http://jetty.mortbay.org")) {
found = true;
break;
}
}
assertTrue("implementation-url of http://jetty.mortbay.org not found in org.mortbay.jetty.jar", found);
found = false;
for (Evidence e : result.getVersionEvidence()) {
if (e.getName().equalsIgnoreCase("Implementation-Version")
&& e.getValue().equalsIgnoreCase("4.2.27")) {
found = true;
break;
}
}
assertTrue("implementation-version of 4.2.27 not found in org.mortbay.jetty.jar", found);
//file = new File(this.getClass().getClassLoader().getResource("org.mortbay.jmx.jar").getPath());
file = BaseTest.getResourceAsFile(this, "org.mortbay.jmx.jar");
result = new Dependency(file);
instance.analyze(result, null);
assertEquals("org.mortbar.jmx.jar has version evidence?", result.getVersionEvidence().size(), 0);
}
/**
* Test of getSupportedExtensions method, of class JarAnalyzer.
*/
@Test
public void testAcceptSupportedExtensions() throws Exception {
JarAnalyzer instance = new JarAnalyzer();
instance.initialize();
instance.setEnabled(true);
String[] files = {"test.jar", "test.war"};
for (String name : files) {
assertTrue(name, instance.accept(new File(name)));
}
}
/**
* Test of getName method, of class JarAnalyzer.
*/
@Test
public void testGetName() {
JarAnalyzer instance = new JarAnalyzer();
String expResult = "Jar Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
}
@Test
public void testParseManifest() throws Exception {
File file = BaseTest.getResourceAsFile(this, "xalan-2.7.0.jar");
Dependency result = new Dependency(file);
JarAnalyzer instance = new JarAnalyzer();
List<JarAnalyzer.ClassNameInformation> cni = new ArrayList<JarAnalyzer.ClassNameInformation>();
instance.parseManifest(result, cni);
assertTrue(result.getVersionEvidence().getEvidence("manifest: org/apache/xalan/").size() > 0);
}
}
| added analyzer initialization so that temp files get put in the correct location
| dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java | added analyzer initialization so that temp files get put in the correct location | <ide><path>ependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java
<ide> File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar");
<ide> Dependency result = new Dependency(file);
<ide> JarAnalyzer instance = new JarAnalyzer();
<add> instance.initializeFileTypeAnalyzer();
<ide> instance.analyze(result, null);
<ide> assertTrue(result.getVendorEvidence().toString().toLowerCase().contains("apache"));
<ide> assertTrue(result.getVendorEvidence().getWeighting().contains("apache")); |
|
Java | agpl-3.0 | 82cb849996dd312f13675ddad5e577133627a992 | 0 | danielpgross/phenotips,veronikaslc/phenotips,itaiGershtansky/phenotips,phenotips/phenotips,danielpgross/phenotips,alexhenrie/phenotips,tmarathe/phenotips,phenotips/phenotips,mjshepherd/phenotips,JKereliuk/phenotips,teyden/phenotips,tmarathe/phenotips,mjshepherd/phenotips,teyden/phenotips,DeanWay/phenotips,teyden/phenotips,alexhenrie/phenotips,mjshepherd/phenotips,tmarathe/phenotips,danielpgross/phenotips,phenotips/phenotips,veronikaslc/phenotips,alexhenrie/phenotips,JKereliuk/phenotips,JKereliuk/phenotips,itaiGershtansky/phenotips,DeanWay/phenotips,veronikaslc/phenotips,teyden/phenotips,teyden/phenotips,phenotips/phenotips,itaiGershtansky/phenotips,phenotips/phenotips,DeanWay/phenotips | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.phenotips.data.internal;
import org.phenotips.components.ComponentManagerRegistry;
import org.phenotips.data.OntologyProperty;
import org.phenotips.ontology.OntologyManager;
import org.phenotips.ontology.OntologyTerm;
import org.xwiki.component.manager.ComponentLookupException;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import net.sf.json.JSONObject;
/**
* Implementation of patient data based on the XWiki data model, where disease data is represented by properties in
* objects of type {@code PhenoTips.PatientClass}.
*
* @version $Id$
* @since 1.0M8
*/
public abstract class AbstractPhenoTipsOntologyProperty implements OntologyProperty, Comparable<OntologyProperty>
{
/** Used for reading and writing properties to JSON. */
protected static final String ID_JSON_KEY_NAME = "id";
protected static final String NAME_JSON_KEY_NAME = "label";
/** Pattern used for identifying ontology terms from free text terms. */
private static final Pattern ONTOLOGY_TERM_PATTERN = Pattern.compile("\\w++:\\w++");
/** @see #getId() */
protected final String id;
/** @see #getName() */
protected String name;
/**
* Simple constructor providing the {@link #id term identifier}.
*
* @param id the ontology term identifier
*/
protected AbstractPhenoTipsOntologyProperty(String id)
{
if (ONTOLOGY_TERM_PATTERN.matcher(id).matches()) {
this.id = id;
this.name = null;
} else {
this.id = "";
this.name = id;
}
}
/**
* Constructor for initializing from a JSON Object.
*
* @param json JSON object describing this property
*/
protected AbstractPhenoTipsOntologyProperty(JSONObject json)
{
this.id = json.has(ID_JSON_KEY_NAME) ? json.getString(ID_JSON_KEY_NAME) : "";
this.name = json.has(NAME_JSON_KEY_NAME) ? json.getString(NAME_JSON_KEY_NAME) : null;
}
@Override
public String getId()
{
return this.id;
}
@Override
public String getName()
{
if (this.name != null) {
return this.name;
}
try {
OntologyManager om =
ComponentManagerRegistry.getContextComponentManager().getInstance(OntologyManager.class);
OntologyTerm term = om.resolveTerm(this.id);
if (term != null && StringUtils.isNotEmpty(term.getName())) {
this.name = term.getName();
return this.name;
}
} catch (ComponentLookupException ex) {
// Shouldn't happen
}
return this.id;
}
@Override
public String toString()
{
return toJSON().toString(2);
}
@Override
public JSONObject toJSON()
{
JSONObject result = new JSONObject();
if (StringUtils.isNotEmpty(this.getId())) {
result.element(ID_JSON_KEY_NAME, getId());
}
if (StringUtils.isNotEmpty(this.getName())) {
result.element(NAME_JSON_KEY_NAME, getName());
}
return result;
}
@Override
public int compareTo(OntologyProperty o)
{
if (o == null) {
// Nulls at the end
return -1;
}
return getName().compareTo(o.getName());
}
}
| components/patient-data/impl/src/main/java/org/phenotips/data/internal/AbstractPhenoTipsOntologyProperty.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.phenotips.data.internal;
import org.phenotips.components.ComponentManagerRegistry;
import org.phenotips.data.OntologyProperty;
import org.phenotips.ontology.OntologyManager;
import org.phenotips.ontology.OntologyTerm;
import org.xwiki.component.manager.ComponentLookupException;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import net.sf.json.JSONObject;
/**
* Implementation of patient data based on the XWiki data model, where disease data is represented by properties in
* objects of type {@code PhenoTips.PatientClass}.
*
* @version $Id$
* @since 1.0M8
*/
public abstract class AbstractPhenoTipsOntologyProperty implements OntologyProperty, Comparable<OntologyProperty>
{
/** Used for reading and writing properties to JSON. */
protected static final String ID_JSON_KEY_NAME = "id";
protected static final String NAME_JSON_KEY_NAME = "label";
/** Pattern used for identifying ontology terms from free text terms. */
private static final Pattern ONTOLOGY_TERM_PATTERN = Pattern.compile("\\w++:\\w++");
/** @see #getId() */
protected final String id;
/** @see #getName() */
protected String name;
/**
* Simple constructor providing the {@link #id term identifier}.
*
* @param id the ontology term identifier
*/
protected AbstractPhenoTipsOntologyProperty(String id)
{
if (ONTOLOGY_TERM_PATTERN.matcher(id).matches()) {
this.id = id;
this.name = null;
} else {
this.id = "";
this.name = id;
}
}
/**
* Constructor for initializing from a JSON Object.
*
* @param json JSON object describing this property
*/
protected AbstractPhenoTipsOntologyProperty(JSONObject json)
{
this.id = json.getString(ID_JSON_KEY_NAME);
this.name = json.getString(NAME_JSON_KEY_NAME);
}
@Override
public String getId()
{
return this.id;
}
@Override
public String getName()
{
if (this.name != null) {
return this.name;
}
try {
OntologyManager om =
ComponentManagerRegistry.getContextComponentManager().getInstance(OntologyManager.class);
OntologyTerm term = om.resolveTerm(this.id);
if (term != null && StringUtils.isNotEmpty(term.getName())) {
this.name = term.getName();
return this.name;
}
} catch (ComponentLookupException ex) {
// Shouldn't happen
}
return this.id;
}
@Override
public String toString()
{
return toJSON().toString(2);
}
@Override
public JSONObject toJSON()
{
JSONObject result = new JSONObject();
result.element(ID_JSON_KEY_NAME, getId());
result.element(NAME_JSON_KEY_NAME, getName());
return result;
}
@Override
public int compareTo(OntologyProperty o)
{
if (o == null) {
// Nulls at the end
return -1;
}
return getName().compareTo(o.getName());
}
}
| Issue #951: Remove the (empty) id from the JSON export of non-standard features
Done.
| components/patient-data/impl/src/main/java/org/phenotips/data/internal/AbstractPhenoTipsOntologyProperty.java | Issue #951: Remove the (empty) id from the JSON export of non-standard features Done. | <ide><path>omponents/patient-data/impl/src/main/java/org/phenotips/data/internal/AbstractPhenoTipsOntologyProperty.java
<ide> */
<ide> protected AbstractPhenoTipsOntologyProperty(JSONObject json)
<ide> {
<del> this.id = json.getString(ID_JSON_KEY_NAME);
<del> this.name = json.getString(NAME_JSON_KEY_NAME);
<add> this.id = json.has(ID_JSON_KEY_NAME) ? json.getString(ID_JSON_KEY_NAME) : "";
<add> this.name = json.has(NAME_JSON_KEY_NAME) ? json.getString(NAME_JSON_KEY_NAME) : null;
<ide> }
<ide>
<ide> @Override
<ide> public JSONObject toJSON()
<ide> {
<ide> JSONObject result = new JSONObject();
<del> result.element(ID_JSON_KEY_NAME, getId());
<del> result.element(NAME_JSON_KEY_NAME, getName());
<add> if (StringUtils.isNotEmpty(this.getId())) {
<add> result.element(ID_JSON_KEY_NAME, getId());
<add> }
<add> if (StringUtils.isNotEmpty(this.getName())) {
<add> result.element(NAME_JSON_KEY_NAME, getName());
<add> }
<ide> return result;
<ide> }
<ide> |
|
Java | isc | b3c06b04d19e64bbdf7fba6a804786b6a4f65dd7 | 0 | magicgoose/ormlite-core,ylcolala/ormlite-core,dankito/ormlite-jpa-core,lobo12/ormlite-core,ylfonline/ormlite-core,j256/ormlite-core | package com.j256.ormlite.logger;
import java.lang.reflect.Constructor;
/**
* Factory that creates {@link Logger} instances.
*/
public class LoggerFactory {
private static LogType logType;
/**
* For static calls only.
*/
private LoggerFactory() {
}
/**
* Return a logger associated with a particular class.
*/
public static Logger getLogger(Class<?> clazz) {
return getLogger(clazz.getName());
}
/**
* Return a logger associated with a particular class name.
*/
public static Logger getLogger(String className) {
if (logType == null) {
logType = findLogType();
}
return new Logger(logType.createLog(className));
}
public static String getSimpleClassName(String className) {
// get the last part of the class name
String[] parts = className.split("\\.");
if (parts.length == 0) {
return className;
} else {
return parts[parts.length - 1];
}
}
/**
* Return the most appropriate log type. This should _never_ return null.
*/
private static LogType findLogType() {
for (LogType logType : LogType.values()) {
if (logType.isAvailable()) {
return logType;
}
}
// fall back is always LOCAL
return LogType.LOCAL;
}
private enum LogType {
/**
* WARNING: This should be _before_ commons logging since Android provides commons logging but logging messages
* are ignored that are sent there. Grrrrr.
*/
ANDROID("android.util.Log") {
@Override
public Log createLog(String classLabel) {
try {
Class<?> clazz = Class.forName("com.j256.ormlite.android.AndroidLog");
@SuppressWarnings("unchecked")
Constructor<Log> constructor = (Constructor<Log>) clazz.getConstructor(String.class);
return constructor.newInstance(classLabel);
} catch (Exception e) {
// oh well, fallback to the local log
return LOCAL.createLog(classLabel);
}
}
},
COMMONS_LOGGING("org.apache.commons.logging.LogFactory") {
@Override
public Log createLog(String classLabel) {
return new CommonsLoggingLog(classLabel);
}
},
LOG4J("org.apache.log4j.Logger") {
@Override
public Log createLog(String classLabel) {
return new Log4jLog(classLabel);
}
},
LOCAL("com.j256.ormlite.logger.LocalLog") {
@Override
public Log createLog(String classLabel) {
return new LocalLog(classLabel);
}
@Override
public boolean isAvailable() {
// it's always available
return true;
}
},
// end
;
private String detectClassName;
private LogType(String detectClassName) {
this.detectClassName = detectClassName;
}
/**
* Create and return a Log class for this type.
*/
public abstract Log createLog(String classLabel);
/**
* Return true if the log class is available.
*/
public boolean isAvailable() {
try {
Class.forName(detectClassName);
return true;
} catch (Exception e) {
return false;
}
}
}
}
| src/main/java/com/j256/ormlite/logger/LoggerFactory.java | package com.j256.ormlite.logger;
import java.lang.reflect.Constructor;
/**
* Factory that creates {@link Logger} instances.
*/
public class LoggerFactory {
private static LogType logType;
/**
* For static calls only.
*/
private LoggerFactory() {
}
/**
* Return a logger associated with a particular class.
*/
public static Logger getLogger(Class<?> clazz) {
return getLogger(clazz.getName());
}
/**
* Return a logger associated with a particular class name.
*/
public static Logger getLogger(String className) {
if (logType == null) {
logType = findLogType();
}
return new Logger(logType.createLog(className));
}
public static String getSimpleClassName(String className) {
// get the last part of the class name
String[] parts = className.split("\\.");
if (parts.length == 0) {
return className;
} else {
return parts[parts.length - 1];
}
}
/**
* Return the most appropriate log type. This should _never_ return null.
*/
private static LogType findLogType() {
for (LogType logType : LogType.values()) {
if (logType.isAvailable()) {
return logType;
}
}
// fall back is always LOCAL
return LogType.LOCAL;
}
private enum LogType {
COMMONS_LOGGING("org.apache.commons.logging.LogFactory") {
@Override
public Log createLog(String classLabel) {
return new CommonsLoggingLog(classLabel);
}
},
LOG4J("org.apache.log4j.Logger") {
@Override
public Log createLog(String classLabel) {
return new Log4jLog(classLabel);
}
},
ANDROID("android.util.Log") {
@Override
public Log createLog(String classLabel) {
try {
Class<?> clazz = Class.forName("com.j256.ormlite.android.AndroidLog");
@SuppressWarnings("unchecked")
Constructor<Log> constructor = (Constructor<Log>) clazz.getConstructor(String.class);
return constructor.newInstance(classLabel);
} catch (Exception e) {
// oh well, fallback to the local log
return LOCAL.createLog(classLabel);
}
}
},
LOCAL("com.j256.ormlite.logger.LocalLog") {
@Override
public Log createLog(String classLabel) {
return new LocalLog(classLabel);
}
@Override
public boolean isAvailable() {
// it's always available
return true;
}
},
// end
;
private String detectClassName;
private LogType(String detectClassName) {
this.detectClassName = detectClassName;
}
/**
* Create and return a Log class for this type.
*/
public abstract Log createLog(String classLabel);
/**
* Return true if the log class is available.
*/
public boolean isAvailable() {
try {
Class.forName(detectClassName);
return true;
} catch (Exception e) {
return false;
}
}
}
}
| Reordered the log class detection to put Android Log before commons logging. Fixes bug #3167100.
| src/main/java/com/j256/ormlite/logger/LoggerFactory.java | Reordered the log class detection to put Android Log before commons logging. Fixes bug #3167100. | <ide><path>rc/main/java/com/j256/ormlite/logger/LoggerFactory.java
<ide> }
<ide>
<ide> private enum LogType {
<del> COMMONS_LOGGING("org.apache.commons.logging.LogFactory") {
<del> @Override
<del> public Log createLog(String classLabel) {
<del> return new CommonsLoggingLog(classLabel);
<del> }
<del>
<del> },
<del> LOG4J("org.apache.log4j.Logger") {
<del> @Override
<del> public Log createLog(String classLabel) {
<del> return new Log4jLog(classLabel);
<del> }
<del> },
<add> /**
<add> * WARNING: This should be _before_ commons logging since Android provides commons logging but logging messages
<add> * are ignored that are sent there. Grrrrr.
<add> */
<ide> ANDROID("android.util.Log") {
<ide> @Override
<ide> public Log createLog(String classLabel) {
<ide> // oh well, fallback to the local log
<ide> return LOCAL.createLog(classLabel);
<ide> }
<add> }
<add> },
<add> COMMONS_LOGGING("org.apache.commons.logging.LogFactory") {
<add> @Override
<add> public Log createLog(String classLabel) {
<add> return new CommonsLoggingLog(classLabel);
<add> }
<add>
<add> },
<add> LOG4J("org.apache.log4j.Logger") {
<add> @Override
<add> public Log createLog(String classLabel) {
<add> return new Log4jLog(classLabel);
<ide> }
<ide> },
<ide> LOCAL("com.j256.ormlite.logger.LocalLog") { |
|
JavaScript | isc | b99055cf9dfeaf87de2ace6355c87da81ffed2d9 | 0 | giancarlobonansea/clusterednode-client,giancarlobonansea/clusterednode-client,giancarlobonansea/clusterednode-client | (function(app) {
app.AppSimulator = (function() {
//// Constants
var _s_SIM = 'S',
_s_CFG = 'C',
_s_PI = ['raspberrypi2','raspberrypi3','raspberrypi5','raspberrypi6'],
_s_STG = ['-redis','-node','-nginx','-angular'],
_s_BURL = 'https://giancarlobonansea.homeip.net:3333',
_s_AURL = _s_BURL + '3/api',
_s_HURL = _s_BURL + '3/hdr',
_s_IURL = _s_BURL + '1',
_s_STA = 'STABILITY',
_s_STR = 'STRESS',
_j_ERE = {
//rtt = A
A: 0,
//hst = H
H: '',
//rid = Q
Q: 0,
//tsn = X
X: 0,
//exts = N
N: 0,
//erd = R
R: 0,
//cached = C
C: false
},
_a_PRE = [
[[0,
5,
50,
4],
[100,
0,
0,
2],
'Small'],
[[0,
10,
30,
4],
[512,
0,
0,
16],
'Medium'],
[[0,
30,
25,
4],
[1024,
0,
0,
64],
'Large'],
[[0,
60,
25,
8],
[2048,
0,
0,
128],
'Huge']
],
_a_OPE = [0,
0,
0,
0,
0,
0,
0,
1,
2,
3],
_o_SIO = io(_s_IURL,{autoConnect:false}),
_e_SIO = {},
//// helper functions
iRL = function(t) {
var l = {
l0: _RL.l0,
l1: _RL.l1,
v: []
};
for (var i = 0; i < _RL.v.length; i++) {
l.v.push({
t: _RL.v[i].t,
a: []
});
for (var j = 0; j < _RL.v[i].a.length; j++) {
l.v[i].a.push({
h: t.safeUrl(_RL.v[i].a[j].h),
d: _RL.v[i].a[j].d
});
}
}
return l;
},
mR = function(v) {
return (Math.random() * v) | 0;
},
//// Google Analytics
sGA = function(a, b, c, d) {
ga('send', 'event', a, b, c, d);
},
//// initCharts
cP = function(t) {
return {
chart: {
type: 'pieChart',
height: 299,
showLegend: false,
donut: true,
padAngle: 0.08,
cornerRadius: 5,
title: t,
x: function(d) {return d.key;},
y: function(d) {return d.y;},
showLabels: true,
labelType: function(d) {return d.data.key + ': ' + (d.data.y | 0);},
labelsOutside: true,
duration: 500
}
}
},
//// resetExecutionScopeVariables
cRS = function() {
var j = [];
for(var i=0;i<4;i++) {
j.push([_s_PI[i],[],0]);
}
return j;
},
//// createPIX
cPIX = function() {
var j = {};
for(var i=0;i<4;i++) {
j[_s_PI[i]]=[i,{}];
}
return j;
},
//// deactivateLiveEvents
dLE = function() {
if (_e_SIO) {
_e_SIO.destroy();
if (_o_SIO.connected) {
_o_SIO.close();
}
}
},
//// activateLiveEvents
aLE = function(m) {
_o_SIO.connect();
_e_SIO = _o_SIO.on('redis', function(d) {
if (m[d.x][d.y] < 3) {
var x = d.x,
y = d.y;
m[x][y] = 3;
setTimeout(function() {
m[x][y] = ((((x << 5) + y) << 4) / 2731) | 0;
}, 750);
}
});
},
//// observableResponses
oR = function(t, re, rs, rq, cc, pix) {
for (var k = 0; k < re.length; k++) {
oR1(t, re[k], rs, rq, cc, pix);
}
},
//// for STRESS
oR1 = function(t, re, rs, rq, cc, pix, eid) {
var res = re,
req = res.Q,
hst = res.json.h,
ndx = pix[hst][0],
cch = res.C;
rq[0][req] = {
Q: 'Req ' + ((req | 0) + 1),
H: ndx,
A: res.A,
X: res.X,
N: res.N,
R: res.R,
C: cch,
T: eid
};
if (cch) {
t.rqCh++;
cc.push(++t.rOK);
}
else {
var pid = res.json.p,
o = rq[2][req];
if (!(pid in pix[hst][1])) {
rs[ndx][1].push([pid,
[[],
[],
[],
[]]]);
pix[hst][1][pid] = rs[ndx][1].length - 1;
}
rs[ndx][1][pix[hst][1][pid]][1][o].push(++t.rOK);
rs[ndx][2]++;
}
},
//// startStatistics
sSt = function(t, rqEx, dur, cnEr, rq, rs, cc) {
t.clc = true;
t.dur = dur;
t.rqEx = rqEx;
t.rER = cnEr;
t.rs = rs;
t.chRe = cc;
setTimeout(function(){
var aR = cH(t, rqEx, dur, rq);
t.bcd = aR[0];
t.pcd = aR[1];
t.pcd2 = aR[2];
t.tpA = aR[3];
t.tpX = aR[4];
t.tpN = aR[5];
t.tpR = aR[6];
t.hg = aR[7];
});
},
//// throwHTTP
tHr = function(tHt, t, tRqCt, tRqCn, tRqDu, tRqIn, rq, tClc) {
var cnRq = 0,
cnRe = 0,
cnEr = 0,
cc = [],
pix = cPIX(),
rs = cRS(),
iniTime = Date.now();
if (!tHt) {
// STRESS
var ev = [],
fROK = function(d) {
var proReq = cnRq++,
eid = d;
if (proReq<tRqCt) {
rq[1][proReq].subscribe(
function(r) {
oR1(t, r, rs, rq, cc, pix, eid);
},
function(e) {
cnEr++;
},
function() {
if (++cnRe >= tRqCt) {
ev[eid].unsubscribe();
sSt(t, tRqCt, Date.now() - iniTime, cnEr, rq, rs, cc);
}
else {
ev[eid].emit(eid);
}
this.unsubscribe();
}
);
} else {
ev[eid].unsubscribe();
}
};
for(var e=0;e<tRqCn;e++) {
ev.push(new ng.core.EventEmitter(true));
ev[e].subscribe(fROK);
ev[e].emit(e);
}
} else {
// DURATION
var tmR = true,
sHd = function() {
if (inH) {
clearInterval(inH);
}
sSt(t, cnRe, Date.now() - iniTime, cnEr, rq, rs, cc);
},
inF = function() {
if (tmR && cnRq < tRqCt) {
cnRq += tRqCn;
var oRA = Rx.Observable.forkJoin(rq[1].slice(cnRq - tRqCn, cnRq<tRqCt?cnRq:tRqCt)).subscribe(
function(r) {
oR(t, r, rs, rq, cc, pix);
},
function(e) {
cnEr += tRqCn;
},
function() {
cnRe += tRqCn;
oRA.unsubscribe();
if (!tmR && !tClc && cnRq === cnRe) {
sHd();
}
}
);
}
else {
if (!tClc && cnRq === cnRe) {
sHd();
}
}
};
setTimeout(function() {
tmR = false;
}, (tRqDu * 1000) + 10);
setTimeout(function() {inF();});
var inH = setInterval(function() {inF();}, tRqIn);
}
},
//// populateRequestSamples
pRS = function(t) {
var rq = [[],
[],
[]],
oT = [0,
0,
0,
0];
for (var q = 0; q < t.rqCt; q++) {
var o = _a_OPE[mR(10)];
oT[o]++;
rq[0].push(_j_ERE);
rq[1].push(t.hS.get(q, _s_AURL, o, mR(16384)));
rq[2].push(o);
}
return [rq,
oT];
},
//// calculateHistogram
cH = function(t, rqEx, dur, rq) {
t.lE = false;
//// resetChartsData
var cBC = function(k1, k2) {
return {
key: k1 + k2,
values: []
};
},
cPC = function(k) {
return {
key: k,
y: 0
};
},
bcd = [],
pcd = [cPC(_s_PI[0]),
cPC(_s_PI[1]),
cPC(_s_PI[2]),
cPC(_s_PI[3])],
pcd2 = [cPC(_s_PI[0]),
cPC(_s_PI[1]),
cPC(_s_PI[2]),
cPC(_s_PI[3])],
lcd = [
{
key: 'w/o Coord. Omission',
values: [],
area: false
},
{
key: 'Latency/Percentile',
values: [],
area: true
}
],
dr = ((rqEx * 0.0455) | 0) + 1,
dLo = (dr / 2) | 0,
dUp = rqEx - dLo,
setBcd = function(i, l, v) {
bcd[i].values.push({
label: l,
value: v
});
},
rq0 = rq[0],
rq1 = rq[0].slice(0),
rq2 = rq[0].slice(0),
rq3 = rq[0].slice(0),
toA = 0,
toX = 0,
toN = 0,
toR = 0,
hg = [[50,
0,
0,
0,
0],
[75,
0,
0,
0,
0],
[87.5,
0,
0,
0,
0],
[93.75,
0,
0,
0,
0],
[96.875,
0,
0,
0,
0],
[98.4375,
0,
0,
0,
0],
[99.21875,
0,
0,
0,
0],
[100,
0,
0,
0,
0]],
totReqAng = [0,
0,
0,
0],
totReqNgi = [0,
0,
0,
0],
hdPD = {arr: []},
byH = function(hl, hv, v) {
return hl === hv ? v : 0;
},
inSD = function(i, v) {
return ((i >= dLo) && (i <= dUp)) ? v : 0;
},
inSDbyH = function(hl, hv, i, v) {
return ((hl === hv) && (i >= dLo) && (i <= dUp)) ? v : 0;
},rtt = [], tsn = [], exts = [], red = [];
//
// Populate barchart structure
//
for(var i=0;i<4;i++) {
for(var j=0;j<4;j++) {
bcd.push(cBC(_s_PI[j], _s_STG[i]));
}
}
//
// Populate barchart as processed (no sorting)
//
for (i = 0; i < rq0.length; i++) {
var _hst = rq0[i].H,
_rid = rq0[i].Q;
rtt = [0,
0,
0,
0];
tsn = [0,
0,
0,
0];
exts = [0,
0,
0,
0];
red = [0,
0,
0,
0];
rtt[_hst] = rq0[i].A;
tsn[_hst] = rq0[i].X;
exts[_hst] = rq0[i].N;
red[_hst] = rq0[i].R;
for (var j = 0; j < 4; j++) {
setBcd(j, _rid, red[j] | 0);
setBcd(j + 4, _rid, (exts[j] - red[j]) | 0);
setBcd(j + 8, _rid, (tsn[j] - exts[j]) | 0);
setBcd(j + 12, _rid, rtt[j] - tsn[j]);
}
hdPD.arr.push(rq0[i].A);
}
//
// Prepare histogram
//
rq0.sort(function(a, b) {return a.A - b.A});
rq1.sort(function(a, b) {return a.X - b.X});
rq2.sort(function(a, b) {return a.N - b.N});
rq3.sort(function(a, b) {return a.R - b.R});
for (i = 0; i < rq0.length; i++) {
var _hstR = rq0[i].H,
_rttR = rq0[i].A,
_hstT = rq1[i].H,
_tsnT = rq1[i].X;
for (j = 0; j < 4; j++) {
rtt[j] = byH(_hstR, j, _rttR);
pcd2[j].y += inSD(i, rtt[j]);
totReqAng[j] += inSDbyH(_hstR, j, i, 1);
tsn[j] = byH(_hstT, j, _tsnT);
pcd[j].y += inSD(i, tsn[j]);
totReqNgi[j] += inSDbyH(_hstT, j, i, 1);
}
toA += inSD(i, _rttR);
toX += inSD(i, _tsnT);
toN += inSD(i, rq2[i].N);
toR += inSD(i, rq3[i].R);
}
for (i = 0; i < 4; i++) {
pcd2[i].y /= totReqAng[i];
pcd[i].y /= totReqNgi[i];
}
var tpA = ((rqEx / (dur / 1000)) | 0) + 1,
tpX = ((tpA * toA / toX) | 0) + 1,
tpN = ((tpX * toX / toN) | 0) + 1,
tpR = ((tpN * toN / toR) | 0) + 1;
for (i = 0; i < hg.length; i++) {
var ix = ((rqEx * hg[i][0] / 100) | 0) - 1;
hg[i][1] = rq0[ix].A;
hg[i][2] = rq1[ix].X;
hg[i][3] = rq2[ix].N;
hg[i][4] = rq3[ix].R;
}
//
// Calculating HDR Histogram
//
var oRT = t.hS.post(_s_HURL, JSON.stringify(hdPD)).subscribe(
function(re) {
for (var n = 0; n < re.chart.length; n++) {
var idx = ((re.chart[n].percentile * t.rOK / 100) | 0) - 1;
lcd[0].values.push({
x: re.chart[n].percentile,
y: re.chart[n].value
});
lcd[1].values.push({
x: re.chart[n].percentile,
y: rq0[(idx < 0) ? 0 : idx].A
});
}
},
function(e) {
},
function() {
t.lcd = lcd;
oRT.unsubscribe();
t.clc = false;
t.run = false;
t.lE = false;
}
);
//
// Set Angular view variables
//
sGA(_s_SIM, 'E', 'T', tpA);
return [bcd,
pcd,
pcd2,
tpA,
tpX,
tpN,
tpR,
hg];
},
//// Create Live Events matrix
cLE = function() {
var lva = [], a0 = [], a01 = [], a1 = [], a12 = [], a2 = [];
for (var i = 0; i < 32; i++) {
a0[i] = 0;
a01[i] = i < 11 ? 0 : 1;
a1[i] = 1;
a12[i] = i < 22 ? 1 : 2;
a2[i] = 2;
}
for (i = 0; i < 5; i++) {
lva.push(a0.slice(0));
}
lva.push(a01);
for (i = 0; i < 4; i++) {
lva.push(a1.slice(0));
}
lva.push(a12);
for (i = 0; i < 5; i++) {
lva.push(a2.slice(0));
}
return lva;
};
//// Constructor
function AppSimulator (HTTPService, DOMSanitizer) {
//
// Initialize services
//
this.hS = HTTPService;
this.snS = DOMSanitizer;
//
// View execution parameters
//
this.sD(false);
//
// View presentation variables - reference links
//
this.links = iRL(this);
//
// Charts configuration and initialization
//
this.bco = {
chart: {
type: 'multiBarChart',
showControls: false,
height: 400,
margin: {
top: 20,
right: 20,
bottom: 20,
left: 45
},
x: function(d) {return d.label;},
y: function(d) {return d.value;},
clipEdge: true,
stacked: true,
showXAxis: false,
duration: 500,
xAxis: {
showMaxMin: false
},
yAxis: {
tickFormat: function(d) {
return d3.format('d')(d);
}
}
}
};
this.lco = {
chart: {
type: 'lineWithFocusChart',
showControls: false,
height: 400,
showLegend: true,
clipEdge: true,
duration: 500,
margin: {
top: 20,
right: 20,
bottom: 40,
left: 55
},
x: function(d) { return d.x; },
y: function(d) { return d.y; },
useInteractiveGuideline: true,
xAxis: {
axisLabel: 'Percentile (%)'
},
yAxis: {
axisLabel: 'AngularJS Latency (ms)',
axisLabelDistance: -10,
rotateYLabel: true
},
brushExtent: [75,
100]
}
};
this.pco = cP('nginX');
this.pco2 = cP('AngularJS');
//
// Live Events socket variables and configuration
//
this.lE = false;
this.gDS = ['text-muted',
'text-primary',
'text-muted',
'text-danger'];
this.oleMx = cLE();
//
// View execution variables
//
this.rVEV();
this.run = false;
}
AppSimulator.parameters = [
app.HTTPService,
ng.platformBrowser.DomSanitizationService
];
AppSimulator.annotations = [
new ng.core.Component({
selector: 'n-c-s',
templateUrl: 'simulator.html',
providers: [
app.HTTPService,
ng.http.HTTP_PROVIDERS,
ng.platformBrowser.BROWSER_SANITIZATION_PROVIDERS
],
directives: [nvD3]
})
];
AppSimulator.prototype.safeUrl = function(u) {
return this.snS.bypassSecurityTrustResourceUrl(u);
};
//
// Configuration & Initialization methods
//
//// resetViewExecVariables
AppSimulator.prototype.rVEV = function() {
this.rER = 0;
this.rOK = 0;
this.rqCh = 0;
this.sRe = false;
this.clc = false;
this.leMx = this.oleMx.slice(0);
};
//
// UI related methods
//
//// setMethodParameters
AppSimulator.prototype.sMP = function(p) {
var m = this.iD ? 0 : 1;
this.rqCt = _a_PRE[p][m][0];
this.rqDu = _a_PRE[p][m][1];
this.rqIn = _a_PRE[p][m][2];
this.rqCn = _a_PRE[p][m][3];
sGA(_s_SIM, _s_CFG, _a_PRE[p][2], 0);
};
//// setDuration or setRequests
AppSimulator.prototype.sD = function(m) {
this.iD = m;
this.sMP(0);
};
//// getSimulationMethod
AppSimulator.prototype.gSM = function() {
return this.iD ? _s_STA : _s_STR;
};
//// onRefLinkClick
AppSimulator.prototype.oRLC = function(t, d) {
sGA('R', t, d, 0);
};
//// showRef
AppSimulator.prototype.shR = function() {
this.sRe = !this.sRe;
if (this.sRe) {
this.lE = false;
dLE();
}
};
//// showLive
AppSimulator.prototype.shL = function() {
this.lE = !this.lE;
if (this.lE) {
aLE(this.leMx);
this.sRe = false;
} else {
dLE();
}
};
//// percValue
AppSimulator.prototype.pV = function(o, c) {
return (o * 100 / c) | 0;
};
//// calcPosition
AppSimulator.prototype.cP = function(o, h) {
return (o * h / 100) | 0;
};
//// getDurationRequests
AppSimulator.prototype.gDR = function(d, c, i) {
var tot = (d * 1000 * c / i) | 0;
return tot - (tot % c);
};
//// getDurationThroughput
AppSimulator.prototype.gDT = function(d, c, i) {
return (this.gDR(d, c, i) / d) | 0;
};
//
// Execution control methods
//
//// startSimulator
AppSimulator.prototype.sSi = function() {
////
//// Initialize execution variables - once for each execution
//// all first time initialization performed on constructor function
////
//
// Save execution parameters & Reset Live Events socket variables
//
this.exM = this.gSM();
this.exiD = this.exM === _s_STA;
this.exR = this.rqCt;
this.exD = this.rqDu;
this.exI = this.rqIn;
this.exC = this.rqCn;
this.exmR = this.gDR(this.rqDu,this.rqCn,this.rqIn);
//
// Reset execution scope variables
//
this.dur = 0;
//
// Reset view execution variables
//
this.rVEV();
this.run = true;
//
// Reset view presentation variables - control
//
this.shL();
//
// Switch among simulation methods (stress or duration)
//
if (this.iD) {
this.rqCt = this.exmR|0;
}
var aR = pRS(this);
this.oT = aR[1];
tHr(this.iD, this, this.rqCt, this.rqCn, this.rqDu, this.rqIn, aR[0], this.clc);
};
return AppSimulator;
})();
})(window.app || (window.app = {}));
| app.simulator.js | (function(app) {
app.AppSimulator = (function() {
//// Constants
var _s_SIM = 'S',
_s_CFG = 'C',
_s_PI = ['raspberrypi2','raspberrypi3','raspberrypi5','raspberrypi6'],
_s_STG = ['-redis','-node','-nginx','-angular'],
_s_BURL = 'https://giancarlobonansea.homeip.net:3333',
_s_AURL = _s_BURL + '3/api',
_s_HURL = _s_BURL + '3/hdr',
_s_IURL = _s_BURL + '1',
_s_STA = 'STABILITY',
_s_STR = 'STRESS',
_j_ERE = {
//rtt = A
A: 0,
//hst = H
H: '',
//rid = Q
Q: 0,
//tsn = X
X: 0,
//exts = N
N: 0,
//erd = R
R: 0,
//cached = C
C: false
},
_a_PRE = [
[[0,
5,
50,
4],
[100,
0,
0,
2],
'Small'],
[[0,
10,
30,
4],
[512,
0,
0,
16],
'Medium'],
[[0,
30,
25,
4],
[1024,
0,
0,
64],
'Large'],
[[0,
60,
25,
8],
[2048,
0,
0,
128],
'Huge']
],
_a_OPE = [0,
0,
0,
0,
0,
0,
0,
1,
2,
3],
_o_SIO = io(_s_IURL,{autoConnect:false}),
_e_SIO = {},
//// helper functions
iRL = function(t) {
var l = {
l0: _RL.l0,
l1: _RL.l1,
v: []
};
for (var i = 0; i < _RL.v.length; i++) {
l.v.push({
t: _RL.v[i].t,
a: []
});
for (var j = 0; j < _RL.v[i].a.length; j++) {
l.v[i].a.push({
h: t.safeUrl(_RL.v[i].a[j].h),
d: _RL.v[i].a[j].d
});
}
}
return l;
},
mR = function(v) {
return (Math.random() * v) | 0;
},
//// Google Analytics
sGA = function(a, b, c, d) {
ga('send', 'event', a, b, c, d);
},
//// initCharts
cP = function(t) {
return {
chart: {
type: 'pieChart',
height: 299,
showLegend: false,
donut: true,
padAngle: 0.08,
cornerRadius: 5,
title: t,
x: function(d) {return d.key;},
y: function(d) {return d.y;},
showLabels: true,
labelType: function(d) {return d.data.key + ': ' + (d.data.y | 0);},
labelsOutside: true,
duration: 500
}
}
},
//// resetExecutionScopeVariables
cRS = function() {
var j = [];
for(var i=0;i<4;i++) {
j.push([_s_PI[i],[],0]);
}
return j;
},
//// createPIX
cPIX = function() {
var j = {};
for(var i=0;i<4;i++) {
j[_s_PI[i]]=[i,{}];
}
return j;
},
//// deactivateLiveEvents
dLE = function() {
if (_e_SIO) {
_e_SIO.destroy();
if (_o_SIO.connected) {
_o_SIO.close();
}
}
},
//// activateLiveEvents
aLE = function(m) {
_o_SIO.connect();
_e_SIO = _o_SIO.on('redis', function(d) {
if (m[d.x][d.y] < 3) {
var x = d.x,
y = d.y;
m[x][y] = 3;
setTimeout(function() {
m[x][y] = ((((x << 5) + y) << 4) / 2731) | 0;
}, 750);
}
});
},
//// observableResponses
oR = function(t, re, rs, rq, cc, pix) {
for (var k = 0; k < re.length; k++) {
oR1(t, re[k], rs, rq, cc, pix);
}
},
oR1 = function(t, re, rs, rq, cc, pix, eid) {
var res = re,
req = res.Q,
hst = res.json.h,
ndx = pix[hst][0],
cch = res.C;
rq[0][req] = {
Q: 'Req ' + ((req | 0) + 1),
H: ndx,
A: res.A,
X: res.X,
N: res.N,
R: res.R,
C: cch,
T: eid
};
if (cch) {
t.rqCh++;
cc.push(++t.rOK);
}
else {
var pid = res.json.p,
o = rq[2][req];
if (!(pid in pix[hst][1])) {
rs[ndx][1].push([pid,
[[],
[],
[],
[]]]);
pix[hst][1][pid] = rs[ndx][1].length - 1;
}
rs[ndx][1][pix[hst][1][pid]][1][o].push(++t.rOK);
rs[ndx][2]++;
}
},
//// startStatistics
sSt = function(t, rqEx, dur, cnEr, rq, rs, cc) {
t.clc = true;
t.dur = dur;
t.rqEx = rqEx;
t.rER = cnEr;
t.rs = rs;
t.chRe = cc;
setTimeout(function(){
var aR = cH(t, rqEx, dur, rq);
t.bcd = aR[0];
t.pcd = aR[1];
t.pcd2 = aR[2];
t.tpA = aR[3];
t.tpX = aR[4];
t.tpN = aR[5];
t.tpR = aR[6];
t.hg = aR[7];
});
},
//// throwHTTP
tHr = function(tHt, t, tRqCt, tRqCn, tRqDu, tRqIn, rq, tClc) {
var cnRq = 0,
cnRe = 0,
cnEr = 0,
cc = [],
pix = cPIX(),
rs = cRS(),
iniTime = Date.now();
if (!tHt) {
// STRESS
var ev = [],
fROK = function(d) {
var proReq = cnRq++,
eid = d;
if (proReq<tRqCt) {
rq[1][proReq].subscribe(
function(r) {
oR1(t, r, rs, rq, cc, pix, eid);
},
function(e) {
cnEr++;
},
function() {
if (++cnRe >= tRqCt) {
ev[eid].unsubscribe();
sSt(t, tRqCt, Date.now() - iniTime, cnEr, rq, rs, cc);
}
else {
ev[eid].emit(eid);
}
this.unsubscribe();
}
);
} else {
ev[eid].unsubscribe();
}
};
for(var e=0;e<tRqCn;e++) {
ev.push(new ng.core.EventEmitter(true));
ev[e].subscribe(fROK);
ev[e].emit(e);
}
} else {
// DURATION
var tmR = true,
sHd = function() {
if (inH) {
clearInterval(inH);
}
sSt(t, cnRe, Date.now() - iniTime, cnEr, rq, rs, cc);
},
inF = function() {
if (tmR && cnRq < tRqCt) {
cnRq += tRqCn;
var oRA = Rx.Observable.forkJoin(rq[1].slice(cnRq - tRqCn, cnRq<tRqCt?cnRq:tRqCt)).subscribe(
function(r) {
oR(t, r, rs, rq, cc, pix);
},
function(e) {
cnEr += tRqCn;
},
function() {
cnRe += tRqCn;
oRA.unsubscribe();
if (!tmR && !tClc && cnRq === cnRe) {
sHd();
}
}
);
}
else {
if (!tClc && cnRq === cnRe) {
sHd();
}
}
};
setTimeout(function() {
tmR = false;
}, (tRqDu * 1000) + 10);
setTimeout(function() {inF();});
var inH = setInterval(function() {inF();}, tRqIn);
}
},
//// populateRequestSamples
pRS = function(t) {
var rq = [[],
[],
[]],
oT = [0,
0,
0,
0];
for (var q = 0; q < t.rqCt; q++) {
var o = _a_OPE[mR(10)];
oT[o]++;
rq[0].push(_j_ERE);
rq[1].push(t.hS.get(q, _s_AURL, o, mR(16384)));
rq[2].push(o);
}
return [rq,
oT];
},
//// calculateHistogram
cH = function(t, rqEx, dur, rq) {
t.lE = false;
//// resetChartsData
var cBC = function(k1, k2) {
return {
key: k1 + k2,
values: []
};
},
cPC = function(k) {
return {
key: k,
y: 0
};
},
bcd = [],
pcd = [cPC(_s_PI[0]),
cPC(_s_PI[1]),
cPC(_s_PI[2]),
cPC(_s_PI[3])],
pcd2 = [cPC(_s_PI[0]),
cPC(_s_PI[1]),
cPC(_s_PI[2]),
cPC(_s_PI[3])],
lcd = [
{
key: 'w/o Coord. Omission',
values: [],
area: false
},
{
key: 'Latency/Percentile',
values: [],
area: true
}
],
dr = ((rqEx * 0.0455) | 0) + 1,
dLo = (dr / 2) | 0,
dUp = rqEx - dLo,
setBcd = function(i, l, v) {
bcd[i].values.push({
label: l,
value: v
});
},
rq0 = rq[0],
rq1 = rq[0].slice(0),
rq2 = rq[0].slice(0),
rq3 = rq[0].slice(0),
toA = 0,
toX = 0,
toN = 0,
toR = 0,
hg = [[50,
0,
0,
0,
0],
[75,
0,
0,
0,
0],
[87.5,
0,
0,
0,
0],
[93.75,
0,
0,
0,
0],
[96.875,
0,
0,
0,
0],
[98.4375,
0,
0,
0,
0],
[99.21875,
0,
0,
0,
0],
[100,
0,
0,
0,
0]],
totReqAng = [0,
0,
0,
0],
totReqNgi = [0,
0,
0,
0],
hdPD = {arr: []},
byH = function(hl, hv, v) {
return hl === hv ? v : 0;
},
inSD = function(i, v) {
return ((i >= dLo) && (i <= dUp)) ? v : 0;
},
inSDbyH = function(hl, hv, i, v) {
return ((hl === hv) && (i >= dLo) && (i <= dUp)) ? v : 0;
},rtt = [], tsn = [], exts = [], red = [];
//
// Populate barchart structure
//
for(var i=0;i<4;i++) {
for(var j=0;j<4;j++) {
bcd.push(cBC(_s_PI[j], _s_STG[i]));
}
}
//
// Populate barchart as processed (no sorting)
//
for (i = 0; i < rq0.length; i++) {
var _hst = rq0[i].H,
_rid = rq0[i].Q;
rtt = [0,
0,
0,
0];
tsn = [0,
0,
0,
0];
exts = [0,
0,
0,
0];
red = [0,
0,
0,
0];
rtt[_hst] = rq0[i].A;
tsn[_hst] = rq0[i].X;
exts[_hst] = rq0[i].N;
red[_hst] = rq0[i].R;
for (var j = 0; j < 4; j++) {
setBcd(j, _rid, red[j] | 0);
setBcd(j + 4, _rid, (exts[j] - red[j]) | 0);
setBcd(j + 8, _rid, (tsn[j] - exts[j]) | 0);
setBcd(j + 12, _rid, rtt[j] - tsn[j]);
}
hdPD.arr.push(rq0[i].A);
}
//
// Prepare histogram
//
rq0.sort(function(a, b) {return a.A - b.A});
rq1.sort(function(a, b) {return a.X - b.X});
rq2.sort(function(a, b) {return a.N - b.N});
rq3.sort(function(a, b) {return a.R - b.R});
for (i = 0; i < rq0.length; i++) {
var _hstR = rq0[i].H,
_rttR = rq0[i].A,
_hstT = rq1[i].H,
_tsnT = rq1[i].X;
for (j = 0; j < 4; j++) {
rtt[j] = byH(_hstR, j, _rttR);
pcd2[j].y += inSD(i, rtt[j]);
totReqAng[j] += inSDbyH(_hstR, j, i, 1);
tsn[j] = byH(_hstT, j, _tsnT);
pcd[j].y += inSD(i, tsn[j]);
totReqNgi[j] += inSDbyH(_hstT, j, i, 1);
}
toA += inSD(i, _rttR);
toX += inSD(i, _tsnT);
toN += inSD(i, rq2[i].N);
toR += inSD(i, rq3[i].R);
}
for (i = 0; i < 4; i++) {
pcd2[i].y /= totReqAng[i];
pcd[i].y /= totReqNgi[i];
}
var tpA = ((rqEx / (dur / 1000)) | 0) + 1,
tpX = ((tpA * toA / toX) | 0) + 1,
tpN = ((tpX * toX / toN) | 0) + 1,
tpR = ((tpN * toN / toR) | 0) + 1;
for (i = 0; i < hg.length; i++) {
var ix = ((rqEx * hg[i][0] / 100) | 0) - 1;
hg[i][1] = rq0[ix].A;
hg[i][2] = rq1[ix].X;
hg[i][3] = rq2[ix].N;
hg[i][4] = rq3[ix].R;
}
//
// Calculating HDR Histogram
//
var oRT = t.hS.post(_s_HURL, JSON.stringify(hdPD)).subscribe(
function(re) {
for (var n = 0; n < re.chart.length; n++) {
var idx = ((re.chart[n].percentile * t.rOK / 100) | 0) - 1;
lcd[0].values.push({
x: re.chart[n].percentile,
y: re.chart[n].value
});
lcd[1].values.push({
x: re.chart[n].percentile,
y: rq0[(idx < 0) ? 0 : idx].A
});
}
},
function(e) {
},
function() {
t.lcd = lcd;
oRT.unsubscribe();
t.clc = false;
t.run = false;
t.lE = false;
}
);
//
// Set Angular view variables
//
sGA(_s_SIM, 'E', 'T', tpA);
return [bcd,
pcd,
pcd2,
tpA,
tpX,
tpN,
tpR,
hg];
},
//// Create Live Events matrix
cLE = function() {
var lva = [], a0 = [], a01 = [], a1 = [], a12 = [], a2 = [];
for (var i = 0; i < 32; i++) {
a0[i] = 0;
a01[i] = i < 11 ? 0 : 1;
a1[i] = 1;
a12[i] = i < 22 ? 1 : 2;
a2[i] = 2;
}
for (i = 0; i < 5; i++) {
lva.push(a0.slice(0));
}
lva.push(a01);
for (i = 0; i < 4; i++) {
lva.push(a1.slice(0));
}
lva.push(a12);
for (i = 0; i < 5; i++) {
lva.push(a2.slice(0));
}
return lva;
};
//// Constructor
function AppSimulator (HTTPService, DOMSanitizer) {
//
// Initialize services
//
this.hS = HTTPService;
this.snS = DOMSanitizer;
//
// View execution parameters
//
this.sD(false);
//
// View presentation variables - reference links
//
this.links = iRL(this);
//
// Charts configuration and initialization
//
this.bco = {
chart: {
type: 'multiBarChart',
showControls: false,
height: 400,
margin: {
top: 20,
right: 20,
bottom: 20,
left: 45
},
x: function(d) {return d.label;},
y: function(d) {return d.value;},
clipEdge: true,
stacked: true,
showXAxis: false,
duration: 500,
xAxis: {
showMaxMin: false
},
yAxis: {
tickFormat: function(d) {
return d3.format('d')(d);
}
}
}
};
this.lco = {
chart: {
type: 'lineWithFocusChart',
showControls: false,
height: 400,
showLegend: true,
clipEdge: true,
duration: 500,
margin: {
top: 20,
right: 20,
bottom: 40,
left: 55
},
x: function(d) { return d.x; },
y: function(d) { return d.y; },
useInteractiveGuideline: true,
xAxis: {
axisLabel: 'Percentile (%)'
},
yAxis: {
axisLabel: 'AngularJS Latency (ms)',
axisLabelDistance: -10,
rotateYLabel: true
},
brushExtent: [75,
100]
}
};
this.pco = cP('nginX');
this.pco2 = cP('AngularJS');
//
// Live Events socket variables and configuration
//
this.lE = false;
this.gDS = ['text-muted',
'text-primary',
'text-muted',
'text-danger'];
this.oleMx = cLE();
//
// View execution variables
//
this.rVEV();
this.run = false;
}
AppSimulator.parameters = [
app.HTTPService,
ng.platformBrowser.DomSanitizationService
];
AppSimulator.annotations = [
new ng.core.Component({
selector: 'n-c-s',
templateUrl: 'simulator.html',
providers: [
app.HTTPService,
ng.http.HTTP_PROVIDERS,
ng.platformBrowser.BROWSER_SANITIZATION_PROVIDERS
],
directives: [nvD3]
})
];
AppSimulator.prototype.safeUrl = function(u) {
return this.snS.bypassSecurityTrustResourceUrl(u);
};
//
// Configuration & Initialization methods
//
//// resetViewExecVariables
AppSimulator.prototype.rVEV = function() {
this.rER = 0;
this.rOK = 0;
this.rqCh = 0;
this.sRe = false;
this.clc = false;
this.leMx = this.oleMx.slice(0);
};
//
// UI related methods
//
//// setMethodParameters
AppSimulator.prototype.sMP = function(p) {
var m = this.iD ? 0 : 1;
this.rqCt = _a_PRE[p][m][0];
this.rqDu = _a_PRE[p][m][1];
this.rqIn = _a_PRE[p][m][2];
this.rqCn = _a_PRE[p][m][3];
sGA(_s_SIM, _s_CFG, _a_PRE[p][2], 0);
};
//// setDuration or setRequests
AppSimulator.prototype.sD = function(m) {
this.iD = m;
this.sMP(0);
};
//// getSimulationMethod
AppSimulator.prototype.gSM = function() {
return this.iD ? _s_STA : _s_STR;
};
//// onRefLinkClick
AppSimulator.prototype.oRLC = function(t, d) {
sGA('R', t, d, 0);
};
//// showRef
AppSimulator.prototype.shR = function() {
this.sRe = !this.sRe;
if (this.sRe) {
this.lE = false;
dLE();
}
};
//// showLive
AppSimulator.prototype.shL = function() {
this.lE = !this.lE;
if (this.lE) {
aLE(this.leMx);
this.sRe = false;
} else {
dLE();
}
};
//// percValue
AppSimulator.prototype.pV = function(o, c) {
return (o * 100 / c) | 0;
};
//// calcPosition
AppSimulator.prototype.cP = function(o, h) {
return (o * h / 100) | 0;
};
//// getDurationRequests
AppSimulator.prototype.gDR = function(d, c, i) {
var tot = (d * 1000 * c / i) | 0;
return tot - (tot % c);
};
//// getDurationThroughput
AppSimulator.prototype.gDT = function(d, c, i) {
return (this.gDR(d, c, i) / d) | 0;
};
//
// Execution control methods
//
//// startSimulator
AppSimulator.prototype.sSi = function() {
////
//// Initialize execution variables - once for each execution
//// all first time initialization performed on constructor function
////
//
// Save execution parameters & Reset Live Events socket variables
//
this.exM = this.gSM();
this.exiD = this.exM === _s_STA;
this.exR = this.rqCt;
this.exD = this.rqDu;
this.exI = this.rqIn;
this.exC = this.rqCn;
this.exmR = this.gDR(this.rqDu,this.rqCn,this.rqIn);
//
// Reset execution scope variables
//
this.dur = 0;
//
// Reset view execution variables
//
this.rVEV();
this.run = true;
//
// Reset view presentation variables - control
//
this.shL();
//
// Switch among simulation methods (stress or duration)
//
if (this.iD) {
this.rqCt = this.exmR|0;
}
var aR = pRS(this);
this.oT = aR[1];
tHr(this.iD, this, this.rqCt, this.rqCn, this.rqDu, this.rqIn, aR[0], this.clc);
};
return AppSimulator;
})();
})(window.app || (window.app = {}));
| Thread info on requests
| app.simulator.js | Thread info on requests | <ide><path>pp.simulator.js
<ide> oR1(t, re[k], rs, rq, cc, pix);
<ide> }
<ide> },
<add> //// for STRESS
<ide> oR1 = function(t, re, rs, rq, cc, pix, eid) {
<ide> var res = re,
<ide> req = res.Q, |
|
Java | apache-2.0 | 831fbaf3d5db73bc7b2d422c807ae525831efe72 | 0 | gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle | /*
* Copyright 2016 the original author or authors.
*
* 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 org.gradle.api.plugins.quality;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileTree;
import org.gradle.api.internal.project.IsolatedAntBuilder;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.plugins.quality.internal.CheckstyleAction;
import org.gradle.api.plugins.quality.internal.CheckstyleActionParameters;
import org.gradle.api.plugins.quality.internal.CheckstyleReportsImpl;
import org.gradle.api.provider.Property;
import org.gradle.api.reporting.Reporting;
import org.gradle.api.resources.TextResource;
import org.gradle.api.tasks.CacheableTask;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.Console;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Nested;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.SourceTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.VerificationTask;
import org.gradle.jvm.toolchain.JavaLauncher;
import org.gradle.util.internal.ClosureBackedAction;
import org.gradle.workers.WorkQueue;
import org.gradle.workers.WorkerExecutor;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Runs Checkstyle against some source files.
*/
@CacheableTask
public class Checkstyle extends SourceTask implements VerificationTask, Reporting<CheckstyleReports> {
private FileCollection checkstyleClasspath;
private FileCollection classpath;
private TextResource config;
private Map<String, Object> configProperties = new LinkedHashMap<String, Object>();
private final CheckstyleReports reports;
private boolean ignoreFailures;
private int maxErrors;
private int maxWarnings = Integer.MAX_VALUE;
private boolean showViolations = true;
private final DirectoryProperty configDirectory;
private final Property<JavaLauncher> javaLauncher;
private final Property<String> minHeapSize;
private final Property<String> maxHeapSize;
public Checkstyle() {
this.configDirectory = getObjectFactory().directoryProperty();
this.reports = getObjectFactory().newInstance(CheckstyleReportsImpl.class, this);
this.javaLauncher = getObjectFactory().property(JavaLauncher.class);
this.minHeapSize = getObjectFactory().property(String.class);
this.maxHeapSize = getObjectFactory().property(String.class);
}
/**
* The Checkstyle configuration file to use.
*/
@Internal
public File getConfigFile() {
return getConfig() == null ? null : getConfig().asFile();
}
/**
* The Checkstyle configuration file to use.
*/
public void setConfigFile(File configFile) {
setConfig(getProject().getResources().getText().fromFile(configFile));
}
@Inject
protected ObjectFactory getObjectFactory() {
throw new UnsupportedOperationException();
}
@Inject
@Deprecated
public IsolatedAntBuilder getAntBuilder() {
throw new UnsupportedOperationException();
}
@Inject
public WorkerExecutor getWorkerExecutor() {
throw new UnsupportedOperationException();
}
/**
* Configures the reports to be generated by this task.
*
* The contained reports can be configured by name and closures. Example:
*
* <pre>
* checkstyleTask {
* reports {
* html {
* destination "build/checkstyle.html"
* }
* }
* }
* </pre>
*
* @param closure The configuration
* @return The reports container
*/
@Override
@SuppressWarnings("rawtypes")
public CheckstyleReports reports(@DelegatesTo(value = CheckstyleReports.class, strategy = Closure.DELEGATE_FIRST) Closure closure) {
return reports(new ClosureBackedAction<>(closure));
}
/**
* Configures the reports to be generated by this task.
*
* The contained reports can be configured by name and closures. Example:
*
* <pre>
* checkstyleTask {
* reports {
* html {
* destination "build/checkstyle.html"
* }
* }
* }
* </pre>
*
* @param configureAction The configuration
* @return The reports container
* @since 3.0
*/
@Override
public CheckstyleReports reports(Action<? super CheckstyleReports> configureAction) {
configureAction.execute(reports);
return reports;
}
/**
* JavaLauncher for toolchain support.
*
* @since 7.5
*/
@Incubating
@Nested
public Property<JavaLauncher> getJavaLauncher() {
return javaLauncher;
}
@TaskAction
public void run() {
runWithProcessIsolation();
}
private void runWithProcessIsolation() {
WorkQueue workQueue = getWorkerExecutor().processIsolation(spec -> {
spec.getForkOptions().setMinHeapSize(minHeapSize.getOrNull());
spec.getForkOptions().setMaxHeapSize(maxHeapSize.getOrNull());
spec.getForkOptions().setExecutable(javaLauncher.get().getExecutablePath().getAsFile().getAbsolutePath());
spec.getClasspath().from(getCheckstyleClasspath());
});
workQueue.submit(CheckstyleAction.class, this::setupParameters);
}
private void setupParameters(CheckstyleActionParameters parameters) {
parameters.getConfig().set(getConfigFile());
parameters.getMaxErrors().set(getMaxErrors());
parameters.getMaxWarnings().set(getMaxWarnings());
parameters.getIgnoreFailures().set(getIgnoreFailures());
parameters.getConfigDirectory().set(getConfigDirectory());
parameters.getShowViolations().set(isShowViolations());
parameters.getSource().setFrom(getSource());
parameters.getIsHtmlRequired().set(getReports().getHtml().getRequired());
parameters.getIsXmlRequired().set(getReports().getXml().getRequired());
parameters.getXmlOuputLocation().set(getReports().getXml().getOutputLocation());
parameters.getHtmlOuputLocation().set(getReports().getHtml().getOutputLocation());
parameters.getTemporaryDir().set(getTemporaryDir());
parameters.getConfigProperties().set(getConfigProperties());
TextResource stylesheetString = getReports().getHtml().getStylesheet();
if (stylesheetString != null) {
parameters.getStylesheetString().set(stylesheetString.asString());
}
}
/**
* {@inheritDoc}
*
* <p>The sources for this task are relatively relocatable even though it produces output that
* includes absolute paths. This is a compromise made to ensure that results can be reused
* between different builds. The downside is that up-to-date results, or results loaded
* from cache can show different absolute paths than would be produced if the task was
* executed.</p>
*/
@Override
@PathSensitive(PathSensitivity.RELATIVE)
public FileTree getSource() {
return super.getSource();
}
/**
* The class path containing the Checkstyle library to be used.
*/
@Classpath
public FileCollection getCheckstyleClasspath() {
return checkstyleClasspath;
}
/**
* The class path containing the Checkstyle library to be used.
*/
public void setCheckstyleClasspath(FileCollection checkstyleClasspath) {
this.checkstyleClasspath = checkstyleClasspath;
}
/**
* The class path containing the compiled classes for the source files to be analyzed.
*/
@Classpath
public FileCollection getClasspath() {
return classpath;
}
/**
* The class path containing the compiled classes for the source files to be analyzed.
*/
public void setClasspath(FileCollection classpath) {
this.classpath = classpath;
}
/**
* The Checkstyle configuration to use. Replaces the {@code configFile} property.
*
* @since 2.2
*/
@Nested
public TextResource getConfig() {
return config;
}
/**
* The Checkstyle configuration to use. Replaces the {@code configFile} property.
*
* @since 2.2
*/
public void setConfig(TextResource config) {
this.config = config;
}
/**
* The properties available for use in the configuration file. These are substituted into the configuration file.
*/
@Nullable
@Optional
@Input
public Map<String, Object> getConfigProperties() {
return configProperties;
}
/**
* The properties available for use in the configuration file. These are substituted into the configuration file.
*/
public void setConfigProperties(@Nullable Map<String, Object> configProperties) {
this.configProperties = configProperties;
}
/**
* Path to other Checkstyle configuration files.
* <p>
* This path will be exposed as the variable {@code config_loc} in Checkstyle's configuration files.
* </p>
*
* @return path to other Checkstyle configuration files
* @since 6.0
*/
@PathSensitive(PathSensitivity.RELATIVE)
@InputFiles
public DirectoryProperty getConfigDirectory() {
return configDirectory;
}
/**
* The reports to be generated by this task.
*/
@Override
@Nested
public final CheckstyleReports getReports() {
return reports;
}
/**
* Whether or not this task will ignore failures and continue running the build.
*
* @return true if failures should be ignored
*/
@Override
public boolean getIgnoreFailures() {
return ignoreFailures;
}
/**
* Whether this task will ignore failures and continue running the build.
*
* @return true if failures should be ignored
*/
@Internal
public boolean isIgnoreFailures() {
return ignoreFailures;
}
/**
* Whether this task will ignore failures and continue running the build.
*/
@Override
public void setIgnoreFailures(boolean ignoreFailures) {
this.ignoreFailures = ignoreFailures;
}
/**
* The maximum number of errors that are tolerated before breaking the build
* or setting the failure property.
*
* @return the maximum number of errors allowed
* @since 3.4
*/
@Input
public int getMaxErrors() {
return maxErrors;
}
/**
* Set the maximum number of errors that are tolerated before breaking the build.
*
* @param maxErrors number of errors allowed
* @since 3.4
*/
public void setMaxErrors(int maxErrors) {
this.maxErrors = maxErrors;
}
/**
* The maximum number of warnings that are tolerated before breaking the build
* or setting the failure property.
*
* @return the maximum number of warnings allowed
* @since 3.4
*/
@Input
public int getMaxWarnings() {
return maxWarnings;
}
/**
* Set the maximum number of warnings that are tolerated before breaking the build.
*
* @param maxWarnings number of warnings allowed
* @since 3.4
*/
public void setMaxWarnings(int maxWarnings) {
this.maxWarnings = maxWarnings;
}
/**
* Whether rule violations are to be displayed on the console.
*
* @return true if violations should be displayed on console
*/
@Console
public boolean isShowViolations() {
return showViolations;
}
/**
* Whether rule violations are to be displayed on the console.
*/
public void setShowViolations(boolean showViolations) {
this.showViolations = showViolations;
}
/**
* The minimum heap size for the Checkstyle worker process, if any.
* Supports the units megabytes (e.g. "512m") and gigabytes (e.g. "1g").
*
* @return The minimum heap size. Value should be null if the default minimum heap size should be used.
*
* @since 7.5
*/
@Incubating
@Optional
@Input
public Property<String> getMinHeapSize() {
return minHeapSize;
}
/**
* The maximum heap size for the Checkstyle worker process, if any.
* Supports the units megabytes (e.g. "512m") and gigabytes (e.g. "1g").
*
* @return The maximum heap size. Value should be null if the default maximum heap size should be used.
*
* @since 7.5
*/
@Incubating
@Optional
@Input
public Property<String> getMaxHeapSize() {
return maxHeapSize;
}
}
| subprojects/code-quality/src/main/groovy/org/gradle/api/plugins/quality/Checkstyle.java | /*
* Copyright 2016 the original author or authors.
*
* 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 org.gradle.api.plugins.quality;
import groovy.lang.Closure;
import groovy.lang.DelegatesTo;
import org.gradle.api.Action;
import org.gradle.api.Incubating;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileTree;
import org.gradle.api.internal.project.IsolatedAntBuilder;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.plugins.quality.internal.CheckstyleAction;
import org.gradle.api.plugins.quality.internal.CheckstyleActionParameters;
import org.gradle.api.plugins.quality.internal.CheckstyleReportsImpl;
import org.gradle.api.provider.Property;
import org.gradle.api.reporting.Reporting;
import org.gradle.api.resources.TextResource;
import org.gradle.api.tasks.CacheableTask;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.Console;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Nested;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.SourceTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.VerificationTask;
import org.gradle.jvm.toolchain.JavaLauncher;
import org.gradle.util.internal.ClosureBackedAction;
import org.gradle.workers.WorkQueue;
import org.gradle.workers.WorkerExecutor;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Runs Checkstyle against some source files.
*/
@CacheableTask
public class Checkstyle extends SourceTask implements VerificationTask, Reporting<CheckstyleReports> {
private FileCollection checkstyleClasspath;
private FileCollection classpath;
private TextResource config;
private Map<String, Object> configProperties = new LinkedHashMap<String, Object>();
private final CheckstyleReports reports;
private boolean ignoreFailures;
private int maxErrors;
private int maxWarnings = Integer.MAX_VALUE;
private boolean showViolations = true;
private final DirectoryProperty configDirectory;
private final Property<JavaLauncher> javaLauncher;
private final Property<String> minHeapSize;
private final Property<String> maxHeapSize;
public Checkstyle() {
this.configDirectory = getObjectFactory().directoryProperty();
this.reports = getObjectFactory().newInstance(CheckstyleReportsImpl.class, this);
this.javaLauncher = getObjectFactory().property(JavaLauncher.class);
this.minHeapSize = getObjectFactory().property(String.class);
this.maxHeapSize = getObjectFactory().property(String.class);
}
/**
* The Checkstyle configuration file to use.
*/
@Internal
public File getConfigFile() {
return getConfig() == null ? null : getConfig().asFile();
}
/**
* The Checkstyle configuration file to use.
*/
public void setConfigFile(File configFile) {
setConfig(getProject().getResources().getText().fromFile(configFile));
}
@Inject
protected ObjectFactory getObjectFactory() {
throw new UnsupportedOperationException();
}
@Inject
@Deprecated
public IsolatedAntBuilder getAntBuilder() {
throw new UnsupportedOperationException();
}
@Inject
public WorkerExecutor getWorkerExecutor() {
throw new UnsupportedOperationException();
}
/**
* Configures the reports to be generated by this task.
*
* The contained reports can be configured by name and closures. Example:
*
* <pre>
* checkstyleTask {
* reports {
* html {
* destination "build/checkstyle.html"
* }
* }
* }
* </pre>
*
* @param closure The configuration
* @return The reports container
*/
@Override
@SuppressWarnings("rawtypes")
public CheckstyleReports reports(@DelegatesTo(value = CheckstyleReports.class, strategy = Closure.DELEGATE_FIRST) Closure closure) {
return reports(new ClosureBackedAction<>(closure));
}
/**
* Configures the reports to be generated by this task.
*
* The contained reports can be configured by name and closures. Example:
*
* <pre>
* checkstyleTask {
* reports {
* html {
* destination "build/checkstyle.html"
* }
* }
* }
* </pre>
*
* @param configureAction The configuration
* @return The reports container
* @since 3.0
*/
@Override
public CheckstyleReports reports(Action<? super CheckstyleReports> configureAction) {
configureAction.execute(reports);
return reports;
}
/**
* JavaLauncher for toolchain support.
*
* @since 7.5
*/
@Incubating
@Nested
public Property<JavaLauncher> getJavaLauncher() {
return javaLauncher;
}
@TaskAction
public void run() {
runWithProcessIsolation();
}
private void runWithProcessIsolation() {
WorkQueue workQueue = getWorkerExecutor().processIsolation(spec -> {
spec.getForkOptions().setMinHeapSize(minHeapSize.getOrNull());
spec.getForkOptions().setMaxHeapSize(maxHeapSize.getOrNull());
spec.getForkOptions().setExecutable(javaLauncher.get().getExecutablePath().getAsFile().getAbsolutePath());
spec.getClasspath().from(getCheckstyleClasspath());
});
workQueue.submit(CheckstyleAction.class, this::setupParameters);
}
private void setupParameters(CheckstyleActionParameters parameters) {
parameters.getConfig().set(getConfigFile());
parameters.getMaxErrors().set(getMaxErrors());
parameters.getMaxWarnings().set(getMaxWarnings());
parameters.getIgnoreFailures().set(getIgnoreFailures());
parameters.getConfigDirectory().set(getConfigDirectory());
parameters.getShowViolations().set(isShowViolations());
parameters.getSource().setFrom(getSource());
parameters.getIsHtmlRequired().set(getReports().getHtml().getRequired());
parameters.getIsXmlRequired().set(getReports().getXml().getRequired());
parameters.getXmlOuputLocation().set(getReports().getXml().getOutputLocation());
parameters.getHtmlOuputLocation().set(getReports().getHtml().getOutputLocation());
parameters.getTemporaryDir().set(getTemporaryDir());
parameters.getConfigProperties().set(getConfigProperties());
TextResource stylesheetString = getReports().getHtml().getStylesheet();
if (stylesheetString != null) {
parameters.getStylesheetString().set(stylesheetString.asString());
}
}
/**
* {@inheritDoc}
*
* <p>The sources for this task are relatively relocatable even though it produces output that
* includes absolute paths. This is a compromise made to ensure that results can be reused
* between different builds. The downside is that up-to-date results, or results loaded
* from cache can show different absolute paths than would be produced if the task was
* executed.</p>
*/
@Override
@PathSensitive(PathSensitivity.RELATIVE)
public FileTree getSource() {
return super.getSource();
}
/**
* The class path containing the Checkstyle library to be used.
*/
@Classpath
public FileCollection getCheckstyleClasspath() {
return checkstyleClasspath;
}
/**
* The class path containing the Checkstyle library to be used.
*/
public void setCheckstyleClasspath(FileCollection checkstyleClasspath) {
this.checkstyleClasspath = checkstyleClasspath;
}
/**
* The class path containing the compiled classes for the source files to be analyzed.
*/
@Classpath
public FileCollection getClasspath() {
return classpath;
}
/**
* The class path containing the compiled classes for the source files to be analyzed.
*/
public void setClasspath(FileCollection classpath) {
this.classpath = classpath;
}
/**
* The Checkstyle configuration to use. Replaces the {@code configFile} property.
*
* @since 2.2
*/
@Nested
public TextResource getConfig() {
return config;
}
/**
* The Checkstyle configuration to use. Replaces the {@code configFile} property.
*
* @since 2.2
*/
public void setConfig(TextResource config) {
this.config = config;
}
/**
* The properties available for use in the configuration file. These are substituted into the configuration file.
*/
@Nullable
@Optional
@Input
public Map<String, Object> getConfigProperties() {
return configProperties;
}
/**
* The properties available for use in the configuration file. These are substituted into the configuration file.
*/
public void setConfigProperties(@Nullable Map<String, Object> configProperties) {
this.configProperties = configProperties;
}
/**
* Path to other Checkstyle configuration files.
* <p>
* This path will be exposed as the variable {@code config_loc} in Checkstyle's configuration files.
* </p>
*
* @return path to other Checkstyle configuration files
* @since 6.0
*/
@PathSensitive(PathSensitivity.RELATIVE)
@InputFiles
public DirectoryProperty getConfigDirectory() {
return configDirectory;
}
/**
* The reports to be generated by this task.
*/
@Override
@Nested
public final CheckstyleReports getReports() {
return reports;
}
/**
* Whether or not this task will ignore failures and continue running the build.
*
* @return true if failures should be ignored
*/
@Override
public boolean getIgnoreFailures() {
return ignoreFailures;
}
/**
* Whether this task will ignore failures and continue running the build.
*
* @return true if failures should be ignored
*/
@Internal
public boolean isIgnoreFailures() {
return ignoreFailures;
}
/**
* Whether this task will ignore failures and continue running the build.
*/
@Override
public void setIgnoreFailures(boolean ignoreFailures) {
this.ignoreFailures = ignoreFailures;
}
/**
* The maximum number of errors that are tolerated before breaking the build
* or setting the failure property.
*
* @return the maximum number of errors allowed
* @since 3.4
*/
@Input
public int getMaxErrors() {
return maxErrors;
}
/**
* Set the maximum number of errors that are tolerated before breaking the build.
*
* @param maxErrors number of errors allowed
* @since 3.4
*/
public void setMaxErrors(int maxErrors) {
this.maxErrors = maxErrors;
}
/**
* The maximum number of warnings that are tolerated before breaking the build
* or setting the failure property.
*
* @return the maximum number of warnings allowed
* @since 3.4
*/
@Input
public int getMaxWarnings() {
return maxWarnings;
}
/**
* Set the maximum number of warnings that are tolerated before breaking the build.
*
* @param maxWarnings number of warnings allowed
* @since 3.4
*/
public void setMaxWarnings(int maxWarnings) {
this.maxWarnings = maxWarnings;
}
/**
* Whether rule violations are to be displayed on the console.
*
* @return true if violations should be displayed on console
*/
@Console
public boolean isShowViolations() {
return showViolations;
}
/**
* Whether rule violations are to be displayed on the console.
*/
public void setShowViolations(boolean showViolations) {
this.showViolations = showViolations;
}
/**
* The minimum heap size for the checkstyle worker process, if any.
* Supports the units megabytes (e.g. "512m") and gigabytes (e.g. "1g").
*
* @return The minimum heap size. Value should be null if the default minimum heap size should be used.
*
* @since 7.5
*/
@Incubating
@Optional
@Input
public Property<String> getMinHeapSize() {
return minHeapSize;
}
/**
* The maximum heap size for the checkstyle worker process, if any.
* Supports the units megabytes (e.g. "512m") and gigabytes (e.g. "1g").
*
* @return The maximum heap size. Value should be null if the default maximum heap size should be used.
*
* @since 7.5
*/
@Incubating
@Optional
@Input
public Property<String> getMaxHeapSize() {
return maxHeapSize;
}
}
| Change 'checkstyle worker' to 'Checkstyle worker' in JavaDoc comments
| subprojects/code-quality/src/main/groovy/org/gradle/api/plugins/quality/Checkstyle.java | Change 'checkstyle worker' to 'Checkstyle worker' in JavaDoc comments | <ide><path>ubprojects/code-quality/src/main/groovy/org/gradle/api/plugins/quality/Checkstyle.java
<ide> }
<ide>
<ide> /**
<del> * The minimum heap size for the checkstyle worker process, if any.
<add> * The minimum heap size for the Checkstyle worker process, if any.
<ide> * Supports the units megabytes (e.g. "512m") and gigabytes (e.g. "1g").
<ide> *
<ide> * @return The minimum heap size. Value should be null if the default minimum heap size should be used.
<ide> return minHeapSize;
<ide> }
<ide>
<del>
<del> /**
<del> * The maximum heap size for the checkstyle worker process, if any.
<add> /**
<add> * The maximum heap size for the Checkstyle worker process, if any.
<ide> * Supports the units megabytes (e.g. "512m") and gigabytes (e.g. "1g").
<ide> *
<ide> * @return The maximum heap size. Value should be null if the default maximum heap size should be used. |
|
Java | apache-2.0 | error: pathspec 'jautomata/src/main/java/net/jhoogland/jautomata/Validation.java' did not match any file(s) known to git
| 51aca71bb2609e6b6b490fd136c64a4d30c6ff9e | 1 | jasperhoogland/jautomata | package net.jhoogland.jautomata;
import java.util.HashSet;
import java.util.Set;
public class Validation
{
/**
*
* Checks if the <code>transitionsOutI</code> and <code>transitionsOutO</code> methods are compatible with the <code>transitionsOut</code> method.
*
*/
public static <I, O, K> void validateExtendedAutomaton(ExtendedTransducer<I, O, K> a, boolean checkReverse)
{
Set<I> inputLabels = new HashSet<I>();
Set<O> outputLabels = new HashSet<O>();
for (Object s : Automata.states(a))
{
for (Object t : a.transitionsOut(s))
{
TLabel<I, O> l = a.label(t);
I li = l.in();
O lo = l.out();
if (! a.transitionsOutI(s, li).contains(t))
{
System.err.println("Transition returned by transitionsOut(state), but not by transitionsOutI(state, inputLabel): " + t);
System.err.println("State: " + s );
System.err.println("Input label: " + li);
System.err.println("Transition: " + t);
throw new RuntimeException();
}
if (! a.transitionsOutO(s, lo).contains(t))
{
System.err.println("Transition returned by transitionsOut(state), but not by transitionsOutO(state, inputLabel): " + t);
System.err.println("State: " + s );
System.err.println("Output label: " + lo);
System.err.println("Transition: " + t);
throw new RuntimeException();
}
if (checkReverse)
{
inputLabels.add(li);
outputLabels.add(lo);
}
}
}
if (! checkReverse) return;
for (Object s : Automata.states(a))
{
for (I li : inputLabels) for (Object t : a.transitionsOutI(s, li))
{
if (! new HashSet<Object>(a.transitionsOut(s)).contains(t))
{
System.err.println("Transition returned by transitionsOutI(state, inputLabel), but not by transitionsOut(state):");
System.err.println("State: " + s );
System.err.println("Input label: " + li);
System.err.println("Transition: " + t);
throw new RuntimeException();
}
}
for (O lo : outputLabels) for (Object t : a.transitionsOutO(s, lo))
{
if (! new HashSet<Object>(a.transitionsOut(s)).contains(t))
{
System.err.println("Transition returned by transitionsOutO(state, outputLabel), but not by transitionsOut(state): " + t);
System.err.println("State: " + s );
System.err.println("Output label: " + lo);
System.err.println("Transition: " + t);
throw new RuntimeException();
}
}
}
}
}
| jautomata/src/main/java/net/jhoogland/jautomata/Validation.java | Validation method added for ExtendedTransducers. | jautomata/src/main/java/net/jhoogland/jautomata/Validation.java | Validation method added for ExtendedTransducers. | <ide><path>automata/src/main/java/net/jhoogland/jautomata/Validation.java
<add>package net.jhoogland.jautomata;
<add>
<add>import java.util.HashSet;
<add>import java.util.Set;
<add>
<add>public class Validation
<add>{
<add> /**
<add> *
<add> * Checks if the <code>transitionsOutI</code> and <code>transitionsOutO</code> methods are compatible with the <code>transitionsOut</code> method.
<add> *
<add> */
<add>
<add> public static <I, O, K> void validateExtendedAutomaton(ExtendedTransducer<I, O, K> a, boolean checkReverse)
<add> {
<add> Set<I> inputLabels = new HashSet<I>();
<add> Set<O> outputLabels = new HashSet<O>();
<add> for (Object s : Automata.states(a))
<add> {
<add> for (Object t : a.transitionsOut(s))
<add> {
<add> TLabel<I, O> l = a.label(t);
<add> I li = l.in();
<add> O lo = l.out();
<add> if (! a.transitionsOutI(s, li).contains(t))
<add> {
<add> System.err.println("Transition returned by transitionsOut(state), but not by transitionsOutI(state, inputLabel): " + t);
<add> System.err.println("State: " + s );
<add> System.err.println("Input label: " + li);
<add> System.err.println("Transition: " + t);
<add> throw new RuntimeException();
<add> }
<add> if (! a.transitionsOutO(s, lo).contains(t))
<add> {
<add> System.err.println("Transition returned by transitionsOut(state), but not by transitionsOutO(state, inputLabel): " + t);
<add> System.err.println("State: " + s );
<add> System.err.println("Output label: " + lo);
<add> System.err.println("Transition: " + t);
<add> throw new RuntimeException();
<add> }
<add> if (checkReverse)
<add> {
<add> inputLabels.add(li);
<add> outputLabels.add(lo);
<add> }
<add> }
<add> }
<add> if (! checkReverse) return;
<add> for (Object s : Automata.states(a))
<add> {
<add> for (I li : inputLabels) for (Object t : a.transitionsOutI(s, li))
<add> {
<add> if (! new HashSet<Object>(a.transitionsOut(s)).contains(t))
<add> {
<add> System.err.println("Transition returned by transitionsOutI(state, inputLabel), but not by transitionsOut(state):");
<add> System.err.println("State: " + s );
<add> System.err.println("Input label: " + li);
<add> System.err.println("Transition: " + t);
<add> throw new RuntimeException();
<add> }
<add> }
<add> for (O lo : outputLabels) for (Object t : a.transitionsOutO(s, lo))
<add> {
<add> if (! new HashSet<Object>(a.transitionsOut(s)).contains(t))
<add> {
<add> System.err.println("Transition returned by transitionsOutO(state, outputLabel), but not by transitionsOut(state): " + t);
<add> System.err.println("State: " + s );
<add> System.err.println("Output label: " + lo);
<add> System.err.println("Transition: " + t);
<add> throw new RuntimeException();
<add> }
<add> }
<add> }
<add> }
<add>} |
|
Java | mit | 45b7aa3836c95753e8ba343a64b961f87eff4d97 | 0 | ryanliang/BarcodeBooster | package edu.toronto.bb.unitest;
import java.util.Iterator;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import edu.toronto.bb.core.PhredScore;
import edu.toronto.bb.core.PhredScoreSequence;
public class PhredScoreSequenceTest {
String phredStr;
@Before
public void setUp() {
phredStr = "37 37 37 37 37 37 37 37 37 37 37 40 39 39 39 40 40 40 40 40 40 40 40 40 40 40 40 40 40 39 39 39 39 39 39 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 37 37 37 37 37 37 37 37" +
"\r\n" +
"37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 35 35 35 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37" +
"\r\n" +
"37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 35 33 33 32 30 26 27 12 11 11 11 11 0 11 11 11 11 11 18 11 11 11 12 12 13 16 16 16 18 13 18 18 20 22 16 16 16 16 16 16 18 16 16 18 11" +
"\r\n" +
"12 13 22 17 18 19 19 23 27 30 28 30 28 21 21 21 19 " +
"\r\n" ; // 197 scores
}
@Test
public void shouldReadPhredSequence() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
Iterator<PhredScore> itr = pss.iterator();
StringBuffer sb = new StringBuffer();
while (itr.hasNext()) {
sb.append(itr.next());
}
assertTrue(sb.length() > 0);
}
@Test
public void shouldGetAllScores() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
assertEquals(197, pss.getScores().size());
}
@Test
public void shouldGetScoreAtPosition() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
assertEquals(37, pss.scoreAt(0).getScoreValue());
assertEquals(19, pss.scoreAt(pss.getScores().size() - 1).getScoreValue());
assertEquals(40, pss.scoreAt(11).getScoreValue());
}
@Test
public void shouldSetScoreAtPosition() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
pss.setScoreAt(new PhredScore(7), 0);
assertEquals(7, pss.scoreAt(0).getScoreValue());
pss.setScoreAt(new PhredScore(7), 196);
assertEquals(7, pss.scoreAt(pss.getScores().size() - 1).getScoreValue());
pss.setScoreAt(new PhredScore(7), 12);
assertEquals(7, pss.scoreAt(12).getScoreValue());
}
@Test
public void shouldHanleSingleDigitScore() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
pss.setScoreAt(new PhredScore(7), 0);
assertEquals(0, pss.scoreAt(147).getScoreValue());
}
}
| test/edu/toronto/bb/unitest/PhredScoreSequenceTest.java | package edu.toronto.bb.unitest;
import java.util.Iterator;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import edu.toronto.bb.core.PhredScore;
import edu.toronto.bb.core.PhredScoreSequence;
public class PhredScoreSequenceTest {
String phredStr;
@Before
public void setUp() {
phredStr = "37 37 37 37 37 37 37 37 37 37 37 40 39 39 39 40 40 40 40 40 40 40 40 40 40 40 40 40 40 39 39 39 39 39 39 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 40 37 37 37 37 37 37 37 37" +
"\r\n" +
"37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 35 35 35 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37" +
"\r\n" +
"37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 35 33 33 32 30 26 27 12 11 11 11 11 0 11 11 11 11 11 18 11 11 11 12 12 13 16 16 16 18 13 18 18 20 22 16 16 16 16 16 16 18 16 16 18 11" +
"\r\n" +
"12 13 22 17 18 19 19 23 27 30 28 30 28 21 21 21 19 " +
"\r\n" ; // 197 scores
}
@Test
public void shouldReadPhredSequence() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
Iterator<PhredScore> itr = pss.iterator();
StringBuffer sb = new StringBuffer();
while (itr.hasNext()) {
sb.append(itr.next());
}
assertTrue(sb.length() > 0);
}
@Test
public void shouldGetAllScores() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
assertEquals(197, pss.getScores().size());
}
@Test
public void shouldGetScoreAtPosition() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
assertEquals(37, pss.scoreAt(0).getScoreValue());
assertEquals(19, pss.scoreAt(pss.getScores().size() - 1).getScoreValue());
assertEquals(40, pss.scoreAt(11).getScoreValue());
}
@Test
public void shouldSetScoreAtPosition() {
PhredScoreSequence pss = new PhredScoreSequence(phredStr);
pss.setScoreAt(new PhredScore(7), 0);
assertEquals(7, pss.scoreAt(0).getScoreValue());
pss.setScoreAt(new PhredScore(7), 196);
assertEquals(7, pss.scoreAt(pss.getScores().size() - 1).getScoreValue());
pss.setScoreAt(new PhredScore(7), 12);
assertEquals(7, pss.scoreAt(12).getScoreValue());
}
}
| Added test case for single digit score | test/edu/toronto/bb/unitest/PhredScoreSequenceTest.java | Added test case for single digit score | <ide><path>est/edu/toronto/bb/unitest/PhredScoreSequenceTest.java
<ide> pss.setScoreAt(new PhredScore(7), 12);
<ide> assertEquals(7, pss.scoreAt(12).getScoreValue());
<ide> }
<add>
<add> @Test
<add> public void shouldHanleSingleDigitScore() {
<add> PhredScoreSequence pss = new PhredScoreSequence(phredStr);
<add>
<add> pss.setScoreAt(new PhredScore(7), 0);
<add> assertEquals(0, pss.scoreAt(147).getScoreValue());
<add>
<add> }
<ide>
<ide> } |
|
Java | lgpl-2.1 | 0428be6690d857fed8379b7798c93b1de0817094 | 0 | dd00/commandergenius,xyzz/vcmi-build,pelya/commandergenius,sexroute/commandergenius,sexroute/commandergenius,sexroute/commandergenius,def-/commandergenius,sexroute/commandergenius,sexroute/commandergenius,xyzz/vcmi-build,sexroute/commandergenius,dd00/commandergenius,pelya/commandergenius,dd00/commandergenius,def-/commandergenius,def-/commandergenius,xyzz/vcmi-build,def-/commandergenius,pelya/commandergenius,dd00/commandergenius,dd00/commandergenius,pelya/commandergenius,def-/commandergenius,xyzz/vcmi-build,sexroute/commandergenius,xyzz/vcmi-build,xyzz/vcmi-build,def-/commandergenius,def-/commandergenius,pelya/commandergenius,dd00/commandergenius,dd00/commandergenius,pelya/commandergenius,pelya/commandergenius,pelya/commandergenius,def-/commandergenius,dd00/commandergenius,xyzz/vcmi-build,sexroute/commandergenius | /*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.os.Environment;
import android.widget.TextView;
import org.apache.http.client.methods.*;
import org.apache.http.*;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.conn.*;
import org.apache.http.conn.params.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.security.cert.*;
import java.security.SecureRandom;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.util.zip.*;
import java.io.*;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.res.Resources;
import java.lang.String;
import android.text.SpannedString;
import android.app.AlertDialog;
import android.content.DialogInterface;
class CountingInputStream extends BufferedInputStream
{
private long bytesReadMark = 0;
private long bytesRead = 0;
public CountingInputStream(InputStream in, int size) {
super(in, size);
}
public CountingInputStream(InputStream in) {
super(in);
}
public long getBytesRead() {
return bytesRead;
}
public synchronized int read() throws IOException {
int read = super.read();
if (read >= 0) {
bytesRead++;
}
return read;
}
public synchronized int read(byte[] b, int off, int len) throws IOException {
int read = super.read(b, off, len);
if (read >= 0) {
bytesRead += read;
}
return read;
}
public synchronized long skip(long n) throws IOException {
long skipped = super.skip(n);
if (skipped >= 0) {
bytesRead += skipped;
}
return skipped;
}
public synchronized void mark(int readlimit) {
super.mark(readlimit);
bytesReadMark = bytesRead;
}
public synchronized void reset() throws IOException {
super.reset();
bytesRead = bytesReadMark;
}
}
class DataDownloader extends Thread
{
public static final String DOWNLOAD_FLAG_FILENAME = "libsdl-DownloadFinished-";
class StatusWriter
{
private TextView Status;
private MainActivity Parent;
private SpannedString oldText = new SpannedString("");
public StatusWriter( TextView _Status, MainActivity _Parent )
{
Status = _Status;
Parent = _Parent;
}
public void setParent( TextView _Status, MainActivity _Parent )
{
synchronized(DataDownloader.this) {
Status = _Status;
Parent = _Parent;
setText( oldText.toString() );
}
}
public void setText(final String str)
{
class Callback implements Runnable
{
public TextView Status;
public SpannedString text;
public void run()
{
Status.setText(text);
}
}
synchronized(DataDownloader.this) {
Callback cb = new Callback();
oldText = new SpannedString(str);
cb.text = new SpannedString(str);
cb.Status = Status;
if( Parent != null && Status != null )
Parent.runOnUiThread(cb);
}
}
}
public DataDownloader( MainActivity _Parent, TextView _Status )
{
Parent = _Parent;
Status = new StatusWriter( _Status, _Parent );
//Status.setText( "Connecting to " + Globals.DataDownloadUrl );
outFilesDir = Globals.DataDir;
DownloadComplete = false;
this.start();
}
public void setStatusField(TextView _Status)
{
synchronized(this) {
Status.setParent( _Status, Parent );
}
}
@Override
public void run()
{
Parent.keyListener = new BackKeyListener(Parent);
String [] downloadFiles = Globals.DataDownloadUrl;
int total = 0;
int count = 0;
for( int i = 0; i < downloadFiles.length; i++ )
{
if( downloadFiles[i].length() > 0 &&
( Globals.OptionalDataDownload.length > i && Globals.OptionalDataDownload[i] ) ||
( Globals.OptionalDataDownload.length <= i && downloadFiles[i].indexOf("!") == 0 ) )
total += 1;
}
for( int i = 0; i < downloadFiles.length; i++ )
{
if( downloadFiles[i].length() > 0 &&
( Globals.OptionalDataDownload.length > i && Globals.OptionalDataDownload[i] ) ||
( Globals.OptionalDataDownload.length <= i && downloadFiles[i].indexOf("!") == 0 ) )
{
if( ! DownloadDataFile(downloadFiles[i], DOWNLOAD_FLAG_FILENAME + String.valueOf(i) + ".flag", count+1, total, i) )
{
DownloadFailed = true;
return;
}
count += 1;
}
}
DownloadComplete = true;
Parent.keyListener = null;
initParent();
}
public boolean DownloadDataFile(final String DataDownloadUrl, final String DownloadFlagFileName, int downloadCount, int downloadTotal, int downloadIndex)
{
DownloadCanBeResumed = false;
Resources res = Parent.getResources();
String [] downloadUrls = DataDownloadUrl.split("[|]");
if( downloadUrls.length < 2 )
{
Log.i("SDL", "Error: download string invalid: '" + DataDownloadUrl + "', your AndroidAppSettigns.cfg is broken");
Status.setText( res.getString(R.string.error_dl_from, DataDownloadUrl) );
return false;
}
boolean forceOverwrite = false;
String path = getOutFilePath(DownloadFlagFileName);
InputStream checkFile = null;
try {
checkFile = new FileInputStream( path );
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) { };
if( checkFile != null )
{
try {
byte b[] = new byte[ Globals.DataDownloadUrl[downloadIndex].getBytes("UTF-8").length + 1 ];
int readed = checkFile.read(b);
String compare = "";
if( readed > 0 )
compare = new String( b, 0, readed, "UTF-8" );
boolean matched = false;
//Log.i("SDL", "Read URL: '" + compare + "'");
for( int i = 1; i < downloadUrls.length; i++ )
{
//Log.i("SDL", "Comparing: '" + downloadUrls[i] + "'");
if( compare.compareTo(downloadUrls[i]) == 0 )
matched = true;
}
//Log.i("SDL", "Matched: " + String.valueOf(matched));
if( ! matched )
throw new IOException();
Status.setText( res.getString(R.string.download_unneeded) );
return true;
} catch ( IOException e ) {
forceOverwrite = true;
new File(path).delete();
}
}
checkFile = null;
// Create output directory (not necessary for phone storage)
Log.i("SDL", "Downloading data to: '" + outFilesDir + "'");
try {
File outDir = new File( outFilesDir );
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
OutputStream out = new FileOutputStream( getOutFilePath(".nomedia") );
out.flush();
out.close();
}
catch( SecurityException e ) {}
catch( FileNotFoundException e ) {}
catch( IOException e ) {};
HttpResponse response = null, responseError = null;
HttpGet request;
long totalLen = 0;
CountingInputStream stream;
byte[] buf = new byte[16384];
boolean DoNotUnzip = false;
boolean FileInAssets = false;
String url = "";
long partialDownloadLen = 0;
int downloadUrlIndex = 1;
while( downloadUrlIndex < downloadUrls.length )
{
Log.i("SDL", "Processing download " + downloadUrls[downloadUrlIndex]);
url = new String(downloadUrls[downloadUrlIndex]);
DoNotUnzip = false;
if(url.indexOf(":") == 0)
{
path = getOutFilePath(url.substring( 1, url.indexOf(":", 1) ));
url = url.substring( url.indexOf(":", 1) + 1 );
DoNotUnzip = true;
DownloadCanBeResumed = true;
File partialDownload = new File( path );
if( partialDownload.exists() && !partialDownload.isDirectory() && !forceOverwrite )
partialDownloadLen = partialDownload.length();
}
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.connecting_to, url) );
if( url.indexOf("http://") == -1 && url.indexOf("https://") == -1 ) // File inside assets
{
InputStream stream1 = null;
try {
stream1 = Parent.getAssets().open(url);
stream1.close();
} catch( Exception e ) {
try {
stream1 = Parent.getAssets().open(url + "000");
stream1.close();
} catch( Exception ee ) {
Log.i("SDL", "Failed to open file in assets: " + url);
downloadUrlIndex++;
continue;
}
}
FileInAssets = true;
Log.i("SDL", "Fetching file from assets: " + url);
break;
}
else
{
Log.i("SDL", "Connecting to: " + url);
request = new HttpGet(url);
request.addHeader("Accept", "*/*");
if( partialDownloadLen > 0 ) {
request.addHeader("Range", "bytes=" + partialDownloadLen + "-");
Log.i("SDL", "Trying to resume download at pos " + partialDownloadLen);
}
try {
DefaultHttpClient client = HttpWithDisabledSslCertCheck();
client.getParams().setBooleanParameter("http.protocol.handle-redirects", true);
response = client.execute(request);
} catch (IOException e) {
Log.i("SDL", "Failed to connect to " + url);
downloadUrlIndex++;
};
if( response != null )
{
if( response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 206 )
{
Log.i("SDL", "Failed to connect to " + url + " with error " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
responseError = response;
response = null;
downloadUrlIndex++;
}
else
break;
}
}
}
if( FileInAssets )
{
int multipartCounter = 0;
InputStream multipart = null;
while( true )
{
try {
// Make string ".zip000", ".zip001" etc for multipart archives
String url1 = url + String.format("%03d", multipartCounter);
CountingInputStream stream1 = new CountingInputStream(Parent.getAssets().open(url1), 8192);
while( stream1.skip(65536) > 0 ) { };
totalLen += stream1.getBytesRead();
stream1.close();
InputStream s = Parent.getAssets().open(url1);
if( multipart == null )
multipart = s;
else
multipart = new SequenceInputStream(multipart, s);
Log.i("SDL", "Multipart archive found: " + url1);
} catch( IOException e ) {
break;
}
multipartCounter += 1;
}
if( multipart != null )
stream = new CountingInputStream(multipart, 8192);
else
{
try {
stream = new CountingInputStream(Parent.getAssets().open(url), 8192);
while( stream.skip(65536) > 0 ) { };
totalLen += stream.getBytesRead();
stream.close();
stream = new CountingInputStream(Parent.getAssets().open(url), 8192);
} catch( IOException e ) {
Log.i("SDL", "Unpacking from assets '" + url + "' - error: " + e.toString());
Status.setText( res.getString(R.string.error_dl_from, url) );
return false;
}
}
}
else
{
if( response == null )
{
Log.i("SDL", "Error connecting to " + url);
Status.setText( res.getString(R.string.failed_connecting_to, url) + (responseError == null ? "" : ": " + responseError.getStatusLine().getStatusCode() + " " + responseError.getStatusLine().getReasonPhrase()) );
return false;
}
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_from, url) );
totalLen = response.getEntity().getContentLength();
try {
stream = new CountingInputStream(response.getEntity().getContent(), 8192);
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_dl_from, url) );
return false;
}
}
long updateStatusTime = 0;
if(DoNotUnzip)
{
Log.i("SDL", "Saving file '" + path + "'");
OutputStream out = null;
try {
try {
File outDir = new File( path.substring(0, path.lastIndexOf("/") ));
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
if( partialDownloadLen > 0 )
{
try {
Header[] range = response.getHeaders("Content-Range");
if( range.length > 0 && range[0].getValue().indexOf("bytes") == 0 )
{
//Log.i("SDL", "Resuming download of file '" + path + "': Content-Range: " + range[0].getValue());
String[] skippedBytes = range[0].getValue().split("/")[0].split("-")[0].split(" ");
if( skippedBytes.length >= 2 && Long.parseLong(skippedBytes[1]) == partialDownloadLen )
{
out = new FileOutputStream( path, true );
Log.i("SDL", "Resuming download of file '" + path + "' at pos " + partialDownloadLen);
}
}
else
Log.i("SDL", "Server does not support partial downloads. " + (range.length == 0 ? "" : range[0].getValue()));
} catch (Exception e) { }
}
if( out == null )
{
out = new FileOutputStream( path );
partialDownloadLen = 0;
}
} catch( FileNotFoundException e ) {
Log.i("SDL", "Saving file '" + path + "' - error creating output file: " + e.toString());
} catch( SecurityException e ) {
Log.i("SDL", "Saving file '" + path + "' - error creating output file: " + e.toString());
};
if( out == null )
{
Status.setText( res.getString(R.string.error_write, path) );
Log.i("SDL", "Saving file '" + path + "' - error creating output file");
return false;
}
try {
int len = stream.read(buf);
while (len >= 0)
{
if(len > 0)
out.write(buf, 0, len);
len = stream.read(buf);
float percent = 0.0f;
if( totalLen > 0 )
percent = (stream.getBytesRead() + partialDownloadLen) * 100.0f / (totalLen + partialDownloadLen);
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
}
out.flush();
out.close();
out = null;
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
Log.i("SDL", "Saving file '" + path + "' - error writing: " + e.toString());
return false;
}
Log.i("SDL", "Saving file '" + path + "' done");
}
else
{
Log.i("SDL", "Reading from zip file '" + url + "'");
ZipInputStream zip = new ZipInputStream(stream);
String extpath = getOutFilePath("");
while(true)
{
ZipEntry entry = null;
try {
entry = zip.getNextEntry();
if( entry != null )
Log.i("SDL", "Reading from zip file '" + url + "' entry '" + entry.getName() + "'");
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_dl_from, url) );
Log.i("SDL", "Error reading from zip file '" + url + "': " + e.toString());
return false;
}
if( entry == null )
{
Log.i("SDL", "Reading from zip file '" + url + "' finished");
break;
}
if( entry.isDirectory() )
{
Log.i("SDL", "Creating dir '" + getOutFilePath(entry.getName()) + "'");
try {
File outDir = new File( getOutFilePath(entry.getName()) );
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
continue;
}
OutputStream out = null;
path = getOutFilePath(entry.getName());
float percent = 0.0f;
Log.i("SDL", "Saving file '" + path + "'");
try {
File outDir = new File( path.substring(0, path.lastIndexOf("/") ));
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
try {
CheckedInputStream check = new CheckedInputStream( new FileInputStream(path), new CRC32() );
while( check.read(buf, 0, buf.length) >= 0 ) {};
check.close();
if( check.getChecksum().getValue() != entry.getCrc() )
{
File ff = new File(path);
ff.delete();
throw new Exception();
}
Log.i("SDL", "File '" + path + "' exists and passed CRC check - not overwriting it");
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
continue;
} catch( Exception e ) { }
try {
out = new FileOutputStream( path );
} catch( FileNotFoundException e ) {
Log.i("SDL", "Saving file '" + path + "' - cannot create file: " + e.toString());
} catch( SecurityException e ) {
Log.i("SDL", "Saving file '" + path + "' - cannot create file: " + e.toString());
};
if( out == null )
{
Status.setText( res.getString(R.string.error_write, path) );
Log.i("SDL", "Saving file '" + path + "' - cannot create file");
return false;
}
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
//Unpacking local zip file into external storage
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path.replace(extpath, "")) );
}
try {
int len = zip.read(buf);
while (len >= 0)
{
if(len > 0)
out.write(buf, 0, len);
len = zip.read(buf);
percent = 0.0f;
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path.replace(extpath, "")) );
}
}
out.flush();
out.close();
out = null;
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
Log.i("SDL", "Saving file '" + path + "' - error writing or downloading: " + e.toString());
return false;
}
try {
long count = 0, ret = 0;
CheckedInputStream check = new CheckedInputStream( new FileInputStream(path), new CRC32() );
while( ret >= 0 )
{
count += ret;
ret = check.read(buf, 0, buf.length);
}
check.close();
if( check.getChecksum().getValue() != entry.getCrc() || count != entry.getSize() )
{
File ff = new File(path);
ff.delete();
Log.i("SDL", "Saving file '" + path + "' - CRC check failed, ZIP: " +
String.format("%x", entry.getCrc()) + " actual file: " + String.format("%x", check.getChecksum().getValue()) +
" file size in ZIP: " + entry.getSize() + " actual size " + count );
throw new Exception();
}
} catch( Exception e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
return false;
}
Log.i("SDL", "Saving file '" + path + "' done");
}
};
OutputStream out = null;
path = getOutFilePath(DownloadFlagFileName);
try {
out = new FileOutputStream( path );
out.write(downloadUrls[downloadUrlIndex].getBytes("UTF-8"));
out.flush();
out.close();
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) {
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
return false;
};
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_finished) );
try {
stream.close();
} catch( java.io.IOException e ) {
};
return true;
};
private void initParent()
{
class Callback implements Runnable
{
public MainActivity Parent;
public void run()
{
Parent.initSDL();
}
}
Callback cb = new Callback();
synchronized(this) {
cb.Parent = Parent;
if(Parent != null)
Parent.runOnUiThread(cb);
}
}
private String getOutFilePath(final String filename)
{
return outFilesDir + "/" + filename;
};
private static DefaultHttpClient HttpWithDisabledSslCertCheck()
{
return new DefaultHttpClient();
// This code does not work
/*
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient http = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
return http;
*/
}
public class BackKeyListener implements MainActivity.KeyEventsListener
{
MainActivity p;
public BackKeyListener(MainActivity _p)
{
p = _p;
}
public void onKeyEvent(final int keyCode)
{
if( DownloadFailed )
System.exit(1);
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.cancel_download));
builder.setMessage(p.getResources().getString(R.string.cancel_download) + (DownloadCanBeResumed ? " " + p.getResources().getString(R.string.cancel_download_resume) : ""));
builder.setPositiveButton(p.getResources().getString(R.string.yes), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
System.exit(1);
dialog.dismiss();
}
});
builder.setNegativeButton(p.getResources().getString(R.string.no), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
public StatusWriter Status;
public boolean DownloadComplete = false;
public boolean DownloadFailed = false;
public boolean DownloadCanBeResumed = false;
private MainActivity Parent;
private String outFilesDir = null;
}
| project/java/DataDownloader.java | /*
Simple DirectMedia Layer
Java source code (C) 2009-2012 Sergii Pylypenko
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
package net.sourceforge.clonekeenplus;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.os.Environment;
import android.widget.TextView;
import org.apache.http.client.methods.*;
import org.apache.http.*;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.conn.*;
import org.apache.http.conn.params.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.security.cert.*;
import java.security.SecureRandom;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.util.zip.*;
import java.io.*;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.res.Resources;
import java.lang.String;
import android.text.SpannedString;
import android.app.AlertDialog;
import android.content.DialogInterface;
class CountingInputStream extends BufferedInputStream
{
private long bytesReadMark = 0;
private long bytesRead = 0;
public CountingInputStream(InputStream in, int size) {
super(in, size);
}
public CountingInputStream(InputStream in) {
super(in);
}
public long getBytesRead() {
return bytesRead;
}
public synchronized int read() throws IOException {
int read = super.read();
if (read >= 0) {
bytesRead++;
}
return read;
}
public synchronized int read(byte[] b, int off, int len) throws IOException {
int read = super.read(b, off, len);
if (read >= 0) {
bytesRead += read;
}
return read;
}
public synchronized long skip(long n) throws IOException {
long skipped = super.skip(n);
if (skipped >= 0) {
bytesRead += skipped;
}
return skipped;
}
public synchronized void mark(int readlimit) {
super.mark(readlimit);
bytesReadMark = bytesRead;
}
public synchronized void reset() throws IOException {
super.reset();
bytesRead = bytesReadMark;
}
}
class DataDownloader extends Thread
{
public static final String DOWNLOAD_FLAG_FILENAME = "libsdl-DownloadFinished-";
class StatusWriter
{
private TextView Status;
private MainActivity Parent;
private SpannedString oldText = new SpannedString("");
public StatusWriter( TextView _Status, MainActivity _Parent )
{
Status = _Status;
Parent = _Parent;
}
public void setParent( TextView _Status, MainActivity _Parent )
{
synchronized(DataDownloader.this) {
Status = _Status;
Parent = _Parent;
setText( oldText.toString() );
}
}
public void setText(final String str)
{
class Callback implements Runnable
{
public TextView Status;
public SpannedString text;
public void run()
{
Status.setText(text);
}
}
synchronized(DataDownloader.this) {
Callback cb = new Callback();
oldText = new SpannedString(str);
cb.text = new SpannedString(str);
cb.Status = Status;
if( Parent != null && Status != null )
Parent.runOnUiThread(cb);
}
}
}
public DataDownloader( MainActivity _Parent, TextView _Status )
{
Parent = _Parent;
Status = new StatusWriter( _Status, _Parent );
//Status.setText( "Connecting to " + Globals.DataDownloadUrl );
outFilesDir = Globals.DataDir;
DownloadComplete = false;
this.start();
}
public void setStatusField(TextView _Status)
{
synchronized(this) {
Status.setParent( _Status, Parent );
}
}
@Override
public void run()
{
Parent.keyListener = new BackKeyListener(Parent);
String [] downloadFiles = Globals.DataDownloadUrl;
int total = 0;
int count = 0;
for( int i = 0; i < downloadFiles.length; i++ )
{
if( downloadFiles[i].length() > 0 &&
( Globals.OptionalDataDownload.length > i && Globals.OptionalDataDownload[i] ) ||
( Globals.OptionalDataDownload.length <= i && downloadFiles[i].indexOf("!") == 0 ) )
total += 1;
}
for( int i = 0; i < downloadFiles.length; i++ )
{
if( downloadFiles[i].length() > 0 &&
( Globals.OptionalDataDownload.length > i && Globals.OptionalDataDownload[i] ) ||
( Globals.OptionalDataDownload.length <= i && downloadFiles[i].indexOf("!") == 0 ) )
{
if( ! DownloadDataFile(downloadFiles[i], DOWNLOAD_FLAG_FILENAME + String.valueOf(i) + ".flag", count+1, total, i) )
{
DownloadFailed = true;
return;
}
count += 1;
}
}
DownloadComplete = true;
Parent.keyListener = null;
initParent();
}
public boolean DownloadDataFile(final String DataDownloadUrl, final String DownloadFlagFileName, int downloadCount, int downloadTotal, int downloadIndex)
{
DownloadCanBeResumed = false;
Resources res = Parent.getResources();
String [] downloadUrls = DataDownloadUrl.split("[|]");
if( downloadUrls.length < 2 )
{
Log.i("SDL", "Error: download string invalid: '" + DataDownloadUrl + "', your AndroidAppSettigns.cfg is broken");
Status.setText( res.getString(R.string.error_dl_from, DataDownloadUrl) );
return false;
}
boolean forceOverwrite = false;
String path = getOutFilePath(DownloadFlagFileName);
InputStream checkFile = null;
try {
checkFile = new FileInputStream( path );
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) { };
if( checkFile != null )
{
try {
byte b[] = new byte[ Globals.DataDownloadUrl[downloadIndex].getBytes("UTF-8").length + 1 ];
int readed = checkFile.read(b);
String compare = "";
if( readed > 0 )
compare = new String( b, 0, readed, "UTF-8" );
boolean matched = false;
//Log.i("SDL", "Read URL: '" + compare + "'");
for( int i = 1; i < downloadUrls.length; i++ )
{
//Log.i("SDL", "Comparing: '" + downloadUrls[i] + "'");
if( compare.compareTo(downloadUrls[i]) == 0 )
matched = true;
}
//Log.i("SDL", "Matched: " + String.valueOf(matched));
if( ! matched )
throw new IOException();
Status.setText( res.getString(R.string.download_unneeded) );
return true;
} catch ( IOException e ) {
forceOverwrite = true;
new File(path).delete();
}
}
checkFile = null;
// Create output directory (not necessary for phone storage)
Log.i("SDL", "Downloading data to: '" + outFilesDir + "'");
try {
File outDir = new File( outFilesDir );
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
OutputStream out = new FileOutputStream( getOutFilePath(".nomedia") );
out.flush();
out.close();
}
catch( SecurityException e ) {}
catch( FileNotFoundException e ) {}
catch( IOException e ) {};
HttpResponse response = null, responseError = null;
HttpGet request;
long totalLen = 0;
CountingInputStream stream;
byte[] buf = new byte[16384];
boolean DoNotUnzip = false;
boolean FileInAssets = false;
String url = "";
long partialDownloadLen = 0;
int downloadUrlIndex = 1;
while( downloadUrlIndex < downloadUrls.length )
{
Log.i("SDL", "Processing download " + downloadUrls[downloadUrlIndex]);
url = new String(downloadUrls[downloadUrlIndex]);
DoNotUnzip = false;
if(url.indexOf(":") == 0)
{
path = getOutFilePath(url.substring( 1, url.indexOf(":", 1) ));
url = url.substring( url.indexOf(":", 1) + 1 );
DoNotUnzip = true;
DownloadCanBeResumed = true;
File partialDownload = new File( path );
if( partialDownload.exists() && !partialDownload.isDirectory() && !forceOverwrite )
partialDownloadLen = partialDownload.length();
}
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.connecting_to, url) );
if( url.indexOf("http://") == -1 && url.indexOf("https://") == -1 ) // File inside assets
{
InputStream stream1 = null;
try {
stream1 = Parent.getAssets().open(url);
stream1.close();
} catch( Exception e ) {
try {
stream1 = Parent.getAssets().open(url + "000");
stream1.close();
} catch( Exception ee ) {
Log.i("SDL", "Failed to open file in assets: " + url);
downloadUrlIndex++;
continue;
}
}
FileInAssets = true;
Log.i("SDL", "Fetching file from assets: " + url);
break;
}
else
{
Log.i("SDL", "Connecting to: " + url);
request = new HttpGet(url);
request.addHeader("Accept", "*/*");
if( partialDownloadLen > 0 ) {
request.addHeader("Range", "bytes=" + partialDownloadLen + "-");
Log.i("SDL", "Trying to resume download at pos " + partialDownloadLen);
}
try {
DefaultHttpClient client = HttpWithDisabledSslCertCheck();
client.getParams().setBooleanParameter("http.protocol.handle-redirects", true);
response = client.execute(request);
} catch (IOException e) {
Log.i("SDL", "Failed to connect to " + url);
downloadUrlIndex++;
};
if( response != null )
{
if( response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 206 )
{
Log.i("SDL", "Failed to connect to " + url + " with error " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
responseError = response;
response = null;
downloadUrlIndex++;
}
else
break;
}
}
}
if( FileInAssets )
{
int multipartCounter = 0;
InputStream multipart = null;
while( true )
{
try {
// Make string ".zip000", ".zip001" etc for multipart archives
String url1 = url + String.format("%03d", multipartCounter);
CountingInputStream stream1 = new CountingInputStream(Parent.getAssets().open(url1), 8192);
while( stream1.skip(65536) > 0 ) { };
totalLen += stream1.getBytesRead();
stream1.close();
InputStream s = Parent.getAssets().open(url1);
if( multipart == null )
multipart = s;
else
multipart = new SequenceInputStream(multipart, s);
Log.i("SDL", "Multipart archive found: " + url1);
} catch( IOException e ) {
break;
}
multipartCounter += 1;
}
if( multipart != null )
stream = new CountingInputStream(multipart, 8192);
else
{
try {
stream = new CountingInputStream(Parent.getAssets().open(url), 8192);
while( stream.skip(65536) > 0 ) { };
totalLen += stream.getBytesRead();
stream.close();
stream = new CountingInputStream(Parent.getAssets().open(url), 8192);
} catch( IOException e ) {
Log.i("SDL", "Unpacking from assets '" + url + "' - error: " + e.toString());
Status.setText( res.getString(R.string.error_dl_from, url) );
return false;
}
}
}
else
{
if( response == null )
{
Log.i("SDL", "Error connecting to " + url);
Status.setText( res.getString(R.string.failed_connecting_to, url) + (responseError == null ? "" : ": " + responseError.getStatusLine().getStatusCode() + " " + responseError.getStatusLine().getReasonPhrase()) );
return false;
}
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_from, url) );
totalLen = response.getEntity().getContentLength();
try {
stream = new CountingInputStream(response.getEntity().getContent(), 8192);
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_dl_from, url) );
return false;
}
}
long updateStatusTime = 0;
if(DoNotUnzip)
{
Log.i("SDL", "Saving file '" + path + "'");
OutputStream out = null;
try {
try {
File outDir = new File( path.substring(0, path.lastIndexOf("/") ));
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
if( partialDownloadLen > 0 )
{
try {
Header[] range = response.getHeaders("Content-Range");
if( range.length > 0 && range[0].getValue().indexOf("bytes") == 0 )
{
//Log.i("SDL", "Resuming download of file '" + path + "': Content-Range: " + range[0].getValue());
String[] skippedBytes = range[0].getValue().split("/")[0].split("-")[0].split(" ");
if( skippedBytes.length >= 2 && Long.parseLong(skippedBytes[1]) == partialDownloadLen )
{
out = new FileOutputStream( path, true );
Log.i("SDL", "Resuming download of file '" + path + "' at pos " + partialDownloadLen);
}
}
else
Log.i("SDL", "Server does not support partial downloads. " + (range.length == 0 ? "" : range[0].getValue()));
} catch (Exception e) { }
}
if( out == null )
{
out = new FileOutputStream( path );
partialDownloadLen = 0;
}
} catch( FileNotFoundException e ) {
Log.i("SDL", "Saving file '" + path + "' - error creating output file: " + e.toString());
} catch( SecurityException e ) {
Log.i("SDL", "Saving file '" + path + "' - error creating output file: " + e.toString());
};
if( out == null )
{
Status.setText( res.getString(R.string.error_write, path) );
Log.i("SDL", "Saving file '" + path + "' - error creating output file");
return false;
}
try {
int len = stream.read(buf);
while (len >= 0)
{
if(len > 0)
out.write(buf, 0, len);
len = stream.read(buf);
float percent = 0.0f;
if( totalLen > 0 )
percent = (stream.getBytesRead() + partialDownloadLen) * 100.0f / (totalLen + partialDownloadLen);
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
}
out.flush();
out.close();
out = null;
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
Log.i("SDL", "Saving file '" + path + "' - error writing: " + e.toString());
return false;
}
Log.i("SDL", "Saving file '" + path + "' done");
}
else
{
Log.i("SDL", "Reading from zip file '" + url + "'");
ZipInputStream zip = new ZipInputStream(stream);
while(true)
{
ZipEntry entry = null;
try {
entry = zip.getNextEntry();
if( entry != null )
Log.i("SDL", "Reading from zip file '" + url + "' entry '" + entry.getName() + "'");
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_dl_from, url) );
Log.i("SDL", "Error reading from zip file '" + url + "': " + e.toString());
return false;
}
if( entry == null )
{
Log.i("SDL", "Reading from zip file '" + url + "' finished");
break;
}
if( entry.isDirectory() )
{
Log.i("SDL", "Creating dir '" + getOutFilePath(entry.getName()) + "'");
try {
File outDir = new File( getOutFilePath(entry.getName()) );
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
continue;
}
OutputStream out = null;
path = getOutFilePath(entry.getName());
float percent = 0.0f;
Log.i("SDL", "Saving file '" + path + "'");
try {
File outDir = new File( path.substring(0, path.lastIndexOf("/") ));
if( !(outDir.exists() && outDir.isDirectory()) )
outDir.mkdirs();
} catch( SecurityException e ) { };
try {
CheckedInputStream check = new CheckedInputStream( new FileInputStream(path), new CRC32() );
while( check.read(buf, 0, buf.length) >= 0 ) {};
check.close();
if( check.getChecksum().getValue() != entry.getCrc() )
{
File ff = new File(path);
ff.delete();
throw new Exception();
}
Log.i("SDL", "File '" + path + "' exists and passed CRC check - not overwriting it");
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
continue;
} catch( Exception e ) { }
try {
out = new FileOutputStream( path );
} catch( FileNotFoundException e ) {
Log.i("SDL", "Saving file '" + path + "' - cannot create file: " + e.toString());
} catch( SecurityException e ) {
Log.i("SDL", "Saving file '" + path + "' - cannot create file: " + e.toString());
};
if( out == null )
{
Status.setText( res.getString(R.string.error_write, path) );
Log.i("SDL", "Saving file '" + path + "' - cannot create file");
return false;
}
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
try {
int len = zip.read(buf);
while (len >= 0)
{
if(len > 0)
out.write(buf, 0, len);
len = zip.read(buf);
percent = 0.0f;
if( totalLen > 0 )
percent = stream.getBytesRead() * 100.0f / totalLen;
if( System.currentTimeMillis() > updateStatusTime + 1000 )
{
updateStatusTime = System.currentTimeMillis();
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
}
}
out.flush();
out.close();
out = null;
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
Log.i("SDL", "Saving file '" + path + "' - error writing or downloading: " + e.toString());
return false;
}
try {
long count = 0, ret = 0;
CheckedInputStream check = new CheckedInputStream( new FileInputStream(path), new CRC32() );
while( ret >= 0 )
{
count += ret;
ret = check.read(buf, 0, buf.length);
}
check.close();
if( check.getChecksum().getValue() != entry.getCrc() || count != entry.getSize() )
{
File ff = new File(path);
ff.delete();
Log.i("SDL", "Saving file '" + path + "' - CRC check failed, ZIP: " +
String.format("%x", entry.getCrc()) + " actual file: " + String.format("%x", check.getChecksum().getValue()) +
" file size in ZIP: " + entry.getSize() + " actual size " + count );
throw new Exception();
}
} catch( Exception e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
return false;
}
Log.i("SDL", "Saving file '" + path + "' done");
}
};
OutputStream out = null;
path = getOutFilePath(DownloadFlagFileName);
try {
out = new FileOutputStream( path );
out.write(downloadUrls[downloadUrlIndex].getBytes("UTF-8"));
out.flush();
out.close();
} catch( FileNotFoundException e ) {
} catch( SecurityException e ) {
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_write, path) + ": " + e.getMessage() );
return false;
};
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_finished) );
try {
stream.close();
} catch( java.io.IOException e ) {
};
return true;
};
private void initParent()
{
class Callback implements Runnable
{
public MainActivity Parent;
public void run()
{
Parent.initSDL();
}
}
Callback cb = new Callback();
synchronized(this) {
cb.Parent = Parent;
if(Parent != null)
Parent.runOnUiThread(cb);
}
}
private String getOutFilePath(final String filename)
{
return outFilesDir + "/" + filename;
};
private static DefaultHttpClient HttpWithDisabledSslCertCheck()
{
return new DefaultHttpClient();
// This code does not work
/*
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient http = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
return http;
*/
}
public class BackKeyListener implements MainActivity.KeyEventsListener
{
MainActivity p;
public BackKeyListener(MainActivity _p)
{
p = _p;
}
public void onKeyEvent(final int keyCode)
{
if( DownloadFailed )
System.exit(1);
AlertDialog.Builder builder = new AlertDialog.Builder(p);
builder.setTitle(p.getResources().getString(R.string.cancel_download));
builder.setMessage(p.getResources().getString(R.string.cancel_download) + (DownloadCanBeResumed ? " " + p.getResources().getString(R.string.cancel_download_resume) : ""));
builder.setPositiveButton(p.getResources().getString(R.string.yes), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
System.exit(1);
dialog.dismiss();
}
});
builder.setNegativeButton(p.getResources().getString(R.string.no), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
dialog.dismiss();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog)
{
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity(p);
alert.show();
}
}
public StatusWriter Status;
public boolean DownloadComplete = false;
public boolean DownloadFailed = false;
public boolean DownloadCanBeResumed = false;
private MainActivity Parent;
private String outFilesDir = null;
}
| Show shorter downlaod paths
| project/java/DataDownloader.java | Show shorter downlaod paths | <ide><path>roject/java/DataDownloader.java
<ide> {
<ide> Log.i("SDL", "Reading from zip file '" + url + "'");
<ide> ZipInputStream zip = new ZipInputStream(stream);
<add> String extpath = getOutFilePath("");
<ide>
<ide> while(true)
<ide> {
<ide>
<ide> if( totalLen > 0 )
<ide> percent = stream.getBytesRead() * 100.0f / totalLen;
<add> //Unpacking local zip file into external storage
<ide> if( System.currentTimeMillis() > updateStatusTime + 1000 )
<ide> {
<ide> updateStatusTime = System.currentTimeMillis();
<del> Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
<add> Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path.replace(extpath, "")) );
<ide> }
<ide>
<ide> try {
<ide> if( System.currentTimeMillis() > updateStatusTime + 1000 )
<ide> {
<ide> updateStatusTime = System.currentTimeMillis();
<del> Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path) );
<add> Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_progress, percent, path.replace(extpath, "")) );
<ide> }
<ide> }
<ide> out.flush(); |
|
JavaScript | mit | ba63cbd959162f162ec6b236630152b612e50d1e | 0 | AnthonyAstige/meteor,mjmasn/meteor,DAB0mB/meteor,chasertech/meteor,AnthonyAstige/meteor,DAB0mB/meteor,AnthonyAstige/meteor,Hansoft/meteor,jdivy/meteor,DAB0mB/meteor,chasertech/meteor,mjmasn/meteor,lorensr/meteor,chasertech/meteor,Hansoft/meteor,4commerce-technologies-AG/meteor,mjmasn/meteor,mjmasn/meteor,Hansoft/meteor,4commerce-technologies-AG/meteor,DAB0mB/meteor,jdivy/meteor,jdivy/meteor,jdivy/meteor,Hansoft/meteor,mjmasn/meteor,lorensr/meteor,jdivy/meteor,lorensr/meteor,DAB0mB/meteor,nuvipannu/meteor,AnthonyAstige/meteor,4commerce-technologies-AG/meteor,lorensr/meteor,Hansoft/meteor,jdivy/meteor,4commerce-technologies-AG/meteor,AnthonyAstige/meteor,nuvipannu/meteor,nuvipannu/meteor,chasertech/meteor,AnthonyAstige/meteor,nuvipannu/meteor,Hansoft/meteor,mjmasn/meteor,mjmasn/meteor,Hansoft/meteor,chasertech/meteor,chasertech/meteor,chasertech/meteor,4commerce-technologies-AG/meteor,nuvipannu/meteor,AnthonyAstige/meteor,nuvipannu/meteor,4commerce-technologies-AG/meteor,jdivy/meteor,AnthonyAstige/meteor,lorensr/meteor,lorensr/meteor,4commerce-technologies-AG/meteor,DAB0mB/meteor,lorensr/meteor,nuvipannu/meteor,DAB0mB/meteor | import assert from "assert";
import {isString, has, keys, each, map, without} from "underscore";
import {sha1, readAndWatchFileWithHash} from "../fs/watch.js";
import {matches as archMatches} from "../utils/archinfo.js";
import {findImportedModuleIdentifiers} from "./js-analyze.js";
import buildmessage from "../utils/buildmessage.js";
import LRU from "lru-cache";
import {Profile} from "../tool-env/profile.js";
import {SourceNode, SourceMapConsumer} from "source-map";
import {
pathJoin,
pathRelative,
pathNormalize,
pathDirname,
pathBasename,
pathExtname,
pathIsAbsolute,
statOrNull,
convertToOSPath,
convertToPosixPath,
} from "../fs/files.js";
const nativeModulesMap = Object.create(null);
const nativeNames = Object.keys(process.binding("natives"));
// Node 0.10 does not include process as a built-in module, but later
// versions of Node do, and we provide a stub for it on the client.
nativeNames.push("process");
nativeNames.forEach(id => {
if (id === "freelist" ||
id.startsWith("internal/")) {
return;
}
// When a native Node module is imported, we register a dependency on a
// meteor-node-stubs/deps/* module of the same name, so that the
// necessary stub modules will be included in the bundle. This alternate
// identifier will not be imported at runtime, but the modules it
// depends on are necessary for the original import to succeed.
nativeModulesMap[id] = "meteor-node-stubs/deps/" + id;
});
// Default handlers for well-known file extensions.
// Note that these function expect strings, not Buffer objects.
const defaultExtensionHandlers = {
".js"(dataString) {
// Strip any #! line from the beginning of the file.
return dataString.replace(/^#![^\n]*/, "");
},
".json"(dataString) {
return "module.exports = " +
JSON.stringify(JSON.parse(dataString), null, 2) +
";\n";
}
};
// Map from SHA (which is already calculated, so free for us)
// to the results of calling findImportedModuleIdentifiers.
// Each entry is an array of strings, and this is a case where
// the computation is expensive but the output is very small.
// The cache can be global because findImportedModuleIdentifiers
// is a pure function, and that way it applies across instances
// of ImportScanner (which do not persist across builds).
const IMPORT_SCANNER_CACHE = new LRU({
max: 1024*1024,
length(value) {
let total = 40; // size of key
value.forEach(str => { total += str.length; });
return total;
}
});
export default class ImportScanner {
constructor({
name,
bundleArch,
extensions = [".js", ".json"],
sourceRoot,
usedPackageNames = {},
nodeModulesPaths = [],
watchSet,
}) {
assert.ok(isString(sourceRoot));
this.name = name;
this.bundleArch = bundleArch;
this.extensions = extensions;
this.sourceRoot = sourceRoot;
this.usedPackageNames = usedPackageNames;
this.nodeModulesPaths = nodeModulesPaths;
this.watchSet = watchSet;
this.absPathToOutputIndex = Object.create(null);
this.allMissingNodeModules = Object.create(null);
this.outputFiles = [];
this._statCache = new Map;
this._pkgJsonCache = new Map;
}
_getFile(absPath) {
absPath = absPath.toLowerCase();
if (has(this.absPathToOutputIndex, absPath)) {
return this.outputFiles[this.absPathToOutputIndex[absPath]];
}
}
_addFile(absPath, file) {
absPath = absPath.toLowerCase();
if (! has(this.absPathToOutputIndex, absPath)) {
this.absPathToOutputIndex[absPath] =
this.outputFiles.push(file) - 1;
return file;
}
}
addInputFiles(files) {
files.forEach(file => {
const absPath = this._ensureSourcePath(file);
const dotExt = "." + file.type;
const dataString = file.data.toString("utf8");
file.dataString = defaultExtensionHandlers[dotExt](dataString);
if (! (file.data instanceof Buffer) ||
file.dataString !== dataString) {
file.data = new Buffer(file.dataString, "utf8");
}
// Files that are not eagerly evaluated (lazy) will only be included
// in the bundle if they are actually imported. Files that are
// eagerly evaluated are effectively "imported" as entry points.
file.imported = ! file.lazy;
file.installPath = this._getInstallPath(absPath);
if (! this._addFile(absPath, file)) {
// Collisions can happen if a compiler plugin calls addJavaScript
// multiple times with the same sourcePath. #6422
this._combineFiles(this._getFile(absPath), file);
}
});
return this;
}
// Concatenate the contents of oldFile and newFile, combining source
// maps and updating all other properties appropriately. Once this
// combination is done, oldFile should be kept and newFile discarded.
_combineFiles(oldFile, newFile) {
// Since we're concatenating the files together, they must be either
// both lazy or both eager. Same for bareness.
assert.strictEqual(oldFile.lazy, newFile.lazy);
assert.strictEqual(oldFile.bare, newFile.bare);
function getChunk(file) {
const consumer = file.sourceMap &&
new SourceMapConsumer(file.sourceMap);
const node = consumer &&
SourceNode.fromStringWithSourceMap(file.dataString, consumer);
return node || file.dataString;
}
const {
code: combinedDataString,
map: combinedSourceMap,
} = new SourceNode(null, null, null, [
getChunk(oldFile),
"\n\n",
getChunk(newFile)
]).toStringWithSourceMap({
file: oldFile.servePath || newFile.servePath
});
oldFile.dataString = combinedDataString;
oldFile.data = new Buffer(oldFile.dataString, "utf8");
oldFile.hash = sha1(oldFile.data);
oldFile.imported = oldFile.imported || newFile.imported;
oldFile.sourceMap = combinedSourceMap.toJSON();
if (! oldFile.sourceMap.mappings) {
oldFile.sourceMap = null;
}
}
scanImports() {
this.outputFiles.forEach(file => {
if (! file.lazy || file.imported) {
this._scanFile(file);
}
});
return this;
}
addNodeModules(identifiers) {
const newMissingNodeModules = Object.create(null);
if (identifiers) {
if (typeof identifiers === "object" &&
! Array.isArray(identifiers)) {
identifiers = Object.keys(identifiers);
}
if (identifiers.length > 0) {
const previousAllMissingNodeModules = this.allMissingNodeModules;
this.allMissingNodeModules = newMissingNodeModules;
try {
this._scanFile({
sourcePath: "fake.js",
// By specifying the .deps property of this fake file ahead of
// time, we can avoid calling findImportedModuleIdentifiers in the
// _scanFile method.
deps: identifiers,
});
} finally {
this.allMissingNodeModules = previousAllMissingNodeModules;
// Remove previously seen missing module identifiers from
// newMissingNodeModules and merge the new identifiers back into
// this.allMissingNodeModules.
each(keys(newMissingNodeModules), key => {
if (has(previousAllMissingNodeModules, key)) {
delete newMissingNodeModules[key];
} else {
previousAllMissingNodeModules[key] =
newMissingNodeModules[key];
}
});
}
}
}
return newMissingNodeModules;
}
getOutputFiles(options) {
// Return all installable output files that are either eager or
// imported by another module.
return this.outputFiles.filter(file => {
return file.installPath && (! file.lazy || file.imported);
});
}
_ensureSourcePath(file) {
let sourcePath = file.sourcePath;
if (sourcePath) {
if (pathIsAbsolute(sourcePath)) {
sourcePath = pathRelative(this.sourceRoot, sourcePath);
if (sourcePath.startsWith("..")) {
throw new Error("sourcePath outside sourceRoot: " + sourcePath);
}
}
} else if (file.servePath) {
sourcePath = convertToOSPath(file.servePath.replace(/^\//, ""));
} else if (file.path) {
sourcePath = file.path;
}
file.sourcePath = sourcePath;
// Note: this absolute path may not necessarily exist on the file
// system, but any import statements or require calls in file.data
// will be interpreted relative to this path, so it needs to be
// something plausible. #6411 #6383
return pathJoin(this.sourceRoot, sourcePath);
}
_findImportedModuleIdentifiers(file) {
if (IMPORT_SCANNER_CACHE.has(file.hash)) {
return IMPORT_SCANNER_CACHE.get(file.hash);
}
const result = keys(findImportedModuleIdentifiers(
file.dataString,
file.hash,
));
// there should always be file.hash, but better safe than sorry
if (file.hash) {
IMPORT_SCANNER_CACHE.set(file.hash, result);
}
return result;
}
_scanFile(file) {
const absPath = pathJoin(this.sourceRoot, file.sourcePath);
try {
file.deps = file.deps || this._findImportedModuleIdentifiers(file);
} catch (e) {
if (e.$ParseError) {
buildmessage.error(e.message, {
file: file.sourcePath,
line: e.loc.line,
column: e.loc.column,
});
return;
}
throw e;
}
each(file.deps, id => {
const resolved = this._tryToResolveImportedPath(file, id);
if (! resolved) {
return;
}
const absImportedPath = resolved.path;
let depFile = this._getFile(absImportedPath);
if (depFile) {
// Avoid scanning files that we've scanned before, but mark them
// as imported so we know to include them in the bundle if they
// are lazy. Eager files and files that we have imported before do
// not need to be scanned again. Lazy files that we have not
// imported before still need to be scanned, however.
const alreadyScanned = ! depFile.lazy || depFile.imported;
// Whether the file is eager or lazy, mark it as imported. For
// lazy files, this makes the difference between being included in
// or omitted from the bundle. For eager files, this just ensures
// we won't scan them again.
depFile.imported = true;
if (! alreadyScanned) {
this._scanFile(depFile);
}
return;
}
if (! this._hasDefaultExtension(absImportedPath)) {
// The _readModule method provides hardcoded support for files
// with known extensions, but any other type of file must be
// ignored at this point, because it was not in the set of input
// files and therefore must not have been processed by a compiler
// plugin for the current architecture (this.bundleArch).
return;
}
const installPath = this._getInstallPath(absImportedPath);
if (! installPath) {
// The given path cannot be installed on this architecture.
return;
}
// The object returned by _readModule will have .data, .dataString,
// and .hash properties.
depFile = this._readModule(absImportedPath);
depFile.type = "js"; // TODO Is this correct?
depFile.sourcePath = pathRelative(this.sourceRoot, absImportedPath);
depFile.installPath = installPath;
depFile.servePath = installPath;
depFile.lazy = true;
depFile.imported = true;
// Append this file to the output array and record its index.
this._addFile(absImportedPath, depFile);
this._scanFile(depFile);
});
}
_readFile(absPath) {
let { contents, hash } =
readAndWatchFileWithHash(this.watchSet, absPath);
return {
data: contents,
dataString: contents.toString("utf8"),
hash
};
}
_readModule(absPath) {
const info = this._readFile(absPath);
const dataString = info.dataString;
// Same logic/comment as stripBOM in node/lib/module.js:
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
if (info.dataString.charCodeAt(0) === 0xfeff) {
info.dataString = info.dataString.slice(1);
}
const ext = pathExtname(absPath).toLowerCase();
info.dataString = defaultExtensionHandlers[ext](info.dataString);
if (info.dataString !== dataString) {
info.data = new Buffer(info.dataString, "utf8");
}
return info;
}
// Returns a relative path indicating where to install the given file
// via meteorInstall. May return undefined if the file should not be
// installed on the current architecture.
_getInstallPath(absPath) {
let path =
this._getNodeModulesInstallPath(absPath) ||
this._getSourceRootInstallPath(absPath);
if (! path) {
return;
}
if (this.name) {
// If we're bundling a package, prefix path with
// node_modules/<package name>/.
path = pathJoin("node_modules", "meteor", this.name, path);
}
// Install paths should always be delimited by /.
return convertToPosixPath(path);
}
_getNodeModulesInstallPath(absPath) {
let installPath;
this.nodeModulesPaths.some(path => {
const relPathWithinNodeModules = pathRelative(path, absPath);
if (relPathWithinNodeModules.startsWith("..")) {
// absPath is not a subdirectory of path.
return;
}
if (! this._hasDefaultExtension(relPathWithinNodeModules)) {
// Only accept files within node_modules directories if they
// have one of the known extensions.
return;
}
// Install the module into the local node_modules directory within
// this app or package.
return installPath = pathJoin(
"node_modules",
relPathWithinNodeModules
);
});
return installPath;
}
_getSourceRootInstallPath(absPath) {
const installPath = pathRelative(this.sourceRoot, absPath);
if (installPath.startsWith("..")) {
// absPath is not a subdirectory of this.sourceRoot.
return;
}
const dirs = this._splitPath(pathDirname(installPath));
const isApp = ! this.name;
const bundlingForWeb = archMatches(this.bundleArch, "web");
const topLevelDir = dirs[0];
if (topLevelDir === "private" ||
topLevelDir === "packages" ||
topLevelDir === "programs" ||
topLevelDir === "cordova-build-override") {
// Don't load anything from these special top-level directories
return;
}
for (let dir of dirs) {
if (dir.charAt(0) === ".") {
// Files/directories whose names start with a dot are never loaded
return;
}
if (isApp) {
if (bundlingForWeb) {
if (dir === "server") {
// If we're bundling an app for a client architecture, any files
// contained by a server-only directory that is not contained by
// a node_modules directory must be ignored.
return;
}
} else if (dir === "client") {
// If we're bundling an app for a server architecture, any files
// contained by a client-only directory that is not contained by
// a node_modules directory must be ignored.
return;
}
}
if (dir === "node_modules") {
if (! this._hasDefaultExtension(installPath)) {
// Reject any files within node_modules directories that do
// not have one of the known extensions.
return;
}
// Accept any file within a node_modules directory if it has a
// known file extension.
return installPath;
}
}
return installPath;
}
_hasDefaultExtension(path) {
return has(
defaultExtensionHandlers,
pathExtname(path).toLowerCase()
);
}
_splitPath(path) {
const partsInReverse = [];
for (let dir; (dir = pathDirname(path)) !== path; path = dir) {
partsInReverse.push(pathBasename(path));
}
return partsInReverse.reverse();
}
// TODO This method can probably be consolidated with _getInstallPath.
_tryToResolveImportedPath(file, id, seenDirPaths) {
let resolved =
this._resolveAbsolute(file, id) ||
this._resolveRelative(file, id) ||
this._resolveNodeModule(file, id);
while (resolved && resolved.stat.isDirectory()) {
let dirPath = resolved.path;
seenDirPaths = seenDirPaths || new Set;
// If the "main" field of a package.json file resolves to a
// directory we've already considered, then we should not attempt to
// read the same package.json file again.
if (! seenDirPaths.has(dirPath)) {
seenDirPaths.add(dirPath);
resolved = this._resolvePkgJsonMain(dirPath, seenDirPaths);
if (resolved) {
// The _resolvePkgJsonMain call above may have returned a
// directory, so continue the loop to make sure we fully resolve
// it to a non-directory.
continue;
}
}
// If we didn't find a `package.json` file, or it didn't have a
// resolvable `.main` property, the only possibility left to
// consider is that this directory contains an `index.js` module.
// This assignment almost always terminates the while loop, because
// there's very little chance an `index.js` file will be a
// directory. However, in principle it is remotely possible that a
// file called `index.js` could be a directory instead of a file.
resolved = this._joinAndStat(dirPath, "index.js");
}
return resolved;
}
_joinAndStat(...joinArgs) {
const joined = pathJoin(...joinArgs);
if (this._statCache.has(joined)) {
return this._statCache.get(joined);
}
const path = pathNormalize(joined);
const exactStat = statOrNull(path);
const exactResult = exactStat && { path, stat: exactStat };
let result = null;
if (exactResult && exactStat.isFile()) {
result = exactResult;
}
if (! result) {
this.extensions.some(ext => {
const pathWithExt = path + ext;
const stat = statOrNull(pathWithExt);
if (stat) {
return result = { path: pathWithExt, stat };
}
});
}
if (! result && exactResult && exactStat.isDirectory()) {
// After trying all available file extensions, fall back to the
// original result if it was a directory.
result = exactResult;
}
this._statCache.set(joined, result);
return result;
}
_resolveAbsolute(file, id) {
return id.charAt(0) === "/" &&
this._joinAndStat(this.sourceRoot, id.slice(1));
}
_resolveRelative({ sourcePath }, id) {
if (id.charAt(0) === ".") {
return this._joinAndStat(
this.sourceRoot, sourcePath, "..", id
);
}
}
_resolveNodeModule(file, id) {
let resolved = null;
const isNative = has(nativeModulesMap, id);
if (isNative && archMatches(this.bundleArch, "os")) {
// Forbid installing any server module with the same name as a
// native Node module.
return null;
}
const absPath = pathJoin(this.sourceRoot, file.sourcePath);
let sourceRoot;
if (! file.sourcePath.startsWith("..")) {
// If the file is contained by this.sourceRoot, then it's safe to
// use this.sourceRoot as the limiting ancestor directory in the
// while loop below, but we're still going to check whether the file
// resides in an external node_modules directory, since "external"
// .npm/package/node_modules directories are technically contained
// within the root directory of their packages.
sourceRoot = this.sourceRoot;
}
this.nodeModulesPaths.some(path => {
if (! pathRelative(path, absPath).startsWith("..")) {
// If the file is inside an external node_modules directory,
// consider the rootDir to be the parent directory of that
// node_modules directory, rather than this.sourceRoot.
return sourceRoot = pathDirname(path);
}
});
if (sourceRoot) {
let dir = absPath; // It's ok for absPath to be a directory!
let info = this._joinAndStat(dir);
if (! info || ! info.stat.isDirectory()) {
dir = pathDirname(dir);
}
while (! (resolved = this._joinAndStat(dir, "node_modules", id))) {
if (dir === sourceRoot) {
break;
}
const parentDir = pathDirname(dir);
if (dir === parentDir) {
// We've reached the root of the file system??
break;
}
dir = parentDir;
}
}
if (! resolved) {
// After checking any local node_modules directories, fall back to
// the package NPM directory, if one was specified.
this.nodeModulesPaths.some(path => {
return resolved = this._joinAndStat(path, id);
});
}
if (! resolved) {
const isApp = ! this.name;
// The reason `&& isApp` is required here is somewhat subtle: When a
// Meteor package imports a missing native Node module on the
// client, we should not assume the missing module will be
// implemented by /node_modules/meteor-node-stubs, because the app
// might have a custom stub package installed in its node_modules
// directory that should take precedence over meteor-node-stubs.
// Instead, we have to wait for computeJsOutputFilesMap to call
// addNodeModules against the app's ImportScanner, then fall back to
// meteor-node-stubs only if the app lookup fails. When isApp is
// true, however, we know that the app lookup just failed.
if (isNative && isApp) {
assert.ok(archMatches(this.bundleArch, "web"));
// To ensure the native module can be evaluated at runtime,
// register a dependency on meteor-node-stubs/defs/<id>.js.
id = nativeModulesMap[id];
}
// If the imported identifier is neither absolute nor relative, but
// top-level, then it might be satisfied by a package installed in
// the top-level node_modules directory, and we should record the
// missing dependency so that we can include it in the app bundle.
const missing = file.missingNodeModules || Object.create(null);
this.allMissingNodeModules[id] = missing[id] = true;
file.missingNodeModules = missing;
}
// If the dependency is still not resolved, it might be handled by the
// fallback function defined in meteor/packages/modules/modules.js, or
// it might be imported in code that will never run on this platform,
// so there is always the possibility that its absence is not actually
// a problem. As much as we might like to issue warnings about missing
// dependencies here, we just don't have enough information to make
// that determination until the code actually runs.
return resolved;
}
_readPkgJson(path) {
if (this._pkgJsonCache.has(path)) {
return this._pkgJsonCache.get(path);
}
let result = null;
try {
result = JSON.parse(this._readFile(path).dataString);
} catch (e) {
// leave result null
}
this._pkgJsonCache.set(path, result);
return result;
}
_resolvePkgJsonMain(dirPath, seenDirPaths) {
const pkgJsonPath = pathJoin(dirPath, "package.json");
const pkg = this._readPkgJson(pkgJsonPath);
if (! pkg) {
return null;
}
let main = pkg.main;
if (archMatches(this.bundleArch, "web") &&
isString(pkg.browser)) {
main = pkg.browser;
}
if (isString(main)) {
// The "main" field of package.json does not have to begin with ./
// to be considered relative, so first we try simply appending it to
// the directory path before falling back to a full resolve, which
// might return a package from a node_modules directory.
const resolved = this._joinAndStat(dirPath, main) ||
// The _tryToResolveImportedPath method takes a file object as its
// first parameter, but only the .sourcePath property is ever
// used, so we can get away with passing a fake file object with
// only that property.
this._tryToResolveImportedPath({
sourcePath: pathRelative(this.sourceRoot, pkgJsonPath),
}, main, seenDirPaths);
if (resolved) {
// Output a JS module that exports just the "name", "version", and
// "main" properties defined in the package.json file.
const pkgSubset = {
name: pkg.name,
};
if (has(pkg, "version")) {
pkgSubset.version = pkg.version;
}
pkgSubset.main = main;
this._addPkgJsonToOutput(pkgJsonPath, pkgSubset);
return resolved;
}
}
return null;
}
_addPkgJsonToOutput(pkgJsonPath, pkg) {
if (! this._getFile(pkgJsonPath)) {
const data = new Buffer(map(pkg, (value, key) => {
return `exports.${key} = ${JSON.stringify(value)};\n`;
}).join(""));
const relPkgJsonPath = pathRelative(this.sourceRoot, pkgJsonPath);
const pkgFile = {
type: "js", // We represent the JSON module with JS.
data,
deps: [], // Avoid accidentally re-scanning this file.
sourcePath: relPkgJsonPath,
installPath: this._getInstallPath(pkgJsonPath),
servePath: relPkgJsonPath,
hash: sha1(data),
lazy: true,
imported: true,
};
this._addFile(pkgJsonPath, pkgFile);
}
}
}
each(["_readFile", "_findImportedModuleIdentifiers",
"_getInstallPath", "_tryToResolveImportedPath",
"_resolvePkgJsonMain"], funcName => {
ImportScanner.prototype[funcName] = Profile(
`ImportScanner#${funcName}`, ImportScanner.prototype[funcName]);
});
| tools/isobuild/import-scanner.js | import assert from "assert";
import {isString, has, keys, each, map, without} from "underscore";
import {sha1, readAndWatchFileWithHash} from "../fs/watch.js";
import {matches as archMatches} from "../utils/archinfo.js";
import {findImportedModuleIdentifiers} from "./js-analyze.js";
import buildmessage from "../utils/buildmessage.js";
import LRU from "lru-cache";
import {Profile} from "../tool-env/profile.js";
import {SourceNode, SourceMapConsumer} from "source-map";
import {
pathJoin,
pathRelative,
pathNormalize,
pathDirname,
pathBasename,
pathExtname,
pathIsAbsolute,
statOrNull,
convertToOSPath,
convertToPosixPath,
} from "../fs/files.js";
const nativeModulesMap = Object.create(null);
const nativeNames = Object.keys(process.binding("natives"));
// Node 0.10 does not include process as a built-in module, but later
// versions of Node do, and we provide a stub for it on the client.
nativeNames.push("process");
nativeNames.forEach(id => {
if (id === "freelist" ||
id.startsWith("internal/")) {
return;
}
// When a native Node module is imported, we register a dependency on a
// meteor-node-stubs/deps/* module of the same name, so that the
// necessary stub modules will be included in the bundle. This alternate
// identifier will not be imported at runtime, but the modules it
// depends on are necessary for the original import to succeed.
nativeModulesMap[id] = "meteor-node-stubs/deps/" + id;
});
// Default handlers for well-known file extensions.
// Note that these function expect strings, not Buffer objects.
const defaultExtensionHandlers = {
".js"(dataString) {
// Strip any #! line from the beginning of the file.
return dataString.replace(/^#![^\n]*/, "");
},
".json"(dataString) {
return "module.exports = " +
JSON.stringify(JSON.parse(dataString), null, 2) +
";\n";
}
};
// Map from SHA (which is already calculated, so free for us)
// to the results of calling findImportedModuleIdentifiers.
// Each entry is an array of strings, and this is a case where
// the computation is expensive but the output is very small.
// The cache can be global because findImportedModuleIdentifiers
// is a pure function, and that way it applies across instances
// of ImportScanner (which do not persist across builds).
const IMPORT_SCANNER_CACHE = new LRU({
max: 1024*1024,
length(value) {
let total = 40; // size of key
value.forEach(str => { total += str.length; });
return total;
}
});
export default class ImportScanner {
constructor({
name,
bundleArch,
extensions = [".js", ".json"],
sourceRoot,
usedPackageNames = {},
nodeModulesPaths = [],
watchSet,
}) {
assert.ok(isString(sourceRoot));
this.name = name;
this.bundleArch = bundleArch;
this.extensions = extensions;
this.sourceRoot = sourceRoot;
this.usedPackageNames = usedPackageNames;
this.nodeModulesPaths = nodeModulesPaths;
this.watchSet = watchSet;
this.absPathToOutputIndex = Object.create(null);
this.allMissingNodeModules = Object.create(null);
this.outputFiles = [];
this._statCache = new Map;
this._pkgJsonCache = new Map;
}
addInputFiles(files) {
files.forEach(file => {
const absPath = this._ensureSourcePath(file);
const dotExt = "." + file.type;
const dataString = file.data.toString("utf8");
file.dataString = defaultExtensionHandlers[dotExt](dataString);
if (! (file.data instanceof Buffer) ||
file.dataString !== dataString) {
file.data = new Buffer(file.dataString, "utf8");
}
// Files that are not eagerly evaluated (lazy) will only be included
// in the bundle if they are actually imported. Files that are
// eagerly evaluated are effectively "imported" as entry points.
file.imported = ! file.lazy;
file.installPath = this._getInstallPath(absPath);
if (has(this.absPathToOutputIndex, absPath)) {
// Collisions can happen if a compiler plugin calls addJavaScript
// multiple times with the same sourcePath. #6422
const index = this.absPathToOutputIndex[absPath];
this._combineFiles(this.outputFiles[index], file);
} else {
this.absPathToOutputIndex[absPath] =
this.outputFiles.push(file) - 1;
}
});
return this;
}
// Concatenate the contents of oldFile and newFile, combining source
// maps and updating all other properties appropriately. Once this
// combination is done, oldFile should be kept and newFile discarded.
_combineFiles(oldFile, newFile) {
// Since we're concatenating the files together, they must be either
// both lazy or both eager. Same for bareness.
assert.strictEqual(oldFile.lazy, newFile.lazy);
assert.strictEqual(oldFile.bare, newFile.bare);
function getChunk(file) {
const consumer = file.sourceMap &&
new SourceMapConsumer(file.sourceMap);
const node = consumer &&
SourceNode.fromStringWithSourceMap(file.dataString, consumer);
return node || file.dataString;
}
const {
code: combinedDataString,
map: combinedSourceMap,
} = new SourceNode(null, null, null, [
getChunk(oldFile),
"\n\n",
getChunk(newFile)
]).toStringWithSourceMap({
file: oldFile.servePath || newFile.servePath
});
oldFile.dataString = combinedDataString;
oldFile.data = new Buffer(oldFile.dataString, "utf8");
oldFile.hash = sha1(oldFile.data);
oldFile.imported = oldFile.imported || newFile.imported;
oldFile.sourceMap = combinedSourceMap.toJSON();
if (! oldFile.sourceMap.mappings) {
oldFile.sourceMap = null;
}
}
scanImports() {
this.outputFiles.forEach(file => {
if (! file.lazy || file.imported) {
this._scanFile(file);
}
});
return this;
}
addNodeModules(identifiers) {
const newMissingNodeModules = Object.create(null);
if (identifiers) {
if (typeof identifiers === "object" &&
! Array.isArray(identifiers)) {
identifiers = Object.keys(identifiers);
}
if (identifiers.length > 0) {
const previousAllMissingNodeModules = this.allMissingNodeModules;
this.allMissingNodeModules = newMissingNodeModules;
try {
this._scanFile({
sourcePath: "fake.js",
// By specifying the .deps property of this fake file ahead of
// time, we can avoid calling findImportedModuleIdentifiers in the
// _scanFile method.
deps: identifiers,
});
} finally {
this.allMissingNodeModules = previousAllMissingNodeModules;
// Remove previously seen missing module identifiers from
// newMissingNodeModules and merge the new identifiers back into
// this.allMissingNodeModules.
each(keys(newMissingNodeModules), key => {
if (has(previousAllMissingNodeModules, key)) {
delete newMissingNodeModules[key];
} else {
previousAllMissingNodeModules[key] =
newMissingNodeModules[key];
}
});
}
}
}
return newMissingNodeModules;
}
getOutputFiles(options) {
// Return all installable output files that are either eager or
// imported by another module.
return this.outputFiles.filter(file => {
return file.installPath && (! file.lazy || file.imported);
});
}
_ensureSourcePath(file) {
let sourcePath = file.sourcePath;
if (sourcePath) {
if (pathIsAbsolute(sourcePath)) {
sourcePath = pathRelative(this.sourceRoot, sourcePath);
if (sourcePath.startsWith("..")) {
throw new Error("sourcePath outside sourceRoot: " + sourcePath);
}
}
} else if (file.servePath) {
sourcePath = convertToOSPath(file.servePath.replace(/^\//, ""));
} else if (file.path) {
sourcePath = file.path;
}
file.sourcePath = sourcePath;
// Note: this absolute path may not necessarily exist on the file
// system, but any import statements or require calls in file.data
// will be interpreted relative to this path, so it needs to be
// something plausible. #6411 #6383
return pathJoin(this.sourceRoot, sourcePath);
}
_findImportedModuleIdentifiers(file) {
if (IMPORT_SCANNER_CACHE.has(file.hash)) {
return IMPORT_SCANNER_CACHE.get(file.hash);
}
const result = keys(findImportedModuleIdentifiers(
file.dataString,
file.hash,
));
// there should always be file.hash, but better safe than sorry
if (file.hash) {
IMPORT_SCANNER_CACHE.set(file.hash, result);
}
return result;
}
_scanFile(file) {
const absPath = pathJoin(this.sourceRoot, file.sourcePath);
try {
file.deps = file.deps || this._findImportedModuleIdentifiers(file);
} catch (e) {
if (e.$ParseError) {
buildmessage.error(e.message, {
file: file.sourcePath,
line: e.loc.line,
column: e.loc.column,
});
return;
}
throw e;
}
each(file.deps, id => {
const resolved = this._tryToResolveImportedPath(file, id);
if (! resolved) {
return;
}
const absImportedPath = resolved.path;
if (has(this.absPathToOutputIndex, absImportedPath)) {
// Avoid scanning files that we've scanned before, but mark them
// as imported so we know to include them in the bundle if they
// are lazy.
const index = this.absPathToOutputIndex[absImportedPath];
const file = this.outputFiles[index];
// Eager files and files that we have imported before do not need
// to be scanned again. Lazy files that we have not imported
// before still need to be scanned, however.
const alreadyScanned = ! file.lazy || file.imported;
// Whether the file is eager or lazy, mark it as imported. For
// lazy files, this makes the difference between being included in
// or omitted from the bundle. For eager files, this just ensures
// we won't scan them again.
file.imported = true;
if (! alreadyScanned) {
this._scanFile(file);
}
return;
}
if (! this._hasDefaultExtension(absImportedPath)) {
// The _readModule method provides hardcoded support for files
// with known extensions, but any other type of file must be
// ignored at this point, because it was not in the set of input
// files and therefore must not have been processed by a compiler
// plugin for the current architecture (this.bundleArch).
return;
}
const installPath = this._getInstallPath(absImportedPath);
if (! installPath) {
// The given path cannot be installed on this architecture.
return;
}
// The object returned by _readModule will have .data, .dataString,
// and .hash properties.
const depFile = this._readModule(absImportedPath);
depFile.type = "js"; // TODO Is this correct?
depFile.sourcePath = pathRelative(this.sourceRoot, absImportedPath);
depFile.installPath = installPath;
depFile.servePath = installPath;
depFile.lazy = true;
depFile.imported = true;
// Append this file to the output array and record its index.
this.absPathToOutputIndex[absImportedPath] =
this.outputFiles.push(depFile) - 1;
this._scanFile(depFile);
});
}
_readFile(absPath) {
let { contents, hash } =
readAndWatchFileWithHash(this.watchSet, absPath);
return {
data: contents,
dataString: contents.toString("utf8"),
hash
};
}
_readModule(absPath) {
const info = this._readFile(absPath);
const dataString = info.dataString;
// Same logic/comment as stripBOM in node/lib/module.js:
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
if (info.dataString.charCodeAt(0) === 0xfeff) {
info.dataString = info.dataString.slice(1);
}
const ext = pathExtname(absPath).toLowerCase();
info.dataString = defaultExtensionHandlers[ext](info.dataString);
if (info.dataString !== dataString) {
info.data = new Buffer(info.dataString, "utf8");
}
return info;
}
// Returns a relative path indicating where to install the given file
// via meteorInstall. May return undefined if the file should not be
// installed on the current architecture.
_getInstallPath(absPath) {
let path =
this._getNodeModulesInstallPath(absPath) ||
this._getSourceRootInstallPath(absPath);
if (! path) {
return;
}
if (this.name) {
// If we're bundling a package, prefix path with
// node_modules/<package name>/.
path = pathJoin("node_modules", "meteor", this.name, path);
}
// Install paths should always be delimited by /.
return convertToPosixPath(path);
}
_getNodeModulesInstallPath(absPath) {
let installPath;
this.nodeModulesPaths.some(path => {
const relPathWithinNodeModules = pathRelative(path, absPath);
if (relPathWithinNodeModules.startsWith("..")) {
// absPath is not a subdirectory of path.
return;
}
if (! this._hasDefaultExtension(relPathWithinNodeModules)) {
// Only accept files within node_modules directories if they
// have one of the known extensions.
return;
}
// Install the module into the local node_modules directory within
// this app or package.
return installPath = pathJoin(
"node_modules",
relPathWithinNodeModules
);
});
return installPath;
}
_getSourceRootInstallPath(absPath) {
const installPath = pathRelative(this.sourceRoot, absPath);
if (installPath.startsWith("..")) {
// absPath is not a subdirectory of this.sourceRoot.
return;
}
const dirs = this._splitPath(pathDirname(installPath));
const isApp = ! this.name;
const bundlingForWeb = archMatches(this.bundleArch, "web");
const topLevelDir = dirs[0];
if (topLevelDir === "private" ||
topLevelDir === "packages" ||
topLevelDir === "programs" ||
topLevelDir === "cordova-build-override") {
// Don't load anything from these special top-level directories
return;
}
for (let dir of dirs) {
if (dir.charAt(0) === ".") {
// Files/directories whose names start with a dot are never loaded
return;
}
if (isApp) {
if (bundlingForWeb) {
if (dir === "server") {
// If we're bundling an app for a client architecture, any files
// contained by a server-only directory that is not contained by
// a node_modules directory must be ignored.
return;
}
} else if (dir === "client") {
// If we're bundling an app for a server architecture, any files
// contained by a client-only directory that is not contained by
// a node_modules directory must be ignored.
return;
}
}
if (dir === "node_modules") {
if (! this._hasDefaultExtension(installPath)) {
// Reject any files within node_modules directories that do
// not have one of the known extensions.
return;
}
// Accept any file within a node_modules directory if it has a
// known file extension.
return installPath;
}
}
return installPath;
}
_hasDefaultExtension(path) {
return has(
defaultExtensionHandlers,
pathExtname(path).toLowerCase()
);
}
_splitPath(path) {
const partsInReverse = [];
for (let dir; (dir = pathDirname(path)) !== path; path = dir) {
partsInReverse.push(pathBasename(path));
}
return partsInReverse.reverse();
}
// TODO This method can probably be consolidated with _getInstallPath.
_tryToResolveImportedPath(file, id, seenDirPaths) {
let resolved =
this._resolveAbsolute(file, id) ||
this._resolveRelative(file, id) ||
this._resolveNodeModule(file, id);
while (resolved && resolved.stat.isDirectory()) {
let dirPath = resolved.path;
seenDirPaths = seenDirPaths || new Set;
// If the "main" field of a package.json file resolves to a
// directory we've already considered, then we should not attempt to
// read the same package.json file again.
if (! seenDirPaths.has(dirPath)) {
seenDirPaths.add(dirPath);
resolved = this._resolvePkgJsonMain(dirPath, seenDirPaths);
if (resolved) {
// The _resolvePkgJsonMain call above may have returned a
// directory, so continue the loop to make sure we fully resolve
// it to a non-directory.
continue;
}
}
// If we didn't find a `package.json` file, or it didn't have a
// resolvable `.main` property, the only possibility left to
// consider is that this directory contains an `index.js` module.
// This assignment almost always terminates the while loop, because
// there's very little chance an `index.js` file will be a
// directory. However, in principle it is remotely possible that a
// file called `index.js` could be a directory instead of a file.
resolved = this._joinAndStat(dirPath, "index.js");
}
return resolved;
}
_joinAndStat(...joinArgs) {
const joined = pathJoin(...joinArgs);
if (this._statCache.has(joined)) {
return this._statCache.get(joined);
}
const path = pathNormalize(joined);
const exactStat = statOrNull(path);
const exactResult = exactStat && { path, stat: exactStat };
let result = null;
if (exactResult && exactStat.isFile()) {
result = exactResult;
}
if (! result) {
this.extensions.some(ext => {
const pathWithExt = path + ext;
const stat = statOrNull(pathWithExt);
if (stat) {
return result = { path: pathWithExt, stat };
}
});
}
if (! result && exactResult && exactStat.isDirectory()) {
// After trying all available file extensions, fall back to the
// original result if it was a directory.
result = exactResult;
}
this._statCache.set(joined, result);
return result;
}
_resolveAbsolute(file, id) {
return id.charAt(0) === "/" &&
this._joinAndStat(this.sourceRoot, id.slice(1));
}
_resolveRelative({ sourcePath }, id) {
if (id.charAt(0) === ".") {
return this._joinAndStat(
this.sourceRoot, sourcePath, "..", id
);
}
}
_resolveNodeModule(file, id) {
let resolved = null;
const isNative = has(nativeModulesMap, id);
if (isNative && archMatches(this.bundleArch, "os")) {
// Forbid installing any server module with the same name as a
// native Node module.
return null;
}
const absPath = pathJoin(this.sourceRoot, file.sourcePath);
let sourceRoot;
if (! file.sourcePath.startsWith("..")) {
// If the file is contained by this.sourceRoot, then it's safe to
// use this.sourceRoot as the limiting ancestor directory in the
// while loop below, but we're still going to check whether the file
// resides in an external node_modules directory, since "external"
// .npm/package/node_modules directories are technically contained
// within the root directory of their packages.
sourceRoot = this.sourceRoot;
}
this.nodeModulesPaths.some(path => {
if (! pathRelative(path, absPath).startsWith("..")) {
// If the file is inside an external node_modules directory,
// consider the rootDir to be the parent directory of that
// node_modules directory, rather than this.sourceRoot.
return sourceRoot = pathDirname(path);
}
});
if (sourceRoot) {
let dir = absPath; // It's ok for absPath to be a directory!
let info = this._joinAndStat(dir);
if (! info || ! info.stat.isDirectory()) {
dir = pathDirname(dir);
}
while (! (resolved = this._joinAndStat(dir, "node_modules", id))) {
if (dir === sourceRoot) {
break;
}
const parentDir = pathDirname(dir);
if (dir === parentDir) {
// We've reached the root of the file system??
break;
}
dir = parentDir;
}
}
if (! resolved) {
// After checking any local node_modules directories, fall back to
// the package NPM directory, if one was specified.
this.nodeModulesPaths.some(path => {
return resolved = this._joinAndStat(path, id);
});
}
if (! resolved) {
const isApp = ! this.name;
// The reason `&& isApp` is required here is somewhat subtle: When a
// Meteor package imports a missing native Node module on the
// client, we should not assume the missing module will be
// implemented by /node_modules/meteor-node-stubs, because the app
// might have a custom stub package installed in its node_modules
// directory that should take precedence over meteor-node-stubs.
// Instead, we have to wait for computeJsOutputFilesMap to call
// addNodeModules against the app's ImportScanner, then fall back to
// meteor-node-stubs only if the app lookup fails. When isApp is
// true, however, we know that the app lookup just failed.
if (isNative && isApp) {
assert.ok(archMatches(this.bundleArch, "web"));
// To ensure the native module can be evaluated at runtime,
// register a dependency on meteor-node-stubs/defs/<id>.js.
id = nativeModulesMap[id];
}
// If the imported identifier is neither absolute nor relative, but
// top-level, then it might be satisfied by a package installed in
// the top-level node_modules directory, and we should record the
// missing dependency so that we can include it in the app bundle.
const missing = file.missingNodeModules || Object.create(null);
this.allMissingNodeModules[id] = missing[id] = true;
file.missingNodeModules = missing;
}
// If the dependency is still not resolved, it might be handled by the
// fallback function defined in meteor/packages/modules/modules.js, or
// it might be imported in code that will never run on this platform,
// so there is always the possibility that its absence is not actually
// a problem. As much as we might like to issue warnings about missing
// dependencies here, we just don't have enough information to make
// that determination until the code actually runs.
return resolved;
}
_readPkgJson(path) {
if (this._pkgJsonCache.has(path)) {
return this._pkgJsonCache.get(path);
}
let result = null;
try {
result = JSON.parse(this._readFile(path).dataString);
} catch (e) {
// leave result null
}
this._pkgJsonCache.set(path, result);
return result;
}
_resolvePkgJsonMain(dirPath, seenDirPaths) {
const pkgJsonPath = pathJoin(dirPath, "package.json");
const pkg = this._readPkgJson(pkgJsonPath);
if (! pkg) {
return null;
}
let main = pkg.main;
if (archMatches(this.bundleArch, "web") &&
isString(pkg.browser)) {
main = pkg.browser;
}
if (isString(main)) {
// The "main" field of package.json does not have to begin with ./
// to be considered relative, so first we try simply appending it to
// the directory path before falling back to a full resolve, which
// might return a package from a node_modules directory.
const resolved = this._joinAndStat(dirPath, main) ||
// The _tryToResolveImportedPath method takes a file object as its
// first parameter, but only the .sourcePath property is ever
// used, so we can get away with passing a fake file object with
// only that property.
this._tryToResolveImportedPath({
sourcePath: pathRelative(this.sourceRoot, pkgJsonPath),
}, main, seenDirPaths);
if (resolved) {
// Output a JS module that exports just the "name", "version", and
// "main" properties defined in the package.json file.
const pkgSubset = {
name: pkg.name,
};
if (has(pkg, "version")) {
pkgSubset.version = pkg.version;
}
pkgSubset.main = main;
this._addPkgJsonToOutput(pkgJsonPath, pkgSubset);
return resolved;
}
}
return null;
}
_addPkgJsonToOutput(pkgJsonPath, pkg) {
if (! has(this.absPathToOutputIndex, pkgJsonPath)) {
const data = new Buffer(map(pkg, (value, key) => {
return `exports.${key} = ${JSON.stringify(value)};\n`;
}).join(""));
const relPkgJsonPath = pathRelative(this.sourceRoot, pkgJsonPath);
const pkgFile = {
type: "js", // We represent the JSON module with JS.
data,
deps: [], // Avoid accidentally re-scanning this file.
sourcePath: relPkgJsonPath,
installPath: this._getInstallPath(pkgJsonPath),
servePath: relPkgJsonPath,
hash: sha1(data),
lazy: true,
imported: true,
};
this.absPathToOutputIndex[pkgJsonPath] =
this.outputFiles.push(pkgFile) - 1;
}
}
}
each(["_readFile", "_findImportedModuleIdentifiers",
"_getInstallPath", "_tryToResolveImportedPath",
"_resolvePkgJsonMain"], funcName => {
ImportScanner.prototype[funcName] = Profile(
`ImportScanner#${funcName}`, ImportScanner.prototype[funcName]);
});
| Make ImportScanner case-insensitive.
Specifically, with this change, the ImportScanner will never include two
files whose paths differ only in case. If one of the files is processed by
compiler plugins, then that file's actual path will "win" in the sense
that its installed module identifier will preserve the original casing.
Fixes #6428.
| tools/isobuild/import-scanner.js | Make ImportScanner case-insensitive. | <ide><path>ools/isobuild/import-scanner.js
<ide> this._pkgJsonCache = new Map;
<ide> }
<ide>
<add> _getFile(absPath) {
<add> absPath = absPath.toLowerCase();
<add> if (has(this.absPathToOutputIndex, absPath)) {
<add> return this.outputFiles[this.absPathToOutputIndex[absPath]];
<add> }
<add> }
<add>
<add> _addFile(absPath, file) {
<add> absPath = absPath.toLowerCase();
<add> if (! has(this.absPathToOutputIndex, absPath)) {
<add> this.absPathToOutputIndex[absPath] =
<add> this.outputFiles.push(file) - 1;
<add> return file;
<add> }
<add> }
<add>
<ide> addInputFiles(files) {
<ide> files.forEach(file => {
<ide> const absPath = this._ensureSourcePath(file);
<ide>
<ide> file.installPath = this._getInstallPath(absPath);
<ide>
<del> if (has(this.absPathToOutputIndex, absPath)) {
<add> if (! this._addFile(absPath, file)) {
<ide> // Collisions can happen if a compiler plugin calls addJavaScript
<ide> // multiple times with the same sourcePath. #6422
<del> const index = this.absPathToOutputIndex[absPath];
<del> this._combineFiles(this.outputFiles[index], file);
<del>
<del> } else {
<del> this.absPathToOutputIndex[absPath] =
<del> this.outputFiles.push(file) - 1;
<add> this._combineFiles(this._getFile(absPath), file);
<ide> }
<ide> });
<ide>
<ide>
<ide> const absImportedPath = resolved.path;
<ide>
<del> if (has(this.absPathToOutputIndex, absImportedPath)) {
<add> let depFile = this._getFile(absImportedPath);
<add> if (depFile) {
<ide> // Avoid scanning files that we've scanned before, but mark them
<ide> // as imported so we know to include them in the bundle if they
<del> // are lazy.
<del> const index = this.absPathToOutputIndex[absImportedPath];
<del> const file = this.outputFiles[index];
<del>
<del> // Eager files and files that we have imported before do not need
<del> // to be scanned again. Lazy files that we have not imported
<del> // before still need to be scanned, however.
<del> const alreadyScanned = ! file.lazy || file.imported;
<add> // are lazy. Eager files and files that we have imported before do
<add> // not need to be scanned again. Lazy files that we have not
<add> // imported before still need to be scanned, however.
<add> const alreadyScanned = ! depFile.lazy || depFile.imported;
<ide>
<ide> // Whether the file is eager or lazy, mark it as imported. For
<ide> // lazy files, this makes the difference between being included in
<ide> // or omitted from the bundle. For eager files, this just ensures
<ide> // we won't scan them again.
<del> file.imported = true;
<add> depFile.imported = true;
<ide>
<ide> if (! alreadyScanned) {
<del> this._scanFile(file);
<add> this._scanFile(depFile);
<ide> }
<ide>
<ide> return;
<ide>
<ide> // The object returned by _readModule will have .data, .dataString,
<ide> // and .hash properties.
<del> const depFile = this._readModule(absImportedPath);
<add> depFile = this._readModule(absImportedPath);
<ide> depFile.type = "js"; // TODO Is this correct?
<ide> depFile.sourcePath = pathRelative(this.sourceRoot, absImportedPath);
<ide> depFile.installPath = installPath;
<ide> depFile.imported = true;
<ide>
<ide> // Append this file to the output array and record its index.
<del> this.absPathToOutputIndex[absImportedPath] =
<del> this.outputFiles.push(depFile) - 1;
<add> this._addFile(absImportedPath, depFile);
<ide>
<ide> this._scanFile(depFile);
<ide> });
<ide> }
<ide>
<ide> _addPkgJsonToOutput(pkgJsonPath, pkg) {
<del> if (! has(this.absPathToOutputIndex, pkgJsonPath)) {
<add> if (! this._getFile(pkgJsonPath)) {
<ide> const data = new Buffer(map(pkg, (value, key) => {
<ide> return `exports.${key} = ${JSON.stringify(value)};\n`;
<ide> }).join(""));
<ide> imported: true,
<ide> };
<ide>
<del> this.absPathToOutputIndex[pkgJsonPath] =
<del> this.outputFiles.push(pkgFile) - 1;
<add> this._addFile(pkgJsonPath, pkgFile);
<ide> }
<ide> }
<ide> } |
|
Java | mit | e330c1d3ecf6bc7c238673ea2e793bd9a00f5b62 | 0 | Enthri/aprctsrpg | package util;
public class Sword extends Item {
private double damage;
/*
* defualt
*/
public Sword(){
super("Sword");
this.damage = 20;
}
/*
* requires input of damage to construct object
*/
public Sword (double damage, String name){
super(name);
this.damage = damage;
}
public double getDamage(){
return damage;
}
public String getName(){
return name;
}
}
| util/Sword.java | package util;
public class Sword extends Item {
private double damage;
/*
* defualt
*/
public Sword(){
super("defualtSword");
this.damage = 20;
}
/*
* requires input of damage to construct object
*/
public Sword (double damage, String name){
super(name);
this.damage = damage;
}
public double getDamage(){
return damage;
}
}
| get Name for items
| util/Sword.java | get Name for items | <ide><path>til/Sword.java
<ide> * defualt
<ide> */
<ide> public Sword(){
<del> super("defualtSword");
<add> super("Sword");
<ide> this.damage = 20;
<ide> }
<ide> /*
<ide> public double getDamage(){
<ide> return damage;
<ide> }
<add> public String getName(){
<add> return name;
<add> }
<ide>
<ide> } |
|
Java | mit | error: pathspec 'src/com/telmomenezes/synthetic/RandomNet.java' did not match any file(s) known to git
| 8693ad9f183765fbd55b82b3a1b72ac5445594a7 | 1 | telmomenezes/synthetic,telmomenezes/synthetic | package com.telmomenezes.synthetic;
public class RandomNet extends Net {
public RandomNet(int nodeCount, int edgeCount) {
super();
for (int i = 0; i < nodeCount; i++) {
addNode();
}
for (int i = 0; i < edgeCount; i++) {
boolean found = false;
while (!found) {
int orig = RandomGenerator.instance().random.nextInt(nodeCount);
int targ = RandomGenerator.instance().random.nextInt(nodeCount);
if ((orig != targ) && (!edgeExists(nodes.get(orig), nodes.get(targ)))) {
addEdge(nodes.get(orig), nodes.get(targ));
found = true;
}
}
}
}
public static void main(String[] args) {
RandomNet net = new RandomNet(100, 1000);
System.out.println(net);
}
}
| src/com/telmomenezes/synthetic/RandomNet.java | Randomnet
| src/com/telmomenezes/synthetic/RandomNet.java | Randomnet | <ide><path>rc/com/telmomenezes/synthetic/RandomNet.java
<add>package com.telmomenezes.synthetic;
<add>
<add>
<add>public class RandomNet extends Net {
<add> public RandomNet(int nodeCount, int edgeCount) {
<add> super();
<add>
<add> for (int i = 0; i < nodeCount; i++) {
<add> addNode();
<add> }
<add>
<add> for (int i = 0; i < edgeCount; i++) {
<add> boolean found = false;
<add>
<add> while (!found) {
<add> int orig = RandomGenerator.instance().random.nextInt(nodeCount);
<add> int targ = RandomGenerator.instance().random.nextInt(nodeCount);
<add>
<add> if ((orig != targ) && (!edgeExists(nodes.get(orig), nodes.get(targ)))) {
<add> addEdge(nodes.get(orig), nodes.get(targ));
<add> found = true;
<add> }
<add> }
<add> }
<add> }
<add>
<add> public static void main(String[] args) {
<add> RandomNet net = new RandomNet(100, 1000);
<add> System.out.println(net);
<add> }
<add>} |
|
Java | bsd-3-clause | 74965a53ef0078a81406fa82adb5482efa5e69f1 | 0 | MXProgrammingClub/Chem-Helper,MXProgrammingClub/Chem-Helper | /*
* Performs various calculations for functions at equilibrium.
*
* Author: Julia McClellan
* Version: 3/28/2016
*/
package Functions;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.TreeMap;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import Equation.Compound;
import Equation.Equation;
import HelperClasses.EnterField;
import HelperClasses.Units;
public class Equilibrium extends Function
{
public static TreeMap<String, Double> KSP = createMap();
private JPanel panel, enterPanel, fields;
private EquationReader reader;
private JLabel expression;
private EnterField[] compounds, precipitate;
private EnterField k, solubility;
private JButton calculate, reset;
private Box steps, results;
private JRadioButton before;
private ArrayList<Double> saved;
private ArrayList<Compound> relevant;
private ArrayList<Integer> powers;
private Compound[] reactants;
public Equilibrium()
{
super("Equilibrium");
saved = new ArrayList<Double>();
reader = new EquationReader(this);
enterPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
expression = new JLabel();
enterPanel.add(expression, c);
c.gridy++;
before = new JRadioButton("Before reaction");
JRadioButton after = new JRadioButton("At equilibrium", true);
ButtonGroup g = new ButtonGroup();
g.add(before);
g.add(after);
JPanel buttons = new JPanel();
buttons.add(after);
buttons.add(before);
enterPanel.add(buttons, c);
c.gridy++;
fields = new JPanel(new GridBagLayout());
enterPanel.add(fields, c);
c.gridy++;
calculate = new JButton("Calculate");
calculate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
results.removeAll();
results.setVisible(false);
steps.removeAll();
steps.setVisible(false);
saved = new ArrayList<Double>();
double[] values = new double[compounds.length + 1];
int sigFigs = Integer.MAX_VALUE;
for(int index = 0; index < compounds.length; index++)
{
values[index] = compounds[index].getAmount();
String name = compounds[index].getName();
name = name.substring(6, name.length() - 7); //Getting rid of the html tags
if(values[index] == Units.ERROR_VALUE)
{
results.add(new JLabel("<html>Error in value for " + name + "</html>"));
results.setVisible(true);
return;
}
else if(values[index] == Units.UNKNOWN_VALUE) steps.add(new JLabel("<html> " + name + " = ? M</html>"));
else
{
steps.add(new JLabel("<html> " + name + " = " + values[index] + " M</html>"));
sigFigs = Math.min(sigFigs, compounds[index].getSigFigs());
}
}
values[compounds.length] = k.getAmount();
if(values[compounds.length] == Units.ERROR_VALUE)
{
results.add(new JLabel("Error in value for K"));
results.setVisible(true);
return;
}
else if(values[compounds.length] == Units.UNKNOWN_VALUE) steps.add(new JLabel("K = ?"));
else
{
steps.add(new JLabel("K = " + values[compounds.length]));
sigFigs = Math.min(sigFigs, k.getSigFigs());
}
double[] extra = new double[6];
if(precipitate != null)
{
for(int index = 0; index < precipitate.length; index++)
{
extra[index] = precipitate[index].getAmount();
if(extra[index] == Units.ERROR_VALUE)
{
results.add(new JLabel("<html>Error in value for " + precipitate[index].getName().substring(7)));
results.setVisible(true);
return;
}
else if(extra[index] != Units.UNKNOWN_VALUE)
{
steps.add(new JLabel(precipitate[index].getName() + " = " + extra[index] + (index > 0 ? "L" : "")));
sigFigs = Math.min(sigFigs, precipitate[index].getSigFigs());
}
else steps.add(new JLabel(precipitate[index].getName() + " = ?"));
}
}
if(solubility != null)
{
extra[5] = solubility.getAmount();
if(extra[5] == Units.ERROR_VALUE)
{
results.add(new JLabel("Error in value for solubility."));
results.setVisible(true);
return;
}
else if(extra[5] != Units.UNKNOWN_VALUE)
{
steps.add(new JLabel("Solubility = " + extra[5] + " mol / L"));
sigFigs = Math.min(sigFigs, solubility.getSigFigs());
}
else steps.add(new JLabel("Solubility = ?"));
}
steps.add(Box.createVerticalStrut(5));
steps.add(new JLabel(expression.getIcon()));
if(precipitate != null)
{
if(values[0] == Units.UNKNOWN_VALUE && extra[0] == Units.UNKNOWN_VALUE) //Fist calculates concentrations of each ion if necessary
{
if(extra[1] == Units.UNKNOWN_VALUE || extra[2] == Units.UNKNOWN_VALUE || extra[3] == Units.UNKNOWN_VALUE || extra[4] ==
Units.UNKNOWN_VALUE)
{
results.add(new JLabel("Insufficient information for calculations."));
results.setVisible(true);
return;
}
LinkedList<String> stepList = new LinkedList<String>();
double[] concentrations = calculateConcentrations(extra, relevant, reactants, stepList);
for(String step: stepList) steps.add(new JLabel(step));
for(int index = 0; index < concentrations.length; index++)
{
values[index] = compounds[index].getBlankAmount(concentrations[index]);
saved.add(values[index]);
results.add(new JLabel("<html>" + relevant.get(index).withoutNumState() + " = " + Function.withSigFigs(values[index], sigFigs)
+ " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
}
}
else if(values[1] == Units.UNKNOWN_VALUE)
{
results.add(new JLabel("Insufficient information to calculate."));
results.setVisible(true);
return;
}
double q;
if(extra[0] == Units.UNKNOWN_VALUE)
{
//Finds Qsp and compares it to Ksp to find if there is a precipitate
LinkedList<String> stepList = new LinkedList<String>();
q = calculateK(values, stepList, powers, false);
for(String step: stepList) steps.add(new JLabel(step));
results.add(new JLabel("Q = " + Function.withSigFigs(q, sigFigs)));
}
else q = extra[0];
steps.add(new JLabel(q + (q > values[values.length - 1] ? " > " : " < ") + values[values.length - 1]));
steps.add(new JLabel("Q" + (q > values[values.length - 1] ? " > " : " < ") + "K"));
if(q > values[values.length - 1]) results.add(new JLabel("Yes, there is a precipitate."));
else results.add(new JLabel("No, there is not a precipitate."));
}
else if(before.isSelected())
{
if(values[compounds.length] == Units.UNKNOWN_VALUE) //K is unknown
{
results.add(new JLabel("Insufficient information- K needs to be specified if reaction is not at equilibrium."));
results.setVisible(true);
return;
}
else //K is known
{
//Creates the ICE table
JLabel[][] labels = new JLabel[4][values.length];
labels[0][0] = new JLabel();
labels[1][0] = new JLabel("Initial");
labels[2][0] = new JLabel("Change");
labels[3][0] = new JLabel("Equilibrium");
String equation = "<html>" + values[values.length - 1] + " = ";
String[] expressions = new String[values.length - 1];
int col = 1;
for(int index = 0; index < relevant.size(); index++)
{
if(values[index] == Units.UNKNOWN_VALUE)
{
results.add(new JLabel("Enter initial concentration for " + relevant.get(index).withoutNumState()));
results.setVisible(true);
return;
}
labels[0][col] = new JLabel("<html>[" + relevant.get(index).withoutNumState() + "]");
labels[1][col] = new JLabel(values[index] + "");
labels[2][col] = new JLabel((powers.get(index) == 1 ? "" : powers.get(index)) + "x");
labels[3][col] = new JLabel((values[index] == 0 ? "" : values[index] + " + ") + (powers.get(index) == 1 ? "" :
(powers.get(index) == -1 ? "-" : powers.get(index))) + "x");
expressions[index] = labels[0][col].getText() + " = " + labels[3][col].getText();
equation += "(" + labels[3][col].getText() + ")<sup>" + powers.get(index) + "</sup> * ";
col++;
}
JPanel table = new JPanel(new GridLayout(4, values.length));
for(JLabel[] row: labels)
{
for(JLabel label: row)
{
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
table.add(label);
}
}
steps.add(table);
steps.add(new JLabel(equation.substring(0, equation.length() - 3) + "</html>"));
//If powers are too high, solves approximately
int sum = 0, index = 0;
double product = 1;
boolean zero = true;
for(; index < powers.size() && powers.get(index) > 0; sum += powers.get(index), index++)
{
if(values[index] != 0) zero = false;
else product *= Math.pow(powers.get(index), powers.get(index));
}
if(sum > 2) //and thus can't be solved as a quadratic
{
if(zero)
{
LinkedList<String> stepList = new LinkedList<String>();
double[] concentrations = solveApprox(values, product, sum, index, powers, stepList, expressions);
for(String step: stepList) steps.add(new JLabel(step));
for(int i = 0; i < concentrations.length; i++)
{
double val = compounds[i].getBlankAmount(concentrations[i]);
saved.add(val);
results.add(new JLabel("<html>[" + relevant.get(i).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)));
}
}
else
{
results.add(new JLabel("ChemHelper cannot solve this equation."));
}
}
else
{
LinkedList<String> stepList = new LinkedList<String>();
double[] concentrations = solveICE(values, powers, stepList, expressions);
for(String step: stepList) steps.add(new JLabel(step));
for(int i = 0; i < concentrations.length; i++)
{
double val = compounds[i].getBlankAmount(concentrations[i]);
saved.add(val);
results.add(new JLabel("<html>[" + relevant.get(i).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)));
}
}
//Things were aligning really weirdly
for(Component c: steps.getComponents()) ((JComponent)c).setAlignmentX(Component.LEFT_ALIGNMENT);
}
}
else //if after is selected
{
if(solubility != null && extra[5] != Units.UNKNOWN_VALUE)
{
LinkedList<String> stepList = new LinkedList<String>();
values = calculateFromSolubility(extra[5], stepList, relevant, powers);
for(String step: stepList) steps.add(new JLabel(step));
for(int index = 0; index < values.length - 1; index++)
{
values[index] = compounds[index].getBlankAmount(values[index]);
saved.add(values[index]);
results.add(new JLabel("<html>["+ relevant.get(index).withoutNumState() + "] = " + Function.withSigFigs(values[index], sigFigs)
+ " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
}
saved.add(values[values.length - 1]);
results.add(new JLabel("K = " + Function.withSigFigs(values[values.length - 1], sigFigs)));
}
else
{
int unknown = -1;
for(int index = 0; index < compounds.length; index++)
{
if(values[index] == Units.UNKNOWN_VALUE)
{
if(unknown == -1) unknown = index;
else
{
unknown = Integer.MAX_VALUE;
break;
}
}
}
if(values[compounds.length] == Units.UNKNOWN_VALUE) //K is unknown
{
if(unknown != -1)
{
results.add(new JLabel("To calculate K, enter the concentrations of all compounds."));
results.setVisible(true);
return;
}
LinkedList<String> stepList = new LinkedList<String>();
double result = calculateK(values, stepList, powers, true);
for(String step: stepList) steps.add(new JLabel(step));
saved.add(result);
results.add(new JLabel("K = " + Function.withSigFigs(result, sigFigs)));
}
else //K is known
{
if(unknown == -1)
{
results.add(new JLabel("Leave a value blank."));
results.setVisible(true);
return;
}
else if(unknown == Integer.MAX_VALUE)
{
LinkedList<String> stepList = new LinkedList<String>();
double[] x = new double[1];
LinkedList<Integer> changed = calculateValues(values, stepList, powers, relevant, x);
if(changed == null)
{
results.add(new JLabel(stepList.getLast()));
results.setVisible(false);
return;
}
for(String step: stepList) steps.add(new JLabel(step));
for(Integer index: changed)
{
double val = compounds[index].getBlankAmount(values[index]);
saved.add(val);
results.add(new JLabel("<html>[" + relevant.get(index).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)
+ " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
}
if(solubility != null)
{
double result = solubility.getBlankAmount(x[0]);
String unit = solubility.getUnitName() + " / " + solubility.getUnit2Name();
steps.add(new JLabel("Solubility = x = " + result + " " + unit));
saved.add(result);
results.add(new JLabel("Solubility = " + Function.withSigFigs(result, sigFigs) + " " + unit));
extra[5] = result; //So it won't accidentally be recalculated later
}
}
else
{
LinkedList<String> stepList = new LinkedList<String>();
double result = calculateConcentration(values, stepList, powers, unknown);
for(String step: stepList) steps.add(new JLabel(step));
saved.add(compounds[unknown].getBlankAmount(result));
if(result != saved.get(0)) steps.add(new JLabel("x = " + saved.get(0) + " " + compounds[unknown].getUnitName() + " / "
+ compounds[unknown].getUnit2Name()));
results.add(new JLabel("<html>[" + relevant.get(unknown).withoutNumState() + "] = " +
Function.withSigFigs(saved.get(0), sigFigs)));
values[unknown] = result; //In case it it needed to calculate solubility later
}
}
}
}
if(solubility != null && extra[5] == Units.UNKNOWN_VALUE)
{
steps.add(new JLabel("Solubility * " + relevant.get(0).getNum() + " = " + compounds[0].getName().substring(6)));
double s = values[0] / relevant.get(0).getNum();
steps.add(new JLabel("Solubility = " + values[0] + " / " + relevant.get(0).getNum() + " = " + s + " mol / L"));
s = solubility.getBlankAmount(s);
saved.add(s);
results.add(new JLabel("Solubility = " + s + " " + solubility.getUnitName() + " / " + solubility.getUnit2Name()));
}
steps.setVisible(true);
results.setVisible(true);
}
});
reset = new JButton("Reset");
reset.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
setPanel();
}
});
JPanel buttons2 = new JPanel();
buttons2.add(calculate);
buttons2.add(reset);
enterPanel.add(buttons2, c);
c.gridy++;
results = Box.createVerticalBox();
enterPanel.add(results, c);
enterPanel.setVisible(false);
JPanel subpanel = new JPanel(new GridBagLayout());
c.gridy = 0;
c.gridx = 0;
c.anchor = GridBagConstraints.NORTH;
subpanel.add(enterPanel, c);
c.gridx++;
subpanel.add(Box.createHorizontalStrut(10), c);
c.gridx++;
steps = Box.createVerticalBox();
subpanel.add(steps);
panel = new JPanel();
panel.add(reader.getPanel());
panel.add(subpanel);
}
/*
* Returns the panel to its original state after the rest button has been pressed.
*/
private void setPanel()
{
expression.setIcon(null);
fields.removeAll();
compounds = null;
k = null;
precipitate = null;
solubility = null;
results.removeAll();
steps.removeAll();
enterPanel.setVisible(false);
panel.add(reader.getPanel());
}
/*
* Calculates the value of K given the concentrations of the relevant compounds.
*/
private static double calculateK(double[] values, LinkedList<String> steps, ArrayList<Integer> powers, boolean k)
{
double value = 1;
String step1 = "<html>" + (k ? "K" : "Q") + " = ", step2 = "<html>" + (k ? "K" : "Q") + " = "; //Step 1 shows multiplication before raising to powers,
//step 2 shows after
for(int index = 0; index < values.length - 1; index++)
{
step1 += "(" + values[index] + ")<sup>" + powers.get(index) + "</sup> * ";
double num = Math.pow(values[index], powers.get(index));
step2 += num + " * ";
value *= num;
}
step1 = step1.substring(0, step1.length() - 3);
step2 = step2.substring(0, step2.length() - 3);
steps.add(step1);
steps.add(step2);
steps.add((k ? "K" : "Q") + " = " + value);
return value;
}
/*
* Calculates one concentration given all the others and K.
*/
public static double calculateConcentration(double[] values, LinkedList<String> steps, ArrayList<Integer> powers, int unknown)
{
double value = 1;
String step1 = "<html>" + values[values.length - 1] + " = ", step2 = "<html>" + values[values.length - 1] + " = ";
for(int index = 0; index < values.length - 1; index++)
{
if(index != unknown)
{
step1 += "(" + values[index] + ")<sup>" + powers.get(index) + "</sup> * ";
double num = Math.pow(values[index], powers.get(index));
step2 += num + " * ";
value *= num;
}
else
{
step1 += "x<sup>" + powers.get(index) + "</sup> * ";
step2 += "x<sup>" + powers.get(index) + "</sup> * ";
}
}
step1 = step1.substring(0, step1.length() - 3);
step2 = step2.substring(0, step2.length() - 3);
steps.add(step1);
steps.add(step2);
value = values[values.length - 1] / value;
steps.add("<html>x<sup>" + powers.get(unknown) + "</sup> = " + value);
value = Math.pow(value, 1.0 / powers.get(unknown));
steps.add("x = " + value + " mol / L");
return value;
}
/*
* Calculates all unknown concentrations given the others and K and returns the indices in values which have been changed, or null if there is insufficient
* information for the calculations.
*/
public static LinkedList<Integer> calculateValues(double[] values, LinkedList<String> steps, ArrayList<Integer> powers, ArrayList<Compound> compounds,
double[] storeX)
{
double newK = values[values.length - 1]; //Will divide K by all known concentrations
String stepK = "<html>" + newK + " / ";
LinkedList<Integer> changed = new LinkedList<Integer>(); //To put in relevant indices
for(int index = 0; index < compounds.size(); index++)
{
if(values[index] == Units.UNKNOWN_VALUE)
{
if(powers.get(index) < 0) //If K is dependent on compounds on the left, the ratios can't be used for concentrations
{
steps.add("Insufficient information for calculations.");
return null;
}
else
{
steps.add("<html>[" + compounds.get(index).withoutNumState() + "] = " + (powers.get(index) == 1 ? "" : powers.get(index)) + "x");
changed.add(index);
}
}
else
{
newK /= Math.pow(values[index], powers.get(index));
stepK += "(" + values[index] + ")<sup>" + powers.get(index) + "</sup> / ";
}
}
if(newK != values[values.length - 1])
{
steps.add("Divide K by known concentrations:");
steps.add(stepK.substring(0, stepK.length() - 3) + " = " + newK); //Gets rid of last / before adding equals
}
String step = "<html>" + newK + " = ";
int value = 1, sum = 0;
for(int index = 0; index < values.length - 1; index++)
{
int power = powers.get(index);
value *= Math.pow(power, power);
sum += power;
step += "(" + (power == 1 ? "" : power) + "x)<sup>" + power + "</sup> * ";
}
steps.add(step.substring(0, step.length() - 3)); //Removes last *
if(value != 1)
{
steps.add("<html>" + newK + " = " + (value == 1 ? "" : value + " * ") + "x<sup>" + sum + "</sup><html>");
newK /= value;
}
steps.add("<html>" + newK + " = x<sup>" + sum + "</sup><html>");
double x = Math.pow(newK, (1 / (double)sum));
steps.add("x = " + x);
storeX[0] = x;
for(Integer index: changed)
{
int power = powers.get(index);
values[index] = x * power;
steps.add("<html>[" + compounds.get(index).withoutNumState() + "] = " + (power == 1 ? "" : power) + "x = " + values[index] + " mol / L</html>");
}
return changed;
}
/*
* Solves the ICE table approximately by assuming that in the denominator x does not matter.
*/
public static double[] solveApprox(double[] original, double product, int sum, int index, ArrayList<Integer> powers, LinkedList<String> steps, String[] ex)
{
double denom = 1;
String fraction = "<html>" + original[original.length - 1] + " = " + product + "x<sup>" + sum + "</sup> / (";
for(; index < powers.size(); index++)
{
steps.add("Assume " + original[index] + " - " + (powers.get(index) == -1 ? "" : -powers.get(index)) + "x \u2245 " + original[index]);
fraction += original[index] + "<sup>" + -powers.get(index) + "</sup> * ";
denom *= Math.pow(original[index], -powers.get(index));
}
steps.add(fraction.substring(0, fraction.length() - 3) + ")</html>");
double x = original[original.length - 1] * denom / product;
steps.add("<html>" + x + " = x<sup>" + sum + "</sup></html>");
x = Math.pow(x, 1.0 / sum);
steps.add("x = " + x);
double[] results = new double[original.length - 1];
for(int i = 0; i < powers.size(); i++)
{
results[i] = original[i] + powers.get(i) * x;
steps.add(ex[i] + " = " + results[i] + " M");
}
return results;
}
/*
* Solves the ICE table with quadratic equations. Returns null if it cannot be solved.
*/
public static double[] solveICE(double[] original, ArrayList<Integer> powers, LinkedList<String> steps, String[] expressions)
{
double[][] num = new double[2][2], denom = new double[2][2]; //Will hold the linear expressions to be multiplied
int index = 0;
num[0][0] = powers.get(index);
num[0][1] = original[index];
if(powers.get(index) == 2)
{
num[1][0] = powers.get(index);
num[1][1] = original[index];
index++;
}
else
{
index++;
num[1][0] = powers.get(index);
num[1][1] = original[index];
index++;
}
denom[0][0] = powers.get(index);
denom[0][1] = original[index];
if(powers.get(index) == 2)
{
denom[1][0] = powers.get(index);
denom[1][1] = original[index];
index++;
}
else
{
index++;
denom[1][0] = powers.get(index);
denom[1][1] = original[index];
index++;
}
double[] top = foil(num), bottom = foil(denom);
steps.add("<html>" + original[original.length - 1] + " = (" + displayQuadratic(top) + ") / (" + displayQuadratic(bottom) + ")</html>");
for(int i = 0; i < bottom.length; i++)
{
bottom[i] *= original[original.length - 1];
}
steps.add("<html>" + displayQuadratic(bottom) + " = " + displayQuadratic(top) + "</html>");
for(int i = 0; i < bottom.length; i++)
{
top[i] -= bottom[i];
}
steps.add("<html>0 = " + displayQuadratic(top) + "</html>");
double x = (-top[1] + Math.sqrt(top[1] * top[1] - 4 * top[0] * top[2])) / (2 * top[0]); //Uses higher root only
steps.add("x = " + x);
double[] results = new double[original.length - 1];
for(int i = 0; i < powers.size(); i++)
{
results[i] = original[i] + powers.get(i) * x;
steps.add(expressions[i] + " = " + results[i] + " M");
}
return results;
}
private static double[] foil(double[][] factors)
{
double[] expression = new double[3];
expression[0] = factors[0][0] * factors[1][0];
expression[1] = factors[0][0] * factors[1][1] + factors[1][0] * factors[0][1];
expression[2] = factors[0][1] * factors[1][1];
return expression;
}
private static String displayQuadratic(double[] expression)
{
String str = "";
if(expression[0] == -1) str += "-";
else if(expression[0] != 1 && expression[0] != 0) str += expression[0];
if(expression[0] != 0) str += "x<sup>2</sup>";
if(expression[1] != 0)
{
if(str.length() != 0) str += expression[1] > 0 ? " + " : " - ";
if(expression[1] != 1 && expression[1] != -1) str += Math.abs(expression[1]);
str += "x";
}
if(expression[2] != 0)
{
if(str.length() != 0) str += expression[2] > 0 ? " + " : " - ";
if(expression[2] != 1 && expression[2] != -1) str += Math.abs(expression[2]);
}
return str;
}
/*
* Calculates the concentrations of each compound and K from the solubility of the solid.
*/
public static double[] calculateFromSolubility(double s, LinkedList<String> steps, ArrayList<Compound> relevant, ArrayList<Integer> powers)
{
double[] values = new double[relevant.size() + 1];
String step1 = "<html>k = ", step2 = "<html>k = "; //Calculates k as it goes
values[values.length - 1] = 1;
for(int index = 0; index < relevant.size(); index++)
{
String compound = "[" + relevant.get(index).withoutNumState() + "]";
int power = powers.get(index);
values[index] = s * power;
steps.add("<html>" + compound + " = " + s + " * " + power + " = " + values[index] + " mol / L</html>");
step1 += compound + "<sup>" + power + "</sup> * ";
step2 += "(" + values[index] + ")<sup>" + power + "</sup> * ";
values[values.length - 1] *= Math.pow(values[index], power);
}
steps.add(step1.substring(0, step1.length() - 3) + "<html>");
steps.add(step2.substring(0, step2.length() - 3) + "<html>");
steps.add("k = " + values[values.length - 1]);
return values;
}
public static double[] calculateConcentrations(double[] values, ArrayList<Compound> compounds, Compound[] original, LinkedList<String> steps)
{
double[] concentrations = new double[2];
int[] coefficients = new int[2]; //Finds the coefficients of each ion in the reactants
coefficients[0] = original[0].numberOf((compounds.get(0).getIons()[0].getElements()[0].getElement()));
if(coefficients[0] == 0)
{
coefficients[0] = original[1].numberOf((compounds.get(0).getIons()[0].getElements()[0].getElement()));
coefficients[1] = original[0].numberOf((compounds.get(1).getIons()[0].getElements()[0].getElement()));
//The values will be in the wrong order for the calculations
double temp = values[1];
values[1] = values[3];
values[3] = temp;
temp = values[2];
values[2] = values[4];
values[4] = temp;
}
else coefficients[1] = original[1].numberOf((compounds.get(1).getIons()[0].getElements()[0].getElement()));
steps.add("<html>[" + compounds.get(0).withoutNumState() + "] = " + values[1] + " * " + values[2] + " * " + coefficients[0] + " / (" + values[1] +
" + " + values[3] + ")</html>");
concentrations[0] = values[1] * values[2] * coefficients[0] / (values[1] + values[3]);
steps.add("<html>[" + compounds.get(0).withoutNumState() + "] = " + concentrations[0] + " mol / L</html>)");
steps.add("<html>[" + compounds.get(1).withoutNumState() + "] = " + values[3] + " * " + values[4] + " * " + coefficients[1] + " / (" + values[1] +
" + " + values[3] + ")</html>");
concentrations[1] = values[3] * values[4] * coefficients[1] / (values[1] + values[3]);
steps.add("<html>[" + compounds.get(1).withoutNumState() + "] = " + concentrations[1] + " mol / L</html>)");
return concentrations;
}
public boolean equation()
{
return true;
}
public Equation saveEquation()
{
return reader.saveEquation();
}
/*
* Takes equation and sets up EnterFields to perform calculations with the compounds in the equation.
*/
public void useSaved(Equation equation)
{
//States of matter are necessary to make an equilibrium expression
{
for(Compound c: equation.getLeft())
{
c.checkForPoly();
if(c.getState().equals(" ") && !getState(c)) return;
}
for(Compound c: equation.getRight())
{
c.checkForPoly();
if(c.getState().equals(" ") && !getState(c)) return;
}
}
int type = equation.isDoubleDisplacement();
reactants = new Compound[2];
if(type == 1)
{
ArrayList<Compound> left = equation.getLeft();
reactants[0] = left.get(0);
reactants[1] = left.get(1);
equation.removeSpectators();
}
panel.remove(reader.getPanel());
relevant = new ArrayList<Compound>();
ArrayList<Compound> irrelevant = new ArrayList<Compound>();
powers = new ArrayList<Integer>();
String ex = equation.getEquilibrium(relevant, irrelevant, powers);
TeXFormula formula = new TeXFormula(ex);
TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
icon.paintIcon(new JLabel(), image.getGraphics(), 0, 0);
expression.setIcon(icon);
compounds = new EnterField[relevant.size()];
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
for(int index = 0; index < compounds.length; index++)
{
EnterField field = new EnterField("<html>[" + relevant.get(index).withoutNumState() + "]</html>", "Amount", "Volume");
compounds[index] = field;
fields.add(field, c);
c.gridy++;
}
k = new EnterField("K");
fields.add(k, c);
if(type != -1)
{
Double kValue = KSP.get(irrelevant.get(0).withoutNumState());
if(kValue != null)
{
JCheckBox stored = new JCheckBox("Use stored value for K");
stored.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if(stored.isSelected()) k.setAmount(kValue);
}
});
c.gridy++;
fields.add(stored, c);
}
int pre = 0;
if(type == 1)
{
pre = JOptionPane.showConfirmDialog(panel, "Does the question involve finding whether there is a precipitate?", "Choose Type",
JOptionPane.YES_NO_OPTION);
}
if(type == 0 || pre != 0)
{
solubility = new EnterField("Solubility", "Amount", "Volume");
c.gridy++;
fields.add(solubility, c);
}
else
{
precipitate = new EnterField[5];
precipitate[0] = new EnterField("Q");
c.gridy++;
fields.add(precipitate[0], c);
for(int index = 1; index < precipitate.length; index += 2)
{
precipitate[index] = new EnterField("<html>Volume " + reactants[index / 2].withoutNumState(), "Volume");
c.gridy++;
fields.add(precipitate[index], c);
precipitate[index + 1] = new EnterField("<html>[" + reactants[index / 2].withoutNumState() + "]", "Amount", "Volume");
c.gridy++;
fields.add(precipitate[index + 1], c);
}
}
}
enterPanel.setVisible(true);
}
/*
* Prompts the user to choose a state for the compound. If they do, returns true, returns false otherwise.
*/
private boolean getState(Compound c)
{
Object obj = JOptionPane.showInputDialog(panel, "<html>Please enter the state of matter of " + c + "</html>", "State", JOptionPane.QUESTION_MESSAGE,
null, Compound.getValidstates().toArray(), "aq");
if(obj == null) return false;
c.setState((String)obj);
return true;
}
public boolean number()
{
return true;
}
public double saveNumber()
{
if(saved.size() == 0) return 0;
if(saved.size() == 1) return saved.get(0);
Object obj = JOptionPane.showInputDialog(panel, "Choose a number to save.", "Save Number", JOptionPane.QUESTION_MESSAGE, null, saved.toArray(),
saved.get(0));
if(obj != null) return (Double) obj;
return 0;
}
public void useSavedNumber(double num)
{
if(k == null) return;
String[] list = new String[compounds.length + (solubility != null ? 2 : precipitate != null ? 6 : 1)];
for(int index = 0; index < compounds.length; index++)
{
list[index] = compounds[index].getName();
}
list[compounds.length] = "K";
if(solubility != null) list[list.length - 1] = "Solubility";
else if(precipitate != null)
{
for(int index = compounds.length + 1; index < list.length; index++)
{
list[index] = precipitate[index - compounds.length - 1].getName();
}
}
Object obj = JOptionPane.showInputDialog(panel, "Choose where to use the number.", "Use Saved", JOptionPane.QUESTION_MESSAGE, null, list, list[0]);
if(obj == null) return;
for(int index = 0; index < compounds.length; index++)
{
if(list[index].equals(obj))
{
compounds[index].setAmount(num);
return;
}
}
if(obj.equals("K"))
{
k.setAmount(num);
return;
}
if(obj.equals("Solubility"))
{
solubility.setAmount(num);
return;
}
for(int index = compounds.length + 1; index < list.length; index++)
{
if(obj.equals(precipitate[index - compounds.length - 1].getName()))
{
precipitate[index - compounds.length - 1].setAmount(num);
return;
}
}
}
private static TreeMap<String, Double> createMap()
{
TreeMap<String, Double> map = new TreeMap<String, Double>();
map.put("Al(OH)<sub>3</sub>", 1.8E-33);
map.put("BaCO<sub>3</sub>", 8.1E-9);
map.put("BaF<sub>2</sub>", 1.7E-6);
map.put("BaSO<sub>4</sub>", 1.1E-10);
map.put("Bi<sub>2</sub>S<sub>3</sub>", 1.6E-72);
map.put("CdS", 8E-28);
map.put("CaCO<sub>3</sub>", 8.7E-9);
map.put("CaF<sub>2</sub>", 3.9E-11);
map.put("Ca(OH)<sub>2</sub>", 8E-6);
map.put("Ca<sub>3</sub>(PO<sub>4</sub>)<sub>2</sub>", 1.2E-26);
map.put("Cr(OH)<sub>3</sub>", 3E-29);
map.put("CoS", 4E-21);
map.put("CuBr", 4.2E-8);
map.put("CuI", 5.1E-12);
map.put("Cu(OH)<sub>2</sub>", 2.2E-20);
map.put("CuS", 6E-37);
map.put("Fe(OH)<sub>2</sub>", 1.6E-14);
map.put("Fe(OH)<sub>3</sub>", 1.1E-36);
map.put("FeS", 6E-19);
map.put("PbCO<sub>3</sub>", 3.3E-14);
map.put("PbCl<sub>2</sub>", 2.4E-4);
map.put("PbCrO<sub>4</sub>", 2E-14);
map.put("PbF<sub>2</sub>", 4.1E-8);
map.put("PbI<sub>2</sub>", 1.4E-8);
map.put("PbS", 3.4E-28);
map.put("MgCO<sub>3</sub>", 4E-3);
map.put("Mg(OH)<sub>2</sub>", 1.2E-11);
map.put("MnS", 3E-14);
map.put("Hg<sub>2</sub>Cl<sub>2</sub>", 3.5E-18);
map.put("Hg(OH)<sub>2</sub>", 3.1E-26);
map.put("HgS", 4E-54);
map.put("Ni(OH)<sub>2</sub>", 5.5E-16);
map.put("NiS", 1.4E-24);
map.put("AgBr", 7.7E-13);
map.put("Ag<sub>2</sub>CO<sub>3</sub>", 8.1E-12);
map.put("AgCl", 1.6E-10);
map.put("AgI", 8.3E-17);
map.put("Ag<sub>2</sub>SO<sub>4</sub>", 1.4E-5);
map.put("Ag<sub>2</sub>S", 6E-51);
map.put("SrCO<sub>3</sub>", 1.6E-9);
map.put("SrSO<sub>4</sub>", 3.8E-7);
map.put("Sn(OH)<sub>2</sub>", 5.4E-27);
map.put("SnS", 1E-26);
map.put("Zn(OH)<sub>2</sub>", 1.8E-14);
map.put("ZnS", 3E-23);
return map;
}
public JPanel getPanel()
{
return panel;
}
} | src/Functions/Equilibrium.java | /*
* Performs various calculations for functions at equilibrium.
*
* Author: Julia McClellan
* Version: 3/27/2016
*/
package Functions;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.TreeMap;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import Equation.Compound;
import Equation.Equation;
import HelperClasses.EnterField;
import HelperClasses.Units;
public class Equilibrium extends Function
{
public static TreeMap<String, Double> KSP = createMap();
private JPanel panel, enterPanel, fields;
private EquationReader reader;
private JLabel expression;
private EnterField[] compounds, precipitate;
private EnterField k, solubility;
private JButton calculate, reset;
private Box steps, results;
private JRadioButton before;
private ArrayList<Double> saved;
private ArrayList<Compound> relevant;
private ArrayList<Integer> powers;
private Compound[] reactants;
public Equilibrium()
{
super("Equilibrium");
saved = new ArrayList<Double>();
reader = new EquationReader(this);
enterPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
expression = new JLabel();
enterPanel.add(expression, c);
c.gridy++;
before = new JRadioButton("Before reaction");
JRadioButton after = new JRadioButton("At equilibrium", true);
ButtonGroup g = new ButtonGroup();
g.add(before);
g.add(after);
JPanel buttons = new JPanel();
buttons.add(after);
buttons.add(before);
enterPanel.add(buttons, c);
c.gridy++;
fields = new JPanel(new GridBagLayout());
enterPanel.add(fields, c);
c.gridy++;
calculate = new JButton("Calculate");
calculate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
results.removeAll();
results.setVisible(false);
steps.removeAll();
steps.setVisible(false);
saved = new ArrayList<Double>();
double[] values = new double[compounds.length + 1];
int sigFigs = Integer.MAX_VALUE;
for(int index = 0; index < compounds.length; index++)
{
values[index] = compounds[index].getAmount();
String name = compounds[index].getName();
name = name.substring(6, name.length() - 7); //Getting rid of the html tags
if(values[index] == Units.ERROR_VALUE)
{
results.add(new JLabel("<html>Error in value for " + name + "</html>"));
results.setVisible(true);
return;
}
else if(values[index] == Units.UNKNOWN_VALUE) steps.add(new JLabel("<html> " + name + " = ? M</html>"));
else
{
steps.add(new JLabel("<html> " + name + " = " + values[index] + " M</html>"));
sigFigs = Math.min(sigFigs, compounds[index].getSigFigs());
}
}
values[compounds.length] = k.getAmount();
if(values[compounds.length] == Units.ERROR_VALUE)
{
results.add(new JLabel("Error in value for K"));
results.setVisible(true);
return;
}
else if(values[compounds.length] == Units.UNKNOWN_VALUE) steps.add(new JLabel("K = ?"));
else
{
steps.add(new JLabel("K = " + values[compounds.length]));
sigFigs = Math.min(sigFigs, k.getSigFigs());
}
double[] extra = new double[6];
if(precipitate != null)
{
for(int index = 0; index < precipitate.length; index++)
{
extra[index] = precipitate[index].getAmount();
if(extra[index] == Units.ERROR_VALUE)
{
results.add(new JLabel("<html>Error in value for " + precipitate[index].getName().substring(7)));
results.setVisible(true);
return;
}
else if(extra[index] != Units.UNKNOWN_VALUE)
{
steps.add(new JLabel(precipitate[index].getName() + " = " + extra[index] + (index > 0 ? "L" : "")));
sigFigs = Math.min(sigFigs, precipitate[index].getSigFigs());
}
else steps.add(new JLabel(precipitate[index].getName() + " = ?"));
}
}
if(solubility != null)
{
extra[5] = solubility.getAmount();
if(extra[5] == Units.ERROR_VALUE)
{
results.add(new JLabel("Error in value for solubility."));
results.setVisible(true);
return;
}
else if(extra[5] != Units.UNKNOWN_VALUE)
{
steps.add(new JLabel("Solubility = " + extra[5] + " mol / L"));
sigFigs = Math.min(sigFigs, solubility.getSigFigs());
}
else steps.add(new JLabel("Solubility = ?"));
}
steps.add(Box.createVerticalStrut(5));
steps.add(new JLabel(expression.getIcon()));
if(precipitate != null)
{
if(values[0] == Units.UNKNOWN_VALUE) //Fist calculates concentrations of each ion if necessary
{
LinkedList<String> stepList = new LinkedList<String>();
double[] concentrations = calculateConcentrations(extra, relevant, reactants, stepList);
for(String step: stepList) steps.add(new JLabel(step));
for(int index = 0; index < concentrations.length; index++)
{
values[index] = compounds[index].getBlankAmount(concentrations[index]);
saved.add(values[index]);
results.add(new JLabel("<html>" + relevant.get(index).withoutNumState() + " = " + Function.withSigFigs(values[index], sigFigs)
+ " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
}
}
else if(values[1] == Units.UNKNOWN_VALUE)
{
results.add(new JLabel("Insufficient information to calculate."));
results.setVisible(true);
return;
}
//Finds Qsp and compares it to Ksp to find if there is a precipitate
LinkedList<String> stepList = new LinkedList<String>();
double q = calculateK(values, stepList, powers, false);
for(String step: stepList) steps.add(new JLabel(step));
results.add(new JLabel("Q = " + Function.withSigFigs(q, sigFigs)));
steps.add(new JLabel(q + (q > values[values.length - 1] ? " > " : " < ") + values[values.length - 1]));
steps.add(new JLabel("Q" + (q > values[values.length - 1] ? " > " : " < ") + "K"));
if(q > values[values.length - 1]) results.add(new JLabel("Yes, there is a precipitate."));
else results.add(new JLabel("No, there is not a precipitate."));
}
else if(before.isSelected())
{
if(values[compounds.length] == Units.UNKNOWN_VALUE) //K is unknown
{
results.add(new JLabel("Insufficient information- K needs to be specified if reaction is not at equilibrium."));
results.setVisible(true);
return;
}
else //K is known
{
//Creates the ICE table
JLabel[][] labels = new JLabel[4][values.length];
labels[0][0] = new JLabel();
labels[1][0] = new JLabel("Initial");
labels[2][0] = new JLabel("Change");
labels[3][0] = new JLabel("Equilibrium");
String equation = "<html>" + values[values.length - 1] + " = ";
String[] expressions = new String[values.length - 1];
int col = 1;
for(int index = 0; index < relevant.size(); index++)
{
if(values[index] == Units.UNKNOWN_VALUE) values[index] = 0;
labels[0][col] = new JLabel("<html>[" + relevant.get(index).withoutNumState() + "]");
labels[1][col] = new JLabel(values[index] + "");
labels[2][col] = new JLabel((powers.get(index) == 1 ? "" : powers.get(index)) + "x");
labels[3][col] = new JLabel((values[index] == 0 ? "" : values[index] + " + ") + (powers.get(index) == 1 ? "" :
(powers.get(index) == -1 ? "-" : powers.get(index))) + "x");
expressions[index] = labels[0][col].getText() + " = " + labels[3][col].getText();
equation += "(" + labels[3][col].getText() + ")<sup>" + powers.get(index) + "</sup> * ";
col++;
}
JPanel table = new JPanel(new GridLayout(4, values.length));
for(JLabel[] row: labels)
{
for(JLabel label: row)
{
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
table.add(label);
}
}
steps.add(table);
steps.add(new JLabel(equation.substring(0, equation.length() - 3) + "</html>"));
//If powers are too high, solves approximately
int sum = 0, index = 0;
double product = 1;
boolean zero = true;
for(; index < powers.size() && powers.get(index) > 0; sum += powers.get(index), index++)
{
if(values[index] != 0) zero = false;
else product *= Math.pow(powers.get(index), powers.get(index));
}
if(sum > 2) //and thus can't be solved as a quadratic
{
if(zero)
{
LinkedList<String> stepList = new LinkedList<String>();
double[] concentrations = solveApprox(values, product, sum, index, powers, stepList, expressions);
for(String step: stepList) steps.add(new JLabel(step));
for(int i = 0; i < concentrations.length; i++)
{
double val = compounds[i].getBlankAmount(concentrations[i]);
saved.add(val);
results.add(new JLabel("<html>[" + relevant.get(i).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)));
}
}
else
{
results.add(new JLabel("ChemHelper cannot solve this equation."));
}
}
else
{
LinkedList<String> stepList = new LinkedList<String>();
double[] concentrations = solveICE(values, powers, stepList, expressions);
for(String step: stepList) steps.add(new JLabel(step));
for(int i = 0; i < concentrations.length; i++)
{
double val = compounds[i].getBlankAmount(concentrations[i]);
saved.add(val);
results.add(new JLabel("<html>[" + relevant.get(i).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)));
}
}
//Things were aligning really weirdly
for(Component c: steps.getComponents()) ((JComponent)c).setAlignmentX(Component.LEFT_ALIGNMENT);
}
}
else //if after is selected
{
if(solubility != null && extra[5] != Units.UNKNOWN_VALUE)
{
LinkedList<String> stepList = new LinkedList<String>();
values = calculateFromSolubility(extra[5], stepList, relevant, powers);
for(String step: stepList) steps.add(new JLabel(step));
for(int index = 0; index < values.length - 1; index++)
{
values[index] = compounds[index].getBlankAmount(values[index]);
saved.add(values[index]);
results.add(new JLabel("<html>["+ relevant.get(index).withoutNumState() + "] = " + Function.withSigFigs(values[index], sigFigs)
+ " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
}
saved.add(values[values.length - 1]);
results.add(new JLabel("K = " + Function.withSigFigs(values[values.length - 1], sigFigs)));
}
else if(values[compounds.length] == Units.UNKNOWN_VALUE) //K is unknown
{
LinkedList<String> stepList = new LinkedList<String>();
double result = calculateK(values, stepList, powers, true);
for(String step: stepList) steps.add(new JLabel(step));
saved.add(result);
results.add(new JLabel("K = " + Function.withSigFigs(result, sigFigs)));
}
else //K is known
{
int unknown = -1;
for(int index = 0; index < compounds.length; index++)
{
if(values[index] == Units.UNKNOWN_VALUE)
{
if(unknown == -1) unknown = index;
else
{
unknown = Integer.MAX_VALUE;
break;
}
}
}
if(unknown == -1)
{
results.add(new JLabel("Leave a value blank."));
results.setVisible(true);
return;
}
else if(unknown == Integer.MAX_VALUE)
{
LinkedList<String> stepList = new LinkedList<String>();
double[] x = new double[1];
LinkedList<Integer> changed = calculateValues(values, stepList, powers, relevant, x);
if(changed == null)
{
results.add(new JLabel(stepList.getLast()));
results.setVisible(false);
return;
}
for(String step: stepList) steps.add(new JLabel(step));
for(Integer index: changed)
{
double val = compounds[index].getBlankAmount(values[index]);
saved.add(val);
results.add(new JLabel("<html>[" + relevant.get(index).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)
+ " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
}
if(solubility != null)
{
double result = solubility.getBlankAmount(x[0]);
String unit = solubility.getUnitName() + " / " + solubility.getUnit2Name();
steps.add(new JLabel("Solubility = x = " + result + " " + unit));
saved.add(result);
results.add(new JLabel("Solubility = " + Function.withSigFigs(result, sigFigs) + " " + unit));
extra[5] = result; //So it won't accidentally be recalculated later
}
}
else
{
LinkedList<String> stepList = new LinkedList<String>();
double result = calculateConcentration(values, stepList, powers, unknown);
for(String step: stepList) steps.add(new JLabel(step));
saved.add(compounds[unknown].getBlankAmount(result));
if(result != saved.get(0)) steps.add(new JLabel("x = " + saved.get(0) + " " + compounds[unknown].getUnitName() + " / "
+ compounds[unknown].getUnit2Name()));
results.add(new JLabel("<html>[" + relevant.get(unknown).withoutNumState() + "] = " +
Function.withSigFigs(saved.get(0), sigFigs)));
values[unknown] = result; //In case it it needed to calculate solubility later
}
}
}
if(solubility != null && extra[5] == Units.UNKNOWN_VALUE)
{
steps.add(new JLabel("Solubility * " + relevant.get(0).getNum() + " = " + compounds[0].getName().substring(6)));
double s = values[0] / relevant.get(0).getNum();
steps.add(new JLabel("Solubility = " + values[0] + " / " + relevant.get(0).getNum() + " = " + s + " mol / L"));
s = solubility.getBlankAmount(s);
saved.add(s);
results.add(new JLabel("Solubility = " + s + " " + solubility.getUnitName() + " / " + solubility.getUnit2Name()));
}
steps.setVisible(true);
results.setVisible(true);
}
});
reset = new JButton("Reset");
reset.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
setPanel();
}
});
JPanel buttons2 = new JPanel();
buttons2.add(calculate);
buttons2.add(reset);
enterPanel.add(buttons2, c);
c.gridy++;
results = Box.createVerticalBox();
enterPanel.add(results, c);
enterPanel.setVisible(false);
JPanel subpanel = new JPanel(new GridBagLayout());
c.gridy = 0;
c.gridx = 0;
c.anchor = GridBagConstraints.NORTH;
subpanel.add(enterPanel, c);
c.gridx++;
subpanel.add(Box.createHorizontalStrut(10), c);
c.gridx++;
steps = Box.createVerticalBox();
subpanel.add(steps);
panel = new JPanel();
panel.add(reader.getPanel());
panel.add(subpanel);
}
/*
* Returns the panel to its original state after the rest button has been pressed.
*/
private void setPanel()
{
expression.setIcon(null);
fields.removeAll();
compounds = null;
k = null;
precipitate = null;
solubility = null;
results.removeAll();
steps.removeAll();
enterPanel.setVisible(false);
panel.add(reader.getPanel());
}
/*
* Calculates the value of K given the concentrations of the relevant compounds.
*/
private static double calculateK(double[] values, LinkedList<String> steps, ArrayList<Integer> powers, boolean k)
{
double value = 1;
String step1 = "<html>" + (k ? "K" : "Q") + " = ", step2 = "<html>" + (k ? "K" : "Q") + " = "; //Step 1 shows multiplication before raising to powers,
//step 2 shows after
for(int index = 0; index < values.length - 1; index++)
{
step1 += "(" + values[index] + ")<sup>" + powers.get(index) + "</sup> * ";
double num = Math.pow(values[index], powers.get(index));
step2 += num + " * ";
value *= num;
}
step1 = step1.substring(0, step1.length() - 3);
step2 = step2.substring(0, step2.length() - 3);
steps.add(step1);
steps.add(step2);
steps.add((k ? "K" : "Q") + " = " + value);
return value;
}
/*
* Calculates one concentration given all the others and K.
*/
public static double calculateConcentration(double[] values, LinkedList<String> steps, ArrayList<Integer> powers, int unknown)
{
double value = 1;
String step1 = "<html>" + values[values.length - 1] + " = ", step2 = "<html>" + values[values.length - 1] + " = ";
for(int index = 0; index < values.length - 1; index++)
{
if(index != unknown)
{
step1 += "(" + values[index] + ")<sup>" + powers.get(index) + "</sup> * ";
double num = Math.pow(values[index], powers.get(index));
step2 += num + " * ";
value *= num;
}
else
{
step1 += "x<sup>" + powers.get(index) + "</sup> * ";
step2 += "x<sup>" + powers.get(index) + "</sup> * ";
}
}
step1 = step1.substring(0, step1.length() - 3);
step2 = step2.substring(0, step2.length() - 3);
steps.add(step1);
steps.add(step2);
value = values[values.length - 1] / value;
steps.add("<html>x<sup>" + powers.get(unknown) + "</sup> = " + value);
value = Math.pow(value, 1.0 / powers.get(unknown));
steps.add("x = " + value + " mol / L");
return value;
}
/*
* Calculates all unknown concentrations given the others and K and returns the indices in values which have been changed, or null if there is insufficient
* information for the calculations.
*/
public static LinkedList<Integer> calculateValues(double[] values, LinkedList<String> steps, ArrayList<Integer> powers, ArrayList<Compound> compounds,
double[] storeX)
{
double newK = values[values.length - 1]; //Will divide K by all known concentrations
String stepK = "<html>" + newK + " / ";
LinkedList<Integer> changed = new LinkedList<Integer>(); //To put in relevant indices
for(int index = 0; index < compounds.size(); index++)
{
if(values[index] == Units.UNKNOWN_VALUE)
{
if(powers.get(index) < 0) //If K is dependent on compounds on the left, the ratios can't be used for concentrations
{
steps.add("Insufficient information for calculations.");
return null;
}
else
{
steps.add("<html>[" + compounds.get(index).withoutNumState() + "] = " + (powers.get(index) == 1 ? "" : powers.get(index)) + "x");
changed.add(index);
}
}
else
{
newK /= Math.pow(values[index], powers.get(index));
stepK += "(" + values[index] + ")<sup>" + powers.get(index) + "</sup> / ";
}
}
if(newK != values[values.length - 1])
{
steps.add("Divide K by known concentrations:");
steps.add(stepK.substring(0, stepK.length() - 3) + " = " + newK); //Gets rid of last / before adding equals
}
String step = "<html>" + newK + " = ";
int value = 1, sum = 0;
for(int index = 0; index < values.length - 1; index++)
{
int power = powers.get(index);
value *= Math.pow(power, power);
sum += power;
step += "(" + (power == 1 ? "" : power) + "x)<sup>" + power + "</sup> * ";
}
steps.add(step.substring(0, step.length() - 3)); //Removes last *
if(value != 1)
{
steps.add("<html>" + newK + " = " + (value == 1 ? "" : value + " * ") + "x<sup>" + sum + "</sup><html>");
newK /= value;
}
steps.add("<html>" + newK + " = x<sup>" + sum + "</sup><html>");
double x = Math.pow(newK, (1 / (double)sum));
steps.add("x = " + x);
storeX[0] = x;
for(Integer index: changed)
{
int power = powers.get(index);
values[index] = x * power;
steps.add("<html>[" + compounds.get(index).withoutNumState() + "] = " + (power == 1 ? "" : power) + "x = " + values[index] + " mol / L</html>");
}
return changed;
}
/*
* Solves the ICE table approximately by assuming that in the denominator x does not matter.
*/
public static double[] solveApprox(double[] original, double product, int sum, int index, ArrayList<Integer> powers, LinkedList<String> steps, String[] ex)
{
double denom = 1;
String fraction = "<html>" + original[original.length - 1] + " = " + product + "x<sup>" + sum + "</sup> / (";
for(; index < powers.size(); index++)
{
steps.add("Assume " + original[index] + " - " + (powers.get(index) == -1 ? "" : -powers.get(index)) + "x \u2245 " + original[index]);
fraction += original[index] + "<sup>" + -powers.get(index) + "</sup> * ";
denom *= Math.pow(original[index], -powers.get(index));
}
steps.add(fraction.substring(0, fraction.length() - 3) + ")</html>");
double x = original[original.length - 1] * denom / product;
steps.add("<html>" + x + " = x<sup>" + sum + "</sup></html>");
x = Math.pow(x, 1.0 / sum);
steps.add("x = " + x);
double[] results = new double[original.length - 1];
for(int i = 0; i < powers.size(); i++)
{
results[i] = original[i] + powers.get(i) * x;
steps.add(ex[i] + " = " + results[i] + " M");
}
return results;
}
/*
* Solves the ICE table with quadratic equations. Returns null if it cannot be solved.
*/
public static double[] solveICE(double[] original, ArrayList<Integer> powers, LinkedList<String> steps, String[] expressions)
{
double[][] num = new double[2][2], denom = new double[2][2]; //Will hold the linear expressions to be multiplied
int index = 0;
num[0][0] = powers.get(index);
num[0][1] = original[index];
if(powers.get(index) == 2)
{
num[1][0] = powers.get(index);
num[1][1] = original[index];
index++;
}
else
{
index++;
num[1][0] = powers.get(index);
num[1][1] = original[index];
index++;
}
denom[0][0] = powers.get(index);
denom[0][1] = original[index];
if(powers.get(index) == 2)
{
denom[1][0] = powers.get(index);
denom[1][1] = original[index];
index++;
}
else
{
index++;
denom[1][0] = powers.get(index);
denom[1][1] = original[index];
index++;
}
double[] top = foil(num), bottom = foil(denom);
steps.add("<html>" + original[original.length - 1] + " = (" + displayQuadratic(top) + ") / (" + displayQuadratic(bottom) + ")</html>");
for(int i = 0; i < bottom.length; i++)
{
bottom[i] *= original[original.length - 1];
}
steps.add("<html>" + displayQuadratic(bottom) + " = " + displayQuadratic(top) + "</html>");
for(int i = 0; i < bottom.length; i++)
{
top[i] -= bottom[i];
}
steps.add("<html>0 = " + displayQuadratic(top) + "</html>");
double x = (-top[1] + Math.sqrt(top[1] * top[1] - 4 * top[0] * top[2])) / (2 * top[0]); //Uses higher root only
steps.add("x = " + x);
double[] results = new double[original.length - 1];
for(int i = 0; i < powers.size(); i++)
{
results[i] = original[i] + powers.get(i) * x;
steps.add(expressions[i] + " = " + results[i] + " M");
}
return results;
}
private static double[] foil(double[][] factors)
{
double[] expression = new double[3];
expression[0] = factors[0][0] * factors[1][0];
expression[1] = factors[0][0] * factors[1][1] + factors[1][0] * factors[0][1];
expression[2] = factors[0][1] * factors[1][1];
return expression;
}
private static String displayQuadratic(double[] expression)
{
String str = "";
if(expression[0] == -1) str += "-";
else if(expression[0] != 1 && expression[0] != 0) str += expression[0];
if(expression[0] != 0) str += "x<sup>2</sup>";
if(expression[1] != 0)
{
if(str.length() != 0) str += expression[1] > 0 ? " + " : " - ";
if(expression[1] != 1 && expression[1] != -1) str += Math.abs(expression[1]);
str += "x";
}
if(expression[2] != 0)
{
if(str.length() != 0) str += expression[2] > 0 ? " + " : " - ";
if(expression[2] != 1 && expression[2] != -1) str += Math.abs(expression[2]);
}
return str;
}
/*
* Calculates the concentrations of each compound and K from the solubility of the solid.
*/
public static double[] calculateFromSolubility(double s, LinkedList<String> steps, ArrayList<Compound> relevant, ArrayList<Integer> powers)
{
double[] values = new double[relevant.size() + 1];
String step1 = "<html>k = ", step2 = "<html>k = "; //Calculates k as it goes
values[values.length - 1] = 1;
for(int index = 0; index < relevant.size(); index++)
{
String compound = "[" + relevant.get(index).withoutNumState() + "]";
int power = powers.get(index);
values[index] = s * power;
steps.add("<html>" + compound + " = " + s + " * " + power + " = " + values[index] + " mol / L</html>");
step1 += compound + "<sup>" + power + "</sup> * ";
step2 += "(" + values[index] + ")<sup>" + power + "</sup> * ";
values[values.length - 1] *= Math.pow(values[index], power);
}
steps.add(step1.substring(0, step1.length() - 3) + "<html>");
steps.add(step2.substring(0, step2.length() - 3) + "<html>");
steps.add("k = " + values[values.length - 1]);
return values;
}
public static double[] calculateConcentrations(double[] values, ArrayList<Compound> compounds, Compound[] original, LinkedList<String> steps)
{
double[] concentrations = new double[2];
int[] coefficients = new int[2]; //Finds the coefficients of each ion in the reactants
coefficients[0] = original[0].numberOf((compounds.get(0).getIons()[0].getElements()[0].getElement()));
if(coefficients[0] == 0)
{
coefficients[0] = original[1].numberOf((compounds.get(0).getIons()[0].getElements()[0].getElement()));
coefficients[1] = original[0].numberOf((compounds.get(1).getIons()[0].getElements()[0].getElement()));
//The values will be in the wrong order for the calculations
double temp = values[1];
values[1] = values[3];
values[3] = temp;
temp = values[2];
values[2] = values[4];
values[4] = temp;
}
else coefficients[1] = original[1].numberOf((compounds.get(1).getIons()[0].getElements()[0].getElement()));
steps.add("<html>[" + compounds.get(0).withoutNumState() + "] = " + values[1] + " * " + values[2] + " * " + coefficients[0] + " / (" + values[1] +
" + " + values[3] + ")</html>");
concentrations[0] = values[1] * values[2] * coefficients[0] / (values[1] + values[3]);
steps.add("<html>[" + compounds.get(0).withoutNumState() + "] = " + concentrations[0] + " mol / L</html>)");
steps.add("<html>[" + compounds.get(1).withoutNumState() + "] = " + values[3] + " * " + values[4] + " * " + coefficients[1] + " / (" + values[1] +
" + " + values[3] + ")</html>");
concentrations[1] = values[3] * values[4] * coefficients[1] / (values[1] + values[3]);
steps.add("<html>[" + compounds.get(1).withoutNumState() + "] = " + concentrations[1] + " mol / L</html>)");
return concentrations;
}
public boolean equation()
{
return true;
}
public Equation saveEquation()
{
return reader.saveEquation();
}
/*
* Takes equation and sets up EnterFields to perform calculations with the compounds in the equation.
*/
public void useSaved(Equation equation)
{
//States of matter are necessary to make an equilibrium expression
{
for(Compound c: equation.getLeft())
{
c.checkForPoly();
if(c.getState().equals(" ") && !getState(c)) return;
}
for(Compound c: equation.getRight())
{
c.checkForPoly();
if(c.getState().equals(" ") && !getState(c)) return;
}
}
int type = equation.isDoubleDisplacement();
reactants = new Compound[2];
if(type == 1)
{
ArrayList<Compound> left = equation.getLeft();
reactants[0] = left.get(0);
reactants[1] = left.get(1);
equation.removeSpectators();
}
panel.remove(reader.getPanel());
relevant = new ArrayList<Compound>();
ArrayList<Compound> irrelevant = new ArrayList<Compound>();
powers = new ArrayList<Integer>();
String ex = equation.getEquilibrium(relevant, irrelevant, powers);
TeXFormula formula = new TeXFormula(ex);
TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
icon.paintIcon(new JLabel(), image.getGraphics(), 0, 0);
expression.setIcon(icon);
compounds = new EnterField[relevant.size()];
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
for(int index = 0; index < compounds.length; index++)
{
EnterField field = new EnterField("<html>[" + relevant.get(index).withoutNumState() + "]</html>", "Amount", "Volume");
compounds[index] = field;
fields.add(field, c);
c.gridy++;
}
k = new EnterField("K");
fields.add(k, c);
if(type != -1)
{
Double kValue = KSP.get(irrelevant.get(0).withoutNumState());
if(kValue != null)
{
JCheckBox stored = new JCheckBox("Use stored value for K");
stored.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if(stored.isSelected()) k.setAmount(kValue);
}
});
c.gridy++;
fields.add(stored, c);
}
int pre = 0;
if(type == 1)
{
pre = JOptionPane.showConfirmDialog(panel, "Does the question involve finding whether there is a precipitate?", "Choose Type",
JOptionPane.YES_NO_OPTION);
}
if(type == 0 || pre != 0)
{
solubility = new EnterField("Solubility", "Amount", "Volume");
c.gridy++;
fields.add(solubility, c);
}
else
{
precipitate = new EnterField[5];
precipitate[0] = new EnterField("Q");
c.gridy++;
fields.add(precipitate[0], c);
for(int index = 1; index < precipitate.length; index += 2)
{
precipitate[index] = new EnterField("<html>Volume " + reactants[index / 2].withoutNumState(), "Volume");
c.gridy++;
fields.add(precipitate[index], c);
precipitate[index + 1] = new EnterField("<html>[" + reactants[index / 2].withoutNumState() + "]", "Amount", "Volume");
c.gridy++;
fields.add(precipitate[index + 1], c);
}
}
}
enterPanel.setVisible(true);
}
/*
* Prompts the user to choose a state for the compound. If they do, returns true, returns false otherwise.
*/
private boolean getState(Compound c)
{
Object obj = JOptionPane.showInputDialog(panel, "<html>Please enter the state of matter of " + c + "</html>", "State", JOptionPane.QUESTION_MESSAGE,
null, Compound.getValidstates().toArray(), "aq");
if(obj == null) return false;
c.setState((String)obj);
return true;
}
public boolean number()
{
return true;
}
public double saveNumber()
{
if(saved.size() == 0) return 0;
if(saved.size() == 1) return saved.get(0);
Object obj = JOptionPane.showInputDialog(panel, "Choose a number to save.", "Save Number", JOptionPane.QUESTION_MESSAGE, null, saved.toArray(),
saved.get(0));
if(obj != null) return (Double) obj;
return 0;
}
public void useSavedNumber(double num)
{
if(k == null) return;
String[] list = new String[compounds.length + (solubility != null ? 2 : precipitate != null ? 6 : 1)];
for(int index = 0; index < compounds.length; index++)
{
list[index] = compounds[index].getName();
}
list[compounds.length] = "K";
if(solubility != null) list[list.length - 1] = "Solubility";
else if(precipitate != null)
{
for(int index = compounds.length + 1; index < list.length; index++)
{
list[index] = precipitate[index - compounds.length - 1].getName();
}
}
Object obj = JOptionPane.showInputDialog(panel, "Choose where to use the number.", "Use Saved", JOptionPane.QUESTION_MESSAGE, null, list, list[0]);
if(obj == null) return;
for(int index = 0; index < compounds.length; index++)
{
if(list[index].equals(obj))
{
compounds[index].setAmount(num);
return;
}
}
if(obj.equals("K"))
{
k.setAmount(num);
return;
}
if(obj.equals("Solubility"))
{
solubility.setAmount(num);
return;
}
for(int index = compounds.length + 1; index < list.length; index++)
{
if(obj.equals(precipitate[index - compounds.length - 1].getName()))
{
precipitate[index - compounds.length - 1].setAmount(num);
return;
}
}
}
private static TreeMap<String, Double> createMap()
{
TreeMap<String, Double> map = new TreeMap<String, Double>();
map.put("Al(OH)<sub>3</sub>", 1.8E-33);
map.put("BaCO<sub>3</sub>", 8.1E-9);
map.put("BaF<sub>2</sub>", 1.7E-6);
map.put("BaSO<sub>4</sub>", 1.1E-10);
map.put("Bi<sub>2</sub>S<sub>3</sub>", 1.6E-72);
map.put("CdS", 8E-28);
map.put("CaCO<sub>3</sub>", 8.7E-9);
map.put("CaF<sub>2</sub>", 3.9E-11);
map.put("Ca(OH)<sub>2</sub>", 8E-6);
map.put("Ca<sub>3</sub>(PO<sub>4</sub>)<sub>2</sub>", 1.2E-26);
map.put("Cr(OH)<sub>3</sub>", 3E-29);
map.put("CoS", 4E-21);
map.put("CuBr", 4.2E-8);
map.put("CuI", 5.1E-12);
map.put("Cu(OH)<sub>2</sub>", 2.2E-20);
map.put("CuS", 6E-37);
map.put("Fe(OH)<sub>2</sub>", 1.6E-14);
map.put("Fe(OH)<sub>3</sub>", 1.1E-36);
map.put("FeS", 6E-19);
map.put("PbCO<sub>3</sub>", 3.3E-14);
map.put("PbCl<sub>2</sub>", 2.4E-4);
map.put("PbCrO<sub>4</sub>", 2E-14);
map.put("PbF<sub>2</sub>", 4.1E-8);
map.put("PbI<sub>2</sub>", 1.4E-8);
map.put("PbS", 3.4E-28);
map.put("MgCO<sub>3</sub>", 4E-3);
map.put("Mg(OH)<sub>2</sub>", 1.2E-11);
map.put("MnS", 3E-14);
map.put("Hg<sub>2</sub>Cl<sub>2</sub>", 3.5E-18);
map.put("Hg(OH)<sub>2</sub>", 3.1E-26);
map.put("HgS", 4E-54);
map.put("Ni(OH)<sub>2</sub>", 5.5E-16);
map.put("NiS", 1.4E-24);
map.put("AgBr", 7.7E-13);
map.put("Ag<sub>2</sub>CO<sub>3</sub>", 8.1E-12);
map.put("AgCl", 1.6E-10);
map.put("AgI", 8.3E-17);
map.put("Ag<sub>2</sub>SO<sub>4</sub>", 1.4E-5);
map.put("Ag<sub>2</sub>S", 6E-51);
map.put("SrCO<sub>3</sub>", 1.6E-9);
map.put("SrSO<sub>4</sub>", 3.8E-7);
map.put("Sn(OH)<sub>2</sub>", 5.4E-27);
map.put("SnS", 1E-26);
map.put("Zn(OH)<sub>2</sub>", 1.8E-14);
map.put("ZnS", 3E-23);
return map;
}
public JPanel getPanel()
{
return panel;
}
} | Equilibrium error messages
| src/Functions/Equilibrium.java | Equilibrium error messages | <ide><path>rc/Functions/Equilibrium.java
<ide> * Performs various calculations for functions at equilibrium.
<ide> *
<ide> * Author: Julia McClellan
<del> * Version: 3/27/2016
<add> * Version: 3/28/2016
<ide> */
<ide>
<ide> package Functions;
<ide>
<ide> if(precipitate != null)
<ide> {
<del> if(values[0] == Units.UNKNOWN_VALUE) //Fist calculates concentrations of each ion if necessary
<del> {
<add> if(values[0] == Units.UNKNOWN_VALUE && extra[0] == Units.UNKNOWN_VALUE) //Fist calculates concentrations of each ion if necessary
<add> {
<add> if(extra[1] == Units.UNKNOWN_VALUE || extra[2] == Units.UNKNOWN_VALUE || extra[3] == Units.UNKNOWN_VALUE || extra[4] ==
<add> Units.UNKNOWN_VALUE)
<add> {
<add> results.add(new JLabel("Insufficient information for calculations."));
<add> results.setVisible(true);
<add> return;
<add> }
<ide> LinkedList<String> stepList = new LinkedList<String>();
<ide> double[] concentrations = calculateConcentrations(extra, relevant, reactants, stepList);
<ide> for(String step: stepList) steps.add(new JLabel(step));
<ide> return;
<ide> }
<ide>
<del> //Finds Qsp and compares it to Ksp to find if there is a precipitate
<del> LinkedList<String> stepList = new LinkedList<String>();
<del> double q = calculateK(values, stepList, powers, false);
<del> for(String step: stepList) steps.add(new JLabel(step));
<del> results.add(new JLabel("Q = " + Function.withSigFigs(q, sigFigs)));
<add> double q;
<add> if(extra[0] == Units.UNKNOWN_VALUE)
<add> {
<add> //Finds Qsp and compares it to Ksp to find if there is a precipitate
<add> LinkedList<String> stepList = new LinkedList<String>();
<add> q = calculateK(values, stepList, powers, false);
<add> for(String step: stepList) steps.add(new JLabel(step));
<add> results.add(new JLabel("Q = " + Function.withSigFigs(q, sigFigs)));
<add> }
<add> else q = extra[0];
<ide> steps.add(new JLabel(q + (q > values[values.length - 1] ? " > " : " < ") + values[values.length - 1]));
<ide> steps.add(new JLabel("Q" + (q > values[values.length - 1] ? " > " : " < ") + "K"));
<ide> if(q > values[values.length - 1]) results.add(new JLabel("Yes, there is a precipitate."));
<ide> int col = 1;
<ide> for(int index = 0; index < relevant.size(); index++)
<ide> {
<del> if(values[index] == Units.UNKNOWN_VALUE) values[index] = 0;
<add> if(values[index] == Units.UNKNOWN_VALUE)
<add> {
<add> results.add(new JLabel("Enter initial concentration for " + relevant.get(index).withoutNumState()));
<add> results.setVisible(true);
<add> return;
<add> }
<ide> labels[0][col] = new JLabel("<html>[" + relevant.get(index).withoutNumState() + "]");
<ide> labels[1][col] = new JLabel(values[index] + "");
<ide> labels[2][col] = new JLabel((powers.get(index) == 1 ? "" : powers.get(index)) + "x");
<ide> saved.add(values[values.length - 1]);
<ide> results.add(new JLabel("K = " + Function.withSigFigs(values[values.length - 1], sigFigs)));
<ide> }
<del> else if(values[compounds.length] == Units.UNKNOWN_VALUE) //K is unknown
<del> {
<del> LinkedList<String> stepList = new LinkedList<String>();
<del> double result = calculateK(values, stepList, powers, true);
<del>
<del> for(String step: stepList) steps.add(new JLabel(step));
<del> saved.add(result);
<del> results.add(new JLabel("K = " + Function.withSigFigs(result, sigFigs)));
<del> }
<del> else //K is known
<add> else
<ide> {
<ide> int unknown = -1;
<ide> for(int index = 0; index < compounds.length; index++)
<ide> }
<ide> }
<ide> }
<del>
<del> if(unknown == -1)
<del> {
<del> results.add(new JLabel("Leave a value blank."));
<del> results.setVisible(true);
<del> return;
<del> }
<del> else if(unknown == Integer.MAX_VALUE)
<del> {
<del> LinkedList<String> stepList = new LinkedList<String>();
<del> double[] x = new double[1];
<del> LinkedList<Integer> changed = calculateValues(values, stepList, powers, relevant, x);
<del> if(changed == null)
<add>
<add> if(values[compounds.length] == Units.UNKNOWN_VALUE) //K is unknown
<add> {
<add> if(unknown != -1)
<ide> {
<del> results.add(new JLabel(stepList.getLast()));
<del> results.setVisible(false);
<add> results.add(new JLabel("To calculate K, enter the concentrations of all compounds."));
<add> results.setVisible(true);
<ide> return;
<ide> }
<del> for(String step: stepList) steps.add(new JLabel(step));
<ide>
<del> for(Integer index: changed)
<del> {
<del> double val = compounds[index].getBlankAmount(values[index]);
<del> saved.add(val);
<del> results.add(new JLabel("<html>[" + relevant.get(index).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)
<del> + " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
<del> }
<del>
<del> if(solubility != null)
<del> {
<del> double result = solubility.getBlankAmount(x[0]);
<del> String unit = solubility.getUnitName() + " / " + solubility.getUnit2Name();
<del> steps.add(new JLabel("Solubility = x = " + result + " " + unit));
<del> saved.add(result);
<del> results.add(new JLabel("Solubility = " + Function.withSigFigs(result, sigFigs) + " " + unit));
<del> extra[5] = result; //So it won't accidentally be recalculated later
<del> }
<del> }
<del> else
<del> {
<ide> LinkedList<String> stepList = new LinkedList<String>();
<del> double result = calculateConcentration(values, stepList, powers, unknown);
<add> double result = calculateK(values, stepList, powers, true);
<ide>
<ide> for(String step: stepList) steps.add(new JLabel(step));
<del> saved.add(compounds[unknown].getBlankAmount(result));
<del> if(result != saved.get(0)) steps.add(new JLabel("x = " + saved.get(0) + " " + compounds[unknown].getUnitName() + " / "
<del> + compounds[unknown].getUnit2Name()));
<del> results.add(new JLabel("<html>[" + relevant.get(unknown).withoutNumState() + "] = " +
<del> Function.withSigFigs(saved.get(0), sigFigs)));
<del> values[unknown] = result; //In case it it needed to calculate solubility later
<add> saved.add(result);
<add> results.add(new JLabel("K = " + Function.withSigFigs(result, sigFigs)));
<add> }
<add> else //K is known
<add> {
<add> if(unknown == -1)
<add> {
<add> results.add(new JLabel("Leave a value blank."));
<add> results.setVisible(true);
<add> return;
<add> }
<add> else if(unknown == Integer.MAX_VALUE)
<add> {
<add> LinkedList<String> stepList = new LinkedList<String>();
<add> double[] x = new double[1];
<add> LinkedList<Integer> changed = calculateValues(values, stepList, powers, relevant, x);
<add> if(changed == null)
<add> {
<add> results.add(new JLabel(stepList.getLast()));
<add> results.setVisible(false);
<add> return;
<add> }
<add> for(String step: stepList) steps.add(new JLabel(step));
<add>
<add> for(Integer index: changed)
<add> {
<add> double val = compounds[index].getBlankAmount(values[index]);
<add> saved.add(val);
<add> results.add(new JLabel("<html>[" + relevant.get(index).withoutNumState() + "] = " + Function.withSigFigs(val, sigFigs)
<add> + " " + compounds[index].getUnitName() + " / " + compounds[index].getUnit2Name()));
<add> }
<add>
<add> if(solubility != null)
<add> {
<add> double result = solubility.getBlankAmount(x[0]);
<add> String unit = solubility.getUnitName() + " / " + solubility.getUnit2Name();
<add> steps.add(new JLabel("Solubility = x = " + result + " " + unit));
<add> saved.add(result);
<add> results.add(new JLabel("Solubility = " + Function.withSigFigs(result, sigFigs) + " " + unit));
<add> extra[5] = result; //So it won't accidentally be recalculated later
<add> }
<add> }
<add> else
<add> {
<add> LinkedList<String> stepList = new LinkedList<String>();
<add> double result = calculateConcentration(values, stepList, powers, unknown);
<add>
<add> for(String step: stepList) steps.add(new JLabel(step));
<add> saved.add(compounds[unknown].getBlankAmount(result));
<add> if(result != saved.get(0)) steps.add(new JLabel("x = " + saved.get(0) + " " + compounds[unknown].getUnitName() + " / "
<add> + compounds[unknown].getUnit2Name()));
<add> results.add(new JLabel("<html>[" + relevant.get(unknown).withoutNumState() + "] = " +
<add> Function.withSigFigs(saved.get(0), sigFigs)));
<add> values[unknown] = result; //In case it it needed to calculate solubility later
<add> }
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 0ce1cba263cbcfe3ffb10c48ad9db3bd6d7d78cd | 0 | flowplayer/flowplayer-hlsjs | /*jslint browser: true, for: true */
/*global Hls, flowplayer */
/*!
hlsjs engine plugin for Flowplayer HTML5
Copyright (c) 2015, Flowplayer Oy
Released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
Includes hls.min.js
Copyright (c) 2015 Dailymotion (http://www.dailymotion.com)
https://github.com/dailymotion/hls.js/blob/master/LICENSE
requires:
- Flowplayer HTML5 version 6.x or greater
- hls.js https://github.com/dailymotion/hls.js
*/
(function () {
"use strict";
var engineName = "hlsjs",
hlsconf,
extend = flowplayer.extend,
engineImpl = function hlsjsEngine(player, root) {
var bean = flowplayer.bean,
common = flowplayer.common,
videoTag,
hls,
engine = {
engineName: engineName,
pick: function (sources) {
var i,
source;
for (i = 0; i < sources.length; i += 1) {
source = sources[i];
if (/mpegurl/i.test(source.type) && (!source.engine || source.engine === "hlsjs")) {
return source;
}
}
},
load: function (video) {
var init = !hls;
common.removeNode(common.findDirect("video", root)[0] || common.find(".fp-player > video", root)[0]);
videoTag = common.createElement("video", {
className: "fp-engine hlsjs-engine",
autoplay: player.conf.autoplay || !init
});
videoTag.setAttribute("x-webkit-airplay", "allow");
bean.on(videoTag, "play", function () {
player.trigger('resume', [player]);
});
bean.on(videoTag, "pause", function () {
player.trigger('pause', [player]);
});
bean.on(videoTag, "timeupdate", function () {
player.trigger('progress', [player, videoTag.currentTime]);
});
bean.on(videoTag, "loadeddata", function () {
var posterClass = "is-poster";
video = extend(video, {
duration: videoTag.duration,
seekable: videoTag.seekable.end(null),
width: videoTag.videoWidth,
height: videoTag.videoHeight,
url: videoTag.currentSrc
});
player.trigger('ready', [player, video]);
// fix timing for poster class
if (common.hasClass(root, posterClass)) {
player.on("stop.hlsjs", function () {
setTimeout(function () {
common.addClass(root, posterClass);
bean.one(videoTag, "play.hlsjs", function () {
common.removeClass(root, posterClass);
});
}, 0);
});
}
// Firefox needs explicit play()
if (player.conf.autoplay || !init) {
videoTag.play();
}
});
bean.on(videoTag, "seeked", function () {
player.trigger('seek', [player, videoTag.currentTime]);
});
bean.on(videoTag, "progress", function (e) {
var ct = videoTag.currentTime,
buffer = 0,
buffend,
buffered,
last,
i;
try {
buffered = videoTag.buffered,
last = buffered.length - 1,
buffend = 0;
// cycle through time ranges to obtain buffer
// nearest current time
if (ct) {
for (i = last; i > -1; i -= 1) {
buffend = buffered.end(i);
if (buffend >= ct) {
buffer = buffend;
}
}
}
} catch (ignored) {}
video.buffer = buffer;
player.trigger('buffer', [player, e]);
});
bean.on(videoTag, "ended", function () {
player.trigger('finish', [player]);
});
bean.on(videoTag, "volumechange", function () {
player.trigger('volume', [player, videoTag.volume]);
});
if (hls) {
hls.destroy();
}
hls = new Hls(hlsconf);
hls.on(Hls.Events.MSE_ATTACHED, function () {
hls.loadSource(video.src);
}).on(Hls.Events.ERROR, function (e, data) {
var fperr,
errobj;
if (data.fatal) {
// try recovery?
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
// in theory should be 3 (Network error)
fperr = 4;
break;
case Hls.ErrorTypes.MEDIA_ERROR:
fperr = 3;
break;
default:
fperr = 5;
break;
}
errobj = {code: fperr};
if (fperr > 2) {
errobj.video = extend(video, {
src: video.src,
url: data.url || video.src
});
}
player.trigger('error', [player, errobj]);
}
/* TODO: */
// log non fatals
});
common.prepend(common.find(".fp-player", root)[0], videoTag);
hls.attachVideo(videoTag);
},
resume: function () {
videoTag.play();
},
pause: function () {
videoTag.pause();
},
seek: function (time) {
videoTag.currentTime = time;
},
volume: function (level) {
if (videoTag) {
videoTag.volume = level;
}
},
speed: function (val) {
videoTag.playbackRate = val;
player.trigger('speed', [player, val]);
},
unload: function () {
// hls conditional probably not needed once
// https://github.com/flowplayer/flowplayer/commit/871ff783a8f23aa603e1120f4319d4a892125b0a
// is released
if (hls) {
hls.destroy();
hls = 0;
common.find("video.fp-engine", root).forEach(common.removeNode);
}
}
};
return engine;
};
if (Hls.isSupported()) {
// only load engine if it can be used
engineImpl.engineName = engineName; // must be exposed
engineImpl.canPlay = function (type, conf) {
var UA = navigator.userAgent,
IE11 = UA.indexOf("Trident/7") > -1;
if (conf.hlsjs === false || conf.clip.hlsjs === false) {
// engine disabled for player or clip
return false;
}
// merge hlsjs clip config at earliest opportunity
hlsconf = extend({}, conf.hlsjs, conf.clip.hlsjs);
// support Safari only when hlsjs debugging
// https://github.com/dailymotion/hls.js/issues/9
return /mpegurl/i.test(type) &&
(IE11 || !flowplayer.support.browser.safari || hlsconf.debug);
};
// put on top of engine stack
// so hlsjs is tested before html5 video hls and flash hls
flowplayer.engines.unshift(engineImpl);
}
}());
| flowplayer.hlsjs.js | /*jslint browser: true, for: true */
/*global Hls, flowplayer */
/*!
hlsjs engine plugin for Flowplayer HTML5
Copyright (c) 2015, Flowplayer Oy
Released under the MIT License:
http://www.opensource.org/licenses/mit-license.php
Includes hls.min.js
Copyright (c) 2015 Dailymotion (http://www.dailymotion.com)
https://github.com/dailymotion/hls.js/blob/master/LICENSE
requires:
- Flowplayer HTML5 version 6.x or greater
- hls.js https://github.com/dailymotion/hls.js
*/
(function () {
"use strict";
var engineName = "hlsjs",
hlsconf,
extend = flowplayer.extend,
engineImpl = function hlsjsEngine(player, root) {
var bean = flowplayer.bean,
common = flowplayer.common,
videoTag,
hls,
engine = {
engineName: engineName,
pick: function (sources) {
var i,
source;
for (i = 0; i < sources.length; i += 1) {
source = sources[i];
if (/mpegurl/i.test(source.type) && (!source.engine || source.engine === "hlsjs")) {
return source;
}
}
},
load: function (video) {
var init = !hls;
common.removeNode(common.findDirect("video", root)[0] || common.find(".fp-player > video", root)[0]);
videoTag = common.createElement("video", {
className: "fp-engine hlsjs-engine",
autoplay: player.conf.autoplay || !init
});
videoTag.setAttribute("x-webkit-airplay", "allow");
bean.on(videoTag, "play", function () {
player.trigger('resume', [player]);
});
bean.on(videoTag, "pause", function () {
player.trigger('pause', [player]);
});
bean.on(videoTag, "timeupdate", function () {
player.trigger('progress', [player, videoTag.currentTime]);
});
bean.on(videoTag, "loadeddata", function () {
var posterClass = "is-poster";
video = extend(video, {
duration: videoTag.duration,
seekable: videoTag.seekable.end(null),
width: videoTag.videoWidth,
height: videoTag.videoHeight,
url: videoTag.currentSrc
});
player.trigger('ready', [player, video]);
// fix timing for poster class
if (common.hasClass(root, posterClass)) {
player.on("stop.hlsjs", function () {
setTimeout(function () {
common.addClass(root, posterClass);
bean.one(videoTag, "play.hlsjs", function () {
common.removeClass(root, posterClass);
});
}, 0);
});
}
// Firefox needs explicit play()
if (player.conf.autoplay || !init) {
videoTag.play();
}
});
bean.on(videoTag, "seeked", function () {
player.trigger('seek', [player, videoTag.currentTime]);
});
bean.on(videoTag, "progress", function (e) {
try {
var buffered = videoTag.buffered,
buffer = buffered.end(null), // first loaded buffer
ct = videoTag.currentTime,
buffend = 0,
i;
// buffered.end(null) will not always return the current buffer
// so we cycle through the time ranges to obtain it
if (ct) {
for (i = 1; i < buffered.length; i += 1) {
buffend = buffered.end(i);
if (buffend >= ct && buffered.start(i) <= ct) {
buffer = buffend;
}
}
}
video.buffer = buffer;
} catch (ignored) {}
player.trigger('buffer', [player, e]);
});
bean.on(videoTag, "ended", function () {
player.trigger('finish', [player]);
});
bean.on(videoTag, "volumechange", function () {
player.trigger('volume', [player, videoTag.volume]);
});
if (hls) {
hls.destroy();
}
hls = new Hls(hlsconf);
hls.on(Hls.Events.MSE_ATTACHED, function () {
hls.loadSource(video.src);
}).on(Hls.Events.ERROR, function (e, data) {
var fperr,
errobj;
if (data.fatal) {
// try recovery?
switch (data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
// in theory should be 3 (Network error)
fperr = 4;
break;
case Hls.ErrorTypes.MEDIA_ERROR:
fperr = 3;
break;
default:
fperr = 5;
break;
}
errobj = {code: fperr};
if (fperr > 2) {
errobj.video = extend(video, {
src: video.src,
url: data.url || video.src
});
}
player.trigger('error', [player, errobj]);
}
/* TODO: */
// log non fatals
});
common.prepend(common.find(".fp-player", root)[0], videoTag);
hls.attachVideo(videoTag);
},
resume: function () {
videoTag.play();
},
pause: function () {
videoTag.pause();
},
seek: function (time) {
videoTag.currentTime = time;
},
volume: function (level) {
if (videoTag) {
videoTag.volume = level;
}
},
speed: function (val) {
videoTag.playbackRate = val;
player.trigger('speed', [player, val]);
},
unload: function () {
// hls conditional probably not needed once
// https://github.com/flowplayer/flowplayer/commit/871ff783a8f23aa603e1120f4319d4a892125b0a
// is released
if (hls) {
hls.destroy();
hls = 0;
common.find("video.fp-engine", root).forEach(common.removeNode);
}
}
};
return engine;
};
if (Hls.isSupported()) {
// only load engine if it can be used
engineImpl.engineName = engineName; // must be exposed
engineImpl.canPlay = function (type, conf) {
var UA = navigator.userAgent,
IE11 = UA.indexOf("Trident/7") > -1;
if (conf.hlsjs === false || conf.clip.hlsjs === false) {
// engine disabled for player or clip
return false;
}
// merge hlsjs clip config at earliest opportunity
hlsconf = extend({}, conf.hlsjs, conf.clip.hlsjs);
// support Safari only when hlsjs debugging
// https://github.com/dailymotion/hls.js/issues/9
return /mpegurl/i.test(type) &&
(IE11 || !flowplayer.support.browser.safari || hlsconf.debug);
};
// put on top of engine stack
// so hlsjs is tested before html5 video hls and flash hls
flowplayer.engines.unshift(engineImpl);
}
}());
| Improve buffer display
To reflect the streaming character, the displayed buffer should be the
one nearest but greater than current time.
| flowplayer.hlsjs.js | Improve buffer display | <ide><path>lowplayer.hlsjs.js
<ide> player.trigger('seek', [player, videoTag.currentTime]);
<ide> });
<ide> bean.on(videoTag, "progress", function (e) {
<add> var ct = videoTag.currentTime,
<add> buffer = 0,
<add> buffend,
<add> buffered,
<add> last,
<add> i;
<add>
<ide> try {
<del> var buffered = videoTag.buffered,
<del> buffer = buffered.end(null), // first loaded buffer
<del> ct = videoTag.currentTime,
<del> buffend = 0,
<del> i;
<del>
<del> // buffered.end(null) will not always return the current buffer
<del> // so we cycle through the time ranges to obtain it
<add> buffered = videoTag.buffered,
<add> last = buffered.length - 1,
<add> buffend = 0;
<add>
<add> // cycle through time ranges to obtain buffer
<add> // nearest current time
<ide> if (ct) {
<del> for (i = 1; i < buffered.length; i += 1) {
<add> for (i = last; i > -1; i -= 1) {
<ide> buffend = buffered.end(i);
<ide>
<del> if (buffend >= ct && buffered.start(i) <= ct) {
<add> if (buffend >= ct) {
<ide> buffer = buffend;
<ide> }
<ide> }
<ide> }
<del> video.buffer = buffer;
<ide> } catch (ignored) {}
<add>
<add> video.buffer = buffer;
<ide> player.trigger('buffer', [player, e]);
<ide> });
<ide> bean.on(videoTag, "ended", function () { |
|
Java | mit | error: pathspec 'tests/com/lfscheidegger/jfacet/shade/expression/Vector4Test.java' did not match any file(s) known to git
| 02ad450037db1edec1022873bf5a7190c32af491 | 1 | lfscheidegger/jfacet,lfscheidegger/jfacet | package com.lfscheidegger.jfacet.shade.expression;
import com.google.common.collect.ImmutableList;
import com.lfscheidegger.jfacet.shade.GlSlType;
import com.lfscheidegger.jfacet.shade.Type;
import com.lfscheidegger.jfacet.shade.expression.evaluators.*;
import com.lfscheidegger.jfacet.shade.expression.evaluators.glsl.UniformEvaluator;
import com.lfscheidegger.jfacet.shade.expression.operators.Operator;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for {@code Vector4}
*/
public class Vector4Test {
private Vector4 vec;
@Before
public void setUp() {
vec = new Vector4(1, 2, 3, 4);
}
@Test
public void testConstructors() {
assertTrue(vec.getEvaluator() instanceof ConstantEvaluator);
assertEquals(vec.evaluate(), new Vector4.Primitive(1, 2, 3, 4));
vec = new Vector4(new Real(1), new Real(2), new Real(3), new Real(4));
assertTrue(vec.getEvaluator() instanceof ConstructorEvaluator);
assertEquals(vec.evaluate(), new Vector4.Primitive(1, 2, 3, 4));
vec = new Vector4(
ImmutableList.<Expression>of(new Real(1), new Real(2), new Real(3), new Real(4)),
new ConstructorEvaluator<Vector4.Primitive>());
assertTrue(vec.getEvaluator() instanceof ConstructorEvaluator);
assertEquals(vec.evaluate(), new Vector4.Primitive(1, 2, 3, 4));
vec = new Vector4(GlSlType.UNIFORM_T, new UniformEvaluator<Vector4.Primitive>());
assertEquals(vec.getGlSlType(), GlSlType.UNIFORM_T);
assertTrue(vec.getEvaluator() instanceof UniformEvaluator);
}
@Test
public void testGetters() {
assertTrue(vec.getX().evaluate() == 1);
assertTrue(vec.getY().evaluate() == 2);
assertTrue(vec.getZ().evaluate() == 3);
assertTrue(vec.getW().evaluate() == 4);
assertTrue(vec.getX().evaluate().equals(vec.get(0).evaluate()));
assertTrue(vec.getY().evaluate().equals(vec.get(1).evaluate()));
assertTrue(vec.getZ().evaluate().equals(vec.get(2).evaluate()));
assertTrue(vec.getW().evaluate().equals(vec.get(3).evaluate()));
}
private void testAddCommon(Vector4 added, Vector4.Primitive expected) {
assertEquals(added.getParents().size(), 2);
assertEquals(added.evaluate(), expected);
assertTrue(added.getEvaluator() instanceof BinaryOperationEvaluator);
Operator op = ((BinaryOperationEvaluator)added.getEvaluator()).getOperator();
assertEquals(op.getOperatorSymbol(), "+");
}
@Test
public void testAdd() {
Vector4 added = vec.add(1);
testAddCommon(added, new Vector4.Primitive(2, 3, 4, 5));
assertSame(added.getParents().get(0), vec);
assertEquals(added.getParents().get(1).evaluate(), 1.0f);
added = vec.add(new Real(1));
testAddCommon(added, new Vector4.Primitive(2, 3, 4, 5));
assertSame(added.getParents().get(0), vec);
assertEquals(added.getParents().get(1).evaluate(), 1.0f);
added = vec.add(vec);
testAddCommon(added, new Vector4.Primitive(2, 4, 6, 8));
assertSame(added.getParents().get(0), vec);
assertSame(added.getParents().get(1), vec);
}
public void testSubCommon(Vector4 subtracted, Vector4.Primitive expected) {
assertEquals(subtracted.getParents().size(), 2);
assertEquals(subtracted.evaluate(), expected);
assertTrue(subtracted.getEvaluator() instanceof BinaryOperationEvaluator);
Operator op = ((BinaryOperationEvaluator)subtracted.getEvaluator()).getOperator();
assertEquals(op.getOperatorSymbol(), "-");
}
@Test
public void testSub() {
Vector4 subtracted = vec.sub(1);
testSubCommon(subtracted, new Vector4.Primitive(0, 1, 2, 3));
assertSame(subtracted.getParents().get(0), vec);
assertEquals(subtracted.getParents().get(1).evaluate(), 1.0f);
subtracted = vec.sub(new Real(1));
testSubCommon(subtracted, new Vector4.Primitive(0, 1, 2, 3));
assertSame(subtracted.getParents().get(0), vec);
assertEquals(subtracted.getParents().get(1).evaluate(), 1.0f);
subtracted = vec.sub(vec);
testSubCommon(subtracted, new Vector4.Primitive(0, 0, 0, 0));
assertSame(subtracted.getParents().get(0), vec);
assertSame(subtracted.getParents().get(1), vec);
}
private void testMulCommon(Vector4 multiplied, Vector4.Primitive expected) {
assertEquals(multiplied.getParents().size(), 2);
assertEquals(multiplied.evaluate(), expected);
assertTrue(multiplied.getEvaluator() instanceof BinaryOperationEvaluator);
Operator op = ((BinaryOperationEvaluator)multiplied.getEvaluator()).getOperator();
assertEquals(op.getOperatorSymbol(), "*");
}
@Test
public void testMul() {
Vector4 multiplied = vec.mul(2);
testMulCommon(multiplied, new Vector4.Primitive(2, 4, 6, 8));
assertSame(multiplied.getParents().get(0), vec);
assertEquals(multiplied.getParents().get(1).evaluate(), 2.0f);
multiplied = vec.mul(new Real(2));
testMulCommon(multiplied, new Vector4.Primitive(2, 4, 6, 8));
assertSame(multiplied.getParents().get(0), vec);
assertEquals(multiplied.getParents().get(1).evaluate(), 2.0f);
multiplied = vec.mul(vec);
testMulCommon(multiplied, new Vector4.Primitive(1, 4, 9, 16));
assertSame(multiplied.getParents().get(0), vec);
assertSame(multiplied.getParents().get(1), vec);
}
private void testDivCommon(Vector4 divided, Vector4.Primitive expected) {
assertEquals(divided.getParents().size(), 2);
assertEquals(divided.evaluate(), expected);
assertTrue(divided.getEvaluator() instanceof BinaryOperationEvaluator);
Operator op = ((BinaryOperationEvaluator)divided.getEvaluator()).getOperator();
assertEquals(op.getOperatorSymbol(), "/");
}
@Test
public void testDiv() {
Vector4 divided = vec.div(2);
testDivCommon(divided, new Vector4.Primitive(0.5f, 1, 1.5f, 2.0f));
assertSame(divided.getParents().get(0), vec);
assertEquals(divided.getParents().get(1).evaluate(), 2.0f);
divided = vec.div(new Real(2));
testDivCommon(divided, new Vector4.Primitive(0.5f, 1, 1.5f, 2.0f));
assertSame(divided.getParents().get(0), vec);
assertEquals(divided.getParents().get(1).evaluate(), 2.0f);
divided = vec.div(vec);
testDivCommon(divided, new Vector4.Primitive(1, 1, 1, 1));
assertSame(divided.getParents().get(0), vec);
assertSame(divided.getParents().get(1), vec);
}
@Test
public void testNeg() {
Vector4 negated = vec.neg();
assertEquals(negated.getParents().size(), 1);
assertSame(negated.getParents().get(0), vec);
assertTrue(negated.getEvaluator() instanceof NegationEvaluator);
assertEquals(negated.evaluate(), vec.evaluate().neg());
}
@Test
public void testDot() {
Real dot = vec.dot(new Vector4(1, 2, 3, 4));
assertEquals(dot.getParents().size(), 2);
assertSame(dot.getParents().get(0), vec);
assertEquals(dot.getParents().get(1).evaluate(), new Vector4.Primitive(1, 2, 3, 4));
assertTrue(dot.getEvaluator() instanceof FunctionEvaluator);
FunctionEvaluator evaluator = ((FunctionEvaluator)dot.getEvaluator());
assertEquals(evaluator.getFunctionName(), "dot");
assertEquals(evaluator.getType(), Type.FLOAT_T);
assertTrue(dot.evaluate() == vec.evaluate().dot(new Vector4.Primitive(1, 2, 3, 4)));
}
@Test
public void testNormalize() {
Vector4 normalized = vec.normalize();
assertEquals(normalized.getParents().size(), 1);
assertSame(normalized.getParents().get(0), vec);
assertTrue(normalized.getEvaluator() instanceof FunctionEvaluator);
FunctionEvaluator evaluator = ((FunctionEvaluator)normalized.getEvaluator());
assertEquals(evaluator.getFunctionName(), "normalize");
assertEquals(evaluator.getType(), Type.VEC4_T);
assertEquals(normalized.evaluate(), vec.evaluate().normalize());
}
@Test
public void testLength() {
Real length = vec.length();
assertEquals(length.getParents().size(), 1);
assertSame(length.getParents().get(0), vec);
assertTrue(length.getEvaluator() instanceof FunctionEvaluator);
FunctionEvaluator evaluator = ((FunctionEvaluator)length.getEvaluator());
assertEquals(evaluator.getFunctionName(), "length");
assertEquals(evaluator.getType(), Type.FLOAT_T);
}
@Test
public void testSwizzle() {
Real swizzle = vec.swizzle('x');
assertEquals(swizzle.getParents().size(), 1);
assertSame(swizzle.getParents().get(0), vec);
assertTrue(swizzle.getEvaluator() instanceof SwizzleEvaluator);
assertTrue(swizzle.evaluate() == vec.evaluate().swizzle('x'));
Vector2 swizzle2 = vec.swizzle('y', 'x');
assertEquals(swizzle2.getParents().size(), 1);
assertSame(swizzle2.getParents().get(0), vec);
assertTrue(swizzle2.getEvaluator() instanceof SwizzleEvaluator);
assertEquals(swizzle2.evaluate(), vec.evaluate().swizzle('y', 'x'));
Vector3 swizzle3 = vec.swizzle('y', 'x', 'x');
assertEquals(swizzle3.getParents().size(), 1);
assertSame(swizzle3.getParents().get(0), vec);
assertTrue(swizzle3.getEvaluator() instanceof SwizzleEvaluator);
assertEquals(swizzle3.evaluate(), vec.evaluate().swizzle('y', 'x', 'x'));
Vector4 swizzle4 = vec.swizzle('y', 'x', 'x', 'y');
assertEquals(swizzle4.getParents().size(), 1);
assertSame(swizzle4.getParents().get(0), vec);
assertTrue(swizzle4.getEvaluator() instanceof SwizzleEvaluator);
assertEquals(swizzle4.evaluate(), vec.evaluate().swizzle('y', 'x', 'x', 'y'));
}
@Test
public void testFill() {
Vector4 filled = vec.fill(new Vector4(1, 2, 3, 4));
assertSame(vec, filled);
}
}
| tests/com/lfscheidegger/jfacet/shade/expression/Vector4Test.java | Vector4Test
| tests/com/lfscheidegger/jfacet/shade/expression/Vector4Test.java | Vector4Test | <ide><path>ests/com/lfscheidegger/jfacet/shade/expression/Vector4Test.java
<add>package com.lfscheidegger.jfacet.shade.expression;
<add>
<add>import com.google.common.collect.ImmutableList;
<add>import com.lfscheidegger.jfacet.shade.GlSlType;
<add>import com.lfscheidegger.jfacet.shade.Type;
<add>import com.lfscheidegger.jfacet.shade.expression.evaluators.*;
<add>import com.lfscheidegger.jfacet.shade.expression.evaluators.glsl.UniformEvaluator;
<add>import com.lfscheidegger.jfacet.shade.expression.operators.Operator;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Unit tests for {@code Vector4}
<add> */
<add>public class Vector4Test {
<add>
<add> private Vector4 vec;
<add>
<add> @Before
<add> public void setUp() {
<add> vec = new Vector4(1, 2, 3, 4);
<add> }
<add>
<add> @Test
<add> public void testConstructors() {
<add> assertTrue(vec.getEvaluator() instanceof ConstantEvaluator);
<add> assertEquals(vec.evaluate(), new Vector4.Primitive(1, 2, 3, 4));
<add>
<add> vec = new Vector4(new Real(1), new Real(2), new Real(3), new Real(4));
<add> assertTrue(vec.getEvaluator() instanceof ConstructorEvaluator);
<add> assertEquals(vec.evaluate(), new Vector4.Primitive(1, 2, 3, 4));
<add>
<add> vec = new Vector4(
<add> ImmutableList.<Expression>of(new Real(1), new Real(2), new Real(3), new Real(4)),
<add> new ConstructorEvaluator<Vector4.Primitive>());
<add> assertTrue(vec.getEvaluator() instanceof ConstructorEvaluator);
<add> assertEquals(vec.evaluate(), new Vector4.Primitive(1, 2, 3, 4));
<add>
<add> vec = new Vector4(GlSlType.UNIFORM_T, new UniformEvaluator<Vector4.Primitive>());
<add> assertEquals(vec.getGlSlType(), GlSlType.UNIFORM_T);
<add> assertTrue(vec.getEvaluator() instanceof UniformEvaluator);
<add> }
<add>
<add> @Test
<add> public void testGetters() {
<add> assertTrue(vec.getX().evaluate() == 1);
<add> assertTrue(vec.getY().evaluate() == 2);
<add> assertTrue(vec.getZ().evaluate() == 3);
<add> assertTrue(vec.getW().evaluate() == 4);
<add>
<add> assertTrue(vec.getX().evaluate().equals(vec.get(0).evaluate()));
<add> assertTrue(vec.getY().evaluate().equals(vec.get(1).evaluate()));
<add> assertTrue(vec.getZ().evaluate().equals(vec.get(2).evaluate()));
<add> assertTrue(vec.getW().evaluate().equals(vec.get(3).evaluate()));
<add> }
<add>
<add> private void testAddCommon(Vector4 added, Vector4.Primitive expected) {
<add> assertEquals(added.getParents().size(), 2);
<add> assertEquals(added.evaluate(), expected);
<add> assertTrue(added.getEvaluator() instanceof BinaryOperationEvaluator);
<add> Operator op = ((BinaryOperationEvaluator)added.getEvaluator()).getOperator();
<add> assertEquals(op.getOperatorSymbol(), "+");
<add> }
<add>
<add> @Test
<add> public void testAdd() {
<add> Vector4 added = vec.add(1);
<add> testAddCommon(added, new Vector4.Primitive(2, 3, 4, 5));
<add> assertSame(added.getParents().get(0), vec);
<add> assertEquals(added.getParents().get(1).evaluate(), 1.0f);
<add>
<add> added = vec.add(new Real(1));
<add> testAddCommon(added, new Vector4.Primitive(2, 3, 4, 5));
<add> assertSame(added.getParents().get(0), vec);
<add> assertEquals(added.getParents().get(1).evaluate(), 1.0f);
<add>
<add> added = vec.add(vec);
<add> testAddCommon(added, new Vector4.Primitive(2, 4, 6, 8));
<add> assertSame(added.getParents().get(0), vec);
<add> assertSame(added.getParents().get(1), vec);
<add> }
<add>
<add> public void testSubCommon(Vector4 subtracted, Vector4.Primitive expected) {
<add> assertEquals(subtracted.getParents().size(), 2);
<add> assertEquals(subtracted.evaluate(), expected);
<add> assertTrue(subtracted.getEvaluator() instanceof BinaryOperationEvaluator);
<add> Operator op = ((BinaryOperationEvaluator)subtracted.getEvaluator()).getOperator();
<add> assertEquals(op.getOperatorSymbol(), "-");
<add> }
<add>
<add> @Test
<add> public void testSub() {
<add> Vector4 subtracted = vec.sub(1);
<add> testSubCommon(subtracted, new Vector4.Primitive(0, 1, 2, 3));
<add> assertSame(subtracted.getParents().get(0), vec);
<add> assertEquals(subtracted.getParents().get(1).evaluate(), 1.0f);
<add>
<add> subtracted = vec.sub(new Real(1));
<add> testSubCommon(subtracted, new Vector4.Primitive(0, 1, 2, 3));
<add> assertSame(subtracted.getParents().get(0), vec);
<add> assertEquals(subtracted.getParents().get(1).evaluate(), 1.0f);
<add>
<add> subtracted = vec.sub(vec);
<add> testSubCommon(subtracted, new Vector4.Primitive(0, 0, 0, 0));
<add> assertSame(subtracted.getParents().get(0), vec);
<add> assertSame(subtracted.getParents().get(1), vec);
<add> }
<add>
<add> private void testMulCommon(Vector4 multiplied, Vector4.Primitive expected) {
<add> assertEquals(multiplied.getParents().size(), 2);
<add> assertEquals(multiplied.evaluate(), expected);
<add> assertTrue(multiplied.getEvaluator() instanceof BinaryOperationEvaluator);
<add> Operator op = ((BinaryOperationEvaluator)multiplied.getEvaluator()).getOperator();
<add> assertEquals(op.getOperatorSymbol(), "*");
<add> }
<add>
<add> @Test
<add> public void testMul() {
<add> Vector4 multiplied = vec.mul(2);
<add> testMulCommon(multiplied, new Vector4.Primitive(2, 4, 6, 8));
<add> assertSame(multiplied.getParents().get(0), vec);
<add> assertEquals(multiplied.getParents().get(1).evaluate(), 2.0f);
<add>
<add> multiplied = vec.mul(new Real(2));
<add> testMulCommon(multiplied, new Vector4.Primitive(2, 4, 6, 8));
<add> assertSame(multiplied.getParents().get(0), vec);
<add> assertEquals(multiplied.getParents().get(1).evaluate(), 2.0f);
<add>
<add> multiplied = vec.mul(vec);
<add> testMulCommon(multiplied, new Vector4.Primitive(1, 4, 9, 16));
<add> assertSame(multiplied.getParents().get(0), vec);
<add> assertSame(multiplied.getParents().get(1), vec);
<add> }
<add>
<add> private void testDivCommon(Vector4 divided, Vector4.Primitive expected) {
<add> assertEquals(divided.getParents().size(), 2);
<add> assertEquals(divided.evaluate(), expected);
<add> assertTrue(divided.getEvaluator() instanceof BinaryOperationEvaluator);
<add> Operator op = ((BinaryOperationEvaluator)divided.getEvaluator()).getOperator();
<add> assertEquals(op.getOperatorSymbol(), "/");
<add> }
<add>
<add> @Test
<add> public void testDiv() {
<add> Vector4 divided = vec.div(2);
<add> testDivCommon(divided, new Vector4.Primitive(0.5f, 1, 1.5f, 2.0f));
<add> assertSame(divided.getParents().get(0), vec);
<add> assertEquals(divided.getParents().get(1).evaluate(), 2.0f);
<add>
<add> divided = vec.div(new Real(2));
<add> testDivCommon(divided, new Vector4.Primitive(0.5f, 1, 1.5f, 2.0f));
<add> assertSame(divided.getParents().get(0), vec);
<add> assertEquals(divided.getParents().get(1).evaluate(), 2.0f);
<add>
<add> divided = vec.div(vec);
<add> testDivCommon(divided, new Vector4.Primitive(1, 1, 1, 1));
<add> assertSame(divided.getParents().get(0), vec);
<add> assertSame(divided.getParents().get(1), vec);
<add> }
<add>
<add> @Test
<add> public void testNeg() {
<add> Vector4 negated = vec.neg();
<add> assertEquals(negated.getParents().size(), 1);
<add> assertSame(negated.getParents().get(0), vec);
<add> assertTrue(negated.getEvaluator() instanceof NegationEvaluator);
<add> assertEquals(negated.evaluate(), vec.evaluate().neg());
<add> }
<add>
<add> @Test
<add> public void testDot() {
<add> Real dot = vec.dot(new Vector4(1, 2, 3, 4));
<add> assertEquals(dot.getParents().size(), 2);
<add> assertSame(dot.getParents().get(0), vec);
<add> assertEquals(dot.getParents().get(1).evaluate(), new Vector4.Primitive(1, 2, 3, 4));
<add> assertTrue(dot.getEvaluator() instanceof FunctionEvaluator);
<add>
<add> FunctionEvaluator evaluator = ((FunctionEvaluator)dot.getEvaluator());
<add> assertEquals(evaluator.getFunctionName(), "dot");
<add> assertEquals(evaluator.getType(), Type.FLOAT_T);
<add>
<add> assertTrue(dot.evaluate() == vec.evaluate().dot(new Vector4.Primitive(1, 2, 3, 4)));
<add> }
<add>
<add> @Test
<add> public void testNormalize() {
<add> Vector4 normalized = vec.normalize();
<add> assertEquals(normalized.getParents().size(), 1);
<add> assertSame(normalized.getParents().get(0), vec);
<add> assertTrue(normalized.getEvaluator() instanceof FunctionEvaluator);
<add>
<add> FunctionEvaluator evaluator = ((FunctionEvaluator)normalized.getEvaluator());
<add> assertEquals(evaluator.getFunctionName(), "normalize");
<add> assertEquals(evaluator.getType(), Type.VEC4_T);
<add>
<add> assertEquals(normalized.evaluate(), vec.evaluate().normalize());
<add> }
<add>
<add> @Test
<add> public void testLength() {
<add> Real length = vec.length();
<add> assertEquals(length.getParents().size(), 1);
<add> assertSame(length.getParents().get(0), vec);
<add> assertTrue(length.getEvaluator() instanceof FunctionEvaluator);
<add>
<add> FunctionEvaluator evaluator = ((FunctionEvaluator)length.getEvaluator());
<add> assertEquals(evaluator.getFunctionName(), "length");
<add> assertEquals(evaluator.getType(), Type.FLOAT_T);
<add> }
<add>
<add> @Test
<add> public void testSwizzle() {
<add> Real swizzle = vec.swizzle('x');
<add> assertEquals(swizzle.getParents().size(), 1);
<add> assertSame(swizzle.getParents().get(0), vec);
<add> assertTrue(swizzle.getEvaluator() instanceof SwizzleEvaluator);
<add> assertTrue(swizzle.evaluate() == vec.evaluate().swizzle('x'));
<add>
<add> Vector2 swizzle2 = vec.swizzle('y', 'x');
<add> assertEquals(swizzle2.getParents().size(), 1);
<add> assertSame(swizzle2.getParents().get(0), vec);
<add> assertTrue(swizzle2.getEvaluator() instanceof SwizzleEvaluator);
<add> assertEquals(swizzle2.evaluate(), vec.evaluate().swizzle('y', 'x'));
<add>
<add> Vector3 swizzle3 = vec.swizzle('y', 'x', 'x');
<add> assertEquals(swizzle3.getParents().size(), 1);
<add> assertSame(swizzle3.getParents().get(0), vec);
<add> assertTrue(swizzle3.getEvaluator() instanceof SwizzleEvaluator);
<add> assertEquals(swizzle3.evaluate(), vec.evaluate().swizzle('y', 'x', 'x'));
<add>
<add> Vector4 swizzle4 = vec.swizzle('y', 'x', 'x', 'y');
<add> assertEquals(swizzle4.getParents().size(), 1);
<add> assertSame(swizzle4.getParents().get(0), vec);
<add> assertTrue(swizzle4.getEvaluator() instanceof SwizzleEvaluator);
<add> assertEquals(swizzle4.evaluate(), vec.evaluate().swizzle('y', 'x', 'x', 'y'));
<add> }
<add>
<add> @Test
<add> public void testFill() {
<add> Vector4 filled = vec.fill(new Vector4(1, 2, 3, 4));
<add> assertSame(vec, filled);
<add> }
<add>} |
|
JavaScript | apache-2.0 | c834a094abcc53ff7f22d8fcd0a40e700d5487a0 | 0 | e-mete/e-mete.github.io,e-mete/e-mete.github.io | function koddostuokunabilirlik(element){
var makale = element.textContent || element.innerText;
makale = makale.replace(/(\r\n|\n|\r)/gm," ").replace(/\s+/g, ' ');
var kelimeler = (makale.match(/ /g) || []).length;
var heceler = (makale.match(/a|e|ı|i|o|ö|u|ü|A|E|O|Ö|I|İ|U|Ü/g) || []).length;
var cumleler = (makale.match(/\.|\?|\:|\!/g) || []).length;
if(cumleler == 0){cumleler = 1;}
var atesman = parseInt(((198825/1000) - ((40175/1000)*(heceler/kelimeler))) - ((2610/1000)*(kelimeler/cumleler)));
if(atesman <= 10 || atesman >= 101){
atesman = 101;
}
var ilk = atesman-20;
var iki = atesman-35;
var uc = atesman-50;
var dort = atesman-80;
var ainterpolasyon = parseInt(((iki*uc*dort)/(-2250)) + ((ilk*uc*dort)/1012) + ((ilk*iki*dort)/(-1929)) + ((ilk*iki*uc)/16200) + 0.3);
document.getElementById('kacinci').innerHTML=ainterpolasyon;
}
| js/koddostuokunabilirlik.js | function koddostuokunabilirlik(){
var makale = element.textContent || element.innerText;
makale = makale.replace(/(\r\n|\n|\r)/gm," ").replace(/\s+/g, ' ');
var kelimeler = (makale.match(/ /g) || []).length;
var heceler = (makale.match(/a|e|ı|i|o|ö|u|ü|A|E|O|Ö|I|İ|U|Ü/g) || []).length;
var cumleler = (makale.match(/\.|\?|\:|\!/g) || []).length;
if(cumleler == 0){cumleler = 1;}
var atesman = parseInt(((198825/1000) - ((40175/1000)*(heceler/kelimeler))) - ((2610/1000)*(kelimeler/cumleler)));
if(atesman <= 10 || atesman >= 101){
atesman = 101;
}
var ilk = atesman-20;
var iki = atesman-35;
var uc = atesman-50;
var dort = atesman-80;
var ainterpolasyon = parseInt(((iki*uc*dort)/(-2250)) + ((ilk*uc*dort)/1012) + ((ilk*iki*dort)/(-1929)) + ((ilk*iki*uc)/16200) + 0.3);
document.getElementById('kacinci').innerHTML=ainterpolasyon;
}
| Update koddostuokunabilirlik.js | js/koddostuokunabilirlik.js | Update koddostuokunabilirlik.js | <ide><path>s/koddostuokunabilirlik.js
<del>function koddostuokunabilirlik(){
<add>function koddostuokunabilirlik(element){
<ide>
<ide> var makale = element.textContent || element.innerText;
<ide> makale = makale.replace(/(\r\n|\n|\r)/gm," ").replace(/\s+/g, ' '); |
|
Java | mit | d6d36538325e1076b8bc4fe5e37a70f8077fc013 | 0 | shuixi2013/ACDDExtension,fojut/ACDDExtension,HiGooogle/ACDDExtension,weiyihz/OpenAtlasExtension,Volcanoscar/OpenAtlasExtension,shuixi2013/ACDDExtension,RyanTech/ACDDExtension,fojut/ACDDExtension,weiyihz/OpenAtlasExtension,shuixi2013/ACDDExtension,Volcanoscar/OpenAtlasExtension,wangkang0627/OpenAtlasExtension,weiyihz/OpenAtlasExtension,fojut/ACDDExtension,shuixi2013/ACDDExtension,wangkang0627/OpenAtlasExtension,RyanTech/ACDDExtension,Volcanoscar/OpenAtlasExtension,treejames/OpenAtlasExtension,weiyihz/OpenAtlasExtension,RyanTech/ACDDExtension,wangkang0627/OpenAtlasExtension,fojut/ACDDExtension,treejames/OpenAtlasExtension,Volcanoscar/OpenAtlasExtension,treejames/OpenAtlasExtension,wangkang0627/OpenAtlasExtension,HiGooogle/ACDDExtension,RyanTech/ACDDExtension,HiGooogle/ACDDExtension,treejames/OpenAtlasExtension | /**
* OpenAtlasForAndroid Project
* <p/>
* The MIT License (MIT)
* Copyright (c) 2015 Bunny Blue
* <p/>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
* <p/>
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
* <p/>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @author BunnyBlue
* *
*/
package com.openAtlas.bundleInfo.maker;
import java.io.File;
import java.util.Collection;
/**
* @author BunnyBlue
*
*/
public class ApkPreProcess {
public static void preProcess(String mDir) {
Collection<File> apkFiles = org.apache.commons.io.FileUtils.listFiles(new File(mDir), new String[]{"apk"}, true);
for (File file : apkFiles) {
String pkgName = PackageLite.parse(file.getAbsolutePath()).packageName;
pkgName = "lib" + pkgName.replaceAll("\\.", "_") + ".so";
File targetFile = new File(mDir + File.separator + pkgName);
if (targetFile.exists())
targetFile.delete();
System.out.println("rename: " + file.getName() + " -> " + pkgName);
while(!file.renameTo(targetFile)) {
System.gc();
Thread.yield();
}
System.out.println("ApkPreProcess.preProcess() processed " + pkgName);
}
}
}
| buildTools/OpenAtlasBundler/src/com/openAtlas/bundleInfo/maker/ApkPreProcess.java | /**OpenAtlasForAndroid Project
The MIT License (MIT)
Copyright (c) 2015 Bunny Blue
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@author BunnyBlue
* **/
package com.openAtlas.bundleInfo.maker;
import java.io.File;
import java.util.Collection;
/**
* @author BunnyBlue
*
*/
public class ApkPreProcess {
public static void preProcess(String mDir) {
Collection<File> apkFiles= org.apache.commons.io.FileUtils.listFiles(new File(mDir), new String[]{"apk"} , true);
for (File file : apkFiles) {
String pkgName= PackageLite.parse(file.getAbsolutePath()).packageName;
pkgName="lib"+pkgName.replaceAll("\\.", "_")+".so";
File targetFile=new File(mDir+File.separator+pkgName);
targetFile.delete();
file.renameTo(targetFile);
System.out.println("ApkPreProcess.preProcess() processed "+pkgName);
}
}
}
| rename fail on Windows
http://stackoverflow.com/a/14123384/188784
resolve #9 | buildTools/OpenAtlasBundler/src/com/openAtlas/bundleInfo/maker/ApkPreProcess.java | rename fail on Windows | <ide><path>uildTools/OpenAtlasBundler/src/com/openAtlas/bundleInfo/maker/ApkPreProcess.java
<del>/**OpenAtlasForAndroid Project
<del>
<del>The MIT License (MIT)
<del>Copyright (c) 2015 Bunny Blue
<del>
<del>Permission is hereby granted, free of charge, to any person obtaining a copy of this software
<del>and associated documentation files (the "Software"), to deal in the Software
<del>without restriction, including without limitation the rights to use, copy, modify,
<del>merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
<del>permit persons to whom the Software is furnished to do so, subject to the following conditions:
<del>
<del>The above copyright notice and this permission notice shall be included in all copies
<del>or substantial portions of the Software.
<del>
<del>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
<del>INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
<del>PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
<del>FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
<del>ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>@author BunnyBlue
<del>* **/
<add>/**
<add> * OpenAtlasForAndroid Project
<add> * <p/>
<add> * The MIT License (MIT)
<add> * Copyright (c) 2015 Bunny Blue
<add> * <p/>
<add> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
<add> * and associated documentation files (the "Software"), to deal in the Software
<add> * without restriction, including without limitation the rights to use, copy, modify,
<add> * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
<add> * permit persons to whom the Software is furnished to do so, subject to the following conditions:
<add> * <p/>
<add> * The above copyright notice and this permission notice shall be included in all copies
<add> * or substantial portions of the Software.
<add> * <p/>
<add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
<add> * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
<add> * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
<add> * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
<add> * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<add> *
<add> * @author BunnyBlue
<add> * *
<add> */
<ide> package com.openAtlas.bundleInfo.maker;
<ide>
<ide> import java.io.File;
<ide> *
<ide> */
<ide> public class ApkPreProcess {
<del> public static void preProcess(String mDir) {
<del> Collection<File> apkFiles= org.apache.commons.io.FileUtils.listFiles(new File(mDir), new String[]{"apk"} , true);
<del>
<del> for (File file : apkFiles) {
<del> String pkgName= PackageLite.parse(file.getAbsolutePath()).packageName;
<del>
<del> pkgName="lib"+pkgName.replaceAll("\\.", "_")+".so";
<del> File targetFile=new File(mDir+File.separator+pkgName);
<del> targetFile.delete();
<del> file.renameTo(targetFile);
<del> System.out.println("ApkPreProcess.preProcess() processed "+pkgName);
<del> }
<del> }
<add> public static void preProcess(String mDir) {
<add> Collection<File> apkFiles = org.apache.commons.io.FileUtils.listFiles(new File(mDir), new String[]{"apk"}, true);
<ide>
<add> for (File file : apkFiles) {
<add> String pkgName = PackageLite.parse(file.getAbsolutePath()).packageName;
<add>
<add> pkgName = "lib" + pkgName.replaceAll("\\.", "_") + ".so";
<add> File targetFile = new File(mDir + File.separator + pkgName);
<add> if (targetFile.exists())
<add> targetFile.delete();
<add>
<add> System.out.println("rename: " + file.getName() + " -> " + pkgName);
<add> while(!file.renameTo(targetFile)) {
<add> System.gc();
<add> Thread.yield();
<add> }
<add> System.out.println("ApkPreProcess.preProcess() processed " + pkgName);
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 567fc9ae887bfff60fcf011e73fc61f9480194c0 | 0 | da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,signed/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,da1z/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,allotria/intellij-community,retomerz/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ibinti/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,allotria/intellij-community,fitermay/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,allotria/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,retomerz/intellij-community,signed/intellij-community,apixandru/intellij-community,fitermay/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ibinti/intellij-community,FHannes/intellij-community,signed/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,fitermay/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,xfournet/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,signed/intellij-community,semonte/intellij-community,fitermay/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,semonte/intellij-community,da1z/intellij-community,youdonghai/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,xfournet/intellij-community,asedunov/intellij-community,semonte/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,semonte/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,retomerz/intellij-community,signed/intellij-community,youdonghai/intellij-community,signed/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,retomerz/intellij-community,signed/intellij-community,allotria/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,signed/intellij-community,retomerz/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,hurricup/intellij-community,da1z/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,semonte/intellij-community,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,semonte/intellij-community,retomerz/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,apixandru/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,apixandru/intellij-community | // "Override method 'm'" "true"
interface A {
default void m(){}
}
interface B extends A {
@Override
default void m() {
}
} | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/afterInterfaceDefault.java | // "Override method 'm'" "true"
interface A {
default void m(){}
}
interface B extends A {
@Override
default void m() {
}
} | fix testdata
| java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/afterInterfaceDefault.java | fix testdata | <ide><path>ava/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/implementAbstractMethod/afterInterfaceDefault.java
<ide> interface B extends A {
<ide> @Override
<ide> default void m() {
<del>
<add>
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | a935b04678bd55b1e6de125e2a038820f25765e8 | 0 | minbrowser/min,minbrowser/min,minbrowser/min | var browserUI = require('api-wrapper.js')
window.sessionRestore = {
save: function () {
var data = {
version: 2,
state: JSON.parse(JSON.stringify(tabState))
}
// save all tabs that aren't private
for (var i = 0; i < data.state.tasks.length; i++) {
data.state.tasks[i].tabs = data.state.tasks[i].tabs.filter(function (tab) {
return !tab.private
})
}
localStorage.setItem('sessionrestoredata', JSON.stringify(data))
},
restore: function () {
var savedStringData = localStorage.getItem('sessionrestoredata')
/* the survey should only be shown after an upgrade from an earlier version */
var shouldShowSurvey = false
if (savedStringData && !localStorage.getItem('1.8survey')) {
shouldShowSurvey = true
}
localStorage.setItem('1.8survey', 'true')
try {
// first run, show the tour
if (!savedStringData) {
tasks.setSelected(tasks.add()) // create a new task
var newTab = currentTask.tabs.add({
url: 'https://minbrowser.github.io/min/tour'
})
browserUI.addTab(newTab, {
enterEditMode: false
})
return
}
console.log(savedStringData)
var data = JSON.parse(savedStringData)
// the data isn't restorable
if ((data.version && data.version !== 2) || (data.state && data.state.tasks && data.state.tasks.length === 0)) {
tasks.setSelected(tasks.add())
browserUI.addTab(currentTask.tabs.add())
return
}
// add the saved tasks
data.state.tasks.forEach(function (task) {
// restore the task item
tasks.add(task)
})
// switch to the previously selected tasks
browserUI.switchToTask(data.state.selectedTask)
if (currentTask.tabs.isEmpty()) {
tabBar.enterEditMode(currentTask.tabs.getSelected())
}
// if this isn't the first run, and the survey popup hasn't been shown yet, show it
if (shouldShowSurvey) {
fetch('https://minbrowser.github.io/min/survey/survey.json').then(function (response) {
return response.json()
}).then(function (data) {
setTimeout(function () {
if (data.available && data.url) {
if (currentTask.tabs.isEmpty()) {
navigate(currentTask.tabs.getSelected(), data.url)
} else {
var surveyTab = currentTask.tabs.add({
url: data.url
})
browserUI.addTab(surveyTab, {
enterEditMode: false
})
}
}}, 200)
})
}
} catch (e) {
// an error occured while restoring the session data
console.error('restoring session failed: ', e)
var backupSavePath = require('path').join(remote.app.getPath('userData'), 'sessionRestoreBackup-' + Date.now() + '.json')
require('fs').writeFileSync(backupSavePath, savedStringData)
// destroy any tabs that were created during the restore attempt
initializeTabState()
// create a new tab with an explanation of what happened
var newTask = tasks.add()
var newSessionErrorTab = tasks.get(newTask).tabs.add({
url: 'file://' + __dirname + '/pages/sessionRestoreError/index.html?backupLoc=' + encodeURIComponent(backupSavePath)
})
browserUI.switchToTask(newTask)
browserUI.switchToTab(newSessionErrorTab)
}
}
}
// TODO make this a preference
sessionRestore.restore()
setInterval(sessionRestore.save, 12500)
| js/sessionRestore.js | var browserUI = require('api-wrapper.js')
window.sessionRestore = {
save: function () {
var data = {
version: 2,
state: JSON.parse(JSON.stringify(tabState))
}
// save all tabs that aren't private
for (var i = 0; i < data.state.tasks.length; i++) {
data.state.tasks[i].tabs = data.state.tasks[i].tabs.filter(function (tab) {
return !tab.private
})
}
localStorage.setItem('sessionrestoredata', JSON.stringify(data))
},
restore: function () {
var savedStringData = localStorage.getItem('sessionrestoredata')
try {
// first run, show the tour
if (!savedStringData) {
tasks.setSelected(tasks.add()) // create a new task
var newTab = currentTask.tabs.add({
url: 'https://minbrowser.github.io/min/tour'
})
browserUI.addTab(newTab, {
enterEditMode: false
})
return
}
console.log(savedStringData)
var data = JSON.parse(savedStringData)
// the data isn't restorable
if ((data.version && data.version !== 2) || (data.state && data.state.tasks && data.state.tasks.length === 0)) {
tasks.setSelected(tasks.add())
browserUI.addTab(currentTask.tabs.add())
return
}
// add the saved tasks
data.state.tasks.forEach(function (task) {
// restore the task item
tasks.add(task)
})
// switch to the previously selected tasks
browserUI.switchToTask(data.state.selectedTask)
if (currentTask.tabs.isEmpty()) {
tabBar.enterEditMode(currentTask.tabs.getSelected())
}
} catch (e) {
// an error occured while restoring the session data
console.error('restoring session failed: ', e)
var backupSavePath = require('path').join(remote.app.getPath('userData'), 'sessionRestoreBackup-' + Date.now() + '.json')
require('fs').writeFileSync(backupSavePath, savedStringData)
// destroy any tabs that were created during the restore attempt
initializeTabState()
// create a new tab with an explanation of what happened
var newTask = tasks.add()
var newSessionErrorTab = tasks.get(newTask).tabs.add({
url: 'file://' + __dirname + '/pages/sessionRestoreError/index.html?backupLoc=' + encodeURIComponent(backupSavePath)
})
browserUI.switchToTask(newTask)
browserUI.switchToTab(newSessionErrorTab)
}
}
}
// TODO make this a preference
sessionRestore.restore()
setInterval(sessionRestore.save, 12500)
| show survey after upgrade
| js/sessionRestore.js | show survey after upgrade | <ide><path>s/sessionRestore.js
<ide> },
<ide> restore: function () {
<ide> var savedStringData = localStorage.getItem('sessionrestoredata')
<add>
<add> /* the survey should only be shown after an upgrade from an earlier version */
<add> var shouldShowSurvey = false
<add> if (savedStringData && !localStorage.getItem('1.8survey')) {
<add> shouldShowSurvey = true
<add> }
<add> localStorage.setItem('1.8survey', 'true')
<ide>
<ide> try {
<ide> // first run, show the tour
<ide> if (currentTask.tabs.isEmpty()) {
<ide> tabBar.enterEditMode(currentTask.tabs.getSelected())
<ide> }
<add>
<add> // if this isn't the first run, and the survey popup hasn't been shown yet, show it
<add>
<add> if (shouldShowSurvey) {
<add> fetch('https://minbrowser.github.io/min/survey/survey.json').then(function (response) {
<add> return response.json()
<add> }).then(function (data) {
<add> setTimeout(function () {
<add> if (data.available && data.url) {
<add> if (currentTask.tabs.isEmpty()) {
<add> navigate(currentTask.tabs.getSelected(), data.url)
<add> } else {
<add> var surveyTab = currentTask.tabs.add({
<add> url: data.url
<add> })
<add> browserUI.addTab(surveyTab, {
<add> enterEditMode: false
<add> })
<add> }
<add> }}, 200)
<add> })
<add> }
<ide> } catch (e) {
<ide> // an error occured while restoring the session data
<ide> |
|
JavaScript | mit | 26ca34416c0d4066eeb3c2cf1ee008428def27a7 | 0 | ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { TICK_SIZE } = require ('./base/functions/number');
const { AuthenticationError, ExchangeError, ArgumentsRequired, PermissionDenied, InvalidOrder, OrderNotFound, InsufficientFunds, BadRequest, RateLimitExceeded, InvalidNonce, NotSupported } = require ('./base/errors');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class bybit extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bybit',
'name': 'Bybit',
'countries': [ 'VG' ], // British Virgin Islands
'version': 'v2',
'userAgent': undefined,
// 50 requests per second for GET requests, 1000ms / 50 = 20ms between requests
// 20 requests per second for POST requests, cost = 50 / 20 = 2.5
'rateLimit': 20,
'hostname': 'bybit.com', // bybit.com, bytick.com
'has': {
'CORS': true,
'spot': true,
'margin': false,
'swap': true,
'future': true,
'option': undefined,
'cancelAllOrders': true,
'cancelOrder': true,
'createOrder': true,
'createStopLimitOrder': true,
'createStopMarketOrder': true,
'createStopOrder': true,
'editOrder': true,
'fetchBalance': true,
'fetchBorrowRate': false,
'fetchBorrowRates': false,
'fetchClosedOrders': true,
'fetchDeposits': true,
'fetchFundingRate': true,
'fetchFundingRateHistory': false,
'fetchIndexOHLCV': true,
'fetchLedger': true,
'fetchMarketLeverageTiers': true,
'fetchMarkets': true,
'fetchMarkOHLCV': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchOrderTrades': true,
'fetchPositions': true,
'fetchPremiumIndexOHLCV': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': false,
'fetchTransactions': undefined,
'fetchWithdrawals': true,
'setLeverage': true,
'setMarginMode': true,
},
'timeframes': {
'1m': '1',
'3m': '3',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'2h': '120',
'4h': '240',
'6h': '360',
'12h': '720',
'1d': 'D',
'1w': 'W',
'1M': 'M',
'1y': 'Y',
},
'urls': {
'test': {
'spot': 'https://api-testnet.{hostname}',
'futures': 'https://api-testnet.{hostname}',
'v2': 'https://api-testnet.{hostname}',
'public': 'https://api-testnet.{hostname}',
'private': 'https://api-testnet.{hostname}',
},
'logo': 'https://user-images.githubusercontent.com/51840849/76547799-daff5b80-649e-11ea-87fb-3be9bac08954.jpg',
'api': {
'spot': 'https://api.{hostname}',
'futures': 'https://api.{hostname}',
'v2': 'https://api.{hostname}',
'public': 'https://api.{hostname}',
'private': 'https://api.{hostname}',
},
'www': 'https://www.bybit.com',
'doc': [
'https://bybit-exchange.github.io/docs/inverse/',
'https://bybit-exchange.github.io/docs/linear/',
'https://github.com/bybit-exchange',
],
'fees': 'https://help.bybit.com/hc/en-us/articles/360039261154',
'referral': 'https://www.bybit.com/app/register?ref=X7Prm',
},
'api': {
// outdated endpoints -----------------------------------------
'spot': {
'public': {
'get': [
'symbols',
],
},
'quote': {
'get': [
'depth',
'depth/merged',
'trades',
'kline',
'ticker/24hr',
'ticker/price',
'ticker/book_ticker',
],
},
'private': {
'get': [
'order',
'open-orders',
'history-orders',
'myTrades',
'account',
'time',
],
'post': [
'order',
],
'delete': [
'order',
'order/fast',
],
},
'order': {
'delete': [
'batch-cancel',
'batch-fast-cancel',
'batch-cancel-by-ids',
],
},
},
'futures': {
'private': {
'get': [
'order/list',
'order',
'stop-order/list',
'stop-order',
'position/list',
'execution/list',
'trade/closed-pnl/list',
],
'post': [
'order/create',
'order/cancel',
'order/cancelAll',
'order/replace',
'stop-order/create',
'stop-order/cancel',
'stop-order/cancelAll',
'stop-order/replace',
'position/change-position-margin',
'position/trading-stop',
'position/leverage/save',
'position/switch-mode',
'position/switch-isolated',
'position/risk-limit',
],
},
},
'v2': {
'public': {
'get': [
'orderBook/L2',
'kline/list',
'tickers',
'trading-records',
'symbols',
'liq-records',
'mark-price-kline',
'index-price-kline',
'premium-index-kline',
'open-interest',
'big-deal',
'account-ratio',
'time',
'announcement',
'funding/prev-funding-rate',
'risk-limit/list',
],
},
'private': {
'get': [
'order/list',
'order',
'stop-order/list',
'stop-order',
'position/list',
'position/fee-rate',
'execution/list',
'trade/closed-pnl/list',
'funding/prev-funding-rate',
'funding/prev-funding',
'funding/predicted-funding',
'account/api-key',
'account/lcp',
'wallet/balance',
'wallet/fund/records',
'wallet/withdraw/list',
'exchange-order/list',
],
'post': [
'order/create',
'order/cancel',
'order/cancelAll',
'order/replace',
'stop-order/create',
'stop-order/cancel',
'stop-order/cancelAll',
'stop-order/replace',
'position/change-position-margin',
'position/trading-stop',
'position/leverage/save',
'position/switch-mode',
'position/switch-isolated',
'position/risk-limit',
],
},
},
// new endpoints ------------------------------------------
'public': {
'get': {
// inverse swap
'v2/public/orderBook/L2': 1,
'v2/public/kline/list': 3,
'v2/public/tickers': 1,
'v2/public/trading-records': 1,
'v2/public/symbols': 1,
'v2/public/mark-price-kline': 3,
'v2/public/index-price-kline': 3,
'v2/public/premium-index-kline': 2,
'v2/public/open-interest': 1,
'v2/public/big-deal': 1,
'v2/public/account-ratio': 1,
'v2/public/funding-rate': 1,
'v2/public/elite-ratio': 1,
'v2/public/risk-limit/list': 1,
// linear swap USDT
'public/linear/kline': 3,
'public/linear/recent-trading-records': 1,
'public/linear/funding/prev-funding-rate': 1,
'public/linear/mark-price-kline': 1,
'public/linear/index-price-kline': 1,
'public/linear/premium-index-kline': 1,
// spot
'spot/v1/time': 1,
'spot/v1/symbols': 1,
'spot/quote/v1/depth': 1,
'spot/quote/v1/depth/merged': 1,
'spot/quote/v1/trades': 1,
'spot/quote/v1/kline': 1,
'spot/quote/v1/ticker/24hr': 1,
'spot/quote/v1/ticker/price': 1,
'spot/quote/v1/ticker/book_ticker': 1,
// data
'v2/public/time': 1,
'v2/public/announcement': 1,
// USDC endpoints are testnet only as of 2022 Jan 11 ----------
// option USDC (testnet only)
'option/usdc/openapi/public/v1/order-book': 1,
'option/usdc/openapi/public/v1/symbols': 1,
'option/usdc/openapi/public/v1/tick': 1,
'option/usdc/openapi/public/v1/delivery-price': 1,
'option/usdc/openapi/public/v1/query-trade-latest': 1,
// perpetual swap USDC (testnet only)
'perpetual/usdc/openapi/public/v1/order-book': 1,
'perpetual/usdc/openapi/public/v1/symbols': 1,
'perpetual/usdc/openapi/public/v1/tick': 1,
'perpetual/usdc/openapi/public/v1/kline/list': 1,
'perpetual/usdc/openapi/public/v1/mark-price-kline': 1,
'perpetual/usdc/openapi/public/v1/index-price-kline': 1,
'perpetual/usdc/openapi/public/v1/premium-index-kline': 1,
'perpetual/usdc/openapi/public/v1/open-interest': 1,
'perpetual/usdc/openapi/public/v1/big-deal': 1,
'perpetual/usdc/openapi/public/v1/account-ratio': 1,
'perpetual/usdc/openapi/public/v1/risk-limit/list': 1,
},
// outdated endpoints--------------------------------------
'linear': {
'get': [
'kline',
'recent-trading-records',
'funding/prev-funding-rate',
'mark-price-kline',
'index-price-kline',
'premium-index-kline',
'risk-limit',
],
},
},
// new endpoints ------------------------------------------
'private': {
'get': {
// inverse swap
'v2/private/order/list': 5,
'v2/private/order': 5,
'v2/private/stop-order/list': 5,
'v2/private/stop-order': 1,
'v2/private/position/list': 25,
'v2/private/position/fee-rate': 40,
'v2/private/execution/list': 25,
'v2/private/trade/closed-pnl/list': 1,
'v2/public/risk-limit/list': 1, // TODO check
'v2/public/funding/prev-funding-rate': 25, // TODO check
'v2/private/funding/prev-funding': 25,
'v2/private/funding/predicted-funding': 25,
'v2/private/account/api-key': 5,
'v2/private/account/lcp': 1,
'v2/private/wallet/balance': 25, // 120 per minute = 2 per second => cost = 50 / 2 = 25
'v2/private/wallet/fund/records': 25,
'v2/private/wallet/withdraw/list': 25,
'v2/private/exchange-order/list': 1,
// linear swap USDT
'private/linear/order/list': 5, // 600 per minute = 10 per second => cost = 50 / 10 = 5
'private/linear/order/search': 5,
'private/linear/stop-order/list': 5,
'private/linear/stop-order/search': 5,
'private/linear/position/list': 25,
'private/linear/trade/execution/list': 25,
'private/linear/trade/closed-pnl/list': 25,
'public/linear/risk-limit': 1,
'private/linear/funding/predicted-funding': 25,
'private/linear/funding/prev-funding': 25,
// inverse futures
'futures/private/order/list': 5,
'futures/private/order': 5,
'futures/private/stop-order/list': 5,
'futures/private/stop-order': 5,
'futures/private/position/list': 25,
'futures/private/execution/list': 25,
'futures/private/trade/closed-pnl/list': 1,
// spot
'spot/v1/account': 2.5,
'spot/v1/order': 2.5,
'spot/v1/open-orders': 2.5,
'spot/v1/history-orders': 2.5,
'spot/v1/myTrades': 2.5,
// account
'asset/v1/private/transfer/list': 50, // 60 per minute = 1 per second => cost = 50 / 1 = 50
'asset/v1/private/sub-member/transfer/list': 50,
'asset/v1/private/sub-member/member-ids': 50,
},
'post': {
// inverse swap
'v2/private/order/create': 30,
'v2/private/order/cancel': 30,
'v2/private/order/cancelAll': 300, // 100 per minute + 'consumes 10 requests'
'v2/private/order/replace': 30,
'v2/private/stop-order/create': 30,
'v2/private/stop-order/cancel': 30,
'v2/private/stop-order/cancelAll': 300,
'v2/private/stop-order/replace': 30,
'v2/private/position/change-position-margin': 40,
'v2/private/position/trading-stop': 40,
'v2/private/position/leverage/save': 40,
'v2/private/tpsl/switch-mode': 40,
'v2/private/position/switch-isolated': 2.5,
'v2/private/position/risk-limit': 2.5,
'v2/private/position/switch-mode': 2.5,
// linear swap USDT
'private/linear/order/create': 30, // 100 per minute = 1.666 per second => cost = 50 / 1.6666 = 30
'private/linear/order/cancel': 30,
'private/linear/order/cancel-all': 300, // 100 per minute + 'consumes 10 requests'
'private/linear/order/replace': 30,
'private/linear/stop-order/create': 30,
'private/linear/stop-order/cancel': 30,
'private/linear/stop-order/cancel-all': 300,
'private/linear/stop-order/replace': 30,
'private/linear/position/set-auto-add-margin': 40,
'private/linear/position/switch-isolated': 40,
'private/linear/position/switch-mode': 40,
'private/linear/tpsl/switch-mode': 2.5,
'private/linear/position/add-margin': 40,
'private/linear/position/set-leverage': 40, // 75 per minute = 1.25 per second => cost = 50 / 1.25 = 40
'private/linear/position/trading-stop': 40,
'private/linear/position/set-risk': 2.5,
// inverse futures
'futures/private/order/create': 30,
'futures/private/order/cancel': 30,
'futures/private/order/cancelAll': 30,
'futures/private/order/replace': 30,
'futures/private/stop-order/create': 30,
'futures/private/stop-order/cancel': 30,
'futures/private/stop-order/cancelAll': 30,
'futures/private/stop-order/replace': 30,
'futures/private/position/change-position-margin': 40,
'futures/private/position/trading-stop': 40,
'futures/private/position/leverage/save': 40,
'futures/private/position/switch-mode': 40,
'futures/private/tpsl/switch-mode': 40,
'futures/private/position/switch-isolated': 40,
'futures/private/position/risk-limit': 2.5,
// spot
'spot/v1/order': 2.5,
// account
'asset/v1/private/transfer': 150, // 20 per minute = 0.333 per second => cost = 50 / 0.3333 = 150
'asset/v1/private/sub-member/transfer': 150,
// USDC endpoints are testnet only as of 2022 Jan 11 ----------
// option USDC (testnet only)
'option/usdc/openapi/private/v1/place-order': 2.5,
'option/usdc/openapi/private/v1/batch-place-order': 2.5,
'option/usdc/openapi/private/v1/replace-order': 2.5,
'option/usdc/openapi/private/v1/batch-replace-orders': 2.5,
'option/usdc/openapi/private/v1/cancel-order': 2.5,
'option/usdc/openapi/private/v1/batch-cancel-orders': 2.5,
'option/usdc/openapi/private/v1/cancel-all': 2.5,
'option/usdc/openapi/private/v1/query-active-orders': 2.5,
'option/usdc/openapi/private/v1/query-order-history': 2.5,
'option/usdc/openapi/private/v1/execution-list': 2.5,
'option/usdc/openapi/private/v1/query-transaction-log': 2.5,
'option/usdc/openapi/private/v1/query-wallet-balance': 2.5,
'option/usdc/openapi/private/v1/query-asset-info': 2.5,
'option/usdc/openapi/private/v1/query-margin-info': 2.5,
'option/usdc/openapi/private/v1/query-position': 2.5,
'option/usdc/openapi/private/v1/query-delivery-list': 2.5,
'option/usdc/openapi/private/v1/query-position-exp-date': 2.5,
'option/usdc/openapi/private/v1/mmp-modify': 2.5,
'option/usdc/openapi/private/v1/mmp-reset': 2.5,
// perpetual swap USDC (testnet only)
'perpetual/usdc/openapi/private/v1/place-order': 2.5,
'perpetual/usdc/openapi/private/v1/replace-order': 2.5,
'perpetual/usdc/openapi/private/v1/cancel-order': 2.5,
'perpetual/usdc/openapi/private/v1/cancel-all': 2.5,
'perpetual/usdc/openapi/private/v1/position/leverage/save': 2.5,
'option/usdc/openapi/private/v1/session-settlement': 2.5,
'perpetual/usdc/openapi/public/v1/risk-limit/list': 2.5,
'perpetual/usdc/openapi/private/v1/position/set-risk-limit': 2.5,
},
'delete': {
// spot
'spot/v1/order': 2.5,
'spot/v1/order/fast': 2.5,
'spot/order/batch-cancel': 2.5,
'spot/order/batch-fast-cancel': 2.5,
'spot/order/batch-cancel-by-ids': 2.5,
},
// outdated endpoints -------------------------------------
'linear': {
'get': [
'order/list',
'order/search',
'stop-order/list',
'stop-order/search',
'position/list',
'trade/execution/list',
'trade/closed-pnl/list',
'funding/predicted-funding',
'funding/prev-funding',
],
'post': [
'order/create',
'order/cancel',
'order/cancel-all',
'order/replace',
'stop-order/create',
'stop-order/cancel',
'stop-order/cancel-all',
'stop-order/replace',
'position/set-auto-add-margin',
'position/switch-isolated',
'position/switch-mode',
'tpsl/switch-mode',
'position/add-margin',
'position/set-leverage',
'position/trading-stop',
'position/set-risk',
],
},
},
},
'httpExceptions': {
'403': RateLimitExceeded, // Forbidden -- You request too many times
},
'exceptions': {
'exact': {
'-10009': BadRequest, // {"ret_code":-10009,"ret_msg":"Invalid period!","result":null,"token":null}
'-2015': AuthenticationError, // Invalid API-key, IP, or permissions for action.
'-1021': BadRequest, // {"ret_code":-1021,"ret_msg":"Timestamp for this request is outside of the recvWindow.","ext_code":null,"ext_info":null,"result":null}
'-1004': BadRequest, // {"ret_code":-1004,"ret_msg":"Missing required parameter \u0027symbol\u0027","ext_code":null,"ext_info":null,"result":null}
'7001': BadRequest, // {"retCode":7001,"retMsg":"request params type error"}
'10001': BadRequest, // parameter error
'10002': InvalidNonce, // request expired, check your timestamp and recv_window
'10003': AuthenticationError, // Invalid apikey
'10004': AuthenticationError, // invalid sign
'10005': PermissionDenied, // permission denied for current apikey
'10006': RateLimitExceeded, // too many requests
'10007': AuthenticationError, // api_key not found in your request parameters
'10010': PermissionDenied, // request ip mismatch
'10016': ExchangeError, // {"retCode":10016,"retMsg":"System error. Please try again later."}
'10017': BadRequest, // request path not found or request method is invalid
'10018': RateLimitExceeded, // exceed ip rate limit
'20001': OrderNotFound, // Order not exists
'20003': InvalidOrder, // missing parameter side
'20004': InvalidOrder, // invalid parameter side
'20005': InvalidOrder, // missing parameter symbol
'20006': InvalidOrder, // invalid parameter symbol
'20007': InvalidOrder, // missing parameter order_type
'20008': InvalidOrder, // invalid parameter order_type
'20009': InvalidOrder, // missing parameter qty
'20010': InvalidOrder, // qty must be greater than 0
'20011': InvalidOrder, // qty must be an integer
'20012': InvalidOrder, // qty must be greater than zero and less than 1 million
'20013': InvalidOrder, // missing parameter price
'20014': InvalidOrder, // price must be greater than 0
'20015': InvalidOrder, // missing parameter time_in_force
'20016': InvalidOrder, // invalid value for parameter time_in_force
'20017': InvalidOrder, // missing parameter order_id
'20018': InvalidOrder, // invalid date format
'20019': InvalidOrder, // missing parameter stop_px
'20020': InvalidOrder, // missing parameter base_price
'20021': InvalidOrder, // missing parameter stop_order_id
'20022': BadRequest, // missing parameter leverage
'20023': BadRequest, // leverage must be a number
'20031': BadRequest, // leverage must be greater than zero
'20070': BadRequest, // missing parameter margin
'20071': BadRequest, // margin must be greater than zero
'20084': BadRequest, // order_id or order_link_id is required
'30001': BadRequest, // order_link_id is repeated
'30003': InvalidOrder, // qty must be more than the minimum allowed
'30004': InvalidOrder, // qty must be less than the maximum allowed
'30005': InvalidOrder, // price exceeds maximum allowed
'30007': InvalidOrder, // price exceeds minimum allowed
'30008': InvalidOrder, // invalid order_type
'30009': ExchangeError, // no position found
'30010': InsufficientFunds, // insufficient wallet balance
'30011': PermissionDenied, // operation not allowed as position is undergoing liquidation
'30012': PermissionDenied, // operation not allowed as position is undergoing ADL
'30013': PermissionDenied, // position is in liq or adl status
'30014': InvalidOrder, // invalid closing order, qty should not greater than size
'30015': InvalidOrder, // invalid closing order, side should be opposite
'30016': ExchangeError, // TS and SL must be cancelled first while closing position
'30017': InvalidOrder, // estimated fill price cannot be lower than current Buy liq_price
'30018': InvalidOrder, // estimated fill price cannot be higher than current Sell liq_price
'30019': InvalidOrder, // cannot attach TP/SL params for non-zero position when placing non-opening position order
'30020': InvalidOrder, // position already has TP/SL params
'30021': InvalidOrder, // cannot afford estimated position_margin
'30022': InvalidOrder, // estimated buy liq_price cannot be higher than current mark_price
'30023': InvalidOrder, // estimated sell liq_price cannot be lower than current mark_price
'30024': InvalidOrder, // cannot set TP/SL/TS for zero-position
'30025': InvalidOrder, // trigger price should bigger than 10% of last price
'30026': InvalidOrder, // price too high
'30027': InvalidOrder, // price set for Take profit should be higher than Last Traded Price
'30028': InvalidOrder, // price set for Stop loss should be between Liquidation price and Last Traded Price
'30029': InvalidOrder, // price set for Stop loss should be between Last Traded Price and Liquidation price
'30030': InvalidOrder, // price set for Take profit should be lower than Last Traded Price
'30031': InsufficientFunds, // insufficient available balance for order cost
'30032': InvalidOrder, // order has been filled or cancelled
'30033': RateLimitExceeded, // The number of stop orders exceeds maximum limit allowed
'30034': OrderNotFound, // no order found
'30035': RateLimitExceeded, // too fast to cancel
'30036': ExchangeError, // the expected position value after order execution exceeds the current risk limit
'30037': InvalidOrder, // order already cancelled
'30041': ExchangeError, // no position found
'30042': InsufficientFunds, // insufficient wallet balance
'30043': InvalidOrder, // operation not allowed as position is undergoing liquidation
'30044': InvalidOrder, // operation not allowed as position is undergoing AD
'30045': InvalidOrder, // operation not allowed as position is not normal status
'30049': InsufficientFunds, // insufficient available balance
'30050': ExchangeError, // any adjustments made will trigger immediate liquidation
'30051': ExchangeError, // due to risk limit, cannot adjust leverage
'30052': ExchangeError, // leverage can not less than 1
'30054': ExchangeError, // position margin is invalid
'30057': ExchangeError, // requested quantity of contracts exceeds risk limit
'30063': ExchangeError, // reduce-only rule not satisfied
'30067': InsufficientFunds, // insufficient available balance
'30068': ExchangeError, // exit value must be positive
'30074': InvalidOrder, // can't create the stop order, because you expect the order will be triggered when the LastPrice(or IndexPrice、 MarkPrice, determined by trigger_by) is raising to stop_px, but the LastPrice(or IndexPrice、 MarkPrice) is already equal to or greater than stop_px, please adjust base_price or stop_px
'30075': InvalidOrder, // can't create the stop order, because you expect the order will be triggered when the LastPrice(or IndexPrice、 MarkPrice, determined by trigger_by) is falling to stop_px, but the LastPrice(or IndexPrice、 MarkPrice) is already equal to or less than stop_px, please adjust base_price or stop_px
'30078': ExchangeError, // {"ret_code":30078,"ret_msg":"","ext_code":"","ext_info":"","result":null,"time_now":"1644853040.916000","rate_limit_status":73,"rate_limit_reset_ms":1644853040912,"rate_limit":75}
// '30084': BadRequest, // Isolated not modified, see handleErrors below
'33004': AuthenticationError, // apikey already expired
'34026': ExchangeError, // the limit is no change
'35015': BadRequest, // {"ret_code":35015,"ret_msg":"Qty not in range","ext_code":"","ext_info":"","result":null,"time_now":"1652277215.821362","rate_limit_status":99,"rate_limit_reset_ms":1652277215819,"rate_limit":100}
'130021': InsufficientFunds, // {"ret_code":130021,"ret_msg":"orderfix price failed for CannotAffordOrderCost.","ext_code":"","ext_info":"","result":null,"time_now":"1644588250.204878","rate_limit_status":98,"rate_limit_reset_ms":1644588250200,"rate_limit":100}
'3100116': BadRequest, // {"retCode":3100116,"retMsg":"Order quantity below the lower limit 0.01.","result":null,"retExtMap":{"key0":"0.01"}}
'3100198': BadRequest, // {"retCode":3100198,"retMsg":"orderLinkId can not be empty.","result":null,"retExtMap":{}}
'3200300': InsufficientFunds, // {"retCode":3200300,"retMsg":"Insufficient margin balance.","result":null,"retExtMap":{}}
},
'broad': {
'unknown orderInfo': OrderNotFound, // {"ret_code":-1,"ret_msg":"unknown orderInfo","ext_code":"","ext_info":"","result":null,"time_now":"1584030414.005545","rate_limit_status":99,"rate_limit_reset_ms":1584030414003,"rate_limit":100}
'invalid api_key': AuthenticationError, // {"ret_code":10003,"ret_msg":"invalid api_key","ext_code":"","ext_info":"","result":null,"time_now":"1599547085.415797"}
},
},
'precisionMode': TICK_SIZE,
'options': {
'createMarketBuyOrderRequiresPrice': true,
'marketTypes': {
'BTC/USDT': 'linear',
'ETH/USDT': 'linear',
'BNB/USDT': 'linear',
'ADA/USDT': 'linear',
'DOGE/USDT': 'linear',
'XRP/USDT': 'linear',
'DOT/USDT': 'linear',
'UNI/USDT': 'linear',
'BCH/USDT': 'linear',
'LTC/USDT': 'linear',
'SOL/USDT': 'linear',
'LINK/USDT': 'linear',
'MATIC/USDT': 'linear',
'ETC/USDT': 'linear',
'FIL/USDT': 'linear',
'EOS/USDT': 'linear',
'AAVE/USDT': 'linear',
'XTZ/USDT': 'linear',
'SUSHI/USDT': 'linear',
'XEM/USDT': 'linear',
'BTC/USD': 'inverse',
'ETH/USD': 'inverse',
'EOS/USD': 'inverse',
'XRP/USD': 'inverse',
},
'defaultType': 'linear', // linear, inverse, futures
//
// ^
// |
// | this will be replaced with the following soon |
// |
// v
//
// 'defaultType': 'swap', // swap, spot, future, option
'code': 'BTC',
'cancelAllOrders': {
// 'method': 'v2PrivatePostOrderCancelAll', // v2PrivatePostStopOrderCancelAll
},
'recvWindow': 5 * 1000, // 5 sec default
'timeDifference': 0, // the difference between system clock and exchange server clock
'adjustForTimeDifference': false, // controls the adjustment logic upon instantiation
'defaultSettle': 'USDT', // USDC for USDC settled markets
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'taker': 0.00075,
'maker': -0.00025,
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {},
'deposit': {},
},
},
});
}
nonce () {
return this.milliseconds () - this.options['timeDifference'];
}
async fetchTime (params = {}) {
const response = await this.publicGetV2PublicTime (params);
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: {},
// time_now: '1583933682.448826'
// }
//
return this.safeTimestamp (response, 'time_now');
}
async fetchMarkets (params = {}) {
if (this.options['adjustForTimeDifference']) {
await this.loadTimeDifference ();
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchMarkets', undefined, params);
if (type === 'spot') {
// spot and swap ids are equal
// so they can't be loaded together
const spotMarkets = await this.fetchSpotMarkets (params);
return spotMarkets;
}
const contractMarkets = await this.fetchSwapAndFutureMarkets (params);
const usdcMarkets = await this.fetchUSDCMarkets (params);
let markets = contractMarkets;
markets = this.arrayConcat (markets, usdcMarkets);
return markets;
}
async fetchSpotMarkets (params) {
const response = await this.publicGetSpotV1Symbols (params);
//
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":[
// {
// "name":"BTCUSDT",
// "alias":"BTCUSDT",
// "baseCurrency":"BTC",
// "quoteCurrency":"USDT",
// "basePrecision":"0.000001",
// "quotePrecision":"0.00000001",
// "minTradeQuantity":"0.000158",
// "minTradeAmount":"10",
// "maxTradeQuantity":"4",
// "maxTradeAmount":"100000",
// "minPricePrecision":"0.01",
// "category":1,
// "showStatus":true
// },
// ]
// }
const markets = this.safeValue (response, 'result', []);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'name');
const baseId = this.safeString (market, 'baseCurrency');
const quoteId = this.safeString (market, 'quoteCurrency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const active = this.safeValue (market, 'showStatus');
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': undefined,
'baseId': baseId,
'quoteId': quoteId,
'settleId': undefined,
'type': 'spot',
'spot': true,
'margin': undefined,
'swap': false,
'future': false,
'option': false,
'active': active,
'contract': false,
'linear': undefined,
'inverse': undefined,
'taker': undefined,
'maker': undefined,
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': this.safeNumber (market, 'basePrecision'),
'price': this.safeNumber (market, 'quotePrecision'),
},
'limits': {
'leverage': {
'min': this.parseNumber ('1'),
'max': undefined,
},
'amount': {
'min': this.safeNumber (market, 'minTradeQuantity'),
'max': this.safeNumber (market, 'maxTradeQuantity'),
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'minTradeAmount'),
'max': this.safeNumber (market, 'maxTradeAmount'),
},
},
'info': market,
});
}
return result;
}
async fetchSwapAndFutureMarkets (params) {
const response = await this.publicGetV2PublicSymbols (params);
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// // inverse swap
// {
// "name":"BTCUSD",
// "alias":"BTCUSD",
// "status":"Trading",
// "base_currency":"BTC",
// "quote_currency":"USD",
// "price_scale":2,
// "taker_fee":"0.00075",
// "maker_fee":"-0.00025",
// "leverage_filter":{"min_leverage":1,"max_leverage":100,"leverage_step":"0.01"},
// "price_filter":{"min_price":"0.5","max_price":"999999","tick_size":"0.5"},
// "lot_size_filter":{"max_trading_qty":1000000,"min_trading_qty":1,"qty_step":1}
// },
// // linear swap
// {
// "name":"BTCUSDT",
// "alias":"BTCUSDT",
// "status":"Trading",
// "base_currency":"BTC",
// "quote_currency":"USDT",
// "price_scale":2,
// "taker_fee":"0.00075",
// "maker_fee":"-0.00025",
// "leverage_filter":{"min_leverage":1,"max_leverage":100,"leverage_step":"0.01"},
// "price_filter":{"min_price":"0.5","max_price":"999999","tick_size":"0.5"},
// "lot_size_filter":{"max_trading_qty":100,"min_trading_qty":0.001, "qty_step":0.001}
// },
// inverse futures
// {
// "name": "BTCUSDU22",
// "alias": "BTCUSD0930",
// "status": "Trading",
// "base_currency": "BTC",
// "quote_currency": "USD",
// "price_scale": "2",
// "taker_fee": "0.0006",
// "maker_fee": "0.0001",
// "funding_interval": "480",
// "leverage_filter": {
// "min_leverage": "1",
// "max_leverage": "100",
// "leverage_step": "0.01"
// },
// "price_filter": {
// "min_price": "0.5",
// "max_price": "999999",
// "tick_size": "0.5"
// },
// "lot_size_filter": {
// "max_trading_qty": "1000000",
// "min_trading_qty": "1",
// "qty_step": "1",
// "post_only_max_trading_qty": "5000000"
// }
// }
// ],
// "time_now":"1642369942.072113"
// }
//
const markets = this.safeValue (response, 'result', []);
const result = [];
const options = this.safeValue (this.options, 'fetchMarkets', {});
const linearQuoteCurrencies = this.safeValue (options, 'linear', { 'USDT': true });
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'name');
const baseId = this.safeString (market, 'base_currency');
const quoteId = this.safeString (market, 'quote_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const linear = (quote in linearQuoteCurrencies);
let symbol = base + '/' + quote;
const baseQuote = base + quote;
let type = 'swap';
if (baseQuote !== id) {
type = 'future';
}
const lotSizeFilter = this.safeValue (market, 'lot_size_filter', {});
const priceFilter = this.safeValue (market, 'price_filter', {});
const leverage = this.safeValue (market, 'leverage_filter', {});
const status = this.safeString (market, 'status');
let active = undefined;
if (status !== undefined) {
active = (status === 'Trading');
}
const swap = (type === 'swap');
const future = (type === 'future');
let expiry = undefined;
let expiryDatetime = undefined;
const settleId = linear ? quoteId : baseId;
const settle = this.safeCurrencyCode (settleId);
symbol = symbol + ':' + settle;
if (future) {
// we have to do some gymnastics here because bybit
// only provides the day and month regarding the contract expiration
const alias = this.safeString (market, 'alias'); // BTCUSD0930
const aliasDate = alias.slice (-4); // 0930
const aliasMonth = aliasDate.slice (0, 2); // 09
const aliasDay = aliasDate.slice (2, 4); // 30
const dateNow = this.yyyymmdd (this.milliseconds ());
const dateParts = dateNow.split ('-');
const year = this.safeValue (dateParts, 0);
const artificial8601Date = year + '-' + aliasMonth + '-' + aliasDay + 'T00:00:00.000Z';
expiryDatetime = artificial8601Date;
expiry = this.parse8601 (expiryDatetime);
symbol = symbol + '-' + this.yymmdd (expiry);
}
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': false,
'margin': undefined,
'swap': swap,
'future': future,
'option': false,
'active': active,
'contract': true,
'linear': linear,
'inverse': !linear,
'taker': this.safeNumber (market, 'taker_fee'),
'maker': this.safeNumber (market, 'maker_fee'),
'contractSize': undefined, // todo
'expiry': expiry,
'expiryDatetime': expiryDatetime,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': this.safeNumber (lotSizeFilter, 'qty_step'),
'price': this.safeNumber (priceFilter, 'tick_size'),
},
'limits': {
'leverage': {
'min': this.parseNumber ('1'),
'max': this.safeNumber (leverage, 'max_leverage', 1),
},
'amount': {
'min': this.safeNumber (lotSizeFilter, 'min_trading_qty'),
'max': this.safeNumber (lotSizeFilter, 'max_trading_qty'),
},
'price': {
'min': this.safeNumber (priceFilter, 'min_price'),
'max': this.safeNumber (priceFilter, 'max_price'),
},
'cost': {
'min': undefined,
'max': undefined,
},
},
'info': market,
});
}
return result;
}
async fetchUSDCMarkets (params) {
const linearOptionsResponse = await this.publicGetOptionUsdcOpenapiPublicV1Symbols (params);
const usdcLinearPerpetualSwaps = await this.publicGetPerpetualUsdcOpenapiPublicV1Symbols (params);
//
// USDC linear options
// {
// "retCode":0,
// "retMsg":"success",
// "result":{
// "resultTotalSize":424,
// "cursor":"0%2C500",
// "dataList":[
// {
// "symbol":"BTC-24JUN22-300000-C",
// "status":"ONLINE",
// "baseCoin":"BTC",
// "quoteCoin":"USD",
// "settleCoin":"USDC",
// "takerFee":"0.0003",
// "makerFee":"0.0003",
// "minLeverage":"",
// "maxLeverage":"",
// "leverageStep":"",
// "minOrderPrice":"0.5",
// "maxOrderPrice":"10000000",
// "minOrderSize":"0.01",
// "maxOrderSize":"200",
// "tickSize":"0.5",
// "minOrderSizeIncrement":"0.01",
// "basicDeliveryFeeRate":"0.00015",
// "deliveryTime":"1656057600000"
// },
// {
// "symbol":"BTC-24JUN22-300000-P",
// "status":"ONLINE",
// "baseCoin":"BTC",
// "quoteCoin":"USD",
// "settleCoin":"USDC",
// "takerFee":"0.0003",
// "makerFee":"0.0003",
// "minLeverage":"",
// "maxLeverage":"",
// "leverageStep":"",
// "minOrderPrice":"0.5",
// "maxOrderPrice":"10000000",
// "minOrderSize":"0.01",
// "maxOrderSize":"200",
// "tickSize":"0.5",
// "minOrderSizeIncrement":"0.01",
// "basicDeliveryFeeRate":"0.00015",
// "deliveryTime":"1656057600000"
// },
// ]
// }
// }
//
// USDC linear perpetual swaps
//
// {
// "retCode":0,
// "retMsg":"",
// "result":[
// {
// "symbol":"BTCPERP",
// "status":"ONLINE",
// "baseCoin":"BTC",
// "quoteCoin":"USD",
// "takerFeeRate":"0.00075",
// "makerFeeRate":"-0.00025",
// "minLeverage":"1",
// "maxLeverage":"100",
// "leverageStep":"0.01",
// "minPrice":"0.50",
// "maxPrice":"999999.00",
// "tickSize":"0.50",
// "maxTradingQty":"5.000",
// "minTradingQty":"0.001",
// "qtyStep":"0.001",
// "deliveryFeeRate":"",
// "deliveryTime":"0"
// }
// ]
// }
//
const optionsResponse = this.safeValue (linearOptionsResponse, 'result', []);
const options = this.safeValue (optionsResponse, 'dataList', []);
const contractsResponse = this.safeValue (usdcLinearPerpetualSwaps, 'result', []);
const markets = this.arrayConcat (options, contractsResponse);
const result = [];
// all markets fetched here are linear
const linear = true;
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'symbol');
const baseId = this.safeString (market, 'baseCoin');
const quoteId = this.safeString (market, 'quoteCoin');
let settleId = this.safeString (market, 'settleCoin');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
let settle = this.safeCurrencyCode (settleId);
let symbol = base + '/' + quote;
let type = 'swap';
if (settleId !== undefined) {
type = 'option';
}
const swap = (type === 'swap');
const option = (type === 'option');
const leverage = this.safeValue (market, 'leverage_filter', {});
const status = this.safeString (market, 'status');
let active = undefined;
if (status !== undefined) {
active = (status === 'ONLINE');
}
let expiry = undefined;
let expiryDatetime = undefined;
let strike = undefined;
let optionType = undefined;
if (settle === undefined) {
settleId = 'USDC';
settle = 'USDC';
}
symbol = symbol + ':' + settle;
if (option) {
expiry = this.safeInteger (market, 'deliveryTime');
expiryDatetime = this.iso8601 (expiry);
const splitId = id.split ('-');
strike = this.safeString (splitId, 2);
const optionLetter = this.safeString (splitId, 3);
symbol = symbol + '-' + this.yymmdd (expiry) + ':' + strike + ':' + optionLetter;
if (optionLetter === 'P') {
optionType = 'put';
} else if (optionLetter === 'C') {
optionType = 'call';
}
}
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': false,
'margin': undefined,
'swap': swap,
'future': false,
'option': option,
'active': active,
'contract': true,
'linear': linear,
'inverse': !linear,
'taker': this.safeNumber (market, 'taker_fee'),
'maker': this.safeNumber (market, 'maker_fee'),
'contractSize': undefined,
'expiry': expiry,
'expiryDatetime': expiryDatetime,
'strike': strike,
'optionType': optionType,
'precision': {
'amount': this.safeNumber (market, 'minOrderSizeIncrement'),
'price': this.safeNumber (market, 'tickSize'),
},
'limits': {
'leverage': {
'min': this.safeNumber (leverage, 'minLeverage', 1),
'max': this.safeNumber (leverage, 'maxLeverage', 1),
},
'amount': {
'min': this.safeNumber (market, 'minOrderSize'),
'max': this.safeNumber (market, 'maxOrderSize'),
},
'price': {
'min': this.safeNumber (market, 'minOrderPrice'),
'max': this.safeNumber (market, 'maxOrderPrice'),
},
'cost': {
'min': undefined,
'max': undefined,
},
},
'info': market,
});
}
return result;
}
parseTicker (ticker, market = undefined) {
// spot
//
// {
// "time": "1651743420061",
// "symbol": "BTCUSDT",
// "bestBidPrice": "39466.75",
// "bestAskPrice": "39466.83",
// "volume": "4396.082921",
// "quoteVolume": "172664909.03216557",
// "lastPrice": "39466.71",
// "highPrice": "40032.79",
// "lowPrice": "38602.39",
// "openPrice": "39031.53"
// }
//
// linear usdt/ inverse swap and future
// {
// "symbol": "BTCUSDT",
// "bid_price": "39458",
// "ask_price": "39458.5",
// "last_price": "39458.00",
// "last_tick_direction": "ZeroMinusTick",
// "prev_price_24h": "39059.50",
// "price_24h_pcnt": "0.010202",
// "high_price_24h": "40058.50",
// "low_price_24h": "38575.50",
// "prev_price_1h": "39534.00",
// "price_1h_pcnt": "-0.001922",
// "mark_price": "39472.49",
// "index_price": "39469.81",
// "open_interest": "28343.61",
// "open_value": "0.00",
// "total_turnover": "85303326477.54",
// "turnover_24h": "4221589085.06",
// "total_volume": "30628792.45",
// "volume_24h": "107569.75",
// "funding_rate": "0.0001",
// "predicted_funding_rate": "0.0001",
// "next_funding_time": "2022-05-05T16:00:00Z",
// "countdown_hour": "7",
// "delivery_fee_rate": "",
// "predicted_delivery_price": "",
// "delivery_time": ""
// }
//
// usdc option/ swap
// {
// "symbol": "BTC-30SEP22-400000-C",
// "bid": "0",
// "bidIv": "0",
// "bidSize": "0",
// "ask": "15",
// "askIv": "1.1234",
// "askSize": "0.01",
// "lastPrice": "5",
// "openInterest": "0.03",
// "indexPrice": "39458.6",
// "markPrice": "0.51901394",
// "markPriceIv": "0.9047",
// "change24h": "0",
// "high24h": "0",
// "low24h": "0",
// "volume24h": "0",
// "turnover24h": "0",
// "totalVolume": "1",
// "totalTurnover": "4",
// "predictedDeliveryPrice": "0",
// "underlyingPrice": "40129.73",
// "delta": "0.00010589",
// "gamma": "0.00000002",
// "vega": "0.10670892",
// "theta": "-0.03262827"
// }
//
const timestamp = this.safeInteger (ticker, 'time');
const marketId = this.safeString (ticker, 'symbol');
const symbol = this.safeSymbol (marketId, market);
const last = this.safeString2 (ticker, 'last_price', 'lastPrice');
const open = this.safeString2 (ticker, 'prev_price_24h', 'openPrice');
let percentage = this.safeString2 (ticker, 'price_24h_pcnt', 'change24h');
percentage = Precise.stringMul (percentage, '100');
let baseVolume = this.safeString2 (ticker, 'turnover_24h', 'turnover24h');
if (baseVolume === undefined) {
baseVolume = this.safeString (ticker, 'volume');
}
let quoteVolume = this.safeString2 (ticker, 'volume_24h', 'volume24h');
if (quoteVolume === undefined) {
quoteVolume = this.safeString (ticker, 'quoteVolume');
}
let bid = this.safeString2 (ticker, 'bid_price', 'bid');
if (bid === undefined) {
bid = this.safeString (ticker, 'bestBidPrice');
}
let ask = this.safeString2 (ticker, 'ask_price', 'ask');
if (ask === undefined) {
ask = this.safeString (ticker, 'bestAskPrice');
}
let high = this.safeString2 (ticker, 'high_price_24h', 'high24h');
if (high === undefined) {
high = this.safeString (ticker, 'highPrice');
}
let low = this.safeString2 (ticker, 'low_price_24h', 'low24h');
if (low === undefined) {
low = this.safeString (ticker, 'lowPrice');
}
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': high,
'low': low,
'bid': bid,
'bidVolume': this.safeString (ticker, 'bidSize'),
'ask': ask,
'askVolume': this.safeString (ticker, 'askSize'),
'vwap': undefined,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': percentage,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, false);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let method = undefined;
const isUsdcSettled = market['settle'] === 'USDC';
if (market['spot']) {
method = 'publicGetSpotQuoteV1Ticker24hr';
} else if (!isUsdcSettled) {
// inverse perpetual // usdt linear // inverse futures
method = 'publicGetV2PublicTickers';
} else if (market['option']) {
// usdc option
method = 'publicGetOptionUsdcOpenapiPublicV1Tick';
} else {
// usdc swap
method = 'publicGetPerpetualUsdcOpenapiPublicV1Tick';
}
const request = {
'symbol': market['id'],
};
const response = await this[method] (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// symbol: 'BTCUSD',
// bid_price: '7680',
// ask_price: '7680.5',
// last_price: '7680.00',
// last_tick_direction: 'MinusTick',
// prev_price_24h: '7870.50',
// price_24h_pcnt: '-0.024204',
// high_price_24h: '8035.00',
// low_price_24h: '7671.00',
// prev_price_1h: '7780.00',
// price_1h_pcnt: '-0.012853',
// mark_price: '7683.27',
// index_price: '7682.74',
// open_interest: 188829147,
// open_value: '23670.06',
// total_turnover: '25744224.90',
// turnover_24h: '102997.83',
// total_volume: 225448878806,
// volume_24h: 809919408,
// funding_rate: '0.0001',
// predicted_funding_rate: '0.0001',
// next_funding_time: '2020-03-12T00:00:00Z',
// countdown_hour: 7
// }
// ],
// time_now: '1583948195.818255'
// }
// usdc ticker
// {
// "retCode": 0,
// "retMsg": "SUCCESS",
// "result": {
// "symbol": "BTC-28JAN22-250000-C",
// "bid": "0",
// "bidIv": "0",
// "bidSize": "0",
// "ask": "0",
// "askIv": "0",
// "askSize": "0",
// "lastPrice": "0",
// "openInterest": "0",
// "indexPrice": "56171.79000000",
// "markPrice": "12.72021285",
// "markPriceIv": "1.1701",
// "change24h": "0",
// "high24h": "0",
// "low24h": "0",
// "volume24h": "0",
// "turnover24h": "0",
// "totalVolume": "0",
// "totalTurnover": "0",
// "predictedDeliveryPrice": "0",
// "underlyingPrice": "57039.61000000",
// "delta": "0.00184380",
// "gamma": "0.00000022",
// "vega": "1.35132531",
// "theta": "-1.33819821"
// }
// }
//
const result = this.safeValue (response, 'result', []);
let rawTicker = undefined;
if (Array.isArray (result)) {
rawTicker = this.safeValue (result, 0);
} else {
rawTicker = result;
}
const ticker = this.parseTicker (rawTicker, market);
return ticker;
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let type = undefined;
let market = undefined;
let isUsdcSettled = undefined;
if (symbols !== undefined) {
const symbol = this.safeValue (symbols, 0);
market = this.market (symbol);
type = market['type'];
isUsdcSettled = market['settle'] === 'USDC';
} else {
[ type, params ] = this.handleMarketTypeAndParams ('fetchTickers', market, params);
if (type !== 'spot') {
let defaultSettle = this.safeString (this.options, 'defaultSettle', 'USDT');
defaultSettle = this.safeString2 (params, 'settle', 'defaultSettle', isUsdcSettled);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = defaultSettle === 'USDC';
}
}
let method = undefined;
if (type === 'spot') {
method = 'publicGetSpotQuoteV1Ticker24hr';
} else if (!isUsdcSettled) {
// inverse perpetual // usdt linear // inverse futures
method = 'publicGetV2PublicTickers';
} else {
throw new NotSupported (this.id + ' fetchTickers() is not supported for USDC markets');
}
const response = await this[method] (params);
const result = this.safeValue (response, 'result', []);
const tickers = {};
for (let i = 0; i < result.length; i++) {
const ticker = this.parseTicker (result[i]);
const symbol = ticker['symbol'];
tickers[symbol] = ticker;
}
return this.filterByArray (tickers, 'symbol', symbols);
}
parseOHLCV (ohlcv, market = undefined) {
//
// inverse perpetual BTC/USD
//
// {
// symbol: 'BTCUSD',
// interval: '1',
// open_time: 1583952540,
// open: '7760.5',
// high: '7764',
// low: '7757',
// close: '7763.5',
// volume: '1259766',
// turnover: '162.32773718999994'
// }
//
// linear perpetual BTC/USDT
//
// {
// "id":143536,
// "symbol":"BTCUSDT",
// "period":"15",
// "start_at":1587883500,
// "volume":1.035,
// "open":7540.5,
// "high":7541,
// "low":7540.5,
// "close":7541
// }
//
// usdc perpetual
// {
// "symbol":"BTCPERP",
// "volume":"0.01",
// "period":"1",
// "openTime":"1636358160",
// "open":"66001.50",
// "high":"66001.50",
// "low":"66001.50",
// "close":"66001.50",
// "turnover":"1188.02"
// }
//
// spot
// [
// 1651837620000, // start tame
// "35831.5", // open
// "35831.5", // high
// "35801.93", // low
// "35817.11", // close
// "1.23453", // volume
// 0, // end time
// "44213.97591627", // quote asset volume
// 24, // number of trades
// "0", // taker base volume
// "0" // taker quote volume
// ]
//
if (Array.isArray (ohlcv)) {
return [
this.safeNumber (ohlcv, 0),
this.safeNumber (ohlcv, 1),
this.safeNumber (ohlcv, 2),
this.safeNumber (ohlcv, 3),
this.safeNumber (ohlcv, 4),
this.safeNumber (ohlcv, 5),
];
}
let timestamp = this.safeTimestamp2 (ohlcv, 'open_time', 'openTime');
if (timestamp === undefined) {
timestamp = this.safeTimestamp (ohlcv, 'start_at');
}
return [
timestamp,
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'high'),
this.safeNumber (ohlcv, 'low'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber2 (ohlcv, 'volume', 'turnover'),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const price = this.safeString (params, 'price');
params = this.omit (params, 'price');
const request = {
'symbol': market['id'],
};
const duration = this.parseTimeframe (timeframe);
const now = this.seconds ();
let sinceTimestamp = undefined;
if (since === undefined) {
if (limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOHLCV() requires a since argument or a limit argument');
} else {
sinceTimestamp = now - limit * duration;
}
} else {
sinceTimestamp = parseInt (since / 1000);
}
if (limit !== undefined) {
request['limit'] = limit; // max 200, default 200
}
let method = undefined;
let intervalKey = 'interval';
let sinceKey = 'from';
const isUsdcSettled = market['settle'] === 'USDC';
if (market['spot']) {
method = 'publicGetSpotQuoteV1Kline';
} else if (market['contract'] && !isUsdcSettled) {
if (market['linear']) {
// linear swaps/futures
const methods = {
'mark': 'publicGetPublicLinearMarkPriceKline',
'index': 'publicGetPublicLinearIndexPriceKline',
'premium': 'publicGetPublicLinearPremiumIndexKline',
};
method = this.safeValue (methods, price, 'publicGetPublicLinearKline');
} else {
// inverse swaps/ futures
const methods = {
'mark': 'publicGetV2PublicMarkPriceKline',
'index': 'publicGetV2PublicIndexPriceKline',
'premium': 'publicGetV2PublicPremiumPriceKline',
};
method = this.safeValue (methods, price, 'publicGetV2PublicKlineList');
}
} else {
// usdc markets
if (market['option']) {
throw new NotSupported (this.id + ' fetchOHLCV() is not supported for USDC options markets');
}
intervalKey = 'period';
sinceKey = 'startTime';
const methods = {
'mark': 'publicGetPerpetualUsdcOpenapiPublicV1MarkPriceKline',
'index': 'publicGetPerpetualUsdcOpenapiPublicV1IndexPriceKline',
'premium': 'publicGetPerpetualUsdcOpenapiPublicV1PremiumPriceKline',
};
method = this.safeValue (methods, price, 'publicGetPerpetualUsdcOpenapiPublicV1KlineList');
}
// spot markets use the same interval format as ccxt
// so we don't need to convert it
request[intervalKey] = market['spot'] ? timeframe : this.timeframes[timeframe];
request[sinceKey] = sinceTimestamp;
const response = await this[method] (this.extend (request, params));
//
// inverse perpetual BTC/USD
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// symbol: 'BTCUSD',
// interval: '1',
// open_time: 1583952540,
// open: '7760.5',
// high: '7764',
// low: '7757',
// close: '7763.5',
// volume: '1259766',
// turnover: '162.32773718999994'
// },
// ],
// time_now: '1583953082.397330'
// }
//
// linear perpetual BTC/USDT
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// {
// "id":143536,
// "symbol":"BTCUSDT",
// "period":"15",
// "start_at":1587883500,
// "volume":1.035,
// "open":7540.5,
// "high":7541,
// "low":7540.5,
// "close":7541
// }
// ],
// "time_now":"1587884120.168077"
// }
// spot
// {
// "ret_code": "0",
// "ret_msg": null,
// "result": [
// [
// 1651837620000,
// "35831.5",
// "35831.5",
// "35801.93",
// "35817.11",
// "1.23453",
// 0,
// "44213.97591627",
// 24,
// "0",
// "0"
// ]
// ],
// "ext_code": null,
// "ext_info": null
// }
//
const result = this.safeValue (response, 'result', {});
return this.parseOHLCVs (result, market, timeframe, since, limit);
}
async fetchFundingRate (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const method = market['linear'] ? 'publicLinearGetFundingPrevFundingRate' : 'v2PublicGetFundingPrevFundingRate';
// TODO const method = market['linear'] ? 'publicGetPublicLinearFundingPrevFundingRate' : 'publicGetV2PublicFundingRate ???? throws ExchangeError';
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "symbol":"BTCUSDT",
// "funding_rate":0.00006418,
// "funding_rate_timestamp":"2022-03-11T16:00:00.000Z"
// },
// "time_now":"1647040818.724895"
// }
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "symbol":"BTCUSD",
// "funding_rate":"0.00009536",
// "funding_rate_timestamp":1647014400
// },
// "time_now":"1647040852.515724"
// }
//
const result = this.safeValue (response, 'result');
const fundingRate = this.safeNumber (result, 'funding_rate');
let fundingTimestamp = this.parse8601 (this.safeString (result, 'funding_rate_timestamp'));
fundingTimestamp = this.safeTimestamp (result, 'funding_rate_timestamp', fundingTimestamp);
const currentTime = this.milliseconds ();
return {
'info': result,
'symbol': symbol,
'markPrice': undefined,
'indexPrice': undefined,
'interestRate': undefined,
'estimatedSettlePrice': undefined,
'timestamp': currentTime,
'datetime': this.iso8601 (currentTime),
'fundingRate': fundingRate,
'fundingTimestamp': fundingTimestamp,
'fundingDatetime': this.iso8601 (fundingTimestamp),
'nextFundingRate': undefined,
'nextFundingTimestamp': undefined,
'nextFundingDatetime': undefined,
'previousFundingRate': undefined,
'previousFundingTimestamp': undefined,
'previousFundingDatetime': undefined,
};
}
async fetchIndexOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
if (since === undefined && limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchIndexOHLCV() requires a since argument or a limit argument');
}
const request = {
'price': 'index',
};
return await this.fetchOHLCV (symbol, timeframe, since, limit, this.extend (request, params));
}
async fetchMarkOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
if (since === undefined && limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMarkOHLCV() requires a since argument or a limit argument');
}
const request = {
'price': 'mark',
};
return await this.fetchOHLCV (symbol, timeframe, since, limit, this.extend (request, params));
}
async fetchPremiumIndexOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
if (since === undefined && limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchPremiumIndexOHLCV() requires a since argument or a limit argument');
}
const request = {
'price': 'premiumIndex',
};
return await this.fetchOHLCV (symbol, timeframe, since, limit, this.extend (request, params));
}
parseTrade (trade, market = undefined) {
//
// public spot
//
// {
// "price": "39548.68",
// "time": "1651748717850",
// "qty": "0.166872",
// "isBuyerMaker": true
// }
//
// public linear/inverse swap/future
//
// {
// "id": "112348766532",
// "symbol": "BTCUSDT",
// "price": "39536",
// "qty": "0.011",
// "side": "Buy",
// "time": "2022-05-05T11:16:02.000Z",
// "trade_time_ms": "1651749362196"
// }
//
// public usdc market
//
// {
// "symbol": "BTC-30SEP22-400000-C",
// "orderQty": "0.010",
// "orderPrice": "5.00",
// "time": "1651104300208"
// }
//
// private futures/swap
//
// {
// "order_id": "b020b4bc-6fe2-45b5-adbc-dd07794f9746",
// "order_link_id": "",
// "side": "Buy",
// "symbol": "AAVEUSDT",
// "exec_id": "09abe8f0-aea6-514e-942b-7da8cb935120",
// "price": "269.3",
// "order_price": "269.3",
// "order_qty": "0.1",
// "order_type": "Market",
// "fee_rate": "0.00075",
// "exec_price": "256.35",
// "exec_type": "Trade",
// "exec_qty": "0.1",
// "exec_fee": "0.01922625",
// "exec_value": "25.635",
// "leaves_qty": "0",
// "closed_size": "0",
// "last_liquidity_ind": "RemovedLiquidity",
// "trade_time": "1638276374",
// "trade_time_ms": "1638276374312"
// }
//
// spot
// {
// "id": "1149467000412631552",
// "symbol": "LTCUSDT",
// "symbolName": "LTCUSDT",
// "orderId": "1149467000244912384",
// "ticketId": "2200000000002601358",
// "matchOrderId": "1149465793552007078",
// "price": "100.19",
// "qty": "0.09973",
// "commission": "0.0099919487",
// "commissionAsset": "USDT",
// "time": "1651763144465",
// "isBuyer": false,
// "isMaker": false,
// "fee": {
// "feeTokenId": "USDT",
// "feeTokenName": "USDT",
// "fee": "0.0099919487"
// },
// "feeTokenId": "USDT",
// "feeAmount": "0.0099919487",
// "makerRebate": "0"
// }
//
const id = this.safeString2 (trade, 'id', 'exec_id');
const marketId = this.safeString (trade, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let amountString = this.safeString2 (trade, 'qty', 'exec_qty');
if (amountString === undefined) {
amountString = this.safeString (trade, 'orderQty');
}
let priceString = this.safeString2 (trade, 'exec_price', 'price');
if (priceString === undefined) {
priceString = this.safeString (trade, 'orderPrice');
}
const costString = this.safeString (trade, 'exec_value');
let timestamp = this.parse8601 (this.safeString (trade, 'time'));
if (timestamp === undefined) {
timestamp = this.safeNumber2 (trade, 'trade_time_ms', 'time');
}
let side = this.safeStringLower (trade, 'side');
if (side === undefined) {
const isBuyer = this.safeValue (trade, 'isBuyer');
if (isBuyer !== undefined) {
side = isBuyer ? 'buy' : 'sell';
}
}
const isMaker = this.safeValue (trade, 'isMaker');
let takerOrMaker = undefined;
if (isMaker !== undefined) {
takerOrMaker = isMaker ? 'maker' : 'taker';
} else {
const lastLiquidityInd = this.safeString (trade, 'last_liquidity_ind');
takerOrMaker = (lastLiquidityInd === 'AddedLiquidity') ? 'maker' : 'taker';
}
const feeCostString = this.safeString (trade, 'exec_fee');
let fee = undefined;
if (feeCostString !== undefined) {
const feeCurrencyCode = market['inverse'] ? market['base'] : market['quote'];
fee = {
'cost': feeCostString,
'currency': feeCurrencyCode,
'rate': this.safeString (trade, 'fee_rate'),
};
}
return this.safeTrade ({
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'order': this.safeString2 (trade, 'order_id', 'orderId'),
'type': this.safeStringLower (trade, 'order_type'),
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': costString,
'fee': fee,
}, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let method = undefined;
const request = {
'symbol': market['id'],
};
const isUsdcSettled = market['settle'] === 'USDC';
if (market['type'] === 'spot') {
method = 'publicGetSpotQuoteV1Trades';
} else if (!isUsdcSettled) {
// inverse perpetual // usdt linear // inverse futures
method = market['linear'] ? 'publicGetPublicLinearRecentTradingRecords' : 'publicGetV2PublicTradingRecords';
} else {
// usdc option/ swap
method = 'publicGetOptionUsdcOpenapiPublicV1QueryTradeLatest';
request['category'] = market['option'] ? 'OPTION' : 'PERPETUAL';
}
if (limit !== undefined) {
request['limit'] = limit; // default 500, max 1000
}
const response = await this[method] (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// id: 43785688,
// symbol: 'BTCUSD',
// price: 7786,
// qty: 67,
// side: 'Sell',
// time: '2020-03-11T19:18:30.123Z'
// },
// ],
// time_now: '1583954313.393362'
// }
//
// usdc trades
// {
// "retCode": 0,
// "retMsg": "Success.",
// "result": {
// "resultTotalSize": 2,
// "cursor": "",
// "dataList": [
// {
// "id": "3caaa0ca",
// "symbol": "BTCPERP",
// "orderPrice": "58445.00",
// "orderQty": "0.010",
// "side": "Buy",
// "time": "1638275679673"
// }
// ]
// }
// }
//
let trades = this.safeValue (response, 'result', {});
if (!Array.isArray (trades)) {
trades = this.safeValue (trades, 'dataList', []);
}
return this.parseTrades (trades, market, since, limit);
}
parseOrderBook (orderbook, symbol, timestamp = undefined, bidsKey = 'Buy', asksKey = 'Sell', priceKey = 'price', amountKey = 'size') {
const bids = [];
const asks = [];
for (let i = 0; i < orderbook.length; i++) {
const bidask = orderbook[i];
const side = this.safeString (bidask, 'side');
if (side === 'Buy') {
bids.push (this.parseBidAsk (bidask, priceKey, amountKey));
} else if (side === 'Sell') {
asks.push (this.parseBidAsk (bidask, priceKey, amountKey));
} else {
throw new ExchangeError (this.id + ' parseOrderBook() encountered an unrecognized bidask format: ' + this.json (bidask));
}
}
return {
'symbol': symbol,
'bids': this.sortBy (bids, 0, true),
'asks': this.sortBy (asks, 0),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'nonce': undefined,
};
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const response = await this.publicGetV2PublicOrderBookL2 (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// { symbol: 'BTCUSD', price: '7767.5', size: 677956, side: 'Buy' },
// { symbol: 'BTCUSD', price: '7767', size: 580690, side: 'Buy' },
// { symbol: 'BTCUSD', price: '7766.5', size: 475252, side: 'Buy' },
// { symbol: 'BTCUSD', price: '7768', size: 330847, side: 'Sell' },
// { symbol: 'BTCUSD', price: '7768.5', size: 97159, side: 'Sell' },
// { symbol: 'BTCUSD', price: '7769', size: 6508, side: 'Sell' },
// ],
// time_now: '1583954829.874823'
// }
//
const result = this.safeValue (response, 'result', []);
const timestamp = this.safeTimestamp (response, 'time_now');
return this.parseOrderBook (result, symbol, timestamp, 'Buy', 'Sell', 'price', 'size');
}
parseBalance (response) {
//
// spot balance
// {
// "ret_code": "0",
// "ret_msg": "",
// "ext_code": null,
// "ext_info": null,
// "result": {
// "balances": [
// {
// "coin": "LTC",
// "coinId": "LTC",
// "coinName": "LTC",
// "total": "0.00000783",
// "free": "0.00000783",
// "locked": "0"
// }
// ]
// }
// }
//
// linear/inverse swap/futures
// {
// "ret_code": "0",
// "ret_msg": "OK",
// "ext_code": "",
// "ext_info": "",
// "result": {
// "ADA": {
// "equity": "0",
// "available_balance": "0",
// "used_margin": "0",
// "order_margin": "0",
// "position_margin": "0",
// "occ_closing_fee": "0",
// "occ_funding_fee": "0",
// "wallet_balance": "0",
// "realised_pnl": "0",
// "unrealised_pnl": "0",
// "cum_realised_pnl": "0",
// "given_cash": "0",
// "service_cash": "0"
// },
// },
// "time_now": "1651772170.050566",
// "rate_limit_status": "119",
// "rate_limit_reset_ms": "1651772170042",
// "rate_limit": "120"
// }
//
// usdc wallet
// {
// "result": {
// "walletBalance": "10.0000",
// "accountMM": "0.0000",
// "bonus": "0.0000",
// "accountIM": "0.0000",
// "totalSessionRPL": "0.0000",
// "equity": "10.0000",
// "totalRPL": "0.0000",
// "marginBalance": "10.0000",
// "availableBalance": "10.0000",
// "totalSessionUPL": "0.0000"
// },
// "retCode": "0",
// "retMsg": "Success."
// }
//
const result = {
'info': response,
};
const data = this.safeValue (response, 'result', {});
const balances = this.safeValue (data, 'balances');
if (Array.isArray (balances)) {
// spot balances
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
const currencyId = this.safeString (balance, 'coin');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (balance, 'availableBalance');
account['used'] = this.safeString (balance, 'locked');
account['total'] = this.safeString (balance, 'total');
result[code] = account;
}
} else {
if ('walletBalance' in data) {
// usdc wallet
const code = 'USDC';
const account = this.account ();
account['free'] = this.safeString (data, 'availableBalance');
account['total'] = this.safeString (data, 'walletBalance');
result[code] = account;
} else {
// linear/inverse swap/futures
const currencyIds = Object.keys (data);
for (let i = 0; i < currencyIds.length; i++) {
const currencyId = currencyIds[i];
const balance = data[currencyId];
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (balance, 'available_balance');
account['total'] = this.safeString (balance, 'wallet_balance');
result[code] = account;
}
}
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
const request = {};
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchBalance', undefined, params);
let method = undefined;
if (type === 'spot') {
method = 'privateGetSpotV1Account';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
let isUsdcSettled = settle === 'USDC';
isUsdcSettled = true;
if (!isUsdcSettled) {
// linear/inverse future/swap
method = 'privateGetV2PrivateWalletBalance';
const coin = this.safeString2 (params, 'coin', 'code');
params = this.omit (params, [ 'coin', 'code' ]);
if (coin !== undefined) {
const currency = this.currency (coin);
request['coin'] = currency['id'];
}
} else {
// usdc account
method = 'privatePostOptionUsdcOpenapiPrivateV1QueryWalletBalance';
}
}
await this.loadMarkets ();
const response = await this[method] (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: {
// BTC: {
// equity: 0,
// available_balance: 0,
// used_margin: 0,
// order_margin: 0,
// position_margin: 0,
// occ_closing_fee: 0,
// occ_funding_fee: 0,
// wallet_balance: 0,
// realised_pnl: 0,
// unrealised_pnl: 0,
// cum_realised_pnl: 0,
// given_cash: 0,
// service_cash: 0
// }
// },
// time_now: '1583937810.370020',
// rate_limit_status: 119,
// rate_limit_reset_ms: 1583937810367,
// rate_limit: 120
// }
//
return this.parseBalance (response);
}
parseOrderStatus (status) {
const statuses = {
// basic orders
'created': 'open',
'rejected': 'rejected', // order is triggered but failed upon being placed
'new': 'open',
'partiallyfilled': 'open',
'filled': 'closed',
'cancelled': 'canceled',
'pendingcancel': 'canceling', // the engine has received the cancellation but there is no guarantee that it will be successful
// conditional orders
'active': 'open', // order is triggered and placed successfully
'untriggered': 'open', // order waits to be triggered
'triggered': 'closed', // order is triggered
// 'Cancelled': 'canceled', // order is cancelled
// 'Rejected': 'rejected', // order is triggered but fail to be placed
'deactivated': 'canceled', // conditional order was cancelled before triggering
};
return this.safeString (statuses, status, status);
}
parseTimeInForce (timeInForce) {
const timeInForces = {
'GoodTillCancel': 'GTC',
'ImmediateOrCancel': 'IOC',
'FillOrKill': 'FOK',
'PostOnly': 'PO',
};
return this.safeString (timeInForces, timeInForce, timeInForce);
}
parseOrder (order, market = undefined) {
//
// createOrder
//
// {
// "user_id": 1,
// "order_id": "335fd977-e5a5-4781-b6d0-c772d5bfb95b",
// "symbol": "BTCUSD",
// "side": "Buy",
// "order_type": "Limit",
// "price": 8800,
// "qty": 1,
// "time_in_force": "GoodTillCancel",
// "order_status": "Created",
// "last_exec_time": 0,
// "last_exec_price": 0,
// "leaves_qty": 1,
// "cum_exec_qty": 0, // in contracts, where 1 contract = 1 quote currency unit (USD for inverse contracts)
// "cum_exec_value": 0, // in contract's underlying currency (BTC for inverse contracts)
// "cum_exec_fee": 0,
// "reject_reason": "",
// "order_link_id": "",
// "created_at": "2019-11-30T11:03:43.452Z",
// "updated_at": "2019-11-30T11:03:43.455Z"
// }
//
// fetchOrder
//
// {
// "user_id" : 599946,
// "symbol" : "BTCUSD",
// "side" : "Buy",
// "order_type" : "Limit",
// "price" : "7948",
// "qty" : 10,
// "time_in_force" : "GoodTillCancel",
// "order_status" : "Filled",
// "ext_fields" : {
// "o_req_num" : -1600687220498,
// "xreq_type" : "x_create"
// },
// "last_exec_time" : "1588150113.968422",
// "last_exec_price" : "7948",
// "leaves_qty" : 0,
// "leaves_value" : "0",
// "cum_exec_qty" : 10,
// "cum_exec_value" : "0.00125817",
// "cum_exec_fee" : "-0.00000031",
// "reject_reason" : "",
// "cancel_type" : "",
// "order_link_id" : "",
// "created_at" : "2020-04-29T08:45:24.399146Z",
// "updated_at" : "2020-04-29T08:48:33.968422Z",
// "order_id" : "dd2504b9-0157-406a-99e1-efa522373944"
// }
//
// fetchOrders linear swaps
//
// {
// "order_id":"7917bd70-e7c3-4af5-8147-3285cd99c509",
// "user_id":22919890,
// "symbol":"GMTUSDT",
// "side":"Buy",
// "order_type":"Limit",
// "price":2.9262,
// "qty":50,
// "time_in_force":"GoodTillCancel",
// "order_status":"Filled",
// "last_exec_price":2.9219,
// "cum_exec_qty":50,
// "cum_exec_value":146.095,
// "cum_exec_fee":0.087657,
// "reduce_only":false,
// "close_on_trigger":false,
// "order_link_id":"",
// "created_time":"2022-04-18T17:09:54Z",
// "updated_time":"2022-04-18T17:09:54Z",
// "take_profit":0,
// "stop_loss":0,
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN"
// }
//
// conditional order
//
// {
// "user_id":"24478789",
// "stop_order_id":"68e996af-fa55-4ca1-830e-4bf68ffbff3e",
// "symbol":"LTCUSDT",
// "side":"Buy",
// "order_type":"Limit",
// "price":"86",
// "qty":"0.1",
// "time_in_force":"GoodTillCancel",
// "order_status":"Filled",
// "trigger_price":"86",
// "order_link_id":"",
// "created_time":"2022-05-09T14:36:36Z",
// "updated_time":"2022-05-09T14:39:25Z",
// "take_profit":"0",
// "stop_loss":"0",
// "trigger_by":"LastPrice",
// "base_price":"86.96",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN",
// "reduce_only":false,
// "close_on_trigger":false
// }
// future
// {
// "user_id":24478789,
// "position_idx":0,
// "order_status":"Filled",
// "symbol":"ETHUSDM22",
// "side":"Buy",
// "order_type":"Market",
// "price":"2523.35",
// "qty":"10",
// "time_in_force":"ImmediateOrCancel",
// "order_link_id":"",
// "order_id":"54feb0e2-ece7-484f-b870-47910609b5ac",
// "created_at":"2022-05-09T14:46:42.346Z",
// "updated_at":"2022-05-09T14:46:42.350Z",
// "leaves_qty":"0",
// "leaves_value":"0",
// "cum_exec_qty":"10",
// "cum_exec_value":"0.00416111",
// "cum_exec_fee":"0.0000025",
// "reject_reason":"EC_NoError",
// "take_profit":"0.0000",
// "stop_loss":"0.0000",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN"
// }
//
// fetchOpenOrder spot
// {
// "accountId":"24478790",
// "exchangeId":"301",
// "symbol":"LTCUSDT",
// "symbolName":"LTCUSDT",
// "orderLinkId":"1652115972506",
// "orderId":"1152426740986003968",
// "price":"50",
// "origQty":"0.2",
// "executedQty":"0",
// "cummulativeQuoteQty":"0",
// "avgPrice":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY",
// "stopPrice":"0.0",
// "icebergQty":"0.0",
// "time":"1652115973053",
// "updateTime":"1652115973063",
// "isWorking":true
// }
//
// create order usdc
// {
// "orderId":"34450a59-325e-4296-8af0-63c7c524ae33",
// "orderLinkId":"",
// "mmp":false,
// "symbol":"BTCPERP",
// "orderType":"Limit",
// "side":"Buy",
// "orderQty":"0.00100000",
// "orderPrice":"20000.00",
// "iv":"0",
// "timeInForce":"GoodTillCancel",
// "orderStatus":"Created",
// "createdAt":"1652261746007873",
// "basePrice":"0.00",
// "triggerPrice":"0.00",
// "takeProfit":"0.00",
// "stopLoss":"0.00",
// "slTriggerBy":"UNKNOWN",
// "tpTriggerBy":"UNKNOWN"
// }
//
const marketId = this.safeString (order, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let feeCurrency = undefined;
let timestamp = this.parse8601 (this.safeString2 (order, 'created_at', 'created_time'));
if (timestamp === undefined) {
timestamp = this.safeNumber2 (order, 'time', 'transactTime');
if (timestamp === undefined) {
timestamp = this.safeIntegerProduct (order, 'createdAt', 0.001);
}
}
const id = this.safeStringN (order, [ 'order_id', 'stop_order_id', 'orderId' ]);
const type = this.safeStringLowerN (order, [ 'order_type', 'type', 'orderType' ]);
const price = this.safeString2 (order, 'price', 'orderPrice');
const average = this.safeString2 (order, 'average_price', 'avgPrice');
const amount = this.safeStringN (order, [ 'qty', 'origQty', 'orderQty' ]);
const cost = this.safeString (order, 'cum_exec_value');
const filled = this.safeString2 (order, 'cum_exec_qty', 'executedQty');
const remaining = this.safeString (order, 'leaves_qty');
const marketTypes = this.safeValue (this.options, 'marketTypes', {});
const marketType = this.safeString (marketTypes, symbol);
if (marketType === 'linear') {
feeCurrency = market['quote'];
} else {
feeCurrency = market['base'];
}
let lastTradeTimestamp = this.safeTimestamp (order, 'last_exec_time');
if (lastTradeTimestamp === 0) {
lastTradeTimestamp = undefined;
} else if (lastTradeTimestamp === undefined) {
lastTradeTimestamp = this.parse8601 (this.safeString2 (order, 'updated_time', 'updated_at'));
if (lastTradeTimestamp === undefined) {
lastTradeTimestamp = this.safeNumber (order, 'updateTime');
}
}
const raw_status = this.safeStringLowerN (order, [ 'order_status', 'stop_order_status', 'status', 'orderStatus' ]);
const status = this.parseOrderStatus (raw_status);
const side = this.safeStringLower (order, 'side');
const feeCostString = this.safeString (order, 'cum_exec_fee');
let fee = undefined;
if (feeCostString !== undefined) {
fee = {
'cost': feeCostString,
'currency': feeCurrency,
};
}
let clientOrderId = this.safeString2 (order, 'order_link_id', 'orderLinkId');
if ((clientOrderId !== undefined) && (clientOrderId.length < 1)) {
clientOrderId = undefined;
}
const timeInForce = this.parseTimeInForce (this.safeString2 (order, 'time_in_force', 'timeInForce'));
const stopPrice = this.safeStringN (order, [ 'trigger_price', 'stop_px', 'stopPrice', 'triggerPrice' ]);
const postOnly = (timeInForce === 'PO');
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': type,
'timeInForce': timeInForce,
'postOnly': postOnly,
'side': side,
'price': price,
'stopPrice': stopPrice,
'amount': amount,
'cost': cost,
'average': average,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
'trades': undefined,
}, market);
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchOrder', market, params);
if (type !== 'spot' && symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrder() requires a symbol argument for ' + type + ' markets');
}
if (type === 'spot') {
// only spot markets have a dedicated endpoint for fetching a order
const request = {
'orderId': id,
};
const response = await this.privateGetSpotV1Order (this.extend (params, request));
const result = this.safeValue (response, 'result', {});
return this.parseOrder (result);
}
const isUsdcSettled = (market['settle'] === 'USDC');
const orderKey = isUsdcSettled ? 'orderId' : 'order_id';
params[orderKey] = id;
if (isUsdcSettled || market['future'] || market['inverse']) {
return this.fetchOpenOrders (symbol, undefined, undefined, params);
} else {
// only linear swap markets allow using all purpose
// fetchOrders endpoint filtering by id
return this.fetchOrders (symbol, undefined, undefined, params);
}
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
symbol = market['symbol'];
amount = this.amountToPrecision (symbol, amount);
price = (price !== undefined) ? this.priceToPrecision (symbol, price) : undefined;
const isUsdcSettled = (market['settle'] === 'USDC');
if (market['spot']) {
return await this.createSpotOrder (symbol, type, side, amount, price, params);
} else if (isUsdcSettled) {
return await this.createUsdcOrder (symbol, type, side, amount, price, params);
} else {
return await this.createContractOrder (symbol, type, side, amount, price, params);
}
}
async createSpotOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (type === 'market' && side === 'buy') {
// for market buy it requires the amount of quote currency to spend
if (this.options['createMarketBuyOrderRequiresPrice']) {
const cost = this.safeNumber (params, 'cost');
params = this.omit (params, 'cost');
if (price === undefined && cost === undefined) {
throw new InvalidOrder (this.id + " createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = false to supply the cost in the amount argument (the exchange-specific behaviour)");
} else {
amount = (cost !== undefined) ? cost : amount * price;
}
}
}
const request = {
'symbol': market['id'],
'side': this.capitalize (side),
'type': type.toUpperCase (), // limit, market or limit_maker
'timeInForce': 'GTC', // FOK, IOC
'qty': amount,
};
if (type === 'limit' || type === 'limit_maker') {
if (price === undefined) {
throw new InvalidOrder (this.id + ' createOrder requires a price argument for a ' + type + ' order');
}
request['price'] = price;
}
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'orderLinkId');
if (clientOrderId !== undefined) {
request['orderLinkId'] = clientOrderId;
}
params = this.omit (params, [ 'clientOrderId', 'orderLinkId' ]);
const response = await this.privatePostSpotV1Order (this.extend (request, params));
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":{
// "accountId":"24478790",
// "symbol":"ETHUSDT",
// "symbolName":"ETHUSDT",
// "orderLinkId":"1652266305358517",
// "orderId":"1153687819821127168",
// "transactTime":"1652266305365",
// "price":"80",
// "origQty":"0.05",
// "executedQty":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY"
// }
// }
const order = this.safeValue (response, 'result', {});
return this.parseOrder (order);
}
async createUsdcOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (type === 'market') {
throw NotSupported (this.id + 'createOrder does not allow market orders for ' + symbol + ' markets');
}
if (price === undefined && type === 'limit') {
throw new ArgumentsRequired (this.id + ' createOrder requires a price argument for limit orders');
}
const request = {
'symbol': market['id'],
'side': this.capitalize (side),
'orderType': this.capitalize (type), // limit
'timeInForce': 'GoodTillCancel', // ImmediateOrCancel, FillOrKill, PostOnly
'orderQty': amount,
};
if (price !== undefined) {
request['orderPrice'] = price;
}
if (market['swap']) {
const stopPx = this.safeValue2 (params, 'stopPrice', 'triggerPrice');
params = this.omit (params, [ 'stopPrice', 'triggerPrice' ]);
if (stopPx !== undefined) {
const basePrice = this.safeValue (params, 'basePrice');
if (basePrice === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder() requires both the triggerPrice and basePrice params for a conditional ' + type + ' order');
}
request['orderFilter'] = 'StopOrder';
request['triggerPrice'] = this.priceToPrecision (symbol, stopPx);
} else {
request['orderFilter'] = 'Order';
}
}
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'orderLinkId');
if (clientOrderId !== undefined) {
request['orderLinkId'] = clientOrderId;
} else if (market['option']) {
// mandatory field for options
request['orderLinkId'] = this.uuid16 ();
}
params = this.omit (params, [ 'clientOrderId', 'orderLinkId' ]);
const method = market['option'] ? 'privatePostOptionUsdcOpenapiPrivateV1PlaceOrder' : 'privatePostPerpetualUsdcOpenapiPrivateV1PlaceOrder';
const response = await this[method] (this.extend (request, params));
//
// {
// "retCode":0,
// "retMsg":"",
// "result":{
// "orderId":"34450a59-325e-4296-8af0-63c7c524ae33",
// "orderLinkId":"",
// "mmp":false,
// "symbol":"BTCPERP",
// "orderType":"Limit",
// "side":"Buy",
// "orderQty":"0.00100000",
// "orderPrice":"20000.00",
// "iv":"0",
// "timeInForce":"GoodTillCancel",
// "orderStatus":"Created",
// "createdAt":"1652261746007873",
// "basePrice":"0.00",
// "triggerPrice":"0.00",
// "takeProfit":"0.00",
// "stopLoss":"0.00",
// "slTriggerBy":"UNKNOWN",
// "tpTriggerBy":"UNKNOWN"
// }
//
const order = this.safeValue (response, 'result', {});
return this.parseOrder (order);
}
async createContractOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (price === undefined && type === 'limit') {
throw new ArgumentsRequired (this.id + ' createOrder requires a price argument for limit orders');
}
const request = {
'symbol': market['id'],
'side': this.capitalize (side),
'order_type': this.capitalize (type), // limit
'time_in_force': 'GoodTillCancel', // ImmediateOrCancel, FillOrKill, PostOnly
'qty': amount,
};
if (market['future']) {
const positionIdx = this.safeInteger (params, 'position_idx', 0); // 0 One-Way Mode, 1 Buy-side, 2 Sell-side
request['position_idx'] = positionIdx;
params = this.omit (params, 'position_idx');
}
if (market['linear']) {
const reduceOnly = this.safeValue2 (params, 'reduce_only', 'reduceOnly', false);
const closeOnTrigger = this.safeValue2 (params, 'reduce_only', 'reduceOnly', false);
request['reduce_only'] = reduceOnly;
request['close_on_trigger'] = closeOnTrigger;
}
if (price !== undefined) {
request['price'] = price;
}
const stopPx = this.safeValue2 (params, 'stop_px', 'stopPrice');
const basePrice = this.safeValue2 (params, 'base_price', 'basePrice');
let isConditionalOrder = false;
if (stopPx !== undefined) {
isConditionalOrder = true;
if (basePrice === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder() requires both the stop_px and base_price params for a conditional ' + type + ' order');
}
request['stop_px'] = parseFloat (this.priceToPrecision (symbol, stopPx));
request['base_price'] = parseFloat (this.priceToPrecision (symbol, basePrice, 'basePrice'));
const triggerBy = this.safeString2 (params, 'trigger_by', 'triggerBy', 'LastPrice');
request['trigger_by'] = triggerBy;
params = this.omit (params, [ 'stop_px', 'stopPrice', 'base_price', 'triggerBy', 'trigger_by' ]);
}
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'orderLinkId');
if (clientOrderId !== undefined) {
request['orderLinkId'] = clientOrderId;
}
params = this.omit (params, [ 'clientOrderId', 'orderLinkId' ]);
let method = undefined;
if (market['future']) {
method = isConditionalOrder ? 'privatePostFuturesPrivateStopOrderCreate' : 'privatePostFuturesPrivateOrderCreate';
} else if (market['linear']) {
method = isConditionalOrder ? 'privatePostPrivateLinearStopOrderCreate' : 'privatePostPrivateLinearOrderCreate';
} else {
// inverse swaps
method = isConditionalOrder ? 'privatePostV2PrivateStopOrderCreate' : 'privatePostV2PrivateOrderCreate';
}
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "order_id":"f016f912-68c2-4da9-a289-1bb9b62b5c3b",
// "user_id":24478789,
// "symbol":"LTCUSDT",
// "side":"Buy",
// "order_type":"Market",
// "price":79.72,
// "qty":1,
// "time_in_force":"ImmediateOrCancel",
// "order_status":"Created",
// "last_exec_price":0,
// "cum_exec_qty":0,
// "cum_exec_value":0,
// "cum_exec_fee":0,
// "reduce_only":false,
// "close_on_trigger":false,
// "order_link_id":"",
// "created_time":"2022-05-11T13:56:29Z",
// "updated_time":"2022-05-11T13:56:29Z",
// "take_profit":0,
// "stop_loss":0,
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN",
// "position_idx":1
// },
// "time_now":"1652277389.122038",
// "rate_limit_status":98,
// "rate_limit_reset_ms":1652277389119,
// "rate_limit":100
// }
//
const order = this.safeValue (response, 'result', {});
return this.parseOrder (order);
}
async editUsdcOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
'orderId': id,
};
if (amount !== undefined) {
request['orderQty'] = amount;
}
if (price !== undefined) {
request['orderPrice'] = price;
}
const method = market['option'] ? 'privatePostOptionUsdcOpenApiPrivateV1ReplaceOrder' : 'privatePostPerpetualUsdcOpenApiPrivateV1ReplaceOrder';
const response = await this[method] (this.extend (request, params));
//
// {
// "retCode": 0,
// "retMsg": "OK",
// "result": {
// "outRequestId": "",
// "symbol": "BTC-13MAY22-40000-C",
// "orderId": "8c65df91-91fc-461d-9b14-786379ef138c",
// "orderLinkId": "AAAAA41133"
// },
// "retExtMap": {}
// }
//
return {
'info': response,
'id': id,
};
}
async editContractOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' editOrder() requires an symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
// 'order_id': id, // only for non-conditional orders
'symbol': market['id'],
// 'p_r_qty': this.amountToPrecision (symbol, amount), // new order quantity, optional
// 'p_r_price' this.priceToprecision (symbol, price), // new order price, optional
// ----------------------------------------------------------------
// conditional orders
// 'stop_order_id': id, // only for conditional orders
// 'p_r_trigger_price': 123.45, // new trigger price also known as stop_px
};
const orderType = this.safeString (params, 'orderType');
const isConditionalOrder = (orderType === 'stop' || orderType === 'conditional');
const idKey = isConditionalOrder ? 'stop_order_id' : 'order_id';
request[idKey] = id;
if (amount !== undefined) {
request['p_r_qty'] = amount;
}
if (price !== undefined) {
request['p_r_price'] = price;
}
let method = undefined;
if (market['linear']) {
method = isConditionalOrder ? 'privatePostPrivateLinearStopOrderReplace' : 'privatePostPrivateLinearOrderReplace';
} else if (market['future']) {
method = isConditionalOrder ? 'privatePostFuturesPrivateStopOrderReplace' : 'privatePostFuturesPrivateOrderReplace';
} else {
// inverse swaps
method = isConditionalOrder ? 'privatePostV2PrivateSpotOrderReplace' : 'privatePostV2PrivateOrderReplace';
}
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": { "order_id": "efa44157-c355-4a98-b6d6-1d846a936b93" },
// "time_now": "1539778407.210858",
// "rate_limit_status": 99, // remaining number of accesses in one minute
// "rate_limit_reset_ms": 1580885703683,
// "rate_limit": 100
// }
//
// conditional orders
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": { "stop_order_id": "378a1bbc-a93a-4e75-87f4-502ea754ba36" },
// "ext_info": null,
// "time_now": "1577475760.604942",
// "rate_limit_status": 96,
// "rate_limit_reset_ms": 1577475760612,
// "rate_limit": "100"
// }
//
const result = this.safeValue (response, 'result', {});
return {
'info': response,
'id': this.safeString2 (result, 'order_id', 'stop_order_id'),
'order_id': this.safeString (result, 'order_id'),
'stop_order_id': this.safeString (result, 'stop_order_id'),
};
}
async editOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' editOrder() requires an symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
amount = (amount !== undefined) ? this.amountToPrecision (symbol, amount) : undefined;
price = (price !== undefined) ? this.priceToPrecision (symbol, price) : undefined;
const isUsdcSettled = market['settle'] === 'USDC';
if (market['spot']) {
throw new NotSupported (this.id + ' editOrder() does not support spot markets');
} else if (isUsdcSettled) {
return await this.editUsdcOrder (id, symbol, type, side, amount, price, params);
} else {
return await this.editContractOrder (id, symbol, type, side, amount, price, params);
}
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
// 'order_link_id': 'string', // one of order_id, stop_order_id or order_link_id is required
// regular orders ---------------------------------------------
// 'order_id': id, // one of order_id or order_link_id is required for regular orders
// conditional orders ---------------------------------------------
// 'stop_order_id': id, // one of stop_order_id or order_link_id is required for conditional orders
// spot orders
// 'orderId': id
};
const orderType = this.safeStringLower (params, 'orderType');
const isConditional = (orderType === 'stop') || (orderType === 'conditional');
const isUsdcSettled = market['settle'] === 'USDC';
let method = undefined;
if (market['spot']) {
method = 'privateDeleteSpotV1Order';
request['orderId'] = id;
} else if (isUsdcSettled) {
request['orderId'] = id;
if (market['option']) {
method = 'privatePostOptionUsdcOpenapiPrivateV1CancelOrder';
} else {
method = 'privatePostPerpetualUsdcOpenapiPrivateV1CancelOrder';
request['orderFilter'] = isConditional ? 'StopOrder' : 'Order';
}
} else if (market['linear']) {
method = isConditional ? 'privatePostPrivateLinearStopOrderCancel' : 'privatePostPrivateLinearOrderCancel';
} else if (market['future']) {
method = isConditional ? 'privatePostFuturesPrivateStopOrderCancel' : 'privatePostFuturesPrivateOrderCancel';
} else {
// inverse futures
method = isConditional ? 'privatePostFuturesPrivateStopOrderCancel' : 'privatePostFuturesPrivateOrderCancel';
}
if (market['contract'] && !isUsdcSettled) {
if (!isConditional) {
request['order_id'] = id;
} else {
request['stop_order_id'] = id;
}
}
const response = await this[method] (this.extend (request, params));
// spot order
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":{
// "accountId":"24478790",
// "symbol":"LTCUSDT",
// "orderLinkId":"1652192399682",
// "orderId":"1153067855569315072",
// "transactTime":"1652192399866",
// "price":"50",
// "origQty":"0.2",
// "executedQty":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY"
// }
// }
// linear
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "order_id":"f5103487-f7f9-48d3-a26d-b74a3a53d3d3"
// },
// "time_now":"1652192814.880473",
// "rate_limit_status":99,
// "rate_limit_reset_ms":1652192814876,
// "rate_limit":100
// }
const result = this.safeValue (response, 'result', {});
return this.parseOrder (result, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
let market = undefined;
let isUsdcSettled = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
isUsdcSettled = market['settle'] === 'USDC';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = (settle === 'USDC');
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('cancelAllOrders', market, params);
if (!isUsdcSettled && symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelAllOrders() requires a symbol argument for ' + type + ' markets');
}
await this.loadMarkets ();
const request = {};
if (!isUsdcSettled) {
request['symbol'] = market['id'];
}
const orderType = this.safeStringLower (params, 'orderType');
const isConditional = (orderType === 'stop') || (orderType === 'conditional');
let method = undefined;
if (type === 'spot') {
method = 'privateDeleteSpotOrderBatchCancel';
} else if (isUsdcSettled) {
method = (type === 'option') ? 'privatePostOptionUsdcOpenapiPrivateV1CancelAll' : 'privatePostPerpetualUsdcOpenapiPrivateV1CancelAll';
} else if (type === 'future') {
method = isConditional ? 'privatePostFuturesPrivateStopOrderCancelAll' : 'privatePostFuturesPrivateOrderCancelAll';
} else if (market['linear']) {
// linear swap
method = isConditional ? 'privatePostPrivateLinearStopOrderCancelAll' : 'privatePostPrivateLinearOrderCancelAll';
} else {
// inverse swap
method = isConditional ? 'privatePostV2PrivateStopOrderCancelAll' : 'privatePostV2PrivateOrderCancelAll';
}
const response = await this[method] (this.extend (request, params));
// spot
// {
// "ret_code": 0,
// "ret_msg": "",
// "ext_code": null,
// "ext_info": null,
// "result": {
// "success": true
// }
// }
//
// linear swap
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// "49d9ee94-303b-4bcf-959b-9e5d215e4973"
// ],
// "time_now":"1652182444.015560",
// "rate_limit_status":90,
// "rate_limit_reset_ms":1652182444010,
// "rate_limit":100
// }
//
// conditional futures
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// {
// "clOrdID":"a14aea1e-9148-4a34-871a-f935f7cdb654",
// "user_id":24478789,
// "symbol":"ETHUSDM22",
// "side":"Buy",
// "order_type":"Limit",
// "price":"2001",
// "qty":10,
// "time_in_force":"GoodTillCancel",
// "create_type":"CreateByStopOrder",
// "cancel_type":"CancelByUser",
// "order_status":"",
// "leaves_value":"0",
// "created_at":"2022-05-10T11:43:29.705138839Z",
// "updated_at":"2022-05-10T11:43:37.988493739Z",
// "cross_status":"Deactivated",
// "cross_seq":-1,
// "stop_order_type":"Stop",
// "trigger_by":"LastPrice",
// "base_price":"2410.65",
// "trail_value":"0",
// "expected_direction":"Falling"
// }
// ],
// "time_now":"1652183017.988764",
// "rate_limit_status":97,
// "rate_limit_reset_ms":1652183017986,
// "rate_limit":100
// }
//
const result = this.safeValue (response, 'result', []);
if (!Array.isArray (result)) {
return response;
}
return this.parseOrders (result, market);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
if (market['spot'] || (market['settle'] === 'USDC')) {
throw new NotSupported (this.id + ' fetchOrders() does not support market ' + market['symbol']);
}
let method = undefined;
const type = this.safeStringLower (params, 'type');
params = this.omit (params, 'type');
const isConditionalOrder = (type === 'stop') || (type === 'conditional');
if (market['linear']) {
method = !isConditionalOrder ? 'privateGetPrivateLinearOrderList' : 'privateGetPrivateLinearStopOrderList';
} else if (market['future']) {
method = !isConditionalOrder ? 'privateGetFuturesPrivateOrderList' : 'privateGetFuturesPrivateStopOrderList';
} else {
// inverse swap
method = !isConditionalOrder ? 'privateGetV2PrivateOrderList' : 'privateGetV2PrivateStopOrderList';
}
const request = {
'symbol': market['id'],
// 'order_id': 'string'
// 'order_link_id': 'string', // unique client order id, max 36 characters
// 'symbol': market['id'], // default BTCUSD
// 'order': 'desc', // asc
// 'page': 1,
// 'limit': 20, // max 50
// 'order_status': 'Created,New'
// conditional orders ---------------------------------------------
// 'stop_order_id': 'string',
// 'stop_order_status': 'Untriggered',
};
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this[method] (this.extend (request, params));
//
// linear swap
//
// {
// "ret_code":"0",
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "current_page":"1",
// "data":[
// {
// "order_id":"68ab115d-cdbc-4c38-adc0-b2fbc60136ab",
// "user_id":"24478789",
// "symbol":"LTCUSDT",
// "side":"Sell",
// "order_type":"Market",
// "price":"94.72",
// "qty":"0.1",
// "time_in_force":"ImmediateOrCancel",
// "order_status":"Filled",
// "last_exec_price":"99.65",
// "cum_exec_qty":"0.1",
// "cum_exec_value":"9.965",
// "cum_exec_fee":"0.005979",
// "reduce_only":true,
// "close_on_trigger":true,
// "order_link_id":"",
// "created_time":"2022-05-05T15:15:34Z",
// "updated_time":"2022-05-05T15:15:34Z",
// "take_profit":"0",
// "stop_loss":"0",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN"
// }
// ]
// },
// "time_now":"1652106664.857572",
// "rate_limit_status":"598",
// "rate_limit_reset_ms":"1652106664856",
// "rate_limit":"600"
// }
//
//
// conditional orders
//
// {
// "ret_code":"0",
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "current_page":"1",
// "last_page":"0",
// "data":[
// {
// "user_id":"24478789",
// "stop_order_id":"68e996af-fa55-4ca1-830e-4bf68ffbff3e",
// "symbol":"LTCUSDT",
// "side":"Buy",
// "order_type":"Limit",
// "price":"86",
// "qty":"0.1",
// "time_in_force":"GoodTillCancel",
// "order_status":"Untriggered",
// "trigger_price":"86",
// "order_link_id":"",
// "created_time":"2022-05-09T14:36:36Z",
// "updated_time":"2022-05-09T14:36:36Z",
// "take_profit":"0",
// "stop_loss":"0",
// "trigger_by":"LastPrice",
// "base_price":"86.96",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN",
// "reduce_only":false,
// "close_on_trigger":false
// }
// ]
// },
// "time_now":"1652107028.148177",
// "rate_limit_status":"598",
// "rate_limit_reset_ms":"1652107028146",
// "rate_limit":"600"
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseOrders (data, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let market = undefined;
let isUsdcSettled = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
isUsdcSettled = market['settle'] === 'USDC';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = settle === 'USDC';
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchClosedOrders', market, params);
if ((type === 'swap' || type === 'future') && !isUsdcSettled) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchClosedOrders requires a symbol argument for ' + symbol + ' markets');
}
const type = this.safeStringLower (params, 'type');
const isConditional = (type === 'stop') || (type === 'conditional');
let defaultStatuses = undefined;
if (!isConditional) {
defaultStatuses = [
'Rejected',
'Filled',
'Cancelled',
];
} else {
// conditional orders
defaultStatuses = [
'Active',
'Triggered',
'Cancelled',
'Rejected',
'Deactivated',
];
}
const closeStatus = defaultStatuses.join (',');
const status = this.safeString2 (params, 'order_status', 'status', closeStatus);
params = this.omit (params, [ 'order_status', 'status' ]);
params['order_status'] = status;
return await this.fetchOrders (symbol, since, limit, params);
}
const request = {};
let method = undefined;
if (type === 'spot') {
method = 'privateGetSpotV1HistoryOrders';
} else {
// usdc
method = 'privatePostOptionUsdcOpenapiPrivateV1QueryOrderHistory';
request['category'] = (type === 'swap') ? 'perpetual' : 'option';
}
const orders = await this[method] (this.extend (request, params));
let result = this.safeValue (orders, 'result', []);
if (!Array.isArray (result)) {
result = this.safeValue (result, 'dataList', []);
}
return this.parseOrders (result, market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let market = undefined;
let isUsdcSettled = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
isUsdcSettled = market['settle'] === 'USDC';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = settle === 'USDC';
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchOpenOrders', market, params);
const request = {};
let method = undefined;
if ((type === 'swap' || type === 'future') && !isUsdcSettled) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOpenOrders requires a symbol argument for ' + symbol + ' markets');
}
request['symbol'] = market['id'];
const type = this.safeStringLower (params, 'orderType');
const isConditional = (type === 'stop') || (type === 'conditional');
if (market['future']) {
method = isConditional ? 'privateGetFuturesPrivateStopOrder' : 'privateGetFuturesPrivateOrder';
} else if (market['linear']) {
method = isConditional ? 'privateGetPrivateLinearStopOrderSearch' : 'privateGetPrivateLinearOrderSearch';
} else {
// inverse swap
method = isConditional ? 'privateGetV2PrivateStopOrder' : 'privateGetV2PrivateOrder';
}
} else if (type === 'spot') {
method = 'privateGetSpotV1OpenOrders';
} else {
// usdc
method = 'privatePostOptionUsdcOpenapiPrivateV1QueryActiveOrders';
request['category'] = (type === 'swap') ? 'perpetual' : 'option';
}
const orders = await this[method] (this.extend (request, params));
let result = this.safeValue (orders, 'result', []);
if (!Array.isArray (result)) {
const dataList = this.safeValue (result, 'dataList');
if (dataList === undefined) {
return this.parseOrder (result, market);
}
result = dataList;
}
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":[
// {
// "accountId":"24478790",
// "exchangeId":"301",
// "symbol":"LTCUSDT",
// "symbolName":"LTCUSDT",
// "orderLinkId":"1652115972506",
// "orderId":"1152426740986003968",
// "price":"50",
// "origQty":"0.2",
// "executedQty":"0",
// "cummulativeQuoteQty":"0",
// "avgPrice":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY",
// "stopPrice":"0.0",
// "icebergQty":"0.0",
// "time":"1652115973053",
// "updateTime":"1652115973063",
// "isWorking":true
// }
// ]
// }
return this.parseOrders (result, market, since, limit);
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
const request = {
'order_id': id,
};
return await this.fetchMyTrades (symbol, since, limit, this.extend (request, params));
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMyTrades() requires a symbol argument');
}
await this.loadMarkets ();
const request = {
// 'order_id': 'f185806b-b801-40ff-adec-52289370ed62', // if not provided will return user's trading records
// 'symbol': market['id'],
// 'start_time': parseInt (since / 1000),
// 'page': 1,
// 'limit' 20, // max 50
};
let market = undefined;
const orderId = this.safeString (params, 'order_id');
if (orderId !== undefined) {
request['order_id'] = orderId;
params = this.omit (params, 'order_id');
}
market = this.market (symbol);
const isUsdcSettled = market['settle'] === 'USDC';
if (isUsdcSettled) {
throw new NotSupported (this.id + ' fetchMyTrades() is not supported for market ' + symbol);
}
request['symbol'] = market['id'];
if (since !== undefined) {
request['start_time'] = since;
}
if (limit !== undefined) {
request['limit'] = limit; // default 20, max 50
}
let method = undefined;
if (market['spot']) {
method = 'privateGetSpotV1MyTrades';
} else if (market['future']) {
method = 'privateGetFuturesPrivateExecutionList';
} else {
// linear and inverse swaps
method = market['linear'] ? 'privateGetPrivateLinearTradeExecutionList' : 'privateGetV2PrivateExecutionList';
}
const response = await this[method] (this.extend (request, params));
//
// spot
// {
// "ret_code": 0,
// "ret_msg": "",
// "ext_code": null,
// "ext_info": null,
// "result": [
// {
// "id": "931975237315196160",
// "symbol": "BTCUSDT",
// "symbolName": "BTCUSDT",
// "orderId": "931975236946097408",
// "ticketId": "1057753175328833537",
// "matchOrderId": "931975113180558592",
// "price": "20000.00001",
// "qty": "0.01",
// "commission": "0.02000000001",
// "commissionAsset": "USDT",
// "time": "1625836105890",
// "isBuyer": false,
// "isMaker": false,
// "fee": {
// "feeTokenId": "USDT",
// "feeTokenName": "USDT",
// "fee": "0.02000000001"
// },
// "feeTokenId": "USDT",
// "feeAmount": "0.02000000001",
// "makerRebate": "0"
// }
// ]
// }
//
// inverse
//
// {
// "ret_code": 0,
// "ret_msg": "OK",
// "ext_code": "",
// "ext_info": "",
// "result": {
// "order_id": "Abandoned!!", // Abandoned!!
// "trade_list": [
// {
// "closed_size": 0,
// "cross_seq": 277136382,
// "exec_fee": "0.0000001",
// "exec_id": "256e5ef8-abfe-5772-971b-f944e15e0d68",
// "exec_price": "8178.5",
// "exec_qty": 1,
// "exec_time": "1571676941.70682",
// "exec_type": "Trade", //Exec Type Enum
// "exec_value": "0.00012227",
// "fee_rate": "0.00075",
// "last_liquidity_ind": "RemovedLiquidity", //Liquidity Enum
// "leaves_qty": 0,
// "nth_fill": 2,
// "order_id": "7ad50cb1-9ad0-4f74-804b-d82a516e1029",
// "order_link_id": "",
// "order_price": "8178",
// "order_qty": 1,
// "order_type": "Market", //Order Type Enum
// "side": "Buy", //Side Enum
// "symbol": "BTCUSD", //Symbol Enum
// "user_id": 1
// }
// ]
// },
// "time_now": "1577483699.281488",
// "rate_limit_status": 118,
// "rate_limit_reset_ms": 1577483699244737,
// "rate_limit": 120
// }
//
// linear
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "current_page":1,
// "data":[
// {
// "order_id":"b59418ec-14d4-4ef9-b9f4-721d5d576974",
// "order_link_id":"",
// "side":"Sell",
// "symbol":"BTCUSDT",
// "exec_id":"0327284d-faec-5191-bd89-acc5b4fafda9",
// "price":0.5,
// "order_price":0.5,
// "order_qty":0.01,
// "order_type":"Market",
// "fee_rate":0.00075,
// "exec_price":9709.5,
// "exec_type":"Trade",
// "exec_qty":0.01,
// "exec_fee":0.07282125,
// "exec_value":97.095,
// "leaves_qty":0,
// "closed_size":0.01,
// "last_liquidity_ind":"RemovedLiquidity",
// "trade_time":1591648052,
// "trade_time_ms":1591648052861
// }
// ]
// },
// "time_now":"1591736501.979264",
// "rate_limit_status":119,
// "rate_limit_reset_ms":1591736501974,
// "rate_limit":120
// }
//
let result = this.safeValue (response, 'result', {});
if (!Array.isArray (result)) {
result = this.safeValue2 (result, 'trade_list', 'data', []);
}
return this.parseTrades (result, market, since, limit);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'coin': currency['id'],
// 'currency': currency['id'], // alias
// 'start_date': this.iso8601 (since),
// 'end_date': this.iso8601 (till),
'wallet_fund_type': 'Deposit', // Deposit, Withdraw, RealisedPNL, Commission, Refund, Prize, ExchangeOrderWithdraw, ExchangeOrderDeposit
// 'page': 1,
// 'limit': 20, // max 50
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['coin'] = currency['id'];
}
if (since !== undefined) {
request['start_date'] = this.yyyymmdd (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.v2PrivateGetWalletFundRecords (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": {
// "data": [
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
// ]
// },
// "ext_info": null,
// "time_now": "1577481867.115552",
// "rate_limit_status": 119,
// "rate_limit_reset_ms": 1577481867122,
// "rate_limit": 120
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseTransactions (data, currency, since, limit, { 'type': 'deposit' });
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'coin': currency['id'],
// 'start_date': this.iso8601 (since),
// 'end_date': this.iso8601 (till),
// 'status': 'Pending', // ToBeConfirmed, UnderReview, Pending, Success, CancelByUser, Reject, Expire
// 'page': 1,
// 'limit': 20, // max 50
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['coin'] = currency['id'];
}
if (since !== undefined) {
request['start_date'] = this.yyyymmdd (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.v2PrivateGetWalletWithdrawList (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": {
// "data": [
// {
// "id": 137,
// "user_id": 1,
// "coin": "XRP", // Coin Enum
// "status": "Pending", // Withdraw Status Enum
// "amount": "20.00000000",
// "fee": "0.25000000",
// "address": "rH7H595XYEVTEHU2FySYsWnmfACBnZS9zM",
// "tx_id": "",
// "submited_at": "2019-06-11T02:20:24.000Z",
// "updated_at": "2019-06-11T02:20:24.000Z"
// },
// ],
// "current_page": 1,
// "last_page": 1
// },
// "ext_info": null,
// "time_now": "1577482295.125488",
// "rate_limit_status": 119,
// "rate_limit_reset_ms": 1577482295132,
// "rate_limit": 120
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseTransactions (data, currency, since, limit, { 'type': 'withdrawal' });
}
parseTransactionStatus (status) {
const statuses = {
'ToBeConfirmed': 'pending',
'UnderReview': 'pending',
'Pending': 'pending',
'Success': 'ok',
'CancelByUser': 'canceled',
'Reject': 'rejected',
'Expire': 'expired',
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// fetchWithdrawals
//
// {
// "id": 137,
// "user_id": 1,
// "coin": "XRP", // Coin Enum
// "status": "Pending", // Withdraw Status Enum
// "amount": "20.00000000",
// "fee": "0.25000000",
// "address": "rH7H595XYEVTEHU2FySYsWnmfACBnZS9zM",
// "tx_id": "",
// "submited_at": "2019-06-11T02:20:24.000Z",
// "updated_at": "2019-06-11T02:20:24.000Z"
// }
//
// fetchDeposits ledger entries
//
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
//
const currencyId = this.safeString (transaction, 'coin');
const code = this.safeCurrencyCode (currencyId, currency);
const timestamp = this.parse8601 (this.safeString2 (transaction, 'submited_at', 'exec_time'));
const updated = this.parse8601 (this.safeString (transaction, 'updated_at'));
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const address = this.safeString (transaction, 'address');
const feeCost = this.safeNumber (transaction, 'fee');
const type = this.safeStringLower (transaction, 'type');
let fee = undefined;
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': code,
};
}
return {
'info': transaction,
'id': this.safeString (transaction, 'id'),
'txid': this.safeString (transaction, 'tx_id'),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'network': undefined,
'address': address,
'addressTo': undefined,
'addressFrom': undefined,
'tag': undefined,
'tagTo': undefined,
'tagFrom': undefined,
'type': type,
'amount': this.safeNumber (transaction, 'amount'),
'currency': code,
'status': status,
'updated': updated,
'fee': fee,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'coin': currency['id'],
// 'currency': currency['id'], // alias
// 'start_date': this.iso8601 (since),
// 'end_date': this.iso8601 (till),
// 'wallet_fund_type': 'Deposit', // Withdraw, RealisedPNL, Commission, Refund, Prize, ExchangeOrderWithdraw, ExchangeOrderDeposit
// 'page': 1,
// 'limit': 20, // max 50
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['coin'] = currency['id'];
}
if (since !== undefined) {
request['start_date'] = this.yyyymmdd (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.v2PrivateGetWalletFundRecords (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": {
// "data": [
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
// ]
// },
// "ext_info": null,
// "time_now": "1577481867.115552",
// "rate_limit_status": 119,
// "rate_limit_reset_ms": 1577481867122,
// "rate_limit": 120
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseLedger (data, currency, since, limit);
}
parseLedgerEntry (item, currency = undefined) {
//
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
//
const currencyId = this.safeString (item, 'coin');
const code = this.safeCurrencyCode (currencyId, currency);
const amount = this.safeNumber (item, 'amount');
const after = this.safeNumber (item, 'wallet_balance');
const direction = (amount < 0) ? 'out' : 'in';
let before = undefined;
if (after !== undefined && amount !== undefined) {
const difference = (direction === 'out') ? amount : -amount;
before = this.sum (after, difference);
}
const timestamp = this.parse8601 (this.safeString (item, 'exec_time'));
const type = this.parseLedgerEntryType (this.safeString (item, 'type'));
const id = this.safeString (item, 'id');
const referenceId = this.safeString (item, 'tx_id');
return {
'id': id,
'currency': code,
'account': this.safeString (item, 'wallet_id'),
'referenceAccount': undefined,
'referenceId': referenceId,
'status': undefined,
'amount': amount,
'before': before,
'after': after,
'fee': undefined,
'direction': direction,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'type': type,
'info': item,
};
}
parseLedgerEntryType (type) {
const types = {
'Deposit': 'transaction',
'Withdraw': 'transaction',
'RealisedPNL': 'trade',
'Commission': 'fee',
'Refund': 'cashback',
'Prize': 'prize', // ?
'ExchangeOrderWithdraw': 'transaction',
'ExchangeOrderDeposit': 'transaction',
};
return this.safeString (types, type, type);
}
async fetchPositions (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (Array.isArray (symbols)) {
const length = symbols.length;
if (length !== 1) {
throw new ArgumentsRequired (this.id + ' fetchPositions() takes an array with exactly one symbol');
}
request['symbol'] = this.marketId (symbols[0]);
}
const defaultType = this.safeString (this.options, 'defaultType', 'linear');
const type = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
let response = undefined;
if (type === 'linear') {
response = await this.privateLinearGetPositionList (this.extend (request, params));
} else if (type === 'inverse') {
response = await this.v2PrivateGetPositionList (this.extend (request, params));
} else if (type === 'inverseFuture') {
response = await this.futuresPrivateGetPositionList (this.extend (request, params));
}
if ((typeof response === 'string') && this.isJsonEncodedObject (response)) {
response = JSON.parse (response);
}
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [] or {} depending on the request
// }
//
return this.safeValue (response, 'result');
}
async setMarginMode (marginType, symbol = undefined, params = {}) {
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": null,
// "ext_info": null,
// "time_now": "1577477968.175013",
// "rate_limit_status": 74,
// "rate_limit_reset_ms": 1577477968183,
// "rate_limit": 75
// }
//
const leverage = this.safeValue (params, 'leverage');
if (leverage === undefined) {
throw new ArgumentsRequired (this.id + ' setMarginMode() requires a leverage parameter');
}
marginType = marginType.toUpperCase ();
if (marginType === 'CROSSED') { // * Deprecated, use 'CROSS' instead
marginType = 'CROSS';
}
if ((marginType !== 'ISOLATED') && (marginType !== 'CROSS')) {
throw new BadRequest (this.id + ' setMarginMode() marginType must be either isolated or cross');
}
await this.loadMarkets ();
const market = this.market (symbol);
let method = undefined;
const defaultType = this.safeString (this.options, 'defaultType', 'linear');
const marketTypes = this.safeValue (this.options, 'marketTypes', {});
const marketType = this.safeString (marketTypes, symbol, defaultType);
const linear = market['linear'] || (marketType === 'linear');
const inverse = (market['swap'] && market['inverse']) || (marketType === 'inverse');
const future = market['future'] || ((marketType === 'future') || (marketType === 'futures')); // * (marketType === 'futures') deprecated, use (marketType === 'future')
if (linear) {
method = 'privateLinearPostPositionSwitchIsolated';
} else if (inverse) {
method = 'v2PrivatePostPositionSwitchIsolated';
} else if (future) {
method = 'privateFuturesPostPositionSwitchIsolated';
}
const isIsolated = (marginType === 'ISOLATED');
const request = {
'symbol': market['id'],
'is_isolated': isIsolated,
'buy_leverage': leverage,
'sell_leverage': leverage,
};
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "OK",
// "ext_code": "",
// "ext_info": "",
// "result": null,
// "time_now": "1585881597.006026",
// "rate_limit_status": 74,
// "rate_limit_reset_ms": 1585881597004,
// "rate_limit": 75
// }
//
return response;
}
async setLeverage (leverage, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' setLeverage() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
// WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
// AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
const defaultType = this.safeString (this.options, 'defaultType', 'linear');
const marketTypes = this.safeValue (this.options, 'marketTypes', {});
const marketType = this.safeString (marketTypes, symbol, defaultType);
const linear = market['linear'] || (marketType === 'linear');
const inverse = (market['swap'] && market['inverse']) || (marketType === 'inverse');
const future = market['future'] || ((marketType === 'future') || (marketType === 'futures')); // * (marketType === 'futures') deprecated, use (marketType === 'future')
let method = undefined;
if (linear) {
method = 'privateLinearPostPositionSetLeverage';
} else if (inverse) {
method = 'v2PrivatePostPositionLeverageSave';
} else if (future) {
method = 'privateFuturesPostPositionLeverageSave';
}
let buy_leverage = leverage;
let sell_leverage = leverage;
if (params['buy_leverage'] && params['sell_leverage'] && linear) {
buy_leverage = params['buy_leverage'];
sell_leverage = params['sell_leverage'];
} else if (!leverage) {
if (linear) {
throw new ArgumentsRequired (this.id + ' setLeverage() requires either the parameter leverage or params["buy_leverage"] and params["sell_leverage"] for linear contracts');
} else {
throw new ArgumentsRequired (this.id + ' setLeverage() requires parameter leverage for inverse and futures contracts');
}
}
if ((buy_leverage < 1) || (buy_leverage > 100) || (sell_leverage < 1) || (sell_leverage > 100)) {
throw new BadRequest (this.id + ' setLeverage() leverage should be between 1 and 100');
}
const request = {
'symbol': market['id'],
'leverage_only': true,
};
if (!linear) {
request['leverage'] = buy_leverage;
} else {
request['buy_leverage'] = buy_leverage;
request['sell_leverage'] = sell_leverage;
}
return await this[method] (this.extend (request, params));
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = undefined;
if (Array.isArray (api)) {
const type = this.safeString (api, 0);
let section = this.safeString (api, 1);
if (type === 'spot') {
if (section === 'public') {
section = 'v1';
} else {
section += '/v1';
}
}
url = this.implodeHostname (this.urls['api'][type]);
let request = '/' + type + '/' + section + '/' + path;
if ((type === 'spot') || (type === 'quote')) {
if (Object.keys (params).length) {
request += '?' + this.rawencode (params);
}
} else if (section === 'public') {
if (Object.keys (params).length) {
request += '?' + this.rawencode (params);
}
} else if (type === 'public') {
if (Object.keys (params).length) {
request += '?' + this.rawencode (params);
}
} else {
this.checkRequiredCredentials ();
const timestamp = this.nonce ();
const query = this.extend (params, {
'api_key': this.apiKey,
'recv_window': this.options['recvWindow'],
'timestamp': timestamp,
});
const sortedQuery = this.keysort (query);
const auth = this.rawencode (sortedQuery);
const signature = this.hmac (this.encode (auth), this.encode (this.secret));
if (method === 'POST') {
body = this.json (this.extend (query, {
'sign': signature,
}));
headers = {
'Content-Type': 'application/json',
};
} else {
request += '?' + this.urlencode (sortedQuery) + '&sign=' + signature;
}
}
url += request;
} else {
url = this.implodeHostname (this.urls['api'][api]) + '/' + path;
if (api === 'public') {
if (Object.keys (params).length) {
url += '?' + this.rawencode (params);
}
} else if (api === 'private') {
this.checkRequiredCredentials ();
const isOpenapi = url.indexOf ('openapi') >= 0;
const timestamp = this.milliseconds ();
if (isOpenapi) {
let query = {};
if (Object.keys (params).length) {
query = params;
}
// this is a PHP specific check
const queryLength = query.length;
if (Array.isArray (query) && queryLength === 0) {
query = '';
} else {
query = this.json (query);
}
body = query;
const payload = timestamp.toString () + this.apiKey + query;
const signature = this.hmac (this.encode (payload), this.encode (this.secret), 'sha256', 'hex');
headers = {
'X-BAPI-API-KEY': this.apiKey,
'X-BAPI-TIMESTAMP': timestamp.toString (),
'X-BAPI-SIGN': signature,
};
} else {
const query = this.extend (params, {
'api_key': this.apiKey,
'recv_window': this.options['recvWindow'],
'timestamp': timestamp,
});
const sortedQuery = this.keysort (query);
const auth = this.rawencode (sortedQuery);
const signature = this.hmac (this.encode (auth), this.encode (this.secret));
if (method === 'POST') {
const isSpot = url.indexOf ('spot') >= 0;
const extendedQuery = this.extend (query, {
'sign': signature,
});
if (!isSpot) {
body = this.json (extendedQuery);
headers = {
'Content-Type': 'application/json',
};
} else {
body = this.urlencode (extendedQuery);
headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
}
} else {
url += '?' + this.urlencode (sortedQuery) + '&sign=' + signature;
}
}
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (!response) {
return; // fallback to default error handler
}
//
// {
// ret_code: 10001,
// ret_msg: 'ReadMapCB: expect { or n, but found \u0000, error ' +
// 'found in #0 byte of ...||..., bigger context ' +
// '...||...',
// ext_code: '',
// ext_info: '',
// result: null,
// time_now: '1583934106.590436'
// }
//
// {
// "retCode":10001,
// "retMsg":"symbol params err",
// "result":{"symbol":"","bid":"","bidIv":"","bidSize":"","ask":"","askIv":"","askSize":"","lastPrice":"","openInterest":"","indexPrice":"","markPrice":"","markPriceIv":"","change24h":"","high24h":"","low24h":"","volume24h":"","turnover24h":"","totalVolume":"","totalTurnover":"","fundingRate":"","predictedFundingRate":"","nextFundingTime":"","countdownHour":"0","predictedDeliveryPrice":"","underlyingPrice":"","delta":"","gamma":"","vega":"","theta":""}
// }
//
const errorCode = this.safeString2 (response, 'ret_code', 'retCode');
if (errorCode !== '0') {
if (errorCode === '30084') {
// not an error
// https://github.com/ccxt/ccxt/issues/11268
// https://github.com/ccxt/ccxt/pull/11624
// POST https://api.bybit.com/v2/private/position/switch-isolated 200 OK
// {"ret_code":30084,"ret_msg":"Isolated not modified","ext_code":"","ext_info":"","result":null,"time_now":"1642005219.937988","rate_limit_status":73,"rate_limit_reset_ms":1642005219894,"rate_limit":75}
return undefined;
}
const feedback = this.id + ' ' + body;
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], body, feedback);
throw new ExchangeError (feedback); // unknown message
}
}
async fetchMarketLeverageTiers (symbol, params = {}) {
await this.loadMarkets ();
const request = {};
let market = undefined;
market = this.market (symbol);
if (market['spot'] || market['option']) {
throw new BadRequest (this.id + ' fetchLeverageTiers() symbol does not support market ' + symbol);
}
request['symbol'] = market['id'];
const isUsdcSettled = market['settle'] === 'USDC';
let method = undefined;
if (isUsdcSettled) {
method = 'publicGetPerpetualUsdcOpenapiPublicV1RiskLimitList';
} else if (market['linear']) {
method = 'publicLinearGetRiskLimit';
} else {
method = 'publicGetV2PublicRiskLimitList';
}
const response = await this[method] (this.extend (request, params));
//
// publicLinearGetRiskLimit
// {
// ret_code: '0',
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// id: '11',
// symbol: 'ETHUSDT',
// limit: '800000',
// maintain_margin: '0.01',
// starting_margin: '0.02',
// section: [
// '1', '2', '3',
// '5', '10', '15',
// '25'
// ],
// is_lowest_risk: '1',
// created_at: '2022-02-04 23:30:33.555252',
// updated_at: '2022-02-04 23:30:33.555254',
// max_leverage: '50'
// },
// ...
// ]
// }
//
// v2PublicGetRiskLimitList
// {
// ret_code: '0',
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// id: '180',
// is_lowest_risk: '0',
// section: [
// '1', '2', '3',
// '4', '5', '7',
// '8', '9'
// ],
// symbol: 'ETHUSDH22',
// limit: '30000',
// max_leverage: '9',
// starting_margin: '11',
// maintain_margin: '5.5',
// coin: 'ETH',
// created_at: '2021-04-22T15:00:00Z',
// updated_at: '2021-04-22T15:00:00Z'
// },
// ],
// time_now: '1644017569.683191'
// }
//
const result = this.safeValue (response, 'result');
return this.parseMarketLeverageTiers (result, market);
}
parseMarketLeverageTiers (info, market) {
//
// Linear
// [
// {
// id: '11',
// symbol: 'ETHUSDT',
// limit: '800000',
// maintain_margin: '0.01',
// starting_margin: '0.02',
// section: [
// '1', '2', '3',
// '5', '10', '15',
// '25'
// ],
// is_lowest_risk: '1',
// created_at: '2022-02-04 23:30:33.555252',
// updated_at: '2022-02-04 23:30:33.555254',
// max_leverage: '50'
// },
// ...
// ]
//
// Inverse
// [
// {
// id: '180',
// is_lowest_risk: '0',
// section: [
// '1', '2', '3',
// '4', '5', '7',
// '8', '9'
// ],
// symbol: 'ETHUSDH22',
// limit: '30000',
// max_leverage: '9',
// starting_margin: '11',
// maintain_margin: '5.5',
// coin: 'ETH',
// created_at: '2021-04-22T15:00:00Z',
// updated_at: '2021-04-22T15:00:00Z'
// }
// ...
// ]
//
// usdc swap
//
// {
// "riskId":"10001",
// "symbol":"BTCPERP",
// "limit":"1000000",
// "startingMargin":"0.0100",
// "maintainMargin":"0.0050",
// "isLowestRisk":true,
// "section":[
// "1",
// "2",
// "3",
// "5",
// "10",
// "25",
// "50",
// "100"
// ],
// "maxLeverage":"100.00"
// }
//
let minNotional = 0;
const tiers = [];
for (let i = 0; i < info.length; i++) {
const item = info[i];
const maxNotional = this.safeNumber (item, 'limit');
tiers.push ({
'tier': this.sum (i, 1),
'currency': market['base'],
'minNotional': minNotional,
'maxNotional': maxNotional,
'maintenanceMarginRate': this.safeNumber2 (item, 'maintain_margin', 'maintainMargin'),
'maxLeverage': this.safeNumber2 (item, 'max_leverage', 'maxLeverage'),
'info': item,
});
minNotional = maxNotional;
}
return tiers;
}
};
| js/bybit.js | 'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { TICK_SIZE } = require ('./base/functions/number');
const { AuthenticationError, ExchangeError, ArgumentsRequired, PermissionDenied, InvalidOrder, OrderNotFound, InsufficientFunds, BadRequest, RateLimitExceeded, InvalidNonce, NotSupported } = require ('./base/errors');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class bybit extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bybit',
'name': 'Bybit',
'countries': [ 'VG' ], // British Virgin Islands
'version': 'v2',
'userAgent': undefined,
// 50 requests per second for GET requests, 1000ms / 50 = 20ms between requests
// 20 requests per second for POST requests, cost = 50 / 20 = 2.5
'rateLimit': 20,
'hostname': 'bybit.com', // bybit.com, bytick.com
'has': {
'CORS': true,
'spot': true,
'margin': false,
'swap': true,
'future': true,
'option': undefined,
'cancelAllOrders': true,
'cancelOrder': true,
'createOrder': true,
'createStopLimitOrder': true,
'createStopMarketOrder': true,
'createStopOrder': true,
'editOrder': true,
'fetchBalance': true,
'fetchBorrowRate': false,
'fetchBorrowRates': false,
'fetchClosedOrders': true,
'fetchDeposits': true,
'fetchFundingRate': true,
'fetchFundingRateHistory': false,
'fetchIndexOHLCV': true,
'fetchLedger': true,
'fetchMarketLeverageTiers': true,
'fetchMarkets': true,
'fetchMarkOHLCV': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchOrderTrades': true,
'fetchPositions': true,
'fetchPremiumIndexOHLCV': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingFee': false,
'fetchTradingFees': false,
'fetchTransactions': undefined,
'fetchWithdrawals': true,
'setLeverage': true,
'setMarginMode': true,
},
'timeframes': {
'1m': '1',
'3m': '3',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'2h': '120',
'4h': '240',
'6h': '360',
'12h': '720',
'1d': 'D',
'1w': 'W',
'1M': 'M',
'1y': 'Y',
},
'urls': {
'test': {
'spot': 'https://api-testnet.{hostname}',
'futures': 'https://api-testnet.{hostname}',
'v2': 'https://api-testnet.{hostname}',
'public': 'https://api-testnet.{hostname}',
'private': 'https://api-testnet.{hostname}',
},
'logo': 'https://user-images.githubusercontent.com/51840849/76547799-daff5b80-649e-11ea-87fb-3be9bac08954.jpg',
'api': {
'spot': 'https://api.{hostname}',
'futures': 'https://api.{hostname}',
'v2': 'https://api.{hostname}',
'public': 'https://api.{hostname}',
'private': 'https://api.{hostname}',
},
'www': 'https://www.bybit.com',
'doc': [
'https://bybit-exchange.github.io/docs/inverse/',
'https://bybit-exchange.github.io/docs/linear/',
'https://github.com/bybit-exchange',
],
'fees': 'https://help.bybit.com/hc/en-us/articles/360039261154',
'referral': 'https://www.bybit.com/app/register?ref=X7Prm',
},
'api': {
// outdated endpoints -----------------------------------------
'spot': {
'public': {
'get': [
'symbols',
],
},
'quote': {
'get': [
'depth',
'depth/merged',
'trades',
'kline',
'ticker/24hr',
'ticker/price',
'ticker/book_ticker',
],
},
'private': {
'get': [
'order',
'open-orders',
'history-orders',
'myTrades',
'account',
'time',
],
'post': [
'order',
],
'delete': [
'order',
'order/fast',
],
},
'order': {
'delete': [
'batch-cancel',
'batch-fast-cancel',
'batch-cancel-by-ids',
],
},
},
'futures': {
'private': {
'get': [
'order/list',
'order',
'stop-order/list',
'stop-order',
'position/list',
'execution/list',
'trade/closed-pnl/list',
],
'post': [
'order/create',
'order/cancel',
'order/cancelAll',
'order/replace',
'stop-order/create',
'stop-order/cancel',
'stop-order/cancelAll',
'stop-order/replace',
'position/change-position-margin',
'position/trading-stop',
'position/leverage/save',
'position/switch-mode',
'position/switch-isolated',
'position/risk-limit',
],
},
},
'v2': {
'public': {
'get': [
'orderBook/L2',
'kline/list',
'tickers',
'trading-records',
'symbols',
'liq-records',
'mark-price-kline',
'index-price-kline',
'premium-index-kline',
'open-interest',
'big-deal',
'account-ratio',
'time',
'announcement',
'funding/prev-funding-rate',
'risk-limit/list',
],
},
'private': {
'get': [
'order/list',
'order',
'stop-order/list',
'stop-order',
'position/list',
'position/fee-rate',
'execution/list',
'trade/closed-pnl/list',
'funding/prev-funding-rate',
'funding/prev-funding',
'funding/predicted-funding',
'account/api-key',
'account/lcp',
'wallet/balance',
'wallet/fund/records',
'wallet/withdraw/list',
'exchange-order/list',
],
'post': [
'order/create',
'order/cancel',
'order/cancelAll',
'order/replace',
'stop-order/create',
'stop-order/cancel',
'stop-order/cancelAll',
'stop-order/replace',
'position/change-position-margin',
'position/trading-stop',
'position/leverage/save',
'position/switch-mode',
'position/switch-isolated',
'position/risk-limit',
],
},
},
// new endpoints ------------------------------------------
'public': {
'get': {
// inverse swap
'v2/public/orderBook/L2': 1,
'v2/public/kline/list': 3,
'v2/public/tickers': 1,
'v2/public/trading-records': 1,
'v2/public/symbols': 1,
'v2/public/mark-price-kline': 3,
'v2/public/index-price-kline': 3,
'v2/public/premium-index-kline': 2,
'v2/public/open-interest': 1,
'v2/public/big-deal': 1,
'v2/public/account-ratio': 1,
'v2/public/funding-rate': 1,
'v2/public/elite-ratio': 1,
'v2/public/risk-limit/list': 1,
// linear swap USDT
'public/linear/kline': 3,
'public/linear/recent-trading-records': 1,
'public/linear/funding/prev-funding-rate': 1,
'public/linear/mark-price-kline': 1,
'public/linear/index-price-kline': 1,
'public/linear/premium-index-kline': 1,
// spot
'spot/v1/time': 1,
'spot/v1/symbols': 1,
'spot/quote/v1/depth': 1,
'spot/quote/v1/depth/merged': 1,
'spot/quote/v1/trades': 1,
'spot/quote/v1/kline': 1,
'spot/quote/v1/ticker/24hr': 1,
'spot/quote/v1/ticker/price': 1,
'spot/quote/v1/ticker/book_ticker': 1,
// data
'v2/public/time': 1,
'v2/public/announcement': 1,
// USDC endpoints are testnet only as of 2022 Jan 11 ----------
// option USDC (testnet only)
'option/usdc/openapi/public/v1/order-book': 1,
'option/usdc/openapi/public/v1/symbols': 1,
'option/usdc/openapi/public/v1/tick': 1,
'option/usdc/openapi/public/v1/delivery-price': 1,
'option/usdc/openapi/public/v1/query-trade-latest': 1,
// perpetual swap USDC (testnet only)
'perpetual/usdc/openapi/public/v1/order-book': 1,
'perpetual/usdc/openapi/public/v1/symbols': 1,
'perpetual/usdc/openapi/public/v1/tick': 1,
'perpetual/usdc/openapi/public/v1/kline/list': 1,
'perpetual/usdc/openapi/public/v1/mark-price-kline': 1,
'perpetual/usdc/openapi/public/v1/index-price-kline': 1,
'perpetual/usdc/openapi/public/v1/premium-index-kline': 1,
'perpetual/usdc/openapi/public/v1/open-interest': 1,
'perpetual/usdc/openapi/public/v1/big-deal': 1,
'perpetual/usdc/openapi/public/v1/account-ratio': 1,
'perpetual/usdc/openapi/public/v1/risk-limit/list': 1,
},
// outdated endpoints--------------------------------------
'linear': {
'get': [
'kline',
'recent-trading-records',
'funding/prev-funding-rate',
'mark-price-kline',
'index-price-kline',
'premium-index-kline',
'risk-limit',
],
},
},
// new endpoints ------------------------------------------
'private': {
'get': {
// inverse swap
'v2/private/order/list': 5,
'v2/private/order': 5,
'v2/private/stop-order/list': 5,
'v2/private/stop-order': 1,
'v2/private/position/list': 25,
'v2/private/position/fee-rate': 40,
'v2/private/execution/list': 25,
'v2/private/trade/closed-pnl/list': 1,
'v2/public/risk-limit/list': 1, // TODO check
'v2/public/funding/prev-funding-rate': 25, // TODO check
'v2/private/funding/prev-funding': 25,
'v2/private/funding/predicted-funding': 25,
'v2/private/account/api-key': 5,
'v2/private/account/lcp': 1,
'v2/private/wallet/balance': 25, // 120 per minute = 2 per second => cost = 50 / 2 = 25
'v2/private/wallet/fund/records': 25,
'v2/private/wallet/withdraw/list': 25,
'v2/private/exchange-order/list': 1,
// linear swap USDT
'private/linear/order/list': 5, // 600 per minute = 10 per second => cost = 50 / 10 = 5
'private/linear/order/search': 5,
'private/linear/stop-order/list': 5,
'private/linear/stop-order/search': 5,
'private/linear/position/list': 25,
'private/linear/trade/execution/list': 25,
'private/linear/trade/closed-pnl/list': 25,
'public/linear/risk-limit': 1,
'private/linear/funding/predicted-funding': 25,
'private/linear/funding/prev-funding': 25,
// inverse futures
'futures/private/order/list': 5,
'futures/private/order': 5,
'futures/private/stop-order/list': 5,
'futures/private/stop-order': 5,
'futures/private/position/list': 25,
'futures/private/execution/list': 25,
'futures/private/trade/closed-pnl/list': 1,
// spot
'spot/v1/account': 2.5,
'spot/v1/order': 2.5,
'spot/v1/open-orders': 2.5,
'spot/v1/history-orders': 2.5,
'spot/v1/myTrades': 2.5,
// account
'asset/v1/private/transfer/list': 50, // 60 per minute = 1 per second => cost = 50 / 1 = 50
'asset/v1/private/sub-member/transfer/list': 50,
'asset/v1/private/sub-member/member-ids': 50,
},
'post': {
// inverse swap
'v2/private/order/create': 30,
'v2/private/order/cancel': 30,
'v2/private/order/cancelAll': 300, // 100 per minute + 'consumes 10 requests'
'v2/private/order/replace': 30,
'v2/private/stop-order/create': 30,
'v2/private/stop-order/cancel': 30,
'v2/private/stop-order/cancelAll': 300,
'v2/private/stop-order/replace': 30,
'v2/private/position/change-position-margin': 40,
'v2/private/position/trading-stop': 40,
'v2/private/position/leverage/save': 40,
'v2/private/tpsl/switch-mode': 40,
'v2/private/position/switch-isolated': 2.5,
'v2/private/position/risk-limit': 2.5,
'v2/private/position/switch-mode': 2.5,
// linear swap USDT
'private/linear/order/create': 30, // 100 per minute = 1.666 per second => cost = 50 / 1.6666 = 30
'private/linear/order/cancel': 30,
'private/linear/order/cancel-all': 300, // 100 per minute + 'consumes 10 requests'
'private/linear/order/replace': 30,
'private/linear/stop-order/create': 30,
'private/linear/stop-order/cancel': 30,
'private/linear/stop-order/cancel-all': 300,
'private/linear/stop-order/replace': 30,
'private/linear/position/set-auto-add-margin': 40,
'private/linear/position/switch-isolated': 40,
'private/linear/position/switch-mode': 40,
'private/linear/tpsl/switch-mode': 2.5,
'private/linear/position/add-margin': 40,
'private/linear/position/set-leverage': 40, // 75 per minute = 1.25 per second => cost = 50 / 1.25 = 40
'private/linear/position/trading-stop': 40,
'private/linear/position/set-risk': 2.5,
// inverse futures
'futures/private/order/create': 30,
'futures/private/order/cancel': 30,
'futures/private/order/cancelAll': 30,
'futures/private/order/replace': 30,
'futures/private/stop-order/create': 30,
'futures/private/stop-order/cancel': 30,
'futures/private/stop-order/cancelAll': 30,
'futures/private/stop-order/replace': 30,
'futures/private/position/change-position-margin': 40,
'futures/private/position/trading-stop': 40,
'futures/private/position/leverage/save': 40,
'futures/private/position/switch-mode': 40,
'futures/private/tpsl/switch-mode': 40,
'futures/private/position/switch-isolated': 40,
'futures/private/position/risk-limit': 2.5,
// spot
'spot/v1/order': 2.5,
// account
'asset/v1/private/transfer': 150, // 20 per minute = 0.333 per second => cost = 50 / 0.3333 = 150
'asset/v1/private/sub-member/transfer': 150,
// USDC endpoints are testnet only as of 2022 Jan 11 ----------
// option USDC (testnet only)
'option/usdc/openapi/private/v1/place-order': 2.5,
'option/usdc/openapi/private/v1/batch-place-order': 2.5,
'option/usdc/openapi/private/v1/replace-order': 2.5,
'option/usdc/openapi/private/v1/batch-replace-orders': 2.5,
'option/usdc/openapi/private/v1/cancel-order': 2.5,
'option/usdc/openapi/private/v1/batch-cancel-orders': 2.5,
'option/usdc/openapi/private/v1/cancel-all': 2.5,
'option/usdc/openapi/private/v1/query-active-orders': 2.5,
'option/usdc/openapi/private/v1/query-order-history': 2.5,
'option/usdc/openapi/private/v1/execution-list': 2.5,
'option/usdc/openapi/private/v1/query-transaction-log': 2.5,
'option/usdc/openapi/private/v1/query-wallet-balance': 2.5,
'option/usdc/openapi/private/v1/query-asset-info': 2.5,
'option/usdc/openapi/private/v1/query-margin-info': 2.5,
'option/usdc/openapi/private/v1/query-position': 2.5,
'option/usdc/openapi/private/v1/query-delivery-list': 2.5,
'option/usdc/openapi/private/v1/query-position-exp-date': 2.5,
'option/usdc/openapi/private/v1/mmp-modify': 2.5,
'option/usdc/openapi/private/v1/mmp-reset': 2.5,
// perpetual swap USDC (testnet only)
'perpetual/usdc/openapi/private/v1/place-order': 2.5,
'perpetual/usdc/openapi/private/v1/replace-order': 2.5,
'perpetual/usdc/openapi/private/v1/cancel-order': 2.5,
'perpetual/usdc/openapi/private/v1/cancel-all': 2.5,
'perpetual/usdc/openapi/private/v1/position/leverage/save': 2.5,
'option/usdc/openapi/private/v1/session-settlement': 2.5,
'perpetual/usdc/openapi/public/v1/risk-limit/list': 2.5,
'perpetual/usdc/openapi/private/v1/position/set-risk-limit': 2.5,
},
'delete': {
// spot
'spot/v1/order': 2.5,
'spot/v1/order/fast': 2.5,
'spot/order/batch-cancel': 2.5,
'spot/order/batch-fast-cancel': 2.5,
'spot/order/batch-cancel-by-ids': 2.5,
},
// outdated endpoints -------------------------------------
'linear': {
'get': [
'order/list',
'order/search',
'stop-order/list',
'stop-order/search',
'position/list',
'trade/execution/list',
'trade/closed-pnl/list',
'funding/predicted-funding',
'funding/prev-funding',
],
'post': [
'order/create',
'order/cancel',
'order/cancel-all',
'order/replace',
'stop-order/create',
'stop-order/cancel',
'stop-order/cancel-all',
'stop-order/replace',
'position/set-auto-add-margin',
'position/switch-isolated',
'position/switch-mode',
'tpsl/switch-mode',
'position/add-margin',
'position/set-leverage',
'position/trading-stop',
'position/set-risk',
],
},
},
},
'httpExceptions': {
'403': RateLimitExceeded, // Forbidden -- You request too many times
},
'exceptions': {
'exact': {
'-10009': BadRequest, // {"ret_code":-10009,"ret_msg":"Invalid period!","result":null,"token":null}
'-2015': AuthenticationError, // Invalid API-key, IP, or permissions for action.
'-1021': BadRequest, // {"ret_code":-1021,"ret_msg":"Timestamp for this request is outside of the recvWindow.","ext_code":null,"ext_info":null,"result":null}
'-1004': BadRequest, // {"ret_code":-1004,"ret_msg":"Missing required parameter \u0027symbol\u0027","ext_code":null,"ext_info":null,"result":null}
'7001': BadRequest, // {"retCode":7001,"retMsg":"request params type error"}
'10001': BadRequest, // parameter error
'10002': InvalidNonce, // request expired, check your timestamp and recv_window
'10003': AuthenticationError, // Invalid apikey
'10004': AuthenticationError, // invalid sign
'10005': PermissionDenied, // permission denied for current apikey
'10006': RateLimitExceeded, // too many requests
'10007': AuthenticationError, // api_key not found in your request parameters
'10010': PermissionDenied, // request ip mismatch
'10016': ExchangeError, // {"retCode":10016,"retMsg":"System error. Please try again later."}
'10017': BadRequest, // request path not found or request method is invalid
'10018': RateLimitExceeded, // exceed ip rate limit
'20001': OrderNotFound, // Order not exists
'20003': InvalidOrder, // missing parameter side
'20004': InvalidOrder, // invalid parameter side
'20005': InvalidOrder, // missing parameter symbol
'20006': InvalidOrder, // invalid parameter symbol
'20007': InvalidOrder, // missing parameter order_type
'20008': InvalidOrder, // invalid parameter order_type
'20009': InvalidOrder, // missing parameter qty
'20010': InvalidOrder, // qty must be greater than 0
'20011': InvalidOrder, // qty must be an integer
'20012': InvalidOrder, // qty must be greater than zero and less than 1 million
'20013': InvalidOrder, // missing parameter price
'20014': InvalidOrder, // price must be greater than 0
'20015': InvalidOrder, // missing parameter time_in_force
'20016': InvalidOrder, // invalid value for parameter time_in_force
'20017': InvalidOrder, // missing parameter order_id
'20018': InvalidOrder, // invalid date format
'20019': InvalidOrder, // missing parameter stop_px
'20020': InvalidOrder, // missing parameter base_price
'20021': InvalidOrder, // missing parameter stop_order_id
'20022': BadRequest, // missing parameter leverage
'20023': BadRequest, // leverage must be a number
'20031': BadRequest, // leverage must be greater than zero
'20070': BadRequest, // missing parameter margin
'20071': BadRequest, // margin must be greater than zero
'20084': BadRequest, // order_id or order_link_id is required
'30001': BadRequest, // order_link_id is repeated
'30003': InvalidOrder, // qty must be more than the minimum allowed
'30004': InvalidOrder, // qty must be less than the maximum allowed
'30005': InvalidOrder, // price exceeds maximum allowed
'30007': InvalidOrder, // price exceeds minimum allowed
'30008': InvalidOrder, // invalid order_type
'30009': ExchangeError, // no position found
'30010': InsufficientFunds, // insufficient wallet balance
'30011': PermissionDenied, // operation not allowed as position is undergoing liquidation
'30012': PermissionDenied, // operation not allowed as position is undergoing ADL
'30013': PermissionDenied, // position is in liq or adl status
'30014': InvalidOrder, // invalid closing order, qty should not greater than size
'30015': InvalidOrder, // invalid closing order, side should be opposite
'30016': ExchangeError, // TS and SL must be cancelled first while closing position
'30017': InvalidOrder, // estimated fill price cannot be lower than current Buy liq_price
'30018': InvalidOrder, // estimated fill price cannot be higher than current Sell liq_price
'30019': InvalidOrder, // cannot attach TP/SL params for non-zero position when placing non-opening position order
'30020': InvalidOrder, // position already has TP/SL params
'30021': InvalidOrder, // cannot afford estimated position_margin
'30022': InvalidOrder, // estimated buy liq_price cannot be higher than current mark_price
'30023': InvalidOrder, // estimated sell liq_price cannot be lower than current mark_price
'30024': InvalidOrder, // cannot set TP/SL/TS for zero-position
'30025': InvalidOrder, // trigger price should bigger than 10% of last price
'30026': InvalidOrder, // price too high
'30027': InvalidOrder, // price set for Take profit should be higher than Last Traded Price
'30028': InvalidOrder, // price set for Stop loss should be between Liquidation price and Last Traded Price
'30029': InvalidOrder, // price set for Stop loss should be between Last Traded Price and Liquidation price
'30030': InvalidOrder, // price set for Take profit should be lower than Last Traded Price
'30031': InsufficientFunds, // insufficient available balance for order cost
'30032': InvalidOrder, // order has been filled or cancelled
'30033': RateLimitExceeded, // The number of stop orders exceeds maximum limit allowed
'30034': OrderNotFound, // no order found
'30035': RateLimitExceeded, // too fast to cancel
'30036': ExchangeError, // the expected position value after order execution exceeds the current risk limit
'30037': InvalidOrder, // order already cancelled
'30041': ExchangeError, // no position found
'30042': InsufficientFunds, // insufficient wallet balance
'30043': InvalidOrder, // operation not allowed as position is undergoing liquidation
'30044': InvalidOrder, // operation not allowed as position is undergoing AD
'30045': InvalidOrder, // operation not allowed as position is not normal status
'30049': InsufficientFunds, // insufficient available balance
'30050': ExchangeError, // any adjustments made will trigger immediate liquidation
'30051': ExchangeError, // due to risk limit, cannot adjust leverage
'30052': ExchangeError, // leverage can not less than 1
'30054': ExchangeError, // position margin is invalid
'30057': ExchangeError, // requested quantity of contracts exceeds risk limit
'30063': ExchangeError, // reduce-only rule not satisfied
'30067': InsufficientFunds, // insufficient available balance
'30068': ExchangeError, // exit value must be positive
'30074': InvalidOrder, // can't create the stop order, because you expect the order will be triggered when the LastPrice(or IndexPrice、 MarkPrice, determined by trigger_by) is raising to stop_px, but the LastPrice(or IndexPrice、 MarkPrice) is already equal to or greater than stop_px, please adjust base_price or stop_px
'30075': InvalidOrder, // can't create the stop order, because you expect the order will be triggered when the LastPrice(or IndexPrice、 MarkPrice, determined by trigger_by) is falling to stop_px, but the LastPrice(or IndexPrice、 MarkPrice) is already equal to or less than stop_px, please adjust base_price or stop_px
'30078': ExchangeError, // {"ret_code":30078,"ret_msg":"","ext_code":"","ext_info":"","result":null,"time_now":"1644853040.916000","rate_limit_status":73,"rate_limit_reset_ms":1644853040912,"rate_limit":75}
// '30084': BadRequest, // Isolated not modified, see handleErrors below
'33004': AuthenticationError, // apikey already expired
'34026': ExchangeError, // the limit is no change
'35015': BadRequest, // {"ret_code":35015,"ret_msg":"Qty not in range","ext_code":"","ext_info":"","result":null,"time_now":"1652277215.821362","rate_limit_status":99,"rate_limit_reset_ms":1652277215819,"rate_limit":100}
'130021': InsufficientFunds, // {"ret_code":130021,"ret_msg":"orderfix price failed for CannotAffordOrderCost.","ext_code":"","ext_info":"","result":null,"time_now":"1644588250.204878","rate_limit_status":98,"rate_limit_reset_ms":1644588250200,"rate_limit":100}
'3100116': BadRequest, // {"retCode":3100116,"retMsg":"Order quantity below the lower limit 0.01.","result":null,"retExtMap":{"key0":"0.01"}}
'3100198': BadRequest, // {"retCode":3100198,"retMsg":"orderLinkId can not be empty.","result":null,"retExtMap":{}}
'3200300': InsufficientFunds, // {"retCode":3200300,"retMsg":"Insufficient margin balance.","result":null,"retExtMap":{}}
},
'broad': {
'unknown orderInfo': OrderNotFound, // {"ret_code":-1,"ret_msg":"unknown orderInfo","ext_code":"","ext_info":"","result":null,"time_now":"1584030414.005545","rate_limit_status":99,"rate_limit_reset_ms":1584030414003,"rate_limit":100}
'invalid api_key': AuthenticationError, // {"ret_code":10003,"ret_msg":"invalid api_key","ext_code":"","ext_info":"","result":null,"time_now":"1599547085.415797"}
},
},
'precisionMode': TICK_SIZE,
'options': {
'createMarketBuyOrderRequiresPrice': true,
'marketTypes': {
'BTC/USDT': 'linear',
'ETH/USDT': 'linear',
'BNB/USDT': 'linear',
'ADA/USDT': 'linear',
'DOGE/USDT': 'linear',
'XRP/USDT': 'linear',
'DOT/USDT': 'linear',
'UNI/USDT': 'linear',
'BCH/USDT': 'linear',
'LTC/USDT': 'linear',
'SOL/USDT': 'linear',
'LINK/USDT': 'linear',
'MATIC/USDT': 'linear',
'ETC/USDT': 'linear',
'FIL/USDT': 'linear',
'EOS/USDT': 'linear',
'AAVE/USDT': 'linear',
'XTZ/USDT': 'linear',
'SUSHI/USDT': 'linear',
'XEM/USDT': 'linear',
'BTC/USD': 'inverse',
'ETH/USD': 'inverse',
'EOS/USD': 'inverse',
'XRP/USD': 'inverse',
},
'defaultType': 'linear', // linear, inverse, futures
//
// ^
// |
// | this will be replaced with the following soon |
// |
// v
//
// 'defaultType': 'swap', // swap, spot, future, option
'code': 'BTC',
'cancelAllOrders': {
// 'method': 'v2PrivatePostOrderCancelAll', // v2PrivatePostStopOrderCancelAll
},
'recvWindow': 5 * 1000, // 5 sec default
'timeDifference': 0, // the difference between system clock and exchange server clock
'adjustForTimeDifference': false, // controls the adjustment logic upon instantiation
'defaultSettle': 'USDT', // USDC for USDC settled markets
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'taker': 0.00075,
'maker': -0.00025,
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {},
'deposit': {},
},
},
});
}
nonce () {
return this.milliseconds () - this.options['timeDifference'];
}
async fetchTime (params = {}) {
const response = await this.publicGetV2PublicTime (params);
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: {},
// time_now: '1583933682.448826'
// }
//
return this.safeTimestamp (response, 'time_now');
}
async fetchMarkets (params = {}) {
if (this.options['adjustForTimeDifference']) {
await this.loadTimeDifference ();
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchMarkets', undefined, params);
if (type === 'spot') {
// spot and swap ids are equal
// so they can't be loaded together
const spotMarkets = await this.fetchSpotMarkets (params);
return spotMarkets;
}
const contractMarkets = await this.fetchSwapAndFutureMarkets (params);
const usdcMarkets = await this.fetchUSDCMarkets (params);
let markets = contractMarkets;
markets = this.arrayConcat (markets, usdcMarkets);
return markets;
}
async fetchSpotMarkets (params) {
const response = await this.publicGetSpotV1Symbols (params);
//
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":[
// {
// "name":"BTCUSDT",
// "alias":"BTCUSDT",
// "baseCurrency":"BTC",
// "quoteCurrency":"USDT",
// "basePrecision":"0.000001",
// "quotePrecision":"0.00000001",
// "minTradeQuantity":"0.000158",
// "minTradeAmount":"10",
// "maxTradeQuantity":"4",
// "maxTradeAmount":"100000",
// "minPricePrecision":"0.01",
// "category":1,
// "showStatus":true
// },
// ]
// }
const markets = this.safeValue (response, 'result', []);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'name');
const baseId = this.safeString (market, 'baseCurrency');
const quoteId = this.safeString (market, 'quoteCurrency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const active = this.safeValue (market, 'showStatus');
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': undefined,
'baseId': baseId,
'quoteId': quoteId,
'settleId': undefined,
'type': 'spot',
'spot': true,
'margin': undefined,
'swap': false,
'future': false,
'option': false,
'active': active,
'contract': false,
'linear': undefined,
'inverse': undefined,
'taker': undefined,
'maker': undefined,
'contractSize': undefined,
'expiry': undefined,
'expiryDatetime': undefined,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': this.safeNumber (market, 'basePrecision'),
'price': this.safeNumber (market, 'quotePrecision'),
},
'limits': {
'leverage': {
'min': this.parseNumber ('1'),
'max': undefined,
},
'amount': {
'min': this.safeNumber (market, 'minTradeQuantity'),
'max': this.safeNumber (market, 'maxTradeQuantity'),
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'minTradeAmount'),
'max': this.safeNumber (market, 'maxTradeAmount'),
},
},
'info': market,
});
}
return result;
}
async fetchSwapAndFutureMarkets (params) {
const response = await this.publicGetV2PublicSymbols (params);
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// // inverse swap
// {
// "name":"BTCUSD",
// "alias":"BTCUSD",
// "status":"Trading",
// "base_currency":"BTC",
// "quote_currency":"USD",
// "price_scale":2,
// "taker_fee":"0.00075",
// "maker_fee":"-0.00025",
// "leverage_filter":{"min_leverage":1,"max_leverage":100,"leverage_step":"0.01"},
// "price_filter":{"min_price":"0.5","max_price":"999999","tick_size":"0.5"},
// "lot_size_filter":{"max_trading_qty":1000000,"min_trading_qty":1,"qty_step":1}
// },
// // linear swap
// {
// "name":"BTCUSDT",
// "alias":"BTCUSDT",
// "status":"Trading",
// "base_currency":"BTC",
// "quote_currency":"USDT",
// "price_scale":2,
// "taker_fee":"0.00075",
// "maker_fee":"-0.00025",
// "leverage_filter":{"min_leverage":1,"max_leverage":100,"leverage_step":"0.01"},
// "price_filter":{"min_price":"0.5","max_price":"999999","tick_size":"0.5"},
// "lot_size_filter":{"max_trading_qty":100,"min_trading_qty":0.001, "qty_step":0.001}
// },
// inverse futures
// {
// "name": "BTCUSDU22",
// "alias": "BTCUSD0930",
// "status": "Trading",
// "base_currency": "BTC",
// "quote_currency": "USD",
// "price_scale": "2",
// "taker_fee": "0.0006",
// "maker_fee": "0.0001",
// "funding_interval": "480",
// "leverage_filter": {
// "min_leverage": "1",
// "max_leverage": "100",
// "leverage_step": "0.01"
// },
// "price_filter": {
// "min_price": "0.5",
// "max_price": "999999",
// "tick_size": "0.5"
// },
// "lot_size_filter": {
// "max_trading_qty": "1000000",
// "min_trading_qty": "1",
// "qty_step": "1",
// "post_only_max_trading_qty": "5000000"
// }
// }
// ],
// "time_now":"1642369942.072113"
// }
//
const markets = this.safeValue (response, 'result', []);
const result = [];
const options = this.safeValue (this.options, 'fetchMarkets', {});
const linearQuoteCurrencies = this.safeValue (options, 'linear', { 'USDT': true });
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'name');
const baseId = this.safeString (market, 'base_currency');
const quoteId = this.safeString (market, 'quote_currency');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const linear = (quote in linearQuoteCurrencies);
let symbol = base + '/' + quote;
const baseQuote = base + quote;
let type = 'swap';
if (baseQuote !== id) {
type = 'future';
}
const lotSizeFilter = this.safeValue (market, 'lot_size_filter', {});
const priceFilter = this.safeValue (market, 'price_filter', {});
const leverage = this.safeValue (market, 'leverage_filter', {});
const status = this.safeString (market, 'status');
let active = undefined;
if (status !== undefined) {
active = (status === 'Trading');
}
const swap = (type === 'swap');
const future = (type === 'future');
let expiry = undefined;
let expiryDatetime = undefined;
const settleId = linear ? quoteId : baseId;
const settle = this.safeCurrencyCode (settleId);
symbol = symbol + ':' + settle;
if (future) {
// we have to do some gymnastics here because bybit
// only provides the day and month regarding the contract expiration
const alias = this.safeString (market, 'alias'); // BTCUSD0930
const aliasDate = alias.slice (-4); // 0930
const aliasMonth = aliasDate.slice (0, 2); // 09
const aliasDay = aliasDate.slice (2, 4); // 30
const dateNow = this.yyyymmdd (this.milliseconds ());
const dateParts = dateNow.split ('-');
const year = this.safeValue (dateParts, 0);
const artificial8601Date = year + '-' + aliasMonth + '-' + aliasDay + 'T00:00:00.000Z';
expiryDatetime = artificial8601Date;
expiry = this.parse8601 (expiryDatetime);
symbol = symbol + '-' + this.yymmdd (expiry);
}
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': false,
'margin': undefined,
'swap': swap,
'future': future,
'option': false,
'active': active,
'contract': true,
'linear': linear,
'inverse': !linear,
'taker': this.safeNumber (market, 'taker_fee'),
'maker': this.safeNumber (market, 'maker_fee'),
'contractSize': undefined, // todo
'expiry': expiry,
'expiryDatetime': expiryDatetime,
'strike': undefined,
'optionType': undefined,
'precision': {
'amount': this.safeNumber (lotSizeFilter, 'qty_step'),
'price': this.safeNumber (priceFilter, 'tick_size'),
},
'limits': {
'leverage': {
'min': this.parseNumber ('1'),
'max': this.safeNumber (leverage, 'max_leverage', 1),
},
'amount': {
'min': this.safeNumber (lotSizeFilter, 'min_trading_qty'),
'max': this.safeNumber (lotSizeFilter, 'max_trading_qty'),
},
'price': {
'min': this.safeNumber (priceFilter, 'min_price'),
'max': this.safeNumber (priceFilter, 'max_price'),
},
'cost': {
'min': undefined,
'max': undefined,
},
},
'info': market,
});
}
return result;
}
async fetchUSDCMarkets (params) {
const linearOptionsResponse = await this.publicGetOptionUsdcOpenapiPublicV1Symbols (params);
const usdcLinearPerpetualSwaps = await this.publicGetPerpetualUsdcOpenapiPublicV1Symbols (params);
//
// USDC linear options
// {
// "retCode":0,
// "retMsg":"success",
// "result":{
// "resultTotalSize":424,
// "cursor":"0%2C500",
// "dataList":[
// {
// "symbol":"BTC-24JUN22-300000-C",
// "status":"ONLINE",
// "baseCoin":"BTC",
// "quoteCoin":"USD",
// "settleCoin":"USDC",
// "takerFee":"0.0003",
// "makerFee":"0.0003",
// "minLeverage":"",
// "maxLeverage":"",
// "leverageStep":"",
// "minOrderPrice":"0.5",
// "maxOrderPrice":"10000000",
// "minOrderSize":"0.01",
// "maxOrderSize":"200",
// "tickSize":"0.5",
// "minOrderSizeIncrement":"0.01",
// "basicDeliveryFeeRate":"0.00015",
// "deliveryTime":"1656057600000"
// },
// {
// "symbol":"BTC-24JUN22-300000-P",
// "status":"ONLINE",
// "baseCoin":"BTC",
// "quoteCoin":"USD",
// "settleCoin":"USDC",
// "takerFee":"0.0003",
// "makerFee":"0.0003",
// "minLeverage":"",
// "maxLeverage":"",
// "leverageStep":"",
// "minOrderPrice":"0.5",
// "maxOrderPrice":"10000000",
// "minOrderSize":"0.01",
// "maxOrderSize":"200",
// "tickSize":"0.5",
// "minOrderSizeIncrement":"0.01",
// "basicDeliveryFeeRate":"0.00015",
// "deliveryTime":"1656057600000"
// },
// ]
// }
// }
//
// USDC linear perpetual swaps
//
// {
// "retCode":0,
// "retMsg":"",
// "result":[
// {
// "symbol":"BTCPERP",
// "status":"ONLINE",
// "baseCoin":"BTC",
// "quoteCoin":"USD",
// "takerFeeRate":"0.00075",
// "makerFeeRate":"-0.00025",
// "minLeverage":"1",
// "maxLeverage":"100",
// "leverageStep":"0.01",
// "minPrice":"0.50",
// "maxPrice":"999999.00",
// "tickSize":"0.50",
// "maxTradingQty":"5.000",
// "minTradingQty":"0.001",
// "qtyStep":"0.001",
// "deliveryFeeRate":"",
// "deliveryTime":"0"
// }
// ]
// }
//
const optionsResponse = this.safeValue (linearOptionsResponse, 'result', []);
const options = this.safeValue (optionsResponse, 'dataList', []);
const contractsResponse = this.safeValue (usdcLinearPerpetualSwaps, 'result', []);
const markets = this.arrayConcat (options, contractsResponse);
const result = [];
// all markets fetched here are linear
const linear = true;
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'symbol');
const baseId = this.safeString (market, 'baseCoin');
const quoteId = this.safeString (market, 'quoteCoin');
let settleId = this.safeString (market, 'settleCoin');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
let settle = this.safeCurrencyCode (settleId);
let symbol = base + '/' + quote;
let type = 'swap';
if (settleId !== undefined) {
type = 'option';
}
const swap = (type === 'swap');
const option = (type === 'option');
const leverage = this.safeValue (market, 'leverage_filter', {});
const status = this.safeString (market, 'status');
let active = undefined;
if (status !== undefined) {
active = (status === 'ONLINE');
}
let expiry = undefined;
let expiryDatetime = undefined;
let strike = undefined;
let optionType = undefined;
if (settle === undefined) {
settleId = 'USDC';
settle = 'USDC';
}
symbol = symbol + ':' + settle;
if (option) {
expiry = this.safeInteger (market, 'deliveryTime');
expiryDatetime = this.iso8601 (expiry);
const splitId = id.split ('-');
strike = this.safeString (splitId, 2);
const optionLetter = this.safeString (splitId, 3);
symbol = symbol + '-' + this.yymmdd (expiry) + ':' + strike + ':' + optionLetter;
if (optionLetter === 'P') {
optionType = 'put';
} else if (optionLetter === 'C') {
optionType = 'call';
}
}
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': false,
'margin': undefined,
'swap': swap,
'future': false,
'option': option,
'active': active,
'contract': true,
'linear': linear,
'inverse': !linear,
'taker': this.safeNumber (market, 'taker_fee'),
'maker': this.safeNumber (market, 'maker_fee'),
'contractSize': undefined,
'expiry': expiry,
'expiryDatetime': expiryDatetime,
'strike': strike,
'optionType': optionType,
'precision': {
'amount': this.safeNumber (market, 'minOrderSizeIncrement'),
'price': this.safeNumber (market, 'tickSize'),
},
'limits': {
'leverage': {
'min': this.safeNumber (leverage, 'minLeverage', 1),
'max': this.safeNumber (leverage, 'maxLeverage', 1),
},
'amount': {
'min': this.safeNumber (market, 'minOrderSize'),
'max': this.safeNumber (market, 'maxOrderSize'),
},
'price': {
'min': this.safeNumber (market, 'minOrderPrice'),
'max': this.safeNumber (market, 'maxOrderPrice'),
},
'cost': {
'min': undefined,
'max': undefined,
},
},
'info': market,
});
}
return result;
}
parseTicker (ticker, market = undefined) {
// spot
//
// {
// "time": "1651743420061",
// "symbol": "BTCUSDT",
// "bestBidPrice": "39466.75",
// "bestAskPrice": "39466.83",
// "volume": "4396.082921",
// "quoteVolume": "172664909.03216557",
// "lastPrice": "39466.71",
// "highPrice": "40032.79",
// "lowPrice": "38602.39",
// "openPrice": "39031.53"
// }
//
// linear usdt/ inverse swap and future
// {
// "symbol": "BTCUSDT",
// "bid_price": "39458",
// "ask_price": "39458.5",
// "last_price": "39458.00",
// "last_tick_direction": "ZeroMinusTick",
// "prev_price_24h": "39059.50",
// "price_24h_pcnt": "0.010202",
// "high_price_24h": "40058.50",
// "low_price_24h": "38575.50",
// "prev_price_1h": "39534.00",
// "price_1h_pcnt": "-0.001922",
// "mark_price": "39472.49",
// "index_price": "39469.81",
// "open_interest": "28343.61",
// "open_value": "0.00",
// "total_turnover": "85303326477.54",
// "turnover_24h": "4221589085.06",
// "total_volume": "30628792.45",
// "volume_24h": "107569.75",
// "funding_rate": "0.0001",
// "predicted_funding_rate": "0.0001",
// "next_funding_time": "2022-05-05T16:00:00Z",
// "countdown_hour": "7",
// "delivery_fee_rate": "",
// "predicted_delivery_price": "",
// "delivery_time": ""
// }
//
// usdc option/ swap
// {
// "symbol": "BTC-30SEP22-400000-C",
// "bid": "0",
// "bidIv": "0",
// "bidSize": "0",
// "ask": "15",
// "askIv": "1.1234",
// "askSize": "0.01",
// "lastPrice": "5",
// "openInterest": "0.03",
// "indexPrice": "39458.6",
// "markPrice": "0.51901394",
// "markPriceIv": "0.9047",
// "change24h": "0",
// "high24h": "0",
// "low24h": "0",
// "volume24h": "0",
// "turnover24h": "0",
// "totalVolume": "1",
// "totalTurnover": "4",
// "predictedDeliveryPrice": "0",
// "underlyingPrice": "40129.73",
// "delta": "0.00010589",
// "gamma": "0.00000002",
// "vega": "0.10670892",
// "theta": "-0.03262827"
// }
//
const timestamp = this.safeInteger (ticker, 'time');
const marketId = this.safeString (ticker, 'symbol');
const symbol = this.safeSymbol (marketId, market);
const last = this.safeString2 (ticker, 'last_price', 'lastPrice');
const open = this.safeString2 (ticker, 'prev_price_24h', 'openPrice');
let percentage = this.safeString2 (ticker, 'price_24h_pcnt', 'change24h');
percentage = Precise.stringMul (percentage, '100');
let baseVolume = this.safeString2 (ticker, 'turnover_24h', 'turnover24h');
if (baseVolume === undefined) {
baseVolume = this.safeString (ticker, 'volume');
}
let quoteVolume = this.safeString2 (ticker, 'volume_24h', 'volume24h');
if (quoteVolume === undefined) {
quoteVolume = this.safeString (ticker, 'quoteVolume');
}
let bid = this.safeString2 (ticker, 'bid_price', 'bid');
if (bid === undefined) {
bid = this.safeString (ticker, 'bestBidPrice');
}
let ask = this.safeString2 (ticker, 'ask_price', 'ask');
if (ask === undefined) {
ask = this.safeString (ticker, 'bestAskPrice');
}
let high = this.safeString2 (ticker, 'high_price_24h', 'high24h');
if (high === undefined) {
high = this.safeString (ticker, 'highPrice');
}
let low = this.safeString2 (ticker, 'low_price_24h', 'low24h');
if (low === undefined) {
low = this.safeString (ticker, 'lowPrice');
}
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': high,
'low': low,
'bid': bid,
'bidVolume': this.safeString (ticker, 'bidSize'),
'ask': ask,
'askVolume': this.safeString (ticker, 'askSize'),
'vwap': undefined,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': percentage,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market, false);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let method = undefined;
const isUsdcSettled = market['settle'] === 'USDC';
if (market['spot']) {
method = 'publicGetSpotQuoteV1Ticker24hr';
} else if (!isUsdcSettled) {
// inverse perpetual // usdt linear // inverse futures
method = 'publicGetV2PublicTickers';
} else if (market['option']) {
// usdc option
method = 'publicGetOptionUsdcOpenapiPublicV1Tick';
} else {
// usdc swap
method = 'publicGetPerpetualUsdcOpenapiPublicV1Tick';
}
const request = {
'symbol': market['id'],
};
const response = await this[method] (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// symbol: 'BTCUSD',
// bid_price: '7680',
// ask_price: '7680.5',
// last_price: '7680.00',
// last_tick_direction: 'MinusTick',
// prev_price_24h: '7870.50',
// price_24h_pcnt: '-0.024204',
// high_price_24h: '8035.00',
// low_price_24h: '7671.00',
// prev_price_1h: '7780.00',
// price_1h_pcnt: '-0.012853',
// mark_price: '7683.27',
// index_price: '7682.74',
// open_interest: 188829147,
// open_value: '23670.06',
// total_turnover: '25744224.90',
// turnover_24h: '102997.83',
// total_volume: 225448878806,
// volume_24h: 809919408,
// funding_rate: '0.0001',
// predicted_funding_rate: '0.0001',
// next_funding_time: '2020-03-12T00:00:00Z',
// countdown_hour: 7
// }
// ],
// time_now: '1583948195.818255'
// }
// usdc ticker
// {
// "retCode": 0,
// "retMsg": "SUCCESS",
// "result": {
// "symbol": "BTC-28JAN22-250000-C",
// "bid": "0",
// "bidIv": "0",
// "bidSize": "0",
// "ask": "0",
// "askIv": "0",
// "askSize": "0",
// "lastPrice": "0",
// "openInterest": "0",
// "indexPrice": "56171.79000000",
// "markPrice": "12.72021285",
// "markPriceIv": "1.1701",
// "change24h": "0",
// "high24h": "0",
// "low24h": "0",
// "volume24h": "0",
// "turnover24h": "0",
// "totalVolume": "0",
// "totalTurnover": "0",
// "predictedDeliveryPrice": "0",
// "underlyingPrice": "57039.61000000",
// "delta": "0.00184380",
// "gamma": "0.00000022",
// "vega": "1.35132531",
// "theta": "-1.33819821"
// }
// }
//
const result = this.safeValue (response, 'result', []);
let rawTicker = undefined;
if (Array.isArray (result)) {
rawTicker = this.safeValue (result, 0);
} else {
rawTicker = result;
}
const ticker = this.parseTicker (rawTicker, market);
return ticker;
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let type = undefined;
let market = undefined;
let isUsdcSettled = undefined;
if (symbols !== undefined) {
const symbol = this.safeValue (symbols, 0);
market = this.market (symbol);
type = market['type'];
isUsdcSettled = market['settle'] === 'USDC';
} else {
[ type, params ] = this.handleMarketTypeAndParams ('fetchTickers', market, params);
if (type !== 'spot') {
let defaultSettle = this.safeString (this.options, 'defaultSettle', 'USDT');
defaultSettle = this.safeString2 (params, 'settle', 'defaultSettle', isUsdcSettled);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = defaultSettle === 'USDC';
}
}
let method = undefined;
if (type === 'spot') {
method = 'publicGetSpotQuoteV1Ticker24hr';
} else if (!isUsdcSettled) {
// inverse perpetual // usdt linear // inverse futures
method = 'publicGetV2PublicTickers';
} else {
throw new NotSupported (this.id + ' fetchTickers() is not supported for USDC markets');
}
const response = await this[method] (params);
const result = this.safeValue (response, 'result', []);
const tickers = {};
for (let i = 0; i < result.length; i++) {
const ticker = this.parseTicker (result[i]);
const symbol = ticker['symbol'];
tickers[symbol] = ticker;
}
return this.filterByArray (tickers, 'symbol', symbols);
}
parseOHLCV (ohlcv, market = undefined) {
//
// inverse perpetual BTC/USD
//
// {
// symbol: 'BTCUSD',
// interval: '1',
// open_time: 1583952540,
// open: '7760.5',
// high: '7764',
// low: '7757',
// close: '7763.5',
// volume: '1259766',
// turnover: '162.32773718999994'
// }
//
// linear perpetual BTC/USDT
//
// {
// "id":143536,
// "symbol":"BTCUSDT",
// "period":"15",
// "start_at":1587883500,
// "volume":1.035,
// "open":7540.5,
// "high":7541,
// "low":7540.5,
// "close":7541
// }
//
// usdc perpetual
// {
// "symbol":"BTCPERP",
// "volume":"0.01",
// "period":"1",
// "openTime":"1636358160",
// "open":"66001.50",
// "high":"66001.50",
// "low":"66001.50",
// "close":"66001.50",
// "turnover":"1188.02"
// }
//
// spot
// [
// 1651837620000, // start tame
// "35831.5", // open
// "35831.5", // high
// "35801.93", // low
// "35817.11", // close
// "1.23453", // volume
// 0, // end time
// "44213.97591627", // quote asset volume
// 24, // number of trades
// "0", // taker base volume
// "0" // taker quote volume
// ]
//
if (Array.isArray (ohlcv)) {
return [
this.safeNumber (ohlcv, 0),
this.safeNumber (ohlcv, 1),
this.safeNumber (ohlcv, 2),
this.safeNumber (ohlcv, 3),
this.safeNumber (ohlcv, 4),
this.safeNumber (ohlcv, 5),
];
}
let timestamp = this.safeTimestamp2 (ohlcv, 'open_time', 'openTime');
if (timestamp === undefined) {
timestamp = this.safeTimestamp (ohlcv, 'start_at');
}
return [
timestamp,
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'high'),
this.safeNumber (ohlcv, 'low'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber2 (ohlcv, 'volume', 'turnover'),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const price = this.safeString (params, 'price');
params = this.omit (params, 'price');
const request = {
'symbol': market['id'],
};
const duration = this.parseTimeframe (timeframe);
const now = this.seconds ();
let sinceTimestamp = undefined;
if (since === undefined) {
if (limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOHLCV() requires a since argument or a limit argument');
} else {
sinceTimestamp = now - limit * duration;
}
} else {
sinceTimestamp = parseInt (since / 1000);
}
if (limit !== undefined) {
request['limit'] = limit; // max 200, default 200
}
let method = undefined;
let intervalKey = 'interval';
let sinceKey = 'from';
const isUsdcSettled = market['settle'] === 'USDC';
if (market['spot']) {
method = 'publicGetSpotQuoteV1Kline';
} else if (market['contract'] && !isUsdcSettled) {
if (market['linear']) {
// linear swaps/futures
const methods = {
'mark': 'publicGetPublicLinearMarkPriceKline',
'index': 'publicGetPublicLinearIndexPriceKline',
'premium': 'publicGetPublicLinearPremiumIndexKline',
};
method = this.safeValue (methods, price, 'publicGetPublicLinearKline');
} else {
// inverse swaps/ futures
const methods = {
'mark': 'publicGetV2PublicMarkPriceKline',
'index': 'publicGetV2PublicIndexPriceKline',
'premium': 'publicGetV2PublicPremiumPriceKline',
};
method = this.safeValue (methods, price, 'publicGetV2PublicKlineList');
}
} else {
// usdc markets
if (market['option']) {
throw new NotSupported (this.id + ' fetchOHLCV() is not supported for USDC options markets');
}
intervalKey = 'period';
sinceKey = 'startTime';
const methods = {
'mark': 'publicGetPerpetualUsdcOpenapiPublicV1MarkPriceKline',
'index': 'publicGetPerpetualUsdcOpenapiPublicV1IndexPriceKline',
'premium': 'publicGetPerpetualUsdcOpenapiPublicV1PremiumPriceKline',
};
method = this.safeValue (methods, price, 'publicGetPerpetualUsdcOpenapiPublicV1KlineList');
}
// spot markets use the same interval format as ccxt
// so we don't need to convert it
request[intervalKey] = market['spot'] ? timeframe : this.timeframes[timeframe];
request[sinceKey] = sinceTimestamp;
const response = await this[method] (this.extend (request, params));
//
// inverse perpetual BTC/USD
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// symbol: 'BTCUSD',
// interval: '1',
// open_time: 1583952540,
// open: '7760.5',
// high: '7764',
// low: '7757',
// close: '7763.5',
// volume: '1259766',
// turnover: '162.32773718999994'
// },
// ],
// time_now: '1583953082.397330'
// }
//
// linear perpetual BTC/USDT
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// {
// "id":143536,
// "symbol":"BTCUSDT",
// "period":"15",
// "start_at":1587883500,
// "volume":1.035,
// "open":7540.5,
// "high":7541,
// "low":7540.5,
// "close":7541
// }
// ],
// "time_now":"1587884120.168077"
// }
// spot
// {
// "ret_code": "0",
// "ret_msg": null,
// "result": [
// [
// 1651837620000,
// "35831.5",
// "35831.5",
// "35801.93",
// "35817.11",
// "1.23453",
// 0,
// "44213.97591627",
// 24,
// "0",
// "0"
// ]
// ],
// "ext_code": null,
// "ext_info": null
// }
//
const result = this.safeValue (response, 'result', {});
return this.parseOHLCVs (result, market, timeframe, since, limit);
}
async fetchFundingRate (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const method = market['linear'] ? 'publicLinearGetFundingPrevFundingRate' : 'v2PublicGetFundingPrevFundingRate';
// TODO const method = market['linear'] ? 'publicGetPublicLinearFundingPrevFundingRate' : 'publicGetV2PublicFundingRate ???? throws ExchangeError';
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "symbol":"BTCUSDT",
// "funding_rate":0.00006418,
// "funding_rate_timestamp":"2022-03-11T16:00:00.000Z"
// },
// "time_now":"1647040818.724895"
// }
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "symbol":"BTCUSD",
// "funding_rate":"0.00009536",
// "funding_rate_timestamp":1647014400
// },
// "time_now":"1647040852.515724"
// }
//
const result = this.safeValue (response, 'result');
const fundingRate = this.safeNumber (result, 'funding_rate');
let fundingTimestamp = this.parse8601 (this.safeString (result, 'funding_rate_timestamp'));
fundingTimestamp = this.safeTimestamp (result, 'funding_rate_timestamp', fundingTimestamp);
const currentTime = this.milliseconds ();
return {
'info': result,
'symbol': symbol,
'markPrice': undefined,
'indexPrice': undefined,
'interestRate': undefined,
'estimatedSettlePrice': undefined,
'timestamp': currentTime,
'datetime': this.iso8601 (currentTime),
'fundingRate': fundingRate,
'fundingTimestamp': fundingTimestamp,
'fundingDatetime': this.iso8601 (fundingTimestamp),
'nextFundingRate': undefined,
'nextFundingTimestamp': undefined,
'nextFundingDatetime': undefined,
'previousFundingRate': undefined,
'previousFundingTimestamp': undefined,
'previousFundingDatetime': undefined,
};
}
async fetchIndexOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
if (since === undefined && limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchIndexOHLCV() requires a since argument or a limit argument');
}
const request = {
'price': 'index',
};
return await this.fetchOHLCV (symbol, timeframe, since, limit, this.extend (request, params));
}
async fetchMarkOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
if (since === undefined && limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMarkOHLCV() requires a since argument or a limit argument');
}
const request = {
'price': 'mark',
};
return await this.fetchOHLCV (symbol, timeframe, since, limit, this.extend (request, params));
}
async fetchPremiumIndexOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
if (since === undefined && limit === undefined) {
throw new ArgumentsRequired (this.id + ' fetchPremiumIndexOHLCV() requires a since argument or a limit argument');
}
const request = {
'price': 'premiumIndex',
};
return await this.fetchOHLCV (symbol, timeframe, since, limit, this.extend (request, params));
}
parseTrade (trade, market = undefined) {
//
// public spot
//
// {
// "price": "39548.68",
// "time": "1651748717850",
// "qty": "0.166872",
// "isBuyerMaker": true
// }
//
// public linear/inverse swap/future
//
// {
// "id": "112348766532",
// "symbol": "BTCUSDT",
// "price": "39536",
// "qty": "0.011",
// "side": "Buy",
// "time": "2022-05-05T11:16:02.000Z",
// "trade_time_ms": "1651749362196"
// }
//
// public usdc market
//
// {
// "symbol": "BTC-30SEP22-400000-C",
// "orderQty": "0.010",
// "orderPrice": "5.00",
// "time": "1651104300208"
// }
//
// private futures/swap
//
// {
// "order_id": "b020b4bc-6fe2-45b5-adbc-dd07794f9746",
// "order_link_id": "",
// "side": "Buy",
// "symbol": "AAVEUSDT",
// "exec_id": "09abe8f0-aea6-514e-942b-7da8cb935120",
// "price": "269.3",
// "order_price": "269.3",
// "order_qty": "0.1",
// "order_type": "Market",
// "fee_rate": "0.00075",
// "exec_price": "256.35",
// "exec_type": "Trade",
// "exec_qty": "0.1",
// "exec_fee": "0.01922625",
// "exec_value": "25.635",
// "leaves_qty": "0",
// "closed_size": "0",
// "last_liquidity_ind": "RemovedLiquidity",
// "trade_time": "1638276374",
// "trade_time_ms": "1638276374312"
// }
//
// spot
// {
// "id": "1149467000412631552",
// "symbol": "LTCUSDT",
// "symbolName": "LTCUSDT",
// "orderId": "1149467000244912384",
// "ticketId": "2200000000002601358",
// "matchOrderId": "1149465793552007078",
// "price": "100.19",
// "qty": "0.09973",
// "commission": "0.0099919487",
// "commissionAsset": "USDT",
// "time": "1651763144465",
// "isBuyer": false,
// "isMaker": false,
// "fee": {
// "feeTokenId": "USDT",
// "feeTokenName": "USDT",
// "fee": "0.0099919487"
// },
// "feeTokenId": "USDT",
// "feeAmount": "0.0099919487",
// "makerRebate": "0"
// }
//
const id = this.safeString2 (trade, 'id', 'exec_id');
const marketId = this.safeString (trade, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let amountString = this.safeString2 (trade, 'qty', 'exec_qty');
if (amountString === undefined) {
amountString = this.safeString (trade, 'orderQty');
}
let priceString = this.safeString2 (trade, 'exec_price', 'price');
if (priceString === undefined) {
priceString = this.safeString (trade, 'orderPrice');
}
const costString = this.safeString (trade, 'exec_value');
let timestamp = this.parse8601 (this.safeString (trade, 'time'));
if (timestamp === undefined) {
timestamp = this.safeNumber2 (trade, 'trade_time_ms', 'time');
}
let side = this.safeStringLower (trade, 'side');
if (side === undefined) {
const isBuyer = this.safeValue (trade, 'isBuyer');
if (isBuyer !== undefined) {
side = isBuyer ? 'buy' : 'sell';
}
}
const isMaker = this.safeValue (trade, 'isMaker');
let takerOrMaker = undefined;
if (isMaker !== undefined) {
takerOrMaker = isMaker ? 'maker' : 'taker';
} else {
const lastLiquidityInd = this.safeString (trade, 'last_liquidity_ind');
takerOrMaker = (lastLiquidityInd === 'AddedLiquidity') ? 'maker' : 'taker';
}
const feeCostString = this.safeString (trade, 'exec_fee');
let fee = undefined;
if (feeCostString !== undefined) {
const feeCurrencyCode = market['inverse'] ? market['base'] : market['quote'];
fee = {
'cost': feeCostString,
'currency': feeCurrencyCode,
'rate': this.safeString (trade, 'fee_rate'),
};
}
return this.safeTrade ({
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'order': this.safeString2 (trade, 'order_id', 'orderId'),
'type': this.safeStringLower (trade, 'order_type'),
'side': side,
'takerOrMaker': takerOrMaker,
'price': priceString,
'amount': amountString,
'cost': costString,
'fee': fee,
}, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let method = undefined;
const request = {
'symbol': market['id'],
};
const isUsdcSettled = market['settle'] === 'USDC';
if (market['type'] === 'spot') {
method = 'publicGetSpotQuoteV1Trades';
} else if (!isUsdcSettled) {
// inverse perpetual // usdt linear // inverse futures
method = market['linear'] ? 'publicGetPublicLinearRecentTradingRecords' : 'publicGetV2PublicTradingRecords';
} else {
// usdc option/ swap
method = 'publicGetOptionUsdcOpenapiPublicV1QueryTradeLatest';
request['category'] = market['option'] ? 'OPTION' : 'PERPETUAL';
}
if (limit !== undefined) {
request['limit'] = limit; // default 500, max 1000
}
const response = await this[method] (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// id: 43785688,
// symbol: 'BTCUSD',
// price: 7786,
// qty: 67,
// side: 'Sell',
// time: '2020-03-11T19:18:30.123Z'
// },
// ],
// time_now: '1583954313.393362'
// }
//
// usdc trades
// {
// "retCode": 0,
// "retMsg": "Success.",
// "result": {
// "resultTotalSize": 2,
// "cursor": "",
// "dataList": [
// {
// "id": "3caaa0ca",
// "symbol": "BTCPERP",
// "orderPrice": "58445.00",
// "orderQty": "0.010",
// "side": "Buy",
// "time": "1638275679673"
// }
// ]
// }
// }
//
let trades = this.safeValue (response, 'result', {});
if (!Array.isArray (trades)) {
trades = this.safeValue (trades, 'dataList', []);
}
return this.parseTrades (trades, market, since, limit);
}
parseOrderBook (orderbook, symbol, timestamp = undefined, bidsKey = 'Buy', asksKey = 'Sell', priceKey = 'price', amountKey = 'size') {
const bids = [];
const asks = [];
for (let i = 0; i < orderbook.length; i++) {
const bidask = orderbook[i];
const side = this.safeString (bidask, 'side');
if (side === 'Buy') {
bids.push (this.parseBidAsk (bidask, priceKey, amountKey));
} else if (side === 'Sell') {
asks.push (this.parseBidAsk (bidask, priceKey, amountKey));
} else {
throw new ExchangeError (this.id + ' parseOrderBook() encountered an unrecognized bidask format: ' + this.json (bidask));
}
}
return {
'symbol': symbol,
'bids': this.sortBy (bids, 0, true),
'asks': this.sortBy (asks, 0),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'nonce': undefined,
};
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const response = await this.publicGetV2PublicOrderBookL2 (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// { symbol: 'BTCUSD', price: '7767.5', size: 677956, side: 'Buy' },
// { symbol: 'BTCUSD', price: '7767', size: 580690, side: 'Buy' },
// { symbol: 'BTCUSD', price: '7766.5', size: 475252, side: 'Buy' },
// { symbol: 'BTCUSD', price: '7768', size: 330847, side: 'Sell' },
// { symbol: 'BTCUSD', price: '7768.5', size: 97159, side: 'Sell' },
// { symbol: 'BTCUSD', price: '7769', size: 6508, side: 'Sell' },
// ],
// time_now: '1583954829.874823'
// }
//
const result = this.safeValue (response, 'result', []);
const timestamp = this.safeTimestamp (response, 'time_now');
return this.parseOrderBook (result, symbol, timestamp, 'Buy', 'Sell', 'price', 'size');
}
parseBalance (response) {
//
// spot balance
// {
// "ret_code": "0",
// "ret_msg": "",
// "ext_code": null,
// "ext_info": null,
// "result": {
// "balances": [
// {
// "coin": "LTC",
// "coinId": "LTC",
// "coinName": "LTC",
// "total": "0.00000783",
// "free": "0.00000783",
// "locked": "0"
// }
// ]
// }
// }
//
// linear/inverse swap/futures
// {
// "ret_code": "0",
// "ret_msg": "OK",
// "ext_code": "",
// "ext_info": "",
// "result": {
// "ADA": {
// "equity": "0",
// "available_balance": "0",
// "used_margin": "0",
// "order_margin": "0",
// "position_margin": "0",
// "occ_closing_fee": "0",
// "occ_funding_fee": "0",
// "wallet_balance": "0",
// "realised_pnl": "0",
// "unrealised_pnl": "0",
// "cum_realised_pnl": "0",
// "given_cash": "0",
// "service_cash": "0"
// },
// },
// "time_now": "1651772170.050566",
// "rate_limit_status": "119",
// "rate_limit_reset_ms": "1651772170042",
// "rate_limit": "120"
// }
//
// usdc wallet
// {
// "result": {
// "walletBalance": "10.0000",
// "accountMM": "0.0000",
// "bonus": "0.0000",
// "accountIM": "0.0000",
// "totalSessionRPL": "0.0000",
// "equity": "10.0000",
// "totalRPL": "0.0000",
// "marginBalance": "10.0000",
// "availableBalance": "10.0000",
// "totalSessionUPL": "0.0000"
// },
// "retCode": "0",
// "retMsg": "Success."
// }
//
const result = {
'info': response,
};
const data = this.safeValue (response, 'result', {});
const balances = this.safeValue (data, 'balances');
if (Array.isArray (balances)) {
// spot balances
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
const currencyId = this.safeString (balance, 'coin');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (balance, 'availableBalance');
account['used'] = this.safeString (balance, 'locked');
account['total'] = this.safeString (balance, 'total');
result[code] = account;
}
} else {
if ('walletBalance' in data) {
// usdc wallet
const code = 'USDC';
const account = this.account ();
account['free'] = this.safeString (data, 'availableBalance');
account['total'] = this.safeString (data, 'walletBalance');
result[code] = account;
} else {
// linear/inverse swap/futures
const currencyIds = Object.keys (data);
for (let i = 0; i < currencyIds.length; i++) {
const currencyId = currencyIds[i];
const balance = data[currencyId];
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['free'] = this.safeString (balance, 'available_balance');
account['total'] = this.safeString (balance, 'wallet_balance');
result[code] = account;
}
}
}
return this.safeBalance (result);
}
async fetchBalance (params = {}) {
const request = {};
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchBalance', undefined, params);
let method = undefined;
if (type === 'spot') {
method = 'privateGetSpotV1Account';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
let isUsdcSettled = settle === 'USDC';
isUsdcSettled = true;
if (!isUsdcSettled) {
// linear/inverse future/swap
method = 'privateGetV2PrivateWalletBalance';
const coin = this.safeString2 (params, 'coin', 'code');
params = this.omit (params, [ 'coin', 'code' ]);
if (coin !== undefined) {
const currency = this.currency (coin);
request['coin'] = currency['id'];
}
} else {
// usdc account
method = 'privatePostOptionUsdcOpenapiPrivateV1QueryWalletBalance';
}
}
await this.loadMarkets ();
const response = await this[method] (this.extend (request, params));
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: {
// BTC: {
// equity: 0,
// available_balance: 0,
// used_margin: 0,
// order_margin: 0,
// position_margin: 0,
// occ_closing_fee: 0,
// occ_funding_fee: 0,
// wallet_balance: 0,
// realised_pnl: 0,
// unrealised_pnl: 0,
// cum_realised_pnl: 0,
// given_cash: 0,
// service_cash: 0
// }
// },
// time_now: '1583937810.370020',
// rate_limit_status: 119,
// rate_limit_reset_ms: 1583937810367,
// rate_limit: 120
// }
//
return this.parseBalance (response);
}
parseOrderStatus (status) {
const statuses = {
// basic orders
'created': 'open',
'rejected': 'rejected', // order is triggered but failed upon being placed
'new': 'open',
'partiallyfilled': 'open',
'filled': 'closed',
'cancelled': 'canceled',
'pendingcancel': 'canceling', // the engine has received the cancellation but there is no guarantee that it will be successful
// conditional orders
'active': 'open', // order is triggered and placed successfully
'untriggered': 'open', // order waits to be triggered
'triggered': 'closed', // order is triggered
// 'Cancelled': 'canceled', // order is cancelled
// 'Rejected': 'rejected', // order is triggered but fail to be placed
'deactivated': 'canceled', // conditional order was cancelled before triggering
};
return this.safeString (statuses, status, status);
}
parseTimeInForce (timeInForce) {
const timeInForces = {
'GoodTillCancel': 'GTC',
'ImmediateOrCancel': 'IOC',
'FillOrKill': 'FOK',
'PostOnly': 'PO',
};
return this.safeString (timeInForces, timeInForce, timeInForce);
}
parseOrder (order, market = undefined) {
//
// createOrder
//
// {
// "user_id": 1,
// "order_id": "335fd977-e5a5-4781-b6d0-c772d5bfb95b",
// "symbol": "BTCUSD",
// "side": "Buy",
// "order_type": "Limit",
// "price": 8800,
// "qty": 1,
// "time_in_force": "GoodTillCancel",
// "order_status": "Created",
// "last_exec_time": 0,
// "last_exec_price": 0,
// "leaves_qty": 1,
// "cum_exec_qty": 0, // in contracts, where 1 contract = 1 quote currency unit (USD for inverse contracts)
// "cum_exec_value": 0, // in contract's underlying currency (BTC for inverse contracts)
// "cum_exec_fee": 0,
// "reject_reason": "",
// "order_link_id": "",
// "created_at": "2019-11-30T11:03:43.452Z",
// "updated_at": "2019-11-30T11:03:43.455Z"
// }
//
// fetchOrder
//
// {
// "user_id" : 599946,
// "symbol" : "BTCUSD",
// "side" : "Buy",
// "order_type" : "Limit",
// "price" : "7948",
// "qty" : 10,
// "time_in_force" : "GoodTillCancel",
// "order_status" : "Filled",
// "ext_fields" : {
// "o_req_num" : -1600687220498,
// "xreq_type" : "x_create"
// },
// "last_exec_time" : "1588150113.968422",
// "last_exec_price" : "7948",
// "leaves_qty" : 0,
// "leaves_value" : "0",
// "cum_exec_qty" : 10,
// "cum_exec_value" : "0.00125817",
// "cum_exec_fee" : "-0.00000031",
// "reject_reason" : "",
// "cancel_type" : "",
// "order_link_id" : "",
// "created_at" : "2020-04-29T08:45:24.399146Z",
// "updated_at" : "2020-04-29T08:48:33.968422Z",
// "order_id" : "dd2504b9-0157-406a-99e1-efa522373944"
// }
//
// fetchOrders linear swaps
//
// {
// "order_id":"7917bd70-e7c3-4af5-8147-3285cd99c509",
// "user_id":22919890,
// "symbol":"GMTUSDT",
// "side":"Buy",
// "order_type":"Limit",
// "price":2.9262,
// "qty":50,
// "time_in_force":"GoodTillCancel",
// "order_status":"Filled",
// "last_exec_price":2.9219,
// "cum_exec_qty":50,
// "cum_exec_value":146.095,
// "cum_exec_fee":0.087657,
// "reduce_only":false,
// "close_on_trigger":false,
// "order_link_id":"",
// "created_time":"2022-04-18T17:09:54Z",
// "updated_time":"2022-04-18T17:09:54Z",
// "take_profit":0,
// "stop_loss":0,
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN"
// }
//
// conditional order
//
// {
// "user_id":"24478789",
// "stop_order_id":"68e996af-fa55-4ca1-830e-4bf68ffbff3e",
// "symbol":"LTCUSDT",
// "side":"Buy",
// "order_type":"Limit",
// "price":"86",
// "qty":"0.1",
// "time_in_force":"GoodTillCancel",
// "order_status":"Filled",
// "trigger_price":"86",
// "order_link_id":"",
// "created_time":"2022-05-09T14:36:36Z",
// "updated_time":"2022-05-09T14:39:25Z",
// "take_profit":"0",
// "stop_loss":"0",
// "trigger_by":"LastPrice",
// "base_price":"86.96",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN",
// "reduce_only":false,
// "close_on_trigger":false
// }
// future
// {
// "user_id":24478789,
// "position_idx":0,
// "order_status":"Filled",
// "symbol":"ETHUSDM22",
// "side":"Buy",
// "order_type":"Market",
// "price":"2523.35",
// "qty":"10",
// "time_in_force":"ImmediateOrCancel",
// "order_link_id":"",
// "order_id":"54feb0e2-ece7-484f-b870-47910609b5ac",
// "created_at":"2022-05-09T14:46:42.346Z",
// "updated_at":"2022-05-09T14:46:42.350Z",
// "leaves_qty":"0",
// "leaves_value":"0",
// "cum_exec_qty":"10",
// "cum_exec_value":"0.00416111",
// "cum_exec_fee":"0.0000025",
// "reject_reason":"EC_NoError",
// "take_profit":"0.0000",
// "stop_loss":"0.0000",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN"
// }
//
// fetchOpenOrder spot
// {
// "accountId":"24478790",
// "exchangeId":"301",
// "symbol":"LTCUSDT",
// "symbolName":"LTCUSDT",
// "orderLinkId":"1652115972506",
// "orderId":"1152426740986003968",
// "price":"50",
// "origQty":"0.2",
// "executedQty":"0",
// "cummulativeQuoteQty":"0",
// "avgPrice":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY",
// "stopPrice":"0.0",
// "icebergQty":"0.0",
// "time":"1652115973053",
// "updateTime":"1652115973063",
// "isWorking":true
// }
//
// create order usdc
// {
// "orderId":"34450a59-325e-4296-8af0-63c7c524ae33",
// "orderLinkId":"",
// "mmp":false,
// "symbol":"BTCPERP",
// "orderType":"Limit",
// "side":"Buy",
// "orderQty":"0.00100000",
// "orderPrice":"20000.00",
// "iv":"0",
// "timeInForce":"GoodTillCancel",
// "orderStatus":"Created",
// "createdAt":"1652261746007873",
// "basePrice":"0.00",
// "triggerPrice":"0.00",
// "takeProfit":"0.00",
// "stopLoss":"0.00",
// "slTriggerBy":"UNKNOWN",
// "tpTriggerBy":"UNKNOWN"
// }
//
const marketId = this.safeString (order, 'symbol');
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
let feeCurrency = undefined;
let timestamp = this.parse8601 (this.safeString2 (order, 'created_at', 'created_time'));
if (timestamp === undefined) {
timestamp = this.safeNumber2 (order, 'time', 'transactTime');
if (timestamp === undefined) {
timestamp = this.safeIntegerProduct (order, 'createdAt', 0.001);
}
}
let id = this.safeString2 (order, 'order_id', 'stop_order_id');
if (id === undefined) {
id = this.safeString (order, 'orderId');
}
let type = this.safeStringLower2 (order, 'order_type', 'type');
if (type === undefined) {
type = this.safeStringLower (order, 'orderType');
}
const price = this.safeString2 (order, 'price', 'orderPrice');
const average = this.safeString2 (order, 'average_price', 'avgPrice');
let amount = this.safeString2 (order, 'qty', 'origQty');
if (amount === undefined) {
amount = this.safeString (order, 'orderQty');
}
const cost = this.safeString (order, 'cum_exec_value');
const filled = this.safeString2 (order, 'cum_exec_qty', 'executedQty');
const remaining = this.safeString (order, 'leaves_qty');
const marketTypes = this.safeValue (this.options, 'marketTypes', {});
const marketType = this.safeString (marketTypes, symbol);
if (marketType === 'linear') {
feeCurrency = market['quote'];
} else {
feeCurrency = market['base'];
}
let lastTradeTimestamp = this.safeTimestamp (order, 'last_exec_time');
if (lastTradeTimestamp === 0) {
lastTradeTimestamp = undefined;
} else if (lastTradeTimestamp === undefined) {
lastTradeTimestamp = this.parse8601 (this.safeString2 (order, 'updated_time', 'updated_at'));
if (lastTradeTimestamp === undefined) {
lastTradeTimestamp = this.safeNumber (order, 'updateTime');
}
}
let raw_status = this.safeStringLower2 (order, 'order_status', 'stop_order_status');
if (raw_status === undefined) {
raw_status = this.safeStringLower2 (order, 'status', 'orderStatus');
}
const status = this.parseOrderStatus (raw_status);
const side = this.safeStringLower (order, 'side');
const feeCostString = this.safeString (order, 'cum_exec_fee');
let fee = undefined;
if (feeCostString !== undefined) {
fee = {
'cost': feeCostString,
'currency': feeCurrency,
};
}
let clientOrderId = this.safeString2 (order, 'order_link_id', 'orderLinkId');
if ((clientOrderId !== undefined) && (clientOrderId.length < 1)) {
clientOrderId = undefined;
}
const timeInForce = this.parseTimeInForce (this.safeString2 (order, 'time_in_force', 'timeInForce'));
let stopPrice = this.safeString2 (order, 'trigger_price', 'stop_px');
if (stopPrice === undefined) {
stopPrice = this.safeString2 (order, 'stopPrice', 'triggerPrice');
}
const postOnly = (timeInForce === 'PO');
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': type,
'timeInForce': timeInForce,
'postOnly': postOnly,
'side': side,
'price': price,
'stopPrice': stopPrice,
'amount': amount,
'cost': cost,
'average': average,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
'trades': undefined,
}, market);
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchOrder', market, params);
if (type !== 'spot' && symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrder() requires a symbol argument for ' + type + ' markets');
}
if (type === 'spot') {
// only spot markets have a dedicated endpoint for fetching a order
const request = {
'orderId': id,
};
const response = await this.privateGetSpotV1Order (this.extend (params, request));
const result = this.safeValue (response, 'result', {});
return this.parseOrder (result);
}
const isUsdcSettled = (market['settle'] === 'USDC');
const orderKey = isUsdcSettled ? 'orderId' : 'order_id';
params[orderKey] = id;
if (isUsdcSettled || market['future'] || market['inverse']) {
return this.fetchOpenOrders (symbol, undefined, undefined, params);
} else {
// only linear swap markets allow using all purpose
// fetchOrders endpoint filtering by id
return this.fetchOrders (symbol, undefined, undefined, params);
}
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
symbol = market['symbol'];
amount = this.amountToPrecision (symbol, amount);
price = (price !== undefined) ? this.priceToPrecision (symbol, price) : undefined;
const isUsdcSettled = (market['settle'] === 'USDC');
if (market['spot']) {
return await this.createSpotOrder (symbol, type, side, amount, price, params);
} else if (isUsdcSettled) {
return await this.createUsdcOrder (symbol, type, side, amount, price, params);
} else {
return await this.createContractOrder (symbol, type, side, amount, price, params);
}
}
async createSpotOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (type === 'market' && side === 'buy') {
// for market buy it requires the amount of quote currency to spend
if (this.options['createMarketBuyOrderRequiresPrice']) {
const cost = this.safeNumber (params, 'cost');
params = this.omit (params, 'cost');
if (price === undefined && cost === undefined) {
throw new InvalidOrder (this.id + " createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = false to supply the cost in the amount argument (the exchange-specific behaviour)");
} else {
amount = (cost !== undefined) ? cost : amount * price;
}
}
}
const request = {
'symbol': market['id'],
'side': this.capitalize (side),
'type': type.toUpperCase (), // limit, market or limit_maker
'timeInForce': 'GTC', // FOK, IOC
'qty': amount,
};
if (type === 'limit' || type === 'limit_maker') {
if (price === undefined) {
throw new InvalidOrder (this.id + ' createOrder requires a price argument for a ' + type + ' order');
}
request['price'] = price;
}
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'orderLinkId');
if (clientOrderId !== undefined) {
request['orderLinkId'] = clientOrderId;
}
params = this.omit (params, [ 'clientOrderId', 'orderLinkId' ]);
const response = await this.privatePostSpotV1Order (this.extend (request, params));
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":{
// "accountId":"24478790",
// "symbol":"ETHUSDT",
// "symbolName":"ETHUSDT",
// "orderLinkId":"1652266305358517",
// "orderId":"1153687819821127168",
// "transactTime":"1652266305365",
// "price":"80",
// "origQty":"0.05",
// "executedQty":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY"
// }
// }
const order = this.safeValue (response, 'result', {});
return this.parseOrder (order);
}
async createUsdcOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (type === 'market') {
throw NotSupported (this.id + 'createOrder does not allow market orders for ' + symbol + ' markets');
}
if (price === undefined && type === 'limit') {
throw new ArgumentsRequired (this.id + ' createOrder requires a price argument for limit orders');
}
const request = {
'symbol': market['id'],
'side': this.capitalize (side),
'orderType': this.capitalize (type), // limit
'timeInForce': 'GoodTillCancel', // ImmediateOrCancel, FillOrKill, PostOnly
'orderQty': amount,
};
if (price !== undefined) {
request['orderPrice'] = price;
}
if (market['swap']) {
const stopPx = this.safeValue2 (params, 'stopPrice', 'triggerPrice');
params = this.omit (params, [ 'stopPrice', 'triggerPrice' ]);
if (stopPx !== undefined) {
const basePrice = this.safeValue (params, 'basePrice');
if (basePrice === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder() requires both the triggerPrice and basePrice params for a conditional ' + type + ' order');
}
request['orderFilter'] = 'StopOrder';
request['triggerPrice'] = this.priceToPrecision (symbol, stopPx);
} else {
request['orderFilter'] = 'Order';
}
}
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'orderLinkId');
if (clientOrderId !== undefined) {
request['orderLinkId'] = clientOrderId;
} else if (market['option']) {
// mandatory field for options
request['orderLinkId'] = this.uuid16 ();
}
params = this.omit (params, [ 'clientOrderId', 'orderLinkId' ]);
const method = market['option'] ? 'privatePostOptionUsdcOpenapiPrivateV1PlaceOrder' : 'privatePostPerpetualUsdcOpenapiPrivateV1PlaceOrder';
const response = await this[method] (this.extend (request, params));
//
// {
// "retCode":0,
// "retMsg":"",
// "result":{
// "orderId":"34450a59-325e-4296-8af0-63c7c524ae33",
// "orderLinkId":"",
// "mmp":false,
// "symbol":"BTCPERP",
// "orderType":"Limit",
// "side":"Buy",
// "orderQty":"0.00100000",
// "orderPrice":"20000.00",
// "iv":"0",
// "timeInForce":"GoodTillCancel",
// "orderStatus":"Created",
// "createdAt":"1652261746007873",
// "basePrice":"0.00",
// "triggerPrice":"0.00",
// "takeProfit":"0.00",
// "stopLoss":"0.00",
// "slTriggerBy":"UNKNOWN",
// "tpTriggerBy":"UNKNOWN"
// }
//
const order = this.safeValue (response, 'result', {});
return this.parseOrder (order);
}
async createContractOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (price === undefined && type === 'limit') {
throw new ArgumentsRequired (this.id + ' createOrder requires a price argument for limit orders');
}
const request = {
'symbol': market['id'],
'side': this.capitalize (side),
'order_type': this.capitalize (type), // limit
'time_in_force': 'GoodTillCancel', // ImmediateOrCancel, FillOrKill, PostOnly
'qty': amount,
};
if (market['future']) {
const positionIdx = this.safeInteger (params, 'position_idx', 0); // 0 One-Way Mode, 1 Buy-side, 2 Sell-side
request['position_idx'] = positionIdx;
params = this.omit (params, 'position_idx');
}
if (market['linear']) {
const reduceOnly = this.safeValue2 (params, 'reduce_only', 'reduceOnly', false);
const closeOnTrigger = this.safeValue2 (params, 'reduce_only', 'reduceOnly', false);
request['reduce_only'] = reduceOnly;
request['close_on_trigger'] = closeOnTrigger;
}
if (price !== undefined) {
request['price'] = price;
}
const stopPx = this.safeValue2 (params, 'stop_px', 'stopPrice');
const basePrice = this.safeValue2 (params, 'base_price', 'basePrice');
let isConditionalOrder = false;
if (stopPx !== undefined) {
isConditionalOrder = true;
if (basePrice === undefined) {
throw new ArgumentsRequired (this.id + ' createOrder() requires both the stop_px and base_price params for a conditional ' + type + ' order');
}
request['stop_px'] = parseFloat (this.priceToPrecision (symbol, stopPx));
request['base_price'] = parseFloat (this.priceToPrecision (symbol, basePrice, 'basePrice'));
const triggerBy = this.safeString2 (params, 'trigger_by', 'triggerBy', 'LastPrice');
request['trigger_by'] = triggerBy;
params = this.omit (params, [ 'stop_px', 'stopPrice', 'base_price', 'triggerBy', 'trigger_by' ]);
}
const clientOrderId = this.safeString2 (params, 'clientOrderId', 'orderLinkId');
if (clientOrderId !== undefined) {
request['orderLinkId'] = clientOrderId;
}
params = this.omit (params, [ 'clientOrderId', 'orderLinkId' ]);
let method = undefined;
if (market['future']) {
method = isConditionalOrder ? 'privatePostFuturesPrivateStopOrderCreate' : 'privatePostFuturesPrivateOrderCreate';
} else if (market['linear']) {
method = isConditionalOrder ? 'privatePostPrivateLinearStopOrderCreate' : 'privatePostPrivateLinearOrderCreate';
} else {
// inverse swaps
method = isConditionalOrder ? 'privatePostV2PrivateStopOrderCreate' : 'privatePostV2PrivateOrderCreate';
}
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "order_id":"f016f912-68c2-4da9-a289-1bb9b62b5c3b",
// "user_id":24478789,
// "symbol":"LTCUSDT",
// "side":"Buy",
// "order_type":"Market",
// "price":79.72,
// "qty":1,
// "time_in_force":"ImmediateOrCancel",
// "order_status":"Created",
// "last_exec_price":0,
// "cum_exec_qty":0,
// "cum_exec_value":0,
// "cum_exec_fee":0,
// "reduce_only":false,
// "close_on_trigger":false,
// "order_link_id":"",
// "created_time":"2022-05-11T13:56:29Z",
// "updated_time":"2022-05-11T13:56:29Z",
// "take_profit":0,
// "stop_loss":0,
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN",
// "position_idx":1
// },
// "time_now":"1652277389.122038",
// "rate_limit_status":98,
// "rate_limit_reset_ms":1652277389119,
// "rate_limit":100
// }
//
const order = this.safeValue (response, 'result', {});
return this.parseOrder (order);
}
async editUsdcOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
'orderId': id,
};
if (amount !== undefined) {
request['orderQty'] = amount;
}
if (price !== undefined) {
request['orderPrice'] = price;
}
const method = market['option'] ? 'privatePostOptionUsdcOpenApiPrivateV1ReplaceOrder' : 'privatePostPerpetualUsdcOpenApiPrivateV1ReplaceOrder';
const response = await this[method] (this.extend (request, params));
//
// {
// "retCode": 0,
// "retMsg": "OK",
// "result": {
// "outRequestId": "",
// "symbol": "BTC-13MAY22-40000-C",
// "orderId": "8c65df91-91fc-461d-9b14-786379ef138c",
// "orderLinkId": "AAAAA41133"
// },
// "retExtMap": {}
// }
//
return {
'info': response,
'id': id,
};
}
async editContractOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' editOrder() requires an symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
// 'order_id': id, // only for non-conditional orders
'symbol': market['id'],
// 'p_r_qty': this.amountToPrecision (symbol, amount), // new order quantity, optional
// 'p_r_price' this.priceToprecision (symbol, price), // new order price, optional
// ----------------------------------------------------------------
// conditional orders
// 'stop_order_id': id, // only for conditional orders
// 'p_r_trigger_price': 123.45, // new trigger price also known as stop_px
};
const orderType = this.safeString (params, 'orderType');
const isConditionalOrder = (orderType === 'stop' || orderType === 'conditional');
const idKey = isConditionalOrder ? 'stop_order_id' : 'order_id';
request[idKey] = id;
if (amount !== undefined) {
request['p_r_qty'] = amount;
}
if (price !== undefined) {
request['p_r_price'] = price;
}
let method = undefined;
if (market['linear']) {
method = isConditionalOrder ? 'privatePostPrivateLinearStopOrderReplace' : 'privatePostPrivateLinearOrderReplace';
} else if (market['future']) {
method = isConditionalOrder ? 'privatePostFuturesPrivateStopOrderReplace' : 'privatePostFuturesPrivateOrderReplace';
} else {
// inverse swaps
method = isConditionalOrder ? 'privatePostV2PrivateSpotOrderReplace' : 'privatePostV2PrivateOrderReplace';
}
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": { "order_id": "efa44157-c355-4a98-b6d6-1d846a936b93" },
// "time_now": "1539778407.210858",
// "rate_limit_status": 99, // remaining number of accesses in one minute
// "rate_limit_reset_ms": 1580885703683,
// "rate_limit": 100
// }
//
// conditional orders
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": { "stop_order_id": "378a1bbc-a93a-4e75-87f4-502ea754ba36" },
// "ext_info": null,
// "time_now": "1577475760.604942",
// "rate_limit_status": 96,
// "rate_limit_reset_ms": 1577475760612,
// "rate_limit": "100"
// }
//
const result = this.safeValue (response, 'result', {});
return {
'info': response,
'id': this.safeString2 (result, 'order_id', 'stop_order_id'),
'order_id': this.safeString (result, 'order_id'),
'stop_order_id': this.safeString (result, 'stop_order_id'),
};
}
async editOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' editOrder() requires an symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
amount = (amount !== undefined) ? this.amountToPrecision (symbol, amount) : undefined;
price = (price !== undefined) ? this.priceToPrecision (symbol, price) : undefined;
const isUsdcSettled = market['settle'] === 'USDC';
if (market['spot']) {
throw new NotSupported (this.id + ' editOrder() does not support spot markets');
} else if (isUsdcSettled) {
return await this.editUsdcOrder (id, symbol, type, side, amount, price, params);
} else {
return await this.editContractOrder (id, symbol, type, side, amount, price, params);
}
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
// 'order_link_id': 'string', // one of order_id, stop_order_id or order_link_id is required
// regular orders ---------------------------------------------
// 'order_id': id, // one of order_id or order_link_id is required for regular orders
// conditional orders ---------------------------------------------
// 'stop_order_id': id, // one of stop_order_id or order_link_id is required for conditional orders
// spot orders
// 'orderId': id
};
const orderType = this.safeStringLower (params, 'orderType');
const isConditional = (orderType === 'stop') || (orderType === 'conditional');
const isUsdcSettled = market['settle'] === 'USDC';
let method = undefined;
if (market['spot']) {
method = 'privateDeleteSpotV1Order';
request['orderId'] = id;
} else if (isUsdcSettled) {
request['orderId'] = id;
if (market['option']) {
method = 'privatePostOptionUsdcOpenapiPrivateV1CancelOrder';
} else {
method = 'privatePostPerpetualUsdcOpenapiPrivateV1CancelOrder';
request['orderFilter'] = isConditional ? 'StopOrder' : 'Order';
}
} else if (market['linear']) {
method = isConditional ? 'privatePostPrivateLinearStopOrderCancel' : 'privatePostPrivateLinearOrderCancel';
} else if (market['future']) {
method = isConditional ? 'privatePostFuturesPrivateStopOrderCancel' : 'privatePostFuturesPrivateOrderCancel';
} else {
// inverse futures
method = isConditional ? 'privatePostFuturesPrivateStopOrderCancel' : 'privatePostFuturesPrivateOrderCancel';
}
if (market['contract'] && !isUsdcSettled) {
if (!isConditional) {
request['order_id'] = id;
} else {
request['stop_order_id'] = id;
}
}
const response = await this[method] (this.extend (request, params));
// spot order
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":{
// "accountId":"24478790",
// "symbol":"LTCUSDT",
// "orderLinkId":"1652192399682",
// "orderId":"1153067855569315072",
// "transactTime":"1652192399866",
// "price":"50",
// "origQty":"0.2",
// "executedQty":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY"
// }
// }
// linear
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "order_id":"f5103487-f7f9-48d3-a26d-b74a3a53d3d3"
// },
// "time_now":"1652192814.880473",
// "rate_limit_status":99,
// "rate_limit_reset_ms":1652192814876,
// "rate_limit":100
// }
const result = this.safeValue (response, 'result', {});
return this.parseOrder (result, market);
}
async cancelAllOrders (symbol = undefined, params = {}) {
let market = undefined;
let isUsdcSettled = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
isUsdcSettled = market['settle'] === 'USDC';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = (settle === 'USDC');
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('cancelAllOrders', market, params);
if (!isUsdcSettled && symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelAllOrders() requires a symbol argument for ' + type + ' markets');
}
await this.loadMarkets ();
const request = {};
if (!isUsdcSettled) {
request['symbol'] = market['id'];
}
const orderType = this.safeStringLower (params, 'orderType');
const isConditional = (orderType === 'stop') || (orderType === 'conditional');
let method = undefined;
if (type === 'spot') {
method = 'privateDeleteSpotOrderBatchCancel';
} else if (isUsdcSettled) {
method = (type === 'option') ? 'privatePostOptionUsdcOpenapiPrivateV1CancelAll' : 'privatePostPerpetualUsdcOpenapiPrivateV1CancelAll';
} else if (type === 'future') {
method = isConditional ? 'privatePostFuturesPrivateStopOrderCancelAll' : 'privatePostFuturesPrivateOrderCancelAll';
} else if (market['linear']) {
// linear swap
method = isConditional ? 'privatePostPrivateLinearStopOrderCancelAll' : 'privatePostPrivateLinearOrderCancelAll';
} else {
// inverse swap
method = isConditional ? 'privatePostV2PrivateStopOrderCancelAll' : 'privatePostV2PrivateOrderCancelAll';
}
const response = await this[method] (this.extend (request, params));
// spot
// {
// "ret_code": 0,
// "ret_msg": "",
// "ext_code": null,
// "ext_info": null,
// "result": {
// "success": true
// }
// }
//
// linear swap
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// "49d9ee94-303b-4bcf-959b-9e5d215e4973"
// ],
// "time_now":"1652182444.015560",
// "rate_limit_status":90,
// "rate_limit_reset_ms":1652182444010,
// "rate_limit":100
// }
//
// conditional futures
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":[
// {
// "clOrdID":"a14aea1e-9148-4a34-871a-f935f7cdb654",
// "user_id":24478789,
// "symbol":"ETHUSDM22",
// "side":"Buy",
// "order_type":"Limit",
// "price":"2001",
// "qty":10,
// "time_in_force":"GoodTillCancel",
// "create_type":"CreateByStopOrder",
// "cancel_type":"CancelByUser",
// "order_status":"",
// "leaves_value":"0",
// "created_at":"2022-05-10T11:43:29.705138839Z",
// "updated_at":"2022-05-10T11:43:37.988493739Z",
// "cross_status":"Deactivated",
// "cross_seq":-1,
// "stop_order_type":"Stop",
// "trigger_by":"LastPrice",
// "base_price":"2410.65",
// "trail_value":"0",
// "expected_direction":"Falling"
// }
// ],
// "time_now":"1652183017.988764",
// "rate_limit_status":97,
// "rate_limit_reset_ms":1652183017986,
// "rate_limit":100
// }
//
const result = this.safeValue (response, 'result', []);
if (!Array.isArray (result)) {
return response;
}
return this.parseOrders (result, market);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
if (market['spot'] || (market['settle'] === 'USDC')) {
throw new NotSupported (this.id + ' fetchOrders() does not support market ' + market['symbol']);
}
let method = undefined;
const type = this.safeStringLower (params, 'type');
params = this.omit (params, 'type');
const isConditionalOrder = (type === 'stop') || (type === 'conditional');
if (market['linear']) {
method = !isConditionalOrder ? 'privateGetPrivateLinearOrderList' : 'privateGetPrivateLinearStopOrderList';
} else if (market['future']) {
method = !isConditionalOrder ? 'privateGetFuturesPrivateOrderList' : 'privateGetFuturesPrivateStopOrderList';
} else {
// inverse swap
method = !isConditionalOrder ? 'privateGetV2PrivateOrderList' : 'privateGetV2PrivateStopOrderList';
}
const request = {
'symbol': market['id'],
// 'order_id': 'string'
// 'order_link_id': 'string', // unique client order id, max 36 characters
// 'symbol': market['id'], // default BTCUSD
// 'order': 'desc', // asc
// 'page': 1,
// 'limit': 20, // max 50
// 'order_status': 'Created,New'
// conditional orders ---------------------------------------------
// 'stop_order_id': 'string',
// 'stop_order_status': 'Untriggered',
};
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this[method] (this.extend (request, params));
//
// linear swap
//
// {
// "ret_code":"0",
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "current_page":"1",
// "data":[
// {
// "order_id":"68ab115d-cdbc-4c38-adc0-b2fbc60136ab",
// "user_id":"24478789",
// "symbol":"LTCUSDT",
// "side":"Sell",
// "order_type":"Market",
// "price":"94.72",
// "qty":"0.1",
// "time_in_force":"ImmediateOrCancel",
// "order_status":"Filled",
// "last_exec_price":"99.65",
// "cum_exec_qty":"0.1",
// "cum_exec_value":"9.965",
// "cum_exec_fee":"0.005979",
// "reduce_only":true,
// "close_on_trigger":true,
// "order_link_id":"",
// "created_time":"2022-05-05T15:15:34Z",
// "updated_time":"2022-05-05T15:15:34Z",
// "take_profit":"0",
// "stop_loss":"0",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN"
// }
// ]
// },
// "time_now":"1652106664.857572",
// "rate_limit_status":"598",
// "rate_limit_reset_ms":"1652106664856",
// "rate_limit":"600"
// }
//
//
// conditional orders
//
// {
// "ret_code":"0",
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "current_page":"1",
// "last_page":"0",
// "data":[
// {
// "user_id":"24478789",
// "stop_order_id":"68e996af-fa55-4ca1-830e-4bf68ffbff3e",
// "symbol":"LTCUSDT",
// "side":"Buy",
// "order_type":"Limit",
// "price":"86",
// "qty":"0.1",
// "time_in_force":"GoodTillCancel",
// "order_status":"Untriggered",
// "trigger_price":"86",
// "order_link_id":"",
// "created_time":"2022-05-09T14:36:36Z",
// "updated_time":"2022-05-09T14:36:36Z",
// "take_profit":"0",
// "stop_loss":"0",
// "trigger_by":"LastPrice",
// "base_price":"86.96",
// "tp_trigger_by":"UNKNOWN",
// "sl_trigger_by":"UNKNOWN",
// "reduce_only":false,
// "close_on_trigger":false
// }
// ]
// },
// "time_now":"1652107028.148177",
// "rate_limit_status":"598",
// "rate_limit_reset_ms":"1652107028146",
// "rate_limit":"600"
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseOrders (data, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let market = undefined;
let isUsdcSettled = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
isUsdcSettled = market['settle'] === 'USDC';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = settle === 'USDC';
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchClosedOrders', market, params);
if ((type === 'swap' || type === 'future') && !isUsdcSettled) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchClosedOrders requires a symbol argument for ' + symbol + ' markets');
}
const type = this.safeStringLower (params, 'type');
const isConditional = (type === 'stop') || (type === 'conditional');
let defaultStatuses = undefined;
if (!isConditional) {
defaultStatuses = [
'Rejected',
'Filled',
'Cancelled',
];
} else {
// conditional orders
defaultStatuses = [
'Active',
'Triggered',
'Cancelled',
'Rejected',
'Deactivated',
];
}
const closeStatus = defaultStatuses.join (',');
const status = this.safeString2 (params, 'order_status', 'status', closeStatus);
params = this.omit (params, [ 'order_status', 'status' ]);
params['order_status'] = status;
return await this.fetchOrders (symbol, since, limit, params);
}
const request = {};
let method = undefined;
if (type === 'spot') {
method = 'privateGetSpotV1HistoryOrders';
} else {
// usdc
method = 'privatePostOptionUsdcOpenapiPrivateV1QueryOrderHistory';
request['category'] = (type === 'swap') ? 'perpetual' : 'option';
}
const orders = await this[method] (this.extend (request, params));
let result = this.safeValue (orders, 'result', []);
if (!Array.isArray (result)) {
result = this.safeValue (result, 'dataList', []);
}
return this.parseOrders (result, market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let market = undefined;
let isUsdcSettled = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
isUsdcSettled = market['settle'] === 'USDC';
} else {
let settle = this.safeString (this.options, 'defaultSettle');
settle = this.safeString2 (params, 'settle', 'defaultSettle', settle);
params = this.omit (params, [ 'settle', 'defaultSettle' ]);
isUsdcSettled = settle === 'USDC';
}
let type = undefined;
[ type, params ] = this.handleMarketTypeAndParams ('fetchOpenOrders', market, params);
const request = {};
let method = undefined;
if ((type === 'swap' || type === 'future') && !isUsdcSettled) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOpenOrders requires a symbol argument for ' + symbol + ' markets');
}
request['symbol'] = market['id'];
const type = this.safeStringLower (params, 'orderType');
const isConditional = (type === 'stop') || (type === 'conditional');
if (market['future']) {
method = isConditional ? 'privateGetFuturesPrivateStopOrder' : 'privateGetFuturesPrivateOrder';
} else if (market['linear']) {
method = isConditional ? 'privateGetPrivateLinearStopOrderSearch' : 'privateGetPrivateLinearOrderSearch';
} else {
// inverse swap
method = isConditional ? 'privateGetV2PrivateStopOrder' : 'privateGetV2PrivateOrder';
}
} else if (type === 'spot') {
method = 'privateGetSpotV1OpenOrders';
} else {
// usdc
method = 'privatePostOptionUsdcOpenapiPrivateV1QueryActiveOrders';
request['category'] = (type === 'swap') ? 'perpetual' : 'option';
}
const orders = await this[method] (this.extend (request, params));
let result = this.safeValue (orders, 'result', []);
if (!Array.isArray (result)) {
const dataList = this.safeValue (result, 'dataList');
if (dataList === undefined) {
return this.parseOrder (result, market);
}
result = dataList;
}
// {
// "ret_code":0,
// "ret_msg":"",
// "ext_code":null,
// "ext_info":null,
// "result":[
// {
// "accountId":"24478790",
// "exchangeId":"301",
// "symbol":"LTCUSDT",
// "symbolName":"LTCUSDT",
// "orderLinkId":"1652115972506",
// "orderId":"1152426740986003968",
// "price":"50",
// "origQty":"0.2",
// "executedQty":"0",
// "cummulativeQuoteQty":"0",
// "avgPrice":"0",
// "status":"NEW",
// "timeInForce":"GTC",
// "type":"LIMIT",
// "side":"BUY",
// "stopPrice":"0.0",
// "icebergQty":"0.0",
// "time":"1652115973053",
// "updateTime":"1652115973063",
// "isWorking":true
// }
// ]
// }
return this.parseOrders (result, market, since, limit);
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
const request = {
'order_id': id,
};
return await this.fetchMyTrades (symbol, since, limit, this.extend (request, params));
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMyTrades() requires a symbol argument');
}
await this.loadMarkets ();
const request = {
// 'order_id': 'f185806b-b801-40ff-adec-52289370ed62', // if not provided will return user's trading records
// 'symbol': market['id'],
// 'start_time': parseInt (since / 1000),
// 'page': 1,
// 'limit' 20, // max 50
};
let market = undefined;
const orderId = this.safeString (params, 'order_id');
if (orderId !== undefined) {
request['order_id'] = orderId;
params = this.omit (params, 'order_id');
}
market = this.market (symbol);
const isUsdcSettled = market['settle'] === 'USDC';
if (isUsdcSettled) {
throw new NotSupported (this.id + ' fetchMyTrades() is not supported for market ' + symbol);
}
request['symbol'] = market['id'];
if (since !== undefined) {
request['start_time'] = since;
}
if (limit !== undefined) {
request['limit'] = limit; // default 20, max 50
}
let method = undefined;
if (market['spot']) {
method = 'privateGetSpotV1MyTrades';
} else if (market['future']) {
method = 'privateGetFuturesPrivateExecutionList';
} else {
// linear and inverse swaps
method = market['linear'] ? 'privateGetPrivateLinearTradeExecutionList' : 'privateGetV2PrivateExecutionList';
}
const response = await this[method] (this.extend (request, params));
//
// spot
// {
// "ret_code": 0,
// "ret_msg": "",
// "ext_code": null,
// "ext_info": null,
// "result": [
// {
// "id": "931975237315196160",
// "symbol": "BTCUSDT",
// "symbolName": "BTCUSDT",
// "orderId": "931975236946097408",
// "ticketId": "1057753175328833537",
// "matchOrderId": "931975113180558592",
// "price": "20000.00001",
// "qty": "0.01",
// "commission": "0.02000000001",
// "commissionAsset": "USDT",
// "time": "1625836105890",
// "isBuyer": false,
// "isMaker": false,
// "fee": {
// "feeTokenId": "USDT",
// "feeTokenName": "USDT",
// "fee": "0.02000000001"
// },
// "feeTokenId": "USDT",
// "feeAmount": "0.02000000001",
// "makerRebate": "0"
// }
// ]
// }
//
// inverse
//
// {
// "ret_code": 0,
// "ret_msg": "OK",
// "ext_code": "",
// "ext_info": "",
// "result": {
// "order_id": "Abandoned!!", // Abandoned!!
// "trade_list": [
// {
// "closed_size": 0,
// "cross_seq": 277136382,
// "exec_fee": "0.0000001",
// "exec_id": "256e5ef8-abfe-5772-971b-f944e15e0d68",
// "exec_price": "8178.5",
// "exec_qty": 1,
// "exec_time": "1571676941.70682",
// "exec_type": "Trade", //Exec Type Enum
// "exec_value": "0.00012227",
// "fee_rate": "0.00075",
// "last_liquidity_ind": "RemovedLiquidity", //Liquidity Enum
// "leaves_qty": 0,
// "nth_fill": 2,
// "order_id": "7ad50cb1-9ad0-4f74-804b-d82a516e1029",
// "order_link_id": "",
// "order_price": "8178",
// "order_qty": 1,
// "order_type": "Market", //Order Type Enum
// "side": "Buy", //Side Enum
// "symbol": "BTCUSD", //Symbol Enum
// "user_id": 1
// }
// ]
// },
// "time_now": "1577483699.281488",
// "rate_limit_status": 118,
// "rate_limit_reset_ms": 1577483699244737,
// "rate_limit": 120
// }
//
// linear
//
// {
// "ret_code":0,
// "ret_msg":"OK",
// "ext_code":"",
// "ext_info":"",
// "result":{
// "current_page":1,
// "data":[
// {
// "order_id":"b59418ec-14d4-4ef9-b9f4-721d5d576974",
// "order_link_id":"",
// "side":"Sell",
// "symbol":"BTCUSDT",
// "exec_id":"0327284d-faec-5191-bd89-acc5b4fafda9",
// "price":0.5,
// "order_price":0.5,
// "order_qty":0.01,
// "order_type":"Market",
// "fee_rate":0.00075,
// "exec_price":9709.5,
// "exec_type":"Trade",
// "exec_qty":0.01,
// "exec_fee":0.07282125,
// "exec_value":97.095,
// "leaves_qty":0,
// "closed_size":0.01,
// "last_liquidity_ind":"RemovedLiquidity",
// "trade_time":1591648052,
// "trade_time_ms":1591648052861
// }
// ]
// },
// "time_now":"1591736501.979264",
// "rate_limit_status":119,
// "rate_limit_reset_ms":1591736501974,
// "rate_limit":120
// }
//
let result = this.safeValue (response, 'result', {});
if (!Array.isArray (result)) {
result = this.safeValue2 (result, 'trade_list', 'data', []);
}
return this.parseTrades (result, market, since, limit);
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'coin': currency['id'],
// 'currency': currency['id'], // alias
// 'start_date': this.iso8601 (since),
// 'end_date': this.iso8601 (till),
'wallet_fund_type': 'Deposit', // Deposit, Withdraw, RealisedPNL, Commission, Refund, Prize, ExchangeOrderWithdraw, ExchangeOrderDeposit
// 'page': 1,
// 'limit': 20, // max 50
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['coin'] = currency['id'];
}
if (since !== undefined) {
request['start_date'] = this.yyyymmdd (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.v2PrivateGetWalletFundRecords (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": {
// "data": [
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
// ]
// },
// "ext_info": null,
// "time_now": "1577481867.115552",
// "rate_limit_status": 119,
// "rate_limit_reset_ms": 1577481867122,
// "rate_limit": 120
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseTransactions (data, currency, since, limit, { 'type': 'deposit' });
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'coin': currency['id'],
// 'start_date': this.iso8601 (since),
// 'end_date': this.iso8601 (till),
// 'status': 'Pending', // ToBeConfirmed, UnderReview, Pending, Success, CancelByUser, Reject, Expire
// 'page': 1,
// 'limit': 20, // max 50
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['coin'] = currency['id'];
}
if (since !== undefined) {
request['start_date'] = this.yyyymmdd (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.v2PrivateGetWalletWithdrawList (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": {
// "data": [
// {
// "id": 137,
// "user_id": 1,
// "coin": "XRP", // Coin Enum
// "status": "Pending", // Withdraw Status Enum
// "amount": "20.00000000",
// "fee": "0.25000000",
// "address": "rH7H595XYEVTEHU2FySYsWnmfACBnZS9zM",
// "tx_id": "",
// "submited_at": "2019-06-11T02:20:24.000Z",
// "updated_at": "2019-06-11T02:20:24.000Z"
// },
// ],
// "current_page": 1,
// "last_page": 1
// },
// "ext_info": null,
// "time_now": "1577482295.125488",
// "rate_limit_status": 119,
// "rate_limit_reset_ms": 1577482295132,
// "rate_limit": 120
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseTransactions (data, currency, since, limit, { 'type': 'withdrawal' });
}
parseTransactionStatus (status) {
const statuses = {
'ToBeConfirmed': 'pending',
'UnderReview': 'pending',
'Pending': 'pending',
'Success': 'ok',
'CancelByUser': 'canceled',
'Reject': 'rejected',
'Expire': 'expired',
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// fetchWithdrawals
//
// {
// "id": 137,
// "user_id": 1,
// "coin": "XRP", // Coin Enum
// "status": "Pending", // Withdraw Status Enum
// "amount": "20.00000000",
// "fee": "0.25000000",
// "address": "rH7H595XYEVTEHU2FySYsWnmfACBnZS9zM",
// "tx_id": "",
// "submited_at": "2019-06-11T02:20:24.000Z",
// "updated_at": "2019-06-11T02:20:24.000Z"
// }
//
// fetchDeposits ledger entries
//
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
//
const currencyId = this.safeString (transaction, 'coin');
const code = this.safeCurrencyCode (currencyId, currency);
const timestamp = this.parse8601 (this.safeString2 (transaction, 'submited_at', 'exec_time'));
const updated = this.parse8601 (this.safeString (transaction, 'updated_at'));
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const address = this.safeString (transaction, 'address');
const feeCost = this.safeNumber (transaction, 'fee');
const type = this.safeStringLower (transaction, 'type');
let fee = undefined;
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': code,
};
}
return {
'info': transaction,
'id': this.safeString (transaction, 'id'),
'txid': this.safeString (transaction, 'tx_id'),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'network': undefined,
'address': address,
'addressTo': undefined,
'addressFrom': undefined,
'tag': undefined,
'tagTo': undefined,
'tagFrom': undefined,
'type': type,
'amount': this.safeNumber (transaction, 'amount'),
'currency': code,
'status': status,
'updated': updated,
'fee': fee,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
// 'coin': currency['id'],
// 'currency': currency['id'], // alias
// 'start_date': this.iso8601 (since),
// 'end_date': this.iso8601 (till),
// 'wallet_fund_type': 'Deposit', // Withdraw, RealisedPNL, Commission, Refund, Prize, ExchangeOrderWithdraw, ExchangeOrderDeposit
// 'page': 1,
// 'limit': 20, // max 50
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['coin'] = currency['id'];
}
if (since !== undefined) {
request['start_date'] = this.yyyymmdd (since);
}
if (limit !== undefined) {
request['limit'] = limit;
}
const response = await this.v2PrivateGetWalletFundRecords (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": {
// "data": [
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
// ]
// },
// "ext_info": null,
// "time_now": "1577481867.115552",
// "rate_limit_status": 119,
// "rate_limit_reset_ms": 1577481867122,
// "rate_limit": 120
// }
//
const result = this.safeValue (response, 'result', {});
const data = this.safeValue (result, 'data', []);
return this.parseLedger (data, currency, since, limit);
}
parseLedgerEntry (item, currency = undefined) {
//
// {
// "id": 234467,
// "user_id": 1,
// "coin": "BTC",
// "wallet_id": 27913,
// "type": "Realized P&L",
// "amount": "-0.00000006",
// "tx_id": "",
// "address": "BTCUSD",
// "wallet_balance": "0.03000330",
// "exec_time": "2019-12-09T00:00:25.000Z",
// "cross_seq": 0
// }
//
const currencyId = this.safeString (item, 'coin');
const code = this.safeCurrencyCode (currencyId, currency);
const amount = this.safeNumber (item, 'amount');
const after = this.safeNumber (item, 'wallet_balance');
const direction = (amount < 0) ? 'out' : 'in';
let before = undefined;
if (after !== undefined && amount !== undefined) {
const difference = (direction === 'out') ? amount : -amount;
before = this.sum (after, difference);
}
const timestamp = this.parse8601 (this.safeString (item, 'exec_time'));
const type = this.parseLedgerEntryType (this.safeString (item, 'type'));
const id = this.safeString (item, 'id');
const referenceId = this.safeString (item, 'tx_id');
return {
'id': id,
'currency': code,
'account': this.safeString (item, 'wallet_id'),
'referenceAccount': undefined,
'referenceId': referenceId,
'status': undefined,
'amount': amount,
'before': before,
'after': after,
'fee': undefined,
'direction': direction,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'type': type,
'info': item,
};
}
parseLedgerEntryType (type) {
const types = {
'Deposit': 'transaction',
'Withdraw': 'transaction',
'RealisedPNL': 'trade',
'Commission': 'fee',
'Refund': 'cashback',
'Prize': 'prize', // ?
'ExchangeOrderWithdraw': 'transaction',
'ExchangeOrderDeposit': 'transaction',
};
return this.safeString (types, type, type);
}
async fetchPositions (symbols = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
if (Array.isArray (symbols)) {
const length = symbols.length;
if (length !== 1) {
throw new ArgumentsRequired (this.id + ' fetchPositions() takes an array with exactly one symbol');
}
request['symbol'] = this.marketId (symbols[0]);
}
const defaultType = this.safeString (this.options, 'defaultType', 'linear');
const type = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
let response = undefined;
if (type === 'linear') {
response = await this.privateLinearGetPositionList (this.extend (request, params));
} else if (type === 'inverse') {
response = await this.v2PrivateGetPositionList (this.extend (request, params));
} else if (type === 'inverseFuture') {
response = await this.futuresPrivateGetPositionList (this.extend (request, params));
}
if ((typeof response === 'string') && this.isJsonEncodedObject (response)) {
response = JSON.parse (response);
}
//
// {
// ret_code: 0,
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [] or {} depending on the request
// }
//
return this.safeValue (response, 'result');
}
async setMarginMode (marginType, symbol = undefined, params = {}) {
//
// {
// "ret_code": 0,
// "ret_msg": "ok",
// "ext_code": "",
// "result": null,
// "ext_info": null,
// "time_now": "1577477968.175013",
// "rate_limit_status": 74,
// "rate_limit_reset_ms": 1577477968183,
// "rate_limit": 75
// }
//
const leverage = this.safeValue (params, 'leverage');
if (leverage === undefined) {
throw new ArgumentsRequired (this.id + ' setMarginMode() requires a leverage parameter');
}
marginType = marginType.toUpperCase ();
if (marginType === 'CROSSED') { // * Deprecated, use 'CROSS' instead
marginType = 'CROSS';
}
if ((marginType !== 'ISOLATED') && (marginType !== 'CROSS')) {
throw new BadRequest (this.id + ' setMarginMode() marginType must be either isolated or cross');
}
await this.loadMarkets ();
const market = this.market (symbol);
let method = undefined;
const defaultType = this.safeString (this.options, 'defaultType', 'linear');
const marketTypes = this.safeValue (this.options, 'marketTypes', {});
const marketType = this.safeString (marketTypes, symbol, defaultType);
const linear = market['linear'] || (marketType === 'linear');
const inverse = (market['swap'] && market['inverse']) || (marketType === 'inverse');
const future = market['future'] || ((marketType === 'future') || (marketType === 'futures')); // * (marketType === 'futures') deprecated, use (marketType === 'future')
if (linear) {
method = 'privateLinearPostPositionSwitchIsolated';
} else if (inverse) {
method = 'v2PrivatePostPositionSwitchIsolated';
} else if (future) {
method = 'privateFuturesPostPositionSwitchIsolated';
}
const isIsolated = (marginType === 'ISOLATED');
const request = {
'symbol': market['id'],
'is_isolated': isIsolated,
'buy_leverage': leverage,
'sell_leverage': leverage,
};
const response = await this[method] (this.extend (request, params));
//
// {
// "ret_code": 0,
// "ret_msg": "OK",
// "ext_code": "",
// "ext_info": "",
// "result": null,
// "time_now": "1585881597.006026",
// "rate_limit_status": 74,
// "rate_limit_reset_ms": 1585881597004,
// "rate_limit": 75
// }
//
return response;
}
async setLeverage (leverage, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' setLeverage() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
// WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
// AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
const defaultType = this.safeString (this.options, 'defaultType', 'linear');
const marketTypes = this.safeValue (this.options, 'marketTypes', {});
const marketType = this.safeString (marketTypes, symbol, defaultType);
const linear = market['linear'] || (marketType === 'linear');
const inverse = (market['swap'] && market['inverse']) || (marketType === 'inverse');
const future = market['future'] || ((marketType === 'future') || (marketType === 'futures')); // * (marketType === 'futures') deprecated, use (marketType === 'future')
let method = undefined;
if (linear) {
method = 'privateLinearPostPositionSetLeverage';
} else if (inverse) {
method = 'v2PrivatePostPositionLeverageSave';
} else if (future) {
method = 'privateFuturesPostPositionLeverageSave';
}
let buy_leverage = leverage;
let sell_leverage = leverage;
if (params['buy_leverage'] && params['sell_leverage'] && linear) {
buy_leverage = params['buy_leverage'];
sell_leverage = params['sell_leverage'];
} else if (!leverage) {
if (linear) {
throw new ArgumentsRequired (this.id + ' setLeverage() requires either the parameter leverage or params["buy_leverage"] and params["sell_leverage"] for linear contracts');
} else {
throw new ArgumentsRequired (this.id + ' setLeverage() requires parameter leverage for inverse and futures contracts');
}
}
if ((buy_leverage < 1) || (buy_leverage > 100) || (sell_leverage < 1) || (sell_leverage > 100)) {
throw new BadRequest (this.id + ' setLeverage() leverage should be between 1 and 100');
}
const request = {
'symbol': market['id'],
'leverage_only': true,
};
if (!linear) {
request['leverage'] = buy_leverage;
} else {
request['buy_leverage'] = buy_leverage;
request['sell_leverage'] = sell_leverage;
}
return await this[method] (this.extend (request, params));
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = undefined;
if (Array.isArray (api)) {
const type = this.safeString (api, 0);
let section = this.safeString (api, 1);
if (type === 'spot') {
if (section === 'public') {
section = 'v1';
} else {
section += '/v1';
}
}
url = this.implodeHostname (this.urls['api'][type]);
let request = '/' + type + '/' + section + '/' + path;
if ((type === 'spot') || (type === 'quote')) {
if (Object.keys (params).length) {
request += '?' + this.rawencode (params);
}
} else if (section === 'public') {
if (Object.keys (params).length) {
request += '?' + this.rawencode (params);
}
} else if (type === 'public') {
if (Object.keys (params).length) {
request += '?' + this.rawencode (params);
}
} else {
this.checkRequiredCredentials ();
const timestamp = this.nonce ();
const query = this.extend (params, {
'api_key': this.apiKey,
'recv_window': this.options['recvWindow'],
'timestamp': timestamp,
});
const sortedQuery = this.keysort (query);
const auth = this.rawencode (sortedQuery);
const signature = this.hmac (this.encode (auth), this.encode (this.secret));
if (method === 'POST') {
body = this.json (this.extend (query, {
'sign': signature,
}));
headers = {
'Content-Type': 'application/json',
};
} else {
request += '?' + this.urlencode (sortedQuery) + '&sign=' + signature;
}
}
url += request;
} else {
url = this.implodeHostname (this.urls['api'][api]) + '/' + path;
if (api === 'public') {
if (Object.keys (params).length) {
url += '?' + this.rawencode (params);
}
} else if (api === 'private') {
this.checkRequiredCredentials ();
const isOpenapi = url.indexOf ('openapi') >= 0;
const timestamp = this.milliseconds ();
if (isOpenapi) {
let query = {};
if (Object.keys (params).length) {
query = params;
}
// this is a PHP specific check
const queryLength = query.length;
if (Array.isArray (query) && queryLength === 0) {
query = '';
} else {
query = this.json (query);
}
body = query;
const payload = timestamp.toString () + this.apiKey + query;
const signature = this.hmac (this.encode (payload), this.encode (this.secret), 'sha256', 'hex');
headers = {
'X-BAPI-API-KEY': this.apiKey,
'X-BAPI-TIMESTAMP': timestamp.toString (),
'X-BAPI-SIGN': signature,
};
} else {
const query = this.extend (params, {
'api_key': this.apiKey,
'recv_window': this.options['recvWindow'],
'timestamp': timestamp,
});
const sortedQuery = this.keysort (query);
const auth = this.rawencode (sortedQuery);
const signature = this.hmac (this.encode (auth), this.encode (this.secret));
if (method === 'POST') {
const isSpot = url.indexOf ('spot') >= 0;
const extendedQuery = this.extend (query, {
'sign': signature,
});
if (!isSpot) {
body = this.json (extendedQuery);
headers = {
'Content-Type': 'application/json',
};
} else {
body = this.urlencode (extendedQuery);
headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
}
} else {
url += '?' + this.urlencode (sortedQuery) + '&sign=' + signature;
}
}
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (!response) {
return; // fallback to default error handler
}
//
// {
// ret_code: 10001,
// ret_msg: 'ReadMapCB: expect { or n, but found \u0000, error ' +
// 'found in #0 byte of ...||..., bigger context ' +
// '...||...',
// ext_code: '',
// ext_info: '',
// result: null,
// time_now: '1583934106.590436'
// }
//
// {
// "retCode":10001,
// "retMsg":"symbol params err",
// "result":{"symbol":"","bid":"","bidIv":"","bidSize":"","ask":"","askIv":"","askSize":"","lastPrice":"","openInterest":"","indexPrice":"","markPrice":"","markPriceIv":"","change24h":"","high24h":"","low24h":"","volume24h":"","turnover24h":"","totalVolume":"","totalTurnover":"","fundingRate":"","predictedFundingRate":"","nextFundingTime":"","countdownHour":"0","predictedDeliveryPrice":"","underlyingPrice":"","delta":"","gamma":"","vega":"","theta":""}
// }
//
const errorCode = this.safeString2 (response, 'ret_code', 'retCode');
if (errorCode !== '0') {
if (errorCode === '30084') {
// not an error
// https://github.com/ccxt/ccxt/issues/11268
// https://github.com/ccxt/ccxt/pull/11624
// POST https://api.bybit.com/v2/private/position/switch-isolated 200 OK
// {"ret_code":30084,"ret_msg":"Isolated not modified","ext_code":"","ext_info":"","result":null,"time_now":"1642005219.937988","rate_limit_status":73,"rate_limit_reset_ms":1642005219894,"rate_limit":75}
return undefined;
}
const feedback = this.id + ' ' + body;
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], body, feedback);
throw new ExchangeError (feedback); // unknown message
}
}
async fetchMarketLeverageTiers (symbol, params = {}) {
await this.loadMarkets ();
const request = {};
let market = undefined;
market = this.market (symbol);
if (market['spot'] || market['option']) {
throw new BadRequest (this.id + ' fetchLeverageTiers() symbol does not support market ' + symbol);
}
request['symbol'] = market['id'];
const isUsdcSettled = market['settle'] === 'USDC';
let method = undefined;
if (isUsdcSettled) {
method = 'publicGetPerpetualUsdcOpenapiPublicV1RiskLimitList';
} else if (market['linear']) {
method = 'publicLinearGetRiskLimit';
} else {
method = 'publicGetV2PublicRiskLimitList';
}
const response = await this[method] (this.extend (request, params));
//
// publicLinearGetRiskLimit
// {
// ret_code: '0',
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// id: '11',
// symbol: 'ETHUSDT',
// limit: '800000',
// maintain_margin: '0.01',
// starting_margin: '0.02',
// section: [
// '1', '2', '3',
// '5', '10', '15',
// '25'
// ],
// is_lowest_risk: '1',
// created_at: '2022-02-04 23:30:33.555252',
// updated_at: '2022-02-04 23:30:33.555254',
// max_leverage: '50'
// },
// ...
// ]
// }
//
// v2PublicGetRiskLimitList
// {
// ret_code: '0',
// ret_msg: 'OK',
// ext_code: '',
// ext_info: '',
// result: [
// {
// id: '180',
// is_lowest_risk: '0',
// section: [
// '1', '2', '3',
// '4', '5', '7',
// '8', '9'
// ],
// symbol: 'ETHUSDH22',
// limit: '30000',
// max_leverage: '9',
// starting_margin: '11',
// maintain_margin: '5.5',
// coin: 'ETH',
// created_at: '2021-04-22T15:00:00Z',
// updated_at: '2021-04-22T15:00:00Z'
// },
// ],
// time_now: '1644017569.683191'
// }
//
const result = this.safeValue (response, 'result');
return this.parseMarketLeverageTiers (result, market);
}
parseMarketLeverageTiers (info, market) {
//
// Linear
// [
// {
// id: '11',
// symbol: 'ETHUSDT',
// limit: '800000',
// maintain_margin: '0.01',
// starting_margin: '0.02',
// section: [
// '1', '2', '3',
// '5', '10', '15',
// '25'
// ],
// is_lowest_risk: '1',
// created_at: '2022-02-04 23:30:33.555252',
// updated_at: '2022-02-04 23:30:33.555254',
// max_leverage: '50'
// },
// ...
// ]
//
// Inverse
// [
// {
// id: '180',
// is_lowest_risk: '0',
// section: [
// '1', '2', '3',
// '4', '5', '7',
// '8', '9'
// ],
// symbol: 'ETHUSDH22',
// limit: '30000',
// max_leverage: '9',
// starting_margin: '11',
// maintain_margin: '5.5',
// coin: 'ETH',
// created_at: '2021-04-22T15:00:00Z',
// updated_at: '2021-04-22T15:00:00Z'
// }
// ...
// ]
//
// usdc swap
//
// {
// "riskId":"10001",
// "symbol":"BTCPERP",
// "limit":"1000000",
// "startingMargin":"0.0100",
// "maintainMargin":"0.0050",
// "isLowestRisk":true,
// "section":[
// "1",
// "2",
// "3",
// "5",
// "10",
// "25",
// "50",
// "100"
// ],
// "maxLeverage":"100.00"
// }
//
let minNotional = 0;
const tiers = [];
for (let i = 0; i < info.length; i++) {
const item = info[i];
const maxNotional = this.safeNumber (item, 'limit');
tiers.push ({
'tier': this.sum (i, 1),
'currency': market['base'],
'minNotional': minNotional,
'maxNotional': maxNotional,
'maintenanceMarginRate': this.safeNumber2 (item, 'maintain_margin', 'maintainMargin'),
'maxLeverage': this.safeNumber2 (item, 'max_leverage', 'maxLeverage'),
'info': item,
});
minNotional = maxNotional;
}
return tiers;
}
};
| use safeMethodN
| js/bybit.js | use safeMethodN | <ide><path>s/bybit.js
<ide> timestamp = this.safeIntegerProduct (order, 'createdAt', 0.001);
<ide> }
<ide> }
<del> let id = this.safeString2 (order, 'order_id', 'stop_order_id');
<del> if (id === undefined) {
<del> id = this.safeString (order, 'orderId');
<del> }
<del> let type = this.safeStringLower2 (order, 'order_type', 'type');
<del> if (type === undefined) {
<del> type = this.safeStringLower (order, 'orderType');
<del> }
<add> const id = this.safeStringN (order, [ 'order_id', 'stop_order_id', 'orderId' ]);
<add> const type = this.safeStringLowerN (order, [ 'order_type', 'type', 'orderType' ]);
<ide> const price = this.safeString2 (order, 'price', 'orderPrice');
<ide> const average = this.safeString2 (order, 'average_price', 'avgPrice');
<del> let amount = this.safeString2 (order, 'qty', 'origQty');
<del> if (amount === undefined) {
<del> amount = this.safeString (order, 'orderQty');
<del> }
<add> const amount = this.safeStringN (order, [ 'qty', 'origQty', 'orderQty' ]);
<ide> const cost = this.safeString (order, 'cum_exec_value');
<ide> const filled = this.safeString2 (order, 'cum_exec_qty', 'executedQty');
<ide> const remaining = this.safeString (order, 'leaves_qty');
<ide> lastTradeTimestamp = this.safeNumber (order, 'updateTime');
<ide> }
<ide> }
<del> let raw_status = this.safeStringLower2 (order, 'order_status', 'stop_order_status');
<del> if (raw_status === undefined) {
<del> raw_status = this.safeStringLower2 (order, 'status', 'orderStatus');
<del> }
<add> const raw_status = this.safeStringLowerN (order, [ 'order_status', 'stop_order_status', 'status', 'orderStatus' ]);
<ide> const status = this.parseOrderStatus (raw_status);
<ide> const side = this.safeStringLower (order, 'side');
<ide> const feeCostString = this.safeString (order, 'cum_exec_fee');
<ide> clientOrderId = undefined;
<ide> }
<ide> const timeInForce = this.parseTimeInForce (this.safeString2 (order, 'time_in_force', 'timeInForce'));
<del> let stopPrice = this.safeString2 (order, 'trigger_price', 'stop_px');
<del> if (stopPrice === undefined) {
<del> stopPrice = this.safeString2 (order, 'stopPrice', 'triggerPrice');
<del> }
<add> const stopPrice = this.safeStringN (order, [ 'trigger_price', 'stop_px', 'stopPrice', 'triggerPrice' ]);
<ide> const postOnly = (timeInForce === 'PO');
<ide> return this.safeOrder ({
<ide> 'info': order, |
|
Java | apache-2.0 | 7346ffe8800b1b3b0d659ef37ab4fb9207cb6cf1 | 0 | jwillia/kc-rice1,sonamuthu/rice-1,jwillia/kc-rice1,cniesen/rice,smith750/rice,bsmith83/rice-1,UniversityOfHawaiiORS/rice,bhutchinson/rice,shahess/rice,smith750/rice,cniesen/rice,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,geothomasp/kualico-rice-kc,kuali/kc-rice,cniesen/rice,shahess/rice,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,smith750/rice,rojlarge/rice-kc,smith750/rice,kuali/kc-rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,kuali/kc-rice,shahess/rice,rojlarge/rice-kc,bhutchinson/rice,cniesen/rice,gathreya/rice-kc,bsmith83/rice-1,bhutchinson/rice,UniversityOfHawaiiORS/rice,shahess/rice,smith750/rice,sonamuthu/rice-1,ewestfal/rice-svn2git-test,kuali/kc-rice,rojlarge/rice-kc,kuali/kc-rice,gathreya/rice-kc,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,ewestfal/rice,bsmith83/rice-1,ewestfal/rice,bhutchinson/rice,ewestfal/rice-svn2git-test,ewestfal/rice,rojlarge/rice-kc,shahess/rice,rojlarge/rice-kc,sonamuthu/rice-1,gathreya/rice-kc,bhutchinson/rice,ewestfal/rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,gathreya/rice-kc,ewestfal/rice-svn2git-test,jwillia/kc-rice1,jwillia/kc-rice1,ewestfal/rice-svn2git-test,ewestfal/rice,cniesen/rice | /*
* Copyright 2005-2006 The Kuali Foundation.
*
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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 org.kuali.rice.kew.routeheader;
import javax.persistence.Transient;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.kew.user.UserUtils;
import org.kuali.rice.kew.web.session.UserSession;
import org.kuali.rice.kim.bo.entity.KimPrincipal;
/**
* An extension of {@link DocumentRouteHeaderValue} which is mapped to OJB to help
* with optimization of the loading of a user's Action List.
*
* @author Kuali Rice Team ([email protected])
*/
//@Entity
//@Table(name="KREW_DOC_HDR_T")
public class DocumentRouteHeaderValueActionListExtension extends DocumentRouteHeaderValue {
private static final long serialVersionUID = 8458532812557846684L;
@Transient
private KimPrincipal actionListInitiatorPrincipal = null;
public KimPrincipal getActionListInitiatorPrincipal() {
return actionListInitiatorPrincipal;
}
public void setActionListInitiatorPrincipal(KimPrincipal actionListInitiatorPrincipal) {
this.actionListInitiatorPrincipal = actionListInitiatorPrincipal;
}
/**
* Gets the initiator name, masked appropriately if restricted.
*/
public String getInitiatorName() {
String initiatorName = UserUtils.getTransposedName(UserSession.getAuthenticatedUser(), getActionListInitiatorPrincipal());
if (StringUtils.isBlank(initiatorName)) {
initiatorName = UserUtils.getDisplayableName(UserSession.getAuthenticatedUser(), getActionListInitiatorPrincipal());
}
if (StringUtils.isBlank(initiatorName) &&
!UserUtils.isEntityNameRestricted(getActionListInitiatorPrincipal().getEntityId())) {
initiatorName = getActionListInitiatorPrincipal().getPrincipalName();
}
return initiatorName;
}
}
| impl/src/main/java/org/kuali/rice/kew/routeheader/DocumentRouteHeaderValueActionListExtension.java | /*
* Copyright 2005-2006 The Kuali Foundation.
*
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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 org.kuali.rice.kew.routeheader;
import javax.persistence.Transient;
import org.kuali.rice.kew.user.UserUtils;
import org.kuali.rice.kew.web.session.UserSession;
import org.kuali.rice.kim.bo.entity.KimPrincipal;
/**
* An extension of {@link DocumentRouteHeaderValue} which is mapped to OJB to help
* with optimization of the loading of a user's Action List.
*
* @author Kuali Rice Team ([email protected])
*/
//@Entity
//@Table(name="KREW_DOC_HDR_T")
public class DocumentRouteHeaderValueActionListExtension extends DocumentRouteHeaderValue {
private static final long serialVersionUID = 8458532812557846684L;
@Transient
private KimPrincipal actionListInitiatorPrincipal = null;
public KimPrincipal getActionListInitiatorPrincipal() {
return actionListInitiatorPrincipal;
}
public void setActionListInitiatorPrincipal(KimPrincipal actionListInitiatorPrincipal) {
this.actionListInitiatorPrincipal = actionListInitiatorPrincipal;
}
/**
* Gets the initiator name, masked appropriately if restricted.
*/
public String getInitiatorName() {
return UserUtils.getTransposedName(UserSession.getAuthenticatedUser(), getActionListInitiatorPrincipal());
}
}
| KULRICE-2930: initiator is showing up blank again on some rows in the action list
https://test.kuali.org/jira/browse/KULRICE-2930
DocumentRouteHeaderValueActionListExtension:
- modified getInitiatorName() to try some other methods of getting the name
should UserUtils.getTransposedName(...) return a null or empty string.
| impl/src/main/java/org/kuali/rice/kew/routeheader/DocumentRouteHeaderValueActionListExtension.java | KULRICE-2930: initiator is showing up blank again on some rows in the action list https://test.kuali.org/jira/browse/KULRICE-2930 | <ide><path>mpl/src/main/java/org/kuali/rice/kew/routeheader/DocumentRouteHeaderValueActionListExtension.java
<ide>
<ide> import javax.persistence.Transient;
<ide>
<add>import org.apache.commons.lang.StringUtils;
<ide> import org.kuali.rice.kew.user.UserUtils;
<ide> import org.kuali.rice.kew.web.session.UserSession;
<ide> import org.kuali.rice.kim.bo.entity.KimPrincipal;
<ide> * Gets the initiator name, masked appropriately if restricted.
<ide> */
<ide> public String getInitiatorName() {
<del> return UserUtils.getTransposedName(UserSession.getAuthenticatedUser(), getActionListInitiatorPrincipal());
<add> String initiatorName = UserUtils.getTransposedName(UserSession.getAuthenticatedUser(), getActionListInitiatorPrincipal());
<add> if (StringUtils.isBlank(initiatorName)) {
<add> initiatorName = UserUtils.getDisplayableName(UserSession.getAuthenticatedUser(), getActionListInitiatorPrincipal());
<add> }
<add> if (StringUtils.isBlank(initiatorName) &&
<add> !UserUtils.isEntityNameRestricted(getActionListInitiatorPrincipal().getEntityId())) {
<add> initiatorName = getActionListInitiatorPrincipal().getPrincipalName();
<add> }
<add> return initiatorName;
<ide> }
<ide>
<ide> } |
|
JavaScript | mit | 7e58341612b3f7a8bc2d9f9a47380a4ff11a9d9b | 0 | grapefruitjs/grapefruit | (function() {
gf.utils = {
applyFriction: function(vel, friction) {
return (
vel + friction < 0 ?
vel + (friction * gf.game._delta) :
(
vel - friction > 0 ?
vel - (friction * gf.game._delta) :
0
)
);
},
_arrayDelim: '|',
ensureVector: function(vec) {
if(vec instanceof THREE.Vector2 || vec instanceof THREE.Vector3)
return vec;
var a = vec;
if(typeof vec == 'string') a = vec.split(gf.utils._arrayDelim);
if(a instanceof Array) {
switch(a.length) {
case 2: return new THREE.Vector2(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0);
case 3: return new THREE.Vector3(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0, parseInt(a[2], 10));
}
}
else {
return new THREE.Vector2();
}
},
spawnSquare: function(x, y, w, h, color) {
var mesh = new THREE.Mesh(
new THREE.PlaneGeometry(w || 1, h || 1),
new THREE.MeshBasicMaterial({ color: color || 0xff0000 })
);
mesh.position.set(x || 0, y || 0, 400);
gf.game._scene.add(mesh);
},
numToHexColor: function(num) { return ('00000000' + num.toString(16)).substr(-8); },
RGBToHex: function(r, g, b) { return r.toHex() + g.toHex() + b.toHex(); },
noop: function() {},
ajax: function(sets) {
//base settings
sets = sets || {};
sets.method = sets.method || 'GET';
sets.dataType = sets.dataType || 'text';
//callbacks
sets.progress = sets.progress || gf.utils.noop;
sets.load = sets.load || gf.utils.noop;
sets.error = sets.error || gf.utils.noop;
sets.abort = sets.abort || gf.utils.noop;
sets.complete = sets.complete || gf.utils.noop;
//start the XHR request
var xhr = new XMLHttpRequest();
xhr.addEventListener('progress', sets.progress.bind(xhr), false);
xhr.addEventListener('error', sets.error.bind(xhr), false);
xhr.addEventListener('abort', sets.abort.bind(xhr), false);
xhr.addEventListener('loadend', sets.complete.bind(xhr), false);
xhr.addEventListener('load', function() {
var res = xhr.response,
err = null;
if(sets.dataType === 'json' && typeof res === 'string') {
try { res = JSON.parse(res); }
catch(e) { err = e; }
}
if(err) {
if(sets.error) sets.error.call(xhr, err);
} else {
if(sets.load) sets.load.call(xhr, res);
}
}, false);
xhr.open(sets.method, sets.url, true);
xhr.send();
},
//similar to https://github.com/mrdoob/three.js/blob/master/src/materials/Material.js#L42
setValues: function(obj, values) {
if(!values) return;
for(var key in values) {
var newVal = values[key];
if(newVal === undefined) {
console.warn('Object parameter "' + key + '" is undefined.');
continue;
}
if(key in obj) {
var curVal = obj[key];
//type massaging
if(typeof curVal === 'number' && typeof newVal === 'string') {
var n;
if(newVal.indexOf('0x') === 0) n = parseInt(newVal, 16);
else n = parseInt(newVal, 10);
if(!isNaN(n))
curVal = n;
else
console.warn('Object parameter "' + key + '" evaluated to NaN, using default. Value passed: ' + newVal);
} else if(curVal instanceof THREE.Color && typeof newVal === 'number') {
curVal.setHex(newVal);
} else if(curVal instanceof THREE.Vector2 && newVal instanceof Array) {
curVal.set(newVal[0] || 0, newVal[1] || 0);
} else if(curVal instanceof THREE.Vector3 && newVal instanceof Array) {
curVal.set(newVal[0] || 0, newVal[1] || 0, newVal[2] || 0);
} else if(curVal instanceof THREE.Vector2 && typeof newVal === 'string') {
var a = newVal.split(gf.utils._arrayDelim, 2);
curVal.set(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0);
} else if(curVal instanceof THREE.Vector3 && typeof newVal === 'string') {
var a = newVal.split(gf.utils._arrayDelim, 3);
curVal.set(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0, parseInt(a[2], 10) || 0);
} else if(curVal instanceof Array && typeof newVal === 'string') {
curVal = newVal.split(gf.utils._arrayDelim);
gf.utils.each(curVal, function(i, val) {
if(!isNaN(val)) curVal[i] = parseInt(val, 10);
});
} else {
obj[key] = newVal;
}
}
}
return obj;
},
clamp: function(n, min, max) { return Math.max(min, Math.min(max, n)); },
isPowerOfTwo: function(n) { return ((n & (n - 1)) === 0); },
nextPowerofTwo: function(n) { return Math.pow(2, Math.ceil(Math.log(n)/Math.LN2)); },
//http://jsperf.com/find-power
getPowerofTwoPower: function(n) {
if(!gf.utils.isPowerOfTwo(n) || n === 0) return undefined;
var p = 0;
while (n >>= 1) ++p;
return p;
},
getPosition: function(o) {
var l = o.offsetLeft,
t = o.offsetTop;
while(o = o.offsetParent) {
l += o.offsetLeft;
t += o.offsetTop;
}
return {
top: t,
left: l
};
},
getStyle: function(elm, prop) {
var style = window.getComputedStyle(elm);
return parseInt(style.getPropertyValue(prop).replace(/px|em|%|pt/, ''), 10);
},
setStyle: function(elm, prop, value) {
var style = window.getComputedStyle(elm);
return style.setPropertyValue(prop, value);
},
//Some things stolen from jQuery
getOffset: function(elem) {
var doc = elem && elem.ownerDocument,
docElem = doc.documentElement;
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// Make sure we're not dealing with a disconnected DOM node
if (!box || !(docElem !== elem && (docElem.contains ? docElem.contains(elem) : true))) { //(!box || !jQuery.contains(docElem, elem)) {
return box ? {
top: box.top,
left: box.left
} : {
top: 0,
left: 0
};
}
var body = doc.body,
win = window,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return {
top: top,
left: left
};
},
each: function(object, callback, args) {
var name, i = 0,
length = object.length,
isObj = length === undefined || typeof object == 'function';
if (args) {
if (isObj) {
for (name in object) {
if (callback.apply(object[name], args) === false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.apply(object[i++], args) === false) {
break;
}
}
}
} else {
if (isObj) {
for (name in object) {
if (callback.call(object[name], name, object[name]) === false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.call(object[i], i, object[i++]) === false) {
break;
}
}
}
}
return object;
},
project: {
_projector: new THREE.Projector(),
positionToViewport: function(position) {
var vector = gf.utils.project._projector.projectVector(position, gf.game._camera),
hWidth = gf.game._domElement.width / 2,
hHeight = gf.game._domElement.height / 2;
return new THREE.Vector2(
Math.round(vector.x * hWidth + hWidth),
Math.round(-vector.y * hHeight + hHeight)
);
},
positionToScreen: function(position) {
var pos = gf.utils.project.positionToViewport(position),
offset = gf.utils.getOffset(gf.game._domElement);
pos.x += offset.left;
pos.y += offset.top;
return pos;
},
screenToPosition: function(pos) {
var vector = new THREE.Vector3(
(pos.x * 2) - 1,
(-pos.y * 2) + 1,
0.5
);
gf.utils.project._projector.unprojectVector(vector, gf.game._camera);
var dir = vector.sub(gf.game._camera.position).normalize(),
ray = new THREE.Ray(gf.game._camera.position, dir),
distance = - gf.game._camera.position.z / dir.z;
return gf.game._camera.position.clone().add(dir.multiplyScalar(distance));
}
},
b64: {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: (window.btoa !== undefined) ? function() { return window.btoa.apply(window, arguments); } : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = gf.util.b64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: (window.atob !== undefined) ? function() { return window.atob.apply(window, arguments); } : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = gf.util.b64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
};
})(); | src/utils/utils.js | (function() {
gf.utils = {
applyFriction: function(vel, friction) {
return (
vel + friction < 0 ?
vel + (friction * gf.game._delta) :
(
vel - friction > 0 ?
vel - (friction * gf.game._delta) :
0
)
);
},
_arrayDelim: '|',
ensureVector: function(vec) {
if(vec instanceof THREE.Vector2 || vec instanceof THREE.Vector3)
return vec;
var a = vec;
if(typeof vec == 'string') a = vec.split(gf.utils._arrayDelim);
if(a instanceof Array) {
switch(a.length) {
case 2: return new THREE.Vector2(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0);
case 3: return new THREE.Vector3(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0, parseInt(a[2], 10));
}
}
else {
return new THREE.Vector2();
}
},
spawnSquare: function(x, y, w, h, color) {
var mesh = new THREE.Mesh(
new THREE.PlaneGeometry(w || 1, h || 1),
new THREE.MeshBasicMaterial({ color: color || 0xff0000 })
);
mesh.position.set(x || 0, y || 0, 400);
gf.game._scene.add(mesh);
},
numToHexColor: function(num) { return ("00000000" + num.toString(16)).substr(-8); },
RGBToHex: function(r, g, b) { return r.toHex() + g.toHex() + b.toHex(); },
noop: function() {},
ajax: function(sets) {
//base settings
sets = sets || {};
sets.method = sets.method || 'GET';
sets.dataType = sets.dataType || 'text';
//callbacks
sets.progress = sets.progress || gf.utils.noop;
sets.load = sets.load || gf.utils.noop;
sets.error = sets.error || gf.utils.noop;
sets.abort = sets.abort || gf.utils.noop;
sets.complete = sets.complete || gf.utils.noop;
//start the XHR request
var xhr = new XMLHttpRequest();
xhr.addEventListener('progress', sets.progress.bind(xhr), false);
xhr.addEventListener('error', sets.error.bind(xhr), false);
xhr.addEventListener('abort', sets.abort.bind(xhr), false);
xhr.addEventListener('loadend', sets.complete.bind(xhr), false);
xhr.addEventListener('load', function() {
var res = xhr.response,
err = null;
if(sets.dataType === 'json' && typeof res === 'string') {
try { res = JSON.parse(res); }
catch(e) { err = e; }
}
if(err) {
if(sets.error) sets.error.call(xhr, err);
} else {
if(sets.load) sets.load.call(xhr, res);
}
}, false);
xhr.open(sets.method, sets.url, true);
xhr.send();
},
//similar to https://github.com/mrdoob/three.js/blob/master/src/materials/Material.js#L42
setValues: function(obj, values) {
if(!values) return;
for(var key in values) {
var newVal = values[key];
if(newVal === undefined) {
console.warn('Object parameter "' + key + '" is undefined.');
continue;
}
if(key in obj) {
var curVal = obj[key];
//type massaging
if(typeof curVal === 'number' && typeof newVal === 'string') {
var n;
if(newVal.indexOf('0x') === 0) n = parseInt(newVal, 16);
else n = parseInt(newVal, 10);
if(!isNaN(n))
curVal = n;
else
console.warn('Object parameter "' + key + '" evaluated to NaN, using default. Value passed: ' + newVal);
} else if(curVal instanceof THREE.Color && typeof newVal === 'number') {
curVal.setHex(newVal);
} else if(curVal instanceof THREE.Vector2 && newVal instanceof Array) {
curVal.set(newVal[0] || 0, newVal[1] || 0);
} else if(curVal instanceof THREE.Vector3 && newVal instanceof Array) {
curVal.set(newVal[0] || 0, newVal[1] || 0, newVal[2] || 0);
} else if(curVal instanceof THREE.Vector2 && typeof newVal === 'string') {
var a = newVal.split(gf.utils._arrayDelim, 2);
curVal.set(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0);
} else if(curVal instanceof THREE.Vector3 && typeof newVal === 'string') {
var a = newVal.split(gf.utils._arrayDelim, 3);
curVal.set(parseInt(a[0], 10) || 0, parseInt(a[1], 10) || 0, parseInt(a[2], 10) || 0);
} else if(curVal instanceof Array && typeof newVal === 'string') {
curVal = newVal.split(gf.utils._arrayDelim);
gf.utils.each(curVal, function(i, val) {
if(!isNaN(val)) curVal[i] = parseInt(val, 10);
});
} else {
obj[key] = newVal;
}
}
}
return obj;
},
clamp: function(n, min, max) { return Math.max(min, Math.min(max, n)); },
isPowerOfTwo: function(n) { return ((n & (n - 1)) === 0); },
nextPowerofTwo: function(n) { return Math.pow(2, Math.ceil(Math.log(n)/Math.LN2)); },
//http://jsperf.com/find-power
getPowerofTwoPower: function(n) {
if(!gf.utils.isPowerOfTwo(n) || n === 0) return undefined;
var p = 0;
while (n >>= 1) ++p;
return p;
},
getPosition: function(o) {
var l = o.offsetLeft,
t = o.offsetTop;
while(o = o.offsetParent) {
l += o.offsetLeft;
t += o.offsetTop;
}
return {
top: t,
left: l
};
},
getStyle: function(elm, prop) {
var style = window.getComputedStyle(elm);
return parseInt(style.getPropertyValue(prop).replace(/px|em|%|pt/, ''), 10);
},
setStyle: function(elm, prop, value) {
var style = window.getComputedStyle(elm);
return style.setPropertyValue(prop, value);
},
//Some things stolen from jQuery
getOffset: function(elem) {
var doc = elem && elem.ownerDocument,
docElem = doc.documentElement;
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// Make sure we're not dealing with a disconnected DOM node
if (!box || !(docElem !== elem && (docElem.contains ? docElem.contains(elem) : true))) { //(!box || !jQuery.contains(docElem, elem)) {
return box ? {
top: box.top,
left: box.left
} : {
top: 0,
left: 0
};
}
var body = doc.body,
win = window,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return {
top: top,
left: left
};
},
each: function(object, callback, args) {
var name, i = 0,
length = object.length,
isObj = length === undefined || typeof object == 'function';
if (args) {
if (isObj) {
for (name in object) {
if (callback.apply(object[name], args) === false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.apply(object[i++], args) === false) {
break;
}
}
}
} else {
if (isObj) {
for (name in object) {
if (callback.call(object[name], name, object[name]) === false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.call(object[i], i, object[i++]) === false) {
break;
}
}
}
}
return object;
},
project: {
_projector: new THREE.Projector(),
positionToViewport: function(position) {
var vector = gf.utils.project._projector.projectVector(position, gf.game._camera),
hWidth = gf.game._domElement.width / 2,
hHeight = gf.game._domElement.height / 2;
return new THREE.Vector2(
Math.round(vector.x * hWidth + hWidth),
Math.round(-vector.y * hHeight + hHeight)
);
},
positionToScreen: function(position) {
var pos = gf.utils.project.positionToViewport(position),
offset = gf.utils.getOffset(gf.game._domElement);
pos.x += offset.left;
pos.y += offset.top;
return pos;
},
screenToPosition: function(pos) {
var vector = new THREE.Vector3(
(pos.x * 2) - 1,
(-pos.y * 2) + 1,
0.5
);
gf.utils.project._projector.unprojectVector(vector, gf.game._camera);
var dir = vector.sub(gf.game._camera.position).normalize(),
ray = new THREE.Ray(gf.game._camera.position, dir),
distance = - gf.game._camera.position.z / dir.z;
return gf.game._camera.position.clone().add(dir.multiplyScalar(distance));
}
},
b64: {
// private property
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode: (window.btoa !== undefined) ? function() { return window.btoa.apply(window, arguments); } : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = gf.util.b64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: (window.atob !== undefined) ? function() { return window.atob.apply(window, arguments); } : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = gf.util.b64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
};
})(); | small quote change
| src/utils/utils.js | small quote change | <ide><path>rc/utils/utils.js
<ide> mesh.position.set(x || 0, y || 0, 400);
<ide> gf.game._scene.add(mesh);
<ide> },
<del> numToHexColor: function(num) { return ("00000000" + num.toString(16)).substr(-8); },
<add> numToHexColor: function(num) { return ('00000000' + num.toString(16)).substr(-8); },
<ide> RGBToHex: function(r, g, b) { return r.toHex() + g.toHex() + b.toHex(); },
<ide> noop: function() {},
<ide> ajax: function(sets) { |
|
Java | apache-2.0 | 3dd582475b1054aa65ae4886e8c655991cae61b8 | 0 | xmpace/jetty-read,jetty-project/jetty-plugin-support,jetty-project/jetty-plugin-support,xmpace/jetty-read,thomasbecker/jetty-7,jetty-project/jetty-plugin-support,thomasbecker/jetty-spdy,xmpace/jetty-read,thomasbecker/jetty-7,thomasbecker/jetty-spdy,xmpace/jetty-read,thomasbecker/jetty-spdy | package org.eclipse.jetty.websocket;
import static org.hamcrest.CoreMatchers.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class WebSocketClientTest
{
private ServerSocket server;
private int serverPort;
@Before
public void startServer() throws IOException {
server = new ServerSocket();
server.bind(null);
serverPort = server.getLocalPort();
}
@After
public void stopServer() throws IOException {
if(server != null) {
server.close();
}
}
@Test
public void testBadURL() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
try
{
client.open(new URI("http://localhost:8080"),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
}
public void onError(String message, Throwable ex)
{
}
public void onClose(int closeCode, String message)
{}
});
Assert.fail();
}
catch(IllegalArgumentException e)
{
bad=true;
}
Assert.assertTrue(bad);
Assert.assertFalse(open.get());
}
@Test
public void testBlockingConnectionRefused() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.start();
client.setBlockingConnect(true);
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
try
{
client.open(new URI("ws://127.0.0.1:1"),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
}
public void onError(String message, Throwable ex)
{
}
public void onClose(int closeCode, String message)
{}
});
Assert.fail();
}
catch(IOException e)
{
bad=true;
}
Assert.assertTrue(bad);
Assert.assertFalse(open.get());
}
@Test
public void testAsyncConnectionRefused() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setConnectTimeout(1000);
client.start();
client.setBlockingConnect(false);
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:1"),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testBlockingConnectionNotAccepted() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setConnectTimeout(500);
client.setBlockingConnect(true);
client.start();
boolean bad=false;
final AtomicReference<String> error = new AtomicReference<String>(null);
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
latch.countDown();
}
});
}
catch(IOException e)
{
e.printStackTrace();
bad=true;
}
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertTrue(bad||error.get()!=null);
}
@Test
public void testAsyncConnectionNotAccepted() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(300);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testBlockingConnectionTimeout() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setConnectTimeout(500);
client.setBlockingConnect(true);
client.start();
boolean bad=false;
final AtomicReference<String> error = new AtomicReference<String>(null);
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
latch.countDown();
}
});
}
catch(IOException e)
{
e.printStackTrace();
bad=true;
}
Assert.assertNotNull(server.accept());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertTrue(bad||error.get()!=null);
}
@Test
public void testAsyncConnectionTimeout() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(300);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertNotNull(server.accept());
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testBadHandshake() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(300);
client.start();
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
System.out.printf("onOpen(%s)%n", connection);
System.out.flush();
// TODO I don't think we should be seeing onOpen called on the
// bad handshake because the error here should mean that there is no
// websocket, so no onOpen call
// what we are seeing is the onOpen is intermittently showing up before the
// onError which triggers the countdown latch and the error message is null
// at that point.
//open.set(true);
//latch.countDown();
}
public void onError(String message, Throwable ex)
{
System.out.printf("onError(%s, %s)%n", message, ex);
System.out.flush();
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
System.out.printf("onClose(%d, %s)%n", closeCode, message);
System.out.flush();
close.set(closeCode);
latch.countDown();
}
});
Socket connection = server.accept();
respondToClient(connection, "HTTP/1.1 404 NOT FOUND\r\n\r\n");
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(10,TimeUnit.SECONDS));
Assert.assertThat("error.get()", error.get(), containsString("404 NOT FOUND"));
}
private void respondToClient(Socket connection, String serverResponse) throws IOException
{
InputStream in = null;
InputStreamReader isr = null;
BufferedReader buf = null;
OutputStream out = null;
try {
in = connection.getInputStream();
isr = new InputStreamReader(in);
buf = new BufferedReader(isr);
String line;
while((line = buf.readLine())!=null) {
System.err.println(line);
if(line.length() == 0) {
// Got the "\r\n" line.
break;
}
}
// System.out.println("[Server-Out] " + serverResponse);
out = connection.getOutputStream();
out.write(serverResponse.getBytes());
out.flush();
} finally {
IO.close(buf);
IO.close(isr);
IO.close(in);
IO.close(out);
}
}
@Test
public void testBadUpgrade() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
// System.err.println(line);
if (line.length()==0)
break;
}
connection.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: rubbish\r\n" +
"\r\n").getBytes());
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testUpgrade() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
String key="not sent";
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
if (line.length()==0)
break;
if (line.startsWith("Sec-WebSocket-Key:"))
key=line.substring(18).trim();
}
connection.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: "+ WebSocketConnectionD10.hashKey(key) +"\r\n" +
"\r\n").getBytes());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNull(error.get());
Assert.assertTrue(open.get());
}
@Test
public void testIdle() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.setMaxIdleTime(500);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(2);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
String key="not sent";
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
if (line.length()==0)
break;
if (line.startsWith("Sec-WebSocket-Key:"))
key=line.substring(18).trim();
}
connection.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: "+ WebSocketConnectionD10.hashKey(key) +"\r\n" +
"\r\n").getBytes());
Assert.assertTrue(latch.await(10,TimeUnit.SECONDS));
Assert.assertTrue(open.get());
Assert.assertEquals(WebSocketConnectionD10.CLOSE_NORMAL,close.get());
}
@Test
public void testNotIdle() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.setMaxIdleTime(500);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final Exchanger<Integer> close = new Exchanger<Integer>();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<WebSocket.Connection> connection = new AtomicReference<WebSocket.Connection>();
final BlockingQueue<String> queue = new BlockingArrayQueue<String>();
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket.OnTextMessage()
{
public void onOpen(Connection c)
{
open.set(true);
connection.set(c);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
latch.countDown();
}
public void onClose(int closeCode, String message)
{
try
{
close.exchange(closeCode);
}
catch(InterruptedException ex)
{}
latch.countDown();
}
public void onMessage(String data)
{
queue.add(data);
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
String key="not sent";
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
if (line.length()==0)
break;
if (line.startsWith("Sec-WebSocket-Key:"))
key=line.substring(18).trim();
}
socket.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: "+ WebSocketConnectionD10.hashKey(key) +"\r\n" +
"\r\n").getBytes());
Assert.assertTrue(latch.await(10,TimeUnit.SECONDS));
Assert.assertTrue(open.get());
// Send some messages client to server
byte[] recv = new byte[1024];
int len=-1;
for (int i=0;i<10;i++)
{
Thread.sleep(250);
connection.get().sendMessage("Hello");
len=socket.getInputStream().read(recv,0,recv.length);
Assert.assertTrue(len>0);
}
// Send some messages server to client
byte[] send = new byte[] { (byte)0x81, (byte) 0x02, (byte)'H', (byte)'i'};
for (int i=0;i<10;i++)
{
Thread.sleep(250);
socket.getOutputStream().write(send,0,send.length);
socket.getOutputStream().flush();
Assert.assertEquals("Hi",queue.poll(1,TimeUnit.SECONDS));
}
socket.getOutputStream().write(new byte[]{(byte)0x88, (byte) 0x02, (byte)4, (byte)87 },0,4);
socket.getOutputStream().flush();
Assert.assertEquals(new Integer(1111),close.exchange(null,1,TimeUnit.SECONDS));
}
}
| jetty-websocket/src/test/java/org/eclipse/jetty/websocket/WebSocketClientTest.java | package org.eclipse.jetty.websocket;
import static org.hamcrest.CoreMatchers.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.IO;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class WebSocketClientTest
{
private ServerSocket server;
private int serverPort;
@Before
public void startServer() throws IOException {
server = new ServerSocket();
server.bind(null);
serverPort = server.getLocalPort();
}
@After
public void stopServer() throws IOException {
if(server != null) {
server.close();
}
}
@Test
public void testBadURL() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
try
{
client.open(new URI("http://localhost:8080"),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
}
public void onError(String message, Throwable ex)
{
}
public void onClose(int closeCode, String message)
{}
});
Assert.fail();
}
catch(IllegalArgumentException e)
{
bad=true;
}
Assert.assertTrue(bad);
Assert.assertFalse(open.get());
}
@Test
public void testBlockingConnectionRefused() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.start();
client.setBlockingConnect(true);
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
try
{
client.open(new URI("ws://127.0.0.1:1"),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
}
public void onError(String message, Throwable ex)
{
}
public void onClose(int closeCode, String message)
{}
});
Assert.fail();
}
catch(IOException e)
{
bad=true;
}
Assert.assertTrue(bad);
Assert.assertFalse(open.get());
}
@Test
public void testAsyncConnectionRefused() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setConnectTimeout(1000);
client.start();
client.setBlockingConnect(false);
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:1"),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testBlockingConnectionNotAccepted() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setConnectTimeout(500);
client.setBlockingConnect(true);
client.start();
boolean bad=false;
final AtomicReference<String> error = new AtomicReference<String>(null);
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
latch.countDown();
}
});
}
catch(IOException e)
{
e.printStackTrace();
bad=true;
}
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertTrue(bad||error.get()!=null);
}
@Test
public void testAsyncConnectionNotAccepted() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(300);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testBlockingConnectionTimeout() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setConnectTimeout(500);
client.setBlockingConnect(true);
client.start();
boolean bad=false;
final AtomicReference<String> error = new AtomicReference<String>(null);
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
latch.countDown();
}
});
}
catch(IOException e)
{
e.printStackTrace();
bad=true;
}
Assert.assertNotNull(server.accept());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertTrue(bad||error.get()!=null);
}
@Test
public void testAsyncConnectionTimeout() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(300);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertNotNull(server.accept());
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testBadHandshake() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(300);
client.start();
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
System.out.printf("onOpen(%s)%n", connection);
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
System.out.printf("onError(%s, %s)%n", message, ex);
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
System.out.printf("onClose(%d, %s)%n", closeCode, message);
close.set(closeCode);
latch.countDown();
}
});
Socket connection = server.accept();
respondToClient(connection, "HTTP/1.1 404 NOT FOUND\r\n\r\n");
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(2,TimeUnit.SECONDS));
Assert.assertThat("error.get()", error.get(), containsString("404 NOT FOUND"));
}
private void respondToClient(Socket connection, String serverResponse) throws IOException
{
InputStream in = null;
InputStreamReader isr = null;
BufferedReader buf = null;
OutputStream out = null;
try {
in = connection.getInputStream();
isr = new InputStreamReader(in);
buf = new BufferedReader(isr);
String line;
while((line = buf.readLine())!=null) {
System.err.println(line);
if(line.length() == 0) {
// Got the "\r\n" line.
break;
}
}
// System.out.println("[Server-Out] " + serverResponse);
out = connection.getOutputStream();
out.write(serverResponse.getBytes());
out.flush();
} finally {
IO.close(buf);
IO.close(isr);
IO.close(in);
IO.close(out);
}
}
@Test
public void testBadUpgrade() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
// System.err.println(line);
if (line.length()==0)
break;
}
connection.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: rubbish\r\n" +
"\r\n").getBytes());
Assert.assertFalse(bad);
Assert.assertFalse(open.get());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNotNull(error.get());
}
@Test
public void testUpgrade() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicReference<String> error = new AtomicReference<String>(null);
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
error.set(message);
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
String key="not sent";
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
if (line.length()==0)
break;
if (line.startsWith("Sec-WebSocket-Key:"))
key=line.substring(18).trim();
}
connection.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: "+ WebSocketConnectionD10.hashKey(key) +"\r\n" +
"\r\n").getBytes());
Assert.assertTrue(latch.await(1,TimeUnit.SECONDS));
Assert.assertNull(error.get());
Assert.assertTrue(open.get());
}
@Test
public void testIdle() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.setMaxIdleTime(500);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final AtomicInteger close = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(2);
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket()
{
public void onOpen(Connection connection)
{
open.set(true);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
latch.countDown();
}
public void onClose(int closeCode, String message)
{
close.set(closeCode);
latch.countDown();
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
String key="not sent";
Socket connection = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
if (line.length()==0)
break;
if (line.startsWith("Sec-WebSocket-Key:"))
key=line.substring(18).trim();
}
connection.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: "+ WebSocketConnectionD10.hashKey(key) +"\r\n" +
"\r\n").getBytes());
Assert.assertTrue(latch.await(10,TimeUnit.SECONDS));
Assert.assertTrue(open.get());
Assert.assertEquals(WebSocketConnectionD10.CLOSE_NORMAL,close.get());
}
@Test
public void testNotIdle() throws Exception
{
WebSocketClient client = new WebSocketClient();
client.setBlockingConnect(true);
client.setConnectTimeout(10000);
client.setMaxIdleTime(500);
client.start();
boolean bad=false;
final AtomicBoolean open = new AtomicBoolean();
final Exchanger<Integer> close = new Exchanger<Integer>();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<WebSocket.Connection> connection = new AtomicReference<WebSocket.Connection>();
final BlockingQueue<String> queue = new BlockingArrayQueue<String>();
try
{
client.open(new URI("ws://127.0.0.1:"+serverPort),new WebSocket.OnTextMessage()
{
public void onOpen(Connection c)
{
open.set(true);
connection.set(c);
latch.countDown();
}
public void onError(String message, Throwable ex)
{
latch.countDown();
}
public void onClose(int closeCode, String message)
{
try
{
close.exchange(closeCode);
}
catch(InterruptedException ex)
{}
latch.countDown();
}
public void onMessage(String data)
{
queue.add(data);
}
});
}
catch(IOException e)
{
bad=true;
}
Assert.assertFalse(bad);
String key="not sent";
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
for (String line=in.readLine();line!=null;line=in.readLine())
{
if (line.length()==0)
break;
if (line.startsWith("Sec-WebSocket-Key:"))
key=line.substring(18).trim();
}
socket.getOutputStream().write((
"HTTP/1.1 101 Upgrade\r\n" +
"Sec-WebSocket-Accept: "+ WebSocketConnectionD10.hashKey(key) +"\r\n" +
"\r\n").getBytes());
Assert.assertTrue(latch.await(10,TimeUnit.SECONDS));
Assert.assertTrue(open.get());
// Send some messages client to server
byte[] recv = new byte[1024];
int len=-1;
for (int i=0;i<10;i++)
{
Thread.sleep(250);
connection.get().sendMessage("Hello");
len=socket.getInputStream().read(recv,0,recv.length);
Assert.assertTrue(len>0);
}
// Send some messages server to client
byte[] send = new byte[] { (byte)0x81, (byte) 0x02, (byte)'H', (byte)'i'};
for (int i=0;i<10;i++)
{
Thread.sleep(250);
socket.getOutputStream().write(send,0,send.length);
socket.getOutputStream().flush();
Assert.assertEquals("Hi",queue.poll(1,TimeUnit.SECONDS));
}
socket.getOutputStream().write(new byte[]{(byte)0x88, (byte) 0x02, (byte)4, (byte)87 },0,4);
socket.getOutputStream().flush();
Assert.assertEquals(new Integer(1111),close.exchange(null,1,TimeUnit.SECONDS));
}
}
| Resolve test case issue with comment for Greg on proper order of on*
responses for websocket interface | jetty-websocket/src/test/java/org/eclipse/jetty/websocket/WebSocketClientTest.java | Resolve test case issue with comment for Greg on proper order of on* responses for websocket interface | <ide><path>etty-websocket/src/test/java/org/eclipse/jetty/websocket/WebSocketClientTest.java
<ide> public void onOpen(Connection connection)
<ide> {
<ide> System.out.printf("onOpen(%s)%n", connection);
<del> open.set(true);
<del> latch.countDown();
<add> System.out.flush();
<add>
<add> // TODO I don't think we should be seeing onOpen called on the
<add> // bad handshake because the error here should mean that there is no
<add> // websocket, so no onOpen call
<add> // what we are seeing is the onOpen is intermittently showing up before the
<add> // onError which triggers the countdown latch and the error message is null
<add> // at that point.
<add>
<add> //open.set(true);
<add> //latch.countDown();
<ide> }
<ide>
<ide> public void onError(String message, Throwable ex)
<ide> {
<ide> System.out.printf("onError(%s, %s)%n", message, ex);
<add> System.out.flush();
<ide> error.set(message);
<ide> latch.countDown();
<ide> }
<ide> public void onClose(int closeCode, String message)
<ide> {
<ide> System.out.printf("onClose(%d, %s)%n", closeCode, message);
<add> System.out.flush();
<ide> close.set(closeCode);
<ide> latch.countDown();
<ide> }
<ide> respondToClient(connection, "HTTP/1.1 404 NOT FOUND\r\n\r\n");
<ide>
<ide> Assert.assertFalse(open.get());
<del> Assert.assertTrue(latch.await(2,TimeUnit.SECONDS));
<add> Assert.assertTrue(latch.await(10,TimeUnit.SECONDS));
<ide> Assert.assertThat("error.get()", error.get(), containsString("404 NOT FOUND"));
<ide> }
<ide> |
|
Java | apache-2.0 | f150c9fe845b11b7e3ed5ceae4f33a59f7ccf633 | 0 | cirg-up/cilib | /*
* Branin.java
*
* Created on June 4, 2003, 4:57 PM
*
*
* Copyright (C) 2003 - 2007
* Computational Intelligence Research Group (CIRG@UP)
* Department of Computer Science
* University of Pretoria
* South Africa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sourceforge.cilib.functions.continuous.unconstrained;
import java.io.Serializable;
import net.sourceforge.cilib.functions.ContinuousFunction;
import net.sourceforge.cilib.type.types.container.Vector;
/**
* <p><b>Booth Function</b></p>
*
* <p><b>Reference:</b> X. Yao, Y. Liu, G. Liu, <i>Evolutionary Programming Made Faster</i>,
* IEEE Transactions on Evolutionary Computation, 3(1):82--102, 1999</p>
*
* <p>Minimum:
* <ul>
* <li> f(<b>x</b>*) = 0.397887 </li>
* <li> <b>x</b>* = (-pi, 12.275), (pi, 2.275), (9.425, 2.425)</li>
* <li> for x_1 in [-5,10], x_2 in [0,15]</li>
* </ul>
* </p>
*
* <p>Characteristics:
* <ul>
* <li>Only defined for 2 dimensions</li>
* <li>Has 3 global minima</li>
* <li>Unimodal</li>
* <li>Seperable</li>
* <li>Regular</li>
* </ul>
* </p>
*
* @author Clive Naicker
*
*/
public class Branin extends ContinuousFunction implements Serializable {
private static final long serialVersionUID = -2254223453957430344L;
private double a = 1.0;
private double b = 5.1/(4*Math.PI*Math.PI);
private double c = 5.0/Math.PI;
private double d = 6.0;
private double e = 10.0;
private double f = 1.0/(8.0*Math.PI);
public Branin() {
a = 1.0;
b = 5.1/(4*Math.PI*Math.PI);
c = 5.0/Math.PI;
d = 6.0;
e = 10.0;
f = 1.0/(8.0*Math.PI);
double x1 = 1.0;
double x2 = 2.0;
//constraint.add(new DimensionValidator(2));
//constraint.add(new ContentValidator(0, new QuantitativeBoundValidator(new Double(-5), new Double(15))));
//constraint.add(new ContentValidator(1, new QuantitativeBoundValidator(new Double(0), new Double(15))));
setDomain("R(-5,10),R(0,15)");
}
public Object getMinimum() {
return new Double(0.397887);
}
public double evaluate(Vector x) {
double x1 = x.getReal(0);
double x2 = x.getReal(1);
return a*Math.pow((x2 - b*x1*x1 + c*x1 - d), 2) + e*(1 - f)*Math.cos(x1) + e;
}
}
| src/main/java/net/sourceforge/cilib/functions/continuous/unconstrained/Branin.java | /*
* Branin.java
*
* Created on June 4, 2003, 4:57 PM
*
*
* Copyright (C) 2003 - 2007
* Computational Intelligence Research Group (CIRG@UP)
* Department of Computer Science
* University of Pretoria
* South Africa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package net.sourceforge.cilib.functions.continuous.unconstrained;
import java.io.Serializable;
import net.sourceforge.cilib.functions.ContinuousFunction;
import net.sourceforge.cilib.type.types.container.Vector;
/**
* <p><b>Booth Function</b></p>
*
* <p><b>Reference:</b> X. Yao, Y. Liu, G. Liu, <i>Evolutionary Programming Made Faster</i>,
* IEEE Transactions on Evolutionary Computation, 3(1):82--102, 1999</p>
*
* <p>Minimum:
* <ul>
* <li> f(<b>x</b>*) = 0.397887 </li>
* <li> <b>x</b>* = (-pi, 12.275), (pi, 2.275), (9.425, 2.425)</li>
* <li> for x_1 in [-5,10], x_2 in [0,15]</li>
* </ul>
* </p>
*
* <p>Characteristics:
* <ul>
* <li>Only defined for 2 dimensions</li>
* <li>Has 3 global minima</li>
* <li>Unimodal</li>
* <li>Seperable</li>
* <li>Regular</li>
* </ul>
* </p>
*
* @author Clive Naicker
*
*/
public class Branin extends ContinuousFunction implements Serializable {
private static final long serialVersionUID = -2254223453957430344L;
private double a = 1.0;
private double b = 5.1/(4*Math.PI*Math.PI);
private double c = 5.0/Math.PI;
private double d = 6.0;
private double e = 10.0;
private double f = 1.0/(8.0*Math.PI);
public Branin() {
a = 1.0;
b = 5.1/(4*Math.PI*Math.PI);
c = 5.0/Math.PI;
d = 6.0;
e = 10.0;
f = 1.0/(8.0*Math.PI);
double x1 = 1.0;
double x2 = 2.0;
System.out.println(a*Math.pow((x2 - b*x1*x1 + c*x1 - d), 2) + e*(1 - f)*Math.cos(x1) + e);
//constraint.add(new DimensionValidator(2));
//constraint.add(new ContentValidator(0, new QuantitativeBoundValidator(new Double(-5), new Double(15))));
//constraint.add(new ContentValidator(1, new QuantitativeBoundValidator(new Double(0), new Double(15))));
setDomain("R(-5,10),R(0,15)");
}
public Object getMinimum() {
return new Double(0.397887);
}
public double evaluate(Vector x) {
double x1 = x.getReal(0);
double x2 = x.getReal(1);
return a*Math.pow((x2 - b*x1*x1 + c*x1 - d), 2) + e*(1 - f)*Math.cos(x1) + e;
}
}
| r828@minifireslug: gpampara | 2007-11-21 15:07:40 +0200
Removed a print out statement.
git-svn-id: e8c528292d4a6d6d86ccd8ee3f978f608db6077d@617 6919081d-ccfc-0310-b8b8-fc61df93b961
| src/main/java/net/sourceforge/cilib/functions/continuous/unconstrained/Branin.java | r828@minifireslug: gpampara | 2007-11-21 15:07:40 +0200 Removed a print out statement. | <ide><path>rc/main/java/net/sourceforge/cilib/functions/continuous/unconstrained/Branin.java
<ide>
<ide> double x1 = 1.0;
<ide> double x2 = 2.0;
<del> System.out.println(a*Math.pow((x2 - b*x1*x1 + c*x1 - d), 2) + e*(1 - f)*Math.cos(x1) + e);
<ide>
<ide> //constraint.add(new DimensionValidator(2));
<ide> //constraint.add(new ContentValidator(0, new QuantitativeBoundValidator(new Double(-5), new Double(15)))); |
|
Java | mit | error: pathspec 'miniLib.java' did not match any file(s) known to git
| 178a05d08e61df3322e1d95868b197015661709b | 1 | nevosial/Hello-World,nevosial/Hello-World | class Library{
static String city_name = "San Jose";
String libname;
String foundingyear;
String libloc;
String street;
String book_name;
String author;
String genre;
long uid;
public void libdetails()
{
System.out.println();
System.out.println("----Library Details----");
System.out.println("Library Name: "+libname);
System.out.println("Founding Year: "+foundingyear);
System.out.println("Location: "+libloc);
System.out.println("------------------------");
}
public void bookdetails()
{
System.out.println();
System.out.println("=========================");
System.out.println("Book Name: "+book_name);
System.out.println("Author: "+author);
System.out.println("Genre: "+genre);
System.out.println("Uid: "+uid);
System.out.println("=========================");
}
}
class miniLib{
public static void main(String args[])
{
Library walkerst = new Library();
Library bushst = new Library();
walkerst.libname = "JFK Library";
walkerst.foundingyear = "5-Oct-1991";
walkerst.street = "Walker Street";
walkerst.libloc = "Martin Pier, San Jose";
walkerst.book_name = "Mein Kampf";
walkerst.author = "Adolf Hitler";
walkerst.genre = "Biography";
walkerst.uid = 19570101;
bushst.libname = "MLK Library";
bushst.foundingyear = "2-May-1982";
bushst.street = "Bush Square";
bushst.libloc = "Downtown, San Jose";
bushst.book_name = "Life of Pi";
bushst.author = "Yann Martel";
bushst.genre = "Fiction";
bushst.uid = 20080808;
walkerst.libdetails();
bushst.libdetails();
walkerst.bookdetails();
bushst.bookdetails();
}
}
| miniLib.java | Library example
| miniLib.java | Library example | <ide><path>iniLib.java
<add>class Library{
<add> static String city_name = "San Jose";
<add> String libname;
<add> String foundingyear;
<add> String libloc;
<add> String street;
<add> String book_name;
<add> String author;
<add> String genre;
<add> long uid;
<add>
<add> public void libdetails()
<add> {
<add> System.out.println();
<add> System.out.println("----Library Details----");
<add> System.out.println("Library Name: "+libname);
<add> System.out.println("Founding Year: "+foundingyear);
<add> System.out.println("Location: "+libloc);
<add> System.out.println("------------------------");
<add>
<add>
<add> }
<add>
<add> public void bookdetails()
<add> {
<add> System.out.println();
<add> System.out.println("=========================");
<add> System.out.println("Book Name: "+book_name);
<add> System.out.println("Author: "+author);
<add> System.out.println("Genre: "+genre);
<add> System.out.println("Uid: "+uid);
<add> System.out.println("=========================");
<add> }
<add>}
<add>
<add>class miniLib{
<add> public static void main(String args[])
<add> {
<add> Library walkerst = new Library();
<add> Library bushst = new Library();
<add>
<add> walkerst.libname = "JFK Library";
<add> walkerst.foundingyear = "5-Oct-1991";
<add> walkerst.street = "Walker Street";
<add> walkerst.libloc = "Martin Pier, San Jose";
<add> walkerst.book_name = "Mein Kampf";
<add> walkerst.author = "Adolf Hitler";
<add> walkerst.genre = "Biography";
<add> walkerst.uid = 19570101;
<add>
<add> bushst.libname = "MLK Library";
<add> bushst.foundingyear = "2-May-1982";
<add> bushst.street = "Bush Square";
<add> bushst.libloc = "Downtown, San Jose";
<add> bushst.book_name = "Life of Pi";
<add> bushst.author = "Yann Martel";
<add> bushst.genre = "Fiction";
<add> bushst.uid = 20080808;
<add>
<add> walkerst.libdetails();
<add> bushst.libdetails();
<add>
<add> walkerst.bookdetails();
<add> bushst.bookdetails();
<add> }
<add> } |
|
Java | bsd-3-clause | 98b1a1e470f237744b11be01d7c1384d29bd1a87 | 0 | andronix3/SwingHacks | package com.smartg.swing;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.function.Function;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicSliderUI;
import com.smartg.java.util.EventListenerListIterator;
/**
* JRangeSlider. This class implements slider with two values. Second value is
* equals to first value plus extent, so I just reused BoundedRangeModel.
* JRangeSlider will look correct on all platforms (using appropriate SliderUI).
*
* @author andronix
*
*/
public class JRangeSlider extends JPanel {
private final class MouseHandler extends MouseAdapter {
private int cursorType;
private int pressX, pressY;
private int firstValue;
private int secondValue;
private int modelExtent;
@Override
public void mouseMoved(MouseEvent e) {
int value = model.getValue() - model.getMinimum();
int secondValue = value + model.getExtent();
switch (slider.getOrientation()) {
case SwingConstants.HORIZONTAL:
int x = ((int) (e.getX() * scaleX));
if (Math.abs(x - secondValue) < 3) {
cursorType = Cursor.E_RESIZE_CURSOR;
} else if (Math.abs(x - value) < 3) {
cursorType = Cursor.W_RESIZE_CURSOR;
} else if (x > value && x < secondValue) {
cursorType = Cursor.MOVE_CURSOR;
} else {
cursorType = Cursor.DEFAULT_CURSOR;
}
setCursor(Cursor.getPredefinedCursor(cursorType));
break;
case SwingConstants.VERTICAL:
int y = ((int) ((getHeight() - e.getY()) * scaleY));
if (Math.abs(y - secondValue) < 3) {
cursorType = Cursor.N_RESIZE_CURSOR;
} else if (Math.abs(y - value) < 3) {
cursorType = Cursor.S_RESIZE_CURSOR;
} else if (y > value && y < secondValue) {
cursorType = Cursor.MOVE_CURSOR;
} else {
cursorType = Cursor.DEFAULT_CURSOR;
}
setCursor(Cursor.getPredefinedCursor(cursorType));
break;
}
}
@Override
public void mouseDragged(MouseEvent e) {
int delta;
int value;
switch (cursorType) {
case Cursor.DEFAULT_CURSOR:
break;
case Cursor.MOVE_CURSOR:
if (slider.getOrientation() == SwingConstants.HORIZONTAL) {
delta = Math.round((pressX - e.getX()) * scaleX);
value = firstValue - delta;
model.setValue((int) value);
} else {
delta = Math.round(-(pressY - e.getY()) * scaleY);
value = firstValue - delta;
model.setValue((int) value);
}
repaint();
break;
case Cursor.E_RESIZE_CURSOR:
delta = Math.round((pressX - e.getX()) * scaleX);
int extent = (int) (modelExtent - delta);
if (extent < 0) {
model.setValue(firstValue + extent);
model.setExtent(0);
} else {
model.setExtent(extent);
}
repaint();
break;
case Cursor.W_RESIZE_CURSOR:
delta = Math.round((pressX - e.getX()) * scaleX);
if (delta > firstValue) {
delta = firstValue;
}
value = firstValue - delta;
if(value < model.getMinimum()) {
value = model.getMinimum();
}
model.setValue(value);
model.setExtent(secondValue - value);
repaint();
break;
case Cursor.N_RESIZE_CURSOR:
delta = Math.round(-(pressY - e.getY()) * scaleY);
extent = (int) (modelExtent - delta);
if (extent < 0) {
model.setValue(firstValue + extent);
model.setExtent(0);
} else {
model.setExtent(extent);
}
repaint();
break;
case Cursor.S_RESIZE_CURSOR:
delta = Math.round(-(pressY - e.getY()) * scaleY);
if (delta > firstValue) {
delta = firstValue;
}
value = firstValue - delta;
if(value < model.getMinimum()) {
value = model.getMinimum();
}
model.setValue(value);
model.setExtent(secondValue - value);
repaint();
break;
}
}
@Override
public void mousePressed(MouseEvent e) {
pressX = e.getX();
pressY = e.getY();
firstValue = model.getValue();
modelExtent = model.getExtent();
secondValue = model.getValue() + model.getExtent();
}
}
private static final long serialVersionUID = -4923076507643832793L;
private BoundedRangeModel model;
private MouseHandler mouseHandler = new MouseHandler();
private float scaleX, scaleY;
private JSlider slider = new JSlider();
private Function<Integer, Integer> function = new Function<Integer, Integer>() {
public Integer apply(Integer t) {
return t;
}
};
private Function<Integer, Float> floatFunction = new Function<Integer, Float>() {
public Float apply(Integer t) {
return t + 0f;
}
};
public JRangeSlider() {
this(0, 100, 0, 10);
}
public JRangeSlider(int min, int max, int value, int extent) {
this(new DefaultBoundedRangeModel(value, extent, min, max));
}
public JRangeSlider(BoundedRangeModel model) {
this.model = model;
slider.setMinimum(model.getMinimum());
slider.setMaximum(model.getMaximum());
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
computeScaleX();
computeScaleY();
}
});
setBorder(new EmptyBorder(1, 1, 1, 1));
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
fireChangeEvent();
repaint();
}
});
}
public int getValue() {
return getFunction().apply(model.getValue());
}
public void setValue(int i) {
i = clamp(i);
int v = model.getValue();
int e = model.getExtent();
model.setRangeProperties(i, v + e - i, model.getMinimum(), model.getMaximum(), false);
}
private int clamp(int i) {
int max = model.getMaximum();
if (i > max) {
i = max;
}
int min = model.getMinimum();
if (i < min) {
i = min;
}
return i;
}
public int getSecondValue() {
return getFunction().apply(model.getValue() + model.getExtent());
}
public void setSecondValue(int i) {
i = clamp(i);
int v = model.getValue();
model.setExtent(i - v);
}
public Function<Integer, Integer> getFunction() {
return function;
}
public void setFunction(Function<Integer, Integer> function) {
if (function != null) {
this.function = function;
} else {
this.function = new Function<Integer, Integer>() {
public Integer apply(Integer t) {
return t;
}
};
}
}
public Function<Integer, Float> getFloatFunction() {
return floatFunction;
}
public void setFloatFunction(Function<Integer, Float> floatFunction) {
if (floatFunction != null) {
this.floatFunction = floatFunction;
} else {
this.floatFunction = new Function<Integer, Float>() {
public Float apply(Integer t) {
return t + 0f;
}
};
}
}
public float getFloatValue() {
return floatFunction.apply(getValue());
}
public float getFloatSecondValue() {
return floatFunction.apply(getSecondValue());
}
private void fireChangeEvent() {
EventListenerListIterator<ChangeListener> iter = new EventListenerListIterator<ChangeListener>(
ChangeListener.class, listenerList);
ChangeEvent e = new ChangeEvent(this);
while (iter.hasNext()) {
ChangeListener next = iter.next();
next.stateChanged(e);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
slider.setMinimum(model.getMinimum());
slider.setMaximum(model.getMaximum());
slider.setBounds(getBounds());
slider.setValue(model.getMinimum());
BasicSliderUI ui = (BasicSliderUI) slider.getUI();
if (getPaintTrack()) {
ui.paintTrack(g);
}
slider.setValue(getSecondValue());
Rectangle clip = g.getClipBounds();
if (getOrientation() == SwingConstants.HORIZONTAL) {
Rectangle r = new Rectangle((int) ((model.getValue() - model.getMinimum()) / scaleX), 0, getWidth(), getHeight());
r = r.intersection(clip);
g.setClip(r.x, r.y, r.width, r.height);
}
slider.paint(g);
g.setClip(clip.x, clip.y, clip.width, clip.height);
if (getPaintLabels()) {
ui.paintLabels(g);
}
if (getPaintTicks()) {
ui.paintTicks(g);
}
slider.setValue(getValue());
ui.paintThumb(g);
}
private void computeScaleX() {
float width = getWidth();
Insets ins = getInsets();
width -= ins.left + ins.right;
int min = model.getMinimum();
int max = model.getMaximum();
float size = max - min;
scaleX = size / width;
}
private void computeScaleY() {
float height = getHeight();
Insets ins = getInsets();
height -= ins.top + ins.bottom;
int min = model.getMinimum();
int max = model.getMaximum();
float size = max - min;
scaleY = size / height;
}
// all following methods just forwarding calls to/from JSlider
@SuppressWarnings("rawtypes")
public Dictionary getLabelTable() {
return slider.getLabelTable();
}
@SuppressWarnings("rawtypes")
public void setLabelTable(Dictionary labels) {
slider.setLabelTable(labels);
}
public boolean getPaintLabels() {
return slider.getPaintLabels();
}
public void setPaintLabels(boolean b) {
slider.setPaintLabels(b);
}
public boolean getPaintTrack() {
return slider.getPaintTrack();
}
public void setPaintTrack(boolean b) {
slider.setPaintTrack(b);
}
public boolean getPaintTicks() {
return slider.getPaintTicks();
}
public void setPaintTicks(boolean b) {
slider.setPaintTicks(b);
}
public boolean getSnapToTicks() {
return slider.getSnapToTicks();
}
public void setSnapToTicks(boolean b) {
slider.setSnapToTicks(b);
}
public int getMinorTickSpacing() {
return slider.getMinorTickSpacing();
}
public void setMinorTickSpacing(int n) {
slider.setMinorTickSpacing(n);
}
public int getMajorTickSpacing() {
return slider.getMajorTickSpacing();
}
public void setMajorTickSpacing(int n) {
slider.setMajorTickSpacing(n);
}
public boolean getInverted() {
return slider.getInverted();
}
public void setInverted(boolean b) {
slider.setInverted(b);
}
public void setFont(Font font) {
if (slider != null) {
slider.setFont(font);
}
}
@SuppressWarnings("rawtypes")
public Hashtable createStandardLabels(int increment, int start) {
return slider.createStandardLabels(increment, start);
}
@SuppressWarnings("rawtypes")
public Hashtable createStandardLabels(int increment) {
return slider.createStandardLabels(increment);
}
@Override
public Dimension getPreferredSize() {
return slider.getPreferredSize();
}
@Override
public void setPreferredSize(Dimension preferredSize) {
slider.setPreferredSize(preferredSize);
}
public int getOrientation() {
return slider.getOrientation();
}
public void setOrientation(int orientation) {
slider.setOrientation(orientation);
}
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
public boolean getValueIsAdjusting() {
return slider.getValueIsAdjusting();
}
public void setValueIsAdjusting(boolean b) {
slider.setValueIsAdjusting(b);
}
public int getMaximum() {
return slider.getMaximum();
}
public void setMaximum(int maximum) {
model.setMaximum(maximum);
slider.setMaximum(maximum);
}
public int getMinimum() {
return slider.getMinimum();
}
public void setMinimum(int minimum) {
model.setMinimum(minimum);
slider.setMinimum(minimum);
}
public BoundedRangeModel getModel() {
return model;
}
public void setModel(BoundedRangeModel newModel) {
this.model = newModel;
slider.setMinimum(model.getMinimum());
slider.setMaximum(model.getMaximum());
}
public ChangeListener[] getChangeListeners() {
return listenerList.getListeners(ChangeListener.class);
}
public static void main(String... s) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
final JRangeSlider jrs = new JRangeSlider(0, 100, 20, 30);
jrs.setFunction(new Function<Integer, Integer>() {
public Integer apply(Integer t) {
return (t / 2) * 2 + 1;
}
});
jrs.setOrientation(SwingConstants.VERTICAL);
final JToggleButton jtb = new JToggleButton("ChangeValue");
jtb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jtb.isSelected()) {
jrs.setValue(30);
} else {
jrs.setValue(70);
}
}
});
frame.getContentPane().add(jrs);
frame.getContentPane().add(jtb);
frame.getContentPane().add(new JSlider());
frame.pack();
frame.setVisible(true);
}
}
| com/smartg/swing/JRangeSlider.java | package com.smartg.swing;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.function.Function;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicSliderUI;
import com.smartg.java.util.EventListenerListIterator;
/**
* JRangeSlider. This class implements slider with two values. Second value is
* equals to first value plus extent, so I just reused BoundedRangeModel.
* JRangeSlider will look correct on all platforms (using appropriate SliderUI).
*
* @author andronix
*
*/
public class JRangeSlider extends JPanel {
private final class MouseHandler extends MouseAdapter {
private int cursorType;
private int pressX, pressY;
private int modelValue;
private int modelExtent;
@Override
public void mouseMoved(MouseEvent e) {
switch (slider.getOrientation()) {
case SwingConstants.HORIZONTAL:
int x = (int) (e.getX() * scaleX);
if (Math.abs(x - (model.getValue() + model.getExtent())) < 3) {
cursorType = Cursor.E_RESIZE_CURSOR;
} else if (Math.abs(x - model.getValue()) < 3) {
cursorType = Cursor.W_RESIZE_CURSOR;
} else if (x > model.getValue() && x < (model.getValue() + model.getExtent())) {
cursorType = Cursor.MOVE_CURSOR;
} else {
cursorType = Cursor.DEFAULT_CURSOR;
}
setCursor(Cursor.getPredefinedCursor(cursorType));
break;
case SwingConstants.VERTICAL:
int y = (int) ((getHeight() - e.getY()) * scaleY);
if (Math.abs(y - (model.getValue() + model.getExtent())) < 3) {
cursorType = Cursor.N_RESIZE_CURSOR;
} else if (Math.abs(y - model.getValue()) < 3) {
cursorType = Cursor.S_RESIZE_CURSOR;
} else if (y > model.getValue() && y < (model.getValue() + model.getExtent())) {
cursorType = Cursor.MOVE_CURSOR;
} else {
cursorType = Cursor.DEFAULT_CURSOR;
}
setCursor(Cursor.getPredefinedCursor(cursorType));
break;
}
}
@Override
public void mouseDragged(MouseEvent e) {
float delta;
switch (cursorType) {
case Cursor.DEFAULT_CURSOR:
break;
case Cursor.MOVE_CURSOR:
if (slider.getOrientation() == SwingConstants.HORIZONTAL) {
delta = (pressX - e.getX()) * scaleX;
model.setValue((int) (modelValue - delta));
} else {
delta = -(pressY - e.getY()) * scaleY;
model.setValue((int) (modelValue - delta));
}
repaint();
break;
case Cursor.E_RESIZE_CURSOR:
delta = (pressX - e.getX()) * scaleX;
int extent = (int) (modelExtent - delta);
if (extent < 0) {
setValue(modelValue + extent);
model.setExtent(0);
} else {
model.setExtent(extent);
}
repaint();
break;
case Cursor.W_RESIZE_CURSOR:
delta = (pressX - e.getX()) * scaleX;
if (delta > modelValue) {
delta = modelValue;
}
setValue((int) (modelValue - delta));
repaint();
break;
case Cursor.N_RESIZE_CURSOR:
delta = -(pressY - e.getY()) * scaleY;
extent = (int) (modelExtent - delta);
if (extent < 0) {
setValue(modelValue + extent);
model.setExtent(0);
} else {
model.setExtent(extent);
}
repaint();
break;
case Cursor.S_RESIZE_CURSOR:
delta = -(pressY - e.getY()) * scaleY;
if (delta > modelValue) {
delta = modelValue;
}
setValue((int) (modelValue - delta));
repaint();
break;
}
}
@Override
public void mousePressed(MouseEvent e) {
pressX = e.getX();
pressY = e.getY();
modelValue = model.getValue();
modelExtent = model.getExtent();
}
}
private static final long serialVersionUID = -4923076507643832793L;
private BoundedRangeModel model;
private MouseHandler mouseHandler = new MouseHandler();
private float scaleX, scaleY;
private JFunctionSlider slider = new JFunctionSlider();
public JRangeSlider() {
this(0, 100, 0, 10);
}
public JRangeSlider(int min, int max, int value, int extent) {
this(new DefaultBoundedRangeModel(value, extent, min, max));
}
public JRangeSlider(BoundedRangeModel model) {
this.model = model;
slider.setMinimum(model.getMinimum());
slider.setMaximum(model.getMaximum());
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
computeScaleX();
computeScaleY();
}
});
setBorder(new EmptyBorder(1, 1, 1, 1));
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
fireChangeEvent();
repaint();
}
});
}
public int getValue() {
return getFunction().apply(model.getValue());
}
public void setValue(int i) {
i = clamp(i);
int v = model.getValue();
int e = model.getExtent();
model.setRangeProperties(i, v + e - i, model.getMinimum(), model.getMaximum(), false);
}
private int clamp(int i) {
int max = model.getMaximum();
if (i > max) {
i = max;
}
int min = model.getMinimum();
if (i < min) {
i = min;
}
return i;
}
public int getSecondValue() {
return getFunction().apply(model.getValue() + model.getExtent());
}
public void setSecondValue(int i) {
i = clamp(i);
int v = model.getValue();
model.setExtent(i - v);
}
public Function<Integer, Integer> getFunction() {
return slider.getFunction();
}
public void setFunction(Function<Integer, Integer> f) {
slider.setFunction(f);
}
public Function<Integer, Float> getFloatFunction() {
return slider.getFloatFunction();
}
public void setFloatFunction(Function<Integer, Float> f) {
slider.setFloatFunction(f);
}
public float getFloatValue() {
return slider.getFloatFunction().apply(getValue());
}
public float getFloatSecondValue() {
return slider.getFloatFunction().apply(getSecondValue());
}
private void fireChangeEvent() {
EventListenerListIterator<ChangeListener> iter = new EventListenerListIterator<ChangeListener>(
ChangeListener.class, listenerList);
ChangeEvent e = new ChangeEvent(this);
while (iter.hasNext()) {
ChangeListener next = iter.next();
next.stateChanged(e);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
slider.setBounds(getBounds());
slider.setValue(0);
BasicSliderUI ui = (BasicSliderUI) slider.getUI();
if (getPaintTrack()) {
ui.paintTrack(g);
}
slider.setValue(model.getValue() + model.getExtent());
Rectangle clip = g.getClipBounds();
if (getOrientation() == SwingConstants.HORIZONTAL) {
Rectangle r = new Rectangle((int) (model.getValue() / scaleX), 0, getWidth(), getHeight());
r = r.intersection(clip);
g.setClip(r.x, r.y, r.width, r.height);
}
slider.paint(g);
g.setClip(clip.x, clip.y, clip.width, clip.height);
if (getPaintLabels()) {
ui.paintLabels(g);
}
if (getPaintTicks()) {
ui.paintTicks(g);
}
slider.setValue(model.getValue());
ui.paintThumb(g);
}
private void computeScaleX() {
float width = getWidth();
Insets ins = getInsets();
width -= ins.left + ins.right;
int min = model.getMinimum();
int max = model.getMaximum();
float size = max - min;
scaleX = size / width;
}
private void computeScaleY() {
float height = getHeight();
Insets ins = getInsets();
height -= ins.top + ins.bottom;
int min = model.getMinimum();
int max = model.getMaximum();
float size = max - min;
scaleY = size / height;
}
// all following methods just forwarding calls to/from JSlider
@SuppressWarnings("rawtypes")
public Dictionary getLabelTable() {
return slider.getLabelTable();
}
@SuppressWarnings("rawtypes")
public void setLabelTable(Dictionary labels) {
slider.setLabelTable(labels);
}
public boolean getPaintLabels() {
return slider.getPaintLabels();
}
public void setPaintLabels(boolean b) {
slider.setPaintLabels(b);
}
public boolean getPaintTrack() {
return slider.getPaintTrack();
}
public void setPaintTrack(boolean b) {
slider.setPaintTrack(b);
}
public boolean getPaintTicks() {
return slider.getPaintTicks();
}
public void setPaintTicks(boolean b) {
slider.setPaintTicks(b);
}
public boolean getSnapToTicks() {
return slider.getSnapToTicks();
}
public void setSnapToTicks(boolean b) {
slider.setSnapToTicks(b);
}
public int getMinorTickSpacing() {
return slider.getMinorTickSpacing();
}
public void setMinorTickSpacing(int n) {
slider.setMinorTickSpacing(n);
}
public int getMajorTickSpacing() {
return slider.getMajorTickSpacing();
}
public void setMajorTickSpacing(int n) {
slider.setMajorTickSpacing(n);
}
public boolean getInverted() {
return slider.getInverted();
}
public void setInverted(boolean b) {
slider.setInverted(b);
}
public void setFont(Font font) {
if (slider != null) {
slider.setFont(font);
}
}
@SuppressWarnings("rawtypes")
public Hashtable createStandardLabels(int increment, int start) {
return slider.createStandardLabels(increment, start);
}
@SuppressWarnings("rawtypes")
public Hashtable createStandardLabels(int increment) {
return slider.createStandardLabels(increment);
}
@Override
public Dimension getPreferredSize() {
return slider.getPreferredSize();
}
@Override
public void setPreferredSize(Dimension preferredSize) {
slider.setPreferredSize(preferredSize);
}
public int getOrientation() {
return slider.getOrientation();
}
public void setOrientation(int orientation) {
slider.setOrientation(orientation);
}
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
public boolean getValueIsAdjusting() {
return slider.getValueIsAdjusting();
}
public void setValueIsAdjusting(boolean b) {
slider.setValueIsAdjusting(b);
}
public int getMaximum() {
return slider.getMaximum();
}
public void setMaximum(int maximum) {
model.setMaximum(maximum);
slider.setMaximum(maximum);
}
public int getMinimum() {
return slider.getMinimum();
}
public void setMinimum(int minimum) {
model.setMinimum(minimum);
slider.setMinimum(minimum);
}
public BoundedRangeModel getModel() {
return model;
}
public void setModel(BoundedRangeModel newModel) {
this.model = newModel;
slider.setMinimum(model.getMinimum());
slider.setMaximum(model.getMaximum());
}
public ChangeListener[] getChangeListeners() {
return listenerList.getListeners(ChangeListener.class);
}
public static void main(String... s) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
final JRangeSlider jrs = new JRangeSlider(0, 100, 20, 30);
jrs.setOrientation(SwingConstants.VERTICAL);
final JToggleButton jtb = new JToggleButton("ChangeValue");
jtb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jtb.isSelected()) {
jrs.setValue(30);
} else {
jrs.setValue(70);
}
}
});
frame.getContentPane().add(jrs);
frame.getContentPane().add(jtb);
frame.getContentPane().add(new JSlider());
frame.pack();
frame.setVisible(true);
}
}
| Fixed painting/mouse handler bugs
| com/smartg/swing/JRangeSlider.java | Fixed painting/mouse handler bugs | <ide><path>om/smartg/swing/JRangeSlider.java
<ide> private final class MouseHandler extends MouseAdapter {
<ide> private int cursorType;
<ide> private int pressX, pressY;
<del> private int modelValue;
<add> private int firstValue;
<add> private int secondValue;
<ide> private int modelExtent;
<ide>
<ide> @Override
<ide> public void mouseMoved(MouseEvent e) {
<add> int value = model.getValue() - model.getMinimum();
<add> int secondValue = value + model.getExtent();
<ide> switch (slider.getOrientation()) {
<ide> case SwingConstants.HORIZONTAL:
<del> int x = (int) (e.getX() * scaleX);
<del> if (Math.abs(x - (model.getValue() + model.getExtent())) < 3) {
<add> int x = ((int) (e.getX() * scaleX));
<add> if (Math.abs(x - secondValue) < 3) {
<ide> cursorType = Cursor.E_RESIZE_CURSOR;
<del> } else if (Math.abs(x - model.getValue()) < 3) {
<add> } else if (Math.abs(x - value) < 3) {
<ide> cursorType = Cursor.W_RESIZE_CURSOR;
<del> } else if (x > model.getValue() && x < (model.getValue() + model.getExtent())) {
<add> } else if (x > value && x < secondValue) {
<ide> cursorType = Cursor.MOVE_CURSOR;
<ide> } else {
<ide> cursorType = Cursor.DEFAULT_CURSOR;
<ide> setCursor(Cursor.getPredefinedCursor(cursorType));
<ide> break;
<ide> case SwingConstants.VERTICAL:
<del> int y = (int) ((getHeight() - e.getY()) * scaleY);
<del> if (Math.abs(y - (model.getValue() + model.getExtent())) < 3) {
<add> int y = ((int) ((getHeight() - e.getY()) * scaleY));
<add> if (Math.abs(y - secondValue) < 3) {
<ide> cursorType = Cursor.N_RESIZE_CURSOR;
<del> } else if (Math.abs(y - model.getValue()) < 3) {
<add> } else if (Math.abs(y - value) < 3) {
<ide> cursorType = Cursor.S_RESIZE_CURSOR;
<del> } else if (y > model.getValue() && y < (model.getValue() + model.getExtent())) {
<add> } else if (y > value && y < secondValue) {
<ide> cursorType = Cursor.MOVE_CURSOR;
<ide> } else {
<ide> cursorType = Cursor.DEFAULT_CURSOR;
<ide>
<ide> @Override
<ide> public void mouseDragged(MouseEvent e) {
<del> float delta;
<add> int delta;
<add> int value;
<ide> switch (cursorType) {
<ide> case Cursor.DEFAULT_CURSOR:
<ide> break;
<ide> case Cursor.MOVE_CURSOR:
<ide> if (slider.getOrientation() == SwingConstants.HORIZONTAL) {
<del> delta = (pressX - e.getX()) * scaleX;
<del> model.setValue((int) (modelValue - delta));
<add> delta = Math.round((pressX - e.getX()) * scaleX);
<add> value = firstValue - delta;
<add> model.setValue((int) value);
<ide> } else {
<del> delta = -(pressY - e.getY()) * scaleY;
<del> model.setValue((int) (modelValue - delta));
<add> delta = Math.round(-(pressY - e.getY()) * scaleY);
<add> value = firstValue - delta;
<add> model.setValue((int) value);
<ide> }
<ide> repaint();
<ide> break;
<ide>
<ide> case Cursor.E_RESIZE_CURSOR:
<del> delta = (pressX - e.getX()) * scaleX;
<add> delta = Math.round((pressX - e.getX()) * scaleX);
<ide> int extent = (int) (modelExtent - delta);
<ide> if (extent < 0) {
<del> setValue(modelValue + extent);
<add> model.setValue(firstValue + extent);
<ide> model.setExtent(0);
<ide> } else {
<ide> model.setExtent(extent);
<ide> break;
<ide>
<ide> case Cursor.W_RESIZE_CURSOR:
<del> delta = (pressX - e.getX()) * scaleX;
<del> if (delta > modelValue) {
<del> delta = modelValue;
<del> }
<del> setValue((int) (modelValue - delta));
<add> delta = Math.round((pressX - e.getX()) * scaleX);
<add> if (delta > firstValue) {
<add> delta = firstValue;
<add> }
<add> value = firstValue - delta;
<add> if(value < model.getMinimum()) {
<add> value = model.getMinimum();
<add> }
<add> model.setValue(value);
<add> model.setExtent(secondValue - value);
<ide> repaint();
<ide> break;
<ide>
<ide> case Cursor.N_RESIZE_CURSOR:
<del> delta = -(pressY - e.getY()) * scaleY;
<add> delta = Math.round(-(pressY - e.getY()) * scaleY);
<ide> extent = (int) (modelExtent - delta);
<ide> if (extent < 0) {
<del> setValue(modelValue + extent);
<add> model.setValue(firstValue + extent);
<ide> model.setExtent(0);
<ide> } else {
<ide> model.setExtent(extent);
<ide> break;
<ide>
<ide> case Cursor.S_RESIZE_CURSOR:
<del> delta = -(pressY - e.getY()) * scaleY;
<del> if (delta > modelValue) {
<del> delta = modelValue;
<del> }
<del> setValue((int) (modelValue - delta));
<add> delta = Math.round(-(pressY - e.getY()) * scaleY);
<add> if (delta > firstValue) {
<add> delta = firstValue;
<add> }
<add> value = firstValue - delta;
<add> if(value < model.getMinimum()) {
<add> value = model.getMinimum();
<add> }
<add> model.setValue(value);
<add> model.setExtent(secondValue - value);
<ide> repaint();
<ide> break;
<ide> }
<ide> public void mousePressed(MouseEvent e) {
<ide> pressX = e.getX();
<ide> pressY = e.getY();
<del> modelValue = model.getValue();
<add> firstValue = model.getValue();
<ide> modelExtent = model.getExtent();
<add> secondValue = model.getValue() + model.getExtent();
<ide> }
<ide> }
<ide>
<ide> private MouseHandler mouseHandler = new MouseHandler();
<ide> private float scaleX, scaleY;
<ide>
<del> private JFunctionSlider slider = new JFunctionSlider();
<add> private JSlider slider = new JSlider();
<add>
<add> private Function<Integer, Integer> function = new Function<Integer, Integer>() {
<add> public Integer apply(Integer t) {
<add> return t;
<add> }
<add> };
<add>
<add> private Function<Integer, Float> floatFunction = new Function<Integer, Float>() {
<add> public Float apply(Integer t) {
<add> return t + 0f;
<add> }
<add> };
<ide>
<ide> public JRangeSlider() {
<ide> this(0, 100, 0, 10);
<ide> }
<ide>
<ide> public Function<Integer, Integer> getFunction() {
<del> return slider.getFunction();
<del> }
<del>
<del> public void setFunction(Function<Integer, Integer> f) {
<del> slider.setFunction(f);
<add> return function;
<add> }
<add>
<add> public void setFunction(Function<Integer, Integer> function) {
<add> if (function != null) {
<add> this.function = function;
<add> } else {
<add> this.function = new Function<Integer, Integer>() {
<add> public Integer apply(Integer t) {
<add> return t;
<add> }
<add> };
<add> }
<ide> }
<ide>
<ide> public Function<Integer, Float> getFloatFunction() {
<del> return slider.getFloatFunction();
<del> }
<del>
<del> public void setFloatFunction(Function<Integer, Float> f) {
<del> slider.setFloatFunction(f);
<add> return floatFunction;
<add> }
<add>
<add> public void setFloatFunction(Function<Integer, Float> floatFunction) {
<add> if (floatFunction != null) {
<add> this.floatFunction = floatFunction;
<add> } else {
<add> this.floatFunction = new Function<Integer, Float>() {
<add> public Float apply(Integer t) {
<add> return t + 0f;
<add> }
<add> };
<add> }
<ide> }
<ide>
<ide> public float getFloatValue() {
<del> return slider.getFloatFunction().apply(getValue());
<add> return floatFunction.apply(getValue());
<ide> }
<ide>
<ide> public float getFloatSecondValue() {
<del> return slider.getFloatFunction().apply(getSecondValue());
<add> return floatFunction.apply(getSecondValue());
<ide> }
<ide>
<ide> private void fireChangeEvent() {
<ide> @Override
<ide> protected void paintComponent(Graphics g) {
<ide> super.paintComponent(g);
<del>
<add>
<add> slider.setMinimum(model.getMinimum());
<add> slider.setMaximum(model.getMaximum());
<add>
<ide> slider.setBounds(getBounds());
<ide>
<del> slider.setValue(0);
<add> slider.setValue(model.getMinimum());
<ide> BasicSliderUI ui = (BasicSliderUI) slider.getUI();
<ide> if (getPaintTrack()) {
<ide> ui.paintTrack(g);
<ide> }
<ide>
<del> slider.setValue(model.getValue() + model.getExtent());
<add> slider.setValue(getSecondValue());
<ide>
<ide> Rectangle clip = g.getClipBounds();
<ide>
<ide> if (getOrientation() == SwingConstants.HORIZONTAL) {
<del> Rectangle r = new Rectangle((int) (model.getValue() / scaleX), 0, getWidth(), getHeight());
<add> Rectangle r = new Rectangle((int) ((model.getValue() - model.getMinimum()) / scaleX), 0, getWidth(), getHeight());
<ide> r = r.intersection(clip);
<ide> g.setClip(r.x, r.y, r.width, r.height);
<ide> }
<ide> ui.paintTicks(g);
<ide> }
<ide>
<del> slider.setValue(model.getValue());
<add> slider.setValue(getValue());
<ide> ui.paintThumb(g);
<ide> }
<ide>
<ide> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<ide> frame.getContentPane().setLayout(new FlowLayout());
<ide> final JRangeSlider jrs = new JRangeSlider(0, 100, 20, 30);
<add> jrs.setFunction(new Function<Integer, Integer>() {
<add> public Integer apply(Integer t) {
<add> return (t / 2) * 2 + 1;
<add> }
<add> });
<ide> jrs.setOrientation(SwingConstants.VERTICAL);
<ide>
<ide> final JToggleButton jtb = new JToggleButton("ChangeValue"); |
|
JavaScript | mit | 12b3f6a195f2c8ab4ff9a70b10ec9181b2036eaa | 0 | openphacts/explorer2,openphacts/explorer2,openphacts/explorer2,openphacts/explorer2,openphacts/explorer2 | App.CompoundsPharmacologyView = Ember.View.extend({
didInsertElement: function() {
$('#assay_organism_box').typeahead({
source: function (query, process) {
$.getJSON(organismsUrl, { query: query }, function (data) {
return process(data);
})
}
});
$('#target_organism_box').typeahead({
source: function (query, process) {
$.getJSON(organismsUrl, { query: query }, function (data) {
return process(data);
})
}
});
var view = this;
$(window).bind("scroll", function() {
view.didScroll();
});
},
willDestroyElement: function() {
$(window).unbind("scroll");
},
didScroll: function() {
if(this.isScrolledToBottom() && !this.get('controller').get('fetching')) {
//this.get('controller').set('fetching', true);
this.get('controller').send('fetchMore');
}
},
isScrolledToBottom: function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var top = $(document).scrollTop();
var scrollPercent = (top/(documentHeight-windowHeight)) * 100;
return scrollPercent > 99;
}
});
| app/assets/javascripts/views/compoundsPharmacologyView.js | App.CompoundsPharmacologyView = Ember.View.extend({
didInsertElement: function() {
var view = this;
$(window).bind("scroll", function() {
view.didScroll();
});
},
willDestroyElement: function() {
$(window).unbind("scroll");
},
didScroll: function() {
if(this.isScrolledToBottom() && !this.get('controller').get('fetching')) {
//this.get('controller').set('fetching', true);
this.get('controller').send('fetchMore');
}
},
isScrolledToBottom: function() {
var documentHeight = $(document).height();
var windowHeight = $(window).height();
var top = $(document).scrollTop();
var scrollPercent = (top/(documentHeight-windowHeight)) * 100;
return scrollPercent > 99;
}
});
| organism type ahead for compound
| app/assets/javascripts/views/compoundsPharmacologyView.js | organism type ahead for compound | <ide><path>pp/assets/javascripts/views/compoundsPharmacologyView.js
<ide> App.CompoundsPharmacologyView = Ember.View.extend({
<ide> didInsertElement: function() {
<add> $('#assay_organism_box').typeahead({
<add> source: function (query, process) {
<add> $.getJSON(organismsUrl, { query: query }, function (data) {
<add> return process(data);
<add> })
<add> }
<add> });
<add> $('#target_organism_box').typeahead({
<add> source: function (query, process) {
<add> $.getJSON(organismsUrl, { query: query }, function (data) {
<add> return process(data);
<add> })
<add> }
<add> });
<ide> var view = this;
<ide> $(window).bind("scroll", function() {
<ide> view.didScroll(); |
|
Java | apache-2.0 | 422db22185665cf9804cd23a4306a56661a7aa92 | 0 | xfournet/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,xfournet/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,consulo/consulo,xfournet/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,ernestp/consulo,suncycheng/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,semonte/intellij-community,kool79/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,allotria/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,blademainer/intellij-community,samthor/intellij-community,clumsy/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,holmes/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,semonte/intellij-community,ahb0327/intellij-community,da1z/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,diorcety/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,clumsy/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,joewalnes/idea-community,allotria/intellij-community,TangHao1987/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,da1z/intellij-community,caot/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,ernestp/consulo,mglukhikh/intellij-community,caot/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,ernestp/consulo,petteyg/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,samthor/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,signed/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,kool79/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,retomerz/intellij-community,asedunov/intellij-community,fitermay/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,allotria/intellij-community,clumsy/intellij-community,hurricup/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,holmes/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,fnouama/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,amith01994/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,izonder/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,semonte/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,kdwink/intellij-community,dslomov/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,signed/intellij-community,clumsy/intellij-community,holmes/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,izonder/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,dslomov/intellij-community,FHannes/intellij-community,fitermay/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,samthor/intellij-community,supersven/intellij-community,adedayo/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,da1z/intellij-community,youdonghai/intellij-community,da1z/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,xfournet/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,robovm/robovm-studio,fnouama/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,fitermay/intellij-community,fnouama/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,adedayo/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,robovm/robovm-studio,kdwink/intellij-community,jagguli/intellij-community,izonder/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,blademainer/intellij-community,retomerz/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,diorcety/intellij-community,jagguli/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,caot/intellij-community,gnuhub/intellij-community,kool79/intellij-community,hurricup/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ibinti/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,semonte/intellij-community,diorcety/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,samthor/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ibinti/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,signed/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,holmes/intellij-community,petteyg/intellij-community,da1z/intellij-community,apixandru/intellij-community,supersven/intellij-community,diorcety/intellij-community,holmes/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,izonder/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,semonte/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,kool79/intellij-community,robovm/robovm-studio,kool79/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,kool79/intellij-community,ryano144/intellij-community,slisson/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,caot/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fitermay/intellij-community,semonte/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,blademainer/intellij-community,supersven/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,petteyg/intellij-community,izonder/intellij-community,apixandru/intellij-community,semonte/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,da1z/intellij-community,vvv1559/intellij-community,samthor/intellij-community,supersven/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,semonte/intellij-community,joewalnes/idea-community,consulo/consulo,FHannes/intellij-community,samthor/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,allotria/intellij-community,adedayo/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,consulo/consulo,signed/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,ernestp/consulo,petteyg/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,caot/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,consulo/consulo,gnuhub/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,ernestp/consulo,orekyuu/intellij-community,signed/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,consulo/consulo,michaelgallacher/intellij-community,izonder/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,amith01994/intellij-community,samthor/intellij-community,FHannes/intellij-community,ibinti/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ryano144/intellij-community,da1z/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,joewalnes/idea-community,apixandru/intellij-community,allotria/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,izonder/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,FHannes/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,izonder/intellij-community,slisson/intellij-community,supersven/intellij-community,izonder/intellij-community,tmpgit/intellij-community,slisson/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,signed/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,caot/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,caot/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,diorcety/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,xfournet/intellij-community,supersven/intellij-community,slisson/intellij-community,adedayo/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,dslomov/intellij-community,asedunov/intellij-community,allotria/intellij-community,dslomov/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,samthor/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,adedayo/intellij-community,dslomov/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,signed/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,amith01994/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,blademainer/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,dslomov/intellij-community,consulo/consulo,ftomassetti/intellij-community,kdwink/intellij-community,ibinti/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,FHannes/intellij-community,FHannes/intellij-community,amith01994/intellij-community,fitermay/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,caot/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,kool79/intellij-community,vladmm/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,slisson/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,dslomov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,caot/intellij-community,dslomov/intellij-community,caot/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,pwoodworth/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,Distrotech/intellij-community | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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 org.jetbrains.idea.maven.dom.inspections;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.Processor;
import com.intellij.util.containers.hash.HashSet;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.highlighting.BasicDomElementsInspection;
import com.intellij.util.xml.highlighting.DomElementAnnotationHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.dom.MavenDomBundle;
import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils;
import org.jetbrains.idea.maven.dom.MavenDomUtil;
import org.jetbrains.idea.maven.dom.model.MavenDomDependency;
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel;
import org.jetbrains.idea.maven.project.MavenProject;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MavenDuplicateDependenciesInspection extends BasicDomElementsInspection<MavenDomProjectModel> {
public MavenDuplicateDependenciesInspection() {
super(MavenDomProjectModel.class);
}
@Override
public void checkFileElement(DomFileElement<MavenDomProjectModel> domFileElement,
DomElementAnnotationHolder holder) {
final XmlFile xmlFile = domFileElement.getFile();
MavenDomProjectModel projectModel = domFileElement.getRootElement();
checkMavenProjectModel(projectModel, xmlFile, holder);
}
private static void checkMavenProjectModel(@NotNull MavenDomProjectModel projectModel,
@NotNull XmlFile xmlFile,
@NotNull DomElementAnnotationHolder holder) {
final Map<String, Set<MavenDomDependency>> allDuplicates = getDuplicateDependenciesMap(projectModel);
for (MavenDomDependency dependency : projectModel.getDependencies().getDependencies()) {
String id = createId(dependency);
if (id != null) {
Set<MavenDomDependency> dependencies = allDuplicates.get(id);
if (dependencies != null && dependencies.size() > 1) {
addProblem(dependency, dependencies, holder);
}
}
}
}
private static void addProblem(@NotNull MavenDomDependency dependency,
@NotNull Set<MavenDomDependency> dependencies,
@NotNull DomElementAnnotationHolder holder) {
StringBuffer sb = new StringBuffer();
Set<MavenDomProjectModel> processed = new HashSet<MavenDomProjectModel>();
for (MavenDomDependency domDependency : dependencies) {
if (dependency.equals(domDependency)) continue;
MavenDomProjectModel model = domDependency.getParentOfType(MavenDomProjectModel.class, false);
if (model != null && !processed.contains(model)) {
if (processed.size() > 0) sb.append(", ");
sb.append(createLinkText(model, domDependency));
processed.add(model);
}
}
holder.createProblem(dependency, HighlightSeverity.WARNING, MavenDomBundle.message("MavenDuplicateDependenciesInspection.has.duplicates", sb.toString()));
}
private static String createLinkText(@NotNull MavenDomProjectModel model,@NotNull MavenDomDependency dependency) {
StringBuffer sb =new StringBuffer();
XmlTag tag = dependency.getXmlTag();
if (tag == null) return getProjectName(model);
VirtualFile file = tag.getContainingFile().getVirtualFile();
if (file == null) return getProjectName(model);
sb.append("<a href ='#navigation/");
sb.append(file.getPath());
sb.append(":");
sb.append(tag.getTextRange().getStartOffset());
sb.append("'>");
sb.append(getProjectName(model));
sb.append("</a>");
return sb.toString();
}
@NotNull
private static String getProjectName(MavenDomProjectModel model) {
MavenProject mavenProject = MavenDomUtil.findProject(model);
if (mavenProject != null) {
return mavenProject.getDisplayName();
} else {
String name = model.getName().getStringValue();
if (!StringUtil.isEmptyOrSpaces(name)) {
return name;
}
else {
return "pom.xml"; // ?
}
}
}
@NotNull
private static Map<String, Set<MavenDomDependency>> getDuplicateDependenciesMap(MavenDomProjectModel projectModel) {
final Map<String, Set<MavenDomDependency>> allDependencies = new HashMap<String, Set<MavenDomDependency>>();
Processor<MavenDomProjectModel> collectProcessor = new Processor<MavenDomProjectModel>() {
public boolean process(MavenDomProjectModel model) {
for (MavenDomDependency dependency : model.getDependencies().getDependencies()) {
String mavenId = createId(dependency);
if (mavenId != null) {
if (allDependencies.containsKey(mavenId)) {
allDependencies.get(mavenId).add(dependency);
}
else {
Set<MavenDomDependency> dependencies = new HashSet<MavenDomDependency>();
dependencies.add(dependency);
allDependencies.put(mavenId, dependencies);
}
}
}
return false;
}
};
MavenDomProjectProcessorUtils.processChildrenRecursively(projectModel, collectProcessor, true);
MavenDomProjectProcessorUtils.processParentProjects(projectModel, collectProcessor);
return allDependencies;
}
@Nullable
private static String createId(MavenDomDependency coordinates) {
String groupId = coordinates.getGroupId().getStringValue();
String artifactId = coordinates.getArtifactId().getStringValue();
if (StringUtil.isEmptyOrSpaces(groupId) || StringUtil.isEmptyOrSpaces(artifactId)) return null;
String version = coordinates.getVersion().getStringValue();
String type = coordinates.getType().getStringValue();
String classifier = coordinates.getClassifier().getStringValue();
return groupId +":" + artifactId + ":" + version + ":" + type + ":" + classifier;
}
@NotNull
public String getGroupDisplayName() {
return MavenDomBundle.message("inspection.group");
}
@NotNull
public String getDisplayName() {
return MavenDomBundle.message("inspection.duplicate.dependencies.name");
}
@NotNull
public String getShortName() {
return "MavenDuplicateDependenciesInspection";
}
@NotNull
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.WARNING;
}
} | plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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 org.jetbrains.idea.maven.dom.inspections;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.Processor;
import com.intellij.util.containers.hash.HashSet;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.highlighting.BasicDomElementsInspection;
import com.intellij.util.xml.highlighting.DomElementAnnotationHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.dom.MavenDomBundle;
import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils;
import org.jetbrains.idea.maven.dom.MavenDomUtil;
import org.jetbrains.idea.maven.dom.model.MavenDomArtifactCoordinates;
import org.jetbrains.idea.maven.dom.model.MavenDomDependency;
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel;
import org.jetbrains.idea.maven.model.MavenId;
import org.jetbrains.idea.maven.project.MavenProject;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MavenDuplicateDependenciesInspection extends BasicDomElementsInspection<MavenDomProjectModel> {
public MavenDuplicateDependenciesInspection() {
super(MavenDomProjectModel.class);
}
@Override
public void checkFileElement(DomFileElement<MavenDomProjectModel> domFileElement,
DomElementAnnotationHolder holder) {
final XmlFile xmlFile = domFileElement.getFile();
MavenDomProjectModel projectModel = domFileElement.getRootElement();
checkMavenProjectModel(projectModel, xmlFile, holder);
}
private static void checkMavenProjectModel(@NotNull MavenDomProjectModel projectModel,
@NotNull XmlFile xmlFile,
@NotNull DomElementAnnotationHolder holder) {
final Map<MavenId, Set<MavenDomDependency>> allDuplicates = getDuplicateDependenciesMap(projectModel);
for (MavenDomDependency dependency : projectModel.getDependencies().getDependencies()) {
MavenId id = createId(dependency);
if (id != null) {
Set<MavenDomDependency> dependencies = allDuplicates.get(id);
if (dependencies != null && dependencies.size() > 1) {
addProblem(dependency, dependencies, holder);
}
}
}
}
private static void addProblem(@NotNull MavenDomDependency dependency,
@NotNull Set<MavenDomDependency> dependencies,
@NotNull DomElementAnnotationHolder holder) {
StringBuffer sb = new StringBuffer();
Set<MavenDomProjectModel> processed = new HashSet<MavenDomProjectModel>();
for (MavenDomDependency domDependency : dependencies) {
if (dependency.equals(domDependency)) continue;
MavenDomProjectModel model = domDependency.getParentOfType(MavenDomProjectModel.class, false);
if (model != null && !processed.contains(model)) {
if (processed.size() > 0) sb.append(", ");
sb.append(createLinkText(model, domDependency));
processed.add(model);
}
}
holder.createProblem(dependency, HighlightSeverity.WARNING, MavenDomBundle.message("MavenDuplicateDependenciesInspection.has.duplicates", sb.toString()));
}
private static String createLinkText(@NotNull MavenDomProjectModel model,@NotNull MavenDomDependency dependency) {
StringBuffer sb =new StringBuffer();
XmlTag tag = dependency.getXmlTag();
if (tag == null) return getProjectName(model);
VirtualFile file = tag.getContainingFile().getVirtualFile();
if (file == null) return getProjectName(model);
sb.append("<a href ='#navigation/");
sb.append(file.getPath());
sb.append(":");
sb.append(tag.getTextRange().getStartOffset());
sb.append("'>");
sb.append(getProjectName(model));
sb.append("</a>");
return sb.toString();
}
@NotNull
private static String getProjectName(MavenDomProjectModel model) {
MavenProject mavenProject = MavenDomUtil.findProject(model);
if (mavenProject != null) {
return mavenProject.getDisplayName();
} else {
String name = model.getName().getStringValue();
if (!StringUtil.isEmptyOrSpaces(name)) {
return name;
}
else {
return "pom.xml"; // ?
}
}
}
@NotNull
private static Map<MavenId, Set<MavenDomDependency>> getDuplicateDependenciesMap(MavenDomProjectModel projectModel) {
final Map<MavenId, Set<MavenDomDependency>> allDependencies = new HashMap<MavenId, Set<MavenDomDependency>>();
Processor<MavenDomProjectModel> collectProcessor = new Processor<MavenDomProjectModel>() {
public boolean process(MavenDomProjectModel model) {
for (MavenDomDependency dependency : model.getDependencies().getDependencies()) {
MavenId mavenId = createId(dependency);
if (mavenId != null) {
if (allDependencies.containsKey(mavenId)) {
allDependencies.get(mavenId).add(dependency);
}
else {
Set<MavenDomDependency> dependencies = new HashSet<MavenDomDependency>();
dependencies.add(dependency);
allDependencies.put(mavenId, dependencies);
}
}
}
return false;
}
};
MavenDomProjectProcessorUtils.processChildrenRecursively(projectModel, collectProcessor, true);
MavenDomProjectProcessorUtils.processParentProjects(projectModel, collectProcessor);
return allDependencies;
}
@Nullable
private static MavenId createId(MavenDomArtifactCoordinates coordinates) {
String groupId = coordinates.getGroupId().getStringValue();
String artifactId = coordinates.getArtifactId().getStringValue();
String version = coordinates.getVersion().getStringValue();
if (StringUtil.isEmptyOrSpaces(groupId) || StringUtil.isEmptyOrSpaces(artifactId)) return null;
return new MavenId(groupId, artifactId, version);
}
@NotNull
public String getGroupDisplayName() {
return MavenDomBundle.message("inspection.group");
}
@NotNull
public String getDisplayName() {
return MavenDomBundle.message("inspection.duplicate.dependencies.name");
}
@NotNull
public String getShortName() {
return "MavenDuplicateDependenciesInspection";
}
@NotNull
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.WARNING;
}
} | maven: erroneous 'duplicate dependency' fixed
| plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java | maven: erroneous 'duplicate dependency' fixed | <ide><path>lugins/maven/src/main/java/org/jetbrains/idea/maven/dom/inspections/MavenDuplicateDependenciesInspection.java
<ide> import org.jetbrains.idea.maven.dom.MavenDomBundle;
<ide> import org.jetbrains.idea.maven.dom.MavenDomProjectProcessorUtils;
<ide> import org.jetbrains.idea.maven.dom.MavenDomUtil;
<del>import org.jetbrains.idea.maven.dom.model.MavenDomArtifactCoordinates;
<ide> import org.jetbrains.idea.maven.dom.model.MavenDomDependency;
<ide> import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel;
<del>import org.jetbrains.idea.maven.model.MavenId;
<ide> import org.jetbrains.idea.maven.project.MavenProject;
<ide>
<ide> import java.util.HashMap;
<ide> private static void checkMavenProjectModel(@NotNull MavenDomProjectModel projectModel,
<ide> @NotNull XmlFile xmlFile,
<ide> @NotNull DomElementAnnotationHolder holder) {
<del> final Map<MavenId, Set<MavenDomDependency>> allDuplicates = getDuplicateDependenciesMap(projectModel);
<add> final Map<String, Set<MavenDomDependency>> allDuplicates = getDuplicateDependenciesMap(projectModel);
<ide>
<ide> for (MavenDomDependency dependency : projectModel.getDependencies().getDependencies()) {
<del> MavenId id = createId(dependency);
<add> String id = createId(dependency);
<ide> if (id != null) {
<ide> Set<MavenDomDependency> dependencies = allDuplicates.get(id);
<ide> if (dependencies != null && dependencies.size() > 1) {
<ide> }
<ide>
<ide> @NotNull
<del> private static Map<MavenId, Set<MavenDomDependency>> getDuplicateDependenciesMap(MavenDomProjectModel projectModel) {
<del> final Map<MavenId, Set<MavenDomDependency>> allDependencies = new HashMap<MavenId, Set<MavenDomDependency>>();
<add> private static Map<String, Set<MavenDomDependency>> getDuplicateDependenciesMap(MavenDomProjectModel projectModel) {
<add> final Map<String, Set<MavenDomDependency>> allDependencies = new HashMap<String, Set<MavenDomDependency>>();
<ide>
<ide> Processor<MavenDomProjectModel> collectProcessor = new Processor<MavenDomProjectModel>() {
<ide> public boolean process(MavenDomProjectModel model) {
<ide> for (MavenDomDependency dependency : model.getDependencies().getDependencies()) {
<del> MavenId mavenId = createId(dependency);
<add> String mavenId = createId(dependency);
<ide> if (mavenId != null) {
<ide> if (allDependencies.containsKey(mavenId)) {
<ide> allDependencies.get(mavenId).add(dependency);
<ide> }
<ide>
<ide> @Nullable
<del> private static MavenId createId(MavenDomArtifactCoordinates coordinates) {
<add> private static String createId(MavenDomDependency coordinates) {
<ide> String groupId = coordinates.getGroupId().getStringValue();
<ide> String artifactId = coordinates.getArtifactId().getStringValue();
<del> String version = coordinates.getVersion().getStringValue();
<ide>
<ide> if (StringUtil.isEmptyOrSpaces(groupId) || StringUtil.isEmptyOrSpaces(artifactId)) return null;
<ide>
<del> return new MavenId(groupId, artifactId, version);
<add> String version = coordinates.getVersion().getStringValue();
<add> String type = coordinates.getType().getStringValue();
<add> String classifier = coordinates.getClassifier().getStringValue();
<add>
<add> return groupId +":" + artifactId + ":" + version + ":" + type + ":" + classifier;
<ide>
<ide> }
<ide> |
|
Java | bsd-3-clause | 26df8667be461390877a6e720ce8c887d46bad47 | 0 | NighatYasmin/RESOLVE,NighatYasmin/RESOLVE,yushan87/RESOLVE,mikekab/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,ClemsonRSRG/RESOLVE,mikekab/RESOLVE | /**
* TreeBuildingListener.java
* ---------------------------------
* Copyright (c) 2016
* RESOLVE Software Research Group
* School of Computing
* Clemson University
* All rights reserved.
* ---------------------------------
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package edu.clemson.cs.rsrg.parsing;
import edu.clemson.cs.r2jt.typeandpopulate2.entry.SymbolTableEntry;
import edu.clemson.cs.rsrg.absyn.declarations.Dec;
import edu.clemson.cs.rsrg.absyn.declarations.facilitydecl.FacilityDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathAssertionDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathCategoricalDefinitionDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathDefinitionDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathTypeTheoremDec;
import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.ModuleDec;
import edu.clemson.cs.rsrg.absyn.ResolveConceptualElement;
import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.ShortFacilityModuleDec;
import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ModuleParameterDec;
import edu.clemson.cs.rsrg.absyn.declarations.variabledecl.MathVarDec;
import edu.clemson.cs.rsrg.absyn.expressions.Exp;
import edu.clemson.cs.rsrg.absyn.expressions.mathexpr.*;
import edu.clemson.cs.rsrg.absyn.expressions.programexpr.*;
import edu.clemson.cs.rsrg.absyn.items.mathitems.DefinitionBodyItem;
import edu.clemson.cs.rsrg.absyn.items.programitems.ModuleArgumentItem;
import edu.clemson.cs.rsrg.absyn.items.programitems.UsesItem;
import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.PrecisModuleDec;
import edu.clemson.cs.rsrg.absyn.rawtypes.ArbitraryExpTy;
import edu.clemson.cs.rsrg.absyn.rawtypes.Ty;
import edu.clemson.cs.rsrg.errorhandling.ErrorHandler;
import edu.clemson.cs.rsrg.init.file.ResolveFile;
import edu.clemson.cs.rsrg.misc.Utilities;
import edu.clemson.cs.rsrg.parsing.data.Location;
import edu.clemson.cs.rsrg.parsing.data.PosSymbol;
import java.util.*;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* <p>This replaces the old RESOLVE ANTLR3 builder and builds the
* intermediate representation objects used during the compilation
* process.</p>
*
* @author Yu-Shan Sun
* @author Daniel Welch
* @version 1.0
*/
public class TreeBuildingListener extends ResolveParserBaseListener {
// ===========================================================
// Member Fields
// ===========================================================
/** <p>Stores all the parser nodes we have encountered.</p> */
private final ParseTreeProperty<ResolveConceptualElement> myNodes;
/**
* <p>Stores the information gathered from the children nodes of
* {@code ResolveParser.DefinitionSignatureContext}</p>
*/
private List<DefinitionMembers> myDefinitionMemberList;
/** <p>Boolean that indicates that we are processing a module argument.</p> */
private boolean myIsProcessingModuleArgument;
/** <p>Stack of current syntactic sugar conversions</p> */
private Stack<ProgramExpAdapter> myCurrentProgExpAdapterStack;
/** <p>The complete module representation.</p> */
private ModuleDec myFinalModule;
/** <p>The current file we are compiling.</p> */
private final ResolveFile myFile;
/** <p>The error listener.</p> */
private final ErrorHandler myErrorHandler;
// ===========================================================
// Constructors
// ===========================================================
/**
* <p>Create a listener to walk the entire compiler generated
* ANTLR4 parser tree and generate the intermediate representation
* objects used by the subsequent modules.</p>
*
* @param file The current file we are compiling.
*/
public TreeBuildingListener(ResolveFile file, ErrorHandler errorHandler) {
myErrorHandler = errorHandler;
myFile = file;
myFinalModule = null;
myNodes = new ParseTreeProperty<>();
myDefinitionMemberList = null;
myIsProcessingModuleArgument = false;
myCurrentProgExpAdapterStack = new Stack<>();
}
// ===========================================================
// Visitor Methods
// ===========================================================
// -----------------------------------------------------------
// Module Declaration
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates and saves the complete
* module declaration.</p>
*
* @param ctx Module node in ANTLR4 AST.
*/
@Override
public void exitModule(ResolveParser.ModuleContext ctx) {
myNodes.put(ctx, myNodes.get(ctx.getChild(0)));
myFinalModule = (ModuleDec) myNodes.get(ctx.getChild(0));
}
// -----------------------------------------------------------
// Precis Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>Checks to see if the {@link ResolveFile} name matches the
* open and close names given in the file.</p>
*
* @param ctx Precis module node in ANTLR4 AST.
*/
@Override
public void enterPrecisModule(ResolveParser.PrecisModuleContext ctx) {
if (!myFile.getName().equals(ctx.name.getText())) {
myErrorHandler.error(createLocation(ctx.name),
"Module name does not match filename.");
}
if (!myFile.getName().equals(ctx.closename.getText())) {
myErrorHandler.error(createLocation(ctx.closename),
"End module name does not match the filename.");
}
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a {@code Precis}
* module declaration.</p>
*
* @param ctx Precis module node in ANTLR4 AST.
*/
@Override
public void exitPrecisModule(ResolveParser.PrecisModuleContext ctx) {
List<Dec> decls =
Utilities.collect(Dec.class,
ctx.precisItems() != null ? ctx.precisItems().precisItem() : new ArrayList<ParseTree>(),
myNodes);
List<ModuleParameterDec> parameterDecls = new ArrayList<>();
List<UsesItem> uses = Utilities.collect(UsesItem.class,
ctx.usesList() != null ? ctx.usesList().usesItem() : new ArrayList<ParseTree>(),
myNodes);
PrecisModuleDec precis = new PrecisModuleDec(createLocation(ctx), createPosSymbol(ctx.name), parameterDecls, uses, decls);
myNodes.put(ctx, precis);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the generated precis item.</p>
*
* @param ctx Precis item node in ANTLR4 AST.
*/
@Override
public void exitPrecisItem(ResolveParser.PrecisItemContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
// -----------------------------------------------------------
// Facility Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityModule(ResolveParser.FacilityModuleContext ctx) {
super.enterFacilityModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityModule(ResolveParser.FacilityModuleContext ctx) {
super.exitFacilityModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityItems(ResolveParser.FacilityItemsContext ctx) {
super.enterFacilityItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityItems(ResolveParser.FacilityItemsContext ctx) {
super.exitFacilityItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityItem(ResolveParser.FacilityItemContext ctx) {
super.enterFacilityItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityItem(ResolveParser.FacilityItemContext ctx) {
super.exitFacilityItem(ctx);
}
// -----------------------------------------------------------
// Short Facility Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a short facility
* module declaration.</p>
*
* @param ctx Short facility module node in ANTLR4 AST.
*/
@Override
public void exitShortFacilityModule(
ResolveParser.ShortFacilityModuleContext ctx) {
//FacilityDec facilityDec = (FacilityDec) myNodes.removeFrom(ctx.facilityDecl());
ShortFacilityModuleDec shortFacility =
new ShortFacilityModuleDec(createLocation(ctx),
createPosSymbol(ctx.facilityDecl().name), null);
myNodes.put(ctx, shortFacility);
}
// -----------------------------------------------------------
// Concept Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptModule(ResolveParser.ConceptModuleContext ctx) {
super.enterConceptModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptModule(ResolveParser.ConceptModuleContext ctx) {
super.exitConceptModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptItems(ResolveParser.ConceptItemsContext ctx) {
super.enterConceptItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptItems(ResolveParser.ConceptItemsContext ctx) {
super.exitConceptItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptItem(ResolveParser.ConceptItemContext ctx) {
super.enterConceptItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptItem(ResolveParser.ConceptItemContext ctx) {
super.exitConceptItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptImplModule(
ResolveParser.ConceptImplModuleContext ctx) {
super.enterConceptImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptImplModule(ResolveParser.ConceptImplModuleContext ctx) {
super.exitConceptImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementModule(
ResolveParser.EnhancementModuleContext ctx) {
super.enterEnhancementModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementModule(ResolveParser.EnhancementModuleContext ctx) {
super.exitEnhancementModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementItems(ResolveParser.EnhancementItemsContext ctx) {
super.enterEnhancementItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementItems(ResolveParser.EnhancementItemsContext ctx) {
super.exitEnhancementItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementItem(ResolveParser.EnhancementItemContext ctx) {
super.enterEnhancementItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementItem(ResolveParser.EnhancementItemContext ctx) {
super.exitEnhancementItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementImplModule(
ResolveParser.EnhancementImplModuleContext ctx) {
super.enterEnhancementImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementImplModule(
ResolveParser.EnhancementImplModuleContext ctx) {
super.exitEnhancementImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterImplItems(ResolveParser.ImplItemsContext ctx) {
super.enterImplItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitImplItems(ResolveParser.ImplItemsContext ctx) {
super.exitImplItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterImplItem(ResolveParser.ImplItemContext ctx) {
super.enterImplItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitImplItem(ResolveParser.ImplItemContext ctx) {
super.exitImplItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptPerformanceModule(
ResolveParser.ConceptPerformanceModuleContext ctx) {
super.enterConceptPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptPerformanceModule(
ResolveParser.ConceptPerformanceModuleContext ctx) {
super.exitConceptPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptPerformanceItems(
ResolveParser.ConceptPerformanceItemsContext ctx) {
super.enterConceptPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptPerformanceItems(
ResolveParser.ConceptPerformanceItemsContext ctx) {
super.exitConceptPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptPerformanceItem(
ResolveParser.ConceptPerformanceItemContext ctx) {
super.enterConceptPerformanceItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptPerformanceItem(
ResolveParser.ConceptPerformanceItemContext ctx) {
super.exitConceptPerformanceItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPerformanceModule(
ResolveParser.EnhancementPerformanceModuleContext ctx) {
super.enterEnhancementPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPerformanceModule(
ResolveParser.EnhancementPerformanceModuleContext ctx) {
super.exitEnhancementPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPerformanceItems(
ResolveParser.EnhancementPerformanceItemsContext ctx) {
super.enterEnhancementPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPerformanceItems(
ResolveParser.EnhancementPerformanceItemsContext ctx) {
super.exitEnhancementPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPerformanceItem(
ResolveParser.EnhancementPerformanceItemContext ctx) {
super.enterEnhancementPerformanceItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPerformanceItem(
ResolveParser.EnhancementPerformanceItemContext ctx) {
super.exitEnhancementPerformanceItem(ctx);
}
// -----------------------------------------------------------
// Uses Items (Imports)
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation for an import
* module name.</p>
*
* @param ctx Uses item node in ANTLR4 AST.
*/
@Override
public void exitUsesItem(ResolveParser.UsesItemContext ctx) {
myNodes.put(ctx, new UsesItem(createPosSymbol(ctx.getStart())));
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationParameterList(
ResolveParser.OperationParameterListContext ctx) {
super.enterOperationParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationParameterList(
ResolveParser.OperationParameterListContext ctx) {
super.exitOperationParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterModuleParameterList(
ResolveParser.ModuleParameterListContext ctx) {
super.enterModuleParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitModuleParameterList(
ResolveParser.ModuleParameterListContext ctx) {
super.exitModuleParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterModuleParameterDecl(
ResolveParser.ModuleParameterDeclContext ctx) {
super.enterModuleParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitModuleParameterDecl(
ResolveParser.ModuleParameterDeclContext ctx) {
super.exitModuleParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterDefinitionParameterDecl(
ResolveParser.DefinitionParameterDeclContext ctx) {
super.enterDefinitionParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitDefinitionParameterDecl(
ResolveParser.DefinitionParameterDeclContext ctx) {
super.exitDefinitionParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterTypeParameterDecl(
ResolveParser.TypeParameterDeclContext ctx) {
super.enterTypeParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitTypeParameterDecl(ResolveParser.TypeParameterDeclContext ctx) {
super.exitTypeParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConstantParameterDecl(
ResolveParser.ConstantParameterDeclContext ctx) {
super.enterConstantParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConstantParameterDecl(
ResolveParser.ConstantParameterDeclContext ctx) {
super.exitConstantParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationParameterDecl(
ResolveParser.OperationParameterDeclContext ctx) {
super.enterOperationParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationParameterDecl(
ResolveParser.OperationParameterDeclContext ctx) {
super.exitOperationParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptImplParameterDecl(
ResolveParser.ConceptImplParameterDeclContext ctx) {
super.enterConceptImplParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptImplParameterDecl(
ResolveParser.ConceptImplParameterDeclContext ctx) {
super.exitConceptImplParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterParameterDecl(ResolveParser.ParameterDeclContext ctx) {
super.enterParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitParameterDecl(ResolveParser.ParameterDeclContext ctx) {
super.exitParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterParameterMode(ResolveParser.ParameterModeContext ctx) {
super.enterParameterMode(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitParameterMode(ResolveParser.ParameterModeContext ctx) {
super.exitParameterMode(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterType(ResolveParser.TypeContext ctx) {
super.enterType(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitType(ResolveParser.TypeContext ctx) {
super.exitType(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecord(ResolveParser.RecordContext ctx) {
super.enterRecord(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecord(ResolveParser.RecordContext ctx) {
super.exitRecord(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecordVariableDeclGroup(
ResolveParser.RecordVariableDeclGroupContext ctx) {
super.enterRecordVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecordVariableDeclGroup(
ResolveParser.RecordVariableDeclGroupContext ctx) {
super.exitRecordVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterTypeModelDecl(ResolveParser.TypeModelDeclContext ctx) {
super.enterTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitTypeModelDecl(ResolveParser.TypeModelDeclContext ctx) {
super.exitTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterTypeRepresentationDecl(
ResolveParser.TypeRepresentationDeclContext ctx) {
super.enterTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitTypeRepresentationDecl(
ResolveParser.TypeRepresentationDeclContext ctx) {
super.exitTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityTypeRepresentationDecl(
ResolveParser.FacilityTypeRepresentationDeclContext ctx) {
super.enterFacilityTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityTypeRepresentationDecl(
ResolveParser.FacilityTypeRepresentationDeclContext ctx) {
super.exitFacilityTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceTypeModelDecl(
ResolveParser.PerformanceTypeModelDeclContext ctx) {
super.enterPerformanceTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceTypeModelDecl(
ResolveParser.PerformanceTypeModelDeclContext ctx) {
super.exitPerformanceTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSharedStateDecl(ResolveParser.SharedStateDeclContext ctx) {
super.enterSharedStateDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSharedStateDecl(ResolveParser.SharedStateDeclContext ctx) {
super.exitSharedStateDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSharedStateRepresentationDecl(
ResolveParser.SharedStateRepresentationDeclContext ctx) {
super.enterSharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSharedStateRepresentationDecl(
ResolveParser.SharedStateRepresentationDeclContext ctx) {
super.exitSharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilitySharedStateRepresentationDecl(
ResolveParser.FacilitySharedStateRepresentationDeclContext ctx) {
super.enterFacilitySharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilitySharedStateRepresentationDecl(
ResolveParser.FacilitySharedStateRepresentationDeclContext ctx) {
super.exitFacilitySharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSpecModelInit(ResolveParser.SpecModelInitContext ctx) {
super.enterSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSpecModelInit(ResolveParser.SpecModelInitContext ctx) {
super.exitSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSpecModelFinal(ResolveParser.SpecModelFinalContext ctx) {
super.enterSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSpecModelFinal(ResolveParser.SpecModelFinalContext ctx) {
super.exitSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRepresentationInit(
ResolveParser.RepresentationInitContext ctx) {
super.enterRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRepresentationInit(
ResolveParser.RepresentationInitContext ctx) {
super.exitRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRepresentationFinal(
ResolveParser.RepresentationFinalContext ctx) {
super.enterRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRepresentationFinal(
ResolveParser.RepresentationFinalContext ctx) {
super.exitRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityRepresentationInit(
ResolveParser.FacilityRepresentationInitContext ctx) {
super.enterFacilityRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityRepresentationInit(
ResolveParser.FacilityRepresentationInitContext ctx) {
super.exitFacilityRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityRepresentationFinal(
ResolveParser.FacilityRepresentationFinalContext ctx) {
super.enterFacilityRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityRepresentationFinal(
ResolveParser.FacilityRepresentationFinalContext ctx) {
super.exitFacilityRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceSpecModelInit(
ResolveParser.PerformanceSpecModelInitContext ctx) {
super.enterPerformanceSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceSpecModelInit(
ResolveParser.PerformanceSpecModelInitContext ctx) {
super.exitPerformanceSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceSpecModelFinal(
ResolveParser.PerformanceSpecModelFinalContext ctx) {
super.enterPerformanceSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceSpecModelFinal(
ResolveParser.PerformanceSpecModelFinalContext ctx) {
super.exitPerformanceSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterProcedureDecl(ResolveParser.ProcedureDeclContext ctx) {
super.enterProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitProcedureDecl(ResolveParser.ProcedureDeclContext ctx) {
super.exitProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecursiveProcedureDecl(
ResolveParser.RecursiveProcedureDeclContext ctx) {
super.enterRecursiveProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecursiveProcedureDecl(
ResolveParser.RecursiveProcedureDeclContext ctx) {
super.exitRecursiveProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationProcedureDecl(
ResolveParser.OperationProcedureDeclContext ctx) {
super.enterOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationProcedureDecl(
ResolveParser.OperationProcedureDeclContext ctx) {
super.exitOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecursiveOperationProcedureDecl(
ResolveParser.RecursiveOperationProcedureDeclContext ctx) {
super.enterRecursiveOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecursiveOperationProcedureDecl(
ResolveParser.RecursiveOperationProcedureDeclContext ctx) {
super.exitRecursiveOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationDecl(ResolveParser.OperationDeclContext ctx) {
super.enterOperationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationDecl(ResolveParser.OperationDeclContext ctx) {
super.exitOperationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceOperationDecl(
ResolveParser.PerformanceOperationDeclContext ctx) {
super.enterPerformanceOperationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceOperationDecl(
ResolveParser.PerformanceOperationDeclContext ctx) {
super.exitPerformanceOperationDecl(ctx);
}
// -----------------------------------------------------------
// Facility declarations
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a new representation for a facility
* declaration.</p>
*
* @param ctx Facility declaration node in ANTLR4 AST.
*/
@Override
public void exitFacilityDecl(ResolveParser.FacilityDeclContext ctx) {
// Concept arguments
List<ModuleArgumentItem> conceptArgs = new ArrayList<>();
if (ctx.specArgs != null) {
List<ResolveParser.ModuleArgumentContext> conceptArgContext = ctx.specArgs.moduleArgument();
for (ResolveParser.ModuleArgumentContext context : conceptArgContext) {
//conceptArgs.add((ModuleArgumentItem) myNodes.removeFrom(context));
}
}
//myNodes.put(ctx, new FacilityDec());
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptEnhancementDecl(
ResolveParser.ConceptEnhancementDeclContext ctx) {
super.enterConceptEnhancementDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptEnhancementDecl(
ResolveParser.ConceptEnhancementDeclContext ctx) {
super.exitConceptEnhancementDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPairDecl(
ResolveParser.EnhancementPairDeclContext ctx) {
super.enterEnhancementPairDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPairDecl(
ResolveParser.EnhancementPairDeclContext ctx) {
super.exitEnhancementPairDecl(ctx);
}
// -----------------------------------------------------------
// Module arguments
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>Since programming array expressions are simply syntactic sugar
* that gets converted to call statements, they are not allowed to be
* passed as module argument. This method stores a boolean that indicates
* we are in a module argument.</p>
*
* @param ctx Module argument node in ANTLR4 AST.
*/
@Override
public void enterModuleArgument(ResolveParser.ModuleArgumentContext ctx) {
myIsProcessingModuleArgument = true;
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a module
* argument.</p>
*
* @param ctx Module argument node in ANTLR4 AST.
*/
@Override
public void exitModuleArgument(ResolveParser.ModuleArgumentContext ctx) {
myIsProcessingModuleArgument = false;
}
// -----------------------------------------------------------
// Variable declarations
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method stores all math variable declarations.</p>
*
* @param ctx Math variable declaration groups node in ANTLR4 AST.
*/
@Override
public void exitMathVariableDeclGroup(
ResolveParser.MathVariableDeclGroupContext ctx) {
Ty rawType = (Ty) myNodes.removeFrom(ctx.mathTypeExp());
List<TerminalNode> varNames = ctx.IDENTIFIER();
for (TerminalNode varName : varNames) {
myNodes.put(varName, new MathVarDec(createPosSymbol(varName
.getSymbol()), rawType.clone()));
}
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a math variable declaration.</p>
*
* @param ctx Math variable declaration node in ANTLR4 AST.
*/
@Override
public void exitMathVariableDecl(ResolveParser.MathVariableDeclContext ctx) {
Ty rawType = (Ty) myNodes.removeFrom(ctx.mathTypeExp());
myNodes.put(ctx, new MathVarDec(createPosSymbol(ctx.IDENTIFIER()
.getSymbol()), rawType));
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterVariableDeclGroup(
ResolveParser.VariableDeclGroupContext ctx) {
super.enterVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitVariableDeclGroup(ResolveParser.VariableDeclGroupContext ctx) {
super.exitVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterVariableDecl(ResolveParser.VariableDeclContext ctx) {
super.enterVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitVariableDecl(ResolveParser.VariableDeclContext ctx) {
super.exitVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAuxVariableDeclGroup(
ResolveParser.AuxVariableDeclGroupContext ctx) {
super.enterAuxVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAuxVariableDeclGroup(
ResolveParser.AuxVariableDeclGroupContext ctx) {
super.exitAuxVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAuxVariableDecl(ResolveParser.AuxVariableDeclContext ctx) {
super.enterAuxVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAuxVariableDecl(ResolveParser.AuxVariableDeclContext ctx) {
super.exitAuxVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterModuleStateVariableDecl(
ResolveParser.ModuleStateVariableDeclContext ctx) {
super.enterModuleStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitModuleStateVariableDecl(
ResolveParser.ModuleStateVariableDeclContext ctx) {
super.exitModuleStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterStateVariableDecl(
ResolveParser.StateVariableDeclContext ctx) {
super.enterStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitStateVariableDecl(ResolveParser.StateVariableDeclContext ctx) {
super.exitStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterStmt(ResolveParser.StmtContext ctx) {
super.enterStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitStmt(ResolveParser.StmtContext ctx) {
super.exitStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAssignStmt(ResolveParser.AssignStmtContext ctx) {
super.enterAssignStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAssignStmt(ResolveParser.AssignStmtContext ctx) {
super.exitAssignStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSwapStmt(ResolveParser.SwapStmtContext ctx) {
super.enterSwapStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSwapStmt(ResolveParser.SwapStmtContext ctx) {
super.exitSwapStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterCallStmt(ResolveParser.CallStmtContext ctx) {
super.enterCallStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitCallStmt(ResolveParser.CallStmtContext ctx) {
super.exitCallStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPresumeStmt(ResolveParser.PresumeStmtContext ctx) {
super.enterPresumeStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPresumeStmt(ResolveParser.PresumeStmtContext ctx) {
super.exitPresumeStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConfirmStmt(ResolveParser.ConfirmStmtContext ctx) {
super.enterConfirmStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConfirmStmt(ResolveParser.ConfirmStmtContext ctx) {
super.exitConfirmStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterIfStmt(ResolveParser.IfStmtContext ctx) {
super.enterIfStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitIfStmt(ResolveParser.IfStmtContext ctx) {
super.exitIfStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterElsePart(ResolveParser.ElsePartContext ctx) {
super.enterElsePart(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitElsePart(ResolveParser.ElsePartContext ctx) {
super.exitElsePart(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterWhileStmt(ResolveParser.WhileStmtContext ctx) {
super.enterWhileStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitWhileStmt(ResolveParser.WhileStmtContext ctx) {
super.exitWhileStmt(ctx);
}
// -----------------------------------------------------------
// Mathematical type theorems
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a math
* type theorem declaration.</p>
*
* @param ctx Type theorem declaration node in ANTLR4 AST.
*/
@Override
public void exitMathTypeTheoremDecl(
ResolveParser.MathTypeTheoremDeclContext ctx) {
List<MathVarDec> varDecls =
Utilities.collect(MathVarDec.class,
ctx.mathVariableDeclGroup(), myNodes);
Exp assertionExp = (Exp) myNodes.removeFrom(ctx.mathImpliesExp());
myNodes.put(ctx, new MathTypeTheoremDec(createPosSymbol(ctx.name),
varDecls, assertionExp));
}
// -----------------------------------------------------------
// Mathematical theorems, corollaries, etc
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a math assertion
* declaration.</p>
*
* @param ctx Math assertion declaration node in ANTLR4 AST.
*/
@Override
public void exitMathAssertionDecl(ResolveParser.MathAssertionDeclContext ctx) {
ResolveConceptualElement newElement;
Exp mathExp = (Exp) myNodes.removeFrom(ctx.mathExp());
switch (ctx.assertionType.getType()) {
case ResolveLexer.THEOREM:
case ResolveLexer.THEOREM_ASSOCIATIVE:
case ResolveLexer.THEOREM_COMMUTATIVE:
MathAssertionDec.TheoremSubtype theoremSubtype;
if (ctx.assertionType.getType() == ResolveLexer.THEOREM_ASSOCIATIVE) {
theoremSubtype = MathAssertionDec.TheoremSubtype.ASSOCIATIVITY;
}
else if (ctx.assertionType.getType() == ResolveLexer.THEOREM_COMMUTATIVE) {
theoremSubtype = MathAssertionDec.TheoremSubtype.COMMUTATIVITY;
}
else {
theoremSubtype = MathAssertionDec.TheoremSubtype.NONE;
}
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
theoremSubtype, mathExp);
break;
case ResolveLexer.AXIOM:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.AXIOM, mathExp);
break;
case ResolveLexer.COROLLARY:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.COROLLARY, mathExp);
break;
case ResolveLexer.LEMMA:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.LEMMA, mathExp);
break;
default:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.PROPERTY, mathExp);
break;
}
myNodes.put(ctx, newElement);
}
// -----------------------------------------------------------
// Mathematical definitions
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method creates a temporary list to store all the
* temporary definition members</p>
*
* @param ctx Defines declaration node in ANTLR4 AST.
*/
@Override
public void enterMathDefinesDecl(ResolveParser.MathDefinesDeclContext ctx) {
myDefinitionMemberList = new ArrayList<>();
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a defines declaration.</p>
*
* @param ctx Defines declaration node in ANTLR4 AST.
*/
@Override
public void exitMathDefinesDecl(ResolveParser.MathDefinesDeclContext ctx) {
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, null, false);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
/**
* {@inheritDoc}
* <p>
* <p>This method creates a temporary list to store all the
* temporary definition members</p>
*
* @param ctx Definition declaration node in ANTLR4 AST.
*/
@Override
public void enterMathDefinitionDecl(ResolveParser.MathDefinitionDeclContext ctx) {
myDefinitionMemberList = new ArrayList<>();
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the definition representation
* generated by its child rules.</p>
*
* @param ctx Definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathDefinitionDecl(
ResolveParser.MathDefinitionDeclContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a categorical definition declaration.</p>
*
* @param ctx Categorical definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathCategoricalDecl(
ResolveParser.MathCategoricalDeclContext ctx) {
// Create all the definition declarations inside
// the categorical definition
List<MathDefinitionDec> definitionDecls = new ArrayList<>();
for (DefinitionMembers members : myDefinitionMemberList) {
definitionDecls.add(new MathDefinitionDec(members.name, members.params, members.rawType, null, false));
}
myDefinitionMemberList = null;
myNodes.put(ctx, new MathCategoricalDefinitionDec(createPosSymbol(ctx.name), definitionDecls, (Exp) myNodes.removeFrom(ctx.mathExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates an implicit definition declaration.</p>
*
* @param ctx Implicit definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathImplicitDefinitionDecl(
ResolveParser.MathImplicitDefinitionDeclContext ctx) {
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, new DefinitionBodyItem((Exp) myNodes
.removeFrom(ctx.mathExp())), true);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates an inductive definition declaration.</p>
*
* @param ctx Inductive definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathInductiveDefinitionDecl(
ResolveParser.MathInductiveDefinitionDeclContext ctx) {
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, new DefinitionBodyItem((Exp) myNodes
.removeFrom(ctx.mathExp(0)), (Exp) myNodes
.removeFrom(ctx.mathExp(1))), false);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a standard definition declaration.</p>
*
* @param ctx Standard definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathStandardDefinitionDecl(
ResolveParser.MathStandardDefinitionDeclContext ctx) {
DefinitionBodyItem bodyItem = null;
if (ctx.mathExp() != null) {
bodyItem =
new DefinitionBodyItem((Exp) myNodes.removeFrom(ctx
.mathExp()));
}
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, bodyItem, false);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
// -----------------------------------------------------------
// Standard definition signatures
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a temporary definition member object that stores
* all the relevant information needed by the parent rule.</p>
*
* @param ctx Infix definition signature node in ANTLR4 AST.
*/
@Override
public void exitStandardInfixSignature(
ResolveParser.StandardInfixSignatureContext ctx) {
PosSymbol name;
if (ctx.IDENTIFIER() != null) {
name = createPosSymbol(ctx.IDENTIFIER().getSymbol());
}
else {
name = createPosSymbol(ctx.infixOp().op);
}
List<MathVarDec> varDecls = new ArrayList<>();
varDecls.add((MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl(0)));
varDecls.add((MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl(1)));
myDefinitionMemberList.add(new DefinitionMembers(name, varDecls, (Ty) myNodes.removeFrom(ctx.mathTypeExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a temporary definition member object that stores
* all the relevant information needed by the parent rule.</p>
*
* @param ctx Outfix definition signature node in ANTLR4 AST.
*/
@Override
public void exitStandardOutfixSignature(
ResolveParser.StandardOutfixSignatureContext ctx) {
PosSymbol name = new PosSymbol(createLocation(ctx.lOp), ctx.lOp.getText() + "_" + ctx.rOp.getText());
List<MathVarDec> varDecls = new ArrayList<>();
varDecls.add((MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl()));
myDefinitionMemberList.add(new DefinitionMembers(name, varDecls, (Ty) myNodes.removeFrom(ctx.mathTypeExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a temporary definition member object that stores
* all the relevant information needed by the parent rule.</p>
*
* @param ctx Prefix definition signature node in ANTLR4 AST.
*/
@Override
public void exitStandardPrefixSignature(
ResolveParser.StandardPrefixSignatureContext ctx) {
Token nameToken;
if (ctx.getStart() == ctx.prefixOp()) {
nameToken = ctx.prefixOp().getStart();
}
else {
nameToken = ctx.getStart();
}
PosSymbol name = createPosSymbol(nameToken);
List<MathVarDec> varDecls =
Utilities.collect(MathVarDec.class, ctx
.definitionParameterList() != null ? ctx
.definitionParameterList().mathVariableDeclGroup()
: new ArrayList<ParseTree>(), myNodes);
myDefinitionMemberList.add(new DefinitionMembers(name, varDecls,
(Ty) myNodes.removeFrom(ctx.mathTypeExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math expression representation
* generated by its child rules.</p>
*
* @param ctx Definition parameter list node in ANTLR4 AST.
*/
@Override
public void exitDefinitionParameterList(
ResolveParser.DefinitionParameterListContext ctx) {
List<ResolveParser.MathVariableDeclGroupContext> variableDeclGroups =
ctx.mathVariableDeclGroup();
for (ResolveParser.MathVariableDeclGroupContext context : variableDeclGroups) {
List<TerminalNode> identifiers = context.IDENTIFIER();
for (TerminalNode id : identifiers) {
myNodes.put(context, myNodes.removeFrom(id));
}
}
}
// -----------------------------------------------------------
// Different Types of Clauses
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAffectsClause(ResolveParser.AffectsClauseContext ctx) {
super.enterAffectsClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAffectsClause(ResolveParser.AffectsClauseContext ctx) {
super.exitAffectsClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRequiresClause(ResolveParser.RequiresClauseContext ctx) {
super.enterRequiresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRequiresClause(ResolveParser.RequiresClauseContext ctx) {
super.exitRequiresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnsuresClause(ResolveParser.EnsuresClauseContext ctx) {
super.enterEnsuresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnsuresClause(ResolveParser.EnsuresClauseContext ctx) {
super.exitEnsuresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConstraintClause(ResolveParser.ConstraintClauseContext ctx) {
super.enterConstraintClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConstraintClause(ResolveParser.ConstraintClauseContext ctx) {
super.exitConstraintClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterChangingClause(ResolveParser.ChangingClauseContext ctx) {
super.enterChangingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitChangingClause(ResolveParser.ChangingClauseContext ctx) {
super.exitChangingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterMaintainingClause(
ResolveParser.MaintainingClauseContext ctx) {
super.enterMaintainingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitMaintainingClause(ResolveParser.MaintainingClauseContext ctx) {
super.exitMaintainingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterDecreasingClause(ResolveParser.DecreasingClauseContext ctx) {
super.enterDecreasingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitDecreasingClause(ResolveParser.DecreasingClauseContext ctx) {
super.exitDecreasingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterWhereClause(ResolveParser.WhereClauseContext ctx) {
super.enterWhereClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitWhereClause(ResolveParser.WhereClauseContext ctx) {
super.exitWhereClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterCorrespondenceClause(
ResolveParser.CorrespondenceClauseContext ctx) {
super.enterCorrespondenceClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitCorrespondenceClause(
ResolveParser.CorrespondenceClauseContext ctx) {
super.exitCorrespondenceClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConventionClause(ResolveParser.ConventionClauseContext ctx) {
super.enterConventionClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConventionClause(ResolveParser.ConventionClauseContext ctx) {
super.exitConventionClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterDurationClause(ResolveParser.DurationClauseContext ctx) {
super.enterDurationClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitDurationClause(ResolveParser.DurationClauseContext ctx) {
super.exitDurationClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterManipulationDispClause(
ResolveParser.ManipulationDispClauseContext ctx) {
super.enterManipulationDispClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitManipulationDispClause(
ResolveParser.ManipulationDispClauseContext ctx) {
super.exitManipulationDispClause(ctx);
}
// -----------------------------------------------------------
// Arbitrary raw type built from a math expression
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a new arbitrary type with
* the math type expression generated by its child rules.</p>
*
* @param ctx Math type expression node in ANTLR4 AST.
*/
@Override
public void exitMathTypeExp(ResolveParser.MathTypeExpContext ctx) {
myNodes.put(ctx, new ArbitraryExpTy((Exp) myNodes.removeFrom(ctx
.getChild(0))));
}
// -----------------------------------------------------------
// Mathematical expressions
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math expression representation
* generated by its child rules.</p>
*
* @param ctx Math expression node in ANTLR4 AST.
*/
@Override
public void exitMathExp(ResolveParser.MathExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates an iterated math expression.</p>
*
* @param ctx Math iterated expression node in ANTLR4 AST.
*/
@Override
public void exitMathIteratedExp(ResolveParser.MathIteratedExpContext ctx) {
IterativeExp.Operator operator;
switch (ctx.op.getType()) {
case ResolveLexer.BIG_CONCAT:
operator = IterativeExp.Operator.CONCATENATION;
break;
case ResolveLexer.BIG_INTERSECT:
operator = IterativeExp.Operator.INTERSECTION;
break;
case ResolveLexer.BIG_PRODUCT:
operator = IterativeExp.Operator.PRODUCT;
break;
case ResolveLexer.BIG_SUM:
operator = IterativeExp.Operator.SUM;
break;
default:
operator = IterativeExp.Operator.UNION;
break;
}
MathVarDec varDecl =
(MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl());
Exp whereExp = (Exp) myNodes.removeFrom(ctx.whereClause());
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new IterativeExp(createLocation(ctx), operator,
varDecl, whereExp, bodyExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a quantified math expression.</p>
*
* @param ctx Math quantified expression node in ANTLR4 AST.
*/
@Override
public void exitMathQuantifiedExp(ResolveParser.MathQuantifiedExpContext ctx) {
ResolveConceptualElement newElement;
ParseTree child = ctx.getChild(0);
// Only need to construct a new ResolveConceptualElement if
// it is a quantified expression.
if (child instanceof ResolveParser.MathImpliesExpContext) {
newElement = myNodes.removeFrom(child);
}
else {
SymbolTableEntry.Quantification quantification;
switch (ctx.getStart().getType()) {
case ResolveLexer.FORALL:
quantification = SymbolTableEntry.Quantification.UNIVERSAL;
break;
case ResolveLexer.EXISTS:
quantification = SymbolTableEntry.Quantification.EXISTENTIAL;
break;
default:
quantification = SymbolTableEntry.Quantification.UNIQUE;
break;
}
List<MathVarDec> mathVarDecls =
Utilities.collect(MathVarDec.class, ctx
.mathVariableDeclGroup() != null ? ctx
.mathVariableDeclGroup().IDENTIFIER()
: new ArrayList<ParseTree>(), myNodes);
Exp whereExp = (Exp) myNodes.removeFrom(ctx.whereClause());
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathQuantifiedExp());
newElement =
new QuantExp(createLocation(ctx), quantification,
mathVarDecls, whereExp, bodyExp);
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math implies expression.</p>
*
* @param ctx Math implies expression node in ANTLR4 AST.
*/
@Override
public void exitMathImpliesExp(ResolveParser.MathImpliesExpContext ctx) {
ResolveConceptualElement newElement;
// if-then-else expressions
if (ctx.getStart().getType() == ResolveLexer.IF) {
Exp testExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(0));
Exp thenExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(1));
Exp elseExp = null;
if (ctx.mathLogicalExp().size() > 2) {
elseExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(2));
}
newElement =
new IfExp(createLocation(ctx), testExp, thenExp, elseExp);
}
// iff and implies expressions
else if (ctx.op != null) {
Exp leftExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(0));
Exp rightExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(1));
newElement =
new InfixExp(createLocation(ctx), leftExp, null,
createPosSymbol(ctx.op), rightExp);
}
else {
newElement = myNodes.removeFrom(ctx.mathLogicalExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math infix expression
* that contains all the logical expressions.</p>
*
* @param ctx Math logical expression node in ANTLR4 AST.
*/
@Override
public void exitMathLogicalExp(ResolveParser.MathLogicalExpContext ctx) {
ResolveConceptualElement newElement;
List<ResolveParser.MathRelationalExpContext> relationalExpContexts =
ctx.mathRelationalExp();
// relational expressions
if (relationalExpContexts.size() == 1) {
newElement = myNodes.removeFrom(ctx.mathRelationalExp(0));
}
// build logical expressions
else {
// Obtain the 2 expressions
Exp leftExp = (Exp) myNodes.removeFrom(ctx.mathRelationalExp(0));
Exp rightExp = (Exp) myNodes.removeFrom(ctx.mathRelationalExp(1));
newElement =
new InfixExp(leftExp.getLocation(), leftExp, null,
createPosSymbol(ctx.op), rightExp);
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules, generates a new math between expression
* or generates a new math infix expression with the specified
* operators.</p>
*
* @param ctx Math relational expression node in ANTLR4 AST.
*/
@Override
public void exitMathRelationalExp(ResolveParser.MathRelationalExpContext ctx) {
ResolveConceptualElement newElement;
// Check to see if this a between expression
if (ctx.op1 != null && ctx.op2 != null) {
// Obtain the 3 expressions
Exp exp1 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(0));
Exp exp2 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(1));
Exp exp3 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(2));
List<Exp> joiningExps = new ArrayList<>();
joiningExps.add(new InfixExp(new Location(exp1.getLocation()), exp1.clone(), null, createPosSymbol(ctx.op1), exp2.clone()));
joiningExps.add(new InfixExp(new Location(exp1.getLocation()), exp2.clone(), null, createPosSymbol(ctx.op2), exp3.clone()));
newElement = new BetweenExp(createLocation(ctx), joiningExps);
}
else {
// Create a math infix expression with the specified operator if needed
if (ctx.mathInfixExp().size() > 1) {
// Obtain the 2 expressions
Exp exp1 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(0));
Exp exp2 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(1));
switch (ctx.op.getType()) {
case ResolveLexer.EQL:
case ResolveLexer.NOT_EQL:
EqualsExp.Operator op;
if (ctx.op.getType() == ResolveLexer.EQL) {
op = EqualsExp.Operator.EQUAL;
}
else {
op = EqualsExp.Operator.NOT_EQUAL;
}
newElement = new EqualsExp(createLocation(ctx), exp1, null, op, exp2);
break;
default:
newElement = new InfixExp(createLocation(ctx), exp1, null, createPosSymbol(ctx.op), exp2);
break;
}
}
else {
newElement = myNodes.removeFrom(ctx.mathInfixExp(0));
}
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math infix expression
* with a range operator.</p>
*
* @param ctx Math infix expression node in ANTLR4 AST.
*/
@Override
public void exitMathInfixExp(ResolveParser.MathInfixExpContext ctx) {
ResolveConceptualElement newElement;
// Create a math infix expression with a range operator if needed
if (ctx.mathTypeAssertionExp().size() > 1) {
newElement =
new InfixExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathTypeAssertionExp(0)), null,
createPosSymbol(ctx.RANGE().getSymbol()),
(Exp) myNodes.removeFrom(ctx
.mathTypeAssertionExp(1)));
}
else {
newElement = myNodes.removeFrom(ctx.mathTypeAssertionExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math type assertion expression.</p>
*
* @param ctx Math type assertion expression node in ANTLR4 AST.
*/
@Override
public void exitMathTypeAssertionExp(
ResolveParser.MathTypeAssertionExpContext ctx) {
ResolveConceptualElement newElement;
// Create a math type assertion expression if needed
if (ctx.mathTypeExp() != null) {
newElement =
new TypeAssertionExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathFunctionTypeExp()),
(ArbitraryExpTy) myNodes.removeFrom(ctx
.mathTypeExp()));
}
else {
newElement = myNodes.removeFrom(ctx.mathFunctionTypeExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math function type expression.</p>
*
* @param ctx Math function type expression node in ANTLR4 AST.
*/
@Override
public void exitMathFunctionTypeExp(
ResolveParser.MathFunctionTypeExpContext ctx) {
ResolveConceptualElement newElement;
// Create an function type expression if needed
if (ctx.mathAddingExp().size() > 1) {
newElement =
new InfixExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathAddingExp(0)), null,
createPosSymbol(ctx.FUNCARROW().getSymbol()),
(Exp) myNodes.removeFrom(ctx.mathAddingExp(1)));
}
else {
newElement = myNodes.removeFrom(ctx.mathAddingExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math adding expression.</p>
*
* @param ctx Math adding expression node in ANTLR4 AST.
*/
@Override
public void exitMathAddingExp(ResolveParser.MathAddingExpContext ctx) {
ResolveConceptualElement newElement;
// Create an addition expression if needed
List<ResolveParser.MathMultiplyingExpContext> mathExps =
ctx.mathMultiplyingExp();
if (mathExps.size() > 1) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// Obtain the 2 expressions
Exp exp1 = (Exp) myNodes.removeFrom(mathExps.get(0));
Exp exp2 = (Exp) myNodes.removeFrom(mathExps.get(1));
newElement =
new InfixExp(createLocation(ctx), exp1, qualifier,
createPosSymbol(ctx.op), exp2);
}
else {
newElement = myNodes.removeFrom(mathExps.remove(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math multiplication expression.</p>
*
* @param ctx Math multiplication expression node in ANTLR4 AST.
*/
@Override
public void exitMathMultiplyingExp(
ResolveParser.MathMultiplyingExpContext ctx) {
ResolveConceptualElement newElement;
// Create a multiplication expression if needed
List<ResolveParser.MathExponentialExpContext> mathExps =
ctx.mathExponentialExp();
if (mathExps.size() != 1) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// Obtain the 2 expressions
Exp exp1 = (Exp) myNodes.removeFrom(mathExps.get(0));
Exp exp2 = (Exp) myNodes.removeFrom(mathExps.get(1));
newElement =
new InfixExp(createLocation(ctx), exp1, qualifier,
createPosSymbol(ctx.op), exp2);
}
else {
newElement = myNodes.removeFrom(mathExps.remove(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math exponential expression.</p>
*
* @param ctx Math exponential expression node in ANTLR4 AST.
*/
@Override
public void exitMathExponentialExp(
ResolveParser.MathExponentialExpContext ctx) {
ResolveConceptualElement newElement;
// Create a exponential expression if needed
if (ctx.mathExponentialExp() != null) {
newElement =
new InfixExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathPrefixExp()), null,
createPosSymbol(ctx.EXP().getSymbol()),
(Exp) myNodes.removeFrom(ctx.mathExponentialExp()));
}
else {
newElement = myNodes.removeFrom(ctx.mathPrefixExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math prefix expression.</p>
*
* @param ctx Math prefix expression node in ANTLR4 AST.
*/
@Override
public void exitMathPrefixExp(ResolveParser.MathPrefixExpContext ctx) {
ResolveConceptualElement newElement;
// Create a prefix expression if needed
if (ctx.prefixOp() != null) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
newElement =
new PrefixExp(createLocation(ctx), qualifier,
createPosSymbol(ctx.prefixOp().op), (Exp) myNodes
.removeFrom(ctx.mathPrimaryExp()));
}
else {
newElement = myNodes.removeFrom(ctx.mathPrimaryExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a math expression representation
* generated by its child rules.</p>
*
* @param ctx Math primary expression node in ANTLR4 AST.
*/
@Override
public void exitMathPrimaryExp(ResolveParser.MathPrimaryExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the mathematical alternative expression.</p>
*
* @param ctx Math alternative expression node in ANTLR4 AST.
*/
@Override
public void exitMathAlternativeExp(
ResolveParser.MathAlternativeExpContext ctx) {
List<ResolveParser.MathAlternativeExpItemContext> mathExps = ctx.mathAlternativeExpItem();
List<AltItemExp> alternatives = new ArrayList<>();
for (ResolveParser.MathAlternativeExpItemContext context : mathExps) {
alternatives.add((AltItemExp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new AlternativeExp(createLocation(ctx), alternatives));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the different alternatives for the
* mathematical alternative expression.</p>
*
* @param ctx Math alternative expression item node in ANTLR4 AST.
*/
@Override
public void exitMathAlternativeExpItem(
ResolveParser.MathAlternativeExpItemContext ctx) {
Exp testExp = null;
if (ctx.mathRelationalExp() != null) {
testExp = (Exp) myNodes.removeFrom(ctx.mathRelationalExp());
}
myNodes.put(ctx, new AltItemExp(createLocation(ctx), testExp,
(Exp) myNodes.removeFrom(ctx.mathAddingExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math boolean literal.</p>
*
* @param ctx Math boolean literal node in ANTLR4 AST.
*/
@Override
public void exitMathBooleanExp(ResolveParser.MathBooleanExpContext ctx) {
myNodes.put(ctx, new VarExp(createLocation(ctx.BOOLEAN_LITERAL()
.getSymbol()), null, createPosSymbol(ctx.BOOLEAN_LITERAL()
.getSymbol())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math integer literal.</p>
*
* @param ctx Math integer literal node in ANTLR4 AST.
*/
@Override
public void exitMathIntegerExp(ResolveParser.MathIntegerExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
myNodes.put(ctx, new IntegerExp(createLocation(ctx), qualifier, Integer
.valueOf(ctx.INTEGER_LITERAL().getText())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math real literal.</p>
*
* @param ctx Math real literal node in ANTLR4 AST.
*/
@Override
public void exitMathRealExp(ResolveParser.MathRealExpContext ctx) {
myNodes.put(ctx, new DoubleExp(createLocation(ctx.REAL_LITERAL()
.getSymbol()), Double.valueOf(ctx.REAL_LITERAL().getText())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math character literal.</p>
*
* @param ctx Math character literal node in ANTLR4 AST.
*/
@Override
public void exitMathCharacterExp(ResolveParser.MathCharacterExpContext ctx) {
myNodes.put(ctx, new CharExp(createLocation(ctx.CHARACTER_LITERAL()
.getSymbol()), ctx.CHARACTER_LITERAL().getText().charAt(1)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math string literal.</p>
*
* @param ctx Math string literal node in ANTLR4 AST.
*/
@Override
public void exitMathStringExp(ResolveParser.MathStringExpContext ctx) {
myNodes.put(ctx, new StringExp(createLocation(ctx.STRING_LITERAL()
.getSymbol()), ctx.STRING_LITERAL().getText()));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expressions representation
* generated by its child rules or generates a new math dotted expression.</p>
*
* @param ctx Math dot expression node in ANTLR4 AST.
*/
@Override
public void exitMathDotExp(ResolveParser.MathDotExpContext ctx) {
ResolveConceptualElement newElement;
// Create a dot expression if needed
List<ResolveParser.MathCleanFunctionExpContext> mathExps = ctx.mathCleanFunctionExp();
if (mathExps.size() > 0) {
// dotted expressions
List<Exp> dotExps = new ArrayList<>();
dotExps.add((Exp) myNodes.removeFrom(ctx.mathFunctionApplicationExp()));
for (ResolveParser.MathCleanFunctionExpContext context : mathExps) {
dotExps.add((Exp) myNodes.removeFrom(context));
}
newElement = new DotExp(createLocation(ctx), dotExps);
}
else {
newElement = myNodes.removeFrom(ctx.mathFunctionApplicationExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a math function expression or variable expression
* representation generated by its child rules.</p>
*
* @param ctx Math function or variable expression node in ANTLR4 AST.
*/
@Override
public void exitMathFunctOrVarExp(ResolveParser.MathFunctOrVarExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.mathCleanFunctionExp()));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math old expression representation.</p>
*
* @param ctx Math old expression node in ANTLR4 AST.
*/
@Override
public void exitMathOldExp(ResolveParser.MathOldExpContext ctx) {
myNodes.put(ctx, new OldExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathCleanFunctionExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math function expression representation.</p>
*
* @param ctx Math function expression node in ANTLR4 AST.
*/
@Override
public void exitMathFunctionExp(ResolveParser.MathFunctionExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// function name
VarExp functionNameExp = new VarExp(createLocation(ctx.name), null, createPosSymbol(ctx.name));
// exponent-like part to the name
Exp caratExp = (Exp) myNodes.removeFrom(ctx.mathNestedExp());
// function arguments
List<ResolveParser.MathExpContext> mathExps = ctx.mathExp();
List<Exp> functionArgs = new ArrayList<>();
for (ResolveParser.MathExpContext context : mathExps) {
functionArgs.add((Exp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new FunctionExp(createLocation(ctx), qualifier, functionNameExp, caratExp, functionArgs));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math variable expression representation.</p>
*
* @param ctx Math variable expression node in ANTLR4 AST.
*/
@Override
public void exitMathVarExp(ResolveParser.MathVarExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
myNodes.put(ctx, new VarExp(createLocation(ctx), qualifier,
createPosSymbol(ctx.name)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math operator name expression representation.</p>
*
* @param ctx Math operator name expression node in ANTLR4 AST.
*/
@Override
public void exitMathOpNameExp(ResolveParser.MathOpNameExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
Token opToken;
if (ctx.infixOp() != null) {
opToken = ctx.infixOp().op;
}
else {
opToken = ctx.op;
}
myNodes.put(ctx, new VarExp(createLocation(ctx), qualifier,
createPosSymbol(opToken)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math outfix expression
* representation generated by its child rules.</p>
*
* @param ctx Math outfix expression node in ANTLR4 AST.
*/
@Override
public void exitMathOutfixExp(ResolveParser.MathOutfixExpContext ctx) {
OutfixExp.Operator operator;
if (ctx.lop.getType() == ResolveLexer.LT) {
operator = OutfixExp.Operator.ANGLE;
}
else if (ctx.lop.getType() == ResolveLexer.LL) {
operator = OutfixExp.Operator.DBL_ANGLE;
}
else if (ctx.lop.getType() == ResolveLexer.BAR) {
operator = OutfixExp.Operator.BAR;
}
else {
operator = OutfixExp.Operator.DBL_BAR;
}
// math expression
Exp mathExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new OutfixExp(createLocation(ctx), operator, mathExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math set builder expression
* representation generated by its child rules.</p>
*
* @param ctx Math set builder expression node in ANTLR4 AST.
*/
@Override
public void exitMathSetBuilderExp(ResolveParser.MathSetBuilderExpContext ctx) {
MathVarDec varDec =
(MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl());
Exp whereExp = (Exp) myNodes.removeFrom(ctx.whereClause());
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new SetExp(createLocation(ctx), varDec, whereExp,
bodyExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math set collection expression
* representation generated by its child rules.</p>
*
* @param ctx Math set collection expression node in ANTLR4 AST.
*/
@Override
public void exitMathSetCollectionExp(
ResolveParser.MathSetCollectionExpContext ctx) {
List<ResolveParser.MathExpContext> mathExps = ctx.mathExp();
Set<MathExp> mathExpsSet = new HashSet<>();
for (ResolveParser.MathExpContext context : mathExps) {
mathExpsSet.add((MathExp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new SetCollectionExp(createLocation(ctx), mathExpsSet));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math tuple expression representation
* generated by its child rules.</p>
*
* @param ctx Math tuple expression node in ANTLR4 AST.
*/
@Override
public void exitMathTupleExp(ResolveParser.MathTupleExpContext ctx) {
// Add the two expressions inside the tuple to a list
List<Exp> tupleExps = new ArrayList<>();
tupleExps.add((Exp) myNodes.removeFrom(ctx.mathExp(0)));
tupleExps.add((Exp) myNodes.removeFrom(ctx.mathExp(1)));
myNodes.put(ctx, new TupleExp(createLocation(ctx), tupleExps));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math lambda expression representation
* generated by its child rules.</p>
*
* @param ctx Math lambda expression node in ANTLR4 AST.
*/
@Override
public void exitMathLambdaExp(ResolveParser.MathLambdaExpContext ctx) {
// Construct the various variables inside the lambda expression
List<ResolveParser.MathVariableDeclGroupContext> variableDeclGroups = ctx.mathVariableDeclGroup();
List<MathVarDec> varDecls = new ArrayList<>();
for (ResolveParser.MathVariableDeclGroupContext context : variableDeclGroups) {
// Get each math variable declaration
varDecls.add((MathVarDec) myNodes.removeFrom(context));
}
// body expression
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new LambdaExp(createLocation(ctx), varDecls, bodyExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math Cartesian product expression
* representation generated by its child rules.</p>
*
* @param ctx Math Cartesian product expression node in ANTLR4 AST.
*/
@Override
public void exitMathTaggedCartProdTypeExp(
ResolveParser.MathTaggedCartProdTypeExpContext ctx) {
// Construct the various variables inside the cartesian product
List<ResolveParser.MathVariableDeclGroupContext> variableDeclGroups = ctx.mathVariableDeclGroup();
Map<PosSymbol, ArbitraryExpTy> tagsToFieldsMap = new HashMap<>();
for (ResolveParser.MathVariableDeclGroupContext context : variableDeclGroups) {
// Get each math variable declaration
MathVarDec varDec = (MathVarDec) myNodes.removeFrom(context);
tagsToFieldsMap.put(varDec.getName(), (ArbitraryExpTy) varDec.getTy());
}
myNodes.put(ctx, new CrossTypeExp(createLocation(ctx), tagsToFieldsMap));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the nested math expression representation
* generated by its child rules.</p>
*
* @param ctx Nested math expression node in ANTLR4 AST.
*/
@Override
public void exitMathNestedExp(ResolveParser.MathNestedExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.mathExp()));
}
// -----------------------------------------------------------
// Programming expressions
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program primary expression representation
* generated by its child rules.</p>
*
* @param ctx Program primary expression node in ANTLR4 AST.
*/
@Override
public void exitProgPrimaryExp(ResolveParser.ProgPrimaryExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program application expression.
* This is really a syntactic sugar for the different function
* calls, so all we are returning are program function expressions.</p>
*
* @param ctx Program application expression node in ANTLR4 AST.
*/
@Override
public void exitProgApplicationExp(
ResolveParser.ProgApplicationExpContext ctx) {
Location functionNameLoc = createLocation(ctx.op);
PosSymbol functionName;
switch (ctx.op.getType()) {
case ResolveLexer.AND:
functionName = new PosSymbol(functionNameLoc, "And");
break;
case ResolveLexer.OR:
functionName = new PosSymbol(functionNameLoc, "Or");
break;
case ResolveLexer.EQL:
functionName = new PosSymbol(functionNameLoc, "Are_Equal");
break;
case ResolveLexer.NOT_EQL:
functionName = new PosSymbol(functionNameLoc, "Are_Not_Equal");
break;
case ResolveLexer.LT:
functionName = new PosSymbol(functionNameLoc, "Less");
break;
case ResolveLexer.LT_EQL:
functionName = new PosSymbol(functionNameLoc, "Less_Or_Equal");
break;
case ResolveLexer.GT:
functionName = new PosSymbol(functionNameLoc, "Greater");
break;
case ResolveLexer.GT_EQL:
functionName = new PosSymbol(functionNameLoc, "Greater_Or_Equal");
break;
case ResolveLexer.PLUS:
functionName = new PosSymbol(functionNameLoc, "Sum");
break;
case ResolveLexer.MINUS:
functionName = new PosSymbol(functionNameLoc, "Difference");
break;
case ResolveLexer.MULTIPLY:
functionName = new PosSymbol(functionNameLoc, "Product");
break;
case ResolveLexer.DIVIDE:
functionName = new PosSymbol(functionNameLoc, "Divide");
break;
case ResolveLexer.MOD:
functionName = new PosSymbol(functionNameLoc, "Mod");
break;
case ResolveLexer.REM:
functionName = new PosSymbol(functionNameLoc, "Rem");
break;
default:
functionName = new PosSymbol(functionNameLoc, "Div");
break;
}
List<ProgramExp> args = new ArrayList<>();
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp(0)));
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp(1)));
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), null, functionName, args));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program exponent expressions representation
* generated by its child rules.</p>
*
* @param ctx Program exponential expression node in ANTLR4 AST.
*/
@Override
public void exitProgExponentialExp(
ResolveParser.ProgExponentialExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program exponential expressions.
* This is really a syntactic sugar for the different function
* calls, so all we are returning are program function expressions.</p>
*
* @param ctx Program exponential node in ANTLR4 AST.
*/
@Override
public void exitProgExponential(ResolveParser.ProgExponentialContext ctx) {
PosSymbol functionName = new PosSymbol(createLocation(ctx.EXP().getSymbol()), "Power");
List<ProgramExp> args = new ArrayList<>();
args.add((ProgramExp) myNodes.removeFrom(ctx.progUnary()));
args.add((ProgramExp) myNodes.removeFrom(ctx.progExponential()));
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), null, functionName, args));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program unary expressions.
* This is really a syntactic sugar for the different function
* calls, so all we are returning are program function expressions.</p>
*
* @param ctx Program unary expression node in ANTLR4 AST.
*/
@Override
public void exitProgUnaryExp(ResolveParser.ProgUnaryExpContext ctx) {
Location functionNameLoc = createLocation(ctx.op);
PosSymbol functionName;
List<ProgramExp> args = new ArrayList<>();
switch (ctx.op.getType()) {
case ResolveLexer.NOT:
functionName = new PosSymbol(functionNameLoc, "Not");
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp()));
break;
default:
functionName = new PosSymbol(functionNameLoc, "Negate");
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp()));
break;
}
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), null, functionName, args));
}
/**
* {@inheritDoc}
* <p>
* <p>This is really a syntactic sugar for the different function calls
* in {@code Static_Array_Template}, so we are returning a function call
* generated by its child rules.</p>
*
* @param ctx Program array expression node in ANTLR4 AST.
*/
@Override
public void exitProgArrayExp(ResolveParser.ProgArrayExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program function expression representation
* generated by its child rules.</p>
*
* @param ctx Program function expression node in ANTLR4 AST.
*/
@Override
public void exitProgFunctionExp(ResolveParser.ProgFunctionExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program named variable expression representation
* generated by its child rules.</p>
*
* @param ctx Program named variable expression node in ANTLR4 AST.
*/
@Override
public void exitProgNamedVariableExp(
ResolveParser.ProgNamedVariableExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program literal expression representation
* generated by its child rules.</p>
*
* @param ctx Program literal expression node in ANTLR4 AST.
*/
@Override
public void exitProgLiteralExp(ResolveParser.ProgLiteralExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program nested expression representation
* generated by its child rules.</p>
*
* @param ctx Program nested expression node in ANTLR4 AST.
*/
@Override
public void exitProgNestedExp(ResolveParser.ProgNestedExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>Checks to see if this expression is part of a module argument.
* If yes, then this is an error, because we can't convert it to the
* appropriate function call.</p>
*
* @param ctx Program variable array expression node in ANTLR4 AST.
*/
@Override
public void enterProgVariableArrayExp(
ResolveParser.ProgVariableArrayExpContext ctx) {
if (myIsProcessingModuleArgument) {
myErrorHandler
.error(createLocation(ctx),
"Variable array expressions cannot be passed as module arguments.");
}
}
/**
* {@inheritDoc}
* <p>
* <p>This is really a syntactic sugar for the different function calls
* in {@code Static_Array_Template}, so we are generating the new
* function calls and storing it.</p>
*
* @param ctx Program variable array expression node in ANTLR4 AST.
*/
@Override
public void exitProgVariableArrayExp(
ResolveParser.ProgVariableArrayExpContext ctx) {
// TODO: Migrate VariableArrayExp conversions logic from PreProcessor.
super.enterProgVariableArrayExp(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the program variable expressions
* representation generated by its child rules.</p>
*
* @param ctx Program variable expression node in ANTLR4 AST.
*/
@Override
public void exitProgVariableExp(ResolveParser.ProgVariableExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the program expressions representation
* generated by its child rules or generates a new program variable
* dotted expression.</p>
*
* @param ctx Program dot expression node in ANTLR4 AST.
*/
@Override
public void exitProgDotExp(ResolveParser.ProgDotExpContext ctx) {
ResolveConceptualElement newElement;
// Create a dot expression if needed
List<ResolveParser.ProgNamedExpContext> progNamedExp = ctx.progNamedExp();
if (progNamedExp.size() > 0) {
// dotted expressions
List<ProgramVariableExp> dotExps = new ArrayList<>();
for (ResolveParser.ProgNamedExpContext context : progNamedExp) {
dotExps.add((ProgramVariableExp) myNodes.removeFrom(context));
}
newElement = new ProgramVariableDotExp(createLocation(ctx), dotExps);
}
else {
newElement = myNodes.removeFrom(ctx.progNamedExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program function expression representation.</p>
*
* @param ctx Program function expression node in ANTLR4 AST.
*/
@Override
public void exitProgParamExp(ResolveParser.ProgParamExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// function arguments
List<ResolveParser.ProgExpContext> programExps = ctx.progExp();
List<ProgramExp> functionArgs = new ArrayList<>();
for (ResolveParser.ProgExpContext context : programExps) {
functionArgs.add((ProgramExp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), qualifier, createPosSymbol(ctx.name), functionArgs));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program variable expression representation.</p>
*
* @param ctx Program variable expression node in ANTLR4 AST.
*/
@Override
public void exitProgNamedExp(ResolveParser.ProgNamedExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
myNodes.put(ctx, new ProgramVariableNameExp(createLocation(ctx),
qualifier, createPosSymbol(ctx.name)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program integer literal.</p>
*
* @param ctx Program integer literal node in ANTLR4 AST.
*/
@Override
public void exitProgIntegerExp(ResolveParser.ProgIntegerExpContext ctx) {
myNodes.put(ctx, new ProgramIntegerExp(createLocation(ctx
.INTEGER_LITERAL().getSymbol()), Integer.valueOf(ctx
.INTEGER_LITERAL().getText())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program character literal.</p>
*
* @param ctx Program character literal node in ANTLR4 AST.
*/
@Override
public void exitProgCharacterExp(ResolveParser.ProgCharacterExpContext ctx) {
myNodes.put(ctx, new ProgramCharExp(createLocation(ctx
.CHARACTER_LITERAL().getSymbol()), ctx.CHARACTER_LITERAL()
.getText().charAt(1)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program string literal.</p>
*
* @param ctx Program string literal node in ANTLR4 AST.
*/
@Override
public void exitProgStringExp(ResolveParser.ProgStringExpContext ctx) {
myNodes
.put(ctx, new ProgramStringExp(createLocation(ctx
.STRING_LITERAL().getSymbol()), ctx.STRING_LITERAL()
.getText()));
}
// ===========================================================
// Public Methods
// ===========================================================
/**
* <p>Return the complete module representation build by
* this class.</p>
*
* @return A {link ModuleDec} (intermediate representation) object.
*/
public ModuleDec getModule() {
return myFinalModule;
}
// ===========================================================
// Private Methods
// ===========================================================
/**
* <p>Create a location for the current parser rule
* we are visiting.</p>
*
* @param ctx The visiting ANTLR4 parser rule.
*
* @return A {@link Location} for the rule.
*/
private Location createLocation(ParserRuleContext ctx) {
return createLocation(ctx.getStart());
}
/**
* <p>Create a location for the current parser token
* we are visiting.</p>
*
* @param t The visiting ANTLR4 parser token.
*
* @return A {@link Location} for the rule.
*/
private Location createLocation(Token t) {
return new Location(new Location(myFile, t.getLine(), t
.getCharPositionInLine(), ""));
}
/**
* <p>Create a symbol representation for the current
* parser token we are visiting.</p>
*
* @param t The visiting ANTLR4 parser token.
*
* @return A {@link PosSymbol} for the rule.
*/
private PosSymbol createPosSymbol(Token t) {
return new PosSymbol(createLocation(t), t.getText());
}
// ===========================================================
// Temporary Constructs
// ===========================================================
/**
* <p>This holds items that are needed to build a
* {@link MathDefinitionDec}</p>
*/
private class DefinitionMembers {
// ===========================================================
// Member Fields
// ===========================================================
/** <p>Definition name</p> */
PosSymbol name;
/** <p>Definition parameters</p> */
List<MathVarDec> params;
/** <p>Definition return type</p> */
Ty rawType;
// ===========================================================
// Constructors
// ===========================================================
/**
* <p>This constructs a temporary structure to store all the relevant
* items to build a {@link MathDefinitionDec}.</p>
*
* @param name Definition name.
* @param params Definition parameters.
* @param rawType Definition return type.
*/
DefinitionMembers(PosSymbol name, List<MathVarDec> params, Ty rawType) {
this.name = name;
this.params = params;
this.rawType = rawType;
}
}
/**
* <p>This holds items related to syntactic sugar conversions for
* {@link ProgramExp}s.</p>
*/
private class ProgramExpAdapter {
// ===========================================================
// Member Fields
// ===========================================================
/** <p>The parent context that instantiated this object</p> */
ParserRuleContext parentContext;
/**
* <p>A map from the program expression context to a list
* containing the new RESOLVE AST nodes.</p>
*/
Map<ResolveParser.ProgExpContext, List<ResolveConceptualElement>> progExpAdapterMap;
// ===========================================================
// Constructors
// ===========================================================
/**
* <p>This constructs a temporary structure to store all the relevant
* items to provide syntactic sugar conversions for {@link ProgramExp}s.</p>
*
* @param parentContext The parent context that instantiated this object.
*/
ProgramExpAdapter(ParserRuleContext parentContext) {
this.parentContext = parentContext;
progExpAdapterMap = new HashMap<>();
}
}
} | src/main/java/edu/clemson/cs/rsrg/parsing/TreeBuildingListener.java | /**
* TreeBuildingListener.java
* ---------------------------------
* Copyright (c) 2016
* RESOLVE Software Research Group
* School of Computing
* Clemson University
* All rights reserved.
* ---------------------------------
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package edu.clemson.cs.rsrg.parsing;
import edu.clemson.cs.r2jt.typeandpopulate2.entry.SymbolTableEntry;
import edu.clemson.cs.rsrg.absyn.declarations.Dec;
import edu.clemson.cs.rsrg.absyn.declarations.facilitydecl.FacilityDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathAssertionDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathCategoricalDefinitionDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathDefinitionDec;
import edu.clemson.cs.rsrg.absyn.declarations.mathdecl.MathTypeTheoremDec;
import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.ModuleDec;
import edu.clemson.cs.rsrg.absyn.ResolveConceptualElement;
import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.ShortFacilityModuleDec;
import edu.clemson.cs.rsrg.absyn.declarations.paramdecl.ModuleParameterDec;
import edu.clemson.cs.rsrg.absyn.declarations.variabledecl.MathVarDec;
import edu.clemson.cs.rsrg.absyn.expressions.Exp;
import edu.clemson.cs.rsrg.absyn.expressions.mathexpr.*;
import edu.clemson.cs.rsrg.absyn.expressions.programexpr.*;
import edu.clemson.cs.rsrg.absyn.items.mathitems.DefinitionBodyItem;
import edu.clemson.cs.rsrg.absyn.items.programitems.ModuleArgumentItem;
import edu.clemson.cs.rsrg.absyn.items.programitems.UsesItem;
import edu.clemson.cs.rsrg.absyn.declarations.moduledecl.PrecisModuleDec;
import edu.clemson.cs.rsrg.absyn.rawtypes.ArbitraryExpTy;
import edu.clemson.cs.rsrg.absyn.rawtypes.Ty;
import edu.clemson.cs.rsrg.errorhandling.ErrorHandler;
import edu.clemson.cs.rsrg.init.file.ResolveFile;
import edu.clemson.cs.rsrg.misc.Utilities;
import edu.clemson.cs.rsrg.parsing.data.Location;
import edu.clemson.cs.rsrg.parsing.data.PosSymbol;
import java.util.*;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* <p>This replaces the old RESOLVE ANTLR3 builder and builds the
* intermediate representation objects used during the compilation
* process.</p>
*
* @author Yu-Shan Sun
* @author Daniel Welch
* @version 1.0
*/
public class TreeBuildingListener extends ResolveParserBaseListener {
// ===========================================================
// Member Fields
// ===========================================================
/** <p>Stores all the parser nodes we have encountered.</p> */
private final ParseTreeProperty<ResolveConceptualElement> myNodes;
/**
* <p>Stores the information gathered from the children nodes of
* {@code ResolveParser.DefinitionSignatureContext}</p>
*/
private List<DefinitionMembers> myDefinitionMemberList;
/** <p>Boolean that indicates that we are processing a module argument.</p> */
private boolean myIsProcessingModuleArgument;
/** <p>The complete module representation.</p> */
private ModuleDec myFinalModule;
/** <p>The current file we are compiling.</p> */
private final ResolveFile myFile;
/** <p>The error listener.</p> */
private final ErrorHandler myErrorHandler;
// ===========================================================
// Constructors
// ===========================================================
/**
* <p>Create a listener to walk the entire compiler generated
* ANTLR4 parser tree and generate the intermediate representation
* objects used by the subsequent modules.</p>
*
* @param file The current file we are compiling.
*/
public TreeBuildingListener(ResolveFile file, ErrorHandler errorHandler) {
myErrorHandler = errorHandler;
myFile = file;
myFinalModule = null;
myNodes = new ParseTreeProperty<>();
myDefinitionMemberList = null;
myIsProcessingModuleArgument = false;
}
// ===========================================================
// Visitor Methods
// ===========================================================
// -----------------------------------------------------------
// Module Declaration
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates and saves the complete
* module declaration.</p>
*
* @param ctx Module node in ANTLR4 AST.
*/
@Override
public void exitModule(ResolveParser.ModuleContext ctx) {
myNodes.put(ctx, myNodes.get(ctx.getChild(0)));
myFinalModule = (ModuleDec) myNodes.get(ctx.getChild(0));
}
// -----------------------------------------------------------
// Precis Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>Checks to see if the {@link ResolveFile} name matches the
* open and close names given in the file.</p>
*
* @param ctx Precis module node in ANTLR4 AST.
*/
@Override
public void enterPrecisModule(ResolveParser.PrecisModuleContext ctx) {
if (!myFile.getName().equals(ctx.name.getText())) {
myErrorHandler.error(createLocation(ctx.name),
"Module name does not match filename.");
}
if (!myFile.getName().equals(ctx.closename.getText())) {
myErrorHandler.error(createLocation(ctx.closename),
"End module name does not match the filename.");
}
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a {@code Precis}
* module declaration.</p>
*
* @param ctx Precis module node in ANTLR4 AST.
*/
@Override
public void exitPrecisModule(ResolveParser.PrecisModuleContext ctx) {
List<Dec> decls =
Utilities.collect(Dec.class,
ctx.precisItems() != null ? ctx.precisItems().precisItem() : new ArrayList<ParseTree>(),
myNodes);
List<ModuleParameterDec> parameterDecls = new ArrayList<>();
List<UsesItem> uses = Utilities.collect(UsesItem.class,
ctx.usesList() != null ? ctx.usesList().usesItem() : new ArrayList<ParseTree>(),
myNodes);
PrecisModuleDec precis = new PrecisModuleDec(createLocation(ctx), createPosSymbol(ctx.name), parameterDecls, uses, decls);
myNodes.put(ctx, precis);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the generated precis item.</p>
*
* @param ctx Precis item node in ANTLR4 AST.
*/
@Override
public void exitPrecisItem(ResolveParser.PrecisItemContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
// -----------------------------------------------------------
// Facility Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityModule(ResolveParser.FacilityModuleContext ctx) {
super.enterFacilityModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityModule(ResolveParser.FacilityModuleContext ctx) {
super.exitFacilityModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityItems(ResolveParser.FacilityItemsContext ctx) {
super.enterFacilityItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityItems(ResolveParser.FacilityItemsContext ctx) {
super.exitFacilityItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityItem(ResolveParser.FacilityItemContext ctx) {
super.enterFacilityItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityItem(ResolveParser.FacilityItemContext ctx) {
super.exitFacilityItem(ctx);
}
// -----------------------------------------------------------
// Short Facility Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a short facility
* module declaration.</p>
*
* @param ctx Short facility module node in ANTLR4 AST.
*/
@Override
public void exitShortFacilityModule(
ResolveParser.ShortFacilityModuleContext ctx) {
//FacilityDec facilityDec = (FacilityDec) myNodes.removeFrom(ctx.facilityDecl());
ShortFacilityModuleDec shortFacility =
new ShortFacilityModuleDec(createLocation(ctx),
createPosSymbol(ctx.facilityDecl().name), null);
myNodes.put(ctx, shortFacility);
}
// -----------------------------------------------------------
// Concept Module
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptModule(ResolveParser.ConceptModuleContext ctx) {
super.enterConceptModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptModule(ResolveParser.ConceptModuleContext ctx) {
super.exitConceptModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptItems(ResolveParser.ConceptItemsContext ctx) {
super.enterConceptItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptItems(ResolveParser.ConceptItemsContext ctx) {
super.exitConceptItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptItem(ResolveParser.ConceptItemContext ctx) {
super.enterConceptItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptItem(ResolveParser.ConceptItemContext ctx) {
super.exitConceptItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptImplModule(
ResolveParser.ConceptImplModuleContext ctx) {
super.enterConceptImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptImplModule(ResolveParser.ConceptImplModuleContext ctx) {
super.exitConceptImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementModule(
ResolveParser.EnhancementModuleContext ctx) {
super.enterEnhancementModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementModule(ResolveParser.EnhancementModuleContext ctx) {
super.exitEnhancementModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementItems(ResolveParser.EnhancementItemsContext ctx) {
super.enterEnhancementItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementItems(ResolveParser.EnhancementItemsContext ctx) {
super.exitEnhancementItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementItem(ResolveParser.EnhancementItemContext ctx) {
super.enterEnhancementItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementItem(ResolveParser.EnhancementItemContext ctx) {
super.exitEnhancementItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementImplModule(
ResolveParser.EnhancementImplModuleContext ctx) {
super.enterEnhancementImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementImplModule(
ResolveParser.EnhancementImplModuleContext ctx) {
super.exitEnhancementImplModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterImplItems(ResolveParser.ImplItemsContext ctx) {
super.enterImplItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitImplItems(ResolveParser.ImplItemsContext ctx) {
super.exitImplItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterImplItem(ResolveParser.ImplItemContext ctx) {
super.enterImplItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitImplItem(ResolveParser.ImplItemContext ctx) {
super.exitImplItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptPerformanceModule(
ResolveParser.ConceptPerformanceModuleContext ctx) {
super.enterConceptPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptPerformanceModule(
ResolveParser.ConceptPerformanceModuleContext ctx) {
super.exitConceptPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptPerformanceItems(
ResolveParser.ConceptPerformanceItemsContext ctx) {
super.enterConceptPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptPerformanceItems(
ResolveParser.ConceptPerformanceItemsContext ctx) {
super.exitConceptPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptPerformanceItem(
ResolveParser.ConceptPerformanceItemContext ctx) {
super.enterConceptPerformanceItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptPerformanceItem(
ResolveParser.ConceptPerformanceItemContext ctx) {
super.exitConceptPerformanceItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPerformanceModule(
ResolveParser.EnhancementPerformanceModuleContext ctx) {
super.enterEnhancementPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPerformanceModule(
ResolveParser.EnhancementPerformanceModuleContext ctx) {
super.exitEnhancementPerformanceModule(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPerformanceItems(
ResolveParser.EnhancementPerformanceItemsContext ctx) {
super.enterEnhancementPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPerformanceItems(
ResolveParser.EnhancementPerformanceItemsContext ctx) {
super.exitEnhancementPerformanceItems(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPerformanceItem(
ResolveParser.EnhancementPerformanceItemContext ctx) {
super.enterEnhancementPerformanceItem(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPerformanceItem(
ResolveParser.EnhancementPerformanceItemContext ctx) {
super.exitEnhancementPerformanceItem(ctx);
}
// -----------------------------------------------------------
// Uses Items (Imports)
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation for an import
* module name.</p>
*
* @param ctx Uses item node in ANTLR4 AST.
*/
@Override
public void exitUsesItem(ResolveParser.UsesItemContext ctx) {
myNodes.put(ctx, new UsesItem(createPosSymbol(ctx.getStart())));
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationParameterList(
ResolveParser.OperationParameterListContext ctx) {
super.enterOperationParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationParameterList(
ResolveParser.OperationParameterListContext ctx) {
super.exitOperationParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterModuleParameterList(
ResolveParser.ModuleParameterListContext ctx) {
super.enterModuleParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitModuleParameterList(
ResolveParser.ModuleParameterListContext ctx) {
super.exitModuleParameterList(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterModuleParameterDecl(
ResolveParser.ModuleParameterDeclContext ctx) {
super.enterModuleParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitModuleParameterDecl(
ResolveParser.ModuleParameterDeclContext ctx) {
super.exitModuleParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterDefinitionParameterDecl(
ResolveParser.DefinitionParameterDeclContext ctx) {
super.enterDefinitionParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitDefinitionParameterDecl(
ResolveParser.DefinitionParameterDeclContext ctx) {
super.exitDefinitionParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterTypeParameterDecl(
ResolveParser.TypeParameterDeclContext ctx) {
super.enterTypeParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitTypeParameterDecl(ResolveParser.TypeParameterDeclContext ctx) {
super.exitTypeParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConstantParameterDecl(
ResolveParser.ConstantParameterDeclContext ctx) {
super.enterConstantParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConstantParameterDecl(
ResolveParser.ConstantParameterDeclContext ctx) {
super.exitConstantParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationParameterDecl(
ResolveParser.OperationParameterDeclContext ctx) {
super.enterOperationParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationParameterDecl(
ResolveParser.OperationParameterDeclContext ctx) {
super.exitOperationParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptImplParameterDecl(
ResolveParser.ConceptImplParameterDeclContext ctx) {
super.enterConceptImplParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptImplParameterDecl(
ResolveParser.ConceptImplParameterDeclContext ctx) {
super.exitConceptImplParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterParameterDecl(ResolveParser.ParameterDeclContext ctx) {
super.enterParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitParameterDecl(ResolveParser.ParameterDeclContext ctx) {
super.exitParameterDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterParameterMode(ResolveParser.ParameterModeContext ctx) {
super.enterParameterMode(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitParameterMode(ResolveParser.ParameterModeContext ctx) {
super.exitParameterMode(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterType(ResolveParser.TypeContext ctx) {
super.enterType(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitType(ResolveParser.TypeContext ctx) {
super.exitType(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecord(ResolveParser.RecordContext ctx) {
super.enterRecord(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecord(ResolveParser.RecordContext ctx) {
super.exitRecord(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecordVariableDeclGroup(
ResolveParser.RecordVariableDeclGroupContext ctx) {
super.enterRecordVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecordVariableDeclGroup(
ResolveParser.RecordVariableDeclGroupContext ctx) {
super.exitRecordVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterTypeModelDecl(ResolveParser.TypeModelDeclContext ctx) {
super.enterTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitTypeModelDecl(ResolveParser.TypeModelDeclContext ctx) {
super.exitTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterTypeRepresentationDecl(
ResolveParser.TypeRepresentationDeclContext ctx) {
super.enterTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitTypeRepresentationDecl(
ResolveParser.TypeRepresentationDeclContext ctx) {
super.exitTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityTypeRepresentationDecl(
ResolveParser.FacilityTypeRepresentationDeclContext ctx) {
super.enterFacilityTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityTypeRepresentationDecl(
ResolveParser.FacilityTypeRepresentationDeclContext ctx) {
super.exitFacilityTypeRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceTypeModelDecl(
ResolveParser.PerformanceTypeModelDeclContext ctx) {
super.enterPerformanceTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceTypeModelDecl(
ResolveParser.PerformanceTypeModelDeclContext ctx) {
super.exitPerformanceTypeModelDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSharedStateDecl(ResolveParser.SharedStateDeclContext ctx) {
super.enterSharedStateDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSharedStateDecl(ResolveParser.SharedStateDeclContext ctx) {
super.exitSharedStateDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSharedStateRepresentationDecl(
ResolveParser.SharedStateRepresentationDeclContext ctx) {
super.enterSharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSharedStateRepresentationDecl(
ResolveParser.SharedStateRepresentationDeclContext ctx) {
super.exitSharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilitySharedStateRepresentationDecl(
ResolveParser.FacilitySharedStateRepresentationDeclContext ctx) {
super.enterFacilitySharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilitySharedStateRepresentationDecl(
ResolveParser.FacilitySharedStateRepresentationDeclContext ctx) {
super.exitFacilitySharedStateRepresentationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSpecModelInit(ResolveParser.SpecModelInitContext ctx) {
super.enterSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSpecModelInit(ResolveParser.SpecModelInitContext ctx) {
super.exitSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSpecModelFinal(ResolveParser.SpecModelFinalContext ctx) {
super.enterSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSpecModelFinal(ResolveParser.SpecModelFinalContext ctx) {
super.exitSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRepresentationInit(
ResolveParser.RepresentationInitContext ctx) {
super.enterRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRepresentationInit(
ResolveParser.RepresentationInitContext ctx) {
super.exitRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRepresentationFinal(
ResolveParser.RepresentationFinalContext ctx) {
super.enterRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRepresentationFinal(
ResolveParser.RepresentationFinalContext ctx) {
super.exitRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityRepresentationInit(
ResolveParser.FacilityRepresentationInitContext ctx) {
super.enterFacilityRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityRepresentationInit(
ResolveParser.FacilityRepresentationInitContext ctx) {
super.exitFacilityRepresentationInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterFacilityRepresentationFinal(
ResolveParser.FacilityRepresentationFinalContext ctx) {
super.enterFacilityRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitFacilityRepresentationFinal(
ResolveParser.FacilityRepresentationFinalContext ctx) {
super.exitFacilityRepresentationFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceSpecModelInit(
ResolveParser.PerformanceSpecModelInitContext ctx) {
super.enterPerformanceSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceSpecModelInit(
ResolveParser.PerformanceSpecModelInitContext ctx) {
super.exitPerformanceSpecModelInit(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceSpecModelFinal(
ResolveParser.PerformanceSpecModelFinalContext ctx) {
super.enterPerformanceSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceSpecModelFinal(
ResolveParser.PerformanceSpecModelFinalContext ctx) {
super.exitPerformanceSpecModelFinal(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterProcedureDecl(ResolveParser.ProcedureDeclContext ctx) {
super.enterProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitProcedureDecl(ResolveParser.ProcedureDeclContext ctx) {
super.exitProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecursiveProcedureDecl(
ResolveParser.RecursiveProcedureDeclContext ctx) {
super.enterRecursiveProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecursiveProcedureDecl(
ResolveParser.RecursiveProcedureDeclContext ctx) {
super.exitRecursiveProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationProcedureDecl(
ResolveParser.OperationProcedureDeclContext ctx) {
super.enterOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationProcedureDecl(
ResolveParser.OperationProcedureDeclContext ctx) {
super.exitOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRecursiveOperationProcedureDecl(
ResolveParser.RecursiveOperationProcedureDeclContext ctx) {
super.enterRecursiveOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRecursiveOperationProcedureDecl(
ResolveParser.RecursiveOperationProcedureDeclContext ctx) {
super.exitRecursiveOperationProcedureDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterOperationDecl(ResolveParser.OperationDeclContext ctx) {
super.enterOperationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitOperationDecl(ResolveParser.OperationDeclContext ctx) {
super.exitOperationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPerformanceOperationDecl(
ResolveParser.PerformanceOperationDeclContext ctx) {
super.enterPerformanceOperationDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPerformanceOperationDecl(
ResolveParser.PerformanceOperationDeclContext ctx) {
super.exitPerformanceOperationDecl(ctx);
}
// -----------------------------------------------------------
// Facility declarations
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a new representation for a facility
* declaration.</p>
*
* @param ctx Facility declaration node in ANTLR4 AST.
*/
@Override
public void exitFacilityDecl(ResolveParser.FacilityDeclContext ctx) {
// Concept arguments
List<ModuleArgumentItem> conceptArgs = new ArrayList<>();
if (ctx.specArgs != null) {
List<ResolveParser.ModuleArgumentContext> conceptArgContext = ctx.specArgs.moduleArgument();
for (ResolveParser.ModuleArgumentContext context : conceptArgContext) {
//conceptArgs.add((ModuleArgumentItem) myNodes.removeFrom(context));
}
}
//myNodes.put(ctx, new FacilityDec());
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConceptEnhancementDecl(
ResolveParser.ConceptEnhancementDeclContext ctx) {
super.enterConceptEnhancementDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConceptEnhancementDecl(
ResolveParser.ConceptEnhancementDeclContext ctx) {
super.exitConceptEnhancementDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnhancementPairDecl(
ResolveParser.EnhancementPairDeclContext ctx) {
super.enterEnhancementPairDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnhancementPairDecl(
ResolveParser.EnhancementPairDeclContext ctx) {
super.exitEnhancementPairDecl(ctx);
}
// -----------------------------------------------------------
// Module arguments
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>Since programming array expressions are simply syntactic sugar
* that gets converted to call statements, they are not allowed to be
* passed as module argument. This method stores a boolean that indicates
* we are in a module argument.</p>
*
* @param ctx Module argument node in ANTLR4 AST.
*/
@Override
public void enterModuleArgument(ResolveParser.ModuleArgumentContext ctx) {
myIsProcessingModuleArgument = true;
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a module
* argument.</p>
*
* @param ctx Module argument node in ANTLR4 AST.
*/
@Override
public void exitModuleArgument(ResolveParser.ModuleArgumentContext ctx) {
myIsProcessingModuleArgument = false;
}
// -----------------------------------------------------------
// Variable declarations
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method stores all math variable declarations.</p>
*
* @param ctx Math variable declaration groups node in ANTLR4 AST.
*/
@Override
public void exitMathVariableDeclGroup(
ResolveParser.MathVariableDeclGroupContext ctx) {
Ty rawType = (Ty) myNodes.removeFrom(ctx.mathTypeExp());
List<TerminalNode> varNames = ctx.IDENTIFIER();
for (TerminalNode varName : varNames) {
myNodes.put(varName, new MathVarDec(createPosSymbol(varName
.getSymbol()), rawType.clone()));
}
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a math variable declaration.</p>
*
* @param ctx Math variable declaration node in ANTLR4 AST.
*/
@Override
public void exitMathVariableDecl(ResolveParser.MathVariableDeclContext ctx) {
Ty rawType = (Ty) myNodes.removeFrom(ctx.mathTypeExp());
myNodes.put(ctx, new MathVarDec(createPosSymbol(ctx.IDENTIFIER()
.getSymbol()), rawType));
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterVariableDeclGroup(
ResolveParser.VariableDeclGroupContext ctx) {
super.enterVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitVariableDeclGroup(ResolveParser.VariableDeclGroupContext ctx) {
super.exitVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterVariableDecl(ResolveParser.VariableDeclContext ctx) {
super.enterVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitVariableDecl(ResolveParser.VariableDeclContext ctx) {
super.exitVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAuxVariableDeclGroup(
ResolveParser.AuxVariableDeclGroupContext ctx) {
super.enterAuxVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAuxVariableDeclGroup(
ResolveParser.AuxVariableDeclGroupContext ctx) {
super.exitAuxVariableDeclGroup(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAuxVariableDecl(ResolveParser.AuxVariableDeclContext ctx) {
super.enterAuxVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAuxVariableDecl(ResolveParser.AuxVariableDeclContext ctx) {
super.exitAuxVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterModuleStateVariableDecl(
ResolveParser.ModuleStateVariableDeclContext ctx) {
super.enterModuleStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitModuleStateVariableDecl(
ResolveParser.ModuleStateVariableDeclContext ctx) {
super.exitModuleStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterStateVariableDecl(
ResolveParser.StateVariableDeclContext ctx) {
super.enterStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitStateVariableDecl(ResolveParser.StateVariableDeclContext ctx) {
super.exitStateVariableDecl(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterStmt(ResolveParser.StmtContext ctx) {
super.enterStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitStmt(ResolveParser.StmtContext ctx) {
super.exitStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAssignStmt(ResolveParser.AssignStmtContext ctx) {
super.enterAssignStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAssignStmt(ResolveParser.AssignStmtContext ctx) {
super.exitAssignStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterSwapStmt(ResolveParser.SwapStmtContext ctx) {
super.enterSwapStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitSwapStmt(ResolveParser.SwapStmtContext ctx) {
super.exitSwapStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterCallStmt(ResolveParser.CallStmtContext ctx) {
super.enterCallStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitCallStmt(ResolveParser.CallStmtContext ctx) {
super.exitCallStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterPresumeStmt(ResolveParser.PresumeStmtContext ctx) {
super.enterPresumeStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitPresumeStmt(ResolveParser.PresumeStmtContext ctx) {
super.exitPresumeStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConfirmStmt(ResolveParser.ConfirmStmtContext ctx) {
super.enterConfirmStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConfirmStmt(ResolveParser.ConfirmStmtContext ctx) {
super.exitConfirmStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterIfStmt(ResolveParser.IfStmtContext ctx) {
super.enterIfStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitIfStmt(ResolveParser.IfStmtContext ctx) {
super.exitIfStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterElsePart(ResolveParser.ElsePartContext ctx) {
super.enterElsePart(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitElsePart(ResolveParser.ElsePartContext ctx) {
super.exitElsePart(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterWhileStmt(ResolveParser.WhileStmtContext ctx) {
super.enterWhileStmt(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitWhileStmt(ResolveParser.WhileStmtContext ctx) {
super.exitWhileStmt(ctx);
}
// -----------------------------------------------------------
// Mathematical type theorems
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a math
* type theorem declaration.</p>
*
* @param ctx Type theorem declaration node in ANTLR4 AST.
*/
@Override
public void exitMathTypeTheoremDecl(
ResolveParser.MathTypeTheoremDeclContext ctx) {
List<MathVarDec> varDecls =
Utilities.collect(MathVarDec.class,
ctx.mathVariableDeclGroup(), myNodes);
Exp assertionExp = (Exp) myNodes.removeFrom(ctx.mathImpliesExp());
myNodes.put(ctx, new MathTypeTheoremDec(createPosSymbol(ctx.name),
varDecls, assertionExp));
}
// -----------------------------------------------------------
// Mathematical theorems, corollaries, etc
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a representation of a math assertion
* declaration.</p>
*
* @param ctx Math assertion declaration node in ANTLR4 AST.
*/
@Override
public void exitMathAssertionDecl(ResolveParser.MathAssertionDeclContext ctx) {
ResolveConceptualElement newElement;
Exp mathExp = (Exp) myNodes.removeFrom(ctx.mathExp());
switch (ctx.assertionType.getType()) {
case ResolveLexer.THEOREM:
case ResolveLexer.THEOREM_ASSOCIATIVE:
case ResolveLexer.THEOREM_COMMUTATIVE:
MathAssertionDec.TheoremSubtype theoremSubtype;
if (ctx.assertionType.getType() == ResolveLexer.THEOREM_ASSOCIATIVE) {
theoremSubtype = MathAssertionDec.TheoremSubtype.ASSOCIATIVITY;
}
else if (ctx.assertionType.getType() == ResolveLexer.THEOREM_COMMUTATIVE) {
theoremSubtype = MathAssertionDec.TheoremSubtype.COMMUTATIVITY;
}
else {
theoremSubtype = MathAssertionDec.TheoremSubtype.NONE;
}
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
theoremSubtype, mathExp);
break;
case ResolveLexer.AXIOM:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.AXIOM, mathExp);
break;
case ResolveLexer.COROLLARY:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.COROLLARY, mathExp);
break;
case ResolveLexer.LEMMA:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.LEMMA, mathExp);
break;
default:
newElement =
new MathAssertionDec(createPosSymbol(ctx.name.getStart()),
MathAssertionDec.AssertionType.PROPERTY, mathExp);
break;
}
myNodes.put(ctx, newElement);
}
// -----------------------------------------------------------
// Mathematical definitions
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method creates a temporary list to store all the
* temporary definition members</p>
*
* @param ctx Defines declaration node in ANTLR4 AST.
*/
@Override
public void enterMathDefinesDecl(ResolveParser.MathDefinesDeclContext ctx) {
myDefinitionMemberList = new ArrayList<>();
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a defines declaration.</p>
*
* @param ctx Defines declaration node in ANTLR4 AST.
*/
@Override
public void exitMathDefinesDecl(ResolveParser.MathDefinesDeclContext ctx) {
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, null, false);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
/**
* {@inheritDoc}
* <p>
* <p>This method creates a temporary list to store all the
* temporary definition members</p>
*
* @param ctx Definition declaration node in ANTLR4 AST.
*/
@Override
public void enterMathDefinitionDecl(ResolveParser.MathDefinitionDeclContext ctx) {
myDefinitionMemberList = new ArrayList<>();
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the definition representation
* generated by its child rules.</p>
*
* @param ctx Definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathDefinitionDecl(
ResolveParser.MathDefinitionDeclContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a categorical definition declaration.</p>
*
* @param ctx Categorical definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathCategoricalDecl(
ResolveParser.MathCategoricalDeclContext ctx) {
// Create all the definition declarations inside
// the categorical definition
List<MathDefinitionDec> definitionDecls = new ArrayList<>();
for (DefinitionMembers members : myDefinitionMemberList) {
definitionDecls.add(new MathDefinitionDec(members.name, members.params, members.rawType, null, false));
}
myDefinitionMemberList = null;
myNodes.put(ctx, new MathCategoricalDefinitionDec(createPosSymbol(ctx.name), definitionDecls, (Exp) myNodes.removeFrom(ctx.mathExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates an implicit definition declaration.</p>
*
* @param ctx Implicit definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathImplicitDefinitionDecl(
ResolveParser.MathImplicitDefinitionDeclContext ctx) {
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, new DefinitionBodyItem((Exp) myNodes
.removeFrom(ctx.mathExp())), true);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates an inductive definition declaration.</p>
*
* @param ctx Inductive definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathInductiveDefinitionDecl(
ResolveParser.MathInductiveDefinitionDeclContext ctx) {
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, new DefinitionBodyItem((Exp) myNodes
.removeFrom(ctx.mathExp(0)), (Exp) myNodes
.removeFrom(ctx.mathExp(1))), false);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a standard definition declaration.</p>
*
* @param ctx Standard definition declaration node in ANTLR4 AST.
*/
@Override
public void exitMathStandardDefinitionDecl(
ResolveParser.MathStandardDefinitionDeclContext ctx) {
DefinitionBodyItem bodyItem = null;
if (ctx.mathExp() != null) {
bodyItem =
new DefinitionBodyItem((Exp) myNodes.removeFrom(ctx
.mathExp()));
}
DefinitionMembers members = myDefinitionMemberList.remove(0);
MathDefinitionDec definitionDec =
new MathDefinitionDec(members.name, members.params,
members.rawType, bodyItem, false);
myDefinitionMemberList = null;
myNodes.put(ctx, definitionDec);
}
// -----------------------------------------------------------
// Standard definition signatures
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a temporary definition member object that stores
* all the relevant information needed by the parent rule.</p>
*
* @param ctx Infix definition signature node in ANTLR4 AST.
*/
@Override
public void exitStandardInfixSignature(
ResolveParser.StandardInfixSignatureContext ctx) {
PosSymbol name;
if (ctx.IDENTIFIER() != null) {
name = createPosSymbol(ctx.IDENTIFIER().getSymbol());
}
else {
name = createPosSymbol(ctx.infixOp().op);
}
List<MathVarDec> varDecls = new ArrayList<>();
varDecls.add((MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl(0)));
varDecls.add((MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl(1)));
myDefinitionMemberList.add(new DefinitionMembers(name, varDecls, (Ty) myNodes.removeFrom(ctx.mathTypeExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a temporary definition member object that stores
* all the relevant information needed by the parent rule.</p>
*
* @param ctx Outfix definition signature node in ANTLR4 AST.
*/
@Override
public void exitStandardOutfixSignature(
ResolveParser.StandardOutfixSignatureContext ctx) {
PosSymbol name = new PosSymbol(createLocation(ctx.lOp), ctx.lOp.getText() + "_" + ctx.rOp.getText());
List<MathVarDec> varDecls = new ArrayList<>();
varDecls.add((MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl()));
myDefinitionMemberList.add(new DefinitionMembers(name, varDecls, (Ty) myNodes.removeFrom(ctx.mathTypeExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method generates a temporary definition member object that stores
* all the relevant information needed by the parent rule.</p>
*
* @param ctx Prefix definition signature node in ANTLR4 AST.
*/
@Override
public void exitStandardPrefixSignature(
ResolveParser.StandardPrefixSignatureContext ctx) {
Token nameToken;
if (ctx.getStart() == ctx.prefixOp()) {
nameToken = ctx.prefixOp().getStart();
}
else {
nameToken = ctx.getStart();
}
PosSymbol name = createPosSymbol(nameToken);
List<MathVarDec> varDecls =
Utilities.collect(MathVarDec.class, ctx
.definitionParameterList() != null ? ctx
.definitionParameterList().mathVariableDeclGroup()
: new ArrayList<ParseTree>(), myNodes);
myDefinitionMemberList.add(new DefinitionMembers(name, varDecls,
(Ty) myNodes.removeFrom(ctx.mathTypeExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math expression representation
* generated by its child rules.</p>
*
* @param ctx Definition parameter list node in ANTLR4 AST.
*/
@Override
public void exitDefinitionParameterList(
ResolveParser.DefinitionParameterListContext ctx) {
List<ResolveParser.MathVariableDeclGroupContext> variableDeclGroups =
ctx.mathVariableDeclGroup();
for (ResolveParser.MathVariableDeclGroupContext context : variableDeclGroups) {
List<TerminalNode> identifiers = context.IDENTIFIER();
for (TerminalNode id : identifiers) {
myNodes.put(context, myNodes.removeFrom(id));
}
}
}
// -----------------------------------------------------------
// Different Types of Clauses
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterAffectsClause(ResolveParser.AffectsClauseContext ctx) {
super.enterAffectsClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitAffectsClause(ResolveParser.AffectsClauseContext ctx) {
super.exitAffectsClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterRequiresClause(ResolveParser.RequiresClauseContext ctx) {
super.enterRequiresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitRequiresClause(ResolveParser.RequiresClauseContext ctx) {
super.exitRequiresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterEnsuresClause(ResolveParser.EnsuresClauseContext ctx) {
super.enterEnsuresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitEnsuresClause(ResolveParser.EnsuresClauseContext ctx) {
super.exitEnsuresClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConstraintClause(ResolveParser.ConstraintClauseContext ctx) {
super.enterConstraintClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConstraintClause(ResolveParser.ConstraintClauseContext ctx) {
super.exitConstraintClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterChangingClause(ResolveParser.ChangingClauseContext ctx) {
super.enterChangingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitChangingClause(ResolveParser.ChangingClauseContext ctx) {
super.exitChangingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterMaintainingClause(
ResolveParser.MaintainingClauseContext ctx) {
super.enterMaintainingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitMaintainingClause(ResolveParser.MaintainingClauseContext ctx) {
super.exitMaintainingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterDecreasingClause(ResolveParser.DecreasingClauseContext ctx) {
super.enterDecreasingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitDecreasingClause(ResolveParser.DecreasingClauseContext ctx) {
super.exitDecreasingClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterWhereClause(ResolveParser.WhereClauseContext ctx) {
super.enterWhereClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitWhereClause(ResolveParser.WhereClauseContext ctx) {
super.exitWhereClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterCorrespondenceClause(
ResolveParser.CorrespondenceClauseContext ctx) {
super.enterCorrespondenceClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitCorrespondenceClause(
ResolveParser.CorrespondenceClauseContext ctx) {
super.exitCorrespondenceClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterConventionClause(ResolveParser.ConventionClauseContext ctx) {
super.enterConventionClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitConventionClause(ResolveParser.ConventionClauseContext ctx) {
super.exitConventionClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterDurationClause(ResolveParser.DurationClauseContext ctx) {
super.enterDurationClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitDurationClause(ResolveParser.DurationClauseContext ctx) {
super.exitDurationClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void enterManipulationDispClause(
ResolveParser.ManipulationDispClauseContext ctx) {
super.enterManipulationDispClause(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>The default implementation does nothing.</p>
*
* @param ctx
*/
@Override
public void exitManipulationDispClause(
ResolveParser.ManipulationDispClauseContext ctx) {
super.exitManipulationDispClause(ctx);
}
// -----------------------------------------------------------
// Arbitrary raw type built from a math expression
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method generates a new arbitrary type with
* the math type expression generated by its child rules.</p>
*
* @param ctx Math type expression node in ANTLR4 AST.
*/
@Override
public void exitMathTypeExp(ResolveParser.MathTypeExpContext ctx) {
myNodes.put(ctx, new ArbitraryExpTy((Exp) myNodes.removeFrom(ctx
.getChild(0))));
}
// -----------------------------------------------------------
// Mathematical expressions
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math expression representation
* generated by its child rules.</p>
*
* @param ctx Math expression node in ANTLR4 AST.
*/
@Override
public void exitMathExp(ResolveParser.MathExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates an iterated math expression.</p>
*
* @param ctx Math iterated expression node in ANTLR4 AST.
*/
@Override
public void exitMathIteratedExp(ResolveParser.MathIteratedExpContext ctx) {
IterativeExp.Operator operator;
switch (ctx.op.getType()) {
case ResolveLexer.BIG_CONCAT:
operator = IterativeExp.Operator.CONCATENATION;
break;
case ResolveLexer.BIG_INTERSECT:
operator = IterativeExp.Operator.INTERSECTION;
break;
case ResolveLexer.BIG_PRODUCT:
operator = IterativeExp.Operator.PRODUCT;
break;
case ResolveLexer.BIG_SUM:
operator = IterativeExp.Operator.SUM;
break;
default:
operator = IterativeExp.Operator.UNION;
break;
}
MathVarDec varDecl =
(MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl());
Exp whereExp = (Exp) myNodes.removeFrom(ctx.whereClause());
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new IterativeExp(createLocation(ctx), operator,
varDecl, whereExp, bodyExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a quantified math expression.</p>
*
* @param ctx Math quantified expression node in ANTLR4 AST.
*/
@Override
public void exitMathQuantifiedExp(ResolveParser.MathQuantifiedExpContext ctx) {
ResolveConceptualElement newElement;
ParseTree child = ctx.getChild(0);
// Only need to construct a new ResolveConceptualElement if
// it is a quantified expression.
if (child instanceof ResolveParser.MathImpliesExpContext) {
newElement = myNodes.removeFrom(child);
}
else {
SymbolTableEntry.Quantification quantification;
switch (ctx.getStart().getType()) {
case ResolveLexer.FORALL:
quantification = SymbolTableEntry.Quantification.UNIVERSAL;
break;
case ResolveLexer.EXISTS:
quantification = SymbolTableEntry.Quantification.EXISTENTIAL;
break;
default:
quantification = SymbolTableEntry.Quantification.UNIQUE;
break;
}
List<MathVarDec> mathVarDecls =
Utilities.collect(MathVarDec.class, ctx
.mathVariableDeclGroup() != null ? ctx
.mathVariableDeclGroup().IDENTIFIER()
: new ArrayList<ParseTree>(), myNodes);
Exp whereExp = (Exp) myNodes.removeFrom(ctx.whereClause());
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathQuantifiedExp());
newElement =
new QuantExp(createLocation(ctx), quantification,
mathVarDecls, whereExp, bodyExp);
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math implies expression.</p>
*
* @param ctx Math implies expression node in ANTLR4 AST.
*/
@Override
public void exitMathImpliesExp(ResolveParser.MathImpliesExpContext ctx) {
ResolveConceptualElement newElement;
// if-then-else expressions
if (ctx.getStart().getType() == ResolveLexer.IF) {
Exp testExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(0));
Exp thenExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(1));
Exp elseExp = null;
if (ctx.mathLogicalExp().size() > 2) {
elseExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(2));
}
newElement =
new IfExp(createLocation(ctx), testExp, thenExp, elseExp);
}
// iff and implies expressions
else if (ctx.op != null) {
Exp leftExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(0));
Exp rightExp = (Exp) myNodes.removeFrom(ctx.mathLogicalExp(1));
newElement =
new InfixExp(createLocation(ctx), leftExp, null,
createPosSymbol(ctx.op), rightExp);
}
else {
newElement = myNodes.removeFrom(ctx.mathLogicalExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math infix expression
* that contains all the logical expressions.</p>
*
* @param ctx Math logical expression node in ANTLR4 AST.
*/
@Override
public void exitMathLogicalExp(ResolveParser.MathLogicalExpContext ctx) {
ResolveConceptualElement newElement;
List<ResolveParser.MathRelationalExpContext> relationalExpContexts =
ctx.mathRelationalExp();
// relational expressions
if (relationalExpContexts.size() == 1) {
newElement = myNodes.removeFrom(ctx.mathRelationalExp(0));
}
// build logical expressions
else {
// Obtain the 2 expressions
Exp leftExp = (Exp) myNodes.removeFrom(ctx.mathRelationalExp(0));
Exp rightExp = (Exp) myNodes.removeFrom(ctx.mathRelationalExp(1));
newElement =
new InfixExp(leftExp.getLocation(), leftExp, null,
createPosSymbol(ctx.op), rightExp);
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules, generates a new math between expression
* or generates a new math infix expression with the specified
* operators.</p>
*
* @param ctx Math relational expression node in ANTLR4 AST.
*/
@Override
public void exitMathRelationalExp(ResolveParser.MathRelationalExpContext ctx) {
ResolveConceptualElement newElement;
// Check to see if this a between expression
if (ctx.op1 != null && ctx.op2 != null) {
// Obtain the 3 expressions
Exp exp1 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(0));
Exp exp2 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(1));
Exp exp3 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(2));
List<Exp> joiningExps = new ArrayList<>();
joiningExps.add(new InfixExp(new Location(exp1.getLocation()), exp1.clone(), null, createPosSymbol(ctx.op1), exp2.clone()));
joiningExps.add(new InfixExp(new Location(exp1.getLocation()), exp2.clone(), null, createPosSymbol(ctx.op2), exp3.clone()));
newElement = new BetweenExp(createLocation(ctx), joiningExps);
}
else {
// Create a math infix expression with the specified operator if needed
if (ctx.mathInfixExp().size() > 1) {
// Obtain the 2 expressions
Exp exp1 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(0));
Exp exp2 = (Exp) myNodes.removeFrom(ctx.mathInfixExp(1));
switch (ctx.op.getType()) {
case ResolveLexer.EQL:
case ResolveLexer.NOT_EQL:
EqualsExp.Operator op;
if (ctx.op.getType() == ResolveLexer.EQL) {
op = EqualsExp.Operator.EQUAL;
}
else {
op = EqualsExp.Operator.NOT_EQUAL;
}
newElement = new EqualsExp(createLocation(ctx), exp1, null, op, exp2);
break;
default:
newElement = new InfixExp(createLocation(ctx), exp1, null, createPosSymbol(ctx.op), exp2);
break;
}
}
else {
newElement = myNodes.removeFrom(ctx.mathInfixExp(0));
}
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math infix expression
* with a range operator.</p>
*
* @param ctx Math infix expression node in ANTLR4 AST.
*/
@Override
public void exitMathInfixExp(ResolveParser.MathInfixExpContext ctx) {
ResolveConceptualElement newElement;
// Create a math infix expression with a range operator if needed
if (ctx.mathTypeAssertionExp().size() > 1) {
newElement =
new InfixExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathTypeAssertionExp(0)), null,
createPosSymbol(ctx.RANGE().getSymbol()),
(Exp) myNodes.removeFrom(ctx
.mathTypeAssertionExp(1)));
}
else {
newElement = myNodes.removeFrom(ctx.mathTypeAssertionExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math type assertion expression.</p>
*
* @param ctx Math type assertion expression node in ANTLR4 AST.
*/
@Override
public void exitMathTypeAssertionExp(
ResolveParser.MathTypeAssertionExpContext ctx) {
ResolveConceptualElement newElement;
// Create a math type assertion expression if needed
if (ctx.mathTypeExp() != null) {
newElement =
new TypeAssertionExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathFunctionTypeExp()),
(ArbitraryExpTy) myNodes.removeFrom(ctx
.mathTypeExp()));
}
else {
newElement = myNodes.removeFrom(ctx.mathFunctionTypeExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math function type expression.</p>
*
* @param ctx Math function type expression node in ANTLR4 AST.
*/
@Override
public void exitMathFunctionTypeExp(
ResolveParser.MathFunctionTypeExpContext ctx) {
ResolveConceptualElement newElement;
// Create an function type expression if needed
if (ctx.mathAddingExp().size() > 1) {
newElement =
new InfixExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathAddingExp(0)), null,
createPosSymbol(ctx.FUNCARROW().getSymbol()),
(Exp) myNodes.removeFrom(ctx.mathAddingExp(1)));
}
else {
newElement = myNodes.removeFrom(ctx.mathAddingExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math adding expression.</p>
*
* @param ctx Math adding expression node in ANTLR4 AST.
*/
@Override
public void exitMathAddingExp(ResolveParser.MathAddingExpContext ctx) {
ResolveConceptualElement newElement;
// Create an addition expression if needed
List<ResolveParser.MathMultiplyingExpContext> mathExps =
ctx.mathMultiplyingExp();
if (mathExps.size() > 1) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// Obtain the 2 expressions
Exp exp1 = (Exp) myNodes.removeFrom(mathExps.get(0));
Exp exp2 = (Exp) myNodes.removeFrom(mathExps.get(1));
newElement =
new InfixExp(createLocation(ctx), exp1, qualifier,
createPosSymbol(ctx.op), exp2);
}
else {
newElement = myNodes.removeFrom(mathExps.remove(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math multiplication expression.</p>
*
* @param ctx Math multiplication expression node in ANTLR4 AST.
*/
@Override
public void exitMathMultiplyingExp(
ResolveParser.MathMultiplyingExpContext ctx) {
ResolveConceptualElement newElement;
// Create a multiplication expression if needed
List<ResolveParser.MathExponentialExpContext> mathExps =
ctx.mathExponentialExp();
if (mathExps.size() != 1) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// Obtain the 2 expressions
Exp exp1 = (Exp) myNodes.removeFrom(mathExps.get(0));
Exp exp2 = (Exp) myNodes.removeFrom(mathExps.get(1));
newElement =
new InfixExp(createLocation(ctx), exp1, qualifier,
createPosSymbol(ctx.op), exp2);
}
else {
newElement = myNodes.removeFrom(mathExps.remove(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math exponential expression.</p>
*
* @param ctx Math exponential expression node in ANTLR4 AST.
*/
@Override
public void exitMathExponentialExp(
ResolveParser.MathExponentialExpContext ctx) {
ResolveConceptualElement newElement;
// Create a exponential expression if needed
if (ctx.mathExponentialExp() != null) {
newElement =
new InfixExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathPrefixExp()), null,
createPosSymbol(ctx.EXP().getSymbol()),
(Exp) myNodes.removeFrom(ctx.mathExponentialExp()));
}
else {
newElement = myNodes.removeFrom(ctx.mathPrefixExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expression representation
* generated by its child rules or generates a new math prefix expression.</p>
*
* @param ctx Math prefix expression node in ANTLR4 AST.
*/
@Override
public void exitMathPrefixExp(ResolveParser.MathPrefixExpContext ctx) {
ResolveConceptualElement newElement;
// Create a prefix expression if needed
if (ctx.prefixOp() != null) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
newElement =
new PrefixExp(createLocation(ctx), qualifier,
createPosSymbol(ctx.prefixOp().op), (Exp) myNodes
.removeFrom(ctx.mathPrimaryExp()));
}
else {
newElement = myNodes.removeFrom(ctx.mathPrimaryExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a math expression representation
* generated by its child rules.</p>
*
* @param ctx Math primary expression node in ANTLR4 AST.
*/
@Override
public void exitMathPrimaryExp(ResolveParser.MathPrimaryExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the mathematical alternative expression.</p>
*
* @param ctx Math alternative expression node in ANTLR4 AST.
*/
@Override
public void exitMathAlternativeExp(
ResolveParser.MathAlternativeExpContext ctx) {
List<ResolveParser.MathAlternativeExpItemContext> mathExps = ctx.mathAlternativeExpItem();
List<AltItemExp> alternatives = new ArrayList<>();
for (ResolveParser.MathAlternativeExpItemContext context : mathExps) {
alternatives.add((AltItemExp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new AlternativeExp(createLocation(ctx), alternatives));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the different alternatives for the
* mathematical alternative expression.</p>
*
* @param ctx Math alternative expression item node in ANTLR4 AST.
*/
@Override
public void exitMathAlternativeExpItem(
ResolveParser.MathAlternativeExpItemContext ctx) {
Exp testExp = null;
if (ctx.mathRelationalExp() != null) {
testExp = (Exp) myNodes.removeFrom(ctx.mathRelationalExp());
}
myNodes.put(ctx, new AltItemExp(createLocation(ctx), testExp,
(Exp) myNodes.removeFrom(ctx.mathAddingExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math boolean literal.</p>
*
* @param ctx Math boolean literal node in ANTLR4 AST.
*/
@Override
public void exitMathBooleanExp(ResolveParser.MathBooleanExpContext ctx) {
myNodes.put(ctx, new VarExp(createLocation(ctx.BOOLEAN_LITERAL()
.getSymbol()), null, createPosSymbol(ctx.BOOLEAN_LITERAL()
.getSymbol())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math integer literal.</p>
*
* @param ctx Math integer literal node in ANTLR4 AST.
*/
@Override
public void exitMathIntegerExp(ResolveParser.MathIntegerExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
myNodes.put(ctx, new IntegerExp(createLocation(ctx), qualifier, Integer
.valueOf(ctx.INTEGER_LITERAL().getText())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math real literal.</p>
*
* @param ctx Math real literal node in ANTLR4 AST.
*/
@Override
public void exitMathRealExp(ResolveParser.MathRealExpContext ctx) {
myNodes.put(ctx, new DoubleExp(createLocation(ctx.REAL_LITERAL()
.getSymbol()), Double.valueOf(ctx.REAL_LITERAL().getText())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math character literal.</p>
*
* @param ctx Math character literal node in ANTLR4 AST.
*/
@Override
public void exitMathCharacterExp(ResolveParser.MathCharacterExpContext ctx) {
myNodes.put(ctx, new CharExp(createLocation(ctx.CHARACTER_LITERAL()
.getSymbol()), ctx.CHARACTER_LITERAL().getText().charAt(1)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math string literal.</p>
*
* @param ctx Math string literal node in ANTLR4 AST.
*/
@Override
public void exitMathStringExp(ResolveParser.MathStringExpContext ctx) {
myNodes.put(ctx, new StringExp(createLocation(ctx.STRING_LITERAL()
.getSymbol()), ctx.STRING_LITERAL().getText()));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the math expressions representation
* generated by its child rules or generates a new math dotted expression.</p>
*
* @param ctx Math dot expression node in ANTLR4 AST.
*/
@Override
public void exitMathDotExp(ResolveParser.MathDotExpContext ctx) {
ResolveConceptualElement newElement;
// Create a dot expression if needed
List<ResolveParser.MathCleanFunctionExpContext> mathExps = ctx.mathCleanFunctionExp();
if (mathExps.size() > 0) {
// dotted expressions
List<Exp> dotExps = new ArrayList<>();
dotExps.add((Exp) myNodes.removeFrom(ctx.mathFunctionApplicationExp()));
for (ResolveParser.MathCleanFunctionExpContext context : mathExps) {
dotExps.add((Exp) myNodes.removeFrom(context));
}
newElement = new DotExp(createLocation(ctx), dotExps);
}
else {
newElement = myNodes.removeFrom(ctx.mathFunctionApplicationExp());
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a math function expression or variable expression
* representation generated by its child rules.</p>
*
* @param ctx Math function or variable expression node in ANTLR4 AST.
*/
@Override
public void exitMathFunctOrVarExp(ResolveParser.MathFunctOrVarExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.mathCleanFunctionExp()));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math old expression representation.</p>
*
* @param ctx Math old expression node in ANTLR4 AST.
*/
@Override
public void exitMathOldExp(ResolveParser.MathOldExpContext ctx) {
myNodes.put(ctx, new OldExp(createLocation(ctx), (Exp) myNodes
.removeFrom(ctx.mathCleanFunctionExp())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math function expression representation.</p>
*
* @param ctx Math function expression node in ANTLR4 AST.
*/
@Override
public void exitMathFunctionExp(ResolveParser.MathFunctionExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// function name
VarExp functionNameExp = new VarExp(createLocation(ctx.name), null, createPosSymbol(ctx.name));
// exponent-like part to the name
Exp caratExp = (Exp) myNodes.removeFrom(ctx.mathNestedExp());
// function arguments
List<ResolveParser.MathExpContext> mathExps = ctx.mathExp();
List<Exp> functionArgs = new ArrayList<>();
for (ResolveParser.MathExpContext context : mathExps) {
functionArgs.add((Exp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new FunctionExp(createLocation(ctx), qualifier, functionNameExp, caratExp, functionArgs));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math variable expression representation.</p>
*
* @param ctx Math variable expression node in ANTLR4 AST.
*/
@Override
public void exitMathVarExp(ResolveParser.MathVarExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
myNodes.put(ctx, new VarExp(createLocation(ctx), qualifier,
createPosSymbol(ctx.name)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math operator name expression representation.</p>
*
* @param ctx Math operator name expression node in ANTLR4 AST.
*/
@Override
public void exitMathOpNameExp(ResolveParser.MathOpNameExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
Token opToken;
if (ctx.infixOp() != null) {
opToken = ctx.infixOp().op;
}
else {
opToken = ctx.op;
}
myNodes.put(ctx, new VarExp(createLocation(ctx), qualifier,
createPosSymbol(opToken)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math outfix expression
* representation generated by its child rules.</p>
*
* @param ctx Math outfix expression node in ANTLR4 AST.
*/
@Override
public void exitMathOutfixExp(ResolveParser.MathOutfixExpContext ctx) {
OutfixExp.Operator operator;
if (ctx.lop.getType() == ResolveLexer.LT) {
operator = OutfixExp.Operator.ANGLE;
}
else if (ctx.lop.getType() == ResolveLexer.LL) {
operator = OutfixExp.Operator.DBL_ANGLE;
}
else if (ctx.lop.getType() == ResolveLexer.BAR) {
operator = OutfixExp.Operator.BAR;
}
else {
operator = OutfixExp.Operator.DBL_BAR;
}
// math expression
Exp mathExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new OutfixExp(createLocation(ctx), operator, mathExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math set builder expression
* representation generated by its child rules.</p>
*
* @param ctx Math set builder expression node in ANTLR4 AST.
*/
@Override
public void exitMathSetBuilderExp(ResolveParser.MathSetBuilderExpContext ctx) {
MathVarDec varDec =
(MathVarDec) myNodes.removeFrom(ctx.mathVariableDecl());
Exp whereExp = (Exp) myNodes.removeFrom(ctx.whereClause());
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new SetExp(createLocation(ctx), varDec, whereExp,
bodyExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math set collection expression
* representation generated by its child rules.</p>
*
* @param ctx Math set collection expression node in ANTLR4 AST.
*/
@Override
public void exitMathSetCollectionExp(
ResolveParser.MathSetCollectionExpContext ctx) {
List<ResolveParser.MathExpContext> mathExps = ctx.mathExp();
Set<MathExp> mathExpsSet = new HashSet<>();
for (ResolveParser.MathExpContext context : mathExps) {
mathExpsSet.add((MathExp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new SetCollectionExp(createLocation(ctx), mathExpsSet));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math tuple expression representation
* generated by its child rules.</p>
*
* @param ctx Math tuple expression node in ANTLR4 AST.
*/
@Override
public void exitMathTupleExp(ResolveParser.MathTupleExpContext ctx) {
// Add the two expressions inside the tuple to a list
List<Exp> tupleExps = new ArrayList<>();
tupleExps.add((Exp) myNodes.removeFrom(ctx.mathExp(0)));
tupleExps.add((Exp) myNodes.removeFrom(ctx.mathExp(1)));
myNodes.put(ctx, new TupleExp(createLocation(ctx), tupleExps));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math lambda expression representation
* generated by its child rules.</p>
*
* @param ctx Math lambda expression node in ANTLR4 AST.
*/
@Override
public void exitMathLambdaExp(ResolveParser.MathLambdaExpContext ctx) {
// Construct the various variables inside the lambda expression
List<ResolveParser.MathVariableDeclGroupContext> variableDeclGroups = ctx.mathVariableDeclGroup();
List<MathVarDec> varDecls = new ArrayList<>();
for (ResolveParser.MathVariableDeclGroupContext context : variableDeclGroups) {
// Get each math variable declaration
varDecls.add((MathVarDec) myNodes.removeFrom(context));
}
// body expression
Exp bodyExp = (Exp) myNodes.removeFrom(ctx.mathExp());
myNodes.put(ctx, new LambdaExp(createLocation(ctx), varDecls, bodyExp));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the math Cartesian product expression
* representation generated by its child rules.</p>
*
* @param ctx Math Cartesian product expression node in ANTLR4 AST.
*/
@Override
public void exitMathTaggedCartProdTypeExp(
ResolveParser.MathTaggedCartProdTypeExpContext ctx) {
// Construct the various variables inside the cartesian product
List<ResolveParser.MathVariableDeclGroupContext> variableDeclGroups = ctx.mathVariableDeclGroup();
Map<PosSymbol, ArbitraryExpTy> tagsToFieldsMap = new HashMap<>();
for (ResolveParser.MathVariableDeclGroupContext context : variableDeclGroups) {
// Get each math variable declaration
MathVarDec varDec = (MathVarDec) myNodes.removeFrom(context);
tagsToFieldsMap.put(varDec.getName(), (ArbitraryExpTy) varDec.getTy());
}
myNodes.put(ctx, new CrossTypeExp(createLocation(ctx), tagsToFieldsMap));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the nested math expression representation
* generated by its child rules.</p>
*
* @param ctx Nested math expression node in ANTLR4 AST.
*/
@Override
public void exitMathNestedExp(ResolveParser.MathNestedExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.mathExp()));
}
// -----------------------------------------------------------
// Programming expressions
// -----------------------------------------------------------
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program primary expression representation
* generated by its child rules.</p>
*
* @param ctx Program primary expression node in ANTLR4 AST.
*/
@Override
public void exitProgPrimaryExp(ResolveParser.ProgPrimaryExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program application expression.
* This is really a syntactic sugar for the different function
* calls, so all we are returning are program function expressions.</p>
*
* @param ctx Program application expression node in ANTLR4 AST.
*/
@Override
public void exitProgApplicationExp(
ResolveParser.ProgApplicationExpContext ctx) {
Location functionNameLoc = createLocation(ctx.op);
PosSymbol functionName;
switch (ctx.op.getType()) {
case ResolveLexer.AND:
functionName = new PosSymbol(functionNameLoc, "And");
break;
case ResolveLexer.OR:
functionName = new PosSymbol(functionNameLoc, "Or");
break;
case ResolveLexer.EQL:
functionName = new PosSymbol(functionNameLoc, "Are_Equal");
break;
case ResolveLexer.NOT_EQL:
functionName = new PosSymbol(functionNameLoc, "Are_Not_Equal");
break;
case ResolveLexer.LT:
functionName = new PosSymbol(functionNameLoc, "Less");
break;
case ResolveLexer.LT_EQL:
functionName = new PosSymbol(functionNameLoc, "Less_Or_Equal");
break;
case ResolveLexer.GT:
functionName = new PosSymbol(functionNameLoc, "Greater");
break;
case ResolveLexer.GT_EQL:
functionName = new PosSymbol(functionNameLoc, "Greater_Or_Equal");
break;
case ResolveLexer.PLUS:
functionName = new PosSymbol(functionNameLoc, "Sum");
break;
case ResolveLexer.MINUS:
functionName = new PosSymbol(functionNameLoc, "Difference");
break;
case ResolveLexer.MULTIPLY:
functionName = new PosSymbol(functionNameLoc, "Product");
break;
case ResolveLexer.DIVIDE:
functionName = new PosSymbol(functionNameLoc, "Divide");
break;
case ResolveLexer.MOD:
functionName = new PosSymbol(functionNameLoc, "Mod");
break;
case ResolveLexer.REM:
functionName = new PosSymbol(functionNameLoc, "Rem");
break;
default:
functionName = new PosSymbol(functionNameLoc, "Div");
break;
}
List<ProgramExp> args = new ArrayList<>();
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp(0)));
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp(1)));
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), null, functionName, args));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program exponent expressions representation
* generated by its child rules.</p>
*
* @param ctx Program exponential expression node in ANTLR4 AST.
*/
@Override
public void exitProgExponentialExp(
ResolveParser.ProgExponentialExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program exponential expressions.
* This is really a syntactic sugar for the different function
* calls, so all we are returning are program function expressions.</p>
*
* @param ctx Program exponential node in ANTLR4 AST.
*/
@Override
public void exitProgExponential(ResolveParser.ProgExponentialContext ctx) {
PosSymbol functionName = new PosSymbol(createLocation(ctx.EXP().getSymbol()), "Power");
List<ProgramExp> args = new ArrayList<>();
args.add((ProgramExp) myNodes.removeFrom(ctx.progUnary()));
args.add((ProgramExp) myNodes.removeFrom(ctx.progExponential()));
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), null, functionName, args));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program unary expressions.
* This is really a syntactic sugar for the different function
* calls, so all we are returning are program function expressions.</p>
*
* @param ctx Program unary expression node in ANTLR4 AST.
*/
@Override
public void exitProgUnaryExp(ResolveParser.ProgUnaryExpContext ctx) {
Location functionNameLoc = createLocation(ctx.op);
PosSymbol functionName;
List<ProgramExp> args = new ArrayList<>();
switch (ctx.op.getType()) {
case ResolveLexer.NOT:
functionName = new PosSymbol(functionNameLoc, "Not");
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp()));
break;
default:
functionName = new PosSymbol(functionNameLoc, "Negate");
args.add((ProgramExp) myNodes.removeFrom(ctx.progExp()));
break;
}
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), null, functionName, args));
}
/**
* {@inheritDoc}
* <p>
* <p>This is really a syntactic sugar for the different function calls
* in {@code Static_Array_Template}, so we are returning a function call
* generated by its child rules.</p>
*
* @param ctx Program array expression node in ANTLR4 AST.
*/
@Override
public void exitProgArrayExp(ResolveParser.ProgArrayExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program function expression representation
* generated by its child rules.</p>
*
* @param ctx Program function expression node in ANTLR4 AST.
*/
@Override
public void exitProgFunctionExp(ResolveParser.ProgFunctionExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program named variable expression representation
* generated by its child rules.</p>
*
* @param ctx Program named variable expression node in ANTLR4 AST.
*/
@Override
public void exitProgNamedVariableExp(
ResolveParser.ProgNamedVariableExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program literal expression representation
* generated by its child rules.</p>
*
* @param ctx Program literal expression node in ANTLR4 AST.
*/
@Override
public void exitProgLiteralExp(ResolveParser.ProgLiteralExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores a program nested expression representation
* generated by its child rules.</p>
*
* @param ctx Program nested expression node in ANTLR4 AST.
*/
@Override
public void exitProgNestedExp(ResolveParser.ProgNestedExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>Checks to see if this expression is part of a module argument.
* If yes, then this is an error, because we can't convert it to the
* appropriate function call.</p>
*
* @param ctx Program variable array expression node in ANTLR4 AST.
*/
@Override
public void enterProgVariableArrayExp(
ResolveParser.ProgVariableArrayExpContext ctx) {
if (myIsProcessingModuleArgument) {
myErrorHandler
.error(createLocation(ctx),
"Variable array expressions cannot be passed as module arguments.");
}
}
/**
* {@inheritDoc}
* <p>
* <p>This is really a syntactic sugar for the different function calls
* in {@code Static_Array_Template}, so we are generating the new
* function calls and storing it.</p>
*
* @param ctx Program variable array expression node in ANTLR4 AST.
*/
@Override
public void exitProgVariableArrayExp(
ResolveParser.ProgVariableArrayExpContext ctx) {
// TODO: Migrate VariableArrayExp conversions logic from PreProcessor.
super.enterProgVariableArrayExp(ctx);
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the program variable expressions
* representation generated by its child rules.</p>
*
* @param ctx Program variable expression node in ANTLR4 AST.
*/
@Override
public void exitProgVariableExp(ResolveParser.ProgVariableExpContext ctx) {
myNodes.put(ctx, myNodes.removeFrom(ctx.getChild(0)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method either stores the program expressions representation
* generated by its child rules or generates a new program variable
* dotted expression.</p>
*
* @param ctx Program dot expression node in ANTLR4 AST.
*/
@Override
public void exitProgDotExp(ResolveParser.ProgDotExpContext ctx) {
ResolveConceptualElement newElement;
// Create a dot expression if needed
List<ResolveParser.ProgNamedExpContext> progNamedExp = ctx.progNamedExp();
if (progNamedExp.size() > 0) {
// dotted expressions
List<ProgramVariableExp> dotExps = new ArrayList<>();
for (ResolveParser.ProgNamedExpContext context : progNamedExp) {
dotExps.add((ProgramVariableExp) myNodes.removeFrom(context));
}
newElement = new ProgramVariableDotExp(createLocation(ctx), dotExps);
}
else {
newElement = myNodes.removeFrom(ctx.progNamedExp(0));
}
myNodes.put(ctx, newElement);
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program function expression representation.</p>
*
* @param ctx Program function expression node in ANTLR4 AST.
*/
@Override
public void exitProgParamExp(ResolveParser.ProgParamExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
// function arguments
List<ResolveParser.ProgExpContext> programExps = ctx.progExp();
List<ProgramExp> functionArgs = new ArrayList<>();
for (ResolveParser.ProgExpContext context : programExps) {
functionArgs.add((ProgramExp) myNodes.removeFrom(context));
}
myNodes.put(ctx, new ProgramFunctionExp(createLocation(ctx), qualifier, createPosSymbol(ctx.name), functionArgs));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program variable expression representation.</p>
*
* @param ctx Program variable expression node in ANTLR4 AST.
*/
@Override
public void exitProgNamedExp(ResolveParser.ProgNamedExpContext ctx) {
PosSymbol qualifier = null;
if (ctx.qualifier != null) {
qualifier = createPosSymbol(ctx.qualifier);
}
myNodes.put(ctx, new ProgramVariableNameExp(createLocation(ctx),
qualifier, createPosSymbol(ctx.name)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program integer literal.</p>
*
* @param ctx Program integer literal node in ANTLR4 AST.
*/
@Override
public void exitProgIntegerExp(ResolveParser.ProgIntegerExpContext ctx) {
myNodes.put(ctx, new ProgramIntegerExp(createLocation(ctx
.INTEGER_LITERAL().getSymbol()), Integer.valueOf(ctx
.INTEGER_LITERAL().getText())));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program character literal.</p>
*
* @param ctx Program character literal node in ANTLR4 AST.
*/
@Override
public void exitProgCharacterExp(ResolveParser.ProgCharacterExpContext ctx) {
myNodes.put(ctx, new ProgramCharExp(createLocation(ctx
.CHARACTER_LITERAL().getSymbol()), ctx.CHARACTER_LITERAL()
.getText().charAt(1)));
}
/**
* {@inheritDoc}
* <p>
* <p>This method stores the program string literal.</p>
*
* @param ctx Program string literal node in ANTLR4 AST.
*/
@Override
public void exitProgStringExp(ResolveParser.ProgStringExpContext ctx) {
myNodes
.put(ctx, new ProgramStringExp(createLocation(ctx
.STRING_LITERAL().getSymbol()), ctx.STRING_LITERAL()
.getText()));
}
// ===========================================================
// Public Methods
// ===========================================================
/**
* <p>Return the complete module representation build by
* this class.</p>
*
* @return A {link ModuleDec} (intermediate representation) object.
*/
public ModuleDec getModule() {
return myFinalModule;
}
// ===========================================================
// Private Methods
// ===========================================================
/**
* <p>Create a location for the current parser rule
* we are visiting.</p>
*
* @param ctx The visiting ANTLR4 parser rule.
*
* @return A {@link Location} for the rule.
*/
private Location createLocation(ParserRuleContext ctx) {
return createLocation(ctx.getStart());
}
/**
* <p>Create a location for the current parser token
* we are visiting.</p>
*
* @param t The visiting ANTLR4 parser token.
*
* @return A {@link Location} for the rule.
*/
private Location createLocation(Token t) {
return new Location(new Location(myFile, t.getLine(), t
.getCharPositionInLine(), ""));
}
/**
* <p>Create a symbol representation for the current
* parser token we are visiting.</p>
*
* @param t The visiting ANTLR4 parser token.
*
* @return A {@link PosSymbol} for the rule.
*/
private PosSymbol createPosSymbol(Token t) {
return new PosSymbol(createLocation(t), t.getText());
}
// ===========================================================
// Temporary Constructs
// ===========================================================
/**
* <p>This holds items that are needed to build a
* {@link MathDefinitionDec}</p>
*/
private class DefinitionMembers {
// ===========================================================
// Member Fields
// ===========================================================
/** <p>Definition name</p> */
PosSymbol name;
/** <p>Definition parameters</p> */
List<MathVarDec> params;
/** <p>Definition return type</p> */
Ty rawType;
// ===========================================================
// Constructors
// ===========================================================
/**
* <p>This constructs a temporary structure to store all the relevant
* items to build a {@link MathDefinitionDec}.</p>
*
* @param name Definition name.
* @param params Definition parameters.
* @param rawType Definition return type.
*/
DefinitionMembers(PosSymbol name, List<MathVarDec> params, Ty rawType) {
this.name = name;
this.params = params;
this.rawType = rawType;
}
}
} | Added a helper class to deal with array conversions
| src/main/java/edu/clemson/cs/rsrg/parsing/TreeBuildingListener.java | Added a helper class to deal with array conversions | <ide><path>rc/main/java/edu/clemson/cs/rsrg/parsing/TreeBuildingListener.java
<ide> /** <p>Boolean that indicates that we are processing a module argument.</p> */
<ide> private boolean myIsProcessingModuleArgument;
<ide>
<add> /** <p>Stack of current syntactic sugar conversions</p> */
<add> private Stack<ProgramExpAdapter> myCurrentProgExpAdapterStack;
<add>
<ide> /** <p>The complete module representation.</p> */
<ide> private ModuleDec myFinalModule;
<ide>
<ide> myNodes = new ParseTreeProperty<>();
<ide> myDefinitionMemberList = null;
<ide> myIsProcessingModuleArgument = false;
<add> myCurrentProgExpAdapterStack = new Stack<>();
<ide> }
<ide>
<ide> // ===========================================================
<ide>
<ide> }
<ide>
<add> /**
<add> * <p>This holds items related to syntactic sugar conversions for
<add> * {@link ProgramExp}s.</p>
<add> */
<add> private class ProgramExpAdapter {
<add>
<add> // ===========================================================
<add> // Member Fields
<add> // ===========================================================
<add>
<add> /** <p>The parent context that instantiated this object</p> */
<add> ParserRuleContext parentContext;
<add>
<add> /**
<add> * <p>A map from the program expression context to a list
<add> * containing the new RESOLVE AST nodes.</p>
<add> */
<add> Map<ResolveParser.ProgExpContext, List<ResolveConceptualElement>> progExpAdapterMap;
<add>
<add> // ===========================================================
<add> // Constructors
<add> // ===========================================================
<add>
<add> /**
<add> * <p>This constructs a temporary structure to store all the relevant
<add> * items to provide syntactic sugar conversions for {@link ProgramExp}s.</p>
<add> *
<add> * @param parentContext The parent context that instantiated this object.
<add> */
<add> ProgramExpAdapter(ParserRuleContext parentContext) {
<add> this.parentContext = parentContext;
<add> progExpAdapterMap = new HashMap<>();
<add> }
<add> }
<add>
<ide> } |
|
JavaScript | mit | 1b74e85248f3f06ced6df1ef3e9a2ee35f23d464 | 0 | ehel/prettyalert,ehel/prettyalert | function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
function insertHtml(title, content, type) {
var attention = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path id="svgico" fill="none" stroke="#FBB03B" stroke-width="8" stroke-linecap="round" stroke-miterlimit="10" d="M50,83v2 M50,14v54"/></svg>';
var error = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path id="svgico" fill="#FFFFFF" stroke="#C1272D" stroke-width="8" stroke-linecap="round" stroke-miterlimit="10" d="M8.8,90.7L90,9 M90,90.7 L8.8,9"/></svg>';
var succes = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path id="svgico" fill="#FFFFFF" stroke="#8CC63F" stroke-miterlimit="10" d="M46.6,64.3l33.7-40L47.4,75.4L24.7,56L46.6,64.3z" /></svg>';
var svg = '';
if (type == 'succes') {
svg = succes;
} else if (type == 'error') {
svg = error;
} else {
svg = attention;
}
var htmlStr = '<div id="overlay"><div id="modalcontainer">' + svg + '<h2>' + title + '</h2><p>' + content + '</p><a id="closeModal" href="#">OK</a></div></div>';
var fragment = create(htmlStr);
document.body.insertBefore(fragment, document.body.childNodes[0]);
}
function insertCss(){
var cssStr="<style>#overlay{visibility:hidden;opacity:0;position:absolute;left:0;top:0;width:100%;height:100%;text-align:center;z-index:1000;transition:opacity 500ms;-webkit-transition:opacity 500ms;-moz-transition:opacity 500ms;-o-transition:opacity 500ms;background-color:rgba(192,192,192,.7);font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif}#overlay div{width:400px;height:250px;margin:100px auto;background-color:#fff;border-radius:3%;padding:15px;text-align:center;transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-webkit-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-moz-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-o-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5)}#closeModal{max-width:70px;opacity:0;color:#fff;background-color:#0080FF;text-decoration:none;width:60px;padding:10px 0;margin:0 auto;display:block;border-radius:10%;-webkit-transition:opacity 400ms;-moz-transition:opacity 400ms;-ms-transition:opacity 400ms;-o-transition:opacity 400ms;transition:opacity 400ms}#modalcontainer h2{font-size:30px;font-weight:600;color:#575757;margin:0}#modalcontainer p{color:#797979;font-size:16px;font-weight:300}svg{height:150px;margin:0}svg path{stroke-dashoffset:170;stroke-dasharray:170;transition:stroke-dashoffset 600ms linear;-webkit-transition:stroke-dashoffset 600ms linear;-moz-transition:stroke-dashoffset 600ms linear;-o-transition:stroke-dashoffset 600ms linear;}</style>";
var fragment = create(cssStr);
document.body.insertBefore(fragment, document.body.childNodes[0]);
}
//TO DO
function animateSvg(elem ,dir , type) {
var path = document.getElementById(elem);
var length = path.getTotalLength();
if (type=='succes') { path.style.strokeDashoffset = (dir)?0:170;};
if (type=='error') { path.style.transform='rotate(720deg)';};
if (type=='attention') {};
}
function openModal(type){
el = document.getElementById("overlay");
mod = document.getElementById("modalcontainer");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
el.style.opacity = 1;
mod.style.width = '450px';
mod.style.height = '300px';
setTimeout('document.getElementById("closeModal").style.opacity = 1; ', 500);
setTimeout(function() {animateSvg('svgico', true,type) ;} , 400);
// animateSvg('svgico' , true);
}
function closeModal(type){
var el = document.getElementById("overlay");
var mod = document.getElementById("modalcontainer");
mod.style.width = '400px';
mod.style.height = '250px';
el.style.opacity = 0;
document.getElementById("closeModal").style.opacity = 0;
setTimeout('el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";', 500);
animateSvg('svgico' , false , type);
}
function prettytalert(title, content, type){
insertHtml(title, content, type);
insertCss();
openModal(type);
window.onload = function()
{
document.getElementById('closeModal').onclick = function () {
closeModal(type);
}};
} | prettyalert.js | function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
function insertHtml(title, content, type) {
var attention = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path id="svgico" fill="none" stroke="#FBB03B" stroke-width="8" stroke-linecap="round" stroke-miterlimit="10" d="M50,83v2 M50,14v54"/></svg>';
var error = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path id="svgico" fill="#FFFFFF" stroke="#C1272D" stroke-width="8" stroke-linecap="round" stroke-miterlimit="10" d="M8.8,90.7L90,9 M90,90.7 L8.8,9"/></svg>';
var succes = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path id="svgico" fill="#FFFFFF" stroke="#8CC63F" stroke-miterlimit="10" d="M46.6,64.3l33.7-40L47.4,75.4L24.7,56L46.6,64.3z" /></svg>';
var svg = '';
if (type == 'succes') {
svg = succes;
} else if (type == 'error') {
svg = error;
} else {
svg = attention;
}
var htmlStr = '<div id="overlay"><div id="modalcontainer">' + svg + '<h2>' + title + '</h2><p>' + content + '</p><a id="closeModal" href="#">OK</a></div></div>';
var fragment = create(htmlStr);
document.body.insertBefore(fragment, document.body.childNodes[0]);
}
function insertCss(){
var cssStr="<style>#overlay{visibility:hidden;opacity:0;position:absolute;left:0;top:0;width:100%;height:100%;text-align:center;z-index:1000;transition:opacity 500ms;-webkit-transition:opacity 500ms;-moz-transition:opacity 500ms;-o-transition:opacity 500ms;background-color:rgba(192,192,192,.7);font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif}#overlay div{width:400px;height:250px;margin:100px auto;background-color:#fff;border-radius:3%;padding:15px;text-align:center;transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-webkit-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-moz-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-o-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5)}#closeModal{max-width:70px;opacity:0;color:#fff;background-color:#0080FF;text-decoration:none;width:60px;padding:10px 0;margin:0 auto;display:block;border-radius:10%;-webkit-transition:opacity 400ms;-moz-transition:opacity 400ms;-ms-transition:opacity 400ms;-o-transition:opacity 400ms;transition:opacity 400ms}#modalcontainer h2{font-size:30px;font-weight:600;color:#575757;margin:0}#modalcontainer p{color:#797979;font-size:16px;font-weight:300}svg{height:150px;margin:0}svg path{stroke-dashoffset:170;stroke-dasharray:170;transition:stroke-dashoffset 600ms linear;-webkit-transition:stroke-dashoffset 600ms linear;-moz-transition:stroke-dashoffset 600ms linear;-o-transition:stroke-dashoffset 600ms linear;}</style>";
var fragment = create(cssStr);
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);
}
function animateSvg(elem ,dir , type) {
var path = document.getElementById(elem);
var length = path.getTotalLength();
if (type=='succes') { path.style.strokeDashoffset = (dir)?0:170; };
if (type=='error') { path.style.transform='rotate(720deg)';};
}
function openModal(type){
el = document.getElementById("overlay");
mod = document.getElementById("modalcontainer");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
el.style.opacity = 1;
mod.style.width = '450px';
mod.style.height = '300px';
setTimeout('document.getElementById("closeModal").style.opacity = 1; ', 500);
setTimeout(function() {animateSvg('svgico', true,type) ;} , 400);
// animateSvg('svgico' , true);
}
function closeModal(type){
var el = document.getElementById("overlay");
var mod = document.getElementById("modalcontainer");
mod.style.width = '400px';
mod.style.height = '250px';
el.style.opacity = 0;
document.getElementById("closeModal").style.opacity = 0;
setTimeout('el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";', 500);
animateSvg('svgico' , false , type);
}
function prettytalert(title, content, type){
insertHtml(title, content, type);
insertCss();
openModal(type);
window.onload = function()
{
document.getElementById('closeModal').onclick = function () {
closeModal(type);
}};
} | Fix js
| prettyalert.js | Fix js | <ide><path>rettyalert.js
<ide>
<ide> var cssStr="<style>#overlay{visibility:hidden;opacity:0;position:absolute;left:0;top:0;width:100%;height:100%;text-align:center;z-index:1000;transition:opacity 500ms;-webkit-transition:opacity 500ms;-moz-transition:opacity 500ms;-o-transition:opacity 500ms;background-color:rgba(192,192,192,.7);font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif}#overlay div{width:400px;height:250px;margin:100px auto;background-color:#fff;border-radius:3%;padding:15px;text-align:center;transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-webkit-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-moz-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5);-o-transition:height 400ms cubic-bezier(.1,-1.5,.1,2.5),width 400ms cubic-bezier(.1,-1.5,.1,2.5)}#closeModal{max-width:70px;opacity:0;color:#fff;background-color:#0080FF;text-decoration:none;width:60px;padding:10px 0;margin:0 auto;display:block;border-radius:10%;-webkit-transition:opacity 400ms;-moz-transition:opacity 400ms;-ms-transition:opacity 400ms;-o-transition:opacity 400ms;transition:opacity 400ms}#modalcontainer h2{font-size:30px;font-weight:600;color:#575757;margin:0}#modalcontainer p{color:#797979;font-size:16px;font-weight:300}svg{height:150px;margin:0}svg path{stroke-dashoffset:170;stroke-dasharray:170;transition:stroke-dashoffset 600ms linear;-webkit-transition:stroke-dashoffset 600ms linear;-moz-transition:stroke-dashoffset 600ms linear;-o-transition:stroke-dashoffset 600ms linear;}</style>";
<ide> var fragment = create(cssStr);
<del>// You can use native DOM methods to insert the fragment:
<add>
<ide> document.body.insertBefore(fragment, document.body.childNodes[0]);
<ide> }
<add>
<add>//TO DO
<ide> function animateSvg(elem ,dir , type) {
<ide> var path = document.getElementById(elem);
<ide> var length = path.getTotalLength();
<del> if (type=='succes') { path.style.strokeDashoffset = (dir)?0:170; };
<add> if (type=='succes') { path.style.strokeDashoffset = (dir)?0:170;};
<ide> if (type=='error') { path.style.transform='rotate(720deg)';};
<add> if (type=='attention') {};
<ide> }
<ide>
<ide> function openModal(type){ |
|
Java | mit | error: pathspec 'java/RotateImage.java' did not match any file(s) known to git
| 0cce301427371b00ae6bf269731610066f9450f4 | 1 | dantin/leetcode-solutions,dantin/leetcode-solutions,dantin/leetcode-solutions | public class RotateImage {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
matrix[n - 1 - j][n - 1 - i] = tmp;
}
}
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < n; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - i][j];
matrix[n - 1 - i][j] = tmp;
}
}
}
public void rotate1(int[][] matrix) {
int row = matrix.length;
for (int i = 0; i < row / 2; i++) {
for (int j = i; j < row - 1 - i; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[row - 1 - j][i];
matrix[row - 1 - j][i] = matrix[row - 1 - i][row - 1 - j];
matrix[row - 1 - i][row - 1 - j] = matrix[j][row - 1 - i];
matrix[j][row - 1 - i] = tmp;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
print(matrix);
RotateImage solution = new RotateImage();
solution.rotate(matrix);
print(matrix);
}
private static void print(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.printf("%d ", matrix[i][j]);
}
System.out.println();
}
}
} | java/RotateImage.java | solution of rotate image
| java/RotateImage.java | solution of rotate image | <ide><path>ava/RotateImage.java
<add>public class RotateImage {
<add>
<add> public void rotate(int[][] matrix) {
<add> int n = matrix.length;
<add> for (int i = 0; i < n; i++) {
<add> for (int j = 0; j < n - i; j++) {
<add> int tmp = matrix[i][j];
<add> matrix[i][j] = matrix[n - 1 - j][n - 1 - i];
<add> matrix[n - 1 - j][n - 1 - i] = tmp;
<add> }
<add> }
<add> for (int i = 0; i < n / 2; i++) {
<add> for (int j = 0; j < n; j++) {
<add> int tmp = matrix[i][j];
<add> matrix[i][j] = matrix[n - 1 - i][j];
<add> matrix[n - 1 - i][j] = tmp;
<add> }
<add> }
<add> }
<add>
<add> public void rotate1(int[][] matrix) {
<add> int row = matrix.length;
<add> for (int i = 0; i < row / 2; i++) {
<add> for (int j = i; j < row - 1 - i; j++) {
<add> int tmp = matrix[i][j];
<add> matrix[i][j] = matrix[row - 1 - j][i];
<add> matrix[row - 1 - j][i] = matrix[row - 1 - i][row - 1 - j];
<add> matrix[row - 1 - i][row - 1 - j] = matrix[j][row - 1 - i];
<add> matrix[j][row - 1 - i] = tmp;
<add> }
<add> }
<add> }
<add>
<add> public static void main(String[] args) {
<add> int[][] matrix = {
<add> {1, 2, 3},
<add> {4, 5, 6},
<add> {7, 8, 9}
<add> };
<add> print(matrix);
<add>
<add> RotateImage solution = new RotateImage();
<add> solution.rotate(matrix);
<add> print(matrix);
<add> }
<add>
<add> private static void print(int[][] matrix) {
<add> for (int i = 0; i < matrix.length; i++) {
<add> for (int j = 0; j < matrix[i].length; j++) {
<add> System.out.printf("%d ", matrix[i][j]);
<add> }
<add> System.out.println();
<add> }
<add>
<add> }
<add>} |
|
Java | apache-2.0 | adb5bacba3fb370e84c6a8317ac01b7efdb011da | 0 | apache/commons-jcs,mohanaraosv/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs,apache/commons-jcs,mohanaraosv/commons-jcs | package org.apache.commons.jcs.auxiliary.remote.server.behavior;
import java.rmi.Remote;
import org.apache.commons.jcs.auxiliary.remote.behavior.IRemoteCacheObserver;
import org.apache.commons.jcs.engine.behavior.ICacheServiceAdmin;
import org.apache.commons.jcs.engine.behavior.ICacheServiceNonLocal;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Interface for managing Remote objects
*
* @author Thomas Vandahl
*
*/
public interface IRemoteCacheServer<K, V>
extends ICacheServiceNonLocal<K, V>, IRemoteCacheObserver, ICacheServiceAdmin, Remote
{
// empty
}
| commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/remote/server/behavior/IRemoteCacheServer.java | package org.apache.commons.jcs.auxiliary.remote.server.behavior;
import java.rmi.Remote;
import org.apache.commons.jcs.engine.behavior.ICacheObserver;
import org.apache.commons.jcs.engine.behavior.ICacheServiceAdmin;
import org.apache.commons.jcs.engine.behavior.ICacheServiceNonLocal;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/**
* Interface for managing Remote objects
*
* @author Thomas Vandahl
*
*/
public interface IRemoteCacheServer<K, V>
extends ICacheServiceNonLocal<K, V>, ICacheObserver, ICacheServiceAdmin, Remote
{
// empty
}
| Cut&Paste error
git-svn-id: fd52ae19693b7be904def34076a5ebbd6e132215@1650019 13f79535-47bb-0310-9956-ffa450edef68
| commons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/remote/server/behavior/IRemoteCacheServer.java | Cut&Paste error | <ide><path>ommons-jcs-core/src/main/java/org/apache/commons/jcs/auxiliary/remote/server/behavior/IRemoteCacheServer.java
<ide> package org.apache.commons.jcs.auxiliary.remote.server.behavior;
<ide>
<ide> import java.rmi.Remote;
<del>import org.apache.commons.jcs.engine.behavior.ICacheObserver;
<add>
<add>import org.apache.commons.jcs.auxiliary.remote.behavior.IRemoteCacheObserver;
<ide> import org.apache.commons.jcs.engine.behavior.ICacheServiceAdmin;
<ide> import org.apache.commons.jcs.engine.behavior.ICacheServiceNonLocal;
<ide>
<ide> *
<ide> */
<ide> public interface IRemoteCacheServer<K, V>
<del> extends ICacheServiceNonLocal<K, V>, ICacheObserver, ICacheServiceAdmin, Remote
<add> extends ICacheServiceNonLocal<K, V>, IRemoteCacheObserver, ICacheServiceAdmin, Remote
<ide> {
<ide> // empty
<ide> } |
|
Java | apache-2.0 | b398ce8432a9fcabf786c533fc59ca7eebbd1ca2 | 0 | groybal/uPortal,Mines-Albi/esup-uportal,pspaude/uPortal,kole9273/uPortal,timlevett/uPortal,phillips1021/uPortal,kole9273/uPortal,apetro/uPortal,groybal/uPortal,groybal/uPortal,ASU-Capstone/uPortal,cousquer/uPortal,MichaelVose2/uPortal,phillips1021/uPortal,andrewstuart/uPortal,vbonamy/esup-uportal,phillips1021/uPortal,jhelmer-unicon/uPortal,doodelicious/uPortal,ChristianMurphy/uPortal,GIP-RECIA/esco-portail,chasegawa/uPortal,joansmith/uPortal,vbonamy/esup-uportal,stalele/uPortal,EdiaEducationTechnology/uPortal,Mines-Albi/esup-uportal,GIP-RECIA/esup-uportal,jameswennmacher/uPortal,doodelicious/uPortal,jameswennmacher/uPortal,jl1955/uPortal5,ASU-Capstone/uPortal,timlevett/uPortal,timlevett/uPortal,Jasig/uPortal,Jasig/SSP-Platform,stalele/uPortal,Jasig/SSP-Platform,GIP-RECIA/esup-uportal,jhelmer-unicon/uPortal,pspaude/uPortal,bjagg/uPortal,ChristianMurphy/uPortal,apetro/uPortal,chasegawa/uPortal,drewwills/uPortal,doodelicious/uPortal,vbonamy/esup-uportal,doodelicious/uPortal,EsupPortail/esup-uportal,drewwills/uPortal,Jasig/uPortal,MichaelVose2/uPortal,andrewstuart/uPortal,joansmith/uPortal,jonathanmtran/uPortal,jonathanmtran/uPortal,bjagg/uPortal,kole9273/uPortal,jhelmer-unicon/uPortal,GIP-RECIA/esup-uportal,ASU-Capstone/uPortal-Forked,vertein/uPortal,ASU-Capstone/uPortal,joansmith/uPortal,MichaelVose2/uPortal,groybal/uPortal,joansmith/uPortal,kole9273/uPortal,stalele/uPortal,jhelmer-unicon/uPortal,apetro/uPortal,stalele/uPortal,Jasig/SSP-Platform,Jasig/SSP-Platform,vertein/uPortal,cousquer/uPortal,jhelmer-unicon/uPortal,ASU-Capstone/uPortal,apetro/uPortal,chasegawa/uPortal,apetro/uPortal,andrewstuart/uPortal,vertein/uPortal,MichaelVose2/uPortal,mgillian/uPortal,vbonamy/esup-uportal,MichaelVose2/uPortal,Mines-Albi/esup-uportal,Mines-Albi/esup-uportal,GIP-RECIA/esco-portail,GIP-RECIA/esup-uportal,kole9273/uPortal,pspaude/uPortal,jameswennmacher/uPortal,GIP-RECIA/esup-uportal,jl1955/uPortal5,ASU-Capstone/uPortal-Forked,GIP-RECIA/esco-portail,Mines-Albi/esup-uportal,jl1955/uPortal5,EsupPortail/esup-uportal,doodelicious/uPortal,cousquer/uPortal,andrewstuart/uPortal,jonathanmtran/uPortal,bjagg/uPortal,groybal/uPortal,ASU-Capstone/uPortal-Forked,Jasig/uPortal-start,jl1955/uPortal5,jameswennmacher/uPortal,jameswennmacher/uPortal,joansmith/uPortal,stalele/uPortal,EdiaEducationTechnology/uPortal,drewwills/uPortal,mgillian/uPortal,EsupPortail/esup-uportal,EdiaEducationTechnology/uPortal,andrewstuart/uPortal,Jasig/uPortal-start,ASU-Capstone/uPortal-Forked,EsupPortail/esup-uportal,ChristianMurphy/uPortal,Jasig/uPortal,jl1955/uPortal5,mgillian/uPortal,phillips1021/uPortal,vbonamy/esup-uportal,chasegawa/uPortal,chasegawa/uPortal,drewwills/uPortal,pspaude/uPortal,timlevett/uPortal,EdiaEducationTechnology/uPortal,ASU-Capstone/uPortal-Forked,phillips1021/uPortal,ASU-Capstone/uPortal,EsupPortail/esup-uportal,vertein/uPortal,Jasig/SSP-Platform | /**
* Copyright 2001, 2002 The JA-SIG Collaborative. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the JA-SIG Collaborative
* (http://www.jasig.org/)."
*
* THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.jasig.portal;
import org.jasig.portal.utils.DocumentFactory;
import org.jasig.portal.utils.CounterStoreFactory;
import org.jasig.portal.services.LogService;
import org.jasig.portal.security.IPerson;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.jasig.portal.services.GroupService;
import org.jasig.portal.groups.IEntityGroup;
import org.jasig.portal.groups.IEntity;
import org.jasig.portal.groups.IGroupMember;
import org.jasig.portal.groups.GroupsException;
/**
* Reference implementation of IChannelRegistryStoreOld. This class is currently
* acting as a wrapper for the real IChannelRegistryStore and will be eventually
* removed.
* @author John Laker, [email protected]
* @version $Revision$
* @deprecated Use {@link RDBMChannelRegistryStore} instead
*/
public class RDBMChannelRegistryStoreOld implements IChannelRegistryStoreOld {
private static final int DEBUG = 0;
private static final Object channelLock = new Object();
private static final HashMap channelCache = new HashMap();
protected static IChannelRegistryStore crs = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl();
public RDBMChannelRegistryStoreOld() throws Exception {
if (RDBMServices.supportsOuterJoins) {
if (RDBMServices.joinQuery instanceof RDBMServices.JdbcDb) {
RDBMServices.joinQuery.addQuery("channel",
"{oj UP_CHANNEL UC LEFT OUTER JOIN UP_CHANNEL_PARAM UCP ON UC.CHAN_ID = UCP.CHAN_ID} WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.PostgreSQLDb) {
RDBMServices.joinQuery.addQuery("channel",
"UP_CHANNEL UC LEFT OUTER JOIN UP_CHANNEL_PARAM UCP ON UC.CHAN_ID = UCP.CHAN_ID WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.OracleDb) {
RDBMServices.joinQuery.addQuery("channel",
"UP_CHANNEL UC, UP_CHANNEL_PARAM UCP WHERE UC.CHAN_ID = UCP.CHAN_ID(+) AND");
} else {
throw new Exception("Unknown database driver");
}
}
}
/**
* Returns an XML document which describes the channel registry.
* Right now this is being stored as a string in a field but could be also implemented to get from multiple tables.
* @return a string of XML
* @throws java.lang.Exception
*/
public Document getChannelRegistryXML () throws Exception {
Document doc = DocumentFactory.getNewDocument();
Element registry = doc.createElement("registry");
doc.appendChild(registry);
IEntityGroup channelCategoriesGroup = GroupService.getChannelCategoriesGroup();
processGroupsRecursively(channelCategoriesGroup, registry);
System.out.println(org.jasig.portal.utils.XML.serializeNode(doc));
return doc;
}
private void processGroupsRecursively(IEntityGroup group, Element parentGroup) throws Exception {
Document registryDoc = parentGroup.getOwnerDocument();
Iterator iter = group.getMembers();
while (iter.hasNext()) {
IGroupMember member = (IGroupMember)iter.next();
if (member.isGroup()) {
IEntityGroup memberGroup = (IEntityGroup)member;
String key = memberGroup.getKey();
String name = memberGroup.getName();
String description = memberGroup.getDescription();
// Create category element and append it to its parent
Element categoryE = registryDoc.createElement("category");
categoryE.setAttribute("ID", "cat" + key);
categoryE.setAttribute("name", name);
categoryE.setAttribute("description", description);
parentGroup.appendChild(categoryE);
processGroupsRecursively(memberGroup, categoryE);
} else {
IEntity channelDefMember = (IEntity)member;
int channelPublishId = Integer.parseInt(channelDefMember.getKey());
ChannelDefinition channelDef = crs.getChannelDefinition(channelPublishId);
Element channelDefE = channelDef.getDocument(registryDoc, "chan" + channelPublishId);
channelDefE = (Element)registryDoc.importNode(channelDefE, true);
parentGroup.appendChild(channelDefE);
}
}
}
/**
* Get channel types xml.
* It will look something like this:
* <p><code>
*
*<channelTypes>
* <channelType ID="0">
* <class>org.jasig.portal.channels.CImage</class>
* <name>Image</name>
* <description>Simple channel to display an image with optional
* caption and subcaption</description>
* <cpd-uri>webpages/media/org/jasig/portal/channels/CImage/CImage.cpd</cpd-uri>
* </channelType>
* <channelType ID="1">
* <class>org.jasig.portal.channels.CWebProxy</class>
* <name>Web Proxy</name>
* <description>Incorporate a dynamic HTML or XML application</description>
* <cpd-uri>webpages/media/org/jasig/portal/channels/CWebProxy/CWebProxy.cpd</cpd-uri>
* </channelType>
*</channelTypes>
*
* </code></p>
* @return types, the channel types as a Document
* @throws java.sql.SQLException
*/
public Document getChannelTypesXML () throws Exception {
Document doc = DocumentFactory.getNewDocument();
Element root = doc.createElement("channelTypes");
doc.appendChild(root);
ChannelType[] channelTypes = crs.getChannelTypes();
for (int i = 0; i < channelTypes.length; i++) {
int channelTypeId = channelTypes[i].getChannelTypeId();
String javaClass = channelTypes[i].getJavaClass();
String name = channelTypes[i].getName();
String descr = channelTypes[i].getDescription();
String cpdUri = channelTypes[i].getCpdUri();
// <channelType>
Element channelType = doc.createElement("channelType");
channelType.setAttribute("ID", String.valueOf(channelTypeId));
Element elem = null;
// <class>
elem = doc.createElement("class");
elem.appendChild(doc.createTextNode(javaClass));
channelType.appendChild(elem);
// <name>
elem = doc.createElement("name");
elem.appendChild(doc.createTextNode(name));
channelType.appendChild(elem);
// <description>
elem = doc.createElement("description");
elem.appendChild(doc.createTextNode(descr));
channelType.appendChild(elem);
// <cpd-uri>
elem = doc.createElement("cpd-uri");
elem.appendChild(doc.createTextNode(cpdUri));
channelType.appendChild(elem);
root.appendChild(channelType);
}
return doc;
}
/** A method for adding a channel to the channel registry.
* This would be called by a publish channel.
* @param id the identifier for the channel
* @param publisherId the identifier for the user who is publishing this channel
* @param chanXML XML that describes the channel
* @param catID an array of category IDs
* @throws java.lang.Exception
*/
public void addChannel (int id, IPerson publisher, Document chanXML, String catID[]) throws Exception {
Element channel = (Element)chanXML.getFirstChild();
String chanTitle = channel.getAttribute("title");
String chanDesc = channel.getAttribute("description");
String chanClass = channel.getAttribute("class");
int chanTypeId = Integer.parseInt(channel.getAttribute("typeID"));
int chanPupblUsrId = publisher.getID();
int chanApvlId = -1;
String timeout = channel.getAttribute("timeout");
int chanTimeout = 0;
if (timeout != null && timeout.trim().length() != 0) {
chanTimeout = Integer.parseInt(timeout);
}
String chanEditable = channel.getAttribute("editable");
String chanHasHelp = channel.getAttribute("hasHelp");
String chanHasAbout = channel.getAttribute("hasAbout");
String chanName = channel.getAttribute("name");
String chanFName = channel.getAttribute("fname");
ChannelDefinition channelDef = new ChannelDefinition(id, chanTitle, chanDesc,
chanClass, chanTypeId, chanPupblUsrId, chanApvlId,
null, null, chanTimeout, chanEditable, chanHasHelp,
chanHasAbout, chanName, chanFName);
NodeList parameters = channel.getChildNodes();
if (parameters != null) {
for (int i = 0; i < parameters.getLength(); i++) {
if (parameters.item(i).getNodeName().equals("parameter")) {
Element parmElement = (Element)parameters.item(i);
NamedNodeMap nm = parmElement.getAttributes();
String paramName = null;
String paramValue = null;
String paramOverride = "NULL";
for (int j = 0; j < nm.getLength(); j++) {
Node param = nm.item(j);
String nodeName = param.getNodeName();
String nodeValue = param.getNodeValue();
if (nodeName.equals("name")) {
paramName = nodeValue;
} else if (nodeName.equals("value")) {
paramValue = nodeValue;
} else if (nodeName.equals("override") && nodeValue.equals("yes")) {
paramOverride = "'Y'";
}
}
if (paramName == null && paramValue == null) {
throw new RuntimeException("Invalid parameter node");
}
channelDef.addParameter(paramName, paramValue, paramOverride);
}
}
}
// Create array of category objects based on String array of catIDs
ChannelCategory[] categories = new ChannelCategory[catID.length];
for (int i = 0; i < catID.length; i++) {
String name = null;
String descr = null;
catID[i] = catID[i].startsWith("cat") ? catID[i].substring(3) : catID[i];
int iCatID = Integer.parseInt(catID[i]);
categories[i] = new ChannelCategory(iCatID);
}
crs.addChannelDefinition(channelDef, categories);
flushChannelEntry(id);
}
/** A method for approving a channel so that users are allowed to subscribe to it.
* This would be called by the publish channel or the administrator channel
* @param chanId Channel to approve
* @param approved Account approving the channel
* @param approveDate When should the channel appear
*/
public void approveChannel(int chanId, IPerson approver, Date approveDate) throws Exception {
crs.approveChannelDefinition(chanId, approver, approveDate);
}
/** A method for getting the next available channel ID.
* This would be called by a publish channel.
*/
public int getNextId () throws PortalException {
int nextID;
try {
nextID = CounterStoreFactory.getCounterStoreImpl().getIncrementIntegerId("UP_CHANNEL");
} catch (Exception e) {
LogService.instance().log(LogService.ERROR, e);
throw new PortalException("Unable to allocate new channel ID", e);
}
return nextID;
}
/**
* Removes a channel from the channel registry. The channel
* is not actually deleted. Rather its status as an "approved"
* channel is revoked.
* @param chanID, the ID of the channel to delete
* @exception java.sql.SQLException
*/
public void removeChannel (String chanID) throws Exception {
String channelPublishId = chanID.startsWith("chan") ? chanID.substring(4) : chanID;
crs.disapproveChannelDefinition(channelPublishId);
flushChannelEntry(Integer.parseInt(channelPublishId));
}
/**
* A method for persisting the channel registry to a file or database.
* @param registryXML an XML description of the channel registry
*/
public void setRegistryXML (String registryXML) throws Exception{
throw new Exception("not implemented yet");
}
/**
* @param chanDoc
* @return the chanDoc as an XML string
*/
private String serializeDOM (Document chanDoc) {
StringWriter stringOut = null;
try {
OutputFormat format = new OutputFormat(chanDoc); //Serialize DOM
stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(chanDoc.getDocumentElement());
} catch (java.io.IOException ioe) {
LogService.instance().log(LogService.ERROR, ioe);
}
return stringOut.toString();
}
/**
* convert true/false into Y/N for database
* @param value to check
* @result boolean
*/
protected static final boolean xmlBool (String value) {
return (value != null && value.equals("true") ? true : false);
}
/**
* Manage the Channel cache
*/
/**
* See if the channel is already in the cache
* @param channel id
*/
protected boolean channelCached(int chanId) {
return channelCache.containsKey(new Integer(chanId));
}
/**
* Remove channel entry from cache
* @param channel id
*/
public void flushChannelEntry(int chanId) {
synchronized (channelLock) {
if (channelCache.remove(new Integer(chanId)) != null) {
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): flushed channel "
+ chanId + " from cache");
}
}
}
/**
* Get a channel from the cache (it better be there)
*/
public ChannelDefinition getChannel(int chanId) {
ChannelDefinition channelDef = null;
try {
channelDef = crs.getChannelDefinition(chanId);
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
}
return channelDef;
}
/**
* Get a channel from the cache (it better be there)
*/
public Element getChannelXML(int chanId, Document doc, String idTag) {
ChannelDefinition channel = getChannel(chanId);
if (channel != null) {
return channel.getDocument(doc, idTag);
} else {
return null;
}
}
/**
* Get a channel from the cache or the store
*/
public ChannelDefinition getChannel(int chanId, boolean cacheChannel, RDBMServices.PreparedStatement pstmtChannel, RDBMServices.PreparedStatement pstmtChannelParm) throws java.sql.SQLException {
Integer chanID = new Integer(chanId);
boolean inCache = true;
ChannelDefinition channel = (ChannelDefinition)channelCache.get(chanID);
if (channel == null) {
synchronized (channelLock) {
channel = (ChannelDefinition)channelCache.get(chanID);
if (channel == null || cacheChannel && channel.refreshMe()) { // Still undefined or stale, let's get it
channel = getChannelDefinition(chanId, pstmtChannel, pstmtChannelParm);
inCache = false;
if (cacheChannel) {
channelCache.put(chanID, channel);
if (DEBUG > 1) {
System.err.println("Cached channel " + chanId);
}
}
}
}
}
if (inCache) {
LogService.instance().log(LogService.DEBUG,
"RDBMChannelRegistryStore.getChannelDefinition(): Got channel " + chanId + " from the cache");
}
return channel;
}
/**
* Read a channel definition from the data store
*/
protected ChannelDefinition getChannelDefinition (int chanId, RDBMServices.PreparedStatement pstmtChannel, RDBMServices.PreparedStatement pstmtChannelParm) throws java.sql.SQLException {
try {
return crs.getChannelDefinition(chanId);
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
throw new SQLException(e.getMessage());
}
}
/**
* Get the channel node
* @param con
* @param doc
* @param chanId
* @param idTag
* @return the channel node as an XML Element
* @exception java.sql.SQLException
*/
/*
public Element getChannelNode (int chanId, Connection con, Document doc, String idTag) throws java.sql.SQLException {
RDBMServices.PreparedStatement pstmtChannel = getChannelPstmt(con);
try {
RDBMServices.PreparedStatement pstmtChannelParm = getChannelParmPstmt(con);
try {
ChannelDefinition cd = getChannel(chanId, false, pstmtChannel, pstmtChannelParm);
if (cd != null) {
return cd.getDocument(doc, idTag);
} else {
return null;
}
} finally {
if (pstmtChannelParm != null) {
pstmtChannelParm.close();
}
}
} finally {
pstmtChannel.close();
}
}
*/
public final RDBMServices.PreparedStatement getChannelParmPstmt(Connection con) throws SQLException {
return RDBMChannelRegistryStore.getChannelParamPstmt();
}
public final RDBMServices.PreparedStatement getChannelPstmt(Connection con) throws SQLException {
return RDBMChannelRegistryStore.getChannelPstmt();
}
}
| source/org/jasig/portal/RDBMChannelRegistryStoreOld.java | /**
* Copyright 2001, 2002 The JA-SIG Collaborative. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the JA-SIG Collaborative
* (http://www.jasig.org/)."
*
* THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.jasig.portal;
import org.jasig.portal.utils.DTDResolver;
import org.jasig.portal.utils.DocumentFactory;
import org.jasig.portal.utils.CounterStoreFactory;
import org.jasig.portal.services.LogService;
import org.jasig.portal.security.IPerson;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Reference implementation of IChannelRegistryStoreOld. This class is currently
* acting as a wrapper for the real IChannelRegistryStore and will be eventually
* removed.
* @author John Laker, [email protected]
* @version $Revision$
* @deprecated Use {@link RDBMChannelRegistryStore} instead
*/
public class RDBMChannelRegistryStoreOld implements IChannelRegistryStoreOld {
private static final int DEBUG = 0;
private static final String sRegDtd = "channelRegistry.dtd";
private static final Object channelLock = new Object();
private static final HashMap channelCache = new HashMap();
protected static IChannelRegistryStore crs = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl();
public RDBMChannelRegistryStoreOld() throws Exception {
if (RDBMServices.supportsOuterJoins) {
if (RDBMServices.joinQuery instanceof RDBMServices.JdbcDb) {
RDBMServices.joinQuery.addQuery("channel",
"{oj UP_CHANNEL UC LEFT OUTER JOIN UP_CHANNEL_PARAM UCP ON UC.CHAN_ID = UCP.CHAN_ID} WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.PostgreSQLDb) {
RDBMServices.joinQuery.addQuery("channel",
"UP_CHANNEL UC LEFT OUTER JOIN UP_CHANNEL_PARAM UCP ON UC.CHAN_ID = UCP.CHAN_ID WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.OracleDb) {
RDBMServices.joinQuery.addQuery("channel",
"UP_CHANNEL UC, UP_CHANNEL_PARAM UCP WHERE UC.CHAN_ID = UCP.CHAN_ID(+) AND");
} else {
throw new Exception("Unknown database driver");
}
}
}
/**
* Returns an XML document which describes the channel registry.
* Right now this is being stored as a string in a field but could be also implemented to get from multiple tables.
* @return a string of XML
* @throws java.lang.Exception
*/
public Document getChannelRegistryXML () throws SQLException {
Document doc = DocumentFactory.getNewDocument();
Element registry = doc.createElement("registry");
doc.appendChild(registry);
Connection con = RDBMServices.getConnection();
try {
RDBMServices.PreparedStatement chanStmt = new RDBMServices.PreparedStatement(con, "SELECT CHAN_ID FROM UP_CAT_CHAN WHERE CAT_ID=?");
try {
Statement stmt = con.createStatement();
try {
try {
String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID IS NULL ORDER BY CAT_TITLE";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.getChannelRegistryXML(): " + query);
ResultSet rs = stmt.executeQuery(query);
try {
while (rs.next()) {
int catId = rs.getInt(1);
String catTitle = rs.getString(2);
String catDesc = rs.getString(3);
// Top level <category>
Element category = doc.createElement("category");
category.setAttribute("ID", "cat" + catId);
category.setAttribute("name", catTitle);
category.setAttribute("description", catDesc);
((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(category.getAttribute("ID"), category);
registry.appendChild(category);
// Add child categories and channels
appendChildCategoriesAndChannels(con, chanStmt, category, catId);
}
} finally {
rs.close();
}
} finally {
// ap.close();
}
} finally {
stmt.close();
}
} finally {
chanStmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return doc;
}
protected void appendChildCategoriesAndChannels (Connection con, RDBMServices.PreparedStatement chanStmt, Element category, int catId) throws SQLException {
Document doc = category.getOwnerDocument();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = con.createStatement();
String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID=" + catId;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): " + query);
rs = stmt.executeQuery(query);
while (rs.next()) {
int childCatId = rs.getInt(1);
String childCatTitle = rs.getString(2);
String childCatDesc = rs.getString(3);
// Child <category>
Element childCategory = doc.createElement("category");
childCategory.setAttribute("ID", "cat" + childCatId);
childCategory.setAttribute("name", childCatTitle);
childCategory.setAttribute("description", childCatDesc);
((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(childCategory.getAttribute("ID"), childCategory);
category.appendChild(childCategory);
// Append child categories and channels recursively
appendChildCategoriesAndChannels(con, chanStmt, childCategory, childCatId);
}
// Append children channels
chanStmt.clearParameters();
chanStmt.setInt(1, catId);
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): " + chanStmt);
rs = chanStmt.executeQuery();
try {
while (rs.next()) {
int chanId = rs.getInt(1);
Element channel = getChannelNode (chanId, con, doc, "chan" + chanId);
if (channel == null) {
LogService.instance().log(LogService.WARN, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): channel " + chanId +
" in category " + catId + " does not exist in the store");
} else {
category.appendChild(channel);
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
}
/**
* Get channel types xml.
* It will look something like this:
* <p><code>
*
*<channelTypes>
* <channelType ID="0">
* <class>org.jasig.portal.channels.CImage</class>
* <name>Image</name>
* <description>Simple channel to display an image with optional
* caption and subcaption</description>
* <cpd-uri>webpages/media/org/jasig/portal/channels/CImage/CImage.cpd</cpd-uri>
* </channelType>
* <channelType ID="1">
* <class>org.jasig.portal.channels.CWebProxy</class>
* <name>Web Proxy</name>
* <description>Incorporate a dynamic HTML or XML application</description>
* <cpd-uri>webpages/media/org/jasig/portal/channels/CWebProxy/CWebProxy.cpd</cpd-uri>
* </channelType>
*</channelTypes>
*
* </code></p>
* @return types, the channel types as a Document
* @throws java.sql.SQLException
*/
public Document getChannelTypesXML () throws Exception {
Document doc = DocumentFactory.getNewDocument();
Element root = doc.createElement("channelTypes");
doc.appendChild(root);
ChannelType[] channelTypes = crs.getChannelTypes();
for (int i = 0; i < channelTypes.length; i++) {
int channelTypeId = channelTypes[i].getChannelTypeId();
String javaClass = channelTypes[i].getJavaClass();
String name = channelTypes[i].getName();
String descr = channelTypes[i].getDescription();
String cpdUri = channelTypes[i].getCpdUri();
// <channelType>
Element channelType = doc.createElement("channelType");
channelType.setAttribute("ID", String.valueOf(channelTypeId));
Element elem = null;
// <class>
elem = doc.createElement("class");
elem.appendChild(doc.createTextNode(javaClass));
channelType.appendChild(elem);
// <name>
elem = doc.createElement("name");
elem.appendChild(doc.createTextNode(name));
channelType.appendChild(elem);
// <description>
elem = doc.createElement("description");
elem.appendChild(doc.createTextNode(descr));
channelType.appendChild(elem);
// <cpd-uri>
elem = doc.createElement("cpd-uri");
elem.appendChild(doc.createTextNode(cpdUri));
channelType.appendChild(elem);
root.appendChild(channelType);
}
return doc;
}
/** A method for adding a channel to the channel registry.
* This would be called by a publish channel.
* @param id the identifier for the channel
* @param publisherId the identifier for the user who is publishing this channel
* @param chanXML XML that describes the channel
* @param catID an array of category IDs
* @throws java.lang.Exception
*/
public void addChannel (int id, IPerson publisher, Document chanXML, String catID[]) throws Exception {
Connection con = RDBMServices.getConnection();
try {
addChannel(id, publisher, chanXML, con);
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// First delete existing categories for this channel
String sDelete = "DELETE FROM UP_CAT_CHAN WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sDelete);
int recordsDeleted = stmt.executeUpdate(sDelete);
for (int i = 0; i < catID.length; i++) {
// Take out "cat" prefix if its there
String categoryID = catID[i].startsWith("cat") ? catID[i].substring(3) : catID[i];
String sInsert = "INSERT INTO UP_CAT_CHAN (CHAN_ID, CAT_ID) VALUES (" + id + "," + categoryID + ")";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
stmt.executeUpdate(sInsert);
}
// Commit the transaction
RDBMServices.commit(con);
} catch (SQLException sqle) {
// Roll back the transaction
RDBMServices.rollback(con);
throw sqle;
} finally {
if (stmt != null)
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/** A method for adding a channel to the channel registry.
* This would be called by a publish channel.
* @param id the identifier for the channel
* @param publisher the user who is publishing this channel
* @param chanXML XML that describes the channel
*/
public void addChannel (int id, IPerson publisher, Document chanXML) throws Exception {
Connection con = RDBMServices.getConnection();
try {
addChannel(id, publisher, chanXML, con);
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Publishes a channel.
* @param id
* @param publisherId
* @param doc
* @param con
* @exception Exception
*/
private void addChannel (int id, IPerson publisher, Document doc, Connection con) throws SQLException {
Element channel = (Element)doc.getFirstChild();
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
String sqlTitle = RDBMServices.sqlEscape(channel.getAttribute("title"));
String sqlDescription = RDBMServices.sqlEscape(channel.getAttribute("description"));
String sqlClass = channel.getAttribute("class");
String sqlTypeID = channel.getAttribute("typeID");
String sysdate = RDBMServices.sqlTimeStamp();
String sqlTimeout = channel.getAttribute("timeout");
String timeout = "0";
if (sqlTimeout != null && sqlTimeout.trim().length() != 0) {
timeout = sqlTimeout;
}
String sqlEditable = RDBMServices.dbFlag(xmlBool(channel.getAttribute("editable")));
String sqlHasHelp = RDBMServices.dbFlag(xmlBool(channel.getAttribute("hasHelp")));
String sqlHasAbout = RDBMServices.dbFlag(xmlBool(channel.getAttribute("hasAbout")));
String sqlName = RDBMServices.sqlEscape(channel.getAttribute("name"));
String sqlFName = RDBMServices.sqlEscape(channel.getAttribute("fname"));
String sQuery = "SELECT CHAN_ID FROM UP_CHANNEL WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
// If channel is already there, do an update, otherwise do an insert
if (rs.next()) {
String sUpdate = "UPDATE UP_CHANNEL SET " +
"CHAN_TITLE='" + sqlTitle + "', " +
"CHAN_DESC='" + sqlDescription + "', " +
"CHAN_CLASS='" + sqlClass + "', " +
"CHAN_TYPE_ID=" + sqlTypeID + ", " +
"CHAN_PUBL_ID=" + publisher.getID() + ", " +
"CHAN_PUBL_DT=" + sysdate + ", " +
"CHAN_APVL_ID=NULL, " +
"CHAN_APVL_DT=NULL, " +
"CHAN_TIMEOUT=" + timeout + ", " +
"CHAN_EDITABLE='" + sqlEditable + "', " +
"CHAN_HAS_HELP='" + sqlHasHelp + "', " +
"CHAN_HAS_ABOUT='" + sqlHasAbout + "', " +
"CHAN_NAME='" + sqlName + "', " +
"CHAN_FNAME='" + sqlFName + "' " +
"WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sUpdate);
stmt.executeUpdate(sUpdate);
} else {
String sInsert = "INSERT INTO UP_CHANNEL (CHAN_ID, CHAN_TITLE, CHAN_DESC, CHAN_CLASS, CHAN_TYPE_ID, CHAN_PUBL_ID, CHAN_PUBL_DT, CHAN_TIMEOUT, "
+ "CHAN_EDITABLE, CHAN_HAS_HELP, CHAN_HAS_ABOUT, CHAN_NAME, CHAN_FNAME) ";
sInsert += "VALUES (" + id + ", '" + sqlTitle + "', '" + sqlDescription + "', '" + sqlClass + "', " + sqlTypeID + ", "
+ publisher.getID() + ", " + sysdate + ", " + timeout
+ ", '" + sqlEditable + "', '" + sqlHasHelp + "', '" + sqlHasAbout
+ "', '" + sqlName + "', '" + sqlFName + "')";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
stmt.executeUpdate(sInsert);
}
// First delete existing parameters for this channel
String sDelete = "DELETE FROM UP_CHANNEL_PARAM WHERE CHAN_ID=" + id;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sDelete);
int recordsDeleted = stmt.executeUpdate(sDelete);
NodeList parameters = channel.getChildNodes();
if (parameters != null) {
for (int i = 0; i < parameters.getLength(); i++) {
if (parameters.item(i).getNodeName().equals("parameter")) {
Element parmElement = (Element)parameters.item(i);
NamedNodeMap nm = parmElement.getAttributes();
String paramName = null;
String paramValue = null;
String paramOverride = "NULL";
for (int j = 0; j < nm.getLength(); j++) {
Node param = nm.item(j);
String nodeName = param.getNodeName();
String nodeValue = param.getNodeValue();
if (nodeName.equals("name")) {
paramName = nodeValue;
} else if (nodeName.equals("value")) {
paramValue = nodeValue;
} else if (nodeName.equals("override") && nodeValue.equals("yes")) {
paramOverride = "'Y'";
}
}
if (paramName == null && paramValue == null) {
throw new RuntimeException("Invalid parameter node");
}
String sInsert = "INSERT INTO UP_CHANNEL_PARAM (CHAN_ID, CHAN_PARM_NM, CHAN_PARM_VAL, CHAN_PARM_OVRD) VALUES (" + id +
",'" + paramName + "','" + paramValue + "'," + paramOverride + ")";
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
stmt.executeUpdate(sInsert);
}
}
}
// Commit the transaction
RDBMServices.commit(con);
flushChannelEntry(id);
} catch (SQLException sqle) {
RDBMServices.rollback(con);
throw sqle;
} finally {
stmt.close();
}
}
/** A method for approving a channel so that users are allowed to subscribe to it.
* This would be called by the publish channel or the administrator channel
* @param chanId Channel to approve
* @param approved Account approving the channel
* @param approveDate When should the channel appear
*/
public void approveChannel(int chanId, IPerson approver, Date approveDate) throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sUpdate = "UPDATE UP_CHANNEL SET CHAN_APVL_ID = " + approver.getID() +
", CHAN_APVL_DT = " + RDBMServices.sqlTimeStamp(approveDate) +
" WHERE CHAN_ID = " + chanId;
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.approveChannel(): " + sUpdate);
stmt.executeUpdate(sUpdate);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/** A method for getting the next available channel ID.
* This would be called by a publish channel.
*/
public int getNextId () throws PortalException {
int nextID;
try {
nextID = CounterStoreFactory.getCounterStoreImpl().getIncrementIntegerId("UP_CHANNEL");
} catch (Exception e) {
LogService.instance().log(LogService.ERROR, e);
throw new PortalException("Unable to allocate new channel ID", e);
}
return nextID;
}
/**
* Removes a channel from the channel registry. The channel
* is not actually deleted. Rather its status as an "approved"
* channel is revoked.
* @param chanID, the ID of the channel to delete
* @exception java.sql.SQLException
*/
public void removeChannel (String chanID) throws Exception {
String channelPublishId = chanID.startsWith("chan") ? chanID.substring(4) : chanID;
crs.disapproveChannelDefinition(channelPublishId);
flushChannelEntry(Integer.parseInt(channelPublishId));
}
/**
* A method for persisting the channel registry to a file or database.
* @param registryXML an XML description of the channel registry
*/
public void setRegistryXML (String registryXML) throws Exception{
throw new Exception("not implemented yet");
}
/**
* @param chanDoc
* @return the chanDoc as an XML string
*/
private String serializeDOM (Document chanDoc) {
StringWriter stringOut = null;
try {
OutputFormat format = new OutputFormat(chanDoc); //Serialize DOM
stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize(chanDoc.getDocumentElement());
} catch (java.io.IOException ioe) {
LogService.instance().log(LogService.ERROR, ioe);
}
return stringOut.toString();
}
/**
* convert true/false into Y/N for database
* @param value to check
* @result boolean
*/
protected static final boolean xmlBool (String value) {
return (value != null && value.equals("true") ? true : false);
}
/**
* Manage the Channel cache
*/
/**
* See if the channel is already in the cache
* @param channel id
*/
protected boolean channelCached(int chanId) {
return channelCache.containsKey(new Integer(chanId));
}
/**
* Remove channel entry from cache
* @param channel id
*/
public void flushChannelEntry(int chanId) {
synchronized (channelLock) {
if (channelCache.remove(new Integer(chanId)) != null) {
LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): flushed channel "
+ chanId + " from cache");
}
}
}
/**
* Get a channel from the cache (it better be there)
*/
public ChannelDefinition getChannel(int chanId) {
ChannelDefinition channelDef = null;
try {
channelDef = crs.getChannelDefinition(chanId);
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
}
return channelDef;
}
/**
* Get a channel from the cache (it better be there)
*/
public Element getChannelXML(int chanId, Document doc, String idTag) {
ChannelDefinition channel = getChannel(chanId);
if (channel != null) {
return channel.getDocument(doc, idTag);
} else {
return null;
}
}
/**
* Get a channel from the cache or the store
*/
public ChannelDefinition getChannel(int chanId, boolean cacheChannel, RDBMServices.PreparedStatement pstmtChannel, RDBMServices.PreparedStatement pstmtChannelParm) throws java.sql.SQLException {
Integer chanID = new Integer(chanId);
boolean inCache = true;
ChannelDefinition channel = (ChannelDefinition)channelCache.get(chanID);
if (channel == null) {
synchronized (channelLock) {
channel = (ChannelDefinition)channelCache.get(chanID);
if (channel == null || cacheChannel && channel.refreshMe()) { // Still undefined or stale, let's get it
channel = getChannelDefinition(chanId, pstmtChannel, pstmtChannelParm);
inCache = false;
if (cacheChannel) {
channelCache.put(chanID, channel);
if (DEBUG > 1) {
System.err.println("Cached channel " + chanId);
}
}
}
}
}
if (inCache) {
LogService.instance().log(LogService.DEBUG,
"RDBMChannelRegistryStore.getChannelDefinition(): Got channel " + chanId + " from the cache");
}
return channel;
}
/**
* Read a channel definition from the data store
*/
protected ChannelDefinition getChannelDefinition (int chanId, RDBMServices.PreparedStatement pstmtChannel, RDBMServices.PreparedStatement pstmtChannelParm) throws java.sql.SQLException {
try {
return crs.getChannelDefinition(chanId);
} catch (Exception e) {
LogService.log(LogService.ERROR, e);
throw new SQLException(e.getMessage());
}
}
/**
* Get the channel node
* @param con
* @param doc
* @param chanId
* @param idTag
* @return the channel node as an XML Element
* @exception java.sql.SQLException
*/
public Element getChannelNode (int chanId, Connection con, Document doc, String idTag) throws java.sql.SQLException {
RDBMServices.PreparedStatement pstmtChannel = getChannelPstmt(con);
try {
RDBMServices.PreparedStatement pstmtChannelParm = getChannelParmPstmt(con);
try {
ChannelDefinition cd = getChannel(chanId, false, pstmtChannel, pstmtChannelParm);
if (cd != null) {
return cd.getDocument(doc, idTag);
} else {
return null;
}
} finally {
if (pstmtChannelParm != null) {
pstmtChannelParm.close();
}
}
} finally {
pstmtChannel.close();
}
}
public final RDBMServices.PreparedStatement getChannelParmPstmt(Connection con) throws SQLException {
return RDBMChannelRegistryStore.getChannelParamPstmt();
}
public final RDBMServices.PreparedStatement getChannelPstmt(Connection con) throws SQLException {
return RDBMChannelRegistryStore.getChannelPstmt();
}
}
| Re-implemented addChannel() method to talk to the newer channel reg store interface.
Removed some private methods that are no longer used.
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@5929 f5dbab47-78f9-eb45-b975-e544023573eb
| source/org/jasig/portal/RDBMChannelRegistryStoreOld.java | Re-implemented addChannel() method to talk to the newer channel reg store interface. Removed some private methods that are no longer used. | <ide><path>ource/org/jasig/portal/RDBMChannelRegistryStoreOld.java
<ide>
<ide> package org.jasig.portal;
<ide>
<del>import org.jasig.portal.utils.DTDResolver;
<ide> import org.jasig.portal.utils.DocumentFactory;
<ide> import org.jasig.portal.utils.CounterStoreFactory;
<ide> import org.jasig.portal.services.LogService;
<ide> import org.jasig.portal.security.IPerson;
<ide> import java.io.StringWriter;
<ide> import java.sql.Connection;
<del>import java.sql.ResultSet;
<ide> import java.sql.SQLException;
<del>import java.sql.Statement;
<ide> import java.util.ArrayList;
<ide> import java.util.Date;
<ide> import java.util.HashMap;
<add>import java.util.Iterator;
<ide> import org.apache.xml.serialize.OutputFormat;
<ide> import org.apache.xml.serialize.XMLSerializer;
<ide> import org.w3c.dom.Document;
<ide> import org.w3c.dom.NamedNodeMap;
<ide> import org.w3c.dom.Node;
<ide> import org.w3c.dom.NodeList;
<add>import org.jasig.portal.services.GroupService;
<add>import org.jasig.portal.groups.IEntityGroup;
<add>import org.jasig.portal.groups.IEntity;
<add>import org.jasig.portal.groups.IGroupMember;
<add>import org.jasig.portal.groups.GroupsException;
<ide>
<ide> /**
<ide> * Reference implementation of IChannelRegistryStoreOld. This class is currently
<ide> */
<ide> public class RDBMChannelRegistryStoreOld implements IChannelRegistryStoreOld {
<ide> private static final int DEBUG = 0;
<del> private static final String sRegDtd = "channelRegistry.dtd";
<ide>
<ide> private static final Object channelLock = new Object();
<ide> private static final HashMap channelCache = new HashMap();
<ide> * @return a string of XML
<ide> * @throws java.lang.Exception
<ide> */
<del> public Document getChannelRegistryXML () throws SQLException {
<add> public Document getChannelRegistryXML () throws Exception {
<ide> Document doc = DocumentFactory.getNewDocument();
<ide> Element registry = doc.createElement("registry");
<ide> doc.appendChild(registry);
<del> Connection con = RDBMServices.getConnection();
<del> try {
<del> RDBMServices.PreparedStatement chanStmt = new RDBMServices.PreparedStatement(con, "SELECT CHAN_ID FROM UP_CAT_CHAN WHERE CAT_ID=?");
<del> try {
<del> Statement stmt = con.createStatement();
<del> try {
<del> try {
<del> String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID IS NULL ORDER BY CAT_TITLE";
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.getChannelRegistryXML(): " + query);
<del> ResultSet rs = stmt.executeQuery(query);
<del> try {
<del> while (rs.next()) {
<del> int catId = rs.getInt(1);
<del> String catTitle = rs.getString(2);
<del> String catDesc = rs.getString(3);
<del>
<del> // Top level <category>
<del> Element category = doc.createElement("category");
<del> category.setAttribute("ID", "cat" + catId);
<del> category.setAttribute("name", catTitle);
<del> category.setAttribute("description", catDesc);
<del> ((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(category.getAttribute("ID"), category);
<del> registry.appendChild(category);
<del>
<del> // Add child categories and channels
<del> appendChildCategoriesAndChannels(con, chanStmt, category, catId);
<del> }
<del> } finally {
<del> rs.close();
<del> }
<del> } finally {
<del> // ap.close();
<del> }
<del> } finally {
<del> stmt.close();
<del> }
<del> } finally {
<del> chanStmt.close();
<del> }
<del> } finally {
<del> RDBMServices.releaseConnection(con);
<del> }
<add>
<add> IEntityGroup channelCategoriesGroup = GroupService.getChannelCategoriesGroup();
<add> processGroupsRecursively(channelCategoriesGroup, registry);
<add> System.out.println(org.jasig.portal.utils.XML.serializeNode(doc));
<add>
<ide> return doc;
<ide> }
<ide>
<del> protected void appendChildCategoriesAndChannels (Connection con, RDBMServices.PreparedStatement chanStmt, Element category, int catId) throws SQLException {
<del> Document doc = category.getOwnerDocument();
<del> Statement stmt = null;
<del> ResultSet rs = null;
<del>
<del> try {
<del> stmt = con.createStatement();
<del> String query = "SELECT CAT_ID, CAT_TITLE, CAT_DESC FROM UP_CATEGORY WHERE PARENT_CAT_ID=" + catId;
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): " + query);
<del> rs = stmt.executeQuery(query);
<del> while (rs.next()) {
<del> int childCatId = rs.getInt(1);
<del> String childCatTitle = rs.getString(2);
<del> String childCatDesc = rs.getString(3);
<del>
<del> // Child <category>
<del> Element childCategory = doc.createElement("category");
<del> childCategory.setAttribute("ID", "cat" + childCatId);
<del> childCategory.setAttribute("name", childCatTitle);
<del> childCategory.setAttribute("description", childCatDesc);
<del> ((org.apache.xerces.dom.DocumentImpl)doc).putIdentifier(childCategory.getAttribute("ID"), childCategory);
<del> category.appendChild(childCategory);
<del>
<del> // Append child categories and channels recursively
<del> appendChildCategoriesAndChannels(con, chanStmt, childCategory, childCatId);
<del> }
<del>
<del> // Append children channels
<del> chanStmt.clearParameters();
<del> chanStmt.setInt(1, catId);
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): " + chanStmt);
<del> rs = chanStmt.executeQuery();
<del>
<del> try {
<del> while (rs.next()) {
<del> int chanId = rs.getInt(1);
<del> Element channel = getChannelNode (chanId, con, doc, "chan" + chanId);
<del> if (channel == null) {
<del> LogService.instance().log(LogService.WARN, "RDBMChannelRegistryStore.appendChildCategoriesAndChannels(): channel " + chanId +
<del> " in category " + catId + " does not exist in the store");
<del> } else {
<del> category.appendChild(channel);
<del> }
<del> }
<del> } finally {
<del> rs.close();
<del> }
<del> } finally {
<del> stmt.close();
<add> private void processGroupsRecursively(IEntityGroup group, Element parentGroup) throws Exception {
<add> Document registryDoc = parentGroup.getOwnerDocument();
<add> Iterator iter = group.getMembers();
<add> while (iter.hasNext()) {
<add> IGroupMember member = (IGroupMember)iter.next();
<add> if (member.isGroup()) {
<add> IEntityGroup memberGroup = (IEntityGroup)member;
<add> String key = memberGroup.getKey();
<add> String name = memberGroup.getName();
<add> String description = memberGroup.getDescription();
<add>
<add> // Create category element and append it to its parent
<add> Element categoryE = registryDoc.createElement("category");
<add> categoryE.setAttribute("ID", "cat" + key);
<add> categoryE.setAttribute("name", name);
<add> categoryE.setAttribute("description", description);
<add> parentGroup.appendChild(categoryE);
<add> processGroupsRecursively(memberGroup, categoryE);
<add> } else {
<add> IEntity channelDefMember = (IEntity)member;
<add> int channelPublishId = Integer.parseInt(channelDefMember.getKey());
<add> ChannelDefinition channelDef = crs.getChannelDefinition(channelPublishId);
<add> Element channelDefE = channelDef.getDocument(registryDoc, "chan" + channelPublishId);
<add> channelDefE = (Element)registryDoc.importNode(channelDefE, true);
<add> parentGroup.appendChild(channelDefE);
<add> }
<ide> }
<ide> }
<ide>
<ide> return doc;
<ide> }
<ide>
<del>
<del>
<ide> /** A method for adding a channel to the channel registry.
<ide> * This would be called by a publish channel.
<ide> * @param id the identifier for the channel
<ide> * @throws java.lang.Exception
<ide> */
<ide> public void addChannel (int id, IPerson publisher, Document chanXML, String catID[]) throws Exception {
<del> Connection con = RDBMServices.getConnection();
<del> try {
<del> addChannel(id, publisher, chanXML, con);
<del> // Set autocommit false for the connection
<del> RDBMServices.setAutoCommit(con, false);
<del> Statement stmt = con.createStatement();
<del> try {
<del> // First delete existing categories for this channel
<del> String sDelete = "DELETE FROM UP_CAT_CHAN WHERE CHAN_ID=" + id;
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sDelete);
<del> int recordsDeleted = stmt.executeUpdate(sDelete);
<del>
<del> for (int i = 0; i < catID.length; i++) {
<del> // Take out "cat" prefix if its there
<del> String categoryID = catID[i].startsWith("cat") ? catID[i].substring(3) : catID[i];
<del>
<del> String sInsert = "INSERT INTO UP_CAT_CHAN (CHAN_ID, CAT_ID) VALUES (" + id + "," + categoryID + ")";
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
<del> stmt.executeUpdate(sInsert);
<del>
<add> Element channel = (Element)chanXML.getFirstChild();
<add>
<add> String chanTitle = channel.getAttribute("title");
<add> String chanDesc = channel.getAttribute("description");
<add> String chanClass = channel.getAttribute("class");
<add> int chanTypeId = Integer.parseInt(channel.getAttribute("typeID"));
<add> int chanPupblUsrId = publisher.getID();
<add> int chanApvlId = -1;
<add> String timeout = channel.getAttribute("timeout");
<add> int chanTimeout = 0;
<add> if (timeout != null && timeout.trim().length() != 0) {
<add> chanTimeout = Integer.parseInt(timeout);
<add> }
<add> String chanEditable = channel.getAttribute("editable");
<add> String chanHasHelp = channel.getAttribute("hasHelp");
<add> String chanHasAbout = channel.getAttribute("hasAbout");
<add> String chanName = channel.getAttribute("name");
<add> String chanFName = channel.getAttribute("fname");
<add>
<add> ChannelDefinition channelDef = new ChannelDefinition(id, chanTitle, chanDesc,
<add> chanClass, chanTypeId, chanPupblUsrId, chanApvlId,
<add> null, null, chanTimeout, chanEditable, chanHasHelp,
<add> chanHasAbout, chanName, chanFName);
<add>
<add> NodeList parameters = channel.getChildNodes();
<add> if (parameters != null) {
<add> for (int i = 0; i < parameters.getLength(); i++) {
<add> if (parameters.item(i).getNodeName().equals("parameter")) {
<add> Element parmElement = (Element)parameters.item(i);
<add> NamedNodeMap nm = parmElement.getAttributes();
<add> String paramName = null;
<add> String paramValue = null;
<add> String paramOverride = "NULL";
<add>
<add> for (int j = 0; j < nm.getLength(); j++) {
<add> Node param = nm.item(j);
<add> String nodeName = param.getNodeName();
<add> String nodeValue = param.getNodeValue();
<add>
<add> if (nodeName.equals("name")) {
<add> paramName = nodeValue;
<add> } else if (nodeName.equals("value")) {
<add> paramValue = nodeValue;
<add> } else if (nodeName.equals("override") && nodeValue.equals("yes")) {
<add> paramOverride = "'Y'";
<add> }
<add> }
<add>
<add> if (paramName == null && paramValue == null) {
<add> throw new RuntimeException("Invalid parameter node");
<add> }
<add>
<add> channelDef.addParameter(paramName, paramValue, paramOverride);
<ide> }
<del> // Commit the transaction
<del> RDBMServices.commit(con);
<del> } catch (SQLException sqle) {
<del> // Roll back the transaction
<del> RDBMServices.rollback(con);
<del> throw sqle;
<del> } finally {
<del> if (stmt != null)
<del> stmt.close();
<del> }
<del> } finally {
<del> RDBMServices.releaseConnection(con);
<del> }
<del> }
<del>
<del> /** A method for adding a channel to the channel registry.
<del> * This would be called by a publish channel.
<del> * @param id the identifier for the channel
<del> * @param publisher the user who is publishing this channel
<del> * @param chanXML XML that describes the channel
<del> */
<del> public void addChannel (int id, IPerson publisher, Document chanXML) throws Exception {
<del> Connection con = RDBMServices.getConnection();
<del> try {
<del> addChannel(id, publisher, chanXML, con);
<del> } finally {
<del> RDBMServices.releaseConnection(con);
<del> }
<del> }
<del>
<del> /**
<del> * Publishes a channel.
<del> * @param id
<del> * @param publisherId
<del> * @param doc
<del> * @param con
<del> * @exception Exception
<del> */
<del> private void addChannel (int id, IPerson publisher, Document doc, Connection con) throws SQLException {
<del> Element channel = (Element)doc.getFirstChild();
<del> // Set autocommit false for the connection
<del> RDBMServices.setAutoCommit(con, false);
<del> Statement stmt = con.createStatement();
<del> try {
<del> String sqlTitle = RDBMServices.sqlEscape(channel.getAttribute("title"));
<del> String sqlDescription = RDBMServices.sqlEscape(channel.getAttribute("description"));
<del> String sqlClass = channel.getAttribute("class");
<del> String sqlTypeID = channel.getAttribute("typeID");
<del> String sysdate = RDBMServices.sqlTimeStamp();
<del> String sqlTimeout = channel.getAttribute("timeout");
<del> String timeout = "0";
<del> if (sqlTimeout != null && sqlTimeout.trim().length() != 0) {
<del> timeout = sqlTimeout;
<del> }
<del> String sqlEditable = RDBMServices.dbFlag(xmlBool(channel.getAttribute("editable")));
<del> String sqlHasHelp = RDBMServices.dbFlag(xmlBool(channel.getAttribute("hasHelp")));
<del> String sqlHasAbout = RDBMServices.dbFlag(xmlBool(channel.getAttribute("hasAbout")));
<del> String sqlName = RDBMServices.sqlEscape(channel.getAttribute("name"));
<del> String sqlFName = RDBMServices.sqlEscape(channel.getAttribute("fname"));
<del>
<del> String sQuery = "SELECT CHAN_ID FROM UP_CHANNEL WHERE CHAN_ID=" + id;
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sQuery);
<del> ResultSet rs = stmt.executeQuery(sQuery);
<del>
<del> // If channel is already there, do an update, otherwise do an insert
<del> if (rs.next()) {
<del> String sUpdate = "UPDATE UP_CHANNEL SET " +
<del> "CHAN_TITLE='" + sqlTitle + "', " +
<del> "CHAN_DESC='" + sqlDescription + "', " +
<del> "CHAN_CLASS='" + sqlClass + "', " +
<del> "CHAN_TYPE_ID=" + sqlTypeID + ", " +
<del> "CHAN_PUBL_ID=" + publisher.getID() + ", " +
<del> "CHAN_PUBL_DT=" + sysdate + ", " +
<del> "CHAN_APVL_ID=NULL, " +
<del> "CHAN_APVL_DT=NULL, " +
<del> "CHAN_TIMEOUT=" + timeout + ", " +
<del> "CHAN_EDITABLE='" + sqlEditable + "', " +
<del> "CHAN_HAS_HELP='" + sqlHasHelp + "', " +
<del> "CHAN_HAS_ABOUT='" + sqlHasAbout + "', " +
<del> "CHAN_NAME='" + sqlName + "', " +
<del> "CHAN_FNAME='" + sqlFName + "' " +
<del> "WHERE CHAN_ID=" + id;
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sUpdate);
<del> stmt.executeUpdate(sUpdate);
<del> } else {
<del> String sInsert = "INSERT INTO UP_CHANNEL (CHAN_ID, CHAN_TITLE, CHAN_DESC, CHAN_CLASS, CHAN_TYPE_ID, CHAN_PUBL_ID, CHAN_PUBL_DT, CHAN_TIMEOUT, "
<del> + "CHAN_EDITABLE, CHAN_HAS_HELP, CHAN_HAS_ABOUT, CHAN_NAME, CHAN_FNAME) ";
<del> sInsert += "VALUES (" + id + ", '" + sqlTitle + "', '" + sqlDescription + "', '" + sqlClass + "', " + sqlTypeID + ", "
<del> + publisher.getID() + ", " + sysdate + ", " + timeout
<del> + ", '" + sqlEditable + "', '" + sqlHasHelp + "', '" + sqlHasAbout
<del> + "', '" + sqlName + "', '" + sqlFName + "')";
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
<del> stmt.executeUpdate(sInsert);
<del> }
<del>
<del> // First delete existing parameters for this channel
<del> String sDelete = "DELETE FROM UP_CHANNEL_PARAM WHERE CHAN_ID=" + id;
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sDelete);
<del> int recordsDeleted = stmt.executeUpdate(sDelete);
<del>
<del> NodeList parameters = channel.getChildNodes();
<del> if (parameters != null) {
<del> for (int i = 0; i < parameters.getLength(); i++) {
<del> if (parameters.item(i).getNodeName().equals("parameter")) {
<del> Element parmElement = (Element)parameters.item(i);
<del> NamedNodeMap nm = parmElement.getAttributes();
<del> String paramName = null;
<del> String paramValue = null;
<del> String paramOverride = "NULL";
<del>
<del> for (int j = 0; j < nm.getLength(); j++) {
<del> Node param = nm.item(j);
<del> String nodeName = param.getNodeName();
<del> String nodeValue = param.getNodeValue();
<del>
<del> if (nodeName.equals("name")) {
<del> paramName = nodeValue;
<del> } else if (nodeName.equals("value")) {
<del> paramValue = nodeValue;
<del> } else if (nodeName.equals("override") && nodeValue.equals("yes")) {
<del> paramOverride = "'Y'";
<del> }
<del> }
<del>
<del> if (paramName == null && paramValue == null) {
<del> throw new RuntimeException("Invalid parameter node");
<del> }
<del>
<del> String sInsert = "INSERT INTO UP_CHANNEL_PARAM (CHAN_ID, CHAN_PARM_NM, CHAN_PARM_VAL, CHAN_PARM_OVRD) VALUES (" + id +
<del> ",'" + paramName + "','" + paramValue + "'," + paramOverride + ")";
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.addChannel(): " + sInsert);
<del> stmt.executeUpdate(sInsert);
<del> }
<del> }
<del> }
<del>
<del> // Commit the transaction
<del> RDBMServices.commit(con);
<del> flushChannelEntry(id);
<del> } catch (SQLException sqle) {
<del> RDBMServices.rollback(con);
<del> throw sqle;
<del> } finally {
<del> stmt.close();
<del> }
<add> }
<add> }
<add>
<add> // Create array of category objects based on String array of catIDs
<add> ChannelCategory[] categories = new ChannelCategory[catID.length];
<add> for (int i = 0; i < catID.length; i++) {
<add> String name = null;
<add> String descr = null;
<add> catID[i] = catID[i].startsWith("cat") ? catID[i].substring(3) : catID[i];
<add> int iCatID = Integer.parseInt(catID[i]);
<add> categories[i] = new ChannelCategory(iCatID);
<add> }
<add>
<add> crs.addChannelDefinition(channelDef, categories);
<add> flushChannelEntry(id);
<ide> }
<ide>
<ide> /** A method for approving a channel so that users are allowed to subscribe to it.
<ide> * @param approveDate When should the channel appear
<ide> */
<ide> public void approveChannel(int chanId, IPerson approver, Date approveDate) throws Exception {
<del> Connection con = RDBMServices.getConnection();
<del> try {
<del> Statement stmt = con.createStatement();
<del> try {
<del> String sUpdate = "UPDATE UP_CHANNEL SET CHAN_APVL_ID = " + approver.getID() +
<del> ", CHAN_APVL_DT = " + RDBMServices.sqlTimeStamp(approveDate) +
<del> " WHERE CHAN_ID = " + chanId;
<del> LogService.instance().log(LogService.DEBUG, "RDBMChannelRegistryStore.approveChannel(): " + sUpdate);
<del> stmt.executeUpdate(sUpdate);
<del> } finally {
<del> stmt.close();
<del> }
<del> } finally {
<del> RDBMServices.releaseConnection(con);
<del> }
<add> crs.approveChannelDefinition(chanId, approver, approveDate);
<ide> }
<ide>
<ide> /** A method for getting the next available channel ID.
<ide> * @return the channel node as an XML Element
<ide> * @exception java.sql.SQLException
<ide> */
<add> /*
<ide> public Element getChannelNode (int chanId, Connection con, Document doc, String idTag) throws java.sql.SQLException {
<ide> RDBMServices.PreparedStatement pstmtChannel = getChannelPstmt(con);
<ide> try {
<ide> pstmtChannel.close();
<ide> }
<ide> }
<add> */
<ide>
<ide> public final RDBMServices.PreparedStatement getChannelParmPstmt(Connection con) throws SQLException {
<ide> return RDBMChannelRegistryStore.getChannelParamPstmt(); |
|
Java | apache-2.0 | 81c7a45a4e342af104346fdbb955d223663d687a | 0 | tpb1908/AndroidProjectsClient,tpb1908/AndroidProjectsClient,tpb1908/AndroidProjectsClient | package com.tpb.projects.data.models;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by theo on 18/12/16.
*/
public class User extends DataModel {
private static final String TAG = User.class.getSimpleName();
private User() {
}
private static final String LOGIN = "login";
private String login;
private int id;
private static final String AVATAR_URL = "avatar_url";
private String avatarUrl;
private static final String URL = "url";
private String url;
private static final String REPOS_URL = "repos_url";
private String reposUrl;
private static final String NAME = "name";
private String name;
private static final String LOCATION = "location";
private String location;
private static final String EMAIL = "email";
private String email;
private static final String REPOS = "public_repos";
private int repos;
private static final String FOLLOWERS = "followers";
private int followers;
private static final String BIO = "bio";
private String bio;
public int getId() {
return id;
}
public String getLogin() {
return login;
}
public String getAvatarUrl() {
return avatarUrl;
}
public String getUrl() {
return url;
}
public String getReposUrl() {
return reposUrl;
}
@Nullable
public String getName() {
return name;
}
@Nullable
public String getLocation() {
return location;
}
public String getEmail() {
return email;
}
public int getRepos() {
return repos;
}
public int getFollowers() {
return followers;
}
public String getBio() {
return bio;
}
public static User parse(JSONObject obj) {
final User u = new User();
try {
u.id = obj.getInt(ID);
u.login = obj.getString(LOGIN);
u.avatarUrl = obj.getString(AVATAR_URL);
u.url = obj.getString(URL);
u.reposUrl = obj.getString(REPOS_URL);
if(obj.has(REPOS)) u.repos = obj.getInt(REPOS);
if(obj.has(FOLLOWERS)) u.followers = obj.getInt(FOLLOWERS);
if(obj.has(BIO)) u.bio = obj.getString(BIO);
if(obj.has(EMAIL)) u.email = obj.getString(EMAIL);
if(obj.has(LOCATION)) u.location = obj.getString(LOCATION);
if(obj.has(NAME)) u.name = obj.getString(NAME);
} catch(JSONException jse) {
Log.e(TAG, "parse: ", jse);
}
return u;
}
public static JSONObject parse(User user) {
final JSONObject obj = new JSONObject();
try {
obj.put(ID, user.id);
obj.put(LOGIN, user.login);
obj.put(AVATAR_URL, user.avatarUrl);
obj.put(URL, user.url);
obj.put(REPOS_URL, user.reposUrl);
obj.put(REPOS, user.repos);
obj.put(FOLLOWERS, user.followers);
if(user.bio != null) obj.put(BIO, user.bio);
if(user.email != null) obj.put(EMAIL, user.email);
if(user.location != null) obj.put(LOCATION, user.location);
if(user.name != null) obj.put(NAME, user.name);
} catch(JSONException jse) {
Log.e(TAG, "parse: ", jse);
}
return obj;
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", id=" + id +
", avatarUrl='" + avatarUrl + '\'' +
", url='" + url + '\'' +
", reposUrl='" + reposUrl + '\'' +
", name='" + name + '\'' +
", location='" + location + '\'' +
", email='" + email + '\'' +
", repos=" + repos +
", followers=" + followers +
", bio='" + bio + '\'' +
'}';
}
}
| app/src/main/java/com/tpb/projects/data/models/User.java | package com.tpb.projects.data.models;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by theo on 18/12/16.
*/
public class User extends DataModel {
private static final String TAG = User.class.getSimpleName();
private User() {
}
private static final String LOGIN = "login";
private String login;
private int id;
private static final String AVATAR_URL = "avatar_url";
private String avatarUrl;
private static final String URL = "url";
private String url;
private static final String REPOS_URL = "repos_url";
private String reposUrl;
private static final String NAME = "name";
private String name;
private static final String LOCATION = "location";
private String location;
private static final String EMAIL = "email";
private String email;
private static final String REPOS = "public_repos";
private int repos;
private static final String FOLLOWERS = "followers";
private int followers;
private static final String BIO = "bio";
private String bio;
public int getId() {
return id;
}
public String getLogin() {
return login;
}
public String getAvatarUrl() {
return avatarUrl;
}
public String getUrl() {
return url;
}
public String getReposUrl() {
return reposUrl;
}
@Nullable
public String getName() {
return name;
}
@Nullable
public String getLocation() {
return location;
}
public String getEmail() {
return email;
}
public int getRepos() {
return repos;
}
public int getFollowers() {
return followers;
}
public String getBio() {
return bio;
}
public static User parse(JSONObject obj) {
final User u = new User();
try {
u.id = obj.getInt(ID);
u.login = obj.getString(LOGIN);
u.avatarUrl = obj.getString(AVATAR_URL);
u.url = obj.getString(URL);
u.reposUrl = obj.getString(REPOS_URL);
if(obj.has(REPOS)) u.repos = obj.getInt(REPOS);
if(obj.has(FOLLOWERS)) u.followers = obj.getInt(FOLLOWERS);
if(obj.has(BIO)) u.bio = obj.getString(BIO);
if(obj.has(EMAIL)) u.email = obj.getString(EMAIL);
if(obj.has(LOCATION)) u.location = obj.getString(LOCATION);
if(obj.has(NAME)) u.name = obj.getString(NAME);
} catch(JSONException jse) {
Log.e(TAG, "parse: ", jse);
}
return u;
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", id=" + id +
", avatarUrl='" + avatarUrl + '\'' +
", url='" + url + '\'' +
", reposUrl='" + reposUrl + '\'' +
", name='" + name + '\'' +
", location='" + location + '\'' +
", email='" + email + '\'' +
", repos=" + repos +
", followers=" + followers +
", bio='" + bio + '\'' +
'}';
}
}
| Added parse to JSONObject to User.
| app/src/main/java/com/tpb/projects/data/models/User.java | Added parse to JSONObject to User. | <ide><path>pp/src/main/java/com/tpb/projects/data/models/User.java
<ide> return u;
<ide> }
<ide>
<add> public static JSONObject parse(User user) {
<add> final JSONObject obj = new JSONObject();
<add> try {
<add> obj.put(ID, user.id);
<add> obj.put(LOGIN, user.login);
<add> obj.put(AVATAR_URL, user.avatarUrl);
<add> obj.put(URL, user.url);
<add> obj.put(REPOS_URL, user.reposUrl);
<add> obj.put(REPOS, user.repos);
<add> obj.put(FOLLOWERS, user.followers);
<add> if(user.bio != null) obj.put(BIO, user.bio);
<add> if(user.email != null) obj.put(EMAIL, user.email);
<add> if(user.location != null) obj.put(LOCATION, user.location);
<add> if(user.name != null) obj.put(NAME, user.name);
<add> } catch(JSONException jse) {
<add> Log.e(TAG, "parse: ", jse);
<add> }
<add> return obj;
<add> }
<add>
<ide> @Override
<ide> public String toString() {
<ide> return "User{" + |
|
Java | apache-2.0 | ad01baedbfacc4d7ccb375c6af6f79ff2c478509 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.lucene.index;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Merges segments of approximately equal size, subject to
* an allowed number of segments per tier. This is similar
* to {@link LogByteSizeMergePolicy}, except this merge
* policy is able to merge non-adjacent segment, and
* separates how many segments are merged at once ({@link
* #setMaxMergeAtOnce}) from how many segments are allowed
* per tier ({@link #setSegmentsPerTier}). This merge
* policy also does not over-merge (i.e. cascade merges).
*
* <p>For normal merging, this policy first computes a
* "budget" of how many segments are allowed to be in the
* index. If the index is over-budget, then the policy
* sorts segments by decreasing size (pro-rating by percent
* deletes), and then finds the least-cost merge. Merge
* cost is measured by a combination of the "skew" of the
* merge (size of largest segment divided by smallest segment),
* total merge size and percent deletes reclaimed,
* so that merges with lower skew, smaller size
* and those reclaiming more deletes, are
* favored.
*
* <p>If a merge will produce a segment that's larger than
* {@link #setMaxMergedSegmentMB}, then the policy will
* merge fewer segments (down to 1 at once, if that one has
* deletions) to keep the segment size under budget.
*
* <p><b>NOTE</b>: this policy freely merges non-adjacent
* segments; if this is a problem, use {@link
* LogMergePolicy}.
*
* <p><b>NOTE</b>: This policy always merges by byte size
* of the segments, always pro-rates by percent deletes
*
* <p><b>NOTE</b> Starting with Lucene 7.5, there are several changes:
*
* - findForcedMerges and findForcedDeletesMerges) respect the max segment
* size by default.
*
* - When findforcedmerges is called with maxSegmentCount other than 1,
* the resulting index is not guaranteed to have <= maxSegmentCount segments.
* Rather it is on a "best effort" basis. Specifically the theoretical ideal
* segment size is calculated and a "fudge factor" of 25% is added as the
* new maxSegmentSize, which is respected.
*
* - findForcedDeletesMerges will not produce segments greater than
* maxSegmentSize.
*
* @lucene.experimental
*/
// TODO
// - we could try to take into account whether a large
// merge is already running (under CMS) and then bias
// ourselves towards picking smaller merges if so (or,
// maybe CMS should do so)
public class TieredMergePolicy extends MergePolicy {
/** Default noCFSRatio. If a merge's size is {@code >= 10%} of
* the index, then we disable compound file for it.
* @see MergePolicy#setNoCFSRatio */
public static final double DEFAULT_NO_CFS_RATIO = 0.1;
private int maxMergeAtOnce = 10;
private long maxMergedSegmentBytes = 5*1024*1024*1024L;
private int maxMergeAtOnceExplicit = 30;
private long floorSegmentBytes = 2*1024*1024L;
private double segsPerTier = 10.0;
private double forceMergeDeletesPctAllowed = 10.0;
private double reclaimDeletesWeight = 2.0;
//TODO breaking this up into two JIRAs, see LUCENE-8263
//private double indexPctDeletedTarget = 20.0;
/** Sole constructor, setting all settings to their
* defaults. */
public TieredMergePolicy() {
super(DEFAULT_NO_CFS_RATIO, MergePolicy.DEFAULT_MAX_CFS_SEGMENT_SIZE);
}
/** Maximum number of segments to be merged at a time
* during "normal" merging. For explicit merging (eg,
* forceMerge or forceMergeDeletes was called), see {@link
* #setMaxMergeAtOnceExplicit}. Default is 10. */
public TieredMergePolicy setMaxMergeAtOnce(int v) {
if (v < 2) {
throw new IllegalArgumentException("maxMergeAtOnce must be > 1 (got " + v + ")");
}
maxMergeAtOnce = v;
return this;
}
private enum MERGE_TYPE {
NATURAL, FORCE_MERGE, FORCE_MERGE_DELETES
}
/** Returns the current maxMergeAtOnce setting.
*
* @see #setMaxMergeAtOnce */
public int getMaxMergeAtOnce() {
return maxMergeAtOnce;
}
// TODO: should addIndexes do explicit merging, too? And,
// if user calls IW.maybeMerge "explicitly"
/** Maximum number of segments to be merged at a time,
* during forceMerge or forceMergeDeletes. Default is 30. */
public TieredMergePolicy setMaxMergeAtOnceExplicit(int v) {
if (v < 2) {
throw new IllegalArgumentException("maxMergeAtOnceExplicit must be > 1 (got " + v + ")");
}
maxMergeAtOnceExplicit = v;
return this;
}
/** Returns the current maxMergeAtOnceExplicit setting.
*
* @see #setMaxMergeAtOnceExplicit */
public int getMaxMergeAtOnceExplicit() {
return maxMergeAtOnceExplicit;
}
/** Maximum sized segment to produce during
* normal merging. This setting is approximate: the
* estimate of the merged segment size is made by summing
* sizes of to-be-merged segments (compensating for
* percent deleted docs). Default is 5 GB. */
public TieredMergePolicy setMaxMergedSegmentMB(double v) {
if (v < 0.0) {
throw new IllegalArgumentException("maxMergedSegmentMB must be >=0 (got " + v + ")");
}
v *= 1024 * 1024;
maxMergedSegmentBytes = v > Long.MAX_VALUE ? Long.MAX_VALUE : (long) v;
return this;
}
//TODO: See LUCENE-8263
// /** Returns the current setIndexPctDeletedTarget setting.
// *
// * @see #setIndexPctDeletedTarget */
// public double getIndexPctDeletedTarget() {
// return indexPctDeletedTarget;
// }
//
// /** Controls what percentage of documents in the index need to be deleted before
// * regular merging considers max segments with more than 50% live documents
// * for merging*/
// public TieredMergePolicy setIndexPctDeletedTarget(double v) {
// if (v < 10.0) {
// throw new IllegalArgumentException("indexPctDeletedTarget must be >= 10.0 (got " + v + ")");
// }
// indexPctDeletedTarget = v;
// return this;
// }
/** Returns the current maxMergedSegmentMB setting.
*
* @see #setMaxMergedSegmentMB */
public double getMaxMergedSegmentMB() {
return maxMergedSegmentBytes/1024/1024.;
}
/** Controls how aggressively merges that reclaim more
* deletions are favored. Higher values will more
* aggressively target merges that reclaim deletions, but
* be careful not to go so high that way too much merging
* takes place; a value of 3.0 is probably nearly too
* high. A value of 0.0 means deletions don't impact
* merge selection. */
public TieredMergePolicy setReclaimDeletesWeight(double v) {
if (v < 0.0) {
throw new IllegalArgumentException("reclaimDeletesWeight must be >= 0.0 (got " + v + ")");
}
reclaimDeletesWeight = v;
return this;
}
/** See {@link #setReclaimDeletesWeight}. */
public double getReclaimDeletesWeight() {
return reclaimDeletesWeight;
}
/** Segments smaller than this are "rounded up" to this
* size, ie treated as equal (floor) size for merge
* selection. This is to prevent frequent flushing of
* tiny segments from allowing a long tail in the index.
* Default is 2 MB. */
public TieredMergePolicy setFloorSegmentMB(double v) {
if (v <= 0.0) {
throw new IllegalArgumentException("floorSegmentMB must be > 0.0 (got " + v + ")");
}
v *= 1024 * 1024;
floorSegmentBytes = v > Long.MAX_VALUE ? Long.MAX_VALUE : (long) v;
return this;
}
/** Returns the current floorSegmentMB.
*
* @see #setFloorSegmentMB */
public double getFloorSegmentMB() {
return floorSegmentBytes/(1024*1024.);
}
/** When forceMergeDeletes is called, we only merge away a
* segment if its delete percentage is over this
* threshold. Default is 10%. */
public TieredMergePolicy setForceMergeDeletesPctAllowed(double v) {
if (v < 0.0 || v > 100.0) {
throw new IllegalArgumentException("forceMergeDeletesPctAllowed must be between 0.0 and 100.0 inclusive (got " + v + ")");
}
forceMergeDeletesPctAllowed = v;
return this;
}
/** Returns the current forceMergeDeletesPctAllowed setting.
*
* @see #setForceMergeDeletesPctAllowed */
public double getForceMergeDeletesPctAllowed() {
return forceMergeDeletesPctAllowed;
}
/** Sets the allowed number of segments per tier. Smaller
* values mean more merging but fewer segments.
*
* <p><b>NOTE</b>: this value should be {@code >=} the {@link
* #setMaxMergeAtOnce} otherwise you'll force too much
* merging to occur.</p>
*
* <p>Default is 10.0.</p> */
public TieredMergePolicy setSegmentsPerTier(double v) {
if (v < 2.0) {
throw new IllegalArgumentException("segmentsPerTier must be >= 2.0 (got " + v + ")");
}
segsPerTier = v;
return this;
}
/** Returns the current segmentsPerTier setting.
*
* @see #setSegmentsPerTier */
public double getSegmentsPerTier() {
return segsPerTier;
}
private static class SegmentSizeAndDocs {
private final SegmentCommitInfo segInfo;
private final long sizeInBytes;
private final int delCount;
private final int maxDoc;
private final String name;
SegmentSizeAndDocs(SegmentCommitInfo info, final long sizeInBytes, final int segDelCount) throws IOException {
segInfo = info;
this.name = info.info.name;
this.sizeInBytes = sizeInBytes;
this.delCount = segDelCount;
this.maxDoc = info.info.maxDoc();
}
}
/** Holds score and explanation for a single candidate
* merge. */
protected static abstract class MergeScore {
/** Sole constructor. (For invocation by subclass
* constructors, typically implicit.) */
protected MergeScore() {
}
/** Returns the score for this merge candidate; lower
* scores are better. */
abstract double getScore();
/** Human readable explanation of how the merge got this
* score. */
abstract String getExplanation();
}
// The size can change concurrently while we are running here, because deletes
// are now applied concurrently, and this can piss off TimSort! So we
// call size() once per segment and sort by that:
private List<SegmentSizeAndDocs> getSortedBySegmentSize(final SegmentInfos infos, final MergeContext mergeContext) throws IOException {
List<SegmentSizeAndDocs> sortedBySize = new ArrayList<>();
for (SegmentCommitInfo info : infos) {
sortedBySize.add(new SegmentSizeAndDocs(info, size(info, mergeContext), mergeContext.numDeletesToMerge(info)));
}
sortedBySize.sort((o1, o2) -> {
// Sort by largest size:
int cmp = Long.compare(o2.sizeInBytes, o1.sizeInBytes);
if (cmp == 0) {
cmp = o1.name.compareTo(o2.name);
}
return cmp;
});
return sortedBySize;
}
@Override
public MergeSpecification findMerges(MergeTrigger mergeTrigger, SegmentInfos infos, MergeContext mergeContext) throws IOException {
final Set<SegmentCommitInfo> merging = mergeContext.getMergingSegments();
// Compute total index bytes & print details about the index
long totIndexBytes = 0;
long minSegmentBytes = Long.MAX_VALUE;
int totalDelDocs = 0;
int totalMaxDoc = 0;
long mergingBytes = 0;
List<SegmentSizeAndDocs> sortedInfos = getSortedBySegmentSize(infos, mergeContext);
Iterator<SegmentSizeAndDocs> iter = sortedInfos.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
final long segBytes = segSizeDocs.sizeInBytes;
if (verbose(mergeContext)) {
String extra = merging.contains(segSizeDocs.segInfo) ? " [merging]" : "";
if (segBytes >= maxMergedSegmentBytes) {
extra += " [skip: too large]";
} else if (segBytes < floorSegmentBytes) {
extra += " [floored]";
}
message(" seg=" + segString(mergeContext, Collections.singleton(segSizeDocs.segInfo)) + " size=" + String.format(Locale.ROOT, "%.3f", segBytes / 1024 / 1024.) + " MB" + extra, mergeContext);
}
if (merging.contains(segSizeDocs.segInfo)) {
mergingBytes += segSizeDocs.sizeInBytes;
iter.remove();
} else {
totalDelDocs += segSizeDocs.delCount;
totalMaxDoc += segSizeDocs.maxDoc;
}
minSegmentBytes = Math.min(segBytes, minSegmentBytes);
totIndexBytes += segBytes;
}
assert totalMaxDoc >= 0;
assert totalDelDocs >= 0;
// If we have too-large segments, grace them out of the maximum segment count
// If we're above certain thresholds, we can merge very large segments.
double totalDelPct = (double) totalDelDocs / (double) totalMaxDoc;
//TODO: See LUCENE-8263
//double targetAsPct = indexPctDeletedTarget / 100.0;
double targetAsPct = 0.5;
int tooBigCount = 0;
iter = sortedInfos.iterator();
// remove large segments from consideration under two conditions.
// 1> Overall percent deleted docs relatively small and this segment is larger than 50% maxSegSize
// 2> overall percent deleted docs large and this segment is large and has few deleted docs
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
double segDelPct = (double) segSizeDocs.delCount / (double) segSizeDocs.maxDoc;
if (segSizeDocs.sizeInBytes > maxMergedSegmentBytes / 2 && (totalDelPct < targetAsPct || segDelPct < targetAsPct)) {
iter.remove();
tooBigCount++; // Just for reporting purposes.
totIndexBytes -= segSizeDocs.sizeInBytes;
}
}
// Compute max allowed segments in the index
long levelSize = Math.max(minSegmentBytes, floorSegmentBytes);
long bytesLeft = totIndexBytes;
double allowedSegCount = 0;
while (true) {
final double segCountLevel = bytesLeft / (double) levelSize;
if (segCountLevel < segsPerTier) {
allowedSegCount += Math.ceil(segCountLevel);
break;
}
allowedSegCount += segsPerTier;
bytesLeft -= segsPerTier * levelSize;
levelSize *= maxMergeAtOnce;
}
if (verbose(mergeContext) && tooBigCount > 0) {
message(" allowedSegmentCount=" + allowedSegCount + " vs count=" + infos.size() +
" (eligible count=" + sortedInfos.size() + ") tooBigCount= " + tooBigCount, mergeContext);
}
return doFindMerges(sortedInfos, maxMergedSegmentBytes, maxMergeAtOnce, (int) allowedSegCount, MERGE_TYPE.NATURAL,
mergeContext, mergingBytes >= maxMergedSegmentBytes);
}
private MergeSpecification doFindMerges(List<SegmentSizeAndDocs> sortedEligibleInfos,
final long maxMergedSegmentBytes,
final int maxMergeAtOnce, final int allowedSegCount,
final MERGE_TYPE mergeType,
MergeContext mergeContext,
boolean maxMergeIsRunning) throws IOException {
List<SegmentSizeAndDocs> sortedEligible = new ArrayList<>(sortedEligibleInfos);
Map<SegmentCommitInfo, SegmentSizeAndDocs> segInfosSizes = new HashMap<>();
for (SegmentSizeAndDocs segSizeDocs : sortedEligible) {
segInfosSizes.put(segSizeDocs.segInfo, segSizeDocs);
}
int originalSortedSize = sortedEligible.size();
if (verbose(mergeContext)) {
message("findMerges: " + originalSortedSize + " segments", mergeContext);
}
if (originalSortedSize == 0) {
return null;
}
final Set<SegmentCommitInfo> toBeMerged = new HashSet<>();
MergeSpecification spec = null;
// Cycle to possibly select more than one merge:
// The trigger point for total deleted documents in the index leads to a bunch of large segment
// merges at the same time. So only put one large merge in the list of merges per cycle. We'll pick up another
// merge next time around.
boolean haveOneLargeMerge = false;
while (true) {
// Gather eligible segments for merging, ie segments
// not already being merged and not already picked (by
// prior iteration of this loop) for merging:
// Remove ineligible segments. These are either already being merged or already picked by prior iterations
Iterator<SegmentSizeAndDocs> iter = sortedEligible.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
if (toBeMerged.contains(segSizeDocs.segInfo)) {
iter.remove();
}
}
if (verbose(mergeContext)) {
message(" allowedSegmentCount=" + allowedSegCount + " vs count=" + originalSortedSize + " (eligible count=" + sortedEligible.size() + ")", mergeContext);
}
if (sortedEligible.size() == 0) {
return spec;
}
if (allowedSegCount != Integer.MAX_VALUE && sortedEligible.size() <= allowedSegCount && mergeType == MERGE_TYPE.NATURAL) {
return spec;
}
// OK we are over budget -- find best merge!
MergeScore bestScore = null;
List<SegmentCommitInfo> best = null;
boolean bestTooLarge = false;
long bestMergeBytes = 0;
// Consider all merge starts.
int lim = sortedEligible.size() - maxMergeAtOnce; // assume the usual case of background merging.
if (mergeType != MERGE_TYPE.NATURAL) { // The unusual case of forceMerge or expungeDeletes.
// The incoming eligible list will have only segments with > forceMergeDeletesPctAllowed in the case of
// findForcedDeletesMerges and segments with < max allowed size in the case of optimize.
// If forcing, we must allow singleton merges.
lim = sortedEligible.size() - 1;
}
for (int startIdx = 0; startIdx <= lim; startIdx++) {
long totAfterMergeBytes = 0;
final List<SegmentCommitInfo> candidate = new ArrayList<>();
boolean hitTooLarge = false;
long bytesThisMerge = 0;
for (int idx = startIdx; idx < sortedEligible.size() && candidate.size() < maxMergeAtOnce && bytesThisMerge < maxMergedSegmentBytes; idx++) {
final SegmentSizeAndDocs segSizeDocs = sortedEligible.get(idx);
final long segBytes = segSizeDocs.sizeInBytes;
if (totAfterMergeBytes + segBytes > maxMergedSegmentBytes) {
hitTooLarge = true;
if (candidate.size() == 0) {
// We should never have something coming in that _cannot_ be merged, so handle singleton merges
candidate.add(segSizeDocs.segInfo);
bytesThisMerge += segBytes;
}
// NOTE: we continue, so that we can try
// "packing" smaller segments into this merge
// to see if we can get closer to the max
// size; this in general is not perfect since
// this is really "bin packing" and we'd have
// to try different permutations.
continue;
}
candidate.add(segSizeDocs.segInfo);
bytesThisMerge += segBytes;
totAfterMergeBytes += segBytes;
}
// We should never see an empty candidate: we iterated over maxMergeAtOnce
// segments, and already pre-excluded the too-large segments:
assert candidate.size() > 0;
// A singleton merge with no deletes makes no sense. We can get here when forceMerge is looping around...
if (candidate.size() == 1) {
SegmentSizeAndDocs segSizeDocs = segInfosSizes.get(candidate.get(0));
if (segSizeDocs.delCount == 0) {
continue;
}
}
final MergeScore score = score(candidate, hitTooLarge, segInfosSizes);
if (verbose(mergeContext)) {
message(" maybe=" + segString(mergeContext, candidate) + " score=" + score.getScore() + " " + score.getExplanation() + " tooLarge=" + hitTooLarge + " size=" + String.format(Locale.ROOT, "%.3f MB", totAfterMergeBytes/1024./1024.), mergeContext);
}
if ((bestScore == null || score.getScore() < bestScore.getScore()) && (!hitTooLarge || !maxMergeIsRunning)) {
best = candidate;
bestScore = score;
bestTooLarge = hitTooLarge;
bestMergeBytes = totAfterMergeBytes;
}
}
if (best == null) {
return spec;
}
// The mergeType == FORCE_MERGE_DELETES behaves as the code does currently and can create a large number of
// concurrent big merges. If we make findForcedDeletesMerges behave as findForcedMerges and cycle through
// we should remove this.
if (haveOneLargeMerge == false || bestTooLarge == false || mergeType == MERGE_TYPE.FORCE_MERGE_DELETES) {
haveOneLargeMerge |= bestTooLarge;
if (spec == null) {
spec = new MergeSpecification();
}
final OneMerge merge = new OneMerge(best);
spec.add(merge);
if (verbose(mergeContext)) {
message(" add merge=" + segString(mergeContext, merge.segments) + " size=" + String.format(Locale.ROOT, "%.3f MB", bestMergeBytes / 1024. / 1024.) + " score=" + String.format(Locale.ROOT, "%.3f", bestScore.getScore()) + " " + bestScore.getExplanation() + (bestTooLarge ? " [max merge]" : ""), mergeContext);
}
}
// whether we're going to return this list in the spec of not, we need to remove it from
// consideration on the next loop.
toBeMerged.addAll(best);
}
}
/** Expert: scores one merge; subclasses can override. */
protected MergeScore score(List<SegmentCommitInfo> candidate, boolean hitTooLarge, Map<SegmentCommitInfo, SegmentSizeAndDocs> segmentsSizes) throws IOException {
long totBeforeMergeBytes = 0;
long totAfterMergeBytes = 0;
long totAfterMergeBytesFloored = 0;
for(SegmentCommitInfo info : candidate) {
final long segBytes = segmentsSizes.get(info).sizeInBytes;
totAfterMergeBytes += segBytes;
totAfterMergeBytesFloored += floorSize(segBytes);
totBeforeMergeBytes += info.sizeInBytes();
}
// Roughly measure "skew" of the merge, i.e. how
// "balanced" the merge is (whether the segments are
// about the same size), which can range from
// 1.0/numSegsBeingMerged (good) to 1.0 (poor). Heavily
// lopsided merges (skew near 1.0) is no good; it means
// O(N^2) merge cost over time:
final double skew;
if (hitTooLarge) {
// Pretend the merge has perfect skew; skew doesn't
// matter in this case because this merge will not
// "cascade" and so it cannot lead to N^2 merge cost
// over time:
skew = 1.0/maxMergeAtOnce;
} else {
skew = ((double) floorSize(segmentsSizes.get(candidate.get(0)).sizeInBytes)) / totAfterMergeBytesFloored;
}
// Strongly favor merges with less skew (smaller
// mergeScore is better):
double mergeScore = skew;
// Gently favor smaller merges over bigger ones. We
// don't want to make this exponent too large else we
// can end up doing poor merges of small segments in
// order to avoid the large merges:
mergeScore *= Math.pow(totAfterMergeBytes, 0.05);
// Strongly favor merges that reclaim deletes:
final double nonDelRatio = ((double) totAfterMergeBytes)/totBeforeMergeBytes;
mergeScore *= Math.pow(nonDelRatio, reclaimDeletesWeight);
final double finalMergeScore = mergeScore;
return new MergeScore() {
@Override
public double getScore() {
return finalMergeScore;
}
@Override
public String getExplanation() {
return "skew=" + String.format(Locale.ROOT, "%.3f", skew) + " nonDelRatio=" + String.format(Locale.ROOT, "%.3f", nonDelRatio);
}
};
}
@Override
public MergeSpecification findForcedMerges(SegmentInfos infos, int maxSegmentCount, Map<SegmentCommitInfo,Boolean> segmentsToMerge, MergeContext mergeContext) throws IOException {
if (verbose(mergeContext)) {
message("findForcedMerges maxSegmentCount=" + maxSegmentCount + " infos=" + segString(mergeContext, infos) +
" segmentsToMerge=" + segmentsToMerge, mergeContext);
}
List<SegmentSizeAndDocs> sortedSizeAndDocs = getSortedBySegmentSize(infos, mergeContext);
long totalMergeBytes = 0;
final Set<SegmentCommitInfo> merging = mergeContext.getMergingSegments();
// Trim the list down, remove if we're respecting max segment size and it's not original. Presumably it's been merged before and
// is close enough to the max segment size we shouldn't add it in again.
Iterator<SegmentSizeAndDocs> iter = sortedSizeAndDocs.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
final Boolean isOriginal = segmentsToMerge.get(segSizeDocs.segInfo);
if (isOriginal == null) {
iter.remove();
} else {
if (merging.contains(segSizeDocs.segInfo)) {
iter.remove();
} else {
totalMergeBytes += segSizeDocs.sizeInBytes;
}
}
}
long maxMergeBytes = maxMergedSegmentBytes;
// Set the maximum segment size based on how many segments have been specified.
if (maxSegmentCount == 1) maxMergeBytes = Long.MAX_VALUE;
else if (maxSegmentCount != Integer.MAX_VALUE) {
// Fudge this up a bit so we have a better chance of not having to rewrite segments. If we use the exact size,
// it's almost guaranteed that the segments won't fit perfectly and we'll be left with more segments than
// we want and have to re-merge in the code at the bottom of this method.
maxMergeBytes = Math.max((long) (((double) totalMergeBytes / (double) maxSegmentCount)), maxMergedSegmentBytes);
maxMergeBytes = (long) ((double) maxMergeBytes * 1.25);
}
iter = sortedSizeAndDocs.iterator();
boolean foundDeletes = false;
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
Boolean isOriginal = segmentsToMerge.get(segSizeDocs.segInfo);
if (segSizeDocs.delCount != 0) { // This is forceMerge, all segments with deleted docs should be merged.
if (isOriginal != null && isOriginal) {
foundDeletes = true;
}
continue;
}
// Let the scoring handle whether to merge large segments.
if (maxSegmentCount == Integer.MAX_VALUE && isOriginal != null && isOriginal == false) {
iter.remove();
}
// Don't try to merge a segment with no deleted docs that's over the max size.
if (maxSegmentCount != Integer.MAX_VALUE && segSizeDocs.sizeInBytes >= maxMergeBytes) {
iter.remove();
}
}
// Nothing to merge this round.
if (sortedSizeAndDocs.size() == 0) {
return null;
}
// We should never bail if there are segments that have deleted documents, all deleted docs should be purged.
if (foundDeletes == false) {
SegmentCommitInfo infoZero = sortedSizeAndDocs.get(0).segInfo;
if ((maxSegmentCount != Integer.MAX_VALUE && maxSegmentCount > 1 && sortedSizeAndDocs.size() <= maxSegmentCount) ||
(maxSegmentCount == 1 && sortedSizeAndDocs.size() == 1 && (segmentsToMerge.get(infoZero) != null || isMerged(infos, infoZero, mergeContext)))) {
if (verbose(mergeContext)) {
message("already merged", mergeContext);
}
return null;
}
}
if (verbose(mergeContext)) {
message("eligible=" + sortedSizeAndDocs, mergeContext);
}
// This is the special case of merging down to one segment
if (sortedSizeAndDocs.size() < maxMergeAtOnceExplicit && maxSegmentCount == 1 && totalMergeBytes < maxMergeBytes) {
MergeSpecification spec = new MergeSpecification();
List<SegmentCommitInfo> allOfThem = new ArrayList<>();
for (SegmentSizeAndDocs segSizeDocs : sortedSizeAndDocs) {
allOfThem.add(segSizeDocs.segInfo);
}
spec.add(new OneMerge(allOfThem));
return spec;
}
MergeSpecification spec = doFindMerges(sortedSizeAndDocs, maxMergeBytes, maxMergeAtOnceExplicit,
maxSegmentCount, MERGE_TYPE.FORCE_MERGE, mergeContext, false);
return spec;
}
@Override
public MergeSpecification findForcedDeletesMerges(SegmentInfos infos, MergeContext mergeContext) throws IOException {
if (verbose(mergeContext)) {
message("findForcedDeletesMerges infos=" + segString(mergeContext, infos) + " forceMergeDeletesPctAllowed=" + forceMergeDeletesPctAllowed, mergeContext);
}
// First do a quick check that there's any work to do.
// NOTE: this makes BaseMergePOlicyTestCase.testFindForcedDeletesMerges work
final Set<SegmentCommitInfo> merging = mergeContext.getMergingSegments();
boolean haveWork = false;
for(SegmentCommitInfo info : infos) {
int delCount = mergeContext.numDeletesToMerge(info);
assert assertDelCount(delCount, info);
double pctDeletes = 100.*((double) delCount)/info.info.maxDoc();
if (pctDeletes > forceMergeDeletesPctAllowed && !merging.contains(info)) {
haveWork = true;
break;
}
}
if (haveWork == false) {
return null;
}
List<SegmentSizeAndDocs> sortedInfos = getSortedBySegmentSize(infos, mergeContext);
Iterator<SegmentSizeAndDocs> iter = sortedInfos.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
double pctDeletes = 100. * ((double) segSizeDocs.delCount / (double) segSizeDocs.maxDoc);
if (merging.contains(segSizeDocs.segInfo) || pctDeletes <= forceMergeDeletesPctAllowed) {
iter.remove();
}
}
if (verbose(mergeContext)) {
message("eligible=" + sortedInfos, mergeContext);
}
return doFindMerges(sortedInfos, maxMergedSegmentBytes,
maxMergeAtOnceExplicit, Integer.MAX_VALUE, MERGE_TYPE.FORCE_MERGE_DELETES, mergeContext, false);
}
private long floorSize(long bytes) {
return Math.max(floorSegmentBytes, bytes);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[" + getClass().getSimpleName() + ": ");
sb.append("maxMergeAtOnce=").append(maxMergeAtOnce).append(", ");
sb.append("maxMergeAtOnceExplicit=").append(maxMergeAtOnceExplicit).append(", ");
sb.append("maxMergedSegmentMB=").append(maxMergedSegmentBytes/1024/1024.).append(", ");
sb.append("floorSegmentMB=").append(floorSegmentBytes/1024/1024.).append(", ");
sb.append("forceMergeDeletesPctAllowed=").append(forceMergeDeletesPctAllowed).append(", ");
sb.append("segmentsPerTier=").append(segsPerTier).append(", ");
sb.append("maxCFSSegmentSizeMB=").append(getMaxCFSSegmentSizeMB()).append(", ");
sb.append("noCFSRatio=").append(noCFSRatio).append(", ");
sb.append("reclaimDeletesWeight=").append(reclaimDeletesWeight);
//TODO: See LUCENE-8263
//sb.append("indexPctDeletedTarget=").append(indexPctDeletedTarget);
return sb.toString();
}
}
| lucene/core/src/java/org/apache/lucene/index/TieredMergePolicy.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.lucene.index;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Merges segments of approximately equal size, subject to
* an allowed number of segments per tier. This is similar
* to {@link LogByteSizeMergePolicy}, except this merge
* policy is able to merge non-adjacent segment, and
* separates how many segments are merged at once ({@link
* #setMaxMergeAtOnce}) from how many segments are allowed
* per tier ({@link #setSegmentsPerTier}). This merge
* policy also does not over-merge (i.e. cascade merges).
*
* <p>For normal merging, this policy first computes a
* "budget" of how many segments are allowed to be in the
* index. If the index is over-budget, then the policy
* sorts segments by decreasing size (pro-rating by percent
* deletes), and then finds the least-cost merge. Merge
* cost is measured by a combination of the "skew" of the
* merge (size of largest segment divided by smallest segment),
* total merge size and percent deletes reclaimed,
* so that merges with lower skew, smaller size
* and those reclaiming more deletes, are
* favored.
*
* <p>If a merge will produce a segment that's larger than
* {@link #setMaxMergedSegmentMB}, then the policy will
* merge fewer segments (down to 1 at once, if that one has
* deletions) to keep the segment size under budget.
*
* <p><b>NOTE</b>: this policy freely merges non-adjacent
* segments; if this is a problem, use {@link
* LogMergePolicy}.
*
* <p><b>NOTE</b>: This policy always merges by byte size
* of the segments, always pro-rates by percent deletes
*
* <p><b>NOTE</b> Starting with Lucene 7.5, there are several changes:
*
* - findForcedMerges and findForcedDeletesMerges) respect the max segment
* size by default.
*
* - When findforcedmerges is called with maxSegmentCount other than 1,
* the resulting index is not guaranteed to have <= maxSegmentCount segments.
* Rather it is on a "best effort" basis. Specifically the theoretical ideal
* segment size is calculated and a "fudge factor" of 25% is added as the
* new maxSegmentSize, which is respected.
*
* - findForcedDeletesMerges will not produce segments greater than
* maxSegmentSize.
*
* @lucene.experimental
*/
// TODO
// - we could try to take into account whether a large
// merge is already running (under CMS) and then bias
// ourselves towards picking smaller merges if so (or,
// maybe CMS should do so)
public class TieredMergePolicy extends MergePolicy {
/** Default noCFSRatio. If a merge's size is {@code >= 10%} of
* the index, then we disable compound file for it.
* @see MergePolicy#setNoCFSRatio */
public static final double DEFAULT_NO_CFS_RATIO = 0.1;
private int maxMergeAtOnce = 10;
private long maxMergedSegmentBytes = 5*1024*1024*1024L;
private int maxMergeAtOnceExplicit = 30;
private long floorSegmentBytes = 2*1024*1024L;
private double segsPerTier = 10.0;
private double forceMergeDeletesPctAllowed = 10.0;
private double reclaimDeletesWeight = 2.0;
//TODO breaking this up into two JIRAs, see LUCENE-8263
//private double indexPctDeletedTarget = 20.0;
/** Sole constructor, setting all settings to their
* defaults. */
public TieredMergePolicy() {
super(DEFAULT_NO_CFS_RATIO, MergePolicy.DEFAULT_MAX_CFS_SEGMENT_SIZE);
}
/** Maximum number of segments to be merged at a time
* during "normal" merging. For explicit merging (eg,
* forceMerge or forceMergeDeletes was called), see {@link
* #setMaxMergeAtOnceExplicit}. Default is 10. */
public TieredMergePolicy setMaxMergeAtOnce(int v) {
if (v < 2) {
throw new IllegalArgumentException("maxMergeAtOnce must be > 1 (got " + v + ")");
}
maxMergeAtOnce = v;
return this;
}
private enum MERGE_TYPE {
NATURAL, FORCE_MERGE, FORCE_MERGE_DELETES
}
/** Returns the current maxMergeAtOnce setting.
*
* @see #setMaxMergeAtOnce */
public int getMaxMergeAtOnce() {
return maxMergeAtOnce;
}
// TODO: should addIndexes do explicit merging, too? And,
// if user calls IW.maybeMerge "explicitly"
/** Maximum number of segments to be merged at a time,
* during forceMerge or forceMergeDeletes. Default is 30. */
public TieredMergePolicy setMaxMergeAtOnceExplicit(int v) {
if (v < 2) {
throw new IllegalArgumentException("maxMergeAtOnceExplicit must be > 1 (got " + v + ")");
}
maxMergeAtOnceExplicit = v;
return this;
}
/** Returns the current maxMergeAtOnceExplicit setting.
*
* @see #setMaxMergeAtOnceExplicit */
public int getMaxMergeAtOnceExplicit() {
return maxMergeAtOnceExplicit;
}
/** Maximum sized segment to produce during
* normal merging. This setting is approximate: the
* estimate of the merged segment size is made by summing
* sizes of to-be-merged segments (compensating for
* percent deleted docs). Default is 5 GB. */
public TieredMergePolicy setMaxMergedSegmentMB(double v) {
if (v < 0.0) {
throw new IllegalArgumentException("maxMergedSegmentMB must be >=0 (got " + v + ")");
}
v *= 1024 * 1024;
maxMergedSegmentBytes = v > Long.MAX_VALUE ? Long.MAX_VALUE : (long) v;
return this;
}
//TODO: See LUCENE-8263
// /** Returns the current setIndexPctDeletedTarget setting.
// *
// * @see #setIndexPctDeletedTarget */
// public double getIndexPctDeletedTarget() {
// return indexPctDeletedTarget;
// }
//
// /** Controls what percentage of documents in the index need to be deleted before
// * regular merging considers max segments with more than 50% live documents
// * for merging*/
// public TieredMergePolicy setIndexPctDeletedTarget(double v) {
// if (v < 10.0) {
// throw new IllegalArgumentException("indexPctDeletedTarget must be >= 10.0 (got " + v + ")");
// }
// indexPctDeletedTarget = v;
// return this;
// }
/** Returns the current maxMergedSegmentMB setting.
*
* @see #setMaxMergedSegmentMB */
public double getMaxMergedSegmentMB() {
return maxMergedSegmentBytes/1024/1024.;
}
/** Controls how aggressively merges that reclaim more
* deletions are favored. Higher values will more
* aggressively target merges that reclaim deletions, but
* be careful not to go so high that way too much merging
* takes place; a value of 3.0 is probably nearly too
* high. A value of 0.0 means deletions don't impact
* merge selection. */
public TieredMergePolicy setReclaimDeletesWeight(double v) {
if (v < 0.0) {
throw new IllegalArgumentException("reclaimDeletesWeight must be >= 0.0 (got " + v + ")");
}
reclaimDeletesWeight = v;
return this;
}
/** See {@link #setReclaimDeletesWeight}. */
public double getReclaimDeletesWeight() {
return reclaimDeletesWeight;
}
/** Segments smaller than this are "rounded up" to this
* size, ie treated as equal (floor) size for merge
* selection. This is to prevent frequent flushing of
* tiny segments from allowing a long tail in the index.
* Default is 2 MB. */
public TieredMergePolicy setFloorSegmentMB(double v) {
if (v <= 0.0) {
throw new IllegalArgumentException("floorSegmentMB must be > 0.0 (got " + v + ")");
}
v *= 1024 * 1024;
floorSegmentBytes = v > Long.MAX_VALUE ? Long.MAX_VALUE : (long) v;
return this;
}
/** Returns the current floorSegmentMB.
*
* @see #setFloorSegmentMB */
public double getFloorSegmentMB() {
return floorSegmentBytes/(1024*1024.);
}
/** When forceMergeDeletes is called, we only merge away a
* segment if its delete percentage is over this
* threshold. Default is 10%. */
public TieredMergePolicy setForceMergeDeletesPctAllowed(double v) {
if (v < 0.0 || v > 100.0) {
throw new IllegalArgumentException("forceMergeDeletesPctAllowed must be between 0.0 and 100.0 inclusive (got " + v + ")");
}
forceMergeDeletesPctAllowed = v;
return this;
}
/** Returns the current forceMergeDeletesPctAllowed setting.
*
* @see #setForceMergeDeletesPctAllowed */
public double getForceMergeDeletesPctAllowed() {
return forceMergeDeletesPctAllowed;
}
/** Sets the allowed number of segments per tier. Smaller
* values mean more merging but fewer segments.
*
* <p><b>NOTE</b>: this value should be {@code >=} the {@link
* #setMaxMergeAtOnce} otherwise you'll force too much
* merging to occur.</p>
*
* <p>Default is 10.0.</p> */
public TieredMergePolicy setSegmentsPerTier(double v) {
if (v < 2.0) {
throw new IllegalArgumentException("segmentsPerTier must be >= 2.0 (got " + v + ")");
}
segsPerTier = v;
return this;
}
/** Returns the current segmentsPerTier setting.
*
* @see #setSegmentsPerTier */
public double getSegmentsPerTier() {
return segsPerTier;
}
private static class SegmentSizeAndDocs {
private final SegmentCommitInfo segInfo;
private final long sizeInBytes;
private final int delCount;
private final int maxDoc;
private final String name;
SegmentSizeAndDocs(SegmentCommitInfo info, final long sizeInBytes, final int segDelCount) throws IOException {
segInfo = info;
this.name = info.info.name;
this.sizeInBytes = sizeInBytes;
this.delCount = segDelCount;
this.maxDoc = info.info.maxDoc();
}
}
/** Holds score and explanation for a single candidate
* merge. */
protected static abstract class MergeScore {
/** Sole constructor. (For invocation by subclass
* constructors, typically implicit.) */
protected MergeScore() {
}
/** Returns the score for this merge candidate; lower
* scores are better. */
abstract double getScore();
/** Human readable explanation of how the merge got this
* score. */
abstract String getExplanation();
}
// The size can change concurrently while we are running here, because deletes
// are now applied concurrently, and this can piss off TimSort! So we
// call size() once per segment and sort by that:
private List<SegmentSizeAndDocs> getSortedBySegmentSize(final SegmentInfos infos, final MergeContext mergeContext) throws IOException {
List<SegmentSizeAndDocs> sortedBySize = new ArrayList<>();
for (SegmentCommitInfo info : infos) {
sortedBySize.add(new SegmentSizeAndDocs(info, size(info, mergeContext), mergeContext.numDeletesToMerge(info)));
}
sortedBySize.sort((o1, o2) -> {
// Sort by largest size:
int cmp = Long.compare(o2.sizeInBytes, o1.sizeInBytes);
if (cmp == 0) {
cmp = o1.name.compareTo(o2.name);
}
return cmp;
});
return sortedBySize;
}
@Override
public MergeSpecification findMerges(MergeTrigger mergeTrigger, SegmentInfos infos, MergeContext mergeContext) throws IOException {
final Set<SegmentCommitInfo> merging = mergeContext.getMergingSegments();
// Compute total index bytes & print details about the index
long totIndexBytes = 0;
long minSegmentBytes = Long.MAX_VALUE;
int totalDelDocs = 0;
int totalMaxDoc = 0;
List<SegmentSizeAndDocs> sortedInfos = getSortedBySegmentSize(infos, mergeContext);
Iterator<SegmentSizeAndDocs> iter = sortedInfos.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
final long segBytes = segSizeDocs.sizeInBytes;
if (verbose(mergeContext)) {
String extra = merging.contains(segSizeDocs.segInfo) ? " [merging]" : "";
if (segBytes >= maxMergedSegmentBytes) {
extra += " [skip: too large]";
} else if (segBytes < floorSegmentBytes) {
extra += " [floored]";
}
message(" seg=" + segString(mergeContext, Collections.singleton(segSizeDocs.segInfo)) + " size=" + String.format(Locale.ROOT, "%.3f", segBytes / 1024 / 1024.) + " MB" + extra, mergeContext);
}
if (merging.contains(segSizeDocs.segInfo)) {
iter.remove();
} else {
totalDelDocs += segSizeDocs.delCount;
totalMaxDoc += segSizeDocs.maxDoc;
}
minSegmentBytes = Math.min(segBytes, minSegmentBytes);
totIndexBytes += segBytes;
}
assert totalMaxDoc >= 0;
assert totalDelDocs >= 0;
// If we have too-large segments, grace them out of the maximum segment count
// If we're above certain thresholds, we can merge very large segments.
double totalDelPct = (double) totalDelDocs / (double) totalMaxDoc;
//TODO: See LUCENE-8263
//double targetAsPct = indexPctDeletedTarget / 100.0;
double targetAsPct = 0.5;
int tooBigCount = 0;
iter = sortedInfos.iterator();
// remove large segments from consideration under two conditions.
// 1> Overall percent deleted docs relatively small and this segment is larger than 50% maxSegSize
// 2> overall percent deleted docs large and this segment is large and has few deleted docs
long mergingBytes = 0L;
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
double segDelPct = (double) segSizeDocs.delCount / (double) segSizeDocs.maxDoc;
if (segSizeDocs.sizeInBytes > maxMergedSegmentBytes / 2 && (totalDelPct < targetAsPct || segDelPct < targetAsPct)) {
iter.remove();
tooBigCount++; // Just for reporting purposes.
totIndexBytes -= segSizeDocs.sizeInBytes;
} else {
mergingBytes += segSizeDocs.sizeInBytes;
}
}
// Compute max allowed segments in the index
long levelSize = Math.max(minSegmentBytes, floorSegmentBytes);
long bytesLeft = totIndexBytes;
double allowedSegCount = 0;
while (true) {
final double segCountLevel = bytesLeft / (double) levelSize;
if (segCountLevel < segsPerTier) {
allowedSegCount += Math.ceil(segCountLevel);
break;
}
allowedSegCount += segsPerTier;
bytesLeft -= segsPerTier * levelSize;
levelSize *= maxMergeAtOnce;
}
if (verbose(mergeContext) && tooBigCount > 0) {
message(" allowedSegmentCount=" + allowedSegCount + " vs count=" + infos.size() +
" (eligible count=" + sortedInfos.size() + ") tooBigCount= " + tooBigCount, mergeContext);
}
return doFindMerges(sortedInfos, maxMergedSegmentBytes, maxMergeAtOnce, (int) allowedSegCount, MERGE_TYPE.NATURAL,
mergeContext, mergingBytes >= maxMergedSegmentBytes);
}
private MergeSpecification doFindMerges(List<SegmentSizeAndDocs> sortedEligibleInfos,
final long maxMergedSegmentBytes,
final int maxMergeAtOnce, final int allowedSegCount,
final MERGE_TYPE mergeType,
MergeContext mergeContext,
boolean maxMergeIsRunning) throws IOException {
List<SegmentSizeAndDocs> sortedEligible = new ArrayList<>(sortedEligibleInfos);
Map<SegmentCommitInfo, SegmentSizeAndDocs> segInfosSizes = new HashMap<>();
for (SegmentSizeAndDocs segSizeDocs : sortedEligible) {
segInfosSizes.put(segSizeDocs.segInfo, segSizeDocs);
}
int originalSortedSize = sortedEligible.size();
if (verbose(mergeContext)) {
message("findMerges: " + originalSortedSize + " segments", mergeContext);
}
if (originalSortedSize == 0) {
return null;
}
final Set<SegmentCommitInfo> toBeMerged = new HashSet<>();
MergeSpecification spec = null;
// Cycle to possibly select more than one merge:
// The trigger point for total deleted documents in the index leads to a bunch of large segment
// merges at the same time. So only put one large merge in the list of merges per cycle. We'll pick up another
// merge next time around.
boolean haveOneLargeMerge = false;
while (true) {
// Gather eligible segments for merging, ie segments
// not already being merged and not already picked (by
// prior iteration of this loop) for merging:
// Remove ineligible segments. These are either already being merged or already picked by prior iterations
Iterator<SegmentSizeAndDocs> iter = sortedEligible.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
if (toBeMerged.contains(segSizeDocs.segInfo)) {
iter.remove();
}
}
if (verbose(mergeContext)) {
message(" allowedSegmentCount=" + allowedSegCount + " vs count=" + originalSortedSize + " (eligible count=" + sortedEligible.size() + ")", mergeContext);
}
if (sortedEligible.size() == 0) {
return spec;
}
if (allowedSegCount != Integer.MAX_VALUE && sortedEligible.size() <= allowedSegCount && mergeType == MERGE_TYPE.NATURAL) {
return spec;
}
// OK we are over budget -- find best merge!
MergeScore bestScore = null;
List<SegmentCommitInfo> best = null;
boolean bestTooLarge = false;
long bestMergeBytes = 0;
// Consider all merge starts.
int lim = sortedEligible.size() - maxMergeAtOnce; // assume the usual case of background merging.
if (mergeType != MERGE_TYPE.NATURAL) { // The unusual case of forceMerge or expungeDeletes.
// The incoming eligible list will have only segments with > forceMergeDeletesPctAllowed in the case of
// findForcedDeletesMerges and segments with < max allowed size in the case of optimize.
// If forcing, we must allow singleton merges.
lim = sortedEligible.size() - 1;
}
for (int startIdx = 0; startIdx <= lim; startIdx++) {
long totAfterMergeBytes = 0;
final List<SegmentCommitInfo> candidate = new ArrayList<>();
boolean hitTooLarge = false;
long bytesThisMerge = 0;
for (int idx = startIdx; idx < sortedEligible.size() && candidate.size() < maxMergeAtOnce && bytesThisMerge < maxMergedSegmentBytes; idx++) {
final SegmentSizeAndDocs segSizeDocs = sortedEligible.get(idx);
final long segBytes = segSizeDocs.sizeInBytes;
if (totAfterMergeBytes + segBytes > maxMergedSegmentBytes) {
hitTooLarge = true;
if (candidate.size() == 0) {
// We should never have something coming in that _cannot_ be merged, so handle singleton merges
candidate.add(segSizeDocs.segInfo);
bytesThisMerge += segBytes;
}
// NOTE: we continue, so that we can try
// "packing" smaller segments into this merge
// to see if we can get closer to the max
// size; this in general is not perfect since
// this is really "bin packing" and we'd have
// to try different permutations.
continue;
}
candidate.add(segSizeDocs.segInfo);
bytesThisMerge += segBytes;
totAfterMergeBytes += segBytes;
}
// We should never see an empty candidate: we iterated over maxMergeAtOnce
// segments, and already pre-excluded the too-large segments:
assert candidate.size() > 0;
// A singleton merge with no deletes makes no sense. We can get here when forceMerge is looping around...
if (candidate.size() == 1) {
SegmentSizeAndDocs segSizeDocs = segInfosSizes.get(candidate.get(0));
if (segSizeDocs.delCount == 0) {
continue;
}
}
final MergeScore score = score(candidate, hitTooLarge, segInfosSizes);
if (verbose(mergeContext)) {
message(" maybe=" + segString(mergeContext, candidate) + " score=" + score.getScore() + " " + score.getExplanation() + " tooLarge=" + hitTooLarge + " size=" + String.format(Locale.ROOT, "%.3f MB", totAfterMergeBytes/1024./1024.), mergeContext);
}
if ((bestScore == null || score.getScore() < bestScore.getScore()) && (!hitTooLarge || !maxMergeIsRunning)) {
best = candidate;
bestScore = score;
bestTooLarge = hitTooLarge;
bestMergeBytes = totAfterMergeBytes;
}
}
if (best == null) {
return spec;
}
// The mergeType == FORCE_MERGE_DELETES behaves as the code does currently and can create a large number of
// concurrent big merges. If we make findForcedDeletesMerges behave as findForcedMerges and cycle through
// we should remove this.
if (haveOneLargeMerge == false || bestTooLarge == false || mergeType == MERGE_TYPE.FORCE_MERGE_DELETES) {
haveOneLargeMerge |= bestTooLarge;
if (spec == null) {
spec = new MergeSpecification();
}
final OneMerge merge = new OneMerge(best);
spec.add(merge);
if (verbose(mergeContext)) {
message(" add merge=" + segString(mergeContext, merge.segments) + " size=" + String.format(Locale.ROOT, "%.3f MB", bestMergeBytes / 1024. / 1024.) + " score=" + String.format(Locale.ROOT, "%.3f", bestScore.getScore()) + " " + bestScore.getExplanation() + (bestTooLarge ? " [max merge]" : ""), mergeContext);
}
}
// whether we're going to return this list in the spec of not, we need to remove it from
// consideration on the next loop.
toBeMerged.addAll(best);
}
}
/** Expert: scores one merge; subclasses can override. */
protected MergeScore score(List<SegmentCommitInfo> candidate, boolean hitTooLarge, Map<SegmentCommitInfo, SegmentSizeAndDocs> segmentsSizes) throws IOException {
long totBeforeMergeBytes = 0;
long totAfterMergeBytes = 0;
long totAfterMergeBytesFloored = 0;
for(SegmentCommitInfo info : candidate) {
final long segBytes = segmentsSizes.get(info).sizeInBytes;
totAfterMergeBytes += segBytes;
totAfterMergeBytesFloored += floorSize(segBytes);
totBeforeMergeBytes += info.sizeInBytes();
}
// Roughly measure "skew" of the merge, i.e. how
// "balanced" the merge is (whether the segments are
// about the same size), which can range from
// 1.0/numSegsBeingMerged (good) to 1.0 (poor). Heavily
// lopsided merges (skew near 1.0) is no good; it means
// O(N^2) merge cost over time:
final double skew;
if (hitTooLarge) {
// Pretend the merge has perfect skew; skew doesn't
// matter in this case because this merge will not
// "cascade" and so it cannot lead to N^2 merge cost
// over time:
skew = 1.0/maxMergeAtOnce;
} else {
skew = ((double) floorSize(segmentsSizes.get(candidate.get(0)).sizeInBytes)) / totAfterMergeBytesFloored;
}
// Strongly favor merges with less skew (smaller
// mergeScore is better):
double mergeScore = skew;
// Gently favor smaller merges over bigger ones. We
// don't want to make this exponent too large else we
// can end up doing poor merges of small segments in
// order to avoid the large merges:
mergeScore *= Math.pow(totAfterMergeBytes, 0.05);
// Strongly favor merges that reclaim deletes:
final double nonDelRatio = ((double) totAfterMergeBytes)/totBeforeMergeBytes;
mergeScore *= Math.pow(nonDelRatio, reclaimDeletesWeight);
final double finalMergeScore = mergeScore;
return new MergeScore() {
@Override
public double getScore() {
return finalMergeScore;
}
@Override
public String getExplanation() {
return "skew=" + String.format(Locale.ROOT, "%.3f", skew) + " nonDelRatio=" + String.format(Locale.ROOT, "%.3f", nonDelRatio);
}
};
}
@Override
public MergeSpecification findForcedMerges(SegmentInfos infos, int maxSegmentCount, Map<SegmentCommitInfo,Boolean> segmentsToMerge, MergeContext mergeContext) throws IOException {
if (verbose(mergeContext)) {
message("findForcedMerges maxSegmentCount=" + maxSegmentCount + " infos=" + segString(mergeContext, infos) +
" segmentsToMerge=" + segmentsToMerge, mergeContext);
}
List<SegmentSizeAndDocs> sortedSizeAndDocs = getSortedBySegmentSize(infos, mergeContext);
long totalMergeBytes = 0;
final Set<SegmentCommitInfo> merging = mergeContext.getMergingSegments();
// Trim the list down, remove if we're respecting max segment size and it's not original. Presumably it's been merged before and
// is close enough to the max segment size we shouldn't add it in again.
Iterator<SegmentSizeAndDocs> iter = sortedSizeAndDocs.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
final Boolean isOriginal = segmentsToMerge.get(segSizeDocs.segInfo);
if (isOriginal == null) {
iter.remove();
} else {
if (merging.contains(segSizeDocs.segInfo)) {
iter.remove();
} else {
totalMergeBytes += segSizeDocs.sizeInBytes;
}
}
}
long maxMergeBytes = maxMergedSegmentBytes;
// Set the maximum segment size based on how many segments have been specified.
if (maxSegmentCount == 1) maxMergeBytes = Long.MAX_VALUE;
else if (maxSegmentCount != Integer.MAX_VALUE) {
// Fudge this up a bit so we have a better chance of not having to rewrite segments. If we use the exact size,
// it's almost guaranteed that the segments won't fit perfectly and we'll be left with more segments than
// we want and have to re-merge in the code at the bottom of this method.
maxMergeBytes = Math.max((long) (((double) totalMergeBytes / (double) maxSegmentCount)), maxMergedSegmentBytes);
maxMergeBytes = (long) ((double) maxMergeBytes * 1.25);
}
iter = sortedSizeAndDocs.iterator();
boolean foundDeletes = false;
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
Boolean isOriginal = segmentsToMerge.get(segSizeDocs.segInfo);
if (segSizeDocs.delCount != 0) { // This is forceMerge, all segments with deleted docs should be merged.
if (isOriginal != null && isOriginal) {
foundDeletes = true;
}
continue;
}
// Let the scoring handle whether to merge large segments.
if (maxSegmentCount == Integer.MAX_VALUE && isOriginal != null && isOriginal == false) {
iter.remove();
}
// Don't try to merge a segment with no deleted docs that's over the max size.
if (maxSegmentCount != Integer.MAX_VALUE && segSizeDocs.sizeInBytes >= maxMergeBytes) {
iter.remove();
}
}
// Nothing to merge this round.
if (sortedSizeAndDocs.size() == 0) {
return null;
}
// We should never bail if there are segments that have deleted documents, all deleted docs should be purged.
if (foundDeletes == false) {
SegmentCommitInfo infoZero = sortedSizeAndDocs.get(0).segInfo;
if ((maxSegmentCount != Integer.MAX_VALUE && maxSegmentCount > 1 && sortedSizeAndDocs.size() <= maxSegmentCount) ||
(maxSegmentCount == 1 && sortedSizeAndDocs.size() == 1 && (segmentsToMerge.get(infoZero) != null || isMerged(infos, infoZero, mergeContext)))) {
if (verbose(mergeContext)) {
message("already merged", mergeContext);
}
return null;
}
}
if (verbose(mergeContext)) {
message("eligible=" + sortedSizeAndDocs, mergeContext);
}
// This is the special case of merging down to one segment
if (sortedSizeAndDocs.size() < maxMergeAtOnceExplicit && maxSegmentCount == 1 && totalMergeBytes < maxMergeBytes) {
MergeSpecification spec = new MergeSpecification();
List<SegmentCommitInfo> allOfThem = new ArrayList<>();
for (SegmentSizeAndDocs segSizeDocs : sortedSizeAndDocs) {
allOfThem.add(segSizeDocs.segInfo);
}
spec.add(new OneMerge(allOfThem));
return spec;
}
MergeSpecification spec = doFindMerges(sortedSizeAndDocs, maxMergeBytes, maxMergeAtOnceExplicit,
maxSegmentCount, MERGE_TYPE.FORCE_MERGE, mergeContext, false);
return spec;
}
@Override
public MergeSpecification findForcedDeletesMerges(SegmentInfos infos, MergeContext mergeContext) throws IOException {
if (verbose(mergeContext)) {
message("findForcedDeletesMerges infos=" + segString(mergeContext, infos) + " forceMergeDeletesPctAllowed=" + forceMergeDeletesPctAllowed, mergeContext);
}
// First do a quick check that there's any work to do.
// NOTE: this makes BaseMergePOlicyTestCase.testFindForcedDeletesMerges work
final Set<SegmentCommitInfo> merging = mergeContext.getMergingSegments();
boolean haveWork = false;
for(SegmentCommitInfo info : infos) {
int delCount = mergeContext.numDeletesToMerge(info);
assert assertDelCount(delCount, info);
double pctDeletes = 100.*((double) delCount)/info.info.maxDoc();
if (pctDeletes > forceMergeDeletesPctAllowed && !merging.contains(info)) {
haveWork = true;
break;
}
}
if (haveWork == false) {
return null;
}
List<SegmentSizeAndDocs> sortedInfos = getSortedBySegmentSize(infos, mergeContext);
Iterator<SegmentSizeAndDocs> iter = sortedInfos.iterator();
while (iter.hasNext()) {
SegmentSizeAndDocs segSizeDocs = iter.next();
double pctDeletes = 100. * ((double) segSizeDocs.delCount / (double) segSizeDocs.maxDoc);
if (merging.contains(segSizeDocs.segInfo) || pctDeletes <= forceMergeDeletesPctAllowed) {
iter.remove();
}
}
if (verbose(mergeContext)) {
message("eligible=" + sortedInfos, mergeContext);
}
return doFindMerges(sortedInfos, maxMergedSegmentBytes,
maxMergeAtOnceExplicit, Integer.MAX_VALUE, MERGE_TYPE.FORCE_MERGE_DELETES, mergeContext, false);
}
private long floorSize(long bytes) {
return Math.max(floorSegmentBytes, bytes);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[" + getClass().getSimpleName() + ": ");
sb.append("maxMergeAtOnce=").append(maxMergeAtOnce).append(", ");
sb.append("maxMergeAtOnceExplicit=").append(maxMergeAtOnceExplicit).append(", ");
sb.append("maxMergedSegmentMB=").append(maxMergedSegmentBytes/1024/1024.).append(", ");
sb.append("floorSegmentMB=").append(floorSegmentBytes/1024/1024.).append(", ");
sb.append("forceMergeDeletesPctAllowed=").append(forceMergeDeletesPctAllowed).append(", ");
sb.append("segmentsPerTier=").append(segsPerTier).append(", ");
sb.append("maxCFSSegmentSizeMB=").append(getMaxCFSSegmentSizeMB()).append(", ");
sb.append("noCFSRatio=").append(noCFSRatio).append(", ");
sb.append("reclaimDeletesWeight=").append(reclaimDeletesWeight);
//TODO: See LUCENE-8263
//sb.append("indexPctDeletedTarget=").append(indexPctDeletedTarget);
return sb.toString();
}
}
| LUCENE-8383: Fix computation of mergingBytes in TieredMergePolicy.
| lucene/core/src/java/org/apache/lucene/index/TieredMergePolicy.java | LUCENE-8383: Fix computation of mergingBytes in TieredMergePolicy. | <ide><path>ucene/core/src/java/org/apache/lucene/index/TieredMergePolicy.java
<ide> int totalDelDocs = 0;
<ide> int totalMaxDoc = 0;
<ide>
<add> long mergingBytes = 0;
<add>
<ide> List<SegmentSizeAndDocs> sortedInfos = getSortedBySegmentSize(infos, mergeContext);
<ide> Iterator<SegmentSizeAndDocs> iter = sortedInfos.iterator();
<ide> while (iter.hasNext()) {
<ide> message(" seg=" + segString(mergeContext, Collections.singleton(segSizeDocs.segInfo)) + " size=" + String.format(Locale.ROOT, "%.3f", segBytes / 1024 / 1024.) + " MB" + extra, mergeContext);
<ide> }
<ide> if (merging.contains(segSizeDocs.segInfo)) {
<add> mergingBytes += segSizeDocs.sizeInBytes;
<ide> iter.remove();
<ide> } else {
<ide> totalDelDocs += segSizeDocs.delCount;
<ide> // 1> Overall percent deleted docs relatively small and this segment is larger than 50% maxSegSize
<ide> // 2> overall percent deleted docs large and this segment is large and has few deleted docs
<ide>
<del> long mergingBytes = 0L;
<del>
<ide> while (iter.hasNext()) {
<ide> SegmentSizeAndDocs segSizeDocs = iter.next();
<ide> double segDelPct = (double) segSizeDocs.delCount / (double) segSizeDocs.maxDoc;
<ide> iter.remove();
<ide> tooBigCount++; // Just for reporting purposes.
<ide> totIndexBytes -= segSizeDocs.sizeInBytes;
<del> } else {
<del> mergingBytes += segSizeDocs.sizeInBytes;
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | 24ff6f89955d98b9d63cc8179b53ae7bcc24764d | 0 | mountaindude/butler | var dict = require('dict');
// Load global variables and functions
var globals = require('../globals');
module.exports.mqttInitHandlers = function () {
// Handler for MQTT connect messages. Called when connection to MQTT broker has been established
globals.mqttClient.on('connect', function () {
var oldLogLevel = globals.logger.transports.console.level;
globals.logger.transports.console.level = 'info';
globals.logger.log('info', 'Connected to MQTT server %s:%s, with client ID %s', globals.config.get('Butler.mqttConfig.brokerIP'), globals.config.get('Butler.mqttConfig.brokerPort'), globals.mqttClient.options.clientId);
globals.logger.transports.console.level = oldLogLevel;
// Let the world know that Butler is connected to MQTT
// console.info('Connected to MQTT broker');
globals.mqttClient.publish('qliksense/butler/mqtt/status', 'Connected to MQTT broker ' + globals.config.get('Butler.mqttConfig.brokerIP') + ':' + globals.config.get('Butler.mqttConfig.brokerPort') + ' with client ID ' + globals.mqttClient.options.clientId);
// Have Butler listen to all messages in the qliksense/ subtree
globals.mqttClient.subscribe('qliksense/#');
});
// Handler for MQTT messages matching the previously set up subscription
globals.mqttClient.on('message', function (topic, message) {
globals.logger.log('info', 'MQTT message received');
globals.logger.log('info', topic.toString());
globals.logger.log('info', message.toString());
// console.info('MQTT message received');
// console.info(topic.toString());
// console.info(message.toString());
// **MQTT message dispatch**
// Start Sense task
if (topic == 'qliksense/start_task') {
globals.qrsUtil.senseStartTask.senseStartTask(message.toString());
}
var array1, array2, serverName, directoryName, userName;
var activeUsers = [],
activeUsersJSON;
var activeUsersPerServer = [],
activeUsersPerServerJSON;
var serverObj;
if ((topic == globals.config.get('Butler.mqttConfig.sessionStartTopic')) ||
(topic == globals.config.get('Butler.mqttConfig.connectionOpenTopic'))) {
// Handle dict of currently active users
// Message arrives as "serverName: directoryName/userName
array1 = message.toString().split(': ');
array2 = array1[1].split('/');
serverName = array1[0];
directoryName = array2[0];
userName = array2[1];
globals.logger.log('info', 'Adding active user');
// console.info('Adding active user');
globals.currentUsers.set(userName, serverName); // Add user as active
// Build JSON of all active users
globals.currentUsers.forEach(function (value, key) {
activeUsers.push(key); // Push to overall list of active users
});
activeUsersJSON = JSON.stringify(activeUsers);
// Handle dict of currently active users, split on proxy they are connected through
if (globals.currentUsersPerServer.has(serverName)) {
// Server already exists in dict - get it
serverObj = globals.currentUsersPerServer.get(serverName);
} else {
serverObj = dict();
}
serverObj.set(userName, 'active');
globals.currentUsersPerServer.set(serverName, serverObj);
// Send active user count messages to MQTT, one for each proxy node
globals.currentUsersPerServer.forEach(function (value, key) {
globals.logger.log('info', 'server:' + key + ', users:' + JSON.stringify(value));
// console.info('server:' + key + ', users:' + JSON.stringify(value));
// console.log('=========');
// console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
// value.forEach(function(value2, key2) {
// console.log('key2:' + key2);
// console.log('value2:' + value2);
// });
// Send MQTT message with info on # of active users per proxy
// console.log('--------');
// console.log(globals.currentUsersPerServer.get(key).size);
globals.mqttClient.publish('qliksense/users/activeperserver/' + key + '/count', globals.currentUsersPerServer.get(key).size.toString());
// console.log('--------');
});
// Send MQTT messages relating to active users
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUserCountTopic').toString(), globals.currentUsers.size.toString());
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUsersTopic').toString(), activeUsersJSON);
globals.logger.log('info', '# of active users: ' + globals.currentUsers.size);
// console.info('# of active users: ' + globals.currentUsers.size );
}
if (topic == globals.config.get('Butler.mqttConfig.sessionStopTopic')) {
// Handle dict of currently active users
// Message arrives as "serverName: directoryName/userName
array1 = message.toString().split(': ');
array2 = array1[1].split('/');
serverName = array1[0];
directoryName = array2[0];
userName = array2[1];
globals.logger.log('info', 'Removing active user');
// console.info('Removing active user');
globals.currentUsers.delete(userName); // Remove user from list of active users
// Build JSON of all active users
globals.currentUsers.forEach(function (value, key) {
activeUsers.push(key);
});
activeUsersJSON = JSON.stringify(activeUsers);
// Handle dict of currently active users, split on proxy they are connected through
if (globals.currentUsersPerServer.has(serverName)) {
// Server already exists in dict - get it.
// If the server does not exist in dict there is no reason to proceed
serverObj = globals.currentUsersPerServer.get(serverName);
serverObj.delete(userName);
globals.currentUsersPerServer.set(serverName, serverObj); // Update the main users-per-server dict
globals.logger.log('info', '----Removed user ' + userName + ' from server ' + serverName);
// console.info('----Removed user ' + userName + ' from server ' + serverName);
// Send active user count messages to MQTT, one for each proxy node
globals.currentUsersPerServer.forEach(function (value, key) {
// console.log('=========');
// console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
// value.forEach(function(value2, key2) {
// console.log('key2:' + key2);
// console.log('value2:' + value2);
// });
// Send MQTT message with info on # of active users per proxy
// console.log('--------');
// console.log(globals.currentUsersPerServer.get(key).size);
globals.mqttClient.publish('qliksense/users/activeperserver/' + key + '/count', globals.currentUsersPerServer.get(key).size.toString());
// console.log('--------');
});
}
// Send MQTT messages relating to active users
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUserCountTopic').toString(), globals.currentUsers.size.toString());
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUsersTopic').toString(), activeUsersJSON);
globals.logger.log('info', '# of active users: ' + globals.currentUsers.size);
// console.info('# of active users: ' + globals.currentUsers.size );
}
});
// Handler for MQTT errors
globals.mqttClient.on('error', function (topic, message) {
// Error occured
globals.logger.log('error', 'MQTT error: ' + message);
// console.error('MQTT error: ' + message);
});
};
| src/mqtt/mqtt_handlers.js | var dict = require('dict');
// Load global variables and functions
var globals = require('../globals');
module.exports.mqttInitHandlers = function () {
// Handler for MQTT connect messages. Called when connection to MQTT broker has been established
globals.mqttClient.on('connect', function () {
var oldLogLevel = globals.logger.transports.console.level;
globals.logger.transports.console.level = 'info';
globals.logger.log('info', 'Connected to MQTT broker');
globals.logger.transports.console.level = oldLogLevel;
// console.info('Connected to MQTT broker');
// Let the world know that Butler is connected to MQTT
globals.mqttClient.publish('qliksense/butler/mqtt/status', 'Connected to MQTT broker');
// Have Butler listen to all messages in the qliksense/ subtree
globals.mqttClient.subscribe('qliksense/#');
});
// Handler for MQTT messages matching the previously set up subscription
globals.mqttClient.on('message', function (topic, message) {
globals.logger.log('info', 'MQTT message received');
globals.logger.log('info', topic.toString());
globals.logger.log('info', message.toString());
// console.info('MQTT message received');
// console.info(topic.toString());
// console.info(message.toString());
// **MQTT message dispatch**
// Start Sense task
if (topic == 'qliksense/start_task') {
globals.qrsUtil.senseStartTask.senseStartTask(message.toString());
}
var array1, array2, serverName, directoryName, userName;
var activeUsers = [], activeUsersJSON;
var activeUsersPerServer = [], activeUsersPerServerJSON;
var serverObj;
if ( (topic == globals.config.get('Butler.mqttConfig.sessionStartTopic')) ||
(topic == globals.config.get('Butler.mqttConfig.connectionOpenTopic')) ) {
// Handle dict of currently active users
// Message arrives as "serverName: directoryName/userName
array1 = message.toString().split(': ');
array2 = array1[1].split('/');
serverName = array1[0];
directoryName = array2[0];
userName = array2[1];
globals.logger.log('info', 'Adding active user');
// console.info('Adding active user');
globals.currentUsers.set(userName, serverName); // Add user as active
// Build JSON of all active users
globals.currentUsers.forEach(function (value, key) {
activeUsers.push(key); // Push to overall list of active users
});
activeUsersJSON = JSON.stringify(activeUsers);
// Handle dict of currently active users, split on proxy they are connected through
if (globals.currentUsersPerServer.has(serverName)) {
// Server already exists in dict - get it
serverObj = globals.currentUsersPerServer.get(serverName);
} else {
serverObj = dict();
}
serverObj.set(userName, 'active');
globals.currentUsersPerServer.set(serverName, serverObj);
// Send active user count messages to MQTT, one for each proxy node
globals.currentUsersPerServer.forEach(function (value, key) {
globals.logger.log('info', 'server:' + key + ', users:' + JSON.stringify(value));
// console.info('server:' + key + ', users:' + JSON.stringify(value));
// console.log('=========');
// console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
// value.forEach(function(value2, key2) {
// console.log('key2:' + key2);
// console.log('value2:' + value2);
// });
// Send MQTT message with info on # of active users per proxy
// console.log('--------');
// console.log(globals.currentUsersPerServer.get(key).size);
globals.mqttClient.publish('qliksense/users/activeperserver/' + key + '/count', globals.currentUsersPerServer.get(key).size.toString());
// console.log('--------');
});
// Send MQTT messages relating to active users
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUserCountTopic').toString(), globals.currentUsers.size.toString());
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUsersTopic').toString(), activeUsersJSON);
globals.logger.log('info', '# of active users: ' + globals.currentUsers.size );
// console.info('# of active users: ' + globals.currentUsers.size );
}
if (topic == globals.config.get('Butler.mqttConfig.sessionStopTopic')) {
// Handle dict of currently active users
// Message arrives as "serverName: directoryName/userName
array1 = message.toString().split(': ');
array2 = array1[1].split('/');
serverName = array1[0];
directoryName = array2[0];
userName = array2[1];
globals.logger.log('info', 'Removing active user');
// console.info('Removing active user');
globals.currentUsers.delete(userName); // Remove user from list of active users
// Build JSON of all active users
globals.currentUsers.forEach(function (value, key) {
activeUsers.push(key);
});
activeUsersJSON = JSON.stringify(activeUsers);
// Handle dict of currently active users, split on proxy they are connected through
if (globals.currentUsersPerServer.has(serverName)) {
// Server already exists in dict - get it.
// If the server does not exist in dict there is no reason to proceed
serverObj = globals.currentUsersPerServer.get(serverName);
serverObj.delete(userName);
globals.currentUsersPerServer.set(serverName, serverObj); // Update the main users-per-server dict
globals.logger.log('info', '----Removed user ' + userName + ' from server ' + serverName);
// console.info('----Removed user ' + userName + ' from server ' + serverName);
// Send active user count messages to MQTT, one for each proxy node
globals.currentUsersPerServer.forEach(function (value, key) {
// console.log('=========');
// console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
// value.forEach(function(value2, key2) {
// console.log('key2:' + key2);
// console.log('value2:' + value2);
// });
// Send MQTT message with info on # of active users per proxy
// console.log('--------');
// console.log(globals.currentUsersPerServer.get(key).size);
globals.mqttClient.publish('qliksense/users/activeperserver/' + key + '/count', globals.currentUsersPerServer.get(key).size.toString());
// console.log('--------');
});
}
// Send MQTT messages relating to active users
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUserCountTopic').toString(), globals.currentUsers.size.toString());
globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUsersTopic').toString(), activeUsersJSON);
globals.logger.log('info', '# of active users: ' + globals.currentUsers.size );
// console.info('# of active users: ' + globals.currentUsers.size );
}
});
// Handler for MQTT errors
globals.mqttClient.on('error', function (topic, message) {
// Error occured
globals.logger.log('error', 'MQTT error: ' + message);
// console.error('MQTT error: ' + message);
});
};
| improved code formatting
| src/mqtt/mqtt_handlers.js | improved code formatting | <ide><path>rc/mqtt/mqtt_handlers.js
<ide> var oldLogLevel = globals.logger.transports.console.level;
<ide> globals.logger.transports.console.level = 'info';
<ide>
<del> globals.logger.log('info', 'Connected to MQTT broker');
<add> globals.logger.log('info', 'Connected to MQTT server %s:%s, with client ID %s', globals.config.get('Butler.mqttConfig.brokerIP'), globals.config.get('Butler.mqttConfig.brokerPort'), globals.mqttClient.options.clientId);
<ide>
<ide> globals.logger.transports.console.level = oldLogLevel;
<ide>
<add> // Let the world know that Butler is connected to MQTT
<ide> // console.info('Connected to MQTT broker');
<del>
<del> // Let the world know that Butler is connected to MQTT
<del> globals.mqttClient.publish('qliksense/butler/mqtt/status', 'Connected to MQTT broker');
<del>
<add> globals.mqttClient.publish('qliksense/butler/mqtt/status', 'Connected to MQTT broker ' + globals.config.get('Butler.mqttConfig.brokerIP') + ':' + globals.config.get('Butler.mqttConfig.brokerPort') + ' with client ID ' + globals.mqttClient.options.clientId);
<add>
<ide> // Have Butler listen to all messages in the qliksense/ subtree
<ide> globals.mqttClient.subscribe('qliksense/#');
<ide> });
<ide>
<ide>
<ide> var array1, array2, serverName, directoryName, userName;
<del> var activeUsers = [], activeUsersJSON;
<del> var activeUsersPerServer = [], activeUsersPerServerJSON;
<add> var activeUsers = [],
<add> activeUsersJSON;
<add> var activeUsersPerServer = [],
<add> activeUsersPerServerJSON;
<ide> var serverObj;
<ide>
<del> if ( (topic == globals.config.get('Butler.mqttConfig.sessionStartTopic')) ||
<del> (topic == globals.config.get('Butler.mqttConfig.connectionOpenTopic')) ) {
<add> if ((topic == globals.config.get('Butler.mqttConfig.sessionStartTopic')) ||
<add> (topic == globals.config.get('Butler.mqttConfig.connectionOpenTopic'))) {
<ide>
<ide> // Handle dict of currently active users
<ide> // Message arrives as "serverName: directoryName/userName
<ide>
<ide> globals.logger.log('info', 'Adding active user');
<ide> // console.info('Adding active user');
<del> globals.currentUsers.set(userName, serverName); // Add user as active
<add> globals.currentUsers.set(userName, serverName); // Add user as active
<ide>
<ide> // Build JSON of all active users
<ide> globals.currentUsers.forEach(function (value, key) {
<del> activeUsers.push(key); // Push to overall list of active users
<add> activeUsers.push(key); // Push to overall list of active users
<ide> });
<ide>
<ide> activeUsersJSON = JSON.stringify(activeUsers);
<ide> globals.currentUsersPerServer.forEach(function (value, key) {
<ide> globals.logger.log('info', 'server:' + key + ', users:' + JSON.stringify(value));
<ide> // console.info('server:' + key + ', users:' + JSON.stringify(value));
<del>// console.log('=========');
<del>// console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
<add> // console.log('=========');
<add> // console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
<ide>
<del>// value.forEach(function(value2, key2) {
<del>// console.log('key2:' + key2);
<del>// console.log('value2:' + value2);
<del>// });
<add> // value.forEach(function(value2, key2) {
<add> // console.log('key2:' + key2);
<add> // console.log('value2:' + value2);
<add> // });
<ide>
<ide> // Send MQTT message with info on # of active users per proxy
<del>// console.log('--------');
<del>// console.log(globals.currentUsersPerServer.get(key).size);
<add> // console.log('--------');
<add> // console.log(globals.currentUsersPerServer.get(key).size);
<ide> globals.mqttClient.publish('qliksense/users/activeperserver/' + key + '/count', globals.currentUsersPerServer.get(key).size.toString());
<del>// console.log('--------');
<add> // console.log('--------');
<ide> });
<ide>
<ide>
<ide> globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUserCountTopic').toString(), globals.currentUsers.size.toString());
<ide> globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUsersTopic').toString(), activeUsersJSON);
<ide>
<del> globals.logger.log('info', '# of active users: ' + globals.currentUsers.size );
<add> globals.logger.log('info', '# of active users: ' + globals.currentUsers.size);
<ide> // console.info('# of active users: ' + globals.currentUsers.size );
<ide> }
<ide>
<ide>
<ide> globals.logger.log('info', 'Removing active user');
<ide> // console.info('Removing active user');
<del> globals.currentUsers.delete(userName); // Remove user from list of active users
<add> globals.currentUsers.delete(userName); // Remove user from list of active users
<ide>
<ide> // Build JSON of all active users
<ide> globals.currentUsers.forEach(function (value, key) {
<ide> serverObj = globals.currentUsersPerServer.get(serverName);
<ide>
<ide> serverObj.delete(userName);
<del> globals.currentUsersPerServer.set(serverName, serverObj); // Update the main users-per-server dict
<add> globals.currentUsersPerServer.set(serverName, serverObj); // Update the main users-per-server dict
<ide> globals.logger.log('info', '----Removed user ' + userName + ' from server ' + serverName);
<ide> // console.info('----Removed user ' + userName + ' from server ' + serverName);
<ide>
<ide> // Send active user count messages to MQTT, one for each proxy node
<ide> globals.currentUsersPerServer.forEach(function (value, key) {
<del>// console.log('=========');
<del>// console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
<add> // console.log('=========');
<add> // console.log('server:' + key + ', # of users=' + globals.currentUsersPerServer.size);
<ide>
<del>// value.forEach(function(value2, key2) {
<del>// console.log('key2:' + key2);
<del>// console.log('value2:' + value2);
<del>// });
<add> // value.forEach(function(value2, key2) {
<add> // console.log('key2:' + key2);
<add> // console.log('value2:' + value2);
<add> // });
<ide>
<ide> // Send MQTT message with info on # of active users per proxy
<del>// console.log('--------');
<del>// console.log(globals.currentUsersPerServer.get(key).size);
<add> // console.log('--------');
<add> // console.log(globals.currentUsersPerServer.get(key).size);
<ide> globals.mqttClient.publish('qliksense/users/activeperserver/' + key + '/count', globals.currentUsersPerServer.get(key).size.toString());
<del>// console.log('--------');
<add> // console.log('--------');
<ide> });
<del> }
<add> }
<ide>
<ide>
<ide>
<ide> globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUserCountTopic').toString(), globals.currentUsers.size.toString());
<ide> globals.mqttClient.publish(globals.config.get('Butler.mqttConfig.activeUsersTopic').toString(), activeUsersJSON);
<ide>
<del> globals.logger.log('info', '# of active users: ' + globals.currentUsers.size );
<add> globals.logger.log('info', '# of active users: ' + globals.currentUsers.size);
<ide> // console.info('# of active users: ' + globals.currentUsers.size );
<ide> }
<ide> |
|
Java | lgpl-2.1 | 6a358f589b5a6c98712850199fae33742ba7f8b3 | 0 | IDgis/GeoPublisher-viewer,IDgis/GeoPublisher-viewer,IDgis/GeoPublisher-viewer | package controllers;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import play.Logger;
import play.Logger.ALogger;
import play.libs.F.Promise;
import play.libs.ws.WSClient;
import play.libs.ws.WSRequest;
import play.libs.ws.WSResponse;
import play.mvc.Controller;
import play.mvc.Result;
public class Proxy extends Controller {
private static final ALogger logger = Logger.of(Proxy.class);
@Inject WSClient ws;
public Promise<Result> proxy(String url) {
WSRequest request = ws.url(url).setFollowRedirects(true).setRequestTimeout(10000);
Map<String, String[]> colStr = request().queryString();
for (Map.Entry<String, String[]> entry: colStr.entrySet()) {
for(String entryValue: entry.getValue()) {
request = request.setQueryParameter(entry.getKey(), entryValue);
}
}
Promise<WSResponse> responsePromise = request.get();
Promise<Result> resultPromise = responsePromise.map (response -> {
Integer statusCode = response.getStatus();
if(statusCode >= 500 && statusCode < 600) {
return status(BAD_GATEWAY, response.asByteArray()).as(response.getHeader(CONTENT_TYPE));
} else {
String encodeValue = colStr.get("encoding")[0];
final String body = new String(response.asByteArray(), encodeValue);
Document doc = Jsoup.parse(body);
Element bodyNew = doc.body();
Elements br = bodyNew.getElementsByTag("br");
br.remove();
response().setContentType("text/html; charset=utf-8");
return status(statusCode, bodyNew.html(), "UTF-8");
}
});
Promise<Result> recoveredPromise = resultPromise.recover ((Throwable throwable) -> {
if (throwable instanceof TimeoutException) {
logger.error("Timeout when requesting: " + url, throwable);
return status (GATEWAY_TIMEOUT, throwable.getMessage ());
} else {
logger.error("Error occured when requesting: " + url, throwable);
return status (BAD_GATEWAY, throwable.getMessage ());
}
});
return recoveredPromise;
}
} | app/controllers/Proxy.java | package controllers;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
import play.Logger;
import play.Logger.ALogger;
import play.libs.F.Promise;
import play.libs.ws.WSClient;
import play.libs.ws.WSRequest;
import play.libs.ws.WSResponse;
import play.mvc.Controller;
import play.mvc.Result;
public class Proxy extends Controller {
private static final ALogger logger = Logger.of(Proxy.class);
@Inject WSClient ws;
public Promise<Result> proxy(String url) {
WSRequest request = ws.url(url).setFollowRedirects(true).setRequestTimeout(10000);
Map<String, String[]> colStr = request().queryString();
for (Map.Entry<String, String[]> entry: colStr.entrySet()) {
for(String entryValue: entry.getValue()) {
request = request.setQueryParameter(entry.getKey(), entryValue);
}
}
Promise<WSResponse> responsePromise = request.get();
Promise<Result> resultPromise = responsePromise.map (response -> {
Integer statusCode = response.getStatus();
if(statusCode >= 500 && statusCode < 600) {
return status(BAD_GATEWAY, response.asByteArray()).as(response.getHeader(CONTENT_TYPE));
} else {
String encodeValue = colStr.get("encoding")[0];
final String body = new String(response.asByteArray(), encodeValue);
StringBuilder strBuilder = new StringBuilder(body);
String strStyle = strBuilder.substring(body.indexOf("<style"), body.indexOf("</style>") + 8);
String strTitle = strBuilder.substring(body.indexOf("<head"), body.indexOf("</head>") + 7);
response().setContentType("text/html; charset=utf-8");
return status(statusCode, body.replace(strStyle, "").replace(strTitle, "").replace("<br/>", ""), "UTF-8");
}
});
Promise<Result> recoveredPromise = resultPromise.recover ((Throwable throwable) -> {
if (throwable instanceof TimeoutException) {
logger.error("Timeout when requesting: " + url, throwable);
return status (GATEWAY_TIMEOUT, throwable.getMessage ());
} else {
logger.error("Error occured when requesting: " + url, throwable);
return status (BAD_GATEWAY, throwable.getMessage ());
}
});
return recoveredPromise;
}
} | GetFeatureInfo -> extract relevant html through Jsoup | app/controllers/Proxy.java | GetFeatureInfo -> extract relevant html through Jsoup | <ide><path>pp/controllers/Proxy.java
<ide> import java.util.concurrent.TimeoutException;
<ide>
<ide> import javax.inject.Inject;
<add>
<add>import org.jsoup.Jsoup;
<add>import org.jsoup.nodes.Document;
<add>import org.jsoup.nodes.Element;
<add>import org.jsoup.select.Elements;
<ide>
<ide> import play.Logger;
<ide> import play.Logger.ALogger;
<ide> } else {
<ide> String encodeValue = colStr.get("encoding")[0];
<ide> final String body = new String(response.asByteArray(), encodeValue);
<del>
<del> StringBuilder strBuilder = new StringBuilder(body);
<del> String strStyle = strBuilder.substring(body.indexOf("<style"), body.indexOf("</style>") + 8);
<del> String strTitle = strBuilder.substring(body.indexOf("<head"), body.indexOf("</head>") + 7);
<add>
<add> Document doc = Jsoup.parse(body);
<add> Element bodyNew = doc.body();
<add>
<add> Elements br = bodyNew.getElementsByTag("br");
<add> br.remove();
<ide>
<ide> response().setContentType("text/html; charset=utf-8");
<ide>
<del> return status(statusCode, body.replace(strStyle, "").replace(strTitle, "").replace("<br/>", ""), "UTF-8");
<add> return status(statusCode, bodyNew.html(), "UTF-8");
<ide> }
<ide> });
<ide> |
|
Java | bsd-3-clause | b8040fea6e6caf702783ef0eea2ec9151093b6d1 | 0 | NCIP/c3pr,NCIP/c3pr,NCIP/c3pr | package edu.duke.cabig.c3pr.web;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.ParticipantDao;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.Participant;
import edu.duke.cabig.c3pr.domain.validator.ParticipantValidator;
import edu.duke.cabig.c3pr.utils.ConfigurationProperty;
import edu.duke.cabig.c3pr.utils.ContextTools;
import edu.duke.cabig.c3pr.utils.Lov;
import edu.duke.cabig.c3pr.web.participant.ParticipantDetailsTab;
import edu.duke.cabig.c3pr.web.participant.ParticipantTab;
import edu.duke.cabig.c3pr.web.participant.ParticipantWrapper;
/**
* @author Ramakrishna
*/
public class CreateParticipantControllerTest extends ControllerTestCase {
private CreateParticipantController controller = new CreateParticipantController();
private ParticipantDao participantDao;
private HealthCareSiteDaoMock healthcareSiteDao;
private ParticipantValidator participantValidator;
private ConfigurationProperty configurationProperty;
private ApplicationContext context;
private Participant participant;
private ParticipantWrapper participantWrapper = new ParticipantWrapper();
protected void setUp() throws Exception {
super.setUp();
context = ContextTools.createConfigPropertiesApplicationContext();
participant = registerMockFor(Participant.class);
participantWrapper.setParticipant(participant);
participantDao = registerMockFor(ParticipantDao.class);
controller.setParticipantDao(participantDao);
healthcareSiteDao = registerMockFor(HealthCareSiteDaoMock.class);
controller.setHealthcareSiteDao(healthcareSiteDao);
participantValidator = registerMockFor(ParticipantValidator.class);
controller.setParticipantValidator(participantValidator);
configurationProperty = registerMockFor(ConfigurationProperty.class);
controller.setConfigurationProperty(new ConfigurationProperty());
configurationProperty = (ConfigurationProperty) context.getBean("configurationProperty");
controller.setConfigurationProperty(configurationProperty);
((ParticipantTab)controller.getFlow().getTab(0)).setConfigurationProperty(configurationProperty);
((ParticipantTab)controller.getFlow().getTab(0)).setHealthcareSiteDao(healthcareSiteDao);
}
public void testReferenceData() throws Exception {
Map<String, Object> refdata = ((ParticipantDetailsTab)controller.getFlow().getTab(0)).referenceData(request,participantWrapper);
List<Lov> genders = (List<Lov>) refdata.get("administrativeGenderCode");
System.out.println(" Size of ref data : " + refdata.size());
Iterator<Lov> genderIter = genders.iterator();
Lov gender;
while (genderIter.hasNext()) {
gender = genderIter.next();
if (gender.getCode() == "Male") {
assertEquals("Genders missing or wrong", "Male", gender.getDesc());
}
}
}
public void testViewOnGet() throws Exception {
//expect(healthcareSiteDao.getAll()).andReturn(null).times(2);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
assertNotNull("Command not present in model: ", mv);
assertEquals("participant/participant", mv.getViewName());
request.setMethod("GET");
verifyMocks();
}
public void testViewOnGoodSubmit() throws Exception {
request.addParameter("firstName", "John");
request.addParameter("lastName", "Doe");
request.addParameter("birthDate", "02/11/1967");
request.addParameter("administrativeGenderCode", "Male");
request.addParameter("ethnicGroupCode", "Non Hispanic or Latino");
request.addParameter("raceCode", "Not Reported");
request.setParameter("_target1", "");
//expect(healthcareSiteDao.getAll()).andReturn(null).times(2);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
assertNotNull("Command not present in model: ", mv);
assertEquals("participant/participant", mv.getViewName());
request.setMethod("GET");
verifyMocks();
}
public class HealthCareSiteDaoMock extends HealthcareSiteDao {
public List<HealthcareSite> getAll() {
List list = new ArrayList();
list = healthcareSiteDao.getAll();
return list;
}
}
}
| codebase/projects/web/test/src/java/edu/duke/cabig/c3pr/web/CreateParticipantControllerTest.java | package edu.duke.cabig.c3pr.web;
import static org.easymock.EasyMock.expect;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.ParticipantDao;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.Participant;
import edu.duke.cabig.c3pr.domain.validator.ParticipantValidator;
import edu.duke.cabig.c3pr.utils.ConfigurationProperty;
import edu.duke.cabig.c3pr.utils.ContextTools;
import edu.duke.cabig.c3pr.utils.Lov;
import edu.duke.cabig.c3pr.web.participant.ParticipantTab;
/**
* @author Ramakrishna
*/
public class CreateParticipantControllerTest extends ControllerTestCase {
private CreateParticipantController controller = new CreateParticipantController();
private ParticipantDao participantDao;
private HealthCareSiteDaoMock healthcareSiteDao;
private ParticipantValidator participantValidator;
private ConfigurationProperty configurationProperty;
private ApplicationContext context;
private Participant participant;
protected void setUp() throws Exception {
super.setUp();
context = ContextTools.createConfigPropertiesApplicationContext();
participant = registerMockFor(Participant.class);
participantDao = registerMockFor(ParticipantDao.class);
controller.setParticipantDao(participantDao);
healthcareSiteDao = registerMockFor(HealthCareSiteDaoMock.class);
controller.setHealthcareSiteDao(healthcareSiteDao);
participantValidator = registerMockFor(ParticipantValidator.class);
controller.setParticipantValidator(participantValidator);
configurationProperty = registerMockFor(ConfigurationProperty.class);
controller.setConfigurationProperty(new ConfigurationProperty());
configurationProperty = (ConfigurationProperty) context.getBean("configurationProperty");
controller.setConfigurationProperty(configurationProperty);
((ParticipantTab)controller.getFlow().getTab(0)).setConfigurationProperty(configurationProperty);
((ParticipantTab)controller.getFlow().getTab(0)).setHealthcareSiteDao(healthcareSiteDao);
}
public void testReferenceData() throws Exception {
Map<String, Object> refdata = controller.getFlow().getTab(0).referenceData(participant);
List<Lov> genders = (List<Lov>) refdata.get("administrativeGenderCode");
System.out.println(" Size of ref data : " + refdata.size());
Iterator<Lov> genderIter = genders.iterator();
Lov gender;
while (genderIter.hasNext()) {
gender = genderIter.next();
if (gender.getCode() == "Male") {
assertEquals("Genders missing or wrong", "Male", gender.getDesc());
}
}
}
public void testViewOnGet() throws Exception {
//expect(healthcareSiteDao.getAll()).andReturn(null).times(2);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
assertNotNull("Command not present in model: ", mv);
assertEquals("participant/participant", mv.getViewName());
request.setMethod("GET");
verifyMocks();
}
public void testViewOnGoodSubmit() throws Exception {
request.addParameter("firstName", "John");
request.addParameter("lastName", "Doe");
request.addParameter("birthDate", "02/11/1967");
request.addParameter("administrativeGenderCode", "Male");
request.addParameter("ethnicGroupCode", "Non Hispanic or Latino");
request.addParameter("raceCode", "Not Reported");
request.setParameter("_target1", "");
//expect(healthcareSiteDao.getAll()).andReturn(null).times(2);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
assertNotNull("Command not present in model: ", mv);
assertEquals("participant/participant", mv.getViewName());
request.setMethod("GET");
verifyMocks();
}
public class HealthCareSiteDaoMock extends HealthcareSiteDao {
public List<HealthcareSite> getAll() {
List list = new ArrayList();
list = healthcareSiteDao.getAll();
return list;
}
}
}
| test case fix
| codebase/projects/web/test/src/java/edu/duke/cabig/c3pr/web/CreateParticipantControllerTest.java | test case fix | <ide><path>odebase/projects/web/test/src/java/edu/duke/cabig/c3pr/web/CreateParticipantControllerTest.java
<ide> package edu.duke.cabig.c3pr.web;
<del>
<del>import static org.easymock.EasyMock.expect;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Iterator;
<ide> import edu.duke.cabig.c3pr.utils.ConfigurationProperty;
<ide> import edu.duke.cabig.c3pr.utils.ContextTools;
<ide> import edu.duke.cabig.c3pr.utils.Lov;
<add>import edu.duke.cabig.c3pr.web.participant.ParticipantDetailsTab;
<ide> import edu.duke.cabig.c3pr.web.participant.ParticipantTab;
<add>import edu.duke.cabig.c3pr.web.participant.ParticipantWrapper;
<ide>
<ide> /**
<ide> * @author Ramakrishna
<ide> private ApplicationContext context;
<ide>
<ide> private Participant participant;
<add>
<add> private ParticipantWrapper participantWrapper = new ParticipantWrapper();
<ide>
<ide> protected void setUp() throws Exception {
<ide> super.setUp();
<ide> context = ContextTools.createConfigPropertiesApplicationContext();
<ide> participant = registerMockFor(Participant.class);
<add> participantWrapper.setParticipant(participant);
<ide> participantDao = registerMockFor(ParticipantDao.class);
<ide> controller.setParticipantDao(participantDao);
<ide> healthcareSiteDao = registerMockFor(HealthCareSiteDaoMock.class);
<ide> public void testReferenceData() throws Exception {
<ide>
<ide>
<del> Map<String, Object> refdata = controller.getFlow().getTab(0).referenceData(participant);
<add> Map<String, Object> refdata = ((ParticipantDetailsTab)controller.getFlow().getTab(0)).referenceData(request,participantWrapper);
<ide> List<Lov> genders = (List<Lov>) refdata.get("administrativeGenderCode");
<ide> System.out.println(" Size of ref data : " + refdata.size());
<ide> Iterator<Lov> genderIter = genders.iterator();
<ide>
<ide> }
<ide> }
<del>
<ide> }
<ide>
<ide> public void testViewOnGet() throws Exception { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.