answer
stringlengths 17
10.2M
|
|---|
package com.miguelgaeta.super_bar;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
public class SuperBar extends View implements ValueAnimator.AnimatorUpdateListener {
public interface ColorFormatter {
/**
* Given the current state of the bar, return the
* desired color integer.
*
* @param value Current value of the bar.
*
* @param maxValue Maximum value the bar can display.
* @param minValue Minimum value the bar can display.
*
* @return Color integer for current values.
*/
int getColor(float value, float maxValue, float minValue);
/**
* Default color formatter that just returns
* a single color.
*/
class Solid implements ColorFormatter {
private int color;
public Solid(int color) {
this.color = color;
}
@Override
public int getColor(float value, float maxVal, float minVal) {
return color;
}
}
}
public interface OnSelectionChanged {
/**
* Called when the user releases his finger from the ValueBar.
*
* @param value Current value of the bar.
*
* @param maxValue Maximum value the bar can display.
* @param minValue Minimum value the bar can display.
*
*
* @param superBar Associated instance.
*/
void onSelectionChanged(float value, float maxValue, float minValue, SuperBar superBar);
}
public interface OnSelectionMoved {
/**
* Called every time the user moves the finger on the ValueBar.
*
* @param value Current value of the bar.
*
* @param maxValue Maximum value the bar can display.
* @param minValue Minimum value the bar can display.
*
* @param superBar Associated instance.
*/
void onSelectionMoved(float value, float maxValue, float minValue, SuperBar superBar);
}
private final Config config = new Config(this);
@SuppressWarnings("unused")
public Config getConfig() {
return config;
}
private RectF mBar = new RectF();
private RectF mBarBackground = new RectF();
private RectF mBarOverlay = new RectF();
private final Painter paint = new Painter(this);
public SuperBar(Context context) {
super(context);
init();
}
public SuperBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SuperBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
//@Setter @Getter TODO
private int controlShadowSize = 12;
//@Setter @Getter @ColorInt TODO
private int controlShadowColor = Color.argb(127, 0, 0, 0);
//@Setter @Getter @ColorRes TODO
private int controlColor = Color.YELLOW;
//@Setter @Getter TODO
private int barMargin = 12;
//@Setter @Getter @ColorInt TODO
private int backgroundBarColor = Color.GREEN;
/**
* Do all preparations.
*/
private void init() {
// Needed to render shadow.
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
view.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return false;
}
});
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final float shadowRadius = controlShadowSize / 2f;
final float halfMargin = barMargin / 2f;
final float controlRadius = (getHeight() / 2f);
float length = ((getWidth() - (controlRadius * 2)) / (config.maxBarValue - config.minBarValue)) * (config.barValue - config.minBarValue);
mBar.set(controlRadius, shadowRadius + halfMargin, length + controlRadius, getHeight() - shadowRadius - halfMargin);
drawBackgroundBar(canvas, shadowRadius, halfMargin, controlRadius);
paint.setColor(config.color.getColor(config.barValue, config.maxBarValue, config.minBarValue));
// draw the value-bar
canvas.drawRoundRect(mBar, mBar.height() / 2f, mBar.height() / 2f, paint);
drawOverlayBar(canvas, shadowRadius, halfMargin, controlRadius);
paint.setColor(controlColor, shadowRadius, controlShadowColor);
// Dragging control.
canvas.drawCircle(mBar.right, (getHeight() / 2f), controlRadius - shadowRadius, paint);
}
private void drawBackgroundBar(Canvas canvas, float halfShadow, float halfMargin, float controlRadius) {
mBarBackground.set(controlRadius, halfShadow + halfMargin, getWidth() - controlRadius, getHeight() - halfShadow - halfMargin);
paint.setColor(backgroundBarColor);
canvas.drawRoundRect(mBarBackground, mBarBackground.height() / 2f, mBarBackground.height() / 2f, paint);
}
private void drawOverlayBar(Canvas canvas, float halfShadow, float halfMargin, float controlRadius) {
float length = ((getWidth() - (controlRadius * 2)) / (config.maxBarValue - config.minBarValue)) * (config.overlayBarValue - config.minBarValue);
mBarOverlay.set(length + controlRadius, halfShadow + halfMargin, getWidth() - controlRadius, getHeight() - halfShadow - halfMargin);
paint.setColor(config.overlayBarColor.getColor(config.overlayBarValue, config.maxBarValue, config.minBarValue));
canvas.drawRoundRect(mBarOverlay, mBarBackground.height() / 2f, mBarBackground.height() / 2f, paint);
}
@Override
public void onAnimationUpdate(ValueAnimator va) {
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
if (!config.touchEnabled) {
return super.onTouchEvent(motionEvent);
}
if (config.gestureDetector != null &&
config.gestureDetector.onTouchEvent(motionEvent)) {
return true;
}
float x = motionEvent.getX();
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
updateValue(x);
invalidate();
case MotionEvent.ACTION_MOVE:
updateValue(x);
invalidate();
if (config.onSelectionMoved != null) {
config.onSelectionMoved.onSelectionMoved(config.barValue, config.maxBarValue, config.minBarValue, this);
}
break;
case MotionEvent.ACTION_UP:
updateValue(x);
invalidate();
if (config.onSelectionChanged != null) {
config.onSelectionChanged.onSelectionChanged(config.barValue, config.maxBarValue, config.minBarValue, this);
}
break;
}
return true;
}
/**
* Updates the value on the ValueBar depending on the touch position.
*/
private void updateValue(float x) {
float newVal;
if (x <= 0)
newVal = config.minBarValue;
else if (x > getWidth())
newVal = config.maxBarValue;
else {
float factor = x / getWidth();
newVal = (config.maxBarValue - config.minBarValue) * factor + config.minBarValue;
}
if (config.barInterval > 0f) {
float remainder = newVal % config.barInterval;
// check if the new value is closer to the next, or the previous
if (remainder <= config.barInterval / 2f) {
newVal = newVal - remainder;
} else {
newVal = newVal - remainder + config.barInterval;
}
}
config.barValue = newVal;
}
private static class Painter extends Paint {
private final View view;
private Painter(View view) {
super();
this.view = view;
setFlags(Paint.ANTI_ALIAS_FLAG);
setStyle(Paint.Style.FILL);
}
@Override
public void setColor(int color) {
setColor(color, null, 0);
}
private void setColor(int color, Float shadowRadius, int shadowColor) {
if (!view.isInEditMode() && shadowRadius != null) {
setShadowLayer(shadowRadius, 0f, 0f, shadowColor);
} else {
clearShadowLayer();
}
super.setColor(color);
}
}
public static class Config {
private final SuperBar superBar;
private Config(SuperBar superBar) {
this.superBar = superBar;
}
private OnSelectionChanged onSelectionChanged;
private OnSelectionMoved onSelectionMoved;
private float barValue = 40f;
private float minBarValue = 0f;
private float maxBarValue = 100f;
private float barInterval = 1f;
private ColorFormatter color = new ColorFormatter.Solid(Color.BLUE);
private GestureDetector gestureDetector;
private boolean touchEnabled = true;
private float overlayBarValue = 90f;
private ColorFormatter overlayBarColor = new ColorFormatter.Solid(Color.RED);
/**
* Set overlay bar value.
* @param overlayBarValue Target bar value.
*/
@SuppressWarnings("unused")
public void setOverlayBarValue(float overlayBarValue) {
this.overlayBarValue = overlayBarValue;
superBar.invalidate();
}
/**
* Get the current value of the overlay bar.
*
* @return Current value of the overlay bar.
*/
@SuppressWarnings("unused")
public float getOverlayBarValue() {
return overlayBarValue;
}
/**
* Sets a custom color formatter for the overlay bar.
*
* @param colorFormatter Color formatter.
*/
public void setOverlayBarColor(ColorFormatter colorFormatter) {
if (colorFormatter == null) {
return;
}
this.overlayBarColor = colorFormatter;
}
/**
* Set a solid color for the overlay bar.
*
* @param color Color.
*/
@SuppressWarnings("unused")
public void setOverlayBarColor(int color) {
setOverlayBarColor(new ColorFormatter.Solid(color));
}
/**
* Set a callback to be fired when the current bar selection
* value is changed by the user.
*
* @param onSelectionChanged Selection changed callback.
*/
@SuppressWarnings("unused")
public void setSelectedChanged(OnSelectionChanged onSelectionChanged) {
this.onSelectionChanged = onSelectionChanged;
}
/***
* Set a callback to be fired when the current bar selection
* value if moved by the user.
*
* @param onSelectionMoved Selection moved callback.
*/
@SuppressWarnings("unused")
public void setOnSelectionMoved(OnSelectionMoved onSelectionMoved) {
this.onSelectionMoved = onSelectionMoved;
}
/**
* Get the current value of the bar.
*
* @return Current value of the bar.
*/
@SuppressWarnings("unused")
public float getBarValue() {
return barValue;
}
/**
* Set bar value from it's current position to another
* value within it's bounds.
*
* @param durationMillis Duration in milliseconds - if null will not animate.
*
* @param barValue Target bar value.
*/
@SuppressWarnings("unused")
public void setBarValue(Integer durationMillis, float barValue) {
setBarValue(durationMillis, barValue, this.barValue);
}
/**
* Set bar value from any value within it's bounds to another
* value within it's bounds.
*
* @param durationMillis Duration in milliseconds - if null will not animate.
*
* @param barValue Target bar value.
* @param barValueFrom Starting bar value.
*/
public void setBarValue(Integer durationMillis, float barValue, float barValueFrom) {
if (barValueFrom < minBarValue) {
barValueFrom = minBarValue;
}
if (barValueFrom > maxBarValue) {
barValueFrom = maxBarValue;
}
if (barValue < minBarValue) {
barValue = minBarValue;
}
if (barValue > maxBarValue) {
barValue = maxBarValue;
}
if (durationMillis == null) {
this.barValue = barValue;
superBar.invalidate();
} else {
final ObjectAnimator animator = ObjectAnimator.ofFloat(this, "barValue", barValueFrom, barValue);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.setDuration(durationMillis);
animator.addUpdateListener(superBar);
animator.start();
}
}
/**
* Sets the minimum and maximum value the bar can display.
*
* @param minBarValue Minimum value.
* @param maxBarValue Maximum value.
*/
@SuppressWarnings("unused")
public void setBarValueBounds(float minBarValue, float maxBarValue) {
this.maxBarValue = maxBarValue;
this.minBarValue = minBarValue;
}
/**
* Returns the maximum value the bar can display.
*
* @return Maximum value.
*/
@SuppressWarnings("unused")
public float getMaxBarValue() {
return maxBarValue;
}
/**
* Returns the minimum value the bar can display.
*
* @return Minimum value.
*/
@SuppressWarnings("unused")
public float getMinBarValue() {
return minBarValue;
}
/**
* Sets the interval in which the values can be chosen and displayed
* from the bar slider.
*
* If interval less than 0, there is no interval.
*
* @param barInterval Bar value interval.
*/
@SuppressWarnings("unused")
public void setBarInterval(float barInterval) {
this.barInterval = barInterval;
}
/**
* Returns bar interval.
*
* @return Bar interval.
*/
@SuppressWarnings("unused")
public float getBarInterval() {
return barInterval;
}
/**
* Sets a custom color formatter for the bar.
*
* @param colorFormatter Color formatter.
*/
public void setColor(ColorFormatter colorFormatter) {
if (colorFormatter == null) {
return;
}
this.color = colorFormatter;
}
/**
* Set a solid color for the bar.
*
* @param color Color.
*/
@SuppressWarnings("unused")
public void setColor(int color) {
setColor(new ColorFormatter.Solid(color));
}
/**
* Set a gesture detector for consumers that wish
* to add custom handling of touch events.
*
* @param gestureDetector Detector that returns true if event is consumed.
*/
@SuppressWarnings("unused")
public void setGestureDetector(GestureDetector gestureDetector) {
this.gestureDetector = gestureDetector;
}
/**
* Set this to true to enable touch gestures on the bar control.
*
* @param touchEnabled Is touch enabled.
*/
@SuppressWarnings("unused")
public void setTouchEnabled(boolean touchEnabled) {
this.touchEnabled = touchEnabled;
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.venky.swf.controller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.venky.core.io.ByteArrayInputStream;
import com.venky.core.string.StringUtil;
import com.venky.core.util.ObjectUtil;
import com.venky.digest.Encryptor;
import com.venky.swf.controller.annotations.Depends;
import com.venky.swf.controller.annotations.SingleRecordAction;
import com.venky.swf.db.Database;
import com.venky.swf.db.annotations.column.pm.PARTICIPANT;
import com.venky.swf.db.annotations.column.ui.CONTENT_TYPE;
import com.venky.swf.db.annotations.column.ui.mimes.MimeType;
import com.venky.swf.db.model.Model;
import com.venky.swf.db.model.reflection.ModelReflector;
import com.venky.swf.db.table.Record;
import com.venky.swf.db.table.Table;
import com.venky.swf.exceptions.AccessDeniedException;
import com.venky.swf.path.Path;
import com.venky.swf.path.Path.ModelInfo;
import com.venky.swf.sql.Conjunction;
import com.venky.swf.sql.Expression;
import com.venky.swf.sql.Operator;
import com.venky.swf.sql.Select;
import com.venky.swf.views.BytesView;
import com.venky.swf.views.HtmlView;
import com.venky.swf.views.RedirectorView;
import com.venky.swf.views.View;
import com.venky.swf.views.model.ModelEditView;
import com.venky.swf.views.model.ModelListView;
import com.venky.swf.views.model.ModelShowView;
/**
*
* @author venky
*/
public class ModelController<M extends Model> extends Controller {
private Class<M> modelClass;
private ModelReflector<M> reflector ;
public ModelController(Path path) {
super(path);
modelClass = getPath().getModelClass();
reflector = ModelReflector.instance(modelClass);
}
protected ModelReflector<M> getReflector(){
return reflector;
}
@Override
public View index() {
Select q = new Select().from(modelClass);
List<M> records = q.where(getPath().getWhereClause()).execute(modelClass, new Select.AccessibilityFilter<M>());
return index(records);
}
protected View index(List<M> records){
return dashboard(createListView(records));
}
protected HtmlView createListView(List<M> records){
return new ModelListView<M>(getPath(), modelClass, getIncludedFields(), records);
}
protected String[] getIncludedFields(){
return null;
}
protected Class<M> getModelClass() {
return modelClass;
}
@SingleRecordAction(icon="/resources/images/show.png")
public View show(int id) {
M record = Database.getTable(modelClass).get(id);
if (record.isAccessibleBy(getSessionUser(),modelClass)){
return dashboard(new ModelShowView<M>(getPath(), modelClass, getIncludedFields(), record));
}else {
throw new AccessDeniedException();
}
}
public View view(int id){
M record = Database.getTable(modelClass).get(id);
if (record.isAccessibleBy(getSessionUser(),modelClass)){
try {
for (Method getter : reflector.getFieldGetters()){
if (InputStream.class.isAssignableFrom(getter.getReturnType())){
CONTENT_TYPE ct = reflector.getAnnotation(getter,CONTENT_TYPE.class);
MimeType mimeType = MimeType.TEXT_PLAIN;
if (ct != null){
mimeType = ct.value();
}
return new BytesView(getPath(), StringUtil.readBytes((InputStream)getter.invoke(record)), mimeType);
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}else {
throw new AccessDeniedException();
}
return back();
}
@SingleRecordAction(icon="/resources/images/edit.png")
@Depends("save")
public View edit(int id) {
M record = Database.getTable(modelClass).get(id);
if (record.isAccessibleBy(getSessionUser(),modelClass)){
return dashboard(new ModelEditView<M>(getPath(), modelClass, getIncludedFields(), record));
}else {
throw new AccessDeniedException();
}
}
@SingleRecordAction(icon="/resources/images/clone.png")
@Depends("save")
public View clone(int id){
Table<M> table = Database.getTable(modelClass);
M record = table.get(id);
M newrecord = table.newRecord();
Record oldRaw = record.getRawRecord();
Record newRaw = newrecord.getRawRecord();
for (String f:oldRaw.getFieldNames()){ //Fields in raw records are column names.
if (!reflector.isHouseKeepingField(reflector.getFieldName(f))){
newRaw.put(f, oldRaw.get(f));
}
}
newRaw.setNewRecord(true);
ModelEditView<M> mev = new ModelEditView<M>(getPath(), modelClass, getIncludedFields(), newrecord);
for (String field : reflector.getFields()){
if (reflector.isHouseKeepingField(field)){
mev.getIncludedFields().remove(field);
}
}
return dashboard(mev);
}
@Depends("save")
public View blank(){
M record = Database.getTable(modelClass).newRecord();
return blank(record);
}
protected View blank(M record) {
List<ModelInfo> modelElements = getPath().getModelElements();
for (Method referredModelGetter: reflector.getReferredModelGetters()){
Class<? extends Model> referredModelClass = (Class<? extends Model>)referredModelGetter.getReturnType();
String referredModelIdFieldName = reflector.getReferenceField(referredModelGetter);
Method referredModelIdSetter = reflector.getFieldSetter(referredModelIdFieldName);
Method referredModelIdGetter = reflector.getFieldGetter(referredModelIdFieldName);
try {
Integer oldValue = (Integer) referredModelIdGetter.invoke(record);
List<Integer> idoptions = getSessionUser().getParticipationOptions(modelClass).get(referredModelIdFieldName);
Integer id = null;
if (oldValue == null){
if (idoptions != null && !idoptions.isEmpty() && idoptions.size() == 1){
id = idoptions.get(0);
if (id != null){
Model referredModel = Database.getTable(referredModelClass).get(id);
if (referredModel.isAccessibleBy(getSessionUser(),referredModelClass)){
referredModelIdSetter.invoke(record,id);
continue;
}
}
}
}
for (Iterator<ModelInfo> miIter = modelElements.iterator() ; miIter.hasNext() ;){
ModelInfo mi = miIter.next();
if(!miIter.hasNext()){
//last model is self.
break;
}
if (mi.getReflector().reflects(referredModelClass)){
try {
Model referredModel = Database.getTable(referredModelClass).get(mi.getId());
if (referredModel.isAccessibleBy(getSessionUser(),referredModelClass)){
referredModelIdSetter.invoke(record, mi.getId());
break;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
record.setCreatorUserId(getSessionUser().getId());
record.setUpdaterUserId(getSessionUser().getId());
ModelEditView<M> mev = new ModelEditView<M>(getPath(), modelClass, getIncludedFields(), record);
for (String field : reflector.getFields()){
if (reflector.isHouseKeepingField(field)){
mev.getIncludedFields().remove(field);
}
}
return dashboard(mev);
}
@SingleRecordAction(icon="/resources/images/destroy.png")
public View destroy(int id){
M record = Database.getTable(modelClass).get(id);
if (record != null){
if (record.isAccessibleBy(getSessionUser(),modelClass)){
record.destroy();
}else {
throw new AccessDeniedException();
}
}
return back();
}
public RedirectorView back(){
RedirectorView v = new RedirectorView(getPath());
v.setRedirectUrl(getPath().getBackTarget());
return v;
}
private RedirectorView redirectTo(String action){
RedirectorView v = new RedirectorView(getPath(),action);
return v;
}
protected Map<String,Object> getFormFields(HttpServletRequest request){
Map<String,Object> formFields = new HashMap<String, Object>();
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart){
FileItemFactory factory = new DiskFileItemFactory(1024*1024*128, new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload fu = new ServletFileUpload(factory);
try {
List<FileItem> fis = fu.parseRequest(request);
for (FileItem fi:fis){
if (fi.isFormField()){
if (!formFields.containsKey(fi.getFieldName())){
formFields.put(fi.getFieldName(), fi.getString());
}
}else {
formFields.put(fi.getFieldName(), new ByteArrayInputStream(StringUtil.readBytes(fi.getInputStream())));
}
}
} catch (FileUploadException e1) {
throw new RuntimeException(e1);
} catch (IOException e1){
throw new RuntimeException(e1);
}
}else {
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()){
String name =parameterNames.nextElement();
formFields.put(name,request.getParameter(name));
}
}
return formFields;
}
private View persistInDB(){
HttpServletRequest request = getPath().getRequest();
if (!request.getMethod().equalsIgnoreCase("POST")) {
throw new RuntimeException("Cannot call save in any other method other than POST");
}
Map<String,Object> formFields = getFormFields(request);
String id = (String)formFields.get("ID");
String lockId = (String)formFields.get("LOCK_ID");
M record = null;
if (ObjectUtil.isVoid(id)) {
record = Database.getTable(modelClass).newRecord();
} else {
record = Database.getTable(modelClass).get(Integer.valueOf(id));
if (!ObjectUtil.isVoid(lockId)) {
if (record.getLockId() != Long.parseLong(lockId)) {
throw new RuntimeException("Stale record update prevented. Please reload and retry!");
}
}
if (!record.isAccessibleBy(getSessionUser(),modelClass)){
throw new AccessDeniedException();
}
}
List<String> fields = reflector.getRealFields();
Iterator<String> e = formFields.keySet().iterator();
String buttonName = null;
String digest = null;
while (e.hasNext()) {
String name = e.next();
String fieldName = fields.contains(name) && !reflector.isHouseKeepingField(name) ? name : null;
if (fieldName != null) {
Object value = formFields.get(fieldName);
reflector.set(record, fieldName, value);
}else if ( name.startsWith("_SUBMIT")){
buttonName = name;
}else if ( name.startsWith("_FORM_DIGEST")){
digest = (String)formFields.get("_FORM_DIGEST");
}
}
boolean isNew = false;
if (hasUserModifiedData(formFields,digest)){
if (record.getRawRecord().isNewRecord()){
isNew = true;
record.setCreatorUserId(getSessionUser().getId());
record.setCreatedAt(null);
}
record.setUpdaterUserId(getSessionUser().getId());
record.setUpdatedAt(null);
if (record.isAccessibleBy(getSessionUser(),modelClass)){
record.save();
if (!getPath().canAccessControllerAction("save",String.valueOf(record.getId()))){
Database.getInstance().getCache(reflector).clear();
throw new AccessDeniedException();
}
}else {
throw new AccessDeniedException();
}
}
if (isNew && buttonName.equals("_SUBMIT_MORE") && getPath().canAccessControllerAction("blank",String.valueOf(record.getId()))){
return redirectTo("blank");
}
return back();
}
protected boolean hasUserModifiedData(Map<String,Object> formFields, String oldDigest){
StringBuilder hash = null;
for (String field: reflector.getFields()){
if (!formFields.containsKey(field)){
continue;
}
Object currentValue = formFields.get(field);
if (currentValue != null && currentValue instanceof InputStream){
if (StringUtil.readBytes((InputStream)currentValue).length > 0){
return true;
}
currentValue = "";
}
if (hash != null){
hash.append(",");
}else {
hash = new StringBuilder();
}
hash.append(field).append("=").append((String)currentValue);
}
String newDigest = hash == null ? null : Encryptor.encrypt(hash.toString());
return !ObjectUtil.equals(newDigest, oldDigest);
}
public View save() {
return persistInDB();
}
public View autocomplete() {
List<String> fields = reflector.getFields();
Map<String,Object> formData = getFormFields(getPath().getRequest());
M model = null;
if (formData.containsKey("ID")){
model = Database.getTable(modelClass).get(Integer.valueOf(formData.get("ID").toString()));
}else {
model = Database.getTable(modelClass).newRecord();
}
model = model.cloneProxy();
String autoCompleteFieldName = null;
String value = "";
for (String fieldName : formData.keySet()){
if (fields.contains(fieldName)){
Object ov = formData.get(fieldName);
reflector.set(model,fieldName, ov);
}else if (fieldName.startsWith("_AUTO_COMPLETE_")){
autoCompleteFieldName = fieldName.split("_AUTO_COMPLETE_")[1];
value = StringUtil.valueOf(formData.get(fieldName));
}
}
model.getRawRecord().remove(autoCompleteFieldName);
Expression where = new Expression(Conjunction.AND);
if (reflector.isAnnotationPresent(reflector.getFieldGetter(autoCompleteFieldName),PARTICIPANT.class)){
Map<String,List<Integer>> pOptions = getSessionUser().getParticipationOptions(reflector.getModelClass(),model);
if (pOptions.containsKey(autoCompleteFieldName)){
List<Integer> autoCompleteFieldValues = pOptions.get(autoCompleteFieldName);
if (!autoCompleteFieldValues.isEmpty()){
autoCompleteFieldValues.remove(null); // We need not try to use null for lookups.
where.add(new Expression("ID",Operator.IN,autoCompleteFieldValues.toArray()));
}
}
}
Class<? extends Model> autoCompleteModelClass = reflector.getReferredModelClass(reflector.getReferredModelGetterFor(reflector.getFieldGetter(autoCompleteFieldName)));
ModelReflector<? extends Model> autoCompleteModelReflector = ModelReflector.instance(autoCompleteModelClass);
Path autoCompletePath = getPath().createRelativePath(autoCompleteModelReflector.getTableName().toLowerCase());
where.add(autoCompletePath.getWhereClause());
return super.autocomplete(autoCompleteModelClass, where, autoCompleteModelReflector.getDescriptionColumn(), value);
}
}
|
package com.creative.service;
import java.util.concurrent.ConcurrentHashMap;
import com.creative.context.Context;
import com.creative.disruptor.DisruptorEvent;
import org.json.JSONException;
public class StateService implements GeneralService {
public StateService(){
}
ConcurrentHashMap <String,String> messageList = new ConcurrentHashMap<String, String>();
public boolean canHandle(String command) {
if(command == null || "".equals(command)) return false;
return command.startsWith("STATE_");
}
@Override
public void onEvent(DisruptorEvent event) throws Exception {
Context context = event.context;
String command;
try{
command = context.getRequest().get(GeneralService.COMMAND);
}catch(JSONException e){
return;
}
if(!canHandle(command)) return;
String result = "";
switch(command){
case "STATE_GET":
result = messageList.get(context.getRequest().get(GeneralService.FROM));
break;
case "STATE_INFO":
result = getInfo();
break;
case "STATE_STATUS":
result = getStatus();
break;
case "STATE_SET":
messageList.put(context.getRequest().get(GeneralService.TO), context.getRequest().toString());
result = "{STATE:OK}";
break;
}
if(result == null || "".equals(result)) result = "{COMMAND:STATE_SET;FROM:nil;TO:"+ context.getRequest().get(GeneralService.FROM) +";DATA:nil}";
context.setResponse(result);
}
private String getStatus() {
// TODO Auto-generated method stub
return null;
}
private String getInfo() {
// TODO Auto-generated method stub
return null;
}
}
|
package org.intermine.web;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Collection;
import java.util.Date;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryNode;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ClassConstraint;
import org.intermine.util.TypeUtil;
/**
* Helper methods for main controller and main action
* @author Mark Woodbridge
*/
public class MainHelper
{
/**
* Given a path, render a set of metadata Nodes to the relevant depth
* @param path of form Gene.organism.name
* @param model the model used to resolve class names
* @return an ordered Set of nodes
*/
public static Collection makeNodes(String path, Model model) {
String className, subPath;
if (path.indexOf(".") == -1) {
className = path;
subPath = "";
} else {
className = path.substring(0, path.indexOf("."));
subPath = path.substring(path.indexOf(".") + 1);
}
Map nodes = new LinkedHashMap();
nodes.put(className, new MetadataNode(className));
makeNodes(getClassDescriptor(className, model), subPath, className, nodes);
return nodes.values();
}
/**
* Recursive method used to add nodes to a set representing a path from a given ClassDescriptor
* @param cld the root ClassDescriptor
* @param path current path prefix (eg Gene)
* @param currentPath current path suffix (eg organism.name)
* @param nodes the current Node set
*/
protected static void makeNodes(ClassDescriptor cld, String path, String currentPath,
Map nodes) {
List sortedNodes = new ArrayList();
// compare FieldDescriptors by name
Comparator comparator = new Comparator() {
public int compare(Object o1, Object o2) {
return ((FieldDescriptor) o1).getName().compareTo(((FieldDescriptor) o2).getName());
}
};
Set attributeNodes = new TreeSet(comparator);
Set referenceAndCollectionNodes = new TreeSet(comparator);
for (Iterator i = cld.getAllFieldDescriptors().iterator(); i.hasNext();) {
FieldDescriptor fd = (FieldDescriptor) i.next();
if (!fd.isReference() && !fd.isCollection()) {
attributeNodes.add(fd);
} else {
referenceAndCollectionNodes.add(fd);
}
}
sortedNodes.addAll(attributeNodes);
sortedNodes.addAll(referenceAndCollectionNodes);
for (Iterator i = sortedNodes.iterator(); i.hasNext();) {
FieldDescriptor fd = (FieldDescriptor) i.next();
String fieldName = fd.getName();
if (fieldName.equals("id")) {
continue;
}
String head, tail;
if (path.indexOf(".") != -1) {
head = path.substring(0, path.indexOf("."));
tail = path.substring(path.indexOf(".") + 1);
} else {
head = path;
tail = "";
}
String button;
if (fieldName.equals(head)) {
button = "-";
} else if (fd.isReference() || fd.isCollection()) {
button = "+";
} else {
button = " ";
}
MetadataNode parent = (MetadataNode) nodes.get(currentPath);
MetadataNode node = new MetadataNode(parent, fieldName, cld.getModel(), button);
nodes.put(node.getPath(), node);
if (fieldName.equals(head)) {
ClassDescriptor refCld = ((ReferenceDescriptor) fd).getReferencedClassDescriptor();
makeNodes(refCld, tail, currentPath + "." + head, nodes);
}
}
}
/**
* Make an InterMine query from a path query
* @param query the PathQuery
* @param savedBags the current saved bags map
* @return an InterMine Query
*/
public static Query makeQuery(PathQuery query, Map savedBags) {
query = (PathQuery) query.clone();
Map qNodes = query.getNodes();
List view = query.getView();
Model model = query.getModel();
//first merge the query and the view
for (Iterator i = view.iterator(); i.hasNext();) {
String path = (String) i.next();
if (!qNodes.containsKey(path)) {
query.addNode(path);
}
}
//create the real query
Query q = new Query();
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
q.setConstraint(cs);
Map queryBits = new HashMap();
//build the FROM and WHERE clauses
for (Iterator i = query.getNodes().values().iterator(); i.hasNext();) {
PathNode node = (PathNode) i.next();
String path = node.getPath();
if (path.indexOf(".") == -1) {
QueryClass qc = new QueryClass(getClass(node.getType(), model));
q.addFrom(qc);
queryBits.put(path, qc);
} else {
String fieldName = node.getFieldName();
QueryClass parentQc = (QueryClass) queryBits.get(node.getPrefix());
if (node.isAttribute()) {
QueryField qf = new QueryField(parentQc, fieldName);
queryBits.put(path, qf);
} else {
QueryReference qr = null;
if (node.isReference()) {
qr = new QueryObjectReference(parentQc, fieldName);
} else {
qr = new QueryCollectionReference(parentQc, fieldName);
}
QueryClass qc = new QueryClass(getClass(node.getType(), model));
cs.addConstraint(new ContainsConstraint(qr, ConstraintOp.CONTAINS, qc));
q.addFrom(qc);
queryBits.put(path, qc);
}
}
QueryNode qn = (QueryNode) queryBits.get(path);
for (Iterator j = node.getConstraints().iterator(); j.hasNext();) {
Constraint c = (Constraint) j.next();
if (BagConstraint.VALID_OPS.contains(c.getOp())) {
cs.addConstraint(new BagConstraint(qn,
c.getOp(),
(Collection) savedBags.get(c.getValue())));
} else if (node.isAttribute()) { //assume, for now, that it's a SimpleConstraint
cs.addConstraint(new SimpleConstraint((QueryField) qn,
c.getOp(),
new QueryValue(c.getValue())));
} else if (node.isReference()) {
QueryClass refQc = (QueryClass) queryBits.get(c.getValue());
cs.addConstraint(new ClassConstraint((QueryClass) qn, c.getOp(), refQc));
}
}
}
//build the SELECT list
for (Iterator i = view.iterator(); i.hasNext();) {
q.addToSelect((QueryNode) queryBits.get((String) i.next()));
}
return q;
}
/**
* Instantiate a class by unqualified name
* The name should be "InterMineObject" or the name of class in the model provided
* @param className the name of the class
* @param model the Model used to resolve class names
* @return the relevant Class
*/
public static Class getClass(String className, Model model) {
if ("InterMineObject".equals(className)) {
className = "org.intermine.model.InterMineObject";
} else {
className = model.getPackageName() + "." + className;
}
try {
return Class.forName(className);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Instantiate a class by unqualified name
* The name should be "Date" or that of a primitive container class such as "Integer"
* @param className the name of the class
* @return the relevant Class
*/
public static Class getClass(String className) {
Class cls = TypeUtil.instantiate(className);
if (cls == null) {
if ("Date".equals(className)) {
cls = Date.class;
} else {
try {
cls = Class.forName("java.lang." + className);
} catch (Exception e) {
}
}
}
return cls;
}
/**
* Get the metadata for a class by unqualified name
* The name is looked up in the provided model
* @param className the name of the class
* @param model the Model used to resolve class names
* @return the relevant ClassDescriptor
*/
public static ClassDescriptor getClassDescriptor(String className, Model model) {
return model.getClassDescriptorByName(getClass(className, model).getName());
}
/**
* Take a Collection of ConstraintOps and builds a map from ConstraintOp.getIndex() to
* ConstraintOp.toString() for each
* @param ops a Collection of ConstraintOps
* @return the Map from index to string
*/
public static Map mapOps(Collection ops) {
Map opString = new LinkedHashMap();
for (Iterator iter = ops.iterator(); iter.hasNext();) {
ConstraintOp op = (ConstraintOp) iter.next();
opString.put(op.getIndex(), op.toString());
}
return opString;
}
/**
* Create constraint values for display. Returns a Map from Constraint to String
* for each Constraint in the path query.
*
* @param pathquery the PathQuery to look at
* @return Map from Constraint to displat value
*/
public static Map makeConstraintDisplayMap(PathQuery pathquery) {
Map map = new HashMap();
Iterator iter = pathquery.getNodes().values().iterator();
while (iter.hasNext()) {
PathNode node = (PathNode) iter.next();
Iterator citer = node.getConstraints().iterator();
while (citer.hasNext()) {
Constraint con = (Constraint) citer.next();
ConstraintOp op = con.getOp();
map.put(con, con.getDisplayValue(node));
}
}
return map;
}
}
|
package net.machinemuse.powersuits.common;
import java.lang.reflect.Field;
import java.util.Arrays;
import net.machinemuse.api.ModularCommon;
import net.machinemuse.api.ModuleManager;
import net.machinemuse.general.gui.MuseIcon;
import net.machinemuse.powersuits.item.IModularItem;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModule;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.Configuration;
import cpw.mods.fml.common.Loader;
public class ModCompatability {
public static boolean isGregTechLoaded() {
return Loader.isModLoaded("GregTech_Addon");
}
public static boolean isBasicComponentsLoaded() {
return Loader.isModLoaded("BasicComponents");
}
public static boolean isIndustrialCraftLoaded() {
return Loader.isModLoaded("IC2");
}
public static boolean isThaumCraftLoaded() {
return Loader.isModLoaded("Thaumcraft");
}
public static boolean isThermalExpansionLoaded() {
return Loader.isModLoaded("ThermalExpansion");
}
public static boolean enableThaumGogglesModule() {
boolean defaultval = isThaumCraftLoaded();
return Config.getConfig().get("Special Modules", "Thaumcraft Goggles Module", defaultval).getBoolean(defaultval);
}
public static boolean vanillaRecipesEnabled() {
boolean defaultval = (!isBasicComponentsLoaded()) && (!isIndustrialCraftLoaded());
return Config.getConfig().get(Configuration.CATEGORY_GENERAL, "Vanilla Recipes", defaultval).getBoolean(defaultval);
}
public static boolean UERecipesEnabled() {
boolean defaultval = isBasicComponentsLoaded();
return Config.getConfig().get(Configuration.CATEGORY_GENERAL, "Universal Electricity Recipes", defaultval).getBoolean(defaultval);
}
public static boolean IC2RecipesEnabled() {
boolean defaultval = isIndustrialCraftLoaded() && (!isGregTechLoaded());
return Config.getConfig().get(Configuration.CATEGORY_GENERAL, "IndustrialCraft Recipes", defaultval).getBoolean(defaultval);
}
public static boolean GregTechRecipesEnabled() {
boolean defaultval = isGregTechLoaded();
return Config.getConfig().get(Configuration.CATEGORY_GENERAL, "Gregtech Recipes", defaultval).getBoolean(defaultval);
}
public static boolean ThermalExpansionRecipesEnabled() {
boolean defaultval = isThermalExpansionLoaded();
return Config.getConfig().get(Configuration.CATEGORY_GENERAL, "Thermal Expansion Recipes", defaultval).getBoolean(defaultval);
}
public static int joulesToEU(double joules) {
return (int) (joules / getIC2Ratio());
}
public static double joulesFromEU(int eu) {
return getIC2Ratio() * eu;
}
public static double getIC2Ratio() {
return Config.getConfig().get(Configuration.CATEGORY_GENERAL, "Joules per IC2 EU", 0.4).getDouble(0.4);
}
public static double getBCRatio() {
return Config.getConfig().get(Configuration.CATEGORY_GENERAL, "Joules per MJ", 1.0).getDouble(1.0);
}
// These 2 elements are basically copied from IC2 api
private static Class Ic2Items;
public static ItemStack getIC2Item(String name) {
try {
if (Ic2Items == null)
Ic2Items = Class.forName("ic2.core.Ic2Items");
Object ret = Ic2Items.getField(name).get(null);
if (ret instanceof ItemStack) {
return ((ItemStack) ret).copy();
} else {
return null;
}
} catch (Exception e) {
System.out.println("IC2 API: Call getItem failed for " + name);
return null;
}
}
public static ItemStack getGregtechItem(int aIndex, int aAmount, int aMeta) {
try {
return (ItemStack) Class.forName("gregtechmod.GT_Mod")
.getMethod("getGregTechItem", new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE })
.invoke(null, new Object[] { Integer.valueOf(aIndex), Integer.valueOf(aAmount), Integer.valueOf(aMeta) });
} catch (Exception e) {}
return null;
}
public static void registerModSpecificModules() {
// Make the IC2 energy ratio show up in config file
getIC2Ratio();
// Add thaumgoggles module
if (ModCompatability.isThaumCraftLoaded() && ModCompatability.enableThaumGogglesModule()) {
Class tcItems;
ItemStack gogglesStack = null;
try {
tcItems = Class.forName("thaumcraft.common.Config");
Field itemGoggles = tcItems.getField("itemGoggles");
Item goggles = (Item) itemGoggles.get(itemGoggles);
gogglesStack = new ItemStack(goggles);
PowerModule module = new PowerModule("Aurameter", Arrays.asList((IModularItem) ModularPowersuits.powerArmorHead), new MuseIcon(
"/thaumcraft/resources/ss_core.png", 144), ModularCommon.CATEGORY_SPECIAL)
.setDescription(
"Connect up some Thaumic goggles to show the nearby aura values. (Does not reveal aura nodes, only shows the HUD)")
.addInstallCost(ItemComponent.laserHologram.copy())
.addInstallCost(gogglesStack);
ModuleManager.addModule(module);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static ItemStack getThermexItem(String string, int quantity) {
try {
return thermalexpansion.api.core.ItemRegistry.getItem(string, quantity);
} catch (Exception e) {
thermalexpansion.api.core.ItemRegistry.printItemNames();
}
MuseLogger.logError("Failed to get Thermal Expansion item " + string);
return null;
}
}
|
package org.ensembl.healthcheck.testcase.funcgen;
import java.sql.Connection;
import java.util.Map;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check that all of certain types of objects have analysis_descriptions. Also check that displayable field is set.
*/
public class AnalysisDescription extends SingleDatabaseTestCase {
String[] types = { "regulatory_feature", "external_feature" }; // annotated_feature?
/**
* Create a new AnalysisDescription testcase.
*/
public AnalysisDescription() {
addToGroup("funcgen");
addToGroup("funcgen-release");
setDescription("Check that all of certain types of objects have analysis_descriptions; also check that displayable field is set.");
setTeamResponsible("Funcgen");
}
/**
* Run the test.
*
* @param dbre The database to use.
* @return true if the test passed.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
result &= checkDescriptions(dbre);
result &= checkDisplayable(dbre);
return result;
} // run
private boolean checkDescriptions(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// cache logic_names by analysis_id
Map logicNamesByAnalID = getLogicNamesFromAnalysisTable(con);
for (int i = 0; i < types.length; i++) {
// get analyses that are used
// special case for transcripts - need to link to gene table and get analysis from there
String sql = "SELECT DISTINCT(analysis_id) FROM " + types[i];
//if (types[i].equals("transcript")) {
// sql = "SELECT DISTINCT(g.analysis_id) FROM gene g, transcript t WHERE t.gene_id=g.gene_id";
String[] analyses = getColumnValues(con, sql);
// check each one has an analysis_description
for (int j = 0; j < analyses.length; j++) {
int count = getRowCount(con, "SELECT COUNT(*) FROM analysis_description WHERE analysis_id=" + analyses[j]);
if (count == 0) {
ReportManager.problem(this, con, "Analysis " + logicNamesByAnalID.get(analyses[j]) + " is used in " + types[i]
+ " but has no entry in analysis_description");
result = false;
} else {
ReportManager.correct(this, con, "Analysis " + logicNamesByAnalID.get(analyses[j]) + " is used in " + types[i]
+ " and has an entry in analysis_description");
}
}
}
return result;
}
private boolean checkDisplayable(DatabaseRegistryEntry dbre) {
return checkNoNulls(dbre.getConnection(), "analysis_description", "displayable");
}
} // AnalysisDescription
|
package org.objectweb.proactive.core.descriptor.data;
import org.objectweb.proactive.ProActive;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.descriptor.services.P2PLookupService;
import org.objectweb.proactive.core.descriptor.services.ServiceThread;
import org.objectweb.proactive.core.descriptor.services.UniversalService;
import org.objectweb.proactive.core.event.NodeCreationEvent;
import org.objectweb.proactive.core.event.NodeCreationEventProducerImpl;
import org.objectweb.proactive.core.event.RuntimeRegistrationEvent;
import org.objectweb.proactive.core.event.RuntimeRegistrationEventListener;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.node.NodeFactory;
import org.objectweb.proactive.core.node.NodeImpl;
import org.objectweb.proactive.core.process.ExternalProcess;
import org.objectweb.proactive.core.process.ExternalProcessDecorator;
import org.objectweb.proactive.core.process.JVMProcess;
import org.objectweb.proactive.core.process.globus.GlobusProcess;
import org.objectweb.proactive.core.process.lsf.LSFBSubProcess;
import org.objectweb.proactive.core.process.prun.PrunSubProcess;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.core.runtime.RuntimeFactory;
import org.objectweb.proactive.core.util.UrlBuilder;
import org.objectweb.proactive.ext.security.PolicyServer;
import java.io.Serializable;
import java.security.cert.X509Certificate;
import java.util.Hashtable;
/**
* A <code>VirtualNode</code> is a conceptual entity that represents one or several nodes. After activation
* a <code>VirtualNode</code> represents one or several nodes.
*
* @author ProActive Team
* @version 1.0, 2002/09/20
* @since ProActive 0.9.3
* @see ProActiveDescriptor
* @see VirtualMachine
*/
public class VirtualNodeImpl extends NodeCreationEventProducerImpl
implements VirtualNode, Serializable, RuntimeRegistrationEventListener {
/** Reference on the local runtime*/
protected transient ProActiveRuntimeImpl proActiveRuntimeImpl;
/** the name of this VirtualNode */
private String name;
/** the property of this virtualNode, property field can take five value: null,unique, unique_singleAO, multiple, multiple_cyclic */
private String property;
/** the list of remote virtual machines associated with this VirtualNode */
private java.util.ArrayList virtualMachines;
/** the list of local virtual machine (normally one) associated with this VirtualNode */
private java.util.ArrayList localVirtualMachines;
/** index of the last associated jvm used */
private int lastVirtualMachineIndex;
/** the list of nodes linked to this VirtualNode that have been created*/
private java.util.ArrayList createdNodes;
/** index of the last node used */
private int lastNodeIndex;
/** Number of Nodes mapped to this VirtualNode in the XML Descriptor */
private int nodeCount;
/** Minimum number of nodes needed for this virtualnode while waiting on the nodes
* creation.
*/
private int minNodeNumber = 0;
/** Number of Nodes mapped to this VitualNode in the XML Descriptor that are actually created */
private int nodeCountCreated;
/** true if the node has been created*/
private boolean nodeCreated = false;
private boolean isActivated = false;
/** the list of VitualNodes Id that this VirualNode is waiting for in order to create Nodes on a JVM
* already assigned in the XML descriptor */
private Hashtable awaitedVirtualNodes;
private String registrationProtocol;
private boolean registration = false;
private boolean waitForTimeout = false;
//boolean used to know if the vn is mapped only with a P2P service that request MAX nodes
// indeed the behavior is different when returning nodes
private boolean MAX_P2P = false;
//protected int MAX_RETRY = 70;
/** represents the timeout in ms*/
protected long timeout = 70000;
/** represents the sum of the timeout + current time in ms*/
protected long globalTimeOut;
private Object uniqueActiveObject = null;
private X509Certificate creatorCertificate;
private PolicyServer policyServer;
private String policyServerFile;
private String jobID = ProActive.getJobId();
/**
* Contructs a new intance of VirtualNode
*/
VirtualNodeImpl() {
}
/**
* Contructs a new intance of VirtualNode
*/
VirtualNodeImpl(String name, X509Certificate creatorCertificate,
PolicyServer policyServer) {
this.name = name;
virtualMachines = new java.util.ArrayList(5);
localVirtualMachines = new java.util.ArrayList();
createdNodes = new java.util.ArrayList();
awaitedVirtualNodes = new Hashtable();
proActiveRuntimeImpl = (ProActiveRuntimeImpl) ProActiveRuntimeImpl.getProActiveRuntime();
if (logger.isDebugEnabled()) {
logger.debug("vn " + this.name + " registered on " +
proActiveRuntimeImpl.getVMInformation().getVMID().toString());
}
proActiveRuntimeImpl.addRuntimeRegistrationEventListener(this);
proActiveRuntimeImpl.registerLocalVirtualNode(this, this.name);
// SECURITY
this.creatorCertificate = creatorCertificate;
this.policyServer = policyServer;
}
/**
* Sets the property attribute to the given value
* @param property the value of property attribute, this value can be "unique", "unique_singleAO", "multiple", "multiple_cyclic" or nothing
*/
public void setProperty(String value) {
this.property = value;
}
public String getProperty() {
return property;
}
public long getTimeout() {
return timeout;
}
/**
* Sets the timeout variable to the given value.
* Calling this method will force this VirtualNode to wait until the timeout expires
* before giving access to its nodes.
*/
public void setTimeout(long timeout, boolean waitForTimeout) {
this.timeout = timeout;
this.waitForTimeout = waitForTimeout;
}
/**
* Sets the name of this VirtualNode
* @param s
*/
public void setName(String s) {
this.name = s;
}
public String getName() {
return name;
}
public void addVirtualMachine(VirtualMachine virtualMachine) {
virtualMachines.add(virtualMachine);
if (!((virtualMachine.getCreatorId()).equals(this.name))) {
// add in the hashtable the vm's creator id, and the number of nodes that should be created
awaitedVirtualNodes.put(virtualMachine.getCreatorId(),
virtualMachine);
//we need to do it here otherwise event could occurs, whereas vm 's creator id is not in the hash map
//just synchro pb, this workaround solves the pb
}
if (logger.isDebugEnabled()) {
logger.debug("mapped VirtualNode=" + name +
" with VirtualMachine=" + virtualMachine.getName());
}
}
public VirtualMachine getVirtualMachine() {
if (virtualMachines.isEmpty()) {
return null;
}
VirtualMachine vm = (VirtualMachine) virtualMachines.get(lastVirtualMachineIndex);
return vm;
}
/**
* Activates all the Nodes mapped to this VirtualNode in the XML Descriptor
*/
public void activate() {
if (!isActivated) {
for (int i = 0; i < virtualMachines.size(); i++) {
VirtualMachine vm = getVirtualMachine();
// first check if it is a process that is attached to the vm
if (vm.hasProcess()) {
boolean vmAlreadyAssigned = !((vm.getCreatorId()).equals(this.name));
ExternalProcess process = getProcess(vm, vmAlreadyAssigned);
// Test if that is this virtual Node that originates the creation of the vm
// done at this point, nodes creation will occur when the runtime associated with the jvm
// will register.
if (!vmAlreadyAssigned) {
setParameters(process, vm);
process.setSecurityFile(policyServerFile);
// It is this virtual Node that originates the creation of the vm
try {
proActiveRuntimeImpl.createVM(process);
} catch (java.io.IOException e) {
e.printStackTrace();
logger.error("cannot activate virtualNode " +
this.name + " with the process " +
process.getCommand());
}
}
} else {
// It is a service that is mapped to the vm.
startService(vm);
}
increaseIndex();
}
// local nodes creation
for (int i = 0; i < localVirtualMachines.size(); i++) {
String protocol = (String) localVirtualMachines.get(i);
internalCreateNodeOnCurrentJvm(protocol);
}
//initialization of the global timeout
globalTimeOut = System.currentTimeMillis() + timeout;
isActivated = true;
if (registration) {
register();
}
} else {
logger.info("VirtualNode " + this.name + " already activated !!!");
}
}
/**
* Returns the number of Nodes mapped to this VirtualNode in the XML Descriptor
* @return int
*/
public int getNodeCount() {
return nodeCount;
}
/**
* Returns the number of Nodes already created among the Nodes mapped to this VirtualNode in the XML Descriptor
* @return int
*/
public int createdNodeCount() {
return nodeCountCreated;
}
/**
* Returns the first Node created among Nodes mapped to this VirtualNode in the XML Descriptor
* Another call to this method will return the following created node if any.
* @return Node
*/
public Node getNode() throws NodeException {
//try first to get the Node from the createdNodes array to be continued
Node node;
waitForNodeCreation();
if (!createdNodes.isEmpty()) {
node = (Node) createdNodes.get(lastNodeIndex);
increaseNodeIndex();
return node;
} else {
throw new NodeException("Cannot get the node " + this.name);
}
}
public Node getNode(int index) throws NodeException {
Node node = (Node) createdNodes.get(index);
if (node == null) {
throw new NodeException(
"Cannot return the first node, no nodes hava been created");
}
return node;
}
public String[] getNodesURL() throws NodeException {
String[] nodeNames;
try {
waitForAllNodesCreation();
} catch (NodeException e) {
logger.error(e.getMessage());
}
if (!createdNodes.isEmpty()) {
synchronized (createdNodes) {
nodeNames = new String[createdNodes.size()];
for (int i = 0; i < createdNodes.size(); i++) {
nodeNames[i] = ((Node) createdNodes.get(i)).getNodeInformation()
.getURL();
}
}
} else {
if (!MAX_P2P) {
throw new NodeException(
"Cannot return nodes, no nodes have been created");
} else {
logger.warn("WARN: No nodes have yet been created.");
logger.warn(
"WARN: This behavior might be normal, since P2P service is used with MAX number of nodes requested");
logger.warn("WARN: Returning empty array");
return new String[0];
}
}
return nodeNames;
}
public Node[] getNodes() throws NodeException {
Node[] nodeTab;
try {
waitForAllNodesCreation();
} catch (NodeException e) {
logger.error(e.getMessage());
}
if (!createdNodes.isEmpty()) {
synchronized (createdNodes) {
nodeTab = new Node[createdNodes.size()];
for (int i = 0; i < createdNodes.size(); i++) {
nodeTab[i] = ((Node) createdNodes.get(i));
}
}
} else {
if (!MAX_P2P) {
throw new NodeException(
"Cannot return nodes, no nodes have been created");
} else {
logger.warn("WARN: No nodes have yet been created.");
logger.warn(
"WARN: This behavior might be normal, since P2P service is used with MAX number of nodes requested");
logger.warn("WARN: Returning empty array");
return new Node[0];
}
}
return nodeTab;
}
public Node getNode(String url) throws NodeException {
Node node = null;
try {
waitForAllNodesCreation();
} catch (NodeException e) {
logger.error(e.getMessage());
}
if (!createdNodes.isEmpty()) {
synchronized (createdNodes) {
for (int i = 0; i < createdNodes.size(); i++) {
if (((Node) createdNodes.get(i)).getNodeInformation()
.getURL().equals(url)) {
node = (Node) createdNodes.get(i);
break;
}
}
return node;
}
} else {
throw new NodeException(
"Cannot return nodes, no nodes hava been created");
}
}
public void killAll(boolean softly) {
Node node;
ProActiveRuntime part = null;
if (isActivated) {
for (int i = 0; i < createdNodes.size(); i++) {
node = (Node) createdNodes.get(i);
part = node.getProActiveRuntime();
//we have to be carefull. Indeed if the node is local, we do not
// want to kill the runtime, otherwise the application is over
// so if the node is local, we just unregister this node from any registry
if (!NodeFactory.isNodeLocal(node)) {
try {
part.killRT(softly);
} catch (ProActiveException e1) {
e1.printStackTrace();
} catch (Exception e) {
logger.info(" Virtual Machine " +
part.getVMInformation().getVMID() + " on host " +
part.getVMInformation().getInetAddress()
.getCanonicalHostName() + " terminated!!!");
}
} else {
try {
// the node is local, unregister it.
part.killNode(node.getNodeInformation().getURL());
} catch (ProActiveException e) {
e.printStackTrace();
}
}
}
isActivated = false;
try {
//if registered in any regigistry, unregister everything
if (registration) {
ProActive.unregisterVirtualNode(this);
}
//else unregister just in the local runtime
else {
proActiveRuntimeImpl.unregisterVirtualNode(this.name);
}
} catch (ProActiveException e) {
e.printStackTrace();
}
// if not activated unregister it from the local runtime
} else {
proActiveRuntimeImpl.unregisterVirtualNode(this.name);
}
}
public void createNodeOnCurrentJvm(String protocol) {
localVirtualMachines.add(protocol);
}
public Object getUniqueAO() throws ProActiveException {
if (!property.equals("unique_singleAO")) {
logger.warn(
"!!!!!!!!!!WARNING. This VirtualNode is not defined with unique_single_AO property in the XML descriptor. Calling getUniqueAO() on this VirtualNode can lead to unexpected behaviour");
}
if (uniqueActiveObject == null) {
try {
Node node = getNode();
if (node.getActiveObjects().length > 1) {
logger.warn(
"!!!!!!!!!!WARNING. More than one active object is created on this VirtualNode.");
}
uniqueActiveObject = node.getActiveObjects()[0];
} catch (Exception e) {
e.printStackTrace();
}
}
if (uniqueActiveObject == null) {
throw new ProActiveException(
"No active object are registered on this VirtualNode");
}
return uniqueActiveObject;
}
public boolean isActivated() {
return isActivated;
}
public boolean isLookup() {
return false;
}
public String getJobID() {
return this.jobID;
}
public synchronized void runtimeRegistered(RuntimeRegistrationEvent event) {
String nodeName;
String[] nodeNames = null;
ProActiveRuntime proActiveRuntimeRegistered;
String nodeHost;
String protocol;
String url;
int port = 0;
VirtualMachine virtualMachine = null;
for (int i = 0; i < virtualMachines.size(); i++) {
if (((VirtualMachine) virtualMachines.get(i)).getName().equals(event.getVmName())) {
virtualMachine = (VirtualMachine) virtualMachines.get(i);
}
}
//Check if it this virtualNode that originates the process
if ((event.getCreatorID().equals(this.name)) &&
(virtualMachine != null)) {
if (logger.isDebugEnabled()) {
logger.debug("runtime " + event.getCreatorID() +
" registered on virtualnode " + this.name);
}
protocol = event.getProtocol();
//gets the registered runtime
proActiveRuntimeRegistered = event.getRegisteredRuntime();
// get the host of nodes
nodeHost = proActiveRuntimeRegistered.getVMInformation()
.getInetAddress()
.getCanonicalHostName();
try {
port = UrlBuilder.getPortFromUrl(proActiveRuntimeRegistered.getURL());
} catch (ProActiveException e) {
logger.warn("port unknown: " + port);
}
try {
//get the node on the registered runtime
// nodeNames = proActiveRuntimeRegistered.getLocalNodeNames();
int nodeNumber = (new Integer((String) virtualMachine.getNodeNumber())).intValue();
for (int i = 1; i <= nodeNumber; i++) {
nodeName = this.name +
Integer.toString(new java.util.Random(
System.currentTimeMillis()).nextInt());
url = buildURL(nodeHost, nodeName, protocol, port);
// nodes are created from the registered runtime, since this virtualNode is
// waiting for runtime registration to perform co-allocation in the jvm.
PolicyServer nodePolicyServer = null;
if (policyServer != null) {
nodePolicyServer = (PolicyServer) policyServer.clone();
nodePolicyServer.generateEntityCertificate(name);
}
proActiveRuntimeRegistered.createLocalNode(url, false,
nodePolicyServer, this.getName(), this.jobID);
performOperations(proActiveRuntimeRegistered, url, protocol);
}
} catch (ProActiveException e) {
e.printStackTrace();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
//Check if the virtualNode that originates the process is among awaited VirtualNodes
if (awaitedVirtualNodes.containsKey(event.getCreatorID())) {
//gets the registered runtime
proActiveRuntimeRegistered = event.getRegisteredRuntime();
// get the host for the node to be created
nodeHost = proActiveRuntimeRegistered.getVMInformation()
.getInetAddress()
.getCanonicalHostName();
protocol = event.getProtocol();
try {
port = UrlBuilder.getPortFromUrl(proActiveRuntimeRegistered.getURL());
} catch (ProActiveException e) {
logger.warn("port unknown: " + port);
}
// it is the only way to get accurate value of nodeNumber
VirtualMachine vm = (VirtualMachine) awaitedVirtualNodes.get(event.getCreatorID());
int nodeNumber = (new Integer((String) vm.getNodeNumber())).intValue();
for (int i = 1; i <= nodeNumber; i++) {
try {
nodeName = this.name +
Integer.toString(new java.util.Random(
System.currentTimeMillis()).nextInt());
url = buildURL(nodeHost, nodeName, protocol, port);
// nodes are created from the registered runtime, since this virtualNode is
// waiting for runtime registration to perform co-allocation in the jvm.
PolicyServer nodePolicyServer = null;
if (policyServer != null) {
nodePolicyServer = (PolicyServer) policyServer.clone();
nodePolicyServer.generateEntityCertificate(name);
}
proActiveRuntimeRegistered.createLocalNode(url, false,
nodePolicyServer, this.getName(), this.jobID);
performOperations(proActiveRuntimeRegistered, url, protocol);
} catch (ProActiveException e) {
e.printStackTrace();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
}
/**
* @see org.objectweb.proactive.core.descriptor.data.VirtualNode#setRuntimeInformations(String,String)
* At the moment no property can be set at runtime on a VirtualNodeImpl.
*/
public void setRuntimeInformations(String information, String value)
throws ProActiveException {
// try {
// checkProperty(information);
// } catch (ProActiveException e) {
// throw new ProActiveException("No property can be set at runtime on this VirtualNode",
//No need to check if the property exist since no property can be set
// at runtime on a VNImpl. This might change in the future.
throw new ProActiveException(
"No property can be set at runtime on this VirtualNode");
}
public void setRegistrationProtocol(String protocol) {
setRegistrationValue(true);
this.registrationProtocol = protocol;
}
public String getRegistrationProtocol() {
return this.registrationProtocol;
}
/**
* Sets the minimal number of nodes this VirtualNode needs to be suitable for the application.
* It means that if in the Deployment file, this VirtualNode is mapped onto n nodes, and the
* minimum number of nodes is set to m, with of course m<n, calling method getNodes will return
* when at least m nodes are created
* @param min the minimum number of nodes
*/
public void setMinNumberOfNodes(int min) {
this.minNodeNumber = min;
}
/**
* @see org.objectweb.proactive.core.descriptor.data.VirtualNode#getMinNumberOfNodes()
*/
public int getMinNumberOfNodes() {
return minNodeNumber;
}
// SECURITY
/* (non-Javadoc)
* @see org.objectweb.proactive.core.descriptor.data.VirtualNode#getCreatorCertificate()
*/
public X509Certificate getCreatorCertificate() {
return creatorCertificate;
}
/* (non-Javadoc)
* @see org.objectweb.proactive.core.descriptor.data.VirtualNode#getPolicyServer()
*/
public PolicyServer getPolicyServer() {
return policyServer;
}
/**
* @param server
*/
public void setPolicyServer(PolicyServer server) {
// logger.debug("Setting PolicyServer " + server + " to VN " +name);
policyServer = server;
}
/* (non-Javadoc)
* @see org.objectweb.proactive.core.descriptor.data.VirtualNode#setPolicyFile(java.lang.String)
*/
public void setPolicyFile(String file) {
policyServerFile = file;
}
private void internalCreateNodeOnCurrentJvm(String protocol) {
try {
// this method should be called when in the xml document the tag currenJVM is encountered. It means that one node must be created
// on the jvm that originates the creation of this virtualNode(the current jvm) and mapped on this virtualNode
// we must increase the node count
String url;
increaseNodeCount(1);
String nodeName = this.name +
Integer.toString(new java.util.Random(
System.currentTimeMillis()).nextInt());
// get the Runtime for the given protocol
ProActiveRuntime defaultRuntime = RuntimeFactory.getProtocolSpecificRuntime(checkProtocol(
protocol));
//create the node
PolicyServer nodePolicyServer = null;
if (policyServer != null) {
nodePolicyServer = (PolicyServer) policyServer.clone();
nodePolicyServer.generateEntityCertificate(name);
}
url = defaultRuntime.createLocalNode(nodeName, false,
nodePolicyServer, this.getName(), ProActive.getJobId());
//add this node to this virtualNode
performOperations(defaultRuntime, url, protocol);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Waits until at least one Node mapped to this VirtualNode in the XML Descriptor is created
*/
private synchronized void waitForNodeCreation() throws NodeException {
while (!nodeCreated) {
if (!timeoutExpired()) {
try {
wait(getTimeToSleep());
} catch (InterruptedException e2) {
e2.printStackTrace();
} catch (IllegalStateException e) {
// it may happen that we entered in the loop and just after
// the timeToSleep is < 0. It means that the timeout expired
// that is why we catch the runtime exception
throw new NodeException(
"After many retries, not even one node can be found");
}
} else {
throw new NodeException(
"After many retries, not even one node can be found");
}
}
return;
}
/**
* Waits until all Nodes mapped to this VirtualNode in the XML Descriptor are created
*/
private synchronized void waitForAllNodesCreation()
throws NodeException {
int tempNodeCount = nodeCount;
if (tempNodeCount != 0) {
//nodeCount equal 0 means there is only a P2P service with MAX number of nodes requested
// so if different of 0, we can set to false the boolean
MAX_P2P = false;
}
if (waitForTimeout) {
try {
Thread.sleep(timeout);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
} else {
// check if we can release the vn before all nodes expected, are created
// i.e the minNumber of nodes is set
if (minNodeNumber != 0) {
tempNodeCount = minNodeNumber;
}
while (nodeCountCreated != tempNodeCount) {
if (!timeoutExpired()) {
try {
wait(getTimeToSleep());
} catch (InterruptedException e2) {
e2.printStackTrace();
} catch (IllegalStateException e) {
// it may happen that we entered in the loop and just after
// the timeToSleep is < 0. It means that the timeout expired
// that is why we catch the runtime exception
throw new NodeException("After many retries, only " +
nodeCountCreated + " nodes are created on " +
tempNodeCount + " expected ");
}
} else {
throw new NodeException("After many retries, only " +
nodeCountCreated + " nodes are created on " +
tempNodeCount + " expected");
}
}
}
return;
}
private boolean timeoutExpired() {
long currentTime = System.currentTimeMillis();
return (globalTimeOut < currentTime);
}
private long getTimeToSleep() {
// if timeToSleep is < 0 we throw an exception
long timeToSleep = globalTimeOut - System.currentTimeMillis();
if (timeToSleep > 0) {
return timeToSleep;
} else {
throw new IllegalStateException("Timeout expired");
}
}
/**
* Returns the process mapped to the given virtual machine mapped to this virtual node
* @param VirtualMachine
* @return ExternalProcess
*/
private ExternalProcess getProcess(VirtualMachine vm,
boolean vmAlreadyAssigned) {
ExternalProcess copyProcess;
//VirtualMachine vm = getVirtualMachine();
ExternalProcess process = vm.getProcess();
// we need to do a deep copy of the process otherwise,
//modifications will be applied on one object that might
// be referenced by other virtualNodes .i.e check started
if (!vmAlreadyAssigned) {
copyProcess = (ExternalProcess) makeDeepCopy(process);
vm.setProcess(copyProcess);
return copyProcess;
} else {
//increment the node count by nodeNumber
increaseNodeCount(new Integer(vm.getNodeNumber()).intValue());
return process;
}
}
/**
* Sets parameters to the JVMProcess linked to the ExternalProcess
* @param process
*/
private void setParameters(ExternalProcess process, VirtualMachine vm) {
ExternalProcess processImpl = process;
ExternalProcessDecorator processImplDecorator;
JVMProcess jvmProcess;
LSFBSubProcess bsub = null;
PrunSubProcess prun = null;
GlobusProcess globus = null;
String protocolId = "";
int nodeNumber = new Integer(vm.getNodeNumber()).intValue();
if (logger.isDebugEnabled()) {
logger.debug("nodeNumber " + nodeNumber);
}
while (ExternalProcessDecorator.class.isInstance(processImpl)) {
String processClassname = processImpl.getClass().getName();
protocolId = protocolId +
findProtocolId(processClassname).toLowerCase();
if (processImpl instanceof LSFBSubProcess) {
//if the process is bsub we have to increase the node count by the number of processors
bsub = (LSFBSubProcess) processImpl;
increaseNodeCount((new Integer(bsub.getProcessorNumber()).intValue()) * nodeNumber);
}
if (processImpl instanceof PrunSubProcess) {
//if the process is prun we have to increase the node count by the number of processors
prun = (PrunSubProcess) processImpl;
if (logger.isDebugEnabled()) {
logger.debug("VirtualNodeImpl getHostsNumber() " +
prun.getHostsNumber());
logger.debug("VirtualNodeImpl getnodeNumber() " +
prun.getProcessorPerNodeNumber());
logger.debug("VM " + vm);
}
increaseNodeCount((new Integer(prun.getHostsNumber()).intValue()) * nodeNumber);
}
if (processImpl instanceof GlobusProcess) {
//if the process is globus we have to increase the node count by the number of processors
globus = (GlobusProcess) processImpl;
increaseNodeCount((new Integer(globus.getCount()).intValue()) * nodeNumber);
}
processImplDecorator = (ExternalProcessDecorator) processImpl;
processImpl = processImplDecorator.getTargetProcess();
if (logger.isDebugEnabled()) {
logger.debug("processImplDecorator " +
processImplDecorator.getClass().getName());
}
}
protocolId = protocolId + "jvm";
//When the virtualNode will be activated, it has to launch the process
//with such parameter.See StartRuntime
jvmProcess = (JVMProcess) processImpl;
//if the target class is StartRuntime, then give parameters otherwise keep parameters
if (jvmProcess.getClassname().equals("org.objectweb.proactive.core.runtime.StartRuntime")) {
//we increment the index of nodecount
if ((bsub == null) && (prun == null) && (globus == null)) {
//if bsub and prun and globus are null we can increase the nodeCount
increaseNodeCount(nodeNumber);
}
//if(!vmAlreadyAssigned){
String vnName = this.name;
String localruntimeURL = null;
try {
localruntimeURL = RuntimeFactory.getDefaultRuntime().getURL();
} catch (ProActiveException e) {
e.printStackTrace();
}
if (logger.isDebugEnabled()) {
logger.debug(localruntimeURL);
}
jvmProcess.setJvmOptions("-Dproactive.jobid=" + this.jobID);
jvmProcess.setParameters(vnName + " " + localruntimeURL + " " +
nodeNumber + " " + protocolId + " " + vm.getName());
}
}
/**
* @param processClassname
* @return
*/
private String findProtocolId(String processClassname) {
int index = processClassname.lastIndexOf(".") + 1;
int lastIndex = processClassname.lastIndexOf("Process");
return processClassname.substring(index, lastIndex) + "-";
}
/**
* Returns a deepcopy of the process
* @param process the process to copy
* @return ExternalProcess, the copy version of the process
*/
private Object makeDeepCopy(Object process) {
//deepCopyTag = true;
Object result = null;
try {
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
oos.writeObject(process);
oos.flush();
oos.close();
java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(baos.toByteArray());
java.io.ObjectInputStream ois = new java.io.ObjectInputStream(bais);
result = ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
//deepCopyTag = false;
return result;
}
private String buildURL(String host, String name, String protocol, int port) {
if (port != 0) {
return UrlBuilder.buildUrl(host, name, protocol, port);
} else {
return UrlBuilder.buildUrl(host, name, protocol);
}
}
private void increaseIndex() {
if (virtualMachines.size() > 1) {
lastVirtualMachineIndex = (lastVirtualMachineIndex + 1) % virtualMachines.size();
}
}
private void increaseNodeCount(int n) {
nodeCount = nodeCount + n;
if (logger.isDebugEnabled()) {
logger.debug("NodeCount: " + nodeCount);
}
}
private void increaseNodeIndex() {
if (createdNodes.size() > 1) {
lastNodeIndex = (lastNodeIndex + 1) % createdNodes.size();
}
}
private String checkProtocol(String protocol) {
if (protocol.indexOf(":") == -1) {
return protocol.concat(":");
}
return protocol;
}
private synchronized void performOperations(ProActiveRuntime part,
String url, String protocol) {
Node node = new NodeImpl(part, url, checkProtocol(protocol), this.jobID);
createdNodes.add(node);
logger.info("**** Mapping VirtualNode " + this.name + " with Node: " +
url + " done");
nodeCreated = true;
nodeCountCreated++;
// wakes up Thread that are waiting for the node creation
notifyAll();
//notify all listeners that a node has been created
notifyListeners(this, NodeCreationEvent.NODE_CREATED, node,
nodeCountCreated);
}
private void register() {
try {
waitForAllNodesCreation();
// ProActiveRuntime part = RuntimeFactory.getProtocolSpecificRuntime(registrationProtocol);
// part.registerVirtualnode(this.name,false);
ProActive.registerVirtualNode(this, registrationProtocol, false);
} catch (NodeException e) {
logger.error(e.getMessage());
} catch (ProActiveException e) {
e.printStackTrace();
}
}
private void setRegistrationValue(boolean value) {
this.registration = value;
}
private void startService(VirtualMachine vm) {
UniversalService service = vm.getService();
//we need to perform a deep copy. Indeed if several vm reference
// the same service this might lead to unexpected behaviour
UniversalService copyService = (UniversalService) makeDeepCopy(service);
vm.setService(copyService);
if (service.getServiceName().equals("P2PLookup")) {
int nodeRequested = ((P2PLookupService) service).getNodeNumber();
// if it is a P2Pservice we must increase the node count with the number
// of nodes requested
if (nodeRequested != ((P2PLookupService) service).getMAX()) {
increaseNodeCount(nodeRequested);
//nodeRequested = MAX means that the service will try to get every nodes
// it can. So we can't predict how many nodes will return.
} else {
MAX_P2P = true;
}
} else {
//increase with 1 node
increaseNodeCount(1);
}
new ServiceThread(this, vm).start();
}
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException {
try {
if (isActivated) {
waitForAllNodesCreation();
}
} catch (NodeException e) {
e.printStackTrace();
}
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
in.defaultReadObject();
}
}
|
package ai.vespa.hosted.cd;
import ai.vespa.cloud.Zone;
import ai.vespa.hosted.cd.internal.TestRuntimeProvider;
import java.util.ServiceLoader;
import java.util.logging.Logger;
/**
* The place to obtain environment-dependent configuration for test of a Vespa deployment.
*
* @author jvenstad
* @author mortent
*/
public interface TestRuntime {
Logger logger = Logger.getLogger(TestRuntime.class.getName());
static TestRuntime get() {
TestRuntime provided = TestRuntimeProvider.getTestRuntime();
if (provided != null) {
logger.fine("Using test runtime from TestRuntimeProvider");
return provided;
}
logger.fine("Using test runtime from ServiceLoader");
return ServiceLoader.load(TestRuntime.class, TestRuntime.class.getClassLoader())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No TestRuntime initialized"));
}
Deployment deploymentToTest();
Zone zone();
}
|
package org.pentaho.di.trans.steps.selectvalues;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.core.xml.XMLInterface;
import org.w3c.dom.Node;
public class SelectMetadataChange implements Cloneable, XMLInterface{
public static final String XML_TAG = "meta";
// META-DATA mode
/** Fields of which we want to change the meta data */
private String name;
/** Meta: new name of field */
private String rename;
/** Meta: new Value type for this field or TYPE_NONE if no change needed! */
private int type;
/** Meta: new length of field */
private int length;
/** Meta: new precision of field (for numbers) */
private int precision;
/** Meta: the storage type, NORMAL or BINARY_STRING */
private int storageType;
/** The conversion metadata if any conversion needs to take place */
private String conversionMask;
/** The decimal symbol for number conversions */
private String decimalSymbol;
/** The grouping symbol for number conversions */
private String groupingSymbol;
/** The currency symbol for number conversions */
private String currencySymbol;
public SelectMetadataChange() {
storageType=-1; // storage type is not used by default!
}
/**
* @param name
* @param rename
* @param type
* @param length
* @param precision
* @param storageType
* @param conversionMask
* @param decimalSymbol
* @param groupingSymbol
* @param currencySymbol
*/
public SelectMetadataChange(String name, String rename, int type, int length, int precision, int storageType,
String conversionMask, String decimalSymbol, String groupingSymbol, String currencySymbol) {
this.name = name;
this.rename = rename;
this.type = type;
this.length = length;
this.precision = precision;
this.storageType = storageType;
this.conversionMask = conversionMask;
this.decimalSymbol = decimalSymbol;
this.groupingSymbol = groupingSymbol;
this.currencySymbol = currencySymbol;
}
public String getXML() {
StringBuffer retval = new StringBuffer();
retval.append(" ").append(XMLHandler.openTag(XML_TAG)); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("name", name)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("rename", rename)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("type", ValueMeta.getTypeDesc(type)) ); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("length", length)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("precision", precision)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("conversion_mask", conversionMask)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("decimal_symbol", decimalSymbol)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("grouping_symbol", groupingSymbol)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("currency_symbol", currencySymbol)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.addTagValue("storage_type", ValueMeta.getStorageTypeCode(storageType))); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" ").append(XMLHandler.closeTag(XML_TAG)); //$NON-NLS-1$
return retval.toString();
}
public SelectMetadataChange(Node metaNode) {
name = XMLHandler.getTagValue(metaNode, "name"); //$NON-NLS-1$
rename = XMLHandler.getTagValue(metaNode, "rename"); //$NON-NLS-1$
type = ValueMeta.getType(XMLHandler.getTagValue(metaNode, "type")); //$NON-NLS-1$
length = Const.toInt(XMLHandler.getTagValue(metaNode, "length"), -2); //$NON-NLS-1$
precision = Const.toInt(XMLHandler.getTagValue(metaNode, "precision"), -2); //$NON-NLS-1$
storageType = ValueMeta.getStorageType( XMLHandler.getTagValue(metaNode, "storage_type") ); //$NON-NLS-1$
conversionMask = XMLHandler.getTagValue(metaNode, "conversion_mask"); //$NON-NLS-1$
decimalSymbol = XMLHandler.getTagValue(metaNode, "decimal_symbol"); //$NON-NLS-1$
groupingSymbol = XMLHandler.getTagValue(metaNode, "grouping_symbol"); //$NON-NLS-1$
currencySymbol = XMLHandler.getTagValue(metaNode, "currency_symbol"); //$NON-NLS-1$
}
public SelectMetadataChange clone() {
try {
return (SelectMetadataChange) super.clone();
}
catch(CloneNotSupportedException e) {
return null;
}
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the rename
*/
public String getRename() {
return rename;
}
/**
* @param rename the rename to set
*/
public void setRename(String rename) {
this.rename = rename;
}
/**
* @return the type
*/
public int getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(int type) {
this.type = type;
}
/**
* @return the length
*/
public int getLength() {
return length;
}
/**
* @param length the length to set
*/
public void setLength(int length) {
this.length = length;
}
/**
* @return the precision
*/
public int getPrecision() {
return precision;
}
/**
* @param precision the precision to set
*/
public void setPrecision(int precision) {
this.precision = precision;
}
/**
* @return the storageType
*/
public int getStorageType() {
return storageType;
}
/**
* @param storageType the storageType to set
*/
public void setStorageType(int storageType) {
this.storageType = storageType;
}
/**
* @return the conversionMask
*/
public String getConversionMask() {
return conversionMask;
}
/**
* @param conversionMask the conversionMask to set
*/
public void setConversionMask(String conversionMask) {
this.conversionMask = conversionMask;
}
/**
* @return the decimalSymbol
*/
public String getDecimalSymbol() {
return decimalSymbol;
}
/**
* @param decimalSymbol the decimalSymbol to set
*/
public void setDecimalSymbol(String decimalSymbol) {
this.decimalSymbol = decimalSymbol;
}
/**
* @return the groupingSymbol
*/
public String getGroupingSymbol() {
return groupingSymbol;
}
/**
* @param groupingSymbol the groupingSymbol to set
*/
public void setGroupingSymbol(String groupingSymbol) {
this.groupingSymbol = groupingSymbol;
}
/**
* @return the currencySymbol
*/
public String getCurrencySymbol() {
return currencySymbol;
}
/**
* @param currencySymbol the currencySymbol to set
*/
public void setCurrencySymbol(String currencySymbol) {
this.currencySymbol = currencySymbol;
}
}
|
package org.usfirst.frc308.FRC2017.commands;
import org.usfirst.frc308.FRC2017.Robot;
import org.usfirst.frc308.FRC2017.RobotConstants;
import org.usfirst.frc308.FRC2017.utils.MathUtils;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
public class AutonomousRotateToTarget extends Command {
private double rot;
public AutonomousRotateToTarget(){
rot = 0.35;
requires(Robot.chassis);
}
@Override
protected void initialize() {
super.initialize();
Robot.chassis.setupDrive();
}
@Override
protected void execute() {
super.execute();
Robot.chassis.arcadeDrive(0, rot);
}
@Override
protected void end() {
super.end();
Robot.chassis.arcadeDrive(0, rot);
}
@Override
protected void interrupted() {
super.interrupted();
end();
}
@Override
protected boolean isFinished() {
if (NetworkTable.getTable("GRIP/myContoursReport").getNumberArray("centerX", new double[0]).length > 0) {
//Check more
int indexBiggest = MathUtils.getLargestIndex(NetworkTable.getTable("GRIP/myContoursReport").getNumberArray("centerX", new double[0]));
double[] array = NetworkTable.getTable("GRIP/myContoursReport").getNumberArray("centerX", new double[0]);
double centerX = RobotConstants.x / 2;
if(MathUtils.getDiffrence(centerX, array[indexBiggest]) < RobotConstants.visionTolerance){
//Done;
return true;
}else{
//Do adjustments later
return false;
}
}
else{
//Done if there is no target
return true;
}
}
}
|
package org.cybergarage.upnp.ssdp;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.io.IOException;
import org.cybergarage.net.*;
import org.cybergarage.util.*;
import org.cybergarage.upnp.device.*;
public class SSDPSearchSocket extends HTTPMUSocket implements Runnable
{
private boolean useIPv6Address;
// Constructor
/**
*
* @param bindAddr The address to bind the service
* @param port The port used for accepting message
* @param multicast The multicast address to use as destination
* @since 1.8
*/
public SSDPSearchSocket(String bindAddr,int port,String multicast){
open(bindAddr,multicast);
}
/**
*
* @param bindAddr the binding address for senging multicast packet
* @since 1.8
*/
public SSDPSearchSocket(InetAddress bindAddr){
if(bindAddr.getAddress().length!=4){
this.open((Inet6Address)bindAddr);
}else{
this.open((Inet4Address)bindAddr);
}
}
// Constructor
public boolean open(Inet4Address bindAddr){
useIPv6Address = false;
return open(SSDP.ADDRESS, SSDP.PORT, bindAddr);
}
public boolean open(Inet6Address bindAddr){
useIPv6Address = true;
return open(SSDP.getIPv6Address(), SSDP.PORT, bindAddr);
}
public boolean open(String bind,String multicast){
if ((HostInterface.isIPv6Address(bind) ) && (HostInterface.isIPv6Address(multicast))){
useIPv6Address = true;
}else if(HostInterface.isIPv4Address(bind) && (HostInterface.isIPv4Address(multicast))){
useIPv6Address = false;
}else{
throw new IllegalArgumentException("Cannot open a UDP Socket for IPv6 address on IPv4 interface or viceversa");
}
return open(multicast, SSDP.PORT, bind);
}
/**
*
* @param bindAddr the hostname of the interface to use for senfing multicast packet
* @return true if and only if it open the socket
* @see {@link SSDP} for default multicast and port destination of the packtes
*/
public boolean open(String bindAddr)
{
String addr = SSDP.ADDRESS;
useIPv6Address = false;
if (HostInterface.isIPv6Address(bindAddr) == true) {
addr = SSDP.getIPv6Address();
useIPv6Address = true;
}
return open(addr, SSDP.PORT, bindAddr);
}
// deviceSearch
private ListenerList deviceSearchListenerList = new ListenerList();
public void addSearchListener(SearchListener listener)
{
deviceSearchListenerList.add(listener);
}
public void removeSearchListener(SearchListener listener)
{
deviceSearchListenerList.remove(listener);
}
public void performSearchListener(SSDPPacket ssdpPacket)
{
int listenerSize = deviceSearchListenerList.size();
for (int n=0; n<listenerSize; n++) {
SearchListener listener = (SearchListener)deviceSearchListenerList.get(n);
listener.deviceSearchReceived(ssdpPacket);
}
}
// run
private Thread deviceSearchThread = null;
public void run()
{
Thread thisThread = Thread.currentThread();
while (deviceSearchThread == thisThread) {
Thread.yield();
// Thanks for Kazuyuki Shudo (08/23/07)
SSDPPacket packet = null;
try {
packet = receive();
}
catch (IOException e) {
break;
}
// Thanks for Mikael Hakman (04/20/05)
if (packet == null)
continue;
//TODO perform delegation with Thread Pooling
if (packet.isDiscover() == true)
performSearchListener(packet);
}
}
public void start() {
StringBuffer name = new StringBuffer("Cyber.SSDPSearchSocket/");
String localAddr = this.getLocalAddress();
if (localAddr != null && 0 < localAddr.length()) {
name.append(this.getLocalAddress()).append(':');
name.append(this.getLocalPort()).append(" -> ");
name.append(this.getMulticastAddress()).append(':');
name.append(this.getMulticastPort());
}
deviceSearchThread = new Thread(this,name.toString());
deviceSearchThread.start();
}
public void stop()
{
// Thanks for Mikael Hakman (04/20/05)
close();
deviceSearchThread = null;
}
}
|
package org.ow2.proactive.scheduler.core;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import org.apache.log4j.Appender;
import org.apache.log4j.AsyncAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.RunActive;
import org.objectweb.proactive.Service;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.api.PAException;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.body.request.RequestFilter;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.remoteobject.RemoteObjectAdapter;
import org.objectweb.proactive.core.remoteobject.RemoteObjectExposer;
import org.objectweb.proactive.core.remoteobject.RemoteObjectHelper;
import org.objectweb.proactive.core.remoteobject.RemoteRemoteObject;
import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
import org.ow2.proactive.resourcemanager.common.RMState;
import org.ow2.proactive.scheduler.common.AdminMethodsInterface;
import org.ow2.proactive.scheduler.common.NotificationData;
import org.ow2.proactive.scheduler.common.SchedulerEvent;
import org.ow2.proactive.scheduler.common.SchedulerState;
import org.ow2.proactive.scheduler.common.SchedulerStatus;
import org.ow2.proactive.scheduler.common.TaskTerminateNotification;
import org.ow2.proactive.scheduler.common.UserSchedulerInterface_;
import org.ow2.proactive.scheduler.common.exception.SchedulerException;
import org.ow2.proactive.scheduler.common.job.JobDescriptor;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobInfo;
import org.ow2.proactive.scheduler.common.job.JobPriority;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.JobStatus;
import org.ow2.proactive.scheduler.common.job.JobType;
import org.ow2.proactive.scheduler.common.policy.Policy;
import org.ow2.proactive.scheduler.common.task.EligibleTaskDescriptor;
import org.ow2.proactive.scheduler.common.task.Log4JTaskLogs;
import org.ow2.proactive.scheduler.common.task.RestartMode;
import org.ow2.proactive.scheduler.common.task.SimpleTaskLogs;
import org.ow2.proactive.scheduler.common.task.TaskDescriptor;
import org.ow2.proactive.scheduler.common.task.TaskId;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
import org.ow2.proactive.scheduler.common.task.TaskLogs;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.util.SchedulerLoggers;
import org.ow2.proactive.scheduler.common.util.Tools;
import org.ow2.proactive.scheduler.common.util.logforwarder.AppenderProvider;
import org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingException;
import org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingService;
import org.ow2.proactive.scheduler.core.db.Condition;
import org.ow2.proactive.scheduler.core.db.ConditionComparator;
import org.ow2.proactive.scheduler.core.db.DatabaseManager;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.scheduler.exception.RunningProcessException;
import org.ow2.proactive.scheduler.exception.StartProcessException;
import org.ow2.proactive.scheduler.job.InternalJob;
import org.ow2.proactive.scheduler.job.InternalJobWrapper;
import org.ow2.proactive.scheduler.job.JobIdImpl;
import org.ow2.proactive.scheduler.job.JobResultImpl;
import org.ow2.proactive.scheduler.resourcemanager.ResourceManagerProxy;
import org.ow2.proactive.scheduler.task.ExecutableContainerInitializer;
import org.ow2.proactive.scheduler.task.JavaExecutableContainer;
import org.ow2.proactive.scheduler.task.TaskResultImpl;
import org.ow2.proactive.scheduler.task.internal.InternalJavaTask;
import org.ow2.proactive.scheduler.task.internal.InternalNativeTask;
import org.ow2.proactive.scheduler.task.internal.InternalTask;
import org.ow2.proactive.scheduler.task.launcher.ProActiveTaskLauncher;
import org.ow2.proactive.scheduler.task.launcher.TaskLauncher;
import org.ow2.proactive.scheduler.util.SchedulerDevLoggers;
import org.ow2.proactive.scheduler.util.classloading.TaskClassServer;
import org.ow2.proactive.scripting.ScriptException;
import org.ow2.proactive.scripting.SelectionScript;
import org.ow2.proactive.utils.NodeSet;
/**
* <i><font size="2" color="#FF0000">** Scheduler core ** </font></i>
* This is the main active object of the scheduler implementation,
* it communicates with the entity manager to acquire nodes and with a policy
* to insert and get jobs from the queue.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
public class SchedulerCore implements UserSchedulerInterface_, AdminMethodsInterface,
TaskTerminateNotification, RunActive {
/** Scheduler logger */
public static final Logger logger = ProActiveLogger.getLogger(SchedulerLoggers.CORE);
public static final Logger logger_dev = ProActiveLogger.getLogger(SchedulerDevLoggers.CORE);
/** Scheduler main loop time out */
private static final int SCHEDULER_TIME_OUT = PASchedulerProperties.SCHEDULER_TIME_OUT.getValueAsInt();
/** Scheduler node ping frequency in second. */
private static final long SCHEDULER_NODE_PING_FREQUENCY = PASchedulerProperties.SCHEDULER_NODE_PING_FREQUENCY
.getValueAsInt() * 1000;
/** Delay to wait for between getting a job result and removing the job concerned */
private static final long SCHEDULER_REMOVED_JOB_DELAY = PASchedulerProperties.SCHEDULER_REMOVED_JOB_DELAY
.getValueAsInt() * 1000;
/** Number of time to retry an active object creation if it fails to create */
private static final int ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER = 3;
/** Implementation of Resource Manager */
private ResourceManagerProxy resourceManager;
/** Scheduler front-end. */
private SchedulerFrontend frontend;
/** Direct link to the current job to submit. */
private InternalJobWrapper currentJobToSubmit;
/** Scheduler current policy */
private Policy policy;
/** list of all jobs managed by the scheduler */
private Map<JobId, InternalJob> jobs = new HashMap<JobId, InternalJob>();
/** list of pending jobs among the managed jobs */
private Vector<InternalJob> pendingJobs = new Vector<InternalJob>();
/** list of running jobs among the managed jobs */
private Vector<InternalJob> runningJobs = new Vector<InternalJob>();
/** list of finished jobs among the managed jobs */
private Vector<InternalJob> finishedJobs = new Vector<InternalJob>();
/** Scheduler current status */
private SchedulerStatus status = SchedulerStatus.STOPPED;
/** Thread that will ping the running nodes */
private Thread pinger;
/** Timer used for remove result method (transient because Timer is not serializable)*/
private transient Timer timer = new Timer();
/** Log forwarding service for nodes */
private LogForwardingService lfs;
/** Jobs that must be logged into the corresponding appenders */
private Hashtable<JobId, AsyncAppender> jobsToBeLogged = new Hashtable<JobId, AsyncAppender>();
/** jobs that must be logged into a file */
//TODO cdelbe : file are logged on core side...
private Hashtable<JobId, FileAppender> jobsToBeLoggedinAFile = new Hashtable<JobId, FileAppender>();
private static final String FILEAPPENDER_SUFFIX = "_FILE";
/** Currently running tasks for a given jobId*/
private Hashtable<JobId, Hashtable<TaskId, TaskLauncher>> currentlyRunningTasks = new Hashtable<JobId, Hashtable<TaskId, TaskLauncher>>();
/** ClassLoading */
// contains taskCLassServer for currently running jobs
private static Hashtable<JobId, TaskClassServer> classServers = new Hashtable<JobId, TaskClassServer>();
private static Hashtable<JobId, RemoteObjectExposer<TaskClassServer>> remoteClassServers = new Hashtable<JobId, RemoteObjectExposer<TaskClassServer>>();
/**
* Return the task classserver for the job jid.<br>
* return null if the classServer is undefine for the given jobId.
*
*
* @param jid the job id
* @return the task classserver for the job jid
*/
public static TaskClassServer getTaskClassServer(JobId jid) {
return classServers.get(jid);
}
/**
* Create a new taskClassServer for the job jid
* @param jid the job id
* @param userClasspathJarFile the contents of the classpath as a serialized jar file
* @param deflateJar if true, the jar file is deflated in the tmpJarFilesDir
*/
private static void addTaskClassServer(JobId jid, byte[] userClasspathJarFile, boolean deflateJar)
throws SchedulerException {
if (getTaskClassServer(jid) != null) {
throw new SchedulerException("ClassServer already exists for job " + jid);
}
try {
// create remote task classserver
logger_dev.info("Create remote task classServer on job '" + jid + "'");
TaskClassServer localReference = new TaskClassServer(jid);
RemoteObjectExposer<TaskClassServer> remoteExposer = new RemoteObjectExposer<TaskClassServer>(
TaskClassServer.class.getName(), localReference);
URI uri = RemoteObjectHelper.generateUrl(jid.toString());
RemoteRemoteObject rro = remoteExposer.createRemoteObject(uri);
// must activate through local ref to avoid copy of the classpath content !
logger_dev.info("Active local reference");
localReference.activate(userClasspathJarFile, deflateJar);
// store references
classServers.put(jid, (TaskClassServer) new RemoteObjectAdapter(rro).getObjectProxy());
remoteClassServers.put(jid, remoteExposer);// stored to be unregistered later
} catch (FileNotFoundException e) {
logger_dev.error("", e);
throw new SchedulerException("Unable to create class server for job " + jid + " because " +
e.getMessage());
} catch (IOException e) {
logger_dev.error("", e);
throw new SchedulerException("Unable to create class server for job " + jid + " because " +
e.getMessage());
} catch (UnknownProtocolException e) {
logger_dev.error("", e);
throw new SchedulerException("Unable to create class server for job " + jid + " because " +
e.getMessage());
} catch (ProActiveException e) {
logger_dev.error("", e);
throw new SchedulerException("Unable to create class server for job " + jid + " because " +
e.getMessage());
}
}
/**
* Remove the taskClassServer for the job jid.
* Delete the classpath associated in SchedulerCore.tmpJarFilesDir.
* @return true if a taskClassServer has been removed, false otherwise.
*/
private static boolean removeTaskClassServer(JobId jid) {
logger_dev.info("Removing TaskClassServer for Job '" + jid + "'");
// desactivate tcs
TaskClassServer tcs = classServers.remove(jid);
if (tcs != null) {
tcs.desactivate();
}
// unexport remote object
RemoteObjectExposer<TaskClassServer> roe = remoteClassServers.remove(jid);
if (roe != null) {
try {
logger_dev.info("Unregister remote TaskClassServer for Job '" + jid + "'");
roe.unregisterAll();
} catch (ProActiveException e) {
logger.error("Unable to unregister remote taskClassServer because : " + e);
logger_dev.error("", e);
}
}
return (tcs != null);
}
/**
* Terminate some job handling at the end of a job
*/
private void terminateJobHandling(JobId jid) {
//remove loggers
logger_dev.info("Cleaning loggers for Job '" + jid + "'");
Logger l = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + jid);
l.removeAllAppenders();
this.jobsToBeLogged.remove(jid);
this.jobsToBeLoggedinAFile.remove(jid);
// remove current running tasks
// TODO cdelbe : When a job can be removed on failure ??
// Other tasks' logs should remain available...
this.currentlyRunningTasks.remove(jid);
removeTaskClassServer(jid);
}
/**
* ProActive empty constructor
*/
public SchedulerCore() {
}
/**
* Create a new scheduler Core with the given arguments.<br>
*
* @param imp the resource manager on which the scheduler will interact.
* @param frontend a reference to the frontend.
* @param policyFullName the fully qualified name of the policy to be used.
*/
public SchedulerCore(ResourceManagerProxy imp, SchedulerFrontend frontend, String policyFullName,
InternalJobWrapper jobSubmitLink) {
try {
this.resourceManager = imp;
this.frontend = frontend;
this.currentJobToSubmit = jobSubmitLink;
//loggers
String providerClassname = PASchedulerProperties.LOGS_FORWARDING_PROVIDER.getValueAsString();
if (providerClassname == null || providerClassname.equals("")) {
logger.error("LogForwardingProvider property is not properly set.");
throw new RuntimeException("LogForwardingProvider property is not properly set.");
} else {
this.lfs = new LogForwardingService(providerClassname);
this.lfs.initialize();
logger_dev.info("Initialized log forwarding service at " + this.lfs.getServerURI());
}
this.policy = (Policy) Class.forName(policyFullName).newInstance();
logger_dev.info("Instanciated policy : " + policyFullName);
logger.info("Scheduler Core ready !");
} catch (InstantiationException e) {
logger.error("The policy class cannot be found : " + e.getMessage());
logger_dev.error("", e);
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
logger.error("The method cannot be accessed " + e.getMessage());
logger_dev.error("", e);
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
logger.error("The class definition cannot be found, it might be due to case sentivity : " +
e.getMessage());
logger_dev.error("", e);
throw new RuntimeException(e);
} catch (LogForwardingException e) {
logger.error("Cannot initialize the logs forwarding service due to " + e.getMessage());
logger_dev.error("", e);
throw new RuntimeException(e);
}
}
/**
* Create the pinger thread to detect unActivity on nodes.
*/
private void createPingThread() {
logger_dev.debug("Creating nodes pinging thread");
pinger = new Thread() {
@Override
public void run() {
while (!isInterrupted()) {
try {
Thread.sleep(SCHEDULER_NODE_PING_FREQUENCY);
if (runningJobs.size() > 0) {
logger_dev.info("Ping deployed nodes (Number of running jobs : " +
runningJobs.size() + ")");
pingDeployedNodes();
}
} catch (InterruptedException e) {
}
}
}
};
logger_dev.info("Starting nodes pinging thread (ping frequency is : " +
SCHEDULER_NODE_PING_FREQUENCY + "ms )");
pinger.start();
}
/**
* - Send every changes through the job state update event.<br>
* - Clear the task info modify status. It is used to change all status of all tasks
* with only one request. It has to be cleared after sending events.<br>
* - Store the changes to the data base.
*
* @param currentJob the job where the task info are.
* @param eventType the type of event to send with the job state updated
*/
private void updateTaskInfosList(InternalJob currentJob, SchedulerEvent eventType) {
logger_dev.info("Send multiple changes to front-end for job '" + currentJob.getId() + "' (event='" +
eventType + "')");
//send event to listeners.
try {
frontend.jobStateUpdated(currentJob.getOwner(), new NotificationData<JobInfo>(eventType,
currentJob.getJobInfo()));
} catch (Throwable t) {
//Just to prevent update method error
}
// don't forget to set the task status modify to null
currentJob.setTaskStatusModify(null);
// used when a job has failed
currentJob.setTaskFinishedTimeModify(null);
// and to database
DatabaseManager.synchronize(currentJob.getJobInfo());
}
/**
* @see org.objectweb.proactive.RunActive#runActivity(org.objectweb.proactive.Body)
*/
public void runActivity(Body body) {
try {
//Start DB and rebuild the scheduler if needed.
recover();
} catch (Exception e) {
ProActiveLogger.getLogger(SchedulerLoggers.CONSOLE).info("Cannot start Hibernate ", e);
kill();
return;
}
//Scheduler started
ProActiveLogger.getLogger(SchedulerLoggers.CONSOLE).info(
"Scheduler successfully created on " +
Tools.getHostURL(PAActiveObject.getActiveObjectNodeUrl(PAActiveObject.getStubOnThis())));
if (status != SchedulerStatus.KILLED) {
//listen log as immediate Service.
//PAActiveObject.setImmediateService("listenLog");
Service service = new Service(body);
//used to read the enumerate schedulerStatus in order to know when submit is possible.
//have to be immediate service
body.setImmediateService("isSubmitPossible");
body.setImmediateService("getTaskResult");
body.setImmediateService("getJobResult");
logger_dev.debug("Core immediate services : isSubmitPossible,getTaskResult,getJobResult");
//set the filter for serveAll method (user action are privileged)
RequestFilter filter = new MainLoopRequestFilter("submit", "terminate", "listenLog",
"getSchedulerState");
createPingThread();
// default scheduler status is started
((SchedulerCore) PAActiveObject.getStubOnThis()).start();
do {
service.blockingServeOldest();
while ((status == SchedulerStatus.STARTED) || (status == SchedulerStatus.PAUSED) ||
(status == SchedulerStatus.STOPPED)) {
try {
//block the loop until a method is invoked and serve it
service.blockingServeOldest(SCHEDULER_TIME_OUT);
//serve all important methods
service.serveAll(filter);
//schedule
schedule();
} catch (Exception e) {
//this point is reached in case of big problem, sometimes unknown
logger
.error(
"\nSchedulerCore.runActivity(MAIN_LOOP) caught an EXCEPTION - it will not terminate the body !",
e);
//trying to check if RM is alive
try {
logger_dev.error("Check if Resource Manager is alive");
resourceManager.isAlive();
} catch (Exception rme) {
logger_dev.error("Resource Manager seems to be dead", rme);
try {
//try to shutdown the proxy
resourceManager.shutdownProxy();
} catch (Exception ev) {
}
//if failed
freeze();
//scheduler functionality are reduced until now
status = SchedulerStatus.UNLINKED;
logger
.fatal("\n*****************************************************************************************************************\n"
+ "* Resource Manager is no more available, Scheduler has been paused waiting for a resource manager to be reconnect\n"
+ "* Scheduler is in critical state and its functionalities are reduced : \n"
+ "* \t-> use the linkResourceManager() method to reconnect a new one.\n"
+ "*****************************************************************************************************************");
frontend.schedulerStateUpdated(SchedulerEvent.RM_DOWN);
}
}
}
} while ((status != SchedulerStatus.SHUTTING_DOWN) && (status != SchedulerStatus.KILLED));
logger.info("Scheduler is shutting down...");
if (pendingJobs.size() + runningJobs.size() > 0) {
logger_dev.info("Unpause all running and pending jobs !");
for (InternalJob job : jobs.values()) {
//finished jobs cannot be paused, so loop on all jobs
if (job.getStatus() == JobStatus.PAUSED) {
job.setUnPause();
//update events list and send event to the frontend
updateTaskInfosList(job, SchedulerEvent.JOB_RESUMED);
}
}
//terminating jobs...
logger.info("Terminating jobs...");
}
while ((runningJobs.size() + pendingJobs.size()) > 0) {
try {
//block the loop until a method is invoked and serve it
service.blockingServeOldest(SCHEDULER_TIME_OUT);
service.serveAll(filter);
schedule();
} catch (Exception e) {
logger_dev.error("", e);
}
}
//stop the pinger thread.
pinger.interrupt();
}
logger.info("Terminating...");
//shutdown resource manager proxy
resourceManager.shutdownProxy();
logger_dev.info("Resource Manager proxy shutdown");
if (status == SchedulerStatus.SHUTTING_DOWN) {
frontend.schedulerStateUpdated(SchedulerEvent.SHUTDOWN);
}
//destroying scheduler active objects
frontend.terminate();
//closing data base
logger.debug("Closing Scheduler data base !");
DatabaseManager.close();
//terminate this active object
PAActiveObject.terminateActiveObject(false);
logger.info("Scheduler is now shutdown !");
//exit
System.exit(0);
}
/**
* Schedule computing method
*/
private void schedule() {
//Number of time to retry an active object creation before leaving scheduling loop
int activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER;
//get job Descriptor list with eligible jobs (running and pending)
ArrayList<JobDescriptor> jobDescriptorList = new ArrayList<JobDescriptor>();
for (InternalJob j : runningJobs) {
jobDescriptorList.add(j.getJobDescriptor());
}
//if scheduler is paused it only finishes running jobs
if (status != SchedulerStatus.PAUSED) {
for (InternalJob j : pendingJobs) {
jobDescriptorList.add(j.getJobDescriptor());
}
}
if (jobDescriptorList.size() > 0) {
logger_dev.info("Number of jobs containing tasks to be scheduled : " + jobDescriptorList.size());
}
//ask the policy all the tasks to be schedule according to the jobs list.
Vector<EligibleTaskDescriptor> taskRetrivedFromPolicy = policy.getOrderedTasks(jobDescriptorList);
if (taskRetrivedFromPolicy == null || taskRetrivedFromPolicy.size() == 0) {
return;
}
if (taskRetrivedFromPolicy.size() > 0) {
logger_dev.info("Number of tasks ready to be scheduled : " + taskRetrivedFromPolicy.size());
}
while (!taskRetrivedFromPolicy.isEmpty()) {
//number of nodes to ask for
int nbNodesToAskFor = 0;
RMState rmState = resourceManager.getRMState();
policy.RMState = rmState;
int freeResourcesNb = rmState.getNumberOfFreeResources().intValue();
logger_dev.info("Number of free resources : " + freeResourcesNb);
if (freeResourcesNb == 0) {
break;
}
int taskToCheck = 0;
//select first task to define the selection script ID
TaskDescriptor taskDescriptor = taskRetrivedFromPolicy.get(taskToCheck);
InternalJob currentJob = jobs.get(taskDescriptor.getJobId());
InternalTask internalTask = currentJob.getIHMTasks().get(taskDescriptor.getId());
InternalTask sentinel = internalTask;
SelectionScript ss = internalTask.getSelectionScript();
NodeSet ns = internalTask.getNodeExclusion();
logger_dev.debug("Get the most nodes matching the current selection");
//if free resources are available and (selection script ID and Node Exclusion) are the same as the first
while (freeResourcesNb > 0 &&
(ss == internalTask.getSelectionScript() || (ss != null && ss.equals(internalTask
.getSelectionScript()))) &&
(ns == internalTask.getNodeExclusion() || (ns != null && ns.equals(internalTask
.getNodeExclusion())))) {
//last task to be launched
sentinel = internalTask;
if (internalTask.getNumberOfNodesNeeded() > freeResourcesNb) {
//TODO what do we want for proActive job?
//Wait until enough resources are free or <<- chosen for the moment
//get the node until number of needed resources is reached?
break;
} else {
//update number of nodes to ask to the RM
nbNodesToAskFor += internalTask.getNumberOfNodesNeeded();
freeResourcesNb -= internalTask.getNumberOfNodesNeeded();
}
//get next task
taskToCheck++;
//if there is no task anymore, break
if (taskToCheck >= taskRetrivedFromPolicy.size()) {
break;
}
taskDescriptor = taskRetrivedFromPolicy.get(taskToCheck);
currentJob = jobs.get(taskDescriptor.getJobId());
internalTask = currentJob.getIHMTasks().get(taskDescriptor.getId());
}
logger_dev.debug("Number of nodes to ask for : " + nbNodesToAskFor);
NodeSet nodeSet = null;
if (nbNodesToAskFor > 0) {
logger.debug("Asking for " + nbNodesToAskFor + " node(s) with" +
((ss == null) ? "out " : " ") + "selection script");
try {
nodeSet = resourceManager.getAtMostNodes(nbNodesToAskFor, ss, ns);
//the following line is used to unwrap the future, warning when moving or removing
//it may also throw a ScriptException which is a RuntimeException
logger.debug("Got " + nodeSet.size() + " node(s)");
} catch (ScriptException e) {
Throwable t = e;
while (t.getCause() != null) {
t = t.getCause();
}
logger_dev.info("Selection script throws an exception : " + t);
//simulate job starting if needed
// set the different informations on job
if (currentJob.getStartTime() < 0) {
// if it is the first task of this job
currentJob.start();
pendingJobs.remove(currentJob);
runningJobs.add(currentJob);
//update tasks events list and send it to front-end
updateTaskInfosList(currentJob, SchedulerEvent.JOB_PENDING_TO_RUNNING);
logger.info("Job '" + currentJob.getId() + "' started");
}
//selection script has failed : end the job
endJob(currentJob, internalTask, "Selection script has failed : " + t, JobStatus.CANCELED);
//leave the method to recreate lists of tasks to start
return;
}
}
if (nbNodesToAskFor <= 0 || nodeSet.size() == 0) {
//if RM returns 0 nodes, i.e. no nodes satisfy selection script (or no nodes at all)
//remove these tasks from the tasks list to Schedule, and then prevent infinite loop :
//always trying to Schedule in vein these tasks (scheduler Core AO stay blocked on this Schedule loop,
//and can't treat terminate request asked by ended tasks for example).
//try again to schedule these tasks on next call to schedule() seems reasonable
while (!taskRetrivedFromPolicy.get(0).getId().equals(sentinel.getId())) {
taskRetrivedFromPolicy.remove(0);
}
taskRetrivedFromPolicy.remove(0);
}
Node node = null;
try {
while (nodeSet != null && !nodeSet.isEmpty()) {
taskDescriptor = taskRetrivedFromPolicy.get(0);
currentJob = jobs.get(taskDescriptor.getJobId());
internalTask = currentJob.getIHMTasks().get(taskDescriptor.getId());
// load and Initialize the executable container
DatabaseManager.load(internalTask);
logger_dev.debug("Load and Initialize the executable container for task '" +
internalTask.getId() + "'");
ExecutableContainerInitializer eci = new ExecutableContainerInitializer();
if (InternalJavaTask.class.isAssignableFrom(internalTask.getClass())) {
eci.setClassServer(getTaskClassServer(currentJob.getId()));
}
internalTask.getExecutableContainer().init(eci);
node = nodeSet.get(0);
TaskLauncher launcher = null;
//if the job is a ProActive job and if all nodes can be launched at the same time
if ((currentJob.getType() == JobType.PROACTIVE) &&
(nodeSet.size() >= internalTask.getNumberOfNodesNeeded())) {
nodeSet.remove(0);
launcher = internalTask.createLauncher(node);
activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER;
this.currentlyRunningTasks.get(internalTask.getJobId()).put(internalTask.getId(),
launcher);
NodeSet nodes = new NodeSet();
for (int i = 0; i < (internalTask.getNumberOfNodesNeeded() - 1); i++) {
nodes.add(nodeSet.remove(0));
}
internalTask.getExecuterInformations().addNodes(nodes);
// activate loggers for this task if needed
if (this.jobsToBeLogged.containsKey(currentJob.getId()) ||
this.jobsToBeLoggedinAFile.containsKey(currentJob.getId())) {
launcher.activateLogs(this.lfs.getAppenderProvider());
}
logger_dev.info("Starting deployment of task '" + internalTask.getName() +
"' for job '" + currentJob.getId() + "'");
((JobResultImpl) currentJob.getJobResult()).storeFuturResult(internalTask.getName(),
((ProActiveTaskLauncher) launcher).doTask((SchedulerCore) PAActiveObject
.getStubOnThis(), (JavaExecutableContainer) internalTask
.getExecutableContainer(), nodes));
} else if (currentJob.getType() != JobType.PROACTIVE) {
nodeSet.remove(0);
launcher = internalTask.createLauncher(node);
activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER;
this.currentlyRunningTasks.get(internalTask.getJobId()).put(internalTask.getId(),
launcher);
// activate loggers for this task if needed
if (this.jobsToBeLogged.containsKey(currentJob.getId()) ||
this.jobsToBeLoggedinAFile.containsKey(currentJob.getId())) {
launcher.activateLogs(this.lfs.getAppenderProvider());
}
//if job is TASKSFLOW, preparing the list of parameters for this task.
int resultSize = taskDescriptor.getParents().size();
if ((currentJob.getType() == JobType.TASKSFLOW) && (resultSize > 0)) {
TaskResult[] params = new TaskResult[resultSize];
for (int i = 0; i < resultSize; i++) {
//get parent task number i
InternalTask parentTask = currentJob.getIHMTasks().get(
taskDescriptor.getParents().get(i).getId());
//set the task result in the arguments array.
params[i] = currentJob.getJobResult().getResult(parentTask.getName());
//if this result has been unloaded, (extremely rare but possible)
if (params[i].getOutput() == null) {
//get the result and load the content from database
DatabaseManager.load(params[i]);
}
}
logger_dev.info("Starting deployment of task '" + internalTask.getName() +
"' for job '" + currentJob.getId() + "'");
//TODO if the next task is a native task, it's no need to pass params
((JobResultImpl) currentJob.getJobResult()).storeFuturResult(internalTask
.getName(), launcher.doTask((SchedulerCore) PAActiveObject
.getStubOnThis(), internalTask.getExecutableContainer(), params));
} else {
logger_dev.info("Starting deployment of task '" + internalTask.getName() +
"' for job '" + currentJob.getId() + "'");
((JobResultImpl) currentJob.getJobResult()).storeFuturResult(internalTask
.getName(), launcher.doTask((SchedulerCore) PAActiveObject
.getStubOnThis(), internalTask.getExecutableContainer()));
}
}
//if a task has been launched
if (launcher != null) {
logger.info("Task '" + internalTask.getId() + "' started on " +
node.getNodeInformation().getVMInformation().getHostName());
// set the different informations on job
if (currentJob.getStartTime() < 0) {
// if it is the first task of this job
currentJob.start();
pendingJobs.remove(currentJob);
runningJobs.add(currentJob);
//update tasks events list and send it to front-end
updateTaskInfosList(currentJob, SchedulerEvent.JOB_PENDING_TO_RUNNING);
logger.info("Job '" + currentJob.getId() + "' started");
}
// set the different informations on task
currentJob.startTask(internalTask);
// send task event to front-end
frontend.taskStateUpdated(currentJob.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_PENDING_TO_RUNNING, internalTask.getTaskInfo()));
//no need to set this status in database
}
//if everything were OK (or if the task could not be launched,
//removed this task from the processed task.
taskRetrivedFromPolicy.remove(0);
//if every task that should be launched have been removed
if (internalTask == sentinel) {
//get back unused nodes to the RManager
if (!nodeSet.isEmpty())
resourceManager.freeNodes(nodeSet);
//and leave the loop
break;
}
}
} catch (ActiveObjectCreationException e1) {
logger_dev.error("", e1);
//Something goes wrong with the active object creation (createLauncher)
logger.warn("Active object creation exception : " + e1.getMessage());
//so try to get back the node to the resource manager
try {
resourceManager.freeNode(node);
} catch (Exception e2) {
}
if (--activeObjectCreationRetryTimeNumber == 0) {
return;
}
} catch (Exception e1) {
logger_dev.error("", e1);
//if we are here, it is that something append while launching the current task.
logger.warn("Current node (" + node + ") has failed : " + e1.getMessage(), e1);
//so try to get back the node to the resource manager
try {
resourceManager.freeNode(node);
} catch (Exception e2) {
}
}
}
}
/**
* Ping every nodes on which a task is currently running and repair the task if need.
*/
private void pingDeployedNodes() {
logger_dev.info("Search for down nodes !");
for (int i = 0; i < runningJobs.size(); i++) {
InternalJob job = runningJobs.get(i);
for (InternalTask td : job.getITasks()) {
if ((td.getStatus() == TaskStatus.RUNNING) &&
!PAActiveObject.pingActiveObject(td.getExecuterInformations().getLauncher())) {
logger_dev.info("Node failed on job '" + job.getId() + "', task '" + td.getId() + "'");
try {
logger_dev.info("Try to free failed node set");
//free execution node even if it is dead
resourceManager.freeNodes(td.getExecuterInformations().getNodes());
} catch (Exception e) {
//just save the rest of the method execution
}
td.decreaseNumberOfExecutionOnFailureLeft();
logger_dev.info("Number of retry on Failure left for the task '" + td.getId() + "' : " +
td.getNumberOfExecutionOnFailureLeft());
if (td.getNumberOfExecutionOnFailureLeft() > 0) {
td.setStatus(TaskStatus.WAITING_ON_FAILURE);
job.newWaitingTask();
frontend.taskStateUpdated(job.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_WAITING_FOR_RESTART, td.getTaskInfo()));
job.reStartTask(td);
logger_dev.info("Task '" + td.getId() + "' is waiting to restart");
} else {
endJob(
job,
td,
"An error has occurred due to a node failure and the maximum amout of retries property has been reached.",
JobStatus.FAILED);
i
break;
}
}
}
}
}
/**
* Return true if a submit is possible, false if not.
*
* @return true if a submit is possible, false if not.
*/
public boolean isSubmitPossible() {
return !((status == SchedulerStatus.SHUTTING_DOWN) || (status == SchedulerStatus.STOPPED));
}
/**
* Submit a new job to the scheduler.
* This method will prepare the new job and get it ready for scheduling.<br>
* It is not possible to submit the job if the Scheduler is stopped
*
* @throws SchedulerException if problem occurs during job preparation
*/
public void submit() throws SchedulerException {
InternalJob job = currentJobToSubmit.getJob();
logger_dev.info("Trying to submit new Job '" + job.getId() + "'");
// TODO cdelbe : create classserver only when job is running ?
// create taskClassLoader for this job
if (job.getEnvironment().getJobClasspath() != null) {
SchedulerCore.addTaskClassServer(job.getId(), job.getEnvironment().getJobClasspathContent(), job
.getEnvironment().containsJarFile());
// if the classserver creation fails, the submit is aborted
}
job.submitAction();
//create job result storage
JobResult jobResult = new JobResultImpl(job.getId());
//store the job result until user get it (MUST BE SET BEFORE DB STORAGE)
job.setJobResult(jobResult);
//Add to data base
DatabaseManager.register(job);
//If register OK : add job to core
jobs.put(job.getId(), job);
pendingJobs.add(job);
logger_dev.info("New job added to Scheduler lists : '" + job.getId() + "'");
// create a running task table for this job
this.currentlyRunningTasks.put(job.getId(), new Hashtable<TaskId, TaskLauncher>());
//create appender for this job if required
if (job.getLogFile() != null) {
logger_dev.info("Create logger for job '" + job.getId() + "'");
Logger l = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + job.getId());
l.setAdditivity(false);
if (l.getAppender(Log4JTaskLogs.JOB_APPENDER_NAME + FILEAPPENDER_SUFFIX) == null) {
try {
FileAppender fa = new FileAppender(Log4JTaskLogs.getTaskLogLayout(), job.getLogFile(),
false);
fa.setName(Log4JTaskLogs.JOB_APPENDER_NAME + FILEAPPENDER_SUFFIX);
l.addAppender(fa);
this.jobsToBeLoggedinAFile.put(job.getId(), fa);
} catch (IOException e) {
logger.warn("Cannot open log file " + job.getLogFile() + " : " + e.getMessage());
}
}
}
//unload job environment that potentially contains classpath as byte[]
DatabaseManager.unload(job.getEnvironment());
//unload heavy object
for (InternalTask it : job.getITasks()) {
DatabaseManager.unload(it);
}
logger_dev.info("JobEnvironment and internalTask unloaded for job '" + job.getId() + "'");
frontend.jobSubmitted(job);
}
/**
* End the given job due to the given task failure.
*
* @param job the job to end.
* @param task the task who has been the caused of failing. **This argument can be null only if jobStatus is killed**
* @param errorMsg the error message to send in the task result.
* @param jobStatus the type of the end for this job. (failed/canceled/killed)
*/
private void endJob(InternalJob job, InternalTask task, String errorMsg, JobStatus jobStatus) {
TaskResult taskResult = null;
if (task != null) {
logger_dev.info("Job ending request for job '" + job.getId() + "' - cause by task '" +
task.getId() + "' - status : " + jobStatus);
} else {
logger_dev.info("Job ending request for job '" + job.getId() + "' - status : " + jobStatus);
}
for (InternalTask td : job.getITasks()) {
if (td.getStatus() == TaskStatus.RUNNING) {
//get the nodes that are used for this descriptor
NodeSet nodes = td.getExecuterInformations().getNodes();
//try to terminate the task
try {
logger_dev.info("Force terminating task '" + td.getId() + "'");
td.getExecuterInformations().getLauncher().terminate();
} catch (Exception e) { /* (nothing to do) */
}
try {
//free every execution nodes
resourceManager.freeNodes(nodes, td.getCleaningScript());
} catch (Exception e) {
try {
// try to get the node back to the RM
resourceManager.freeNodes(td.getExecuterInformations().getNodes());
} catch (Exception e1) {
}
}
//If not killed
if (jobStatus != JobStatus.KILLED) {
//deleting tasks results except the one that causes the error
if (!td.getId().equals(task.getId())) {
job.getJobResult().removeResult(td.getName());
}
//if canceled, get the result of the canceled task
if ((jobStatus == JobStatus.CANCELED) && td.getId().equals(task.getId())) {
try {
taskResult = job.getJobResult().getResult(task.getName());
} catch (RuntimeException e) {
//should never append
logger_dev.error("", e);
}
}
}
}
}
//if job has been killed
if (jobStatus == JobStatus.KILLED) {
job.failed(null, jobStatus);
//the next line will try to remove job from each list.
//once removed, it won't be removed from remaining list, but we ensure that the job is in only one of the list.
if (runningJobs.remove(job) || pendingJobs.remove(job)) {
finishedJobs.add(job);
}
} else {
//if not killed
job.failed(task.getId(), jobStatus);
//store the exception into jobResult / To prevent from empty task result (when job canceled), create one
boolean noResult = (jobStatus == JobStatus.CANCELED && taskResult == null);
if (jobStatus == JobStatus.FAILED || noResult) {
taskResult = new TaskResultImpl(task.getId(), new Exception(errorMsg), new SimpleTaskLogs("",
errorMsg));
((JobResultImpl) job.getJobResult()).addTaskResult(task.getName(), taskResult, task
.isPreciousResult());
} else if (jobStatus == JobStatus.CANCELED) {
taskResult = (TaskResult) PAFuture.getFutureValue(taskResult);
((JobResultImpl) job.getJobResult()).addTaskResult(task.getName(), taskResult, task
.isPreciousResult());
}
//add the result in database
DatabaseManager.update(job.getJobResult());
//unload the result to improve memory usage
DatabaseManager.unload(taskResult);
//move the job from running to finished
runningJobs.remove(job);
finishedJobs.add(job);
if (!noResult) {
//send task event if their was a result
frontend.taskStateUpdated(job.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_RUNNING_TO_FINISHED, task.getTaskInfo()));
}
}
terminateJobHandling(job.getId());
//update job and tasks events list and send it to front-end
updateTaskInfosList(job, SchedulerEvent.JOB_RUNNING_TO_FINISHED);
logger.info("Job '" + job.getId() + "' terminated (" + jobStatus + ")");
}
/**
* Invoke by a task when it is about to finish.
* This method can be invoke just a little amount of time before the result arrival.
* That's why it can block the execution but only for short time.
*
* @param taskId the identification of the executed task.
*/
public void terminate(TaskId taskId) {
int nativeIntegerResult = 0;
JobId jobId = taskId.getJobId();
logger_dev.info("Received terminate task request for task '" + taskId + "' - job '" + jobId + "'");
InternalJob job = jobs.get(jobId);
//if job has been canceled or failed, it is possible that a task has finished just before
//the failure of the job. In this rare case, the job may not exist anymore.
if (job == null) {
logger_dev.info("Job '" + jobId + "' does not exist anymore");
return;
}
InternalTask descriptor = job.getIHMTasks().get(taskId);
// job might have already been removed if job has failed...
Hashtable<TaskId, TaskLauncher> runningTasks = this.currentlyRunningTasks.get(jobId);
if (runningTasks != null) {
runningTasks.remove(taskId);
} else {
return;
}
try {
//first unload the executable container that we don't need until next execution (if re-execution)
DatabaseManager.unload(descriptor);
//The task is terminated but it's possible to have to
//wait for the future of the task result (TaskResult).
//accessing to the taskResult could block current execution but for a very little time.
//it is the time between the end of the task and the arrival of the future from the task.
//check if the task result future has an error due to node death.
//if the node has died, a runtimeException is sent instead of the result
TaskResult tmp = ((JobResultImpl) job.getJobResult()).getAnyResult(descriptor.getName());
//unwrap future
TaskResultImpl res = (TaskResultImpl) PAFuture.getFutureValue(tmp);
logger_dev.info("Task '" + taskId + "' futur result unwrapped");
updateTaskIdReferences(res, descriptor.getId());
if (res != null) {
// HANDLE DESCIPTORS
res.setPreviewerClassName(descriptor.getResultPreview());
res.setJobClasspath(job.getEnvironment().getJobClasspath()); // can be null
if (PAException.isException(res)) {
//in this case, it is a node error. (should never come)
//this is not user exception or usage,
//so we restart independently of user or admin execution property
logger_dev.info("Node failed on job '" + jobId + "', task '" + taskId + "'");
//change status and update GUI
descriptor.setStatus(TaskStatus.WAITING_ON_FAILURE);
job.newWaitingTask();
frontend.taskStateUpdated(job.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_WAITING_FOR_RESTART, descriptor.getTaskInfo()));
job.reStartTask(descriptor);
//update job and task info
DatabaseManager.synchronize(job.getJobInfo());
DatabaseManager.synchronize(descriptor.getTaskInfo());
//free execution node even if it is dead
try {
resourceManager.freeNodes(descriptor.getExecuterInformations().getNodes());
} catch (Exception e) {
//save the return
}
return;
}
}
logger.info("Task '" + taskId + "' on job '" + jobId + "' terminated");
//Check if an exception or error occurred during task execution...
boolean errorOccurred = false;
if (descriptor instanceof InternalNativeTask) {
logger_dev.debug("Terminated task '" + taskId + "' is a native task");
try {
// try to get the result, res.value can throw an exception,
// it means that the process has failed before the end.
nativeIntegerResult = ((Integer) res.value());
// an error occurred if res is not 0
errorOccurred = (nativeIntegerResult != 0);
} catch (RunningProcessException rpe) {
//if res.value throws a RunningProcessException, user is not responsible
//change status and update GUI
descriptor.setStatus(TaskStatus.WAITING_ON_FAILURE);
job.newWaitingTask();
frontend.taskStateUpdated(job.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_WAITING_FOR_RESTART, descriptor.getTaskInfo()));
job.reStartTask(descriptor);
//update job and task info
DatabaseManager.synchronize(job.getJobInfo());
DatabaseManager.synchronize(descriptor.getTaskInfo());
//free execution node even if it is dead
resourceManager.freeNodes(descriptor.getExecuterInformations().getNodes(), descriptor
.getCleaningScript());
return;
} catch (StartProcessException spe) {
//if res.value throws a StartProcessException, it can be due to an IOException thrown by the process
//ie:command not found
//just note that an error occurred.
errorOccurred = true;
} catch (Throwable e) {
//in any other case, note that an error occurred but the user must be informed.
errorOccurred = true;
}
} else {
logger_dev.debug("Terminated task '" + taskId + "' is a java task");
errorOccurred = res.hadException();
}
logger_dev.info("Task '" + taskId + "' terminate with" + (errorOccurred ? "" : "out") + " error");
//if an error occurred
if (errorOccurred) {
//the task threw an exception OR the result is an error code (1-255)
//if the task has to restart
descriptor.decreaseNumberOfExecutionLeft();
//check the number of execution left and fail the job if it is cancelOnError
if (descriptor.getNumberOfExecutionLeft() <= 0 && descriptor.isCancelJobOnError()) {
//if no rerun left, failed the job
endJob(job, descriptor,
"An error occurred in your task and the maximum number of executions has been reached. "
+ "You also ask to cancel the job in such a situation !", JobStatus.CANCELED);
return;
}
if (descriptor.getNumberOfExecutionLeft() > 0) {
if (descriptor.getRestartTaskOnError().equals(RestartMode.ELSEWHERE)) {
//if the task restart ELSEWHERE
descriptor.setNodeExclusion(descriptor.getExecuterInformations().getNodes());
}
try {
resourceManager.freeNodes(descriptor.getExecuterInformations().getNodes(), descriptor
.getCleaningScript());
} catch (Exception e) {
//cannot get back the node, RM take care about that.
}
//change status and update GUI
descriptor.setStatus(TaskStatus.WAITING_ON_ERROR);
job.newWaitingTask();
//store this task result in the job result.
((JobResultImpl) job.getJobResult()).addTaskResult(descriptor.getName(), res, descriptor
.isPreciousResult());
//and update database
//update job and task info
DatabaseManager.synchronize(job.getJobInfo());
DatabaseManager.synchronize(descriptor.getTaskInfo());
DatabaseManager.update(job.getJobResult());
//send event to user
frontend.taskStateUpdated(job.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_WAITING_FOR_RESTART, descriptor.getTaskInfo()));
//the job is not restarted directly
RestartJobTimerTask jtt = new RestartJobTimerTask(job, descriptor);
new Timer().schedule(jtt, job.getNextWaitingTime(descriptor.getMaxNumberOfExecution() -
descriptor.getNumberOfExecutionLeft()));
return;
}
}
//to be done before terminating the task, once terminated it is not running anymore..
TaskDescriptor currentTD = job.getRunningTaskDescriptor(taskId);
descriptor = job.terminateTask(errorOccurred, taskId);
//store this task result in the job result.
((JobResultImpl) job.getJobResult()).addTaskResult(descriptor.getName(), res, descriptor
.isPreciousResult());
logger_dev.info("TaskResult added to job '" + job.getId() + "' - task name is '" +
descriptor.getName() + "'");
//and update database
DatabaseManager.synchronize(job.getJobInfo());
DatabaseManager.synchronize(descriptor.getTaskInfo());
DatabaseManager.update(job.getJobResult());
//clean the result to improve memory usage
if (!job.getJobDescriptor().hasChildren(descriptor.getId())) {
DatabaseManager.unload(res);
}
for (TaskDescriptor td : currentTD.getParents()) {
if (td.getChildrenCount() == 0) {
try {
DatabaseManager.unload(job.getJobResult().getResult(td.getId().getReadableName()));
} catch (RuntimeException e) {
//should never append
logger_dev.error("", e);
}
}
}
//send event
frontend.taskStateUpdated(job.getOwner(), new NotificationData<TaskInfo>(
SchedulerEvent.TASK_RUNNING_TO_FINISHED, descriptor.getTaskInfo()));
//if this job is finished (every task have finished)
logger_dev.info("Number of finished tasks : " + job.getNumberOfFinishedTasks() +
" - Number of tasks : " + job.getTotalNumberOfTasks());
if (job.getNumberOfFinishedTasks() == job.getTotalNumberOfTasks()) {
//terminating job
job.terminate();
runningJobs.remove(job);
finishedJobs.add(job);
logger.info("Job '" + jobId + "' terminated");
terminateJobHandling(job.getId());
//and to data base
DatabaseManager.synchronize(job.getJobInfo());
//clean every task result
for (TaskResult tr : job.getJobResult().getAllResults().values()) {
DatabaseManager.unload(tr);
}
//send event to client
frontend.jobStateUpdated(job.getOwner(), new NotificationData<JobInfo>(
SchedulerEvent.JOB_RUNNING_TO_FINISHED, job.getJobInfo()));
}
//free every execution nodes
resourceManager.freeNodes(descriptor.getExecuterInformations().getNodes(), descriptor
.getCleaningScript());
} catch (NullPointerException eNull) {
//the task has been killed. Nothing to do anymore with this one.
}
}
/**
* For Hibernate use : a Hibernate session cannot accept two different java objects with the same
* Hibernate identifier.
* To avoid this duplicate object (due to serialization),
* this method will join taskId references in the Job result graph object.
*
* @param jobResult the result in which to join cross dependences
* @param res the current result to check. (avoid searching for any)
* @param id the taskId reference known by the Scheduler
*/
private void updateTaskIdReferences(TaskResult res, TaskId id) {
try {
logger_dev.info("TaskResult : " + res.getTaskId());
//find the taskId field
for (Field f : TaskResultImpl.class.getDeclaredFields()) {
if (f.getType().equals(TaskId.class)) {
f.setAccessible(true);
//set to the existing reference
f.set(res, id);
break;
}
}
} catch (Exception e) {
logger_dev.error("", e);
}
}
/**
* Return the scheduler current state with the pending, running, finished jobs list.
*
* @return the scheduler current state with the pending, running, finished jobs list.
*/
public SchedulerState getSchedulerState() {
SchedulerStateImpl sState = new SchedulerStateImpl();
sState.setPendingJobs(convert(pendingJobs));
sState.setRunningJobs(convert(runningJobs));
sState.setFinishedJobs(convert(finishedJobs));
sState.setState(status);
return sState;
}
private Vector<JobState> convert(Vector<InternalJob> jobs) {
Vector<JobState> jobs2 = new Vector<JobState>();
for (InternalJob j : jobs) {
jobs2.add(j);
}
return jobs2;
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#listenLog(org.ow2.proactive.scheduler.common.job.JobId, java.lang.String, int)
*/
public void listenLog(JobId jobId, AppenderProvider appenderProvider) throws SchedulerException {
logger_dev.info("listen logs of job '" + jobId + "'");
AsyncAppender bufferForJobId = this.jobsToBeLogged.get(jobId);
Logger l = null;
// create the appender to the remote listener
Appender appender = null;
try {
appender = appenderProvider.getAppender();
} catch (LogForwardingException e1) {
logger.error("Cannot create an appender for job " + jobId, e1);
logger_dev.error("", e1);
throw new SchedulerException("Cannot create an appender for job " + jobId, e1);
}
if (bufferForJobId == null) {
// can be not null if a log file has been defined for this job
bufferForJobId = new AsyncAppender();
bufferForJobId.setName(Log4JTaskLogs.JOB_APPENDER_NAME);
this.jobsToBeLogged.put(jobId, bufferForJobId);
l = Logger.getLogger(Log4JTaskLogs.JOB_LOGGER_PREFIX + jobId);
l.setAdditivity(false);
l.addAppender(bufferForJobId);
}
// should add the appender before activating logs on running tasks !
bufferForJobId.addAppender(appender);
InternalJob target = this.jobs.get(jobId);
if ((target != null) && !this.pendingJobs.contains(target)) {
// this jobs contains running and finished tasks
// for finished tasks, add logs events "manually"
Collection<TaskResult> allRes = target.getJobResult().getAllResults().values();
for (TaskResult tr : allRes) {
// if taskResult is not awaited, task is terminated
TaskLogs logs = null;
// try to look in the DB
DatabaseManager.load(tr);
logs = tr.getOutput();
// avoid race condition if any...
if (logs == null) {
// the logs has been deleted and stored in the DB during the previous getOutput
// should not be null now !
DatabaseManager.load(tr);
logs = tr.getOutput();
}
// TODO cdelbe Need more genericity for logging mechanism ?
if (logs instanceof Log4JTaskLogs) {
for (LoggingEvent le : ((Log4JTaskLogs) logs).getAllEvents()) {
// write into socket appender directly to avoid double lines on other listeners
appender.doAppend(le);
}
} else {
l.info(logs.getStdoutLogs(false));
l.error(logs.getStderrLogs(false));
}
}
// for running tasks, activate loggers on taskLauncher side
Hashtable<TaskId, TaskLauncher> curRunning = this.currentlyRunningTasks.get(jobId);
// for running tasks
if (curRunning != null) {
for (TaskId tid : curRunning.keySet()) {
try {
TaskLauncher tl = curRunning.get(tid);
tl.activateLogs(this.lfs.getAppenderProvider());
} catch (LogForwardingException e) {
logger.error("Cannot create an appender provider for task " + tid, e);
logger_dev.error("", e);
}
}
}
}
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#getJobResult(org.ow2.proactive.scheduler.common.job.JobId)
*/
public JobResult getJobResult(JobId jobId) throws SchedulerException {
final InternalJob job = jobs.get(jobId);
final SchedulerCore schedulerStub = (SchedulerCore) PAActiveObject.getStubOnThis();
if (job == null) {
throw new SchedulerException("The job " + jobId + " does not exist !");
}
logger_dev.info("Trying to get JobResult of job '" + jobId + "'");
//result = null if not in DB (ie: not yet available)
JobResult result = DatabaseManager.recover(job.getJobResult().getClass(),
new Condition("id", ConditionComparator.EQUALS_TO, job.getJobResult().getJobId())).get(0);
if (!job.getJobInfo().isToBeRemoved() && SCHEDULER_REMOVED_JOB_DELAY > 0) {
//remember that this job is to be removed
job.setToBeRemoved();
DatabaseManager.synchronize(job.getJobInfo());
try {
//remove job after the given delay
TimerTask tt = new TimerTask() {
@Override
public void run() {
schedulerStub.remove(job.getId());
}
};
timer.schedule(tt, SCHEDULER_REMOVED_JOB_DELAY);
logger_dev.info("Job '" + jobId + "' will be removed in " +
(SCHEDULER_REMOVED_JOB_DELAY / 1000) + "sec");
} catch (Exception e) {
logger_dev.error("", e);
}
}
if (result != null) {
((JobResultImpl) result).setJobInfo(job.getJobInfo());
}
return result;
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#getTaskResult(org.ow2.proactive.scheduler.common.job.JobId, java.lang.String)
*/
public TaskResult getTaskResult(JobId jobId, String taskName) throws SchedulerException {
logger_dev.info("Trying to get TaskResult of task '" + taskName + "' for job '" + jobId + "'");
InternalJob job = jobs.get(jobId);
if (job == null) {
logger_dev.info("Job '" + jobId + "' does not exist");
throw new SchedulerException("The job does not exist !");
}
//extract taskResult reference from memory (weak instance)
//useful to get the task result with the task name
TaskResult result = ((JobResultImpl) job.getJobResult()).getResult(taskName);
if (result == null) {
//the task is unknown
logger_dev.info("Task '" + taskName + "' does not exist");
throw new SchedulerException("The task does not exist !");
}
if (PAFuture.isAwaited(result)) {
//the result is not yet available
logger_dev.info("Task '" + taskName + "' is running");
return null;
}
//extract full taskResult from DB
//use the previous result to get the task Id matching the given name.
//extract full copy from DB to avoid load, unload operation
//Hibernate hold every taskResults even the faulty one, can be interesting to have history
//So get the result of the task is getting the last one.
List<? extends TaskResult> results = DatabaseManager.recover(result.getClass(), new Condition("id",
ConditionComparator.EQUALS_TO, result.getTaskId()));
result = results.get(results.size() - 1);
if ((result != null)) {
logger_dev.info("Get '" + taskName + "' task result for job '" + jobId + "'");
}
return result;
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#remove(org.ow2.proactive.scheduler.common.job.JobId)
*/
public void remove(JobId jobId) {
InternalJob job = jobs.get(jobId);
logger_dev.info("Request to remove job '" + jobId + "'");
if (job != null && finishedJobs.contains(job)) {
jobs.remove(jobId);
job.setRemovedTime(System.currentTimeMillis());
finishedJobs.remove(job);
//and to data base
DatabaseManager.synchronize(job.getJobInfo());
// close log buffer
AsyncAppender jobLog = this.jobsToBeLogged.remove(jobId);
if (jobLog != null) {
jobLog.close();
}
FileAppender jobFile = this.jobsToBeLoggedinAFile.remove(jobId);
if (jobFile != null) {
jobFile.close();
}
//remove from DataBase
boolean rfdb = PASchedulerProperties.JOB_REMOVE_FROM_DB.getValueAsBoolean();
logger_dev.info("Remove job '" + jobId + "' also from dataBase : " + rfdb);
if (rfdb) {
DatabaseManager.delete(job);
}
logger.info("Job " + jobId + " removed !");
//send event to front-end
frontend.jobStateUpdated(job.getOwner(), new NotificationData<JobInfo>(
SchedulerEvent.JOB_REMOVE_FINISHED, job.getJobInfo()));
}
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#start()
*/
public BooleanWrapper start() {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if (status != SchedulerStatus.STOPPED) {
return new BooleanWrapper(false);
}
status = SchedulerStatus.STARTED;
logger.info("Scheduler has just been started !");
frontend.schedulerStateUpdated(SchedulerEvent.STARTED);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#stop()
*/
public BooleanWrapper stop() {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if ((status == SchedulerStatus.STOPPED) || (status == SchedulerStatus.SHUTTING_DOWN) ||
(status == SchedulerStatus.KILLED)) {
return new BooleanWrapper(false);
}
status = SchedulerStatus.STOPPED;
logger.info("Scheduler has just been stopped, no tasks will be launched until start.");
frontend.schedulerStateUpdated(SchedulerEvent.STOPPED);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#pause()
*/
public BooleanWrapper pause() {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if ((status == SchedulerStatus.SHUTTING_DOWN) || (status == SchedulerStatus.KILLED)) {
return new BooleanWrapper(false);
}
if ((status != SchedulerStatus.FROZEN) && (status != SchedulerStatus.STARTED)) {
return new BooleanWrapper(false);
}
status = SchedulerStatus.PAUSED;
logger.info("Scheduler has just been paused !");
frontend.schedulerStateUpdated(SchedulerEvent.PAUSED);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#freeze()
*/
public BooleanWrapper freeze() {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if ((status == SchedulerStatus.SHUTTING_DOWN) || (status == SchedulerStatus.KILLED)) {
return new BooleanWrapper(false);
}
if ((status != SchedulerStatus.PAUSED) && (status != SchedulerStatus.STARTED)) {
return new BooleanWrapper(false);
}
status = SchedulerStatus.FROZEN;
logger.info("Scheduler has just been frozen !");
frontend.schedulerStateUpdated(SchedulerEvent.FROZEN);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#resume()
*/
public BooleanWrapper resume() {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if ((status == SchedulerStatus.SHUTTING_DOWN) || (status == SchedulerStatus.KILLED)) {
return new BooleanWrapper(false);
}
if ((status != SchedulerStatus.PAUSED) && (status != SchedulerStatus.FROZEN)) {
return new BooleanWrapper(false);
}
status = SchedulerStatus.STARTED;
logger.info("Scheduler has just been resumed !");
frontend.schedulerStateUpdated(SchedulerEvent.RESUMED);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#shutdown()
*/
public BooleanWrapper shutdown() {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if ((status == SchedulerStatus.KILLED) || (status == SchedulerStatus.SHUTTING_DOWN)) {
return new BooleanWrapper(false);
}
status = SchedulerStatus.SHUTTING_DOWN;
logger.info("Scheduler is shutting down, this make take time to finish every jobs !");
frontend.schedulerStateUpdated(SchedulerEvent.SHUTTING_DOWN);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#kill()
*/
public synchronized BooleanWrapper kill() {
if (status == SchedulerStatus.KILLED) {
return new BooleanWrapper(false);
}
logger_dev.info("Killing all running task processes...");
//destroying running active object launcher
for (InternalJob j : runningJobs) {
for (InternalTask td : j.getITasks()) {
if (td.getStatus() == TaskStatus.RUNNING) {
try {
NodeSet nodes = td.getExecuterInformations().getNodes();
try {
td.getExecuterInformations().getLauncher().terminate();
} catch (Exception e) { /* Tested, nothing to do */
}
try {
resourceManager.freeNodes(nodes, td.getCleaningScript());
} catch (Exception e) {
try {
// try to get the node back to the IM
resourceManager.freeNodes(td.getExecuterInformations().getNodes());
} catch (Exception e1) {
}
}
} catch (Exception e) {
//do nothing, the task is already terminated.
}
}
}
}
logger_dev.info("Cleaning all lists...");
//cleaning all lists
jobs.clear();
pendingJobs.clear();
runningJobs.clear();
finishedJobs.clear();
jobsToBeLogged.clear();
jobsToBeLoggedinAFile.clear();
currentlyRunningTasks.clear();
logger_dev.info("Terminating logging service...");
if (this.lfs != null) {
try {
this.lfs.terminate();
} catch (LogForwardingException e) {
logger.error("Cannot terminate logging service : " + e.getMessage());
logger_dev.error("", e);
}
}
//finally : shutdown
status = SchedulerStatus.KILLED;
logger.info("Scheduler has just been killed !");
frontend.schedulerStateUpdated(SchedulerEvent.KILLED);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#pause(org.ow2.proactive.scheduler.common.job.JobId)
*/
public BooleanWrapper pause(JobId jobId) {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if ((status == SchedulerStatus.SHUTTING_DOWN) || (status == SchedulerStatus.KILLED)) {
return new BooleanWrapper(false);
}
InternalJob job = jobs.get(jobId);
if (finishedJobs.contains(job)) {
return new BooleanWrapper(false);
}
boolean change = job.setPaused();
if (change) {
logger.debug("Job " + jobId + " has just been paused !");
}
//update tasks events list and send it to front-end
updateTaskInfosList(job, SchedulerEvent.JOB_PAUSED);
return new BooleanWrapper(change);
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#resume(org.ow2.proactive.scheduler.common.job.JobId)
*/
public BooleanWrapper resume(JobId jobId) {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if ((status == SchedulerStatus.SHUTTING_DOWN) || (status == SchedulerStatus.KILLED)) {
return new BooleanWrapper(false);
}
InternalJob job = jobs.get(jobId);
if (finishedJobs.contains(job)) {
return new BooleanWrapper(false);
}
boolean change = job.setUnPause();
if (change) {
logger.debug("Job " + jobId + " has just been resumed !");
}
//update tasks events list and send it to front-end
updateTaskInfosList(job, SchedulerEvent.JOB_RESUMED);
return new BooleanWrapper(change);
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#kill(org.ow2.proactive.scheduler.common.job.JobId)
*/
public synchronized BooleanWrapper kill(JobId jobId) {
if (status == SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
if (status == SchedulerStatus.KILLED) {
return new BooleanWrapper(false);
}
logger_dev.info("Request sent to kill job '" + jobId + "'");
InternalJob job = jobs.get(jobId);
if (job == null || job.getStatus() == JobStatus.KILLED) {
return new BooleanWrapper(false);
}
endJob(job, null, "", JobStatus.KILLED);
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.UserSchedulerInterface_#changePriority(org.ow2.proactive.scheduler.common.job.JobId, org.ow2.proactive.scheduler.common.job.JobPriority)
*/
public void changePriority(JobId jobId, JobPriority priority) {
logger_dev
.info("Request sent to change priority on job '" + jobId + "' - new priority : " + priority);
InternalJob job = jobs.get(jobId);
job.setPriority(priority);
DatabaseManager.synchronize(job.getJobInfo());
frontend.jobStateUpdated(job.getOwner(), new NotificationData<JobInfo>(
SchedulerEvent.JOB_CHANGE_PRIORITY, job.getJobInfo()));
}
public BooleanWrapper changePolicy(Class<? extends Policy> newPolicyFile) throws SchedulerException {
try {
policy = newPolicyFile.newInstance();
frontend.schedulerStateUpdated(SchedulerEvent.POLICY_CHANGED);
logger_dev.info("New policy changed ! new policy name : " + newPolicyFile.getName());
} catch (InstantiationException e) {
logger_dev.error("", e);
throw new SchedulerException("Exception occurs while instanciating the policy !");
} catch (IllegalAccessException e) {
logger_dev.error("", e);
throw new SchedulerException("Exception occurs while accessing the policy !");
}
return new BooleanWrapper(true);
}
/**
* @see org.ow2.proactive.scheduler.common.AdminMethodsInterface#linkResourceManager(java.lang.String)
*/
public BooleanWrapper linkResourceManager(String rmURL) throws SchedulerException {
//only if unlink
if (status != SchedulerStatus.UNLINKED) {
return new BooleanWrapper(false);
}
try {
ResourceManagerProxy imp = ResourceManagerProxy.getProxy(new URI(rmURL.trim()));
//re-link the RM
resourceManager = imp;
logger
.info("New resource manager has been linked to the scheduler.\n\t-> Resume to continue the scheduling.");
frontend.schedulerStateUpdated(SchedulerEvent.RM_UP);
//restart the scheduler
status = SchedulerStatus.STARTED;
frontend.schedulerStateUpdated(SchedulerEvent.STARTED);
return new BooleanWrapper(true);
} catch (Exception e) {
throw new SchedulerException("Error while connecting the new Resource Manager !", e);
}
}
/**
* Rebuild the scheduler after a crash.
* Get data base instance, connect it and ask if a rebuild is needed.
* The steps to recover the core are visible below.
*/
private void recover() {
//Start Hibernate
logger.info("Starting Hibernate...");
DatabaseManager.build();
logger.info("Hibernate successfully started !");
//create condition of recovering : recover only non-removed job
//Condition condition = new Condition("jobInfo.removedTime", ConditionComparator.LESS_EQUALS_THAN,(long) 0);
//list of internal job to recover
//List<InternalJob> recovering = DatabaseManager.recover(InternalJob.class, condition);
List<InternalJob> recovering = DatabaseManager.recoverAllJobs();
logger_dev.info("Number of job to recover : " + recovering.size());
if (recovering.size() == 0) {
logger_dev.info("No Job to recover.");
frontend.recover(null);
return;
}
// Recover the scheduler core
logger.info("Re-build jobs lists");
JobId maxId = JobIdImpl.makeJobId("0");
for (InternalJob job : recovering) {
jobs.put(job.getId(), job);
//search last JobId
if (job.getId().compareTo(maxId) > 0) {
maxId = job.getId();
}
}
logger_dev.info("Initialize jobId count");
JobIdImpl.setInitialValue((JobIdImpl) maxId);
logger_dev.info("Re-build jobs pending/running/finished lists");
for (InternalJob job : jobs.values()) {
//rebuild job descriptor if needed (needed because not stored in database)
job.getJobDescriptor();
switch (job.getStatus()) {
case PENDING:
pendingJobs.add(job);
currentlyRunningTasks.put(job.getId(), new Hashtable<TaskId, TaskLauncher>());
// restart classserver if needed
if (job.getEnvironment().getJobClasspath() != null) {
try {
SchedulerCore.addTaskClassServer(job.getId(), job.getEnvironment()
.getJobClasspathContent(), job.getEnvironment().containsJarFile());
} catch (SchedulerException e) {
// TODO cdelbe : exception handling ?
logger_dev.error("", e);
}
}
break;
case STALLED:
case RUNNING:
runningJobs.add(job);
currentlyRunningTasks.put(job.getId(), new Hashtable<TaskId, TaskLauncher>());
//reset the finished events in the order they have occurred
ArrayList<InternalTask> tasksList = copyAndSort(job.getITasks(), true);
for (InternalTask task : tasksList) {
job.update(task.getTaskInfo());
//if the task was in waiting for restart status, restart it
if (task.getStatus() == TaskStatus.WAITING_ON_ERROR ||
task.getStatus() == TaskStatus.WAITING_ON_FAILURE) {
job.newWaitingTask();
job.reStartTask(task);
}
}
// restart classServer if needed
if (job.getEnvironment().getJobClasspath() != null) {
try {
SchedulerCore.addTaskClassServer(job.getId(), job.getEnvironment()
.getJobClasspathContent(), job.getEnvironment().containsJarFile());
} catch (SchedulerException e) {
// TODO cdelbe : exception handling ?
logger_dev.error("", e);
}
}
break;
case FINISHED:
case CANCELED:
case FAILED:
case KILLED:
finishedJobs.add(job);
break;
case PAUSED:
if ((job.getNumberOfPendingTasks() + job.getNumberOfRunningTasks() + job
.getNumberOfFinishedTasks()) == 0) {
pendingJobs.add(job);
} else {
runningJobs.add(job);
//reset the finished events in the order they have occurred
ArrayList<InternalTask> tasksListP = copyAndSort(job.getITasks(), true);
for (InternalTask task : tasksListP) {
job.update(task.getTaskInfo());
}
}
// restart classserver if needed
if (job.getEnvironment().getJobClasspath() != null) {
try {
SchedulerCore.addTaskClassServer(job.getId(), job.getEnvironment()
.getJobClasspathContent(), job.getEnvironment().containsJarFile());
} catch (SchedulerException e) {
// TODO cdelbe : exception handling ?
logger_dev.error("", e);
}
}
}
//unload job environment once handled
DatabaseManager.unload(job.getEnvironment());
}
logger_dev.info("Re-create task dependences");
for (InternalJob job : runningJobs) {
ArrayList<InternalTask> tasksList = copyAndSort(job.getITasks(), true);
//simulate the running execution to recreate the tree.
for (InternalTask task : tasksList) {
job.simulateStartAndTerminate(task.getId());
}
if ((job.getStatus() == JobStatus.RUNNING) || (job.getStatus() == JobStatus.PAUSED)) {
//set the status to stalled because the scheduler start in stopped mode.
if (job.getStatus() == JobStatus.RUNNING) {
job.setStatus(JobStatus.STALLED);
}
//set the task to pause inside the job if it is paused.
if (job.getStatus() == JobStatus.PAUSED) {
job.setStatus(JobStatus.STALLED);
job.setPaused();
job.setTaskStatusModify(null);
}
//update the count of pending and running task.
job.setNumberOfPendingTasks(job.getNumberOfPendingTasks() + job.getNumberOfRunningTasks());
job.setNumberOfRunningTasks(0);
}
}
for (InternalJob job : pendingJobs) {
//set the task to pause inside the job if it is paused.
if (job.getStatus() == JobStatus.PAUSED) {
job.setStatus(JobStatus.STALLED);
job.setPaused();
job.setTaskStatusModify(null);
}
}
logger_dev.info("Removing non-managed jobs");
Iterator<InternalJob> iterJob = jobs.values().iterator();
final SchedulerCore schedulerStub = (SchedulerCore) PAActiveObject.getStubOnThis();
while (iterJob.hasNext()) {
final InternalJob job = iterJob.next();
//re-set job removed delay (if job result has been sent to user)
if (job.isToBeRemoved()) {
if (SCHEDULER_REMOVED_JOB_DELAY > 0) {
try {
//remove job after the given delay
TimerTask tt = new TimerTask() {
@Override
public void run() {
schedulerStub.remove(job.getId());
}
};
timer.schedule(tt, SCHEDULER_REMOVED_JOB_DELAY);
logger.debug("Job " + job.getId() + " will be removed in " +
(SCHEDULER_REMOVED_JOB_DELAY / 1000) + "sec");
} catch (Exception e) {
}
}
}
}
logger.debug("Recover the scheduler front-end");
frontend.recover(jobs);
}
/**
* Make a copy of the given argument with the restriction 'onlyFinished'.
* Then sort the array according to finished time order.
*
* @param tasks the list of internal tasks to copy.
* @param onlyFinished true if the copy must contains only the finished task,
* false to contains every tasks.
* @return the sorted copy of the given argument.
*/
private ArrayList<InternalTask> copyAndSort(ArrayList<InternalTask> tasks, boolean onlyFinished) {
ArrayList<InternalTask> tasksList = new ArrayList<InternalTask>();
//copy the list with only the finished task.
for (InternalTask task : tasks) {
if (onlyFinished) {
switch (task.getStatus()) {
case ABORTED:
case FAILED:
case FINISHED:
case FAULTY:
tasksList.add(task);
}
} else {
tasksList.add(task);
}
}
//sort the finished task according to their finish time.
//to be sure to be in the right tree browsing.
Collections.sort(tasksList, new FinishTimeComparator());
return tasksList;
}
/**
* FinishTimeComparator will compare the internal task on their finished time.
*
* @author The ProActive Team
* @date 25 oct. 07
*
*/
private static class FinishTimeComparator implements Comparator<InternalTask> {
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
* @param o1 First InternalTask to be compared.
* @param o2 Second InternalTask to be compared with the first.
* @return a negative integer, zero, or a positive integer as the
* first argument is less than, equal to, or greater than the
* second.
*/
public int compare(InternalTask o1, InternalTask o2) {
return (int) (o1.getFinishedTime() - o2.getFinishedTime());
}
}
}
|
package com.socialize.test.ui;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import com.socialize.SocializeService;
import com.socialize.android.ioc.IOCContainer;
import com.socialize.api.SocializeSession;
import com.socialize.api.event.EventSystem;
import com.socialize.error.SocializeErrorHandler;
import com.socialize.error.SocializeException;
import com.socialize.launcher.LaunchManager;
import com.socialize.launcher.Launcher;
import com.socialize.listener.SocializeAuthListener;
import com.socialize.ui.SocializeLaunchActivity;
/**
* @author Jason Polites
*
*/
public class SocializeLaunchActivityTest extends SocializeUIActivityTest {
@UsesMocks ({IOCContainer.class, SocializeErrorHandler.class, SocializeService.class, SocializeAuthListener.class, EventSystem.class})
public void testOnCreate() throws Throwable {
final IOCContainer mockContainer = AndroidMock.createMock(IOCContainer.class);
final SocializeService socialize = AndroidMock.createMock(SocializeService.class);
final SocializeAuthListener listener = AndroidMock.createMock(SocializeAuthListener.class);
final EventSystem eventSystem = AndroidMock.createMock(EventSystem.class);
final Bundle bundle = new Bundle();
final CountDownLatch latch = new CountDownLatch(2);
final PublicSocializeLaunchActivity activity = new PublicSocializeLaunchActivity() {
@Override
public IOCContainer getContainer() {
return mockContainer;
}
@Override
public void initSocialize() {
addResult(1, "initSocialize");
latch.countDown();
}
@Override
protected void doAuthenticate() {
super.doAuthenticate();
latch.countDown();
}
@Override
public SocializeService getSocialize() {
return socialize;
}
@Override
public void superOnCreate(Bundle savedInstanceState) {
addResult(0, savedInstanceState);
}
@Override
public SocializeAuthListener getAuthListener(IOCContainer container) {
return listener;
}
@Override
protected void setupLayout() {
addResult(2, "setupLayout");
}
};
AndroidMock.expect(mockContainer.getBean("socializeUIErrorHandler")).andReturn(null).anyTimes();
AndroidMock.expect(mockContainer.getBean("logger")).andReturn(null).anyTimes();
AndroidMock.expect(mockContainer.getBean("eventSystem")).andReturn(eventSystem).anyTimes();
socialize.authenticate(activity, listener);
AndroidMock.replay(mockContainer, socialize);
runTestOnUiThread(new Runnable() {
@Override
public void run() {
activity.onCreate(bundle);
}
});
latch.await(20, TimeUnit.SECONDS);
AndroidMock.verify(mockContainer, socialize);
Bundle savedInstanceState = getResult(0);
String initSocialize = getResult(1);
String setupLayout = getResult(2);
assertNotNull(initSocialize);
assertNotNull(setupLayout);
assertNotNull(savedInstanceState);
assertEquals("setupLayout", setupLayout);
assertEquals("initSocialize", initSocialize);
assertSame(bundle, savedInstanceState);
}
@UsesMocks ({IOCContainer.class, SocializeErrorHandler.class, SocializeSession.class, LaunchManager.class, Launcher.class, Intent.class})
public void testAuthListenerSuccess() {
final IOCContainer mockContainer = AndroidMock.createMock(IOCContainer.class);
final LaunchManager launchManager = AndroidMock.createMock(LaunchManager.class);
final Launcher launcher = AndroidMock.createMock(Launcher.class);
final Intent intent = AndroidMock.createMock(Intent.class);
final SocializeSession session = AndroidMock.createMock(SocializeSession.class);
final Bundle extras = new Bundle(); // can't mock :/
final String action = "foobar";
extras.putString(SocializeLaunchActivity.LAUNCH_ACTION, action);
PublicSocializeLaunchActivity activity = new PublicSocializeLaunchActivity() {
@Override
public Intent getIntent() {
return intent;
}
};
AndroidMock.expect(intent.getExtras()).andReturn(extras);
AndroidMock.expect(mockContainer.getBean("launchManager")).andReturn(launchManager);
AndroidMock.expect(launchManager.getLaucher(action)).andReturn(launcher);
AndroidMock.expect(launcher.getLaunchListener()).andReturn(null).anyTimes();
AndroidMock.expect(launcher.launch(activity, extras)).andReturn(true);
AndroidMock.expect(launcher.shouldFinish()).andReturn(true);
AndroidMock.replay(intent, mockContainer, launchManager, launcher);
SocializeAuthListener authListener = activity.getAuthListener(mockContainer);
authListener.onAuthSuccess(session);
AndroidMock.verify(intent, mockContainer, launchManager, launcher);
}
@UsesMocks ({IOCContainer.class, SocializeErrorHandler.class, SocializeException.class})
public void testAuthListenerAuthFail() {
final IOCContainer mockContainer = AndroidMock.createMock(IOCContainer.class);
final SocializeException error = AndroidMock.createNiceMock(SocializeException.class);
PublicSocializeLaunchActivity activity = new PublicSocializeLaunchActivity() {
@Override
protected void handleError(SocializeException error) {
addResult(0, error);
}
};
SocializeAuthListener authListener = activity.getAuthListener(mockContainer);
authListener.onAuthFail(error);
assertSame(error, getResult(0));
}
@UsesMocks ({IOCContainer.class, SocializeErrorHandler.class, SocializeException.class})
public void testAuthListenerError() {
final IOCContainer mockContainer = AndroidMock.createMock(IOCContainer.class);
final SocializeException error = AndroidMock.createNiceMock(SocializeException.class);
PublicSocializeLaunchActivity activity = new PublicSocializeLaunchActivity() {
@Override
protected void handleError(SocializeException error) {
addResult(0, error);
}
};
SocializeAuthListener authListener = activity.getAuthListener(mockContainer);
authListener.onError(error);
assertSame(error, getResult(0));
}
}
|
package org.broad.igv.tools.parsers;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.tools.converters.GCTtoIGVConverter;
import org.broad.igv.util.ResourceLocator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.broad.igv.util.TestUtils.loadGenome;
/**
* @author jrobinso
* @date Oct 9, 2010
*/
public class GCTtoIGVConverterTest {
Genome genome;
File igvFile;
@Before
public void setUp() throws IOException {
genome = loadGenome("/test/data/genomes/hg18.genome");
igvFile = null;
}
@After
public void tearDown() throws Exception {
if (igvFile != null) {
igvFile.delete();
}
}
@Test
public void testDescriptionMapping() throws IOException {
String gctFile = "test/data/gct/igv_test2.gct";
igvFile = new File("test/data/gct/igv_test2.gct.igv");
ResourceLocator locator = new ResourceLocator(gctFile);
GCTtoIGVConverter.convert(locator, igvFile, null, 50000, null, genome);
}
@Test
public void testAffyMapping() throws IOException {
String gctFile = "test/data/gct/affy_human.gct";
igvFile = new File("test/data/gct/affy_human.gct.igv");
ResourceLocator locator = new ResourceLocator(gctFile);
GCTtoIGVConverter.convert(locator, igvFile, null, 50000, null, genome);
}
}
|
/*
* AUTHORS: Jan Stender (ZIB)
*/
package org.xtreemfs.mrc.operations;
import org.xtreemfs.foundation.ErrNo;
import org.xtreemfs.interfaces.MRCInterface.chownRequest;
import org.xtreemfs.interfaces.MRCInterface.chownResponse;
import org.xtreemfs.mrc.ErrorRecord;
import org.xtreemfs.mrc.MRCRequest;
import org.xtreemfs.mrc.MRCRequestDispatcher;
import org.xtreemfs.mrc.UserException;
import org.xtreemfs.mrc.ErrorRecord.ErrorClass;
import org.xtreemfs.mrc.ac.FileAccessManager;
import org.xtreemfs.mrc.database.AtomicDBUpdate;
import org.xtreemfs.mrc.database.StorageManager;
import org.xtreemfs.mrc.metadata.FileMetadata;
import org.xtreemfs.mrc.utils.MRCHelper;
import org.xtreemfs.mrc.utils.Path;
import org.xtreemfs.mrc.utils.PathResolver;
import org.xtreemfs.mrc.volumes.VolumeManager;
import org.xtreemfs.mrc.volumes.metadata.VolumeInfo;
/**
*
* @author stender
*/
public class ChangeOwnerOperation extends MRCOperation {
public ChangeOwnerOperation(MRCRequestDispatcher master) {
super(master);
}
@Override
public void startRequest(MRCRequest rq) throws Throwable {
final chownRequest rqArgs = (chownRequest) rq.getRequestArgs();
final VolumeManager vMan = master.getVolumeManager();
final FileAccessManager faMan = master.getFileAccessManager();
validateContext(rq);
Path p = new Path(rqArgs.getPath());
VolumeInfo volume = vMan.getVolumeByName(p.getComp(0));
StorageManager sMan = vMan.getStorageManager(volume.getId());
PathResolver res = new PathResolver(sMan, p);
// check whether the path prefix is searchable
faMan.checkSearchPermission(sMan, res, rq.getDetails().userId, rq.getDetails().superUser, rq
.getDetails().groupIds);
// check whether file exists
res.checkIfFileDoesNotExist();
FileMetadata file = res.getFile();
// if the file refers to a symbolic link, resolve the link
String target = sMan.getSoftlinkTarget(file.getId());
if (target != null) {
rqArgs.setPath(target);
p = new Path(target);
// if the local MRC is not responsible, send a redirect
if (!vMan.hasVolume(p.getComp(0))) {
finishRequest(rq, new ErrorRecord(ErrorClass.USER_EXCEPTION, ErrNo.ENOENT, "link target "
+ target + " does not exist"));
return;
}
volume = vMan.getVolumeByName(p.getComp(0));
sMan = vMan.getStorageManager(volume.getId());
res = new PathResolver(sMan, p);
file = res.getFile();
}
// check whether the owner may be changed
if (!rqArgs.getUser_id().equals("")) {
// if a UID is provided, restrict operation to root user
if (!rq.getDetails().superUser)
throw new UserException(ErrNo.EACCES, "changing owners is restricted to superusers");
} else {
// if only a GID is provided, restrict the op to a privileged user
// that is either root or in the group that is supposed to be
// assigned
faMan.checkPrivilegedPermissions(sMan, file, rq.getDetails().userId, rq.getDetails().superUser,
rq.getDetails().groupIds);
if (!(rq.getDetails().superUser || rq.getDetails().groupIds.contains(rqArgs.getGroup_id())))
throw new UserException(
ErrNo.EACCES,
"changing owning groups is restricted to superusers or file owners who are in the group that is supposed to be assigned");
}
AtomicDBUpdate update = sMan.createAtomicDBUpdate(master, rq);
// change owner and owning group
file.setOwnerAndGroup(rqArgs.getUser_id().equals("") ? file.getOwnerId() : rqArgs.getUser_id(),
rqArgs.getGroup_id().equals("") ? file.getOwningGroupId() : rqArgs.getGroup_id());
sMan.setMetadata(file, FileMetadata.RC_METADATA, update);
// update POSIX timestamps
MRCHelper.updateFileTimes(res.getParentDirId(), file, false, true, false, sMan, update);
// set the response
rq.setResponse(new chownResponse());
update.execute();
}
}
|
package com.datasift.client.behavioural;
//CHECKSTYLE:OFF
//@RunWith(Cucumber.class)
//@CucumberOptions(
// plugin = {"pretty", "html:target/cucumber", "junit:target/cucumber/junit.xml"}
// , snippets = SnippetType.CAMELCASE
// , features = {"."}
// //, strict = true
//CHECKSTYLE:ON
public class CucumberRunnerTest {
}
|
package com.github.timtebeek.rst.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import lombok.Getter;
import lombok.Setter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration;
import org.springframework.security.oauth2.client.test.OAuth2ContextSetup;
import org.springframework.security.oauth2.client.test.RestTemplateHolder;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyControllerIT implements RestTemplateHolder {
@Value("http://localhost:${local.server.port}")
protected String host;
@Getter
@Setter
private RestOperations restTemplate = new RestTemplate();
@Rule
public OAuth2ContextSetup context = OAuth2ContextSetup.standard(this);
@Test
@OAuth2ContextConfiguration(UserDetails.class)
public void testHelloUser() {
ResponseEntity<String> entity = restTemplate.getForEntity(host + "/hello", String.class);
assertTrue(entity.toString(), entity.getStatusCode().is2xxSuccessful());
assertEquals("Hello user", entity.getBody());
}
@Test
@OAuth2ContextConfiguration(AliceDetails.class)
public void testHelloAlice() {
ResponseEntity<String> entity = restTemplate.getForEntity(host + "/hello", String.class);
assertTrue(entity.toString(), entity.getStatusCode().is2xxSuccessful());
assertEquals("Hello alice", entity.getBody());
}
@Test(expected = UserDeniedAuthorizationException.class)
@OAuth2ContextConfiguration(EveDetails.class)
public void testHelloEve() {
restTemplate.getForEntity(host + "/hello", String.class);
}
}
class UserDetails extends ResourceOwnerPasswordResourceDetails {
public UserDetails(final Object obj) {
MyControllerIT it = (MyControllerIT) obj;
setAccessTokenUri(it.host + "/oauth/token");
setClientId("myclientwith");
setUsername("user");
setPassword("password");
}
}
class AliceDetails extends ResourceOwnerPasswordResourceDetails {
public AliceDetails(final Object obj) {
MyControllerIT it = (MyControllerIT) obj;
setAccessTokenUri(it.host + "/oauth/token");
setClientId("myclientwith");
setUsername("alice");
setPassword("password");
}
}
class EveDetails extends ResourceOwnerPasswordResourceDetails {
public EveDetails(final Object obj) {
MyControllerIT it = (MyControllerIT) obj;
setAccessTokenUri(it.host + "/oauth/token");
setClientId("myclientwith");
setUsername("eve");
setPassword("password");
}
}
|
package com.ociweb.pronghorn.image;
import com.ociweb.iot.maker.PiImageListenerStage;
import com.ociweb.pronghorn.iot.schema.ImageSchema;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeReader;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;
import com.ociweb.pronghorn.stage.scheduling.NonThreadScheduler;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class ImageDownscaleStageTest {
public static final int[] DOWNSCALE_RESOLUTION_ONE = {640, 360};
public static class DownsamplePipeReaderState {
File file = new File("");
byte[] currentRow = null;
byte[] currentFrame = null;
int frameHead = 0;
}
public static void readFromDownsamplePipe(Pipe<ImageSchema> pipe, DownsamplePipeReaderState state, byte[] pipeEncoding) {
if (PipeReader.tryReadFragment(pipe)) {
switch (PipeReader.getMsgIdx(pipe)) {
case ImageSchema.MSG_FRAMESTART_1:
// Extract data.
int width = PipeReader.readInt(pipe, ImageSchema.MSG_FRAMESTART_1_FIELD_WIDTH_101);
int height = PipeReader.readInt(pipe, ImageSchema.MSG_FRAMESTART_1_FIELD_HEIGHT_201);
long time = PipeReader.readLong(pipe, ImageSchema.MSG_FRAMESTART_1_FIELD_TIMESTAMP_301);
int frameSize = PipeReader.readInt(pipe, ImageSchema.MSG_FRAMESTART_1_FIELD_FRAMEBYTES_401);
int bps = PipeReader.readInt(pipe, ImageSchema.MSG_FRAMESTART_1_FIELD_BITSPERPIXEL_501);
byte[] encoding = Arrays.copyOf(pipeEncoding, pipeEncoding.length);
PipeReader.readBytes(pipe, ImageSchema.MSG_FRAMESTART_1_FIELD_ENCODING_601, encoding, 0);
// Validate data.
assert Arrays.equals(encoding, pipeEncoding);
// Print data.
System.out.printf("New Frame: W%dxH%d @ %d [Frame Bytes: %d, Bits per pixel: %d].\n", width, height, time, frameSize, bps);
// Prep buffer.
state.currentFrame = new byte[frameSize * 3];
state.frameHead = 0;
state.file = new File(new String(pipeEncoding) + "-" + time + ".raw");
break;
case ImageSchema.MSG_FRAMECHUNK_2:
// If frame is full, skip.
if (state.frameHead >= state.currentFrame.length) {
break;
}
// Calculate row length.
int rowLength = PipeReader.readBytesLength(pipe, ImageSchema.MSG_FRAMECHUNK_2_FIELD_ROWBYTES_102);
// Prepare array if not already ready.
if (state.currentRow == null || state.currentRow.length != rowLength) {
state.currentRow = new byte[rowLength];
}
// Read bytes into array.
PipeReader.readBytes(pipe, ImageSchema.MSG_FRAMECHUNK_2_FIELD_ROWBYTES_102, state.currentRow, 0);
// Send bytes to frame.
for (int i = 0; i < state.currentRow.length; i++) {
// Switch by format.
if (pipeEncoding.equals(ImageDownscaleStage.R_OUTPUT_ENCODING)) {
state.currentFrame[state.frameHead] = state.currentRow[i];
state.currentFrame[state.frameHead + 1] = 0;
state.currentFrame[state.frameHead + 2] = 0;
} else if (pipeEncoding.equals(ImageDownscaleStage.G_OUTPUT_ENCODING)) {
state.currentFrame[state.frameHead] = 0;
state.currentFrame[state.frameHead + 1] = state.currentRow[i];
state.currentFrame[state.frameHead + 2] = 0;
} else if (pipeEncoding.equals(ImageDownscaleStage.B_OUTPUT_ENCODING)) {
state.currentFrame[state.frameHead] = 0;
state.currentFrame[state.frameHead + 1] = 0;
state.currentFrame[state.frameHead + 2] = state.currentRow[i];
} else if (pipeEncoding.equals(ImageDownscaleStage.MONO_OUTPUT_ENCODING)) {
state.currentFrame[state.frameHead] = state.currentRow[i];
state.currentFrame[state.frameHead + 1] = state.currentRow[i];
state.currentFrame[state.frameHead + 2] = state.currentRow[i];
}
state.frameHead += 3;
}
// If frame is full, flush.
if (state.frameHead >= state.currentFrame.length) {
System.out.println("Wrote " + state.file.getName().toString() + " to disk.");
try {
state.file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try (FileOutputStream fos = new FileOutputStream(state.file)) {
fos.write(state.currentFrame);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
PipeReader.releaseReadLock(pipe);
}
}
public GraphManager gm;
public Pipe<ImageSchema> imageInputPipe;
public Pipe<ImageSchema>[] downsampleOutputPipes = new Pipe[4];
public DownsamplePipeReaderState[] downsamplePipeReaderStates = new DownsamplePipeReaderState[downsampleOutputPipes.length];
@Before
public void setup() {
// Setup graph manager,
gm = new GraphManager();
// Setup image production pipe.
imageInputPipe = ImageSchema.instance.newPipe(1, PiImageListenerStage.ROW_SIZE * PiImageListenerStage.FRAME_HEIGHT);
imageInputPipe.initBuffers();
// Setup downsampling output pipes.
for (int i = 0; i < downsampleOutputPipes.length; i++) {
downsampleOutputPipes[i] = ImageSchema.instance.newPipe(1, DOWNSCALE_RESOLUTION_ONE[0] * DOWNSCALE_RESOLUTION_ONE[1]);
downsampleOutputPipes[i].initBuffers();
}
// Setup downsample pipe reader states.
for (int i = 0; i < downsamplePipeReaderStates.length; i++) {
downsamplePipeReaderStates[i] = new DownsamplePipeReaderState();
}
// Setup stages.
PiImageListenerStage imageListenerStage = new PiImageListenerStage(gm, imageInputPipe, 1);
ImageDownscaleStage imageDownscaleStage = new ImageDownscaleStage(gm, imageInputPipe,
downsampleOutputPipes,
DOWNSCALE_RESOLUTION_ONE[0],
DOWNSCALE_RESOLUTION_ONE[1]);
}
@Test
public void shouldDownscaleImages() {
// Create test scheduler.
NonThreadScheduler scheduler = new NonThreadScheduler(gm);
scheduler.startup();
// Run until the output pipes have data.
// TODO: Stop condition?
while (true) {
// Run scheduler pipe.
scheduler.run();
// Read from pipes.
for (int i = 0; i < downsampleOutputPipes.length; i++) {
switch (i) {
case ImageDownscaleStage.R_OUTPUT_IDX:
readFromDownsamplePipe(downsampleOutputPipes[i], downsamplePipeReaderStates[i], ImageDownscaleStage.R_OUTPUT_ENCODING);
break;
case ImageDownscaleStage.G_OUTPUT_IDX:
readFromDownsamplePipe(downsampleOutputPipes[i], downsamplePipeReaderStates[i], ImageDownscaleStage.G_OUTPUT_ENCODING);
break;
case ImageDownscaleStage.B_OUTPUT_IDX:
readFromDownsamplePipe(downsampleOutputPipes[i], downsamplePipeReaderStates[i], ImageDownscaleStage.B_OUTPUT_ENCODING);
break;
case ImageDownscaleStage.MONO_OUTPUT_IDX:
readFromDownsamplePipe(downsampleOutputPipes[i], downsamplePipeReaderStates[i], ImageDownscaleStage.MONO_OUTPUT_ENCODING);
break;
}
}
}
}
}
|
package eu.project.ttc.test.termino.export;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Locale;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import eu.project.ttc.api.TsvOptions;
import eu.project.ttc.models.Term;
import eu.project.ttc.models.TermIndex;
import eu.project.ttc.models.TermVariation;
import eu.project.ttc.termino.export.TsvExporter;
import eu.project.ttc.test.TermSuiteAssertions;
import eu.project.ttc.test.unit.TermFactory;
public class TsvExporterSpec {
TermIndex termIndex;
Collection<Term> terms;
Term term1, term2, term3;
StringWriter writer;
@Before
public void setup() {
termIndex = Mockito.mock(TermIndex.class);
term1 = TermFactory.termMock("t1", 1, 3, 0.8);
term2 = TermFactory.termMock("t2", 2, 1, 0.8);
term3 = TermFactory.termMock("t3", 3, 2, 1);
TermVariation tv = Mockito.mock(TermVariation.class);
Mockito.when(tv.getVariant()).thenReturn(term1);
Mockito.when(term3.getVariations()).thenReturn(Sets.newHashSet(tv));
terms = Lists.newArrayList(
term1,
term2,
term3
);
Mockito.when(termIndex.getTerms()).thenReturn(terms);
writer = new StringWriter();
defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
}
Locale defaultLocale;
@After
public void tearDown() {
Locale.setDefault(defaultLocale);
}
@Test
public void testTsvExportNoScore() {
TsvExporter.export(termIndex, writer);
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(5)
.tsvLineEquals(1, "#","type", "gkey", "f")
.tsvLineEquals(2, 1, "T", "t2", 2)
.tsvLineEquals(3, 2, "T", "t3", 3)
.tsvLineEquals(4, 2, "V", "t1", 1)
.tsvLineEquals(5, 3, "T", "t1", 1)
;
}
@Test
public void testTsvExportWithScores() {
TsvExporter.export(termIndex, writer, new TsvOptions().showScores(true));
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(5)
.tsvLineEquals(1, "#","type", "gkey", "f")
.tsvLineEquals(2, 1, "T[]", "t2", 2)
.tsvLineEquals(3, 2, "T[]", "t3", 3)
.tsvLineEquals(4, 2, "V[0.00]", "t1", 1)
.tsvLineEquals(5, 3, "T[]", "t1", 1)
;
}
@Test
public void testTsvExportNoHeaders() {
TsvExporter.export(termIndex, writer, new TsvOptions().showHeaders(false));
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(4)
.tsvLineEquals(1, 1, "T", "t2", 2)
.tsvLineEquals(2, 2, "T", "t3", 3)
.tsvLineEquals(3, 2, "V", "t1", 1)
.tsvLineEquals(4, 3, "T", "t1", 1)
;
}
@Test
public void testTsvExportNoVariant() {
TsvExporter.export(termIndex, writer, new TsvOptions().setShowVariants(false));
TermSuiteAssertions.assertThat(writer.toString())
.hasLineCount(4)
.tsvLineEquals(1, "#","type", "gkey", "f")
.tsvLineEquals(2, 1, "T", "t2", 2)
.tsvLineEquals(3, 2, "T", "t3", 3)
.tsvLineEquals(4, 3, "T", "t1", 1)
;
}
}
|
package io.usethesource.vallang.basic;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
import io.usethesource.vallang.IValue;
import io.usethesource.vallang.IValueFactory;
import io.usethesource.vallang.ValueProvider;
import io.usethesource.vallang.exceptions.FactTypeDeclarationException;
import io.usethesource.vallang.exceptions.FactTypeUseException;
import io.usethesource.vallang.type.Type;
import io.usethesource.vallang.type.TypeFactory;
import io.usethesource.vallang.type.TypeStore;
public final class TypeFactorySmokeTest {
private static TypeFactory ft = TypeFactory.getInstance();
private static Type[] types = new Type[] { ft.integerType(), ft.realType(), ft.sourceLocationType(), ft.valueType(),
ft.listType(ft.integerType()), ft.setType(ft.realType()) };
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testGetInstance() {
if (TypeFactory.getInstance() != ft) {
fail("getInstance did not return the same reference");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testGetTypeByDescriptor() {
// TODO: needs to be tested, after we've implemented it
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testValueType() {
if (ft.valueType() != ft.valueType()) {
fail("valueType should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testIntegerType() {
if (ft.integerType() != ft.integerType()) {
fail("integerType should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testDoubleType() {
if (ft.realType() != ft.realType()) {
fail("doubleType should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testStringType() {
if (ft.stringType() != ft.stringType()) {
fail("stringType should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testSourceLocationType() {
if (ft.sourceLocationType() != ft.sourceLocationType()) {
fail("sourceLocationType should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfType() {
Type t = ft.tupleType(types[0]);
if (t != ft.tupleType(types[0])) {
fail("tuple types should be canonical");
}
checkTupleTypeOf(t, 1);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfTypeType() {
Type t = ft.tupleType(types[0], types[1]);
if (t != ft.tupleType(types[0], types[1])) {
fail("tuple types should be canonical");
}
checkTupleTypeOf(t, 2);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfTypeTypeType() {
Type t = ft.tupleType(types[0], types[1], types[2]);
if (t != ft.tupleType(types[0], types[1], types[2])) {
fail("tuple types should be canonical");
}
checkTupleTypeOf(t, 3);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfTypeTypeTypeType() {
Type t = ft.tupleType(types[0], types[1], types[2], types[3]);
if (t != ft.tupleType(types[0], types[1], types[2], types[3])) {
fail("tuple types should be canonical");
}
checkTupleTypeOf(t, 4);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfTypeTypeTypeTypeType() {
Type t = ft.tupleType(types[0], types[1], types[2], types[3], types[4]);
if (t != ft.tupleType(types[0], types[1], types[2], types[3], types[4])) {
fail("tuple types should be canonical");
}
checkTupleTypeOf(t, 5);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfTypeTypeTypeTypeTypeType() {
Type t = ft.tupleType(types[0], types[1], types[2], types[3], types[4], types[5]);
if (t != ft.tupleType(types[0], types[1], types[2], types[3], types[4], types[5])) {
fail("tuple types should be canonical");
}
checkTupleTypeOf(t, 6);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfTypeTypeTypeTypeTypeTypeType() {
Type t = ft.tupleType(types[0], types[1], types[2], types[3], types[4], types[5]);
if (t != ft.tupleType(types[0], types[1], types[2], types[3], types[4], types[5])) {
fail("tuple types should be canonical");
}
checkTupleTypeOf(t, 6);
}
private void checkTupleTypeOf(Type t, int width) {
if (t.getArity() != width) {
fail("tuple arity broken");
}
for (int i = 0; i < t.getArity(); i++) {
if (t.getFieldType(i) != types[i % types.length]) {
fail("Tuple field type unexpected");
}
}
}
private void checkRelationTypeOf(Type t, int width) {
if (t.getArity() != width) {
fail("relation arity broken");
}
for (int i = 0; i < t.getArity(); i++) {
if (t.getFieldType(i) != types[i % types.length]) {
fail("Relation field type unexpected");
}
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testTupleTypeOfIValueArray(IValueFactory vf) {
// a and b shadow the 'types' field
try {
@SuppressWarnings("deprecation")
IValue[] a = new IValue[] { vf.integer(1), vf.real(1.0),
vf.sourceLocation(new URI("file://bla"), 0, 0, 0, 0, 0, 0) };
@SuppressWarnings("deprecation")
IValue[] b = new IValue[] { vf.integer(1), vf.real(1.0),
vf.sourceLocation(new URI("file://bla"), 0, 0, 0, 0, 0, 0) };
Type t = ft.tupleType(a);
if (t != ft.tupleType(b)) {
fail("tuples should be canonical");
}
checkTupleTypeOf(t, 3);
} catch (URISyntaxException e) {
fail(e.toString());
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testSetTypeOf() {
Type type = ft.setType(ft.integerType());
if (type != ft.setType(ft.integerType())) {
fail("set should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeType() {
try {
TypeStore store = new TypeStore();
Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
// note that the declared type of namedType needs to be Type
Type type = ft.relTypeFromTuple(namedType);
Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
if (type != ft.relTypeFromTuple(namedType2)) {
fail("relation types should be canonical");
}
if (type.getFieldType(0) != ft.integerType() && type.getFieldType(1) != ft.integerType()) {
fail("relation should mimick tuple field types");
}
} catch (FactTypeUseException e) {
fail("type error for correct relation");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testListRelTypeType() {
try {
TypeStore store = new TypeStore();
Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
// note that the declared type of namedType needs to be Type
Type type = ft.lrelTypeFromTuple(namedType);
Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
if (type != ft.lrelTypeFromTuple(namedType2)) {
fail("list relation types should be canonical");
}
if (type.getFieldType(0) != ft.integerType() && type.getFieldType(1) != ft.integerType()) {
fail("list relation should mimick tuple field types");
}
} catch (FactTypeUseException e) {
fail("type error for correct list relation");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeNamedType() {
try {
TypeStore store = new TypeStore();
Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
// note that the declared type of namedType needs to be AliasType
Type type = ft.relTypeFromTuple(namedType);
Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
if (type != ft.relTypeFromTuple(namedType2)) {
fail("relation types should be canonical");
}
} catch (FactTypeUseException e) {
fail("type error for correct relation");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testListRelTypeNamedType() {
try {
TypeStore store = new TypeStore();
Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
// note that the declared type of namedType needs to be AliasType
Type type = ft.lrelTypeFromTuple(namedType);
Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType()));
if (type != ft.lrelTypeFromTuple(namedType2)) {
fail("list relation types should be canonical");
}
} catch (FactTypeUseException e) {
fail("type error for correct list relation");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeTupleType() {
Type tupleType = ft.tupleType(ft.integerType(), ft.integerType());
// note that the declared type of tupleType needs to be TupleType
Type type = ft.relTypeFromTuple(tupleType);
Type tupleType2 = ft.tupleType(ft.integerType(), ft.integerType());
if (type != ft.relTypeFromTuple(tupleType2)) {
fail("relation types should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testListRelTypeTupleType() {
Type tupleType = ft.tupleType(ft.integerType(), ft.integerType());
// note that the declared type of tupleType needs to be TupleType
Type type = ft.lrelTypeFromTuple(tupleType);
Type tupleType2 = ft.tupleType(ft.integerType(), ft.integerType());
if (type != ft.lrelTypeFromTuple(tupleType2)) {
fail("list relation types should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeOfType() {
Type type = ft.relType(types[0]);
if (type != ft.relType(types[0])) {
fail("relation types should be canonical");
}
checkRelationTypeOf(type, 1);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeOfTypeType() {
Type type = ft.relType(types[0], types[1]);
if (type != ft.relType(types[0], types[1])) {
fail("relation types should be canonical");
}
checkRelationTypeOf(type, 2);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeOfTypeTypeType() {
Type type = ft.relType(types[0], types[1], types[2]);
if (type != ft.relType(types[0], types[1], types[2])) {
fail("relation types should be canonical");
}
checkRelationTypeOf(type, 3);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeOfTypeTypeTypeType() {
Type type = ft.relType(types[0], types[1], types[2], types[3]);
if (type != ft.relType(types[0], types[1], types[2], types[3])) {
fail("relation types should be canonical");
}
checkRelationTypeOf(type, 4);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeOfTypeTypeTypeTypeType() {
Type type = ft.relType(types[0], types[1], types[2], types[3], types[4]);
if (type != ft.relType(types[0], types[1], types[2], types[3], types[4])) {
fail("relation types should be canonical");
}
checkRelationTypeOf(type, 5);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeOfTypeTypeTypeTypeTypeType() {
Type type = ft.relType(types[0], types[1], types[2], types[3], types[4], types[5]);
if (type != ft.relType(types[0], types[1], types[2], types[3], types[4], types[5])) {
fail("relation types should be canonical");
}
checkRelationTypeOf(type, 6);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testRelTypeOfTypeTypeTypeTypeTypeTypeType() {
Type type = ft.relType(types[0], types[1], types[2], types[3], types[4], types[5]);
if (type != ft.relType(types[0], types[1], types[2], types[3], types[4], types[5])) {
fail("relation types should be canonical");
}
checkRelationTypeOf(type, 6);
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testNamedType() {
try {
TypeStore ts = new TypeStore();
Type t1 = ft.aliasType(ts, "myType", ft.integerType());
Type t2 = ft.aliasType(ts, "myType", ft.integerType());
if (t1 != t2) {
fail("named types should be canonical");
}
try {
ft.aliasType(ts, "myType", ft.realType());
fail("Should not be allowed to redeclare a type name");
} catch (FactTypeDeclarationException e) {
// this should happen
}
} catch (FactTypeDeclarationException e) {
fail("the above should be type correct");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testListType() {
Type t1 = ft.listType(ft.integerType());
Type t2 = ft.listType(ft.integerType());
if (t1 != t2) {
fail("named types should be canonical");
}
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testFunctionLub(TypeFactory tf) {
Type t1 = tf.functionType(tf.integerType(), tf.tupleType(tf.integerType(), tf.integerType()), tf.tupleEmpty());
Type t2 = tf.functionType(tf.integerType(), tf.tupleType(tf.rationalType(), tf.rationalType()),
tf.tupleEmpty());
// if the arity is the same, the lub is still a function type (for computing the
// types of overloaded functions)
assertTrue(!t1.lub(t2).isTop());
assertTrue(t1.getArity() == t1.lub(t2).getArity());
// but if its not the same, then we default to value, because we don't know how
// to call a function with different amounts of parameters
Type t3 = tf.functionType(tf.integerType(), tf.tupleType(tf.stringType()), tf.tupleEmpty());
assertTrue(t1.lub(t3).isTop());
}
@ParameterizedTest
@ArgumentsSource(ValueProvider.class)
public void testHigherOrderSelfMatchOfFunctionType(TypeFactory tf) {
Type returnType = tf.parameterType("Ret");
Type arg1 = tf.parameterType("Arg1");
Type arg2 = tf.parameterType("Arg2");
// &Ret curried(&Arg2 arg2)
Type curriedFunction = tf.functionType(returnType, tf.tupleType(arg2), tf.tupleEmpty());
// &Ret func (&Arg1 arg1, &Arg2 arg2)
Type parameterFunction = tf.functionType(returnType, tf.tupleType(arg1, arg2), tf.tupleEmpty());
// &Ret (&Arg2) curry (&Return (&Arg1, &Arg2) func, &Arg1 arg1)
Type curry = tf.functionType(curriedFunction, tf.tupleType(parameterFunction, arg1), tf.tupleEmpty());
// First we rename the type parameters for the purpose of parameter hygiene:
Map<Type, Type> renamings = new HashMap<>();
curry.match(tf.voidType(), renamings);
for (Type key : renamings.keySet()) {
renamings.put(key, tf.parameterType(key.getName() + "'"));
}
Type renamedCurry = curry.instantiate(renamings);
// now we self apply the curry function with an add function
Type addFunction = tf.functionType(tf.integerType(), tf.tupleType(tf.integerType(), tf.integerType()), tf.tupleEmpty());
Type curriedAdd = tf.functionType(tf.integerType(), tf.tupleType(tf.integerType()), tf.tupleEmpty());
Type curriedCurryReturn = tf.functionType(curriedAdd, tf.tupleType(tf.integerType()), tf.tupleEmpty());
// the goal is to arrive at a binding of &Ret to an instantiated int (int) curried function, via parameter matching
Type actualParameterTypes = tf.tupleType(renamedCurry, addFunction);
Type formalParameterTypes = curry.getFieldTypes();
Map<Type, Type> bindings = new HashMap<>();
// this is where the bug was/is.
// applying curry(curry, add) should give `int(int arg2) (int arg1)` as a return type.
formalParameterTypes.match(actualParameterTypes, bindings);
// instead we get the uninstantiated version &Ret' (&Arg2') (&Arg1')
System.err.println(curry.getReturnType().instantiate(bindings));
assertTrue(curry.getReturnType().instantiate(bindings) == curriedCurryReturn);
}
}
|
package org.jfree.chart.renderer.junit;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.event.RendererChangeListener;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.ui.TextAnchor;
/**
* Tests for the {@link AbstractRenderer} class.
*/
public class AbstractRendererTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(AbstractRendererTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public AbstractRendererTests(String name) {
super(name);
}
/**
* Test that the equals() method distinguishes all fields.
*/
public void testEquals() {
// have to use a concrete subclass...
BarRenderer r1 = new BarRenderer();
BarRenderer r2 = new BarRenderer();
assertTrue(r1.equals(r2));
assertTrue(r2.equals(r1));
// seriesVisible
r1.setSeriesVisible(Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesVisible(Boolean.TRUE);
assertTrue(r1.equals(r2));
// seriesVisibleList
r1.setSeriesVisible(2, Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesVisible(2, Boolean.TRUE);
assertTrue(r1.equals(r2));
// baseSeriesVisible
r1.setBaseSeriesVisible(false);
assertFalse(r1.equals(r2));
r2.setBaseSeriesVisible(false);
assertTrue(r1.equals(r2));
// seriesVisibleInLegend
r1.setSeriesVisibleInLegend(Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesVisibleInLegend(Boolean.TRUE);
assertTrue(r1.equals(r2));
// seriesVisibleInLegendList
r1.setSeriesVisibleInLegend(1, Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesVisibleInLegend(1, Boolean.TRUE);
assertTrue(r1.equals(r2));
// baseSeriesVisibleInLegend
r1.setBaseSeriesVisibleInLegend(false);
assertFalse(r1.equals(r2));
r2.setBaseSeriesVisibleInLegend(false);
assertTrue(r1.equals(r2));
// paint
r1.setPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// paintList
r1.setSeriesPaint(0, new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.white));
assertFalse(r1.equals(r2));
r2.setSeriesPaint(0, new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.white));
assertTrue(r1.equals(r2));
// basePaint
r1.setBasePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setBasePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// fillPaint
r1.setFillPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setFillPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// fillPaintList
r1.setSeriesFillPaint(0, new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setSeriesFillPaint(0, new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// baseFillPaint
r1.setBaseFillPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setBaseFillPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// outlinePaint
r1.setOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// outlinePaintList
r1.setSeriesOutlinePaint(0, new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setSeriesOutlinePaint(0, new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// baseOutlinePaint
r1.setBaseOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setBaseOutlinePaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// stroke
Stroke s = new BasicStroke(3.21f);
r1.setStroke(s);
assertFalse(r1.equals(r2));
r2.setStroke(s);
assertTrue(r1.equals(r2));
// strokeList
r1.setSeriesStroke(1, s);
assertFalse(r1.equals(r2));
r2.setSeriesStroke(1, s);
assertTrue(r1.equals(r2));
// baseStroke
r1.setBaseStroke(s);
assertFalse(r1.equals(r2));
r2.setBaseStroke(s);
assertTrue(r1.equals(r2));
// outlineStroke
r1.setOutlineStroke(s);
assertFalse(r1.equals(r2));
r2.setOutlineStroke(s);
assertTrue(r1.equals(r2));
// outlineStrokeList
r1.setSeriesOutlineStroke(0, s);
assertFalse(r1.equals(r2));
r2.setSeriesOutlineStroke(0, s);
assertTrue(r1.equals(r2));
// baseOutlineStroke
r1.setBaseOutlineStroke(s);
assertFalse(r1.equals(r2));
r2.setBaseOutlineStroke(s);
assertTrue(r1.equals(r2));
// shape
r1.setShape(new Rectangle(1, 2, 3, 4));
assertFalse(r1.equals(r2));
r2.setShape(new Rectangle(1, 2, 3, 4));
assertTrue(r1.equals(r2));
// shapeList
r1.setSeriesShape(1, new Rectangle(1, 2, 3, 4));
assertFalse(r1.equals(r2));
r2.setSeriesShape(1, new Rectangle(1, 2, 3, 4));
assertTrue(r1.equals(r2));
// baseShape
r1.setBaseShape(new Rectangle(1, 2, 3, 4));
assertFalse(r1.equals(r2));
r2.setBaseShape(new Rectangle(1, 2, 3, 4));
assertTrue(r1.equals(r2));
// itemLabelsVisible
r1.setItemLabelsVisible(true);
assertFalse(r1.equals(r2));
r2.setItemLabelsVisible(true);
assertTrue(r1.equals(r2));
// itemLabelsVisibleList
r1.setSeriesItemLabelsVisible(1, Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesItemLabelsVisible(1, Boolean.TRUE);
assertTrue(r1.equals(r2));
// baseItemLabelsVisible
r1.setBaseItemLabelsVisible(true);
assertFalse(r1.equals(r2));
r2.setBaseItemLabelsVisible(true);
assertTrue(r1.equals(r2));
// itemLabelFont
r1.setItemLabelFont(new Font("Serif", Font.PLAIN, 10));
assertFalse(r1.equals(r2));
r2.setItemLabelFont(new Font("Serif", Font.PLAIN, 10));
assertTrue(r1.equals(r2));
// itemLabelFontList
r1.setSeriesItemLabelFont(1, new Font("Serif", Font.BOLD, 9));
assertFalse(r1.equals(r2));
r2.setSeriesItemLabelFont(1, new Font("Serif", Font.BOLD, 9));
assertTrue(r1.equals(r2));
// baseItemLabelFont
r1.setBaseItemLabelFont(new Font("Serif", Font.PLAIN, 10));
assertFalse(r1.equals(r2));
r2.setBaseItemLabelFont(new Font("Serif", Font.PLAIN, 10));
assertTrue(r1.equals(r2));
// itemLabelPaint
r1.setItemLabelPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.gray));
assertFalse(r1.equals(r2));
r2.setItemLabelPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.gray));
assertTrue(r1.equals(r2));
// itemLabelPaintList
r1.setSeriesItemLabelPaint(0, new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.gray));
assertFalse(r1.equals(r2));
r2.setSeriesItemLabelPaint(0, new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.gray));
assertTrue(r1.equals(r2));
// baseItemLabelPaint
r1.setBaseItemLabelPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.gray));
assertFalse(r1.equals(r2));
r2.setBaseItemLabelPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.gray));
assertTrue(r1.equals(r2));
// positiveItemLabelPosition;
r1.setPositiveItemLabelPosition(new ItemLabelPosition());
assertFalse(r1.equals(r2));
r2.setPositiveItemLabelPosition(new ItemLabelPosition());
assertTrue(r1.equals(r2));
// positiveItemLabelPositionList;
r1.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition());
assertFalse(r1.equals(r2));
r2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition());
assertTrue(r1.equals(r2));
// basePositiveItemLabelPosition;
r1.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertFalse(r1.equals(r2));
r2.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertTrue(r1.equals(r2));
// negativeItemLabelPosition;
r1.setNegativeItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertFalse(r1.equals(r2));
r2.setNegativeItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertTrue(r1.equals(r2));
// negativeItemLabelPositionList;
r1.setSeriesNegativeItemLabelPosition(1, new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertFalse(r1.equals(r2));
r2.setSeriesNegativeItemLabelPosition(1, new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertTrue(r1.equals(r2));
// baseNegativeItemLabelPosition;
r1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertFalse(r1.equals(r2));
r2.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_RIGHT));
assertTrue(r1.equals(r2));
// itemLabelAnchorOffset
r1.setItemLabelAnchorOffset(3.0);
assertFalse(r1.equals(r2));
r2.setItemLabelAnchorOffset(3.0);
assertTrue(r1.equals(r2));
// createEntities;
r1.setCreateEntities(Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setCreateEntities(Boolean.TRUE);
assertTrue(r1.equals(r2));
// createEntitiesList;
r1.setSeriesCreateEntities(0, Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesCreateEntities(0, Boolean.TRUE);
assertTrue(r1.equals(r2));
// baseCreateEntities;
r1.setBaseCreateEntities(false);
assertFalse(r1.equals(r2));
r2.setBaseCreateEntities(false);
assertTrue(r1.equals(r2));
// legendShape
r1.setLegendShape(0, new Line2D.Double(1.0, 2.0, 3.0, 4.0));
assertFalse(r1.equals(r2));
r2.setLegendShape(0, new Line2D.Double(1.0, 2.0, 3.0, 4.0));
assertTrue(r1.equals(r2));
// baseLegendShape
r1.setBaseLegendShape(new Line2D.Double(5.0, 6.0, 7.0, 8.0));
assertFalse(r1.equals(r2));
r2.setBaseLegendShape(new Line2D.Double(5.0, 6.0, 7.0, 8.0));
assertTrue(r1.equals(r2));
// legendTextFont
r1.setLegendTextFont(0, new Font("Dialog", Font.PLAIN, 7));
assertFalse(r1.equals(r2));
r2.setLegendTextFont(0, new Font("Dialog", Font.PLAIN, 7));
assertTrue(r1.equals(r2));
// baseLegendTextFont
r1.setBaseLegendTextFont(new Font("Dialog", Font.PLAIN, 7));
assertFalse(r1.equals(r2));
r2.setBaseLegendTextFont(new Font("Dialog", Font.PLAIN, 7));
assertTrue(r1.equals(r2));
// legendTextPaint
r1.setLegendTextPaint(0, new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setLegendTextPaint(0, new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
// baseOutlinePaint
r1.setBaseLegendTextPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertFalse(r1.equals(r2));
r2.setBaseLegendTextPaint(new GradientPaint(1.0f, 2.0f, Color.blue,
3.0f, 4.0f, Color.red));
assertTrue(r1.equals(r2));
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
LineAndShapeRenderer r1 = new LineAndShapeRenderer();
Rectangle2D shape = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0);
Rectangle2D baseShape = new Rectangle2D.Double(11.0, 12.0, 13.0, 14.0);
r1.setShape(shape);
r1.setBaseShape(baseShape);
r1.setBaseLegendShape(new Rectangle(4, 3, 2, 1));
r1.setBaseLegendTextFont(new Font("Dialog", Font.PLAIN, 3));
r1.setBaseLegendTextPaint(new Color(1, 2, 3));
LineAndShapeRenderer r2 = null;
try {
r2 = (LineAndShapeRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
r1.setSeriesVisible(0, Boolean.FALSE);
assertFalse(r1.equals(r2));
r2.setSeriesVisible(0, Boolean.FALSE);
assertTrue(r1.equals(r2));
r1.setSeriesVisibleInLegend(0, Boolean.FALSE);
assertFalse(r1.equals(r2));
r2.setSeriesVisibleInLegend(0, Boolean.FALSE);
assertTrue(r1.equals(r2));
r1.setSeriesPaint(0, Color.black);
assertFalse(r1.equals(r2));
r2.setSeriesPaint(0, Color.black);
assertTrue(r1.equals(r2));
r1.setSeriesFillPaint(0, Color.yellow);
assertFalse(r1.equals(r2));
r2.setSeriesFillPaint(0, Color.yellow);
assertTrue(r1.equals(r2));
r1.setSeriesOutlinePaint(0, Color.yellow);
assertFalse(r1.equals(r2));
r2.setSeriesOutlinePaint(0, Color.yellow);
assertTrue(r1.equals(r2));
r1.setSeriesStroke(0, new BasicStroke(2.2f));
assertFalse(r1.equals(r2));
r2.setSeriesStroke(0, new BasicStroke(2.2f));
assertTrue(r1.equals(r2));
r1.setSeriesOutlineStroke(0, new BasicStroke(2.2f));
assertFalse(r1.equals(r2));
r2.setSeriesOutlineStroke(0, new BasicStroke(2.2f));
assertTrue(r1.equals(r2));
shape.setRect(4.0, 3.0, 2.0, 1.0);
assertFalse(r1.equals(r2));
r2.setShape(new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0));
assertTrue(r1.equals(r2));
baseShape.setRect(4.0, 3.0, 2.0, 1.0);
assertFalse(r1.equals(r2));
r2.setBaseShape(new Rectangle2D.Double(4.0, 3.0, 2.0, 1.0));
assertTrue(r1.equals(r2));
r1.setSeriesShape(0, new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0));
assertFalse(r1.equals(r2));
r2.setSeriesShape(0, new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0));
assertTrue(r1.equals(r2));
r1.setSeriesItemLabelsVisible(0, Boolean.TRUE);
assertFalse(r1.equals(r2));
r2.setSeriesItemLabelsVisible(0, Boolean.TRUE);
assertTrue(r1.equals(r2));
r1.setSeriesItemLabelPaint(0, Color.red);
assertFalse(r1.equals(r2));
r2.setSeriesItemLabelPaint(0, Color.red);
assertTrue(r1.equals(r2));
r1.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition());
assertFalse(r1.equals(r2));
r2.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition());
assertTrue(r1.equals(r2));
r1.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition());
assertFalse(r1.equals(r2));
r2.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition());
assertTrue(r1.equals(r2));
r1.setSeriesCreateEntities(0, Boolean.FALSE);
assertFalse(r1.equals(r2));
r2.setSeriesCreateEntities(0, Boolean.FALSE);
assertTrue(r1.equals(r2));
r1.setLegendShape(0, new Rectangle(9, 7, 3, 4));
assertFalse(r1.equals(r2));
r2.setLegendShape(0, new Rectangle(9, 7, 3, 4));
assertTrue(r1.equals(r2));
r1.setBaseLegendShape(new Rectangle(3, 4, 1, 5));
assertFalse(r1.equals(r2));
r2.setBaseLegendShape(new Rectangle(3, 4, 1, 5));
assertTrue(r1.equals(r2));
r1.setLegendTextFont(1, new Font("Dialog", Font.PLAIN, 33));
assertFalse(r1.equals(r2));
r2.setLegendTextFont(1, new Font("Dialog", Font.PLAIN, 33));
assertTrue(r1.equals(r2));
r1.setBaseLegendTextFont(new Font("Dialog", Font.PLAIN, 11));
assertFalse(r1.equals(r2));
r2.setBaseLegendTextFont(new Font("Dialog", Font.PLAIN, 11));
assertTrue(r1.equals(r2));
r1.setLegendTextPaint(3, Color.red);
assertFalse(r1.equals(r2));
r2.setLegendTextPaint(3, Color.red);
assertTrue(r1.equals(r2));
r1.setBaseLegendTextPaint(Color.green);
assertFalse(r1.equals(r2));
r2.setBaseLegendTextPaint(Color.green);
assertTrue(r1.equals(r2));
}
/**
* A utility class for listening to changes to a renderer.
*/
static class MyRendererChangeListener implements RendererChangeListener {
/** The last event received. */
public RendererChangeEvent lastEvent;
/**
* Creates a new instance.
*/
public MyRendererChangeListener() {
this.lastEvent = null;
}
public void rendererChanged(RendererChangeEvent event) {
this.lastEvent = event;
}
}
/**
* A check for cloning.
*/
public void testCloning2() {
LineAndShapeRenderer r1 = new LineAndShapeRenderer();
r1.setBasePaint(Color.blue);
r1.setBaseLegendTextPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.blue));
LineAndShapeRenderer r2 = null;
try {
r2 = (LineAndShapeRenderer) r1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
MyRendererChangeListener listener = new MyRendererChangeListener();
r2.addChangeListener(listener);
r2.setBasePaint(Color.red);
assertTrue(listener.lastEvent.getRenderer() == r2);
assertFalse(r1.hasListener(listener));
}
/**
* Test that setting the series visibility for ALL series does in fact work.
*/
public void testSetSeriesVisible() {
BarRenderer r = new BarRenderer();
r.setSeriesVisible(Boolean.TRUE);
assertTrue(r.getItemVisible(0, 0));
}
/**
* Test that setting the paint for ALL series does in fact work.
*/
public void testSetPaint() {
BarRenderer r = new BarRenderer();
r.setPaint(Color.orange);
assertEquals(Color.orange, r.getItemPaint(0, 0));
}
/**
* Test that setting the outline paint for ALL series does in fact work.
*/
public void testSetOutlinePaint() {
BarRenderer r = new BarRenderer();
r.setOutlinePaint(Color.orange);
assertEquals(Color.orange, r.getItemOutlinePaint(0, 0));
}
/**
* Test that setting the stroke for ALL series does in fact work.
*/
public void testSetStroke() {
BarRenderer r = new BarRenderer();
Stroke s = new BasicStroke(10.0f);
r.setStroke(s);
assertEquals(s, r.getItemStroke(0, 0));
}
/**
* Test that setting the outline stroke for ALL series does in fact work.
*/
public void testSetOutlineStroke() {
BarRenderer r = new BarRenderer();
Stroke s = new BasicStroke(10.0f);
r.setOutlineStroke(s);
assertEquals(s, r.getItemOutlineStroke(0, 0));
}
/**
* Test that setting the shape for ALL series does in fact work.
*/
public void testSetShape() {
BarRenderer r = new BarRenderer();
Shape s = new Rectangle2D.Double(1.0, 2.0, 3.0, 4.0);
r.setShape(s);
assertEquals(s, r.getItemShape(0, 0));
}
/**
* Test that setting the item label visibility for ALL series does in fact
* work.
*/
public void testSetItemLabelsVisible() {
BarRenderer r = new BarRenderer();
r.setItemLabelsVisible(true);
assertTrue(r.isItemLabelVisible(0, 0));
}
/**
* Test that setting the font for ALL series does in fact work (it was
* broken at one point).
*/
public void testSetItemLabelFont() {
BarRenderer r = new BarRenderer();
r.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 33));
assertEquals(new Font("SansSerif", Font.PLAIN, 33),
r.getItemLabelFont(0, 0));
}
/**
* Test that setting the paint for ALL series does in fact work (it was
* broken at one point).
*/
public void testSetItemLabelPaint() {
BarRenderer r = new BarRenderer();
r.setItemLabelPaint(Color.green);
assertEquals(Color.green, r.getItemLabelPaint(0, 0));
}
/**
* Test that setting the positive item label position for ALL series does
* in fact work.
*/
public void testSetPositiveItemLabelPosition() {
BarRenderer r = new BarRenderer();
r.setPositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE1, TextAnchor.BASELINE_LEFT));
assertEquals(new ItemLabelPosition(
ItemLabelAnchor.INSIDE1, TextAnchor.BASELINE_LEFT),
r.getPositiveItemLabelPosition(0, 0));
}
/**
* Test that setting the negative item label position for ALL series does
* in fact work.
*/
public void testSetNegativeItemLabelPosition() {
BarRenderer r = new BarRenderer();
r.setNegativeItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.INSIDE1, TextAnchor.BASELINE_LEFT));
assertEquals(new ItemLabelPosition(
ItemLabelAnchor.INSIDE1, TextAnchor.BASELINE_LEFT),
r.getNegativeItemLabelPosition(0, 0));
}
/**
* Tests each setter method to ensure that it sends an event notification.
*/
public void testEventNotification() {
RendererChangeDetector detector = new RendererChangeDetector();
BarRenderer r1 = new BarRenderer(); // have to use a subclass of
// AbstractRenderer
r1.addChangeListener(detector);
// PAINT
detector.setNotified(false);
r1.setPaint(Color.red);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesPaint(0, Color.red);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBasePaint(Color.red);
assertTrue(detector.getNotified());
// OUTLINE PAINT
detector.setNotified(false);
r1.setOutlinePaint(Color.red);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesOutlinePaint(0, Color.red);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseOutlinePaint(Color.red);
assertTrue(detector.getNotified());
// STROKE
detector.setNotified(false);
r1.setStroke(new BasicStroke(1.0f));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesStroke(0, new BasicStroke(1.0f));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseStroke(new BasicStroke(1.0f));
assertTrue(detector.getNotified());
// OUTLINE STROKE
detector.setNotified(false);
r1.setOutlineStroke(new BasicStroke(1.0f));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesOutlineStroke(0, new BasicStroke(1.0f));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseOutlineStroke(new BasicStroke(1.0f));
assertTrue(detector.getNotified());
// SHAPE
detector.setNotified(false);
r1.setShape(new Rectangle2D.Float());
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesShape(0, new Rectangle2D.Float());
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseShape(new Rectangle2D.Float());
assertTrue(detector.getNotified());
// ITEM_LABELS_VISIBLE
detector.setNotified(false);
r1.setItemLabelsVisible(Boolean.TRUE);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesItemLabelsVisible(0, Boolean.TRUE);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseItemLabelsVisible(Boolean.TRUE);
assertTrue(detector.getNotified());
// ITEM_LABEL_FONT
detector.setNotified(false);
r1.setItemLabelFont(new Font("Serif", Font.PLAIN, 12));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesItemLabelFont(0, new Font("Serif", Font.PLAIN, 12));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseItemLabelFont(new Font("Serif", Font.PLAIN, 12));
assertTrue(detector.getNotified());
// ITEM_LABEL_PAINT
detector.setNotified(false);
r1.setItemLabelPaint(Color.blue);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesItemLabelPaint(0, Color.blue);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseItemLabelPaint(Color.blue);
assertTrue(detector.getNotified());
// POSITIVE ITEM LABEL POSITION
detector.setNotified(false);
r1.setPositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.CENTER, TextAnchor.CENTER));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(
ItemLabelAnchor.CENTER, TextAnchor.CENTER));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBasePositiveItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.CENTER, TextAnchor.CENTER));
assertTrue(detector.getNotified());
// NEGATIVE ITEM LABEL ANCHOR
detector.setNotified(false);
r1.setNegativeItemLabelPosition(
new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER)
);
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setSeriesNegativeItemLabelPosition(0, new ItemLabelPosition(
ItemLabelAnchor.CENTER, TextAnchor.CENTER));
assertTrue(detector.getNotified());
detector.setNotified(false);
r1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
ItemLabelAnchor.CENTER, TextAnchor.CENTER));
assertTrue(detector.getNotified());
}
/**
* Serialize an instance, restore it, and check for equality. In addition,
* test for a bug that was reported where the listener list is 'null' after
* deserialization.
*/
public void testSerialization() {
BarRenderer r1 = new BarRenderer();
r1.setBaseLegendTextFont(new Font("Dialog", Font.PLAIN, 4));
r1.setBaseLegendTextPaint(new GradientPaint(1.0f, 2.0f, Color.red,
3.0f, 4.0f, Color.green));
r1.setBaseLegendShape(new Line2D.Double(1.0, 2.0, 3.0, 4.0));
BarRenderer r2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(r1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
r2 = (BarRenderer) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(r1, r2);
try {
r2.notifyListeners(new RendererChangeEvent(r2));
}
catch (NullPointerException e) {
assertTrue(false); // failed
}
}
/**
* Some checks for the autoPopulate flag default values.
*/
public void testAutoPopulateFlagDefaults() {
BarRenderer r = new BarRenderer();
assertEquals(true, r.getAutoPopulateSeriesPaint());
assertEquals(false, r.getAutoPopulateSeriesFillPaint());
assertEquals(false, r.getAutoPopulateSeriesOutlinePaint());
assertEquals(true, r.getAutoPopulateSeriesStroke());
assertEquals(false, r.getAutoPopulateSeriesOutlineStroke());
assertEquals(true, r.getAutoPopulateSeriesShape());
}
/**
* Some checks for the paint lookup mechanism.
*/
public void testPaintLookup() {
BarRenderer r = new BarRenderer();
assertEquals(Color.blue, r.getBasePaint());
// first check that autoPopulate==false works as expected
r.setAutoPopulateSeriesPaint(false);
assertEquals(Color.blue, r.lookupSeriesPaint(0));
assertNull(r.getSeriesPaint(0));
// now check autoPopulate==true
r.setAutoPopulateSeriesPaint(true);
/*CategoryPlot plot =*/ new CategoryPlot(null, new CategoryAxis(
"Category"), new NumberAxis("Value"), r);
assertEquals(DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[0],
r.lookupSeriesPaint(0));
assertNotNull(r.getSeriesPaint(0));
}
/**
* Some checks for the fill paint lookup mechanism.
*/
public void testFillPaintLookup() {
BarRenderer r = new BarRenderer();
assertEquals(Color.white, r.getBaseFillPaint());
// first check that autoPopulate==false works as expected
r.setAutoPopulateSeriesFillPaint(false);
assertEquals(Color.white, r.lookupSeriesFillPaint(0));
assertNull(r.getSeriesFillPaint(0));
// now check autoPopulate==true
r.setAutoPopulateSeriesFillPaint(true);
/*CategoryPlot plot =*/ new CategoryPlot(null, new CategoryAxis(
"Category"), new NumberAxis("Value"), r);
assertEquals(DefaultDrawingSupplier.DEFAULT_FILL_PAINT_SEQUENCE[0],
r.lookupSeriesFillPaint(0));
assertNotNull(r.getSeriesFillPaint(0));
}
/**
* Some checks for the outline paint lookup mechanism.
*/
public void testOutlinePaintLookup() {
BarRenderer r = new BarRenderer();
assertEquals(Color.gray, r.getBaseOutlinePaint());
// first check that autoPopulate==false works as expected
r.setAutoPopulateSeriesOutlinePaint(false);
assertEquals(Color.gray, r.lookupSeriesOutlinePaint(0));
assertNull(r.getSeriesOutlinePaint(0));
// now check autoPopulate==true
r.setAutoPopulateSeriesOutlinePaint(true);
/*CategoryPlot plot =*/ new CategoryPlot(null, new CategoryAxis(
"Category"), new NumberAxis("Value"), r);
assertEquals(DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE[0],
r.lookupSeriesOutlinePaint(0));
assertNotNull(r.getSeriesOutlinePaint(0));
}
}
|
package org.codehaus.plexus.util.cli.shell;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.Commandline;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
public class BourneShellTest
extends TestCase
{
protected Shell newShell()
{
return new BourneShell();
}
public void testQuoteWorkingDirectoryAndExecutable()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/local/bin" );
sh.setExecutable( "chmod" );
String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );
assertEquals( "/bin/sh -c cd /usr/local/bin && chmod", executable );
}
public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/local/'something else'" );
sh.setExecutable( "chmod" );
String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );
assertEquals( "/bin/sh -c cd \"/usr/local/\'something else\'\" && chmod", executable );
}
public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep()
{
Shell sh = newShell();
sh.setWorkingDirectory( "\\usr\\local\\'something else'" );
sh.setExecutable( "chmod" );
String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), " " );
assertEquals( "/bin/sh -c cd \"\\usr\\local\\\'something else\'\" && chmod", executable );
}
public void testPreserveSingleQuotesOnArgument()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/bin" );
sh.setExecutable( "chmod" );
String[] args = { "\'some arg with spaces\'" };
List shellCommandLine = sh.getShellCommandLine( args );
String cli = StringUtils.join( shellCommandLine.iterator(), " " );
System.out.println( cli );
assertTrue( cli.endsWith( args[0] ) );
}
public void testAddSingleQuotesOnArgumentWithSpaces()
{
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/bin" );
sh.setExecutable( "chmod" );
String[] args = { "some arg with spaces" };
List shellCommandLine = sh.getShellCommandLine( args );
String cli = StringUtils.join( shellCommandLine.iterator(), " " );
System.out.println( cli );
assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) );
}
public void testArgumentsWithsemicolon()
{
System.out.println( "
Shell sh = newShell();
sh.setWorkingDirectory( "/usr/bin" );
sh.setExecutable( "chmod" );
String[] args = { ";some&argwithunix$chars" };
List shellCommandLine = sh.getShellCommandLine( args );
String cli = StringUtils.join( shellCommandLine.iterator(), " " );
System.out.println( cli );
assertTrue( cli.endsWith( "\'" + args[0] + "\'" ) );
Commandline commandline = new Commandline(newShell());
commandline.setExecutable( "chmod" );
commandline.getShell().setQuotedArgumentsEnabled( true );
commandline.createArgument().setValue( "--password" );
commandline.createArgument().setValue( ";password");
String[] lines = commandline.getShellCommandline();
System.out.println( Arrays.asList( lines ));
assertEquals( "/bin/sh", lines[0] );
assertEquals( "-c", lines[1] );
assertEquals( "chmod --password ';password'", lines[2] );
commandline = new Commandline(newShell());
commandline.setExecutable( "chmod" );
commandline.getShell().setQuotedArgumentsEnabled( true );
commandline.createArg().setValue( "--password" );
commandline.createArg().setValue( ";password");
lines = commandline.getShellCommandline();
System.out.println( Arrays.asList( lines ));
assertEquals( "/bin/sh", lines[0] );
assertEquals( "-c", lines[1] );
assertEquals( "chmod --password ';password'", lines[2] );
commandline = new Commandline(new CmdShell());
commandline.getShell().setQuotedArgumentsEnabled( true );
commandline.createArgument().setValue( "--password" );
commandline.createArgument().setValue( ";password");
lines = commandline.getShellCommandline();
System.out.println( Arrays.asList( lines ));
assertEquals( "cmd.exe", lines[0] );
assertEquals( "/X", lines[1] );
assertEquals( "/C", lines[2] );
assertEquals( "\"--password ;password\"", lines[3] );
}
}
|
package org.jenkins.plugins.lockableresources;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import hudson.model.Executor;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.BuildWatcher;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.RestartableJenkinsRule;
import org.jvnet.hudson.test.TestBuilder;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import static org.junit.Assert.assertNotNull;
public class LockStepTest {
@Rule
public RestartableJenkinsRule story = new RestartableJenkinsRule();
@ClassRule
public static BuildWatcher buildWatcher = new BuildWatcher();
@Test
public void autoCreateResource() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n" +
" echo 'Resource locked'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
story.j.waitForCompletion(b1);
story.j.assertBuildStatus(Result.SUCCESS, b1);
story.j.assertLogContains("Resource [resource1] did not exist. Created.", b1);
}
});
}
@Test
public void lockWithLabel() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock(label: 'label1') {\n" +
" echo 'Resource locked'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
story.j.waitForCompletion(b1);
story.j.assertBuildStatus(Result.SUCCESS, b1);
story.j.assertLogContains("Lock released on resource [Label: label1]", b1);
}
});
}
@Test
public void lockOrderLabel() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock(label: 'label1', quantity: 2) {\n" +
" semaphore 'wait-inside'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("wait-inside/1", b1);
WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
// Ensure that b2 reaches the lock before b3
story.j.waitForMessage("[Label: label1, Quantity: 2] is locked, waiting...", b2);
story.j.waitForMessage("Found 1 available resource(s). Waiting for correct amount: 2.", b2);
WorkflowRun b3 = p.scheduleBuild2(0).waitForStart();
// Both 2 and 3 are waiting for locking Label: label1, Quantity: 2
story.j.waitForMessage("[Label: label1, Quantity: 2] is locked, waiting...", b3);
story.j.waitForMessage("Found 1 available resource(s). Waiting for correct amount: 2.", b3);
// Unlock Label: label1, Quantity: 2
SemaphoreStep.success("wait-inside/1", null);
story.j.waitForMessage("Lock released on resource [Label: label1, Quantity: 2]", b1);
// #2 gets the lock before #3 (in the order as they requested the lock)
story.j.waitForMessage("Lock acquired on [Label: label1, Quantity: 2]", b2);
SemaphoreStep.success("wait-inside/2", null);
story.j.waitForMessage("Finish", b2);
story.j.waitForMessage("Lock acquired on [Label: label1, Quantity: 2]", b3);
SemaphoreStep.success("wait-inside/3", null);
story.j.waitForMessage("Finish", b3);
}
});
}
@Test
public void lockOrderLabelQuantity() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock(label: 'label1', quantity: 2) {\n" +
" semaphore 'wait-inside'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("wait-inside/1", b1);
WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
// Ensure that b2 reaches the lock before b3
story.j.waitForMessage("[Label: label1, Quantity: 2] is locked, waiting...", b2);
story.j.waitForMessage("Found 1 available resource(s). Waiting for correct amount: 2.", b2);
WorkflowJob p3 = story.j.jenkins.createProject(WorkflowJob.class, "p3");
p3.setDefinition(new CpsFlowDefinition(
"lock(label: 'label1', quantity: 1) {\n" +
" semaphore 'wait-inside-quantity1'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
// While 2 continues waiting, 3 can continue directly
SemaphoreStep.waitForStart("wait-inside-quantity1/1", b3);
// Let 3 finish
SemaphoreStep.success("wait-inside-quantity1/1", null);
story.j.waitForMessage("Finish", b3);
// Unlock Label: label1, Quantity: 2
SemaphoreStep.success("wait-inside/1", null);
story.j.waitForMessage("Lock released on resource [Label: label1, Quantity: 2]", b1);
// #2 gets the lock before #3 (in the order as they requested the lock)
story.j.waitForMessage("Lock acquired on [Label: label1, Quantity: 2]", b2);
SemaphoreStep.success("wait-inside/2", null);
story.j.waitForMessage("Finish", b2);
}
});
}
@Test
public void lockOrder() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n" +
" semaphore 'wait-inside'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("wait-inside/1", b1);
WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
// Ensure that b2 reaches the lock before b3
story.j.waitForMessage("[resource1] is locked, waiting...", b2);
WorkflowRun b3 = p.scheduleBuild2(0).waitForStart();
// Both 2 and 3 are waiting for locking resource1
story.j.waitForMessage("[resource1] is locked, waiting...", b3);
// Unlock resource1
SemaphoreStep.success("wait-inside/1", null);
story.j.waitForMessage("Lock released on resource [resource1]", b1);
// #2 gets the lock before #3 (in the order as they requested the lock)
story.j.waitForMessage("Lock acquired on [resource1]", b2);
SemaphoreStep.success("wait-inside/2", null);
story.j.waitForMessage("Lock acquired on [resource1]", b3);
SemaphoreStep.success("wait-inside/3", null);
story.j.waitForMessage("Finish", b3);
}
});
}
@Test
public void lockInverseOrder() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock(resource: 'resource1', inversePrecedence: true) {\n" +
" semaphore 'wait-inside'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("wait-inside/1", b1);
WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
// Ensure that b2 reaches the lock before b3
story.j.waitForMessage("[resource1] is locked, waiting...", b2);
WorkflowRun b3 = p.scheduleBuild2(0).waitForStart();
// Both 2 and 3 are waiting for locking resource1
story.j.waitForMessage("[resource1] is locked, waiting...", b3);
// Unlock resource1
SemaphoreStep.success("wait-inside/1", null);
story.j.waitForMessage("Lock released on resource [resource1]", b1);
// #3 gets the lock before #2 because of inversePrecedence
story.j.waitForMessage("Lock acquired on [resource1]", b3);
SemaphoreStep.success("wait-inside/2", null);
story.j.waitForMessage("Lock acquired on [resource1]", b2);
SemaphoreStep.success("wait-inside/3", null);
story.j.waitForMessage("Finish", b3);
}
});
}
@Test
public void parallelLock() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"parallel a: {\n" +
" sleep 5\n" +
" lock('resource1') {\n" +
" sleep 5\n" +
" }\n" +
"}, b: {\n" +
" lock('resource1') {\n" +
" semaphore 'wait-b'\n" +
" }\n" +
"}\n"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("wait-b/1", b1);
// both messages are in the log because branch b acquired the lock and branch a is waiting to lock
story.j.waitForMessage("[b] Lock acquired on [resource1]", b1);
story.j.waitForMessage("[a] [resource1] is locked, waiting...", b1);
SemaphoreStep.success("wait-b/1", null);
story.j.waitForMessage("[a] Lock acquired on [resource1]", b1);
}
});
}
@Test
public void lockOrderRestart() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n" +
" semaphore 'wait-inside'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("wait-inside/1", b1);
WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
// Ensure that b2 reaches the lock before b3
story.j.waitForMessage("[resource1] is locked, waiting...", b2);
WorkflowRun b3 = p.scheduleBuild2(0).waitForStart();
// Both 2 and 3 are waiting for locking resource1
story.j.waitForMessage("[resource1] is locked, waiting...", b3);
}
});
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
WorkflowJob p = story.j.jenkins.getItemByFullName("p", WorkflowJob.class);
WorkflowRun b1 = p.getBuildByNumber(1);
WorkflowRun b2 = p.getBuildByNumber(2);
WorkflowRun b3 = p.getBuildByNumber(3);
// Unlock resource1
SemaphoreStep.success("wait-inside/1", null);
story.j.waitForMessage("Lock released on resource [resource1]", b1);
story.j.waitForMessage("Lock acquired on [resource1]", b2);
story.j.assertLogContains("[resource1] is locked, waiting...", b3);
SemaphoreStep.success("wait-inside/2", null);
SemaphoreStep.waitForStart("wait-inside/3", b3);
story.j.assertLogContains("Lock acquired on [resource1]", b3);
SemaphoreStep.success("wait-inside/3", null);
story.j.waitForMessage("Finish", b3);
}
});
}
@Test
public void interoperability() {
final Semaphore semaphore = new Semaphore(1);
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n" +
" echo 'Locked'\n" +
"}\n" +
"echo 'Finish'"
));
FreeStyleProject f = story.j.createFreeStyleProject("f");
f.addProperty(new RequiredResourcesProperty("resource1", null, null, null));
f.getBuildersList().add(new TestBuilder() {
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
semaphore.acquire();
return true;
}
});
semaphore.acquire();
f.scheduleBuild2(0).waitForStart();
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
story.j.waitForMessage("[resource1] is locked, waiting...", b1);
semaphore.release();
// Wait for lock after the freestyle finishes
story.j.waitForMessage("Lock released on resource [resource1]", b1);
}
});
}
@Test
public void interoperabilityOnRestart() {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n" +
" semaphore 'wait-inside'\n" +
"}\n" +
"echo 'Finish'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("wait-inside/1", b1);
FreeStyleProject f = story.j.createFreeStyleProject("f");
f.addProperty(new RequiredResourcesProperty("resource1", null, null, null));
f.scheduleBuild2(0);
while(story.j.jenkins.getQueue().getItems().length != 1) {
System.out.println("Waiting for freestyle to be queued...");
Thread.sleep(1000);
}
}
});
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
WorkflowJob p = story.j.jenkins.getItemByFullName("p", WorkflowJob.class);
FreeStyleProject f = story.j.jenkins.getItemByFullName("f", FreeStyleProject.class);
WorkflowRun b1 = p.getBuildByNumber(1);
// Unlock resource1
SemaphoreStep.success("wait-inside/1", null);
story.j.waitForMessage("Lock released on resource [resource1]", b1);
FreeStyleBuild fb1 = null;
while((fb1 = f.getBuildByNumber(1)) == null) {
System.out.println("Waiting for freestyle #1 to start building...");
Thread.sleep(1000);
}
story.j.waitForMessage("acquired lock on [resource1]", fb1);
}
});
}
@Issue("JENKINS-36479")
@Test public void hardKillNewBuildClearsLock() throws Exception {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p1 = story.j.jenkins.createProject(WorkflowJob.class, "p");
p1.setDefinition(new CpsFlowDefinition("lock('resource1') { echo 'locked!'; semaphore 'wait-inside' }"));
WorkflowRun b1 = p1.scheduleBuild2(0).waitForStart();
story.j.waitForMessage("locked!", b1);
SemaphoreStep.waitForStart("wait-inside/1", b1);
WorkflowJob p2 = story.j.jenkins.createProject(WorkflowJob.class, "p2");
p2.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n"
+ " semaphore 'wait-inside'\n"
+ "}"));
WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
// Make sure that b2 is blocked on b1's lock.
story.j.waitForMessage("[resource1] is locked, waiting...", b2);
// Now b2 is still sitting waiting for a lock. Create b3 and launch it to clear the lock.
WorkflowJob p3 = story.j.jenkins.createProject(WorkflowJob.class, "p3");
p3.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n"
+ " semaphore 'wait-inside'\n"
+ "}"));
WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
story.j.waitForMessage("[resource1] is locked, waiting...", b3);
// Kill b1 hard.
b1.doKill();
story.j.waitForMessage("Hard kill!", b1);
story.j.waitForCompletion(b1);
story.j.assertBuildStatus(Result.ABORTED, b1);
// Verify that b2 gets the lock.
story.j.waitForMessage("Lock acquired on [resource1]", b2);
SemaphoreStep.success("wait-inside/2", b2);
// Verify that b2 releases the lock and finishes successfully.
story.j.waitForMessage("Lock released on resource [resource1]", b2);
story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b2));
// Now b3 should get the lock and do its thing.
story.j.waitForMessage("Lock acquired on [resource1]", b3);
SemaphoreStep.success("wait-inside/3", b3);
story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b3));
}
});
}
// TODO: Figure out what to do about the IOException thrown during clean up, since we don't care about it. It's just
// a result of the first build being deleted and is nothing but noise here.
@Issue("JENKINS-36479")
@Test public void deleteRunningBuildNewBuildClearsLock() throws Exception {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p1 = story.j.jenkins.createProject(WorkflowJob.class, "p");
p1.setDefinition(new CpsFlowDefinition("lock('resource1') { echo 'locked!'; semaphore 'wait-inside' }"));
WorkflowRun b1 = p1.scheduleBuild2(0).waitForStart();
story.j.waitForMessage("locked!", b1);
SemaphoreStep.waitForStart("wait-inside/1", b1);
WorkflowJob p2 = story.j.jenkins.createProject(WorkflowJob.class, "p2");
p2.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n"
+ " semaphore 'wait-inside'\n"
+ "}"));
WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
// Now b2 is still sitting waiting for a lock. Create b3 and launch it to clear the lock.
WorkflowJob p3 = story.j.jenkins.createProject(WorkflowJob.class, "p3");
p3.setDefinition(new CpsFlowDefinition(
"lock('resource1') {\n"
+ " semaphore 'wait-inside'\n"
+ "}"));
WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
// Make sure that b2 is blocked on b1's lock.
story.j.waitForMessage("[resource1] is locked, waiting...", b2);
story.j.waitForMessage("[resource1] is locked, waiting...", b3);
b1.delete();
// Verify that b2 gets the lock.
story.j.waitForMessage("Lock acquired on [resource1]", b2);
SemaphoreStep.success("wait-inside/2", b2);
// Verify that b2 releases the lock and finishes successfully.
story.j.waitForMessage("Lock released on resource [resource1]", b2);
story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b2));
// Now b3 should get the lock and do its thing.
story.j.waitForMessage("Lock acquired on [resource1]", b3);
SemaphoreStep.success("wait-inside/3", b3);
story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b3));
}
});
}
@Issue("JENKINS-40368")
@Test
public void hardKillWithWaitingRuns() throws Exception {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition("retry(99) {\n" +
" lock('resource1') {\n" +
" semaphore('wait-inside')\n" +
" }\n" +
"}", true));
WorkflowRun prevBuild = null;
for (int i = 0; i < 3; i++) {
WorkflowRun rNext = p.scheduleBuild2(0).waitForStart();
if (prevBuild != null) {
story.j.waitForMessage("[resource1] is locked, waiting...", rNext);
Executor ex = prevBuild.getExecutor();
assertNotNull(ex);
ex.interrupt();
story.j.waitForMessage("Click here to forcibly terminate running steps", prevBuild);
prevBuild.doTerm();
story.j.waitForMessage("Click here to forcibly kill entire build", prevBuild);
prevBuild.doKill();
story.j.waitForMessage("Hard kill!", prevBuild);
story.j.waitForCompletion(prevBuild);
story.j.assertBuildStatus(Result.ABORTED, prevBuild);
}
story.j.waitForMessage("Lock acquired on [resource1]", rNext);
SemaphoreStep.waitForStart("wait-inside/" + (i + 1), rNext);
prevBuild = rNext;
}
SemaphoreStep.success("wait-inside/3", null);
story.j.assertBuildStatus(Result.SUCCESS, story.j.waitForCompletion(prevBuild));
}
});
}
@Issue("JENKINS-40879")
@Test
public void parallelLockRelease() throws Exception {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
LockableResourcesManager.get().createResource("resource1");
LockableResourcesManager.get().createResource("resource2");
WorkflowJob j = story.j.jenkins.createProject(WorkflowJob.class, "j");
j.setDefinition(new CpsFlowDefinition(
"lock(resource: 'resource1') {\n" +
" semaphore 'wait-inside-1'\n" +
"}\n" +
"lock(resource: 'resource2') { \n" +
" echo 'Entering semaphore now'\n" +
" semaphore 'wait-inside-2'\n" +
"}\n",
true));
List<WorkflowRun> nextRuns = new ArrayList<>();
WorkflowRun toUnlock = null;
for (int i = 0; i < 5; i++) {
WorkflowRun rNext = j.scheduleBuild2(0).waitForStart();
if (toUnlock != null) {
story.j.waitForMessage("[resource1] is locked, waiting...", rNext);
SemaphoreStep.success("wait-inside-1/" + i, toUnlock);
}
SemaphoreStep.waitForStart("wait-inside-1/" + (i + 1), rNext);
nextRuns.add(rNext);
toUnlock = rNext;
}
SemaphoreStep.success("wait-inside-1/" + nextRuns.size(), toUnlock);
waitAndClear(1, nextRuns);
}
});
}
private void waitAndClear(int semaphoreIndex, List<WorkflowRun> nextRuns) throws Exception {
WorkflowRun toClear = nextRuns.get(0);
System.err.println("Waiting for semaphore to start for " + toClear.getNumber());
SemaphoreStep.waitForStart("wait-inside-2/" + semaphoreIndex, toClear);
List<WorkflowRun> remainingRuns = new ArrayList<>();
if (nextRuns.size() > 1) {
remainingRuns.addAll(nextRuns.subList(1, nextRuns.size()));
for (WorkflowRun r : remainingRuns) {
System.err.println("Verifying no semaphore yet for " + r.getNumber());
story.j.assertLogNotContains("Entering semaphore now", r);
}
}
SemaphoreStep.success("wait-inside-2/" + semaphoreIndex, toClear);
System.err.println("Waiting for " + toClear.getNumber() + " to complete");
story.j.assertBuildStatusSuccess(story.j.waitForCompletion(toClear));
if (!remainingRuns.isEmpty()) {
waitAndClear(semaphoreIndex + 1, remainingRuns);
}
}
}
|
package hudson.model;
/**
* A model object has a human readable name.
*
* And it normally has URL, but this interface doesn't define one.
* (Since there's so many classes that define the <tt>getUrl</tt> method
* we should have such one.)
*
* @author Kohsuke Kawaguchi
*/
public interface ModelObject {
String getDisplayName();
}
|
package to.etc.domui.component2.form4;
import to.etc.domui.component.meta.*;
import to.etc.domui.component2.controlfactory.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.server.*;
import to.etc.webapp.annotations.*;
import javax.annotation.*;
final public class FormBuilder {
interface IAppender {
void add(@Nonnull NodeBase formNode);
}
@Nonnull
final private IAppender m_appender;
private boolean m_horizontal;
private boolean m_currentDirection;
private String m_nextLabel;
private String m_errorLocation;
private Label m_nextLabelControl;
private PropertyMetaModel< ? > m_propertyMetaModel;
private Object m_instance;
private Boolean m_mandatory;
private boolean m_append;
private Boolean m_readOnly;
private NodeBase m_lastAddedControl;
@Nullable
private String m_controlCss;
@Nullable
private String m_labelCss;
public FormBuilder(@Nonnull IAppender appender) {
m_appender = appender;
}
public FormBuilder(@Nonnull final NodeContainer nb) {
this(nb::add);
}
@Nonnull
public FormBuilder append() {
m_append = true;
return this;
}
@Nonnull
public FormBuilder horizontal() {
m_horizontal = true;
return this;
}
@Nonnull
public FormBuilder vertical() {
m_horizontal = false;
return this;
}
/* CODING: Label control. */
/**
*
* @param label
* @return
*/
@Nonnull
public FormBuilder label(@Nonnull String label) {
if(null != m_nextLabelControl)
throw new IllegalStateException("You already set a Label instance");
m_nextLabel = label;
return this;
}
@Nonnull
public FormBuilder label(@Nonnull Label label) {
if(null != m_nextLabel)
throw new IllegalStateException("You already set a String label instance");
m_nextLabelControl = label;
return this;
}
@Nonnull
public FormBuilder errorLocation(@Nonnull String errorLocation) {
m_errorLocation = errorLocation;
return this;
}
@Nonnull
public FormBuilder unlabeled() {
label("");
return this;
}
/* CODING: Readonly, mandatory, disabled. */
/**
*
* @return
*/
@Nonnull
public FormBuilder readOnly() {
m_readOnly = Boolean.TRUE;
return this;
}
@Nonnull
public FormBuilder readOnly(boolean ro) {
m_readOnly = Boolean.valueOf(ro);
return this;
}
@Nonnull
public FormBuilder mandatory() {
m_mandatory = Boolean.TRUE;
return this;
}
@Nonnull
public FormBuilder mandatory(boolean yes) {
m_mandatory = Boolean.valueOf(yes);
return this;
}
/* CODING: defining (manually created) controls. */
/**
* Add the specified control. Since the control is manually created this code assumes that the
* control is <b>properly configured</b> for it's task! This means that this code will not
* make any changes to the control! Specifically: if the form item is marked as "mandatory"
* but the control here is not then the control stays optional.
* The reverse however is not true: if the control passed in is marked as mandatory then the
* form item will be marked as such too.
*
* @param control
* @throws Exception
*/
public void control(@Nonnull IControl< ? > control) throws Exception {
if(control.isMandatory()) {
m_mandatory = Boolean.TRUE;
}
addControl((NodeBase) control);
resetBuilder();
}
@Nonnull
public IControl< ? > control() throws Exception {
return control((Class< ? extends IControl< ? >>) null);
}
@Nonnull
public <T, C extends IControl<T>> C control(@Nullable Class<C> controlClass) throws Exception {
ControlCreatorRegistry builder = DomApplication.get().getControlCreatorRegistry();
PropertyMetaModel<T> pmm = (PropertyMetaModel<T>) m_propertyMetaModel;
if(null == pmm)
throw new IllegalStateException("You must have called 'property(...)' before");
C control = builder.createControl(pmm, controlClass);
bindControlData(control, pmm);
addControl((NodeBase) control);
resetBuilder();
return control;
}
/**
* Adds the specified css class to the control cell.
* @param cssClass
* @return
*/
@Nonnull
public FormBuilder cssControl(@Nonnull String cssClass) {
m_controlCss = cssClass;
return this;
}
/**
* Adds the specified css class to the label cell.
* @param cssClass
* @return
*/
@Nonnull
public FormBuilder cssLabel(@Nonnull String cssClass) {
m_labelCss = cssClass;
return this;
}
public void item(@Nonnull NodeBase item) throws Exception {
addControl(item);
resetBuilder();
}
public <T, C extends IControl<T>> void bindControlData(@Nonnull C control, @Nonnull PropertyMetaModel<T> pmm) throws Exception {
}
@Nonnull
public <T> FormBuilder property(@Nonnull T instance, @GProperty String property) {
if(null != m_propertyMetaModel)
throw new IllegalStateException("You need to end the builder pattern with a call to 'control()'");
m_propertyMetaModel = MetaManager.getPropertyMeta(instance.getClass(), property);
m_instance = instance;
return this;
}
private void resetBuilder() {
m_readOnly = null;
m_instance = null;
m_propertyMetaModel = null;
m_append = false;
m_mandatory = null;
m_nextLabel = null;
m_nextLabelControl = null;
m_controlCss = null;
m_labelCss = null;
m_errorLocation = null;
}
/* CODING: Form building code. */
private Table m_table;
private TBody m_body;
private TR m_labelRow;
private TR m_controlRow;
private void addControl(@Nonnull NodeBase control) throws Exception {
if (control.getClass().getSimpleName().contains("TextArea")
&& m_labelCss == null) {
m_labelCss = "ui-f4-ta";
}
resetDirection();
if(m_horizontal)
addHorizontal(control);
else
addVertical(control);
if(control instanceof IControl) {
IControl< ? > ctl = (IControl< ? >) control;
PropertyMetaModel< ? > pmm = m_propertyMetaModel;
if(null != pmm) {
Object instance = m_instance;
if(null != instance) {
ctl.bind().to(instance, pmm);
}
}
if(isReadOnly()) {
ctl.setReadOnly(true);
}
if(isMandatory()) {
ctl.setMandatory(true);
}
}
m_lastAddedControl = control;
if (null != m_errorLocation){
control.setErrorLocation(m_errorLocation);
}else {
String label = labelTextCalculated();
if(null != label) {
control.setErrorLocation(label);
}
}
}
private void resetDirection() {
if(m_horizontal == m_currentDirection)
return;
clearTable();
m_currentDirection = m_horizontal;
}
public FormBuilder nl() {
clearTable();
return this;
}
private void clearTable() {
m_table = null;
m_body = null;
m_labelRow = null;
m_controlRow = null;
}
@Nonnull
public TBody body() {
if(m_body == null) {
Table tbl = m_table = new Table();
m_appender.add(tbl);
tbl.setCssClass(m_horizontal ? "ui-f4 ui-f4-h" : "ui-f4 ui-f4-v");
tbl.setCellPadding("0");
tbl.setCellSpacing("0");
TBody b = m_body = new TBody();
tbl.add(b);
return b;
}
return m_body;
}
private void addVertical(NodeBase control) {
TBody b = body();
Label lbl = determineLabel();
if(m_append) {
TD cell = b.cell();
if(lbl != null) {
lbl.addCssClass("ui-f4-lbl");
lbl.setMarginLeft("10px");
lbl.setMarginRight("3px");
cell.add(lbl);
}
cell.add(control);
final String controlCss = m_controlCss;
if(null != controlCss)
cell.addCssClass(controlCss);
} else {
TD labelcell = b.addRowAndCell();
labelcell.setCssClass("ui-f4-lbl ui-f4-lbl-v");
if(null != lbl)
labelcell.add(lbl);
String labelCss = m_labelCss;
if(labelCss != null)
labelcell.addCssClass(labelCss);
TD controlcell = b.addCell();
controlcell.setCssClass("ui-f4-ctl ui-f4-ctl-v");
controlcell.add(control);
final String controlCss = m_controlCss;
if(null != controlCss)
controlcell.addCssClass(controlCss);
}
if(null != lbl)
lbl.setForNode(control);
}
@Nonnull
private TR controlRow() {
TR row = m_controlRow;
if(null == row) {
labelRow();
row = m_controlRow = body().addRow();
}
return row;
}
@Nonnull
private TR labelRow() {
TR row = m_labelRow;
if(null == row) {
row = m_labelRow = body().addRow();
}
return row;
}
private void addHorizontal(NodeBase control) {
TBody b = body();
Label lbl = determineLabel();
if(m_append) {
TR row = controlRow();
TD cell;
if(row.getChildCount() == 0) {
cell = row.addCell();
cell.setCssClass("ui-f4-ctl ui-f4-ctl-h");
} else {
cell = (TD) row.getChild(row.getChildCount() - 1);
}
cell.add(control);
final String controlCss = m_controlCss;
if(null != controlCss)
cell.addCssClass(controlCss);
} else {
TD labelcell = labelRow().addCell();
labelcell.setCssClass("ui-f4-lbl ui-f4-lbl-h");
if(null != lbl)
labelcell.add(lbl);
String labelCss = m_labelCss;
if(labelCss != null)
labelcell.addCssClass(labelCss);
TD controlcell = controlRow().addCell();
controlcell.setCssClass("ui-f4-ctl ui-f4-ctl-h");
controlcell.add(control);
final String controlCss = m_controlCss;
if(null != controlCss)
controlcell.addCssClass(controlCss);
}
if(null != lbl)
lbl.setForNode(control);
}
public void appendAfterControl(@Nonnull NodeBase what) {
getLastControlCell().add(what);
}
@Nonnull
public NodeContainer getLastControlCell() {
if (m_lastAddedControl == null) {
throw new IllegalStateException("No controls were added yet.");
}
return m_lastAddedControl.getParent(TD.class);
}
/**
*
* @return
*/
@Nullable
private Label determineLabel() {
Label res = null;
String txt = m_nextLabel;
if(null != txt) {
//m_nextLabel = null;
if(txt.length() != 0) // Not "unlabeled"?
res = new Label(txt);
} else {
res = m_nextLabelControl;
if(res == null) {
//-- Property known?
PropertyMetaModel< ? > pmm = m_propertyMetaModel;
if(null != pmm) {
txt = pmm.getDefaultLabel();
if(txt != null && txt.length() > 0)
res = new Label(txt);
}
}
}
if(res != null && calculateMandatory() && !isReadOnly()) {
res.addCssClass("ui-f4-mandatory");
}
return res;
}
@Nullable
private String labelTextCalculated() {
String txt = m_nextLabel;
if(null != txt) {
if(txt.length() != 0) // Not "unlabeled"?
return txt;
return null;
} else {
Label res = m_nextLabelControl;
if(res != null) {
return res.getTextContents();
} else {
//-- Property known?
PropertyMetaModel< ? > pmm = m_propertyMetaModel;
if(null != pmm) {
txt = pmm.getDefaultLabel();
if(txt != null && txt.length() > 0)
return txt;
}
}
}
return null;
}
private boolean isReadOnly() {
Boolean ro = m_readOnly;
if(null != ro) {
return ro.booleanValue();
}
return false;
}
private boolean isMandatory() {
Boolean man = m_mandatory;
if(null != man) {
return man.booleanValue();
}
return false;
}
private boolean calculateMandatory() {
Boolean m = m_mandatory;
if(null != m)
return m.booleanValue(); // If explicitly set: obey that
PropertyMetaModel<?> pmm = m_propertyMetaModel;
if(null != pmm) {
return pmm.isRequired();
}
return false;
}
}
|
package org.sagebionetworks.web.client;
import static org.junit.Assert.assertEquals;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.junit.Test;
import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.repo.model.FileEntity;
import org.sagebionetworks.repo.model.Folder;
import org.sagebionetworks.repo.model.Link;
import org.sagebionetworks.repo.model.Project;
import org.sagebionetworks.repo.model.table.Dataset;
import org.sagebionetworks.repo.model.table.EntityView;
import org.sagebionetworks.repo.model.table.SubmissionView;
import org.sagebionetworks.repo.model.table.TableEntity;
public class EntityTypeUtilsTest {
@Test
public void testGetEntityClassNameForEntityType() {
assertEquals(FileEntity.class.getName(), EntityTypeUtils.getEntityClassNameForEntityType(EntityType.file.name()));
assertEquals(Folder.class.getName(), EntityTypeUtils.getEntityClassNameForEntityType(EntityType.folder.name()));
assertEquals(Project.class.getName(), EntityTypeUtils.getEntityClassNameForEntityType(EntityType.project.name()));
assertEquals(TableEntity.class.getName(), EntityTypeUtils.getEntityClassNameForEntityType(EntityType.table.name()));
assertEquals(EntityView.class.getName(), EntityTypeUtils.getEntityClassNameForEntityType(EntityType.entityview.name()));
assertEquals(Link.class.getName(), EntityTypeUtils.getEntityClassNameForEntityType(EntityType.link.name()));
assertEquals(FileEntity.class.getName(), EntityTypeUtils.getEntityClassNameForEntityType("default"));
}
@Test
public void testGetEntityTypeForEntityClassName() {
assertEquals(EntityType.file, EntityTypeUtils.getEntityTypeForEntityClassName(FileEntity.class.getName()));
assertEquals(EntityType.folder, EntityTypeUtils.getEntityTypeForEntityClassName(Folder.class.getName()));
assertEquals(EntityType.project, EntityTypeUtils.getEntityTypeForEntityClassName(Project.class.getName()));
assertEquals(EntityType.table, EntityTypeUtils.getEntityTypeForEntityClassName(TableEntity.class.getName()));
assertEquals(EntityType.entityview, EntityTypeUtils.getEntityTypeForEntityClassName(EntityView.class.getName()));
assertEquals(EntityType.link, EntityTypeUtils.getEntityTypeForEntityClassName(Link.class.getName()));
assertEquals(EntityType.file, EntityTypeUtils.getEntityTypeForEntityClassName("default"));
}
@Test
public void testGetIconTypeForEntityClassName() {
assertEquals(IconType.FILE, EntityTypeUtils.getIconTypeForEntityClassName(FileEntity.class.getName()));
assertEquals(IconType.FOLDER, EntityTypeUtils.getIconTypeForEntityClassName(Folder.class.getName()));
assertEquals(IconType.LIST_ALT, EntityTypeUtils.getIconTypeForEntityClassName(Project.class.getName()));
assertEquals(IconType.TABLE, EntityTypeUtils.getIconTypeForEntityClassName(TableEntity.class.getName()));
assertEquals(IconType.TH_LIST, EntityTypeUtils.getIconTypeForEntityClassName(EntityView.class.getName()));
assertEquals(IconType.LINK, EntityTypeUtils.getIconTypeForEntityClassName(Link.class.getName()));
assertEquals(IconType.FILE, EntityTypeUtils.getIconTypeForEntityClassName("default"));
}
@Test
public void testGetFriendlyTableTypeName() {
assertEquals(EntityTypeUtils.TABLE_ENTITY_DISPLAY_NAME, EntityTypeUtils.getFriendlyTableTypeName(TableEntity.class.getName()));
assertEquals(EntityTypeUtils.ENTITY_VIEW_DISPLAY_NAME, EntityTypeUtils.getFriendlyTableTypeName(EntityView.class.getName()));
assertEquals(EntityTypeUtils.SUBMISSION_VIEW_DISPLAY_NAME, EntityTypeUtils.getFriendlyTableTypeName(SubmissionView.class.getName()));
assertEquals(EntityTypeUtils.DATASET_DISPLAY_NAME, EntityTypeUtils.getFriendlyTableTypeName(Dataset.class.getName()));
assertEquals(EntityTypeUtils.UNKNOWN_TABLE_TYPE, EntityTypeUtils.getFriendlyTableTypeName("coffee table"));
}
}
|
package org.semanticrecord.talaan;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import uk.org.lidalia.slf4jext.Level;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
public class SemanticLoggerConfigTest {
TestLogger testLogger = TestLoggerFactory.getTestLogger(SampleLoggerInterface.class);
@BeforeClass
public static void initClass() {
TestLoggerFactory.getInstance().setPrintLevel(Level.DEBUG);
}
@After
public void setup() {
SemanticLoggerConfig.reset();
}
@Test
public void getInstanceNoFile() {
SemanticLoggerConfig config = SemanticLoggerConfig.getInstance();
assertThat(config.isLoadedFromFile()).isFalse();
}
@Test
public void getInstanceIsSingleton() {
SemanticLoggerConfig config = SemanticLoggerConfig.getInstance();
SemanticLoggerConfig config2 = SemanticLoggerConfig.getInstance();
assertThat(config).isSameAs(config2);
}
@Test
public void getInstanceWithFile() {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
PrintWriter pWriter = new PrintWriter(bao);
String expectedValue = "value";
for(String key : SemanticLoggerConfig.getPropertyKeys()) {
pWriter.format("%s=%s\n", key, expectedValue);
}
pWriter.flush();
pWriter.close();
ClassLoader contextCl = Thread.currentThread().getContextClassLoader();
try {
ClassLoader cl = new ClassLoader(contextCl) {
@Override
public InputStream getResourceAsStream(String name) {
if(name.equals(SemanticLoggerConfig.PROPERTIES_FILE)) {
return new ByteArrayInputStream(bao.toByteArray());
}
return super.getResourceAsStream(name);
}
};
Thread.currentThread().setContextClassLoader(cl);
SemanticLoggerConfig config = SemanticLoggerConfig.getInstance();
assertThat(config.isLoadedFromFile()).isTrue();
assertThat(config.getCode()).isEqualTo(expectedValue);
assertThat(config.getEvent()).isEqualTo(expectedValue);
assertThat(config.getPairFormat()).isEqualTo(expectedValue);
assertThat(config.getPlaceholder()).isEqualTo(expectedValue);
assertThat(config.getSeparator()).isEqualTo(expectedValue);
} finally {
Thread.currentThread().setContextClassLoader(contextCl);
}
}
}
|
package serverLogic;
import java.util.LinkedList;
import java.util.List;
import java.util.HashMap;
import java.util.Scanner;
import people.*;
import time.*;
import attendance.*;
public class Parser {
private static final String absentPrependPerformance = "absentStudentPerformance";
private static final String absentPrependRehearsal = "absentStudentRehearsal";
private static final String rehearsalPrepend = "storedRehearsal";
private static final String performancePrepend = "storedPerformance";
private static final String tardyPrepend = "tardyStudent";
private static final String studentPrepend = "studentRecord";
//Remember the people absent and if they were tardy then just remove the absence.
public static void splat(String add) {
// Splats the massive string into an array of strings for each person
String[] people = add.split(",");
HashMap<User, Absence> absences = new HashMap<User, Absence>();
HashMap<User, Tardy> tardies = new HashMap<User, Tardy>();
List<Event> events = new LinkedList<Event>();
//Puts everything into HashMaps!
for (String e : people) {
// The person splat is in the form
// prepend, firstName, lastName, netID, date, startTime, endTime,
// rank
String[] personalInfo = e.split(" ");
String prepend = personalInfo[0];
if (prepend.equalsIgnoreCase(studentPrepend))
continue;
else if (prepend.equalsIgnoreCase(rehearsalPrepend) || prepend.equalsIgnoreCase(performancePrepend))
{
//Store the Event
String date = personalInfo[4];
String startTime = personalInfo[5];
String endTime = personalInfo[6];
Date useDate = parseDate(date);
Time start = parseTime(startTime, useDate);
Time end = parseTime(endTime, useDate);
Event newEvent = new Event(start, end, prepend.substring(0, 6));
DatabaseUtil.addEvent(newEvent);
}
else if (prepend.equalsIgnoreCase(absentPrependPerformance) || prepend.equalsIgnoreCase(absentPrependRehearsal)
|| prepend.equalsIgnoreCase(tardyPrepend))
{
String netID = personalInfo[3];
String date = personalInfo[4];
String startTime = personalInfo[5];
String endTime = personalInfo[6];
User person = DatabaseUtil.getUser(netID);
Date useDate = parseDate(date);
Time start = parseTime(startTime, useDate);
Time end = parseTime(endTime, useDate);
updateMaps(person, prepend, useDate, start, end, absences, tardies);
}
}
//TODO add all the stuff in the hashmaps
updateALLTheThings(absences, tardies, events);
}
private static Date parseDate(String date) {
// Dates in the form year-month-day
Scanner parser = new Scanner(date).useDelimiter("-");
return new Date(Integer.parseInt(parser.next()),
Integer.parseInt(parser.next()),
Integer.parseInt(parser.next()));
}
private static Time parseTime(String time, Date date) {
if (time.length() >= 4)
{
int hour = Integer.parseInt(time.substring(0, 2));
int minute = Integer.parseInt(time.substring(2, 4));
return new Time(hour, minute, date);
}
else //Return an empty date. This should only happen for Tardy endtimes cause it's just a |
return new Time(0,0, date);
}
private static void updateMaps(User guy, String prepend, Date eventDate, Time start, Time end, HashMap<User, Absence> absences, HashMap<User, Tardy> tardies) {
if ( guy!= null && (guy.getType().equalsIgnoreCase("Student")))
{
if (prepend.equalsIgnoreCase(absentPrependPerformance))
{
//guy.addAbsence(new Absence(start, end, "Performance"));
absences.put(guy, new Absence(guy.getNetID(), start, end, "Performance"));
} else if (prepend.equalsIgnoreCase(absentPrependRehearsal))
{
//guy.addAbsence(new Absence(start, end, "Rehearsal"));
absences.put(guy, new Absence(guy.getNetID(), start, end, "Rehearsal"));
}
else if (prepend.equalsIgnoreCase(tardyPrepend))
{
//guy.addTardy(new Tardy(start, "unknown"));
tardies.put(guy, new Tardy(guy.getNetID(), start, "unknown"));
}
}
}
private static void updateALLTheThings(HashMap<User, Absence> absences, HashMap<User, Tardy> tardies, List<Event> events)
{
//If they are in the TardyMap then take them out of the AbsentMap
//Update the tardies to what type of event they are: rehearsal, performance
for (User u: tardies.keySet())
{
if (absences.containsKey(u))
{
absences.remove(u);
}
for (int i = 0; i < events.size(); i++)
{
Event e = events.get(i);
if (e.getStartTime().compareTo(tardies.get(u).getTime()) <= 0
&& e.getEndTime().compareTo(tardies.get(u).getTime()) >= 0)
{
tardies.get(u).setType(e.getType());
}
}
}
for (User u: absences.keySet())
{
DatabaseUtil.addAbsence(absences.get(u));
}
for (User u: tardies.keySet())
{
DatabaseUtil.addTardy(tardies.get(u));
}
}
}
|
package xal.smf.proxy;
import java.util.*;
import xal.smf.AcceleratorNode;
import xal.ca.Channel;
/**
* Access property values for a node
* @author Tom Pelaia
*/
abstract public class AbstractPropertyAccessor implements PropertyAccessor {
/** Get the scale factor for the specified property */
protected double getPropertyScale( final String propertyName ) {
return 1.0;
}
/** get the map of design values keyed by property name */
protected Map<String,Double> getDesignValueMap( final AcceleratorNode node, final List<String> propertyNames ) {
final Map<String,Double> valueMap = new HashMap<String,Double>();
for( final String propertyName : propertyNames ) {
final double scale = getPropertyScale( propertyName );
final double value = scale * node.getDesignPropertyValue( propertyName );
valueMap.put( propertyName, value );
}
return valueMap;
}
/** get the map of live values keyed by property name */
protected Map<String,Double> getLiveValueMap( final AcceleratorNode node, final Map<Channel,Double> channelValues, final List<String> propertyNames ) {
final Map<String,Double> valueMap = new HashMap<String,Double>();
for( final String propertyName : propertyNames ) {
final Channel[] propertyChannels = node.getLivePropertyChannels( propertyName );
final double[] propertyChannelValues = new double[propertyChannels.length];
for ( int index = 0 ; index < propertyChannels.length ; index++ ) {
final Channel channel = propertyChannels[index];
propertyChannelValues[index] = channelValues.get( channel );
}
final double scale = getPropertyScale( propertyName );
final double propertyValue = scale * node.getLivePropertyValue( propertyName, propertyChannelValues );
valueMap.put( propertyName, propertyValue );
}
return valueMap;
}
/** get the channels for live property access */
protected Collection<Channel> getLiveChannels( final AcceleratorNode node, final List<String> propertyNames ) {
final Set<Channel> channels = new HashSet<Channel>();
for( final String propertyName : propertyNames ) {
final Channel[] propertyChannels = node.getLivePropertyChannels( propertyName );
for ( final Channel channel : propertyChannels ) {
channels.add( channel );
}
}
return channels;
}
}
|
package org.unipop.process.start;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.unipop.util.ConversionUtils;
import org.unipop.process.predicate.ReceivesPredicatesHolder;
import org.unipop.process.properties.PropertyFetcher;
import org.unipop.query.StepDescriptor;
import org.unipop.query.controller.ControllerManager;
import org.unipop.query.predicates.PredicatesHolder;
import org.unipop.query.predicates.PredicatesHolderFactory;
import org.unipop.query.search.SearchQuery;
import org.unipop.structure.UniGraph;
import java.util.*;
import java.util.stream.Stream;
public class UniGraphStartStep<S,E extends Element> extends GraphStep<S,E> implements ReceivesPredicatesHolder<S, E>, PropertyFetcher{
private final StepDescriptor stepDescriptor;
List<SearchQuery.SearchController> controllers;
private PredicatesHolder predicates = PredicatesHolderFactory.empty();
private Set<String> propertyKeys;
private int limit;
public UniGraphStartStep(GraphStep<S, E> originalStep, ControllerManager controllerManager) {
super(originalStep.getTraversal(), originalStep.getReturnClass(), originalStep.isStartStep(), originalStep.getIds());
originalStep.getLabels().forEach(this::addLabel);
this.predicates = UniGraph.createIdPredicate(originalStep.getIds(), originalStep.getReturnClass());
this.stepDescriptor = new StepDescriptor(this);
this.controllers = controllerManager.getControllers(SearchQuery.SearchController.class);
this.setIteratorSupplier(this::query);
limit = -1;
this.propertyKeys = new HashSet<>();
}
private Iterator<E> query() {
Stream.concat(
this.predicates.getPredicates().stream(),
this.predicates.getChildren().stream()
.map(PredicatesHolder::getPredicates)
.flatMap(Collection::stream)
).map(HasContainer::getKey).forEach(this::addPropertyKey);
SearchQuery<E> searchQuery = new SearchQuery<>(returnClass, predicates, limit, propertyKeys, stepDescriptor);
return controllers.stream().<Iterator<E>>map(controller -> controller.search(searchQuery)).flatMap(ConversionUtils::asStream).iterator();
}
@Override
public void addPredicate(PredicatesHolder predicatesHolder) {
predicatesHolder.getPredicates().forEach(has -> GraphStep.processHasContainerIds(this, has));
this.predicates = PredicatesHolderFactory.and(this.predicates, predicatesHolder);
}
@Override
public PredicatesHolder getPredicates() {
return predicates;
}
@Override
public void setLimit(int limit) {
this.limit = limit;
}
@Override
public void addPropertyKey(String key) {
if (propertyKeys != null)
propertyKeys.add(key);
}
@Override
public void fetchAllKeys() {
this.propertyKeys = null;
}
@Override
public Set<String> getKeys() {
return propertyKeys;
}
}
|
package VASSAL.configure;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.FocusListener;
import javax.swing.JComponent;
import javax.swing.JLayer;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.LayerUI;
/**
* A Configurer for String values
*/
public class StringConfigurer extends Configurer {
protected JPanel p;
protected JTextField nameField;
protected int length;
protected static final int DEFAULT_LENGHTH = 20;
/**
* Base Constructor for StringConfigurer
*
* @param key Configurer Key - Not used for new-style configs
* @param name Configurer Name (label)
* @param val Initial Configurer value
* @param length Configurer length
* @param hint Hint text
*/
public StringConfigurer(String key, String name, int length, String hint, String val) {
super(key, name, val);
this.length = length > 0 ? length : DEFAULT_LENGHTH;
this.hint = hint;
}
public StringConfigurer(String key, String name, String val) {
this(key, name, DEFAULT_LENGHTH, "", val);
}
public StringConfigurer(String key, String name, int length) {
this (key, name, length, "", "");
}
public StringConfigurer(String key, String name) {
this(key, name, "");
}
public StringConfigurer(String val) {
this (null, "", val);
}
@Override
public String getValueString() {
return (String) value;
}
@Override
public void setValue(String s) {
if (!noUpdate && nameField != null) {
nameField.setText(s);
}
setValue((Object) s);
}
protected String getGrowthConstraint() {
return "growx"; // NON-NLS
}
@Override
public Component getControls() {
if (p == null) {
p = new ConfigurerPanel(getName(), "[fill,grow]0[0]", "[][fill,grow][]"); // NON-NLS
nameField = buildTextField();
nameField.setMaximumSize(new Dimension(
nameField.getMaximumSize().width,
nameField.getPreferredSize().height
));
nameField.setText(getValueString());
LayerUI<JTextField> layerUI = new ConfigLayerUI(this);
JLayer<JTextField> layer = new JLayer<>(nameField, layerUI);
p.add(layer, getGrowthConstraint()); // NON-NLS
nameField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
update();
}
@Override
public void removeUpdate(DocumentEvent e) {
update();
}
@Override
public void changedUpdate(DocumentEvent e) {}
private void update() {
noUpdate = true;
setValue(nameField.getText());
noUpdate = false;
}
});
}
return p;
}
protected JTextField buildTextField() {
return new HintTextField(length, hint);
}
@Override
public void setLabelVisibile(boolean visible) {
if (p instanceof ConfigurerPanel) {
((ConfigurerPanel) p).setLabelVisibility(visible);
}
}
@Override
public void setHighlighted(boolean highlighted) {
super.setHighlighted(highlighted);
getControls();
nameField.setBackground(highlighted ? LIST_ENTRY_HIGHLIGHT_COLOR : Color.white);
nameField.repaint();
}
@Override
public void addFocusListener(FocusListener listener) {
super.addFocusListener(listener);
getControls();
nameField.addFocusListener(listener);
}
@Override
public void removeFocusListener(FocusListener listener) {
super.removeFocusListener(listener);
getControls();
nameField.removeFocusListener(listener);
}
// Use JLayer to outline the field in Red as the Unix LaF ignores TextField background colours
private static class ConfigLayerUI extends LayerUI<JTextField> {
private final Configurer parent;
public ConfigLayerUI(Configurer parent) {
this.parent = parent;
}
@Override
public void paint (Graphics g, JComponent c) {
super.paint(g, c);
final Component cc = ((JLayer) c).getView();
if (parent.isHighlighted()) {
final Dimension d = cc.getSize();
g.setColor(Color.red);
g.drawRect(0, 0, d.width - 2, d.height - 2);
}
}
}
}
|
package nl.b3p.viewer.search;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.geotools.geometry.jts.WKTReader2;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Meine Toonen meinetoonen@b3partners.nl
*/
public class PDOKSearchClient extends SearchClient {
private static final Log log = LogFactory.getLog(SolrSearchClient.class);
private SolrServer server;
private WKTReader2 wkt;
private String filter;
public PDOKSearchClient(String filter){
server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver");
wkt = new WKTReader2();
this.filter = filter;
}
@Override
public SearchResult search(String term) {
SearchResult result = new SearchResult();
try {
JSONArray respDocs = new JSONArray();
SolrQuery query = new SolrQuery();
if(this.filter != null){
term += " " + this.filter;
}
query.setQuery(term);
query.setRequestHandler("/free");
QueryResponse rsp = server.query(query);
SolrDocumentList list = rsp.getResults();
for (SolrDocument solrDocument : list) {
JSONObject doc = solrDocumentToResult(solrDocument);
if (doc != null) {
respDocs.put(doc);
}
}
result.setResults(respDocs);
result.setLimitReached(list.getNumFound() > list.size());
} catch (SolrServerException ex) {
log.error("Cannot search:",ex);
}
return result;
}
@Override
public JSONArray autosuggest(String term) throws JSONException {
SearchResult r = search(term);
return r.getResults();
}
private JSONObject solrDocumentToResult(SolrDocument doc){
JSONObject result = null;
try {
Map<String, Object> values = doc.getFieldValueMap();
result = new JSONObject();
for (String key : values.keySet()) {
result.put(key, values.get(key));
}
String centroide = (String)doc.getFieldValue("centroide_rd");
String geom = centroide;
if(values.containsKey("geometrie_rd")){
geom = (String) values.get("geometrie_rd");
}
Geometry g = wkt.read(geom);
Envelope env = g.getEnvelopeInternal();
if (centroide != null) {
Map bbox = new HashMap();
bbox.put("minx", env.getMinX());
bbox.put("miny", env.getMinY());
bbox.put("maxx", env.getMaxX());
bbox.put("maxy", env.getMaxY());
result.put("location", bbox);
}
result.put("label", values.get("weergavenaam"));
} catch (JSONException | ParseException ex) {
log.error(ex);
}
return result;
}
}
|
package org.mozartoz.truffle.nodes.builtins;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.graalvm.collections.Pair;
import org.mozartoz.truffle.Options;
import org.mozartoz.truffle.nodes.DerefIfBoundNode;
import org.mozartoz.truffle.nodes.DerefNode;
import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.nodes.OzRootNode;
import org.mozartoz.truffle.nodes.call.ReadArgumentNode;
import org.mozartoz.truffle.nodes.local.BindNodeGen;
import org.mozartoz.truffle.runtime.OzLanguage;
import org.mozartoz.truffle.runtime.OzProc;
import org.mozartoz.truffle.runtime.OzRecord;
import org.mozartoz.truffle.translator.BuiltinsRegistry;
import com.oracle.truffle.api.dsl.NodeFactory;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.source.SourceSection;
public abstract class BuiltinsManager {
enum BuiltinFactories {
// Base.oz
Value(ValueBuiltinsFactory.getFactories()),
Literal(LiteralBuiltinsFactory.getFactories()),
Cell(CellBuiltinsFactory.getFactories()),
Port(PortBuiltinsFactory.getFactories()),
Atom(AtomBuiltinsFactory.getFactories()),
Name(NameBuiltinsFactory.getFactories()),
Int(IntBuiltinsFactory.getFactories()),
Float(FloatBuiltinsFactory.getFactories()),
Number(NumberBuiltinsFactory.getFactories()),
Tuple(TupleBuiltinsFactory.getFactories()),
Procedure(ProcedureBuiltinsFactory.getFactories()),
Dictionary(DictionaryBuiltinsFactory.getFactories()),
Record(RecordBuiltinsFactory.getFactories()),
Chunk(ChunkBuiltinsFactory.getFactories()),
VirtualString(VirtualStringBuiltinsFactory.getFactories()),
VirtualByteString(VirtualByteStringBuiltinsFactory.getFactories()),
Coders(CodersBuiltinsFactory.getFactories()),
Array(ArrayBuiltinsFactory.getFactories()),
Object(ObjectBuiltinsFactory.getFactories()),
Thread(ThreadBuiltinsFactory.getFactories()),
Exception(ExceptionBuiltinsFactory.getFactories()),
Time(TimeBuiltinsFactory.getFactories()),
ForeignPointer(ForeignPointerBuiltinsFactory.getFactories()),
CompactString(CompactStringBuiltinsFactory.getFactories()),
System(SystemBuiltinsFactory.getFactories()),
Property(PropertyBuiltinsFactory.getFactories()),
WeakReference(WeakReferenceBuiltinsFactory.getFactories()),
// Init.oz
Boot(BootBuiltinsFactory.getFactories()),
OS(OSBuiltinsFactory.getFactories()),
Debug(DebugBuiltinsFactory.getFactories()),
Reflection(ReflectionBuiltinsFactory.getFactories()),
Space(SpaceBuiltinsFactory.getFactories()),
Browser(BrowserBuiltinsFactory.getFactories());
final List<? extends NodeFactory<? extends OzNode>> factories;
BuiltinFactories(List<? extends NodeFactory<? extends OzNode>> factories) {
this.factories = factories;
}
}
private static final Map<String, OzProc> BUILTINS = new HashMap<>();
private static final Map<String, DynamicObject> BOOT_MODULES = new HashMap<>();
private static final Source BUILTINS_SOURCE = Source.newBuilder("oz", "", "builtin").internal(true).build();
private static final SourceSection BUILTINS_SOURCE_SECTION = BUILTINS_SOURCE.createUnavailableSection();
public static OzProc getBuiltin(String moduleName, String builtinName) {
return getBuiltin(moduleName + "." + builtinName);
}
public static OzProc getBuiltin(String name) {
OzProc fun = BUILTINS.get(name);
if (fun == null) {
throw new Error("No builtin " + name);
}
return fun;
}
public static DynamicObject getBootModule(String name) {
assert BOOT_MODULES.containsKey(name) : name;
return BOOT_MODULES.get(name);
}
public static DynamicObject getBootModulesRecord() {
return OzRecord.buildRecord("bootModules", BOOT_MODULES);
}
public static void defineBuiltins(OzLanguage language) {
assert BUILTINS.isEmpty();
String pkg = BuiltinsManager.class.getPackage().getName();
for (BuiltinFactories builtinFactories : BuiltinFactories.values()) {
installBuiltins(language, builtinFactories.name(), builtinFactories.factories);
}
BOOT_MODULES.put("Boot_WeakRef", BOOT_MODULES.get("Boot_WeakReference")); // TODO: hack
}
public static OzNode createNodeFromFactory(NodeFactory<? extends OzNode> factory, OzNode[] args) {
Builtin builtin = factory.getNodeClass().getAnnotation(Builtin.class);
if (builtin == null) {
builtin = Builtin.DEFAULT;
}
Object[] arguments = new OzNode[args.length];
for (int i = 0; i < args.length; i++) {
arguments[i] = transformArgumentNode(builtin, i, args[i]);
}
return factory.createNode(arguments);
}
private static void installBuiltins(OzLanguage language, String module, List<? extends NodeFactory<? extends OzNode>> factories) {
// The builtins of this module only, indexed by the builtin name
Map<String, OzProc> builtins = new HashMap<>(factories.size());
for (NodeFactory<? extends OzNode> factory : factories) {
Builtin builtin = factory.getNodeClass().getAnnotation(Builtin.class);
if (builtin == null) {
builtin = Builtin.DEFAULT;
}
int arity = factory.getNodeSignatures().get(0).size();
OzNode[] readArguments = new OzNode[arity];
for (int i = 0; i < readArguments.length; i++) {
readArguments[i] = new ReadArgumentNode(i);
}
OzNode node = createNodeFromFactory(factory, readArguments);
if (!builtin.proc()) {
node = BindNodeGen.create(new ReadArgumentNode(arity), node);
arity++;
}
final String builtinName;
if (!builtin.name().isEmpty()) {
builtinName = builtin.name();
} else {
String nodeName = factory.getNodeClass().getSimpleName();
builtinName = Character.toLowerCase(nodeName.charAt(0)) + nodeName.substring(1, nodeName.lastIndexOf("Node"));
}
String name = module + "." + builtinName;
OzRootNode rootNode = new OzRootNode(language, BUILTINS_SOURCE_SECTION, name, new FrameDescriptor(), node, arity, true);
OzProc function = new OzProc(rootNode.toCallTarget(), null, arity);
assert !BUILTINS.containsKey(name) : name;
BUILTINS.put(name, function);
builtins.put(builtinName.intern(), function);
BuiltinsRegistry.register(module, builtinName, arity);
}
String label = module.toLowerCase().intern();
BOOT_MODULES.put(("Boot_" + module).intern(), OzRecord.buildRecord(label, builtins));
}
private static OzNode transformArgumentNode(Builtin builtin, int i, OzNode arg) {
if (annoArrayInclude(builtin.deref(), i + 1)) {
return DerefNode.create(arg);
} else if (annoArrayInclude(builtin.tryDeref(), i + 1)) {
return DerefIfBoundNode.create(arg);
} else {
return arg;
}
}
private static boolean annoArrayInclude(int[] array, int i) {
for (int e : array) {
if (e == Builtin.ALL || e == i) {
return true;
}
}
return false;
}
}
|
package org.jboss.seam.forge.web;
import java.io.File;
import javax.inject.Named;
import org.jboss.seam.forge.project.Facet;
import org.jboss.seam.forge.project.Project;
import org.jboss.seam.forge.project.constraints.RequiresFacets;
import org.jboss.seam.forge.project.facets.WebResourceFacet;
import org.jboss.seam.forge.project.resources.FileResource;
import org.jboss.seam.forge.project.resources.builtin.DirectoryResource;
import org.jboss.shrinkwrap.descriptor.api.DescriptorImporter;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.spec.cdi.beans.BeansDescriptor;
import org.jboss.shrinkwrap.descriptor.impl.spec.cdi.beans.BeansDescriptorImpl;
import org.jboss.shrinkwrap.descriptor.impl.spec.cdi.beans.BeansModel;
import org.jboss.shrinkwrap.descriptor.spi.SchemaDescriptorProvider;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
@Named("cdi-web")
@RequiresFacets({ WebResourceFacet.class })
public class CDIFacet implements Facet
{
private Project project;
private FileResource<?> getConfigFile()
{
DirectoryResource webRoot = project.getFacet(WebResourceFacet.class).getWebRootDirectory();
return (FileResource<?>) webRoot.getChild("WEB-INF" + File.separator + "beans.xml");
}
/*
* Facet Methods
*/
@Override
public Project getProject()
{
return project;
}
@Override
public void setProject(final Project project)
{
this.project = project;
}
@Override
public boolean isInstalled()
{
return getConfigFile().exists();
}
@SuppressWarnings("unchecked")
public BeansModel getConfig()
{
DescriptorImporter<BeansDescriptor> importer = Descriptors.importAs(BeansDescriptor.class);
BeansDescriptor descriptor = importer.from(getConfigFile().getResourceInputStream());
BeansModel model = ((SchemaDescriptorProvider<BeansModel>) descriptor).getSchemaModel();
return model;
}
public void saveConfig(final BeansModel model)
{
BeansDescriptor descriptor = new BeansDescriptorImpl(model);
String output = descriptor.exportAsString();
getConfigFile().setContents(output);
}
@Override
public Facet install()
{
if (!isInstalled())
{
if (!getConfigFile().createNewFile())
{
throw new RuntimeException("Failed to create required [" + getConfigFile().getFullyQualifiedName() + "]");
}
FileResource<?> descriptor = getConfigFile();
if (!descriptor.exists())
{
descriptor.createNewFile();
descriptor.setContents(getClass()
.getResourceAsStream("/org/jboss/seam/forge/web/beans.xml"));
}
}
project.registerFacet(this);
return this;
}
}
|
package br.ufpe.cin.dsoa.adapter;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import br.ufpe.cin.dsoa.adapter.serializer.JsonSerializer;
import br.ufpe.cin.dsoa.api.event.Event;
import br.ufpe.cin.dsoa.api.event.EventAdapter;
import br.ufpe.cin.dsoa.api.event.EventConsumer;
import br.ufpe.cin.dsoa.api.event.EventType;
import br.ufpe.cin.dsoa.api.event.EventTypeCatalog;
import br.ufpe.cin.dsoa.api.event.Subscription;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
public class AMPQAdapter implements EventAdapter {
private ExecutorService executorService;
private EventTypeCatalog eventTypeCatalog;
private final String serviceId;
public AMPQAdapter() {
executorService = Executors.newCachedThreadPool();
serviceId = "AMPQAdapter";
}
@Override
public String getId() {
return serviceId;
}
public void exportEvent(Event event, Map<String, Object> configuration) {
final String queueName = event.getEventType().getName();
try {
Connection connection = createConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queueName, false, false, false, null);
String jsonEvent = JsonSerializer.getInstance().getJson(event);
byte[] msg = jsonEvent.getBytes();
channel.basicPublish("", queueName, null, msg);
channel.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void importEvent(EventConsumer consumer, Subscription subscription) {
final String queueName = subscription.getEventType().getName();
try {
Connection connection = createConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queueName, false, false, false, null);
final QueueingConsumer queueConsumer = new QueueingConsumer(channel);
String consumerTag = queueConsumer.getConsumerTag();
channel.basicConsume(queueName, false, consumerTag, true, false, null, queueConsumer);
executorService.execute(new Worker(queueConsumer, consumer));
} catch (IOException e) {
e.printStackTrace();
}
}
private Connection createConnection() throws IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setUsername("admin");
factory.setPassword("admin");
return factory.newConnection();
}
class Worker implements Runnable {
private QueueingConsumer queueConsumer;
private EventConsumer consumer;
public Worker(QueueingConsumer queueConsumer, EventConsumer consumer) {
super();
this.queueConsumer = queueConsumer;
this.consumer = consumer;
}
@Override
public void run() {
while (true) {
String message = receive();
Map<String, Object> eventMap = JsonSerializer.getInstance().getEventMap(message);
String eventTypeName = (String) eventMap.get("type");
EventType eventType = eventTypeCatalog.get(eventTypeName);
Event dsoaEvent = eventType.convertToEvent(eventMap);
consumer.handleEvent(dsoaEvent);
}
}
private String receive() {
String message = "";
try {
QueueingConsumer.Delivery delivery = queueConsumer.nextDelivery();
message = new String(delivery.getBody());
} catch (ShutdownSignalException e) {
e.printStackTrace();
} catch (ConsumerCancelledException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return message;
}
}
}
|
package com.rbmhtechnology.vind.test;
import com.rbmhtechnology.vind.SearchServerException;
import com.rbmhtechnology.vind.api.SearchServer;
import com.rbmhtechnology.vind.configure.SearchConfiguration;
import org.junit.rules.ExternalResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestSearchServer extends ExternalResource {
private Logger log = LoggerFactory.getLogger(getClass());
private ServerType serverType = ServerType.RemoteStandalone;
private SearchServer searchServer;
@Override
protected void before() throws Throwable {
super.before();
serverType.prepareConfig();
searchServer = SearchServer.getInstance();
}
@Override
protected void after() {
try {
searchServer.close();
} catch (SearchServerException e) {
log.error("Error closing SearchServer: {}", e.getMessage(), e);
} finally {
System.getProperties().remove("runtimeLib");
super.after();
}
}
public SearchServer getSearchServer() {
return searchServer;
}
private enum ServerType {
Embedded("com.rbmhtechnology.vind.solr.backend.EmbeddedSolrServerProvider", null, null, false),
RemoteStandalone("com.rbmhtechnology.vind.solr.backend.RemoteSolrServerProvider", "http://localhost:8983/solr", "vind", false),
RemoteCloud("com.rbmhtechnology.vind.solr.backend.RemoteSolrServerProvider", "localhost:9983", "vind", true);
private String provider;
private String host;
private String collection;
private boolean cloud;
ServerType(String provider, String host, String collection, boolean cloud) {
this.provider = provider;
this.host = host;
this.collection = collection;
this.cloud = cloud;
}
void prepareConfig() {
SearchConfiguration.set(SearchConfiguration.SERVER_PROVIDER, provider);
if(host != null) SearchConfiguration.set(SearchConfiguration.SERVER_HOST, host);
if(collection != null) SearchConfiguration.set(SearchConfiguration.SERVER_COLLECTION, collection);
SearchConfiguration.set(SearchConfiguration.SERVER_SOLR_CLOUD, cloud);
System.setProperty("runtimeLib", String.valueOf(cloud));
}
}
}
|
package sed.app;
import sed.SurfaceCameraControl;
import sed.sky.SkyGradient;
import sed.sky.Sun;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial.CullHint;
/**
* <b>Base layer</b> {@link AppState} providing a sky {@link Node}
* (to attach all sky related things at), a {@link SkyGradient} and
* a {@link Sun}.
*
* @author cn
*/
public class SkyAppState extends BasicAppState {
// TODO: Realize SkyDome and Sun as background geometry in jME via Bucket.Sky?
private static final float HemisphereRadius = 1000f;
private static final float UpdateInterval = 1f; // in seconds
// exists only while AppState is attached
private Node skyNode;
private Sun sun;
private SkyGradient skyGradient;
public SkyAppState() {
super(UpdateInterval);
}
@Override
public void initialize(AppStateManager stateManager, Application baseApp) {
super.initialize(stateManager, baseApp);
skyNode = new Node("SkyNode");
skyNode.setCullHint(CullHint.Never);
getApp().getRootNode().attachChild(skyNode);
// since the constructors shouldn't do anything related to processing
// the delayed update should work
sun = new Sun(getApp().getSimClock(), getApp().getMission());
skyGradient = new SkyGradient(sun);
intervalUpdate();
skyNode.addControl(new SurfaceCameraControl(getApp().getCamera()));
}
@Override
public void cleanup() {
super.cleanup();
skyNode.removeControl(SurfaceCameraControl.class);
getApp().getRootNode().detachChild(skyNode);
skyNode = null;
sun = null;
skyGradient = null;
}
@Override
protected void intervalUpdate() {
sun.update();
skyGradient.setTurbidity(getState(WeatherAppState.class).getWeather().getFloat("sky.turbidity"));
skyGradient.update();
}
// public API
public Node getSkyNode() {
return skyNode;
}
public Sun getSun() {
return sun;
}
public SkyGradient getSkyGradient() {
return skyGradient;
}
public float getNightThetaMax() {
return SkyGradient.NightThetaMax;
}
public ColorRGBA getNightSunColor() {
return SkyGradient.NightSunColor;
}
public float getHemisphereRadius() {
return HemisphereRadius;
}
}
|
package net.darkmist.alib.ref;
import java.lang.ref.WeakReference;
public abstract class MemCachedRef<T> extends AbstractRef<T>
{
private WeakReference<T> valRef = null;
/**
* (Re)Create the object.
*/
protected abstract T make();
/**
* Get the cached object. If the object is not in memory, it is recreated.
*/
public synchronized T get()
{
T val;
synchronized(this)
{
if(valRef==null || (val = valRef.get())==null)
{
val = make();
valRef = new WeakReference<T>(val);
}
}
return val;
}
}
|
package com.kii.thingif.trigger;
import android.os.Parcel;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.kii.thingif.SmallTestBase;
import org.apache.commons.lang3.RandomStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@RunWith(RobolectricTestRunner.class)
public class TriggerOptionsTest extends SmallTestBase {
private static final class TestCase<T> {
@NonNull String errorMessage;
@NonNull TestData input;
@NonNull T expected;
TestCase(
@NonNull String errorMessage,
@NonNull TestData input,
@NonNull T expected)
{
this.errorMessage = errorMessage;
this.input = input;
this.expected = expected;
}
}
private static final class TestData {
@Nullable String title;
@Nullable String description;
@Nullable JSONObject metadata;
TestData(
@Nullable String title,
@Nullable String description,
@Nullable JSONObject metadata)
{
this.title = title;
this.description = description;
this.metadata = metadata;
}
}
private static List<TestCase<TestData>> createNormalTestCases()
throws JSONException
{
List<TestCase<TestData>> retval = new ArrayList<>();
JSONObject metadata = new JSONObject();
metadata.put("key", "value");
Collections.addAll(retval,
createNormalTestData(
"1", new TestData(null, null, null)),
createNormalTestData(
"2", new TestData(null, "description", null)),
createNormalTestData(
"3", new TestData(null, null, metadata)),
createNormalTestData(
"4", new TestData(null, "description", metadata)),
createNormalTestData(
"5", new TestData("title", null, null)),
createNormalTestData(
"6", new TestData("title", "description", null)),
createNormalTestData(
"7", new TestData("title", null, metadata)),
createNormalTestData(
"8", new TestData("title", "description", metadata)));
return retval;
}
private static TestCase<TestData> createNormalTestData(
@NonNull String errorMessage,
@NonNull TestData testData)
{
return new TestCase<>(errorMessage, testData, testData);
}
@Test
public void normalTest() throws Exception {
for (TestCase<TestData> test : createNormalTestCases()) {
TestData input = test.input;
TestData expected = test.expected;
String errorMessage = test.errorMessage;
TriggerOptions.Builder builder = TriggerOptions.Builder.newBuilder();
if (input.title != null) {
Assert.assertEquals(errorMessage,
builder, builder.setTitle(input.title));
}
if (input.description != null) {
Assert.assertEquals(errorMessage,
builder, builder.setDescription(input.description));
}
if (input.metadata != null) {
Assert.assertEquals(errorMessage,
builder, builder.setMetadata(input.metadata));
}
Assert.assertEquals(errorMessage,
builder.getTitle(), expected.title);
Assert.assertEquals(errorMessage,
builder.getDescription(), expected.description);
assertJSONObject(errorMessage,
builder.getMetadata(), expected.metadata);
TriggerOptions options = builder.build();
Assert.assertNotNull(errorMessage, options);
Assert.assertEquals(errorMessage,
expected.title, options.getTitle());
Assert.assertEquals(errorMessage,
expected.description, options.getDescription());
assertJSONObject(errorMessage,
expected.metadata, options.getMetadata());
Parcel parcel = Parcel.obtain();
options.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
TriggerOptions deserialized =
TriggerOptions.CREATOR.createFromParcel(parcel);
Assert.assertNotNull(errorMessage, deserialized);
Assert.assertEquals(errorMessage,
expected.title, deserialized.getTitle());
Assert.assertEquals(errorMessage,
expected.description, deserialized.getDescription());
assertJSONObject(errorMessage,
expected.metadata, deserialized.getMetadata());
}
}
private List<TestCase<String>> createIllegalArgumentTestCases() {
List<TestCase<String>> retval = new ArrayList<>();
Collections.addAll(retval,
new TestCase<>(
"1",
new TestData(RandomStringUtils.random(51), null, null),
"title is more than 50 charactors."),
new TestCase<>(
"2",
new TestData(null, RandomStringUtils.random(201), null),
"description is more than 200 charactors."));
return retval;
}
@Test
public void illegalArgumentExceptionTest() throws Exception {
for (TestCase<String> test : createIllegalArgumentTestCases()) {
TestData input = test.input;
String expected = test.expected;
String errorMessage = test.errorMessage;
TriggerOptions.Builder builder = TriggerOptions.Builder.newBuilder();
IllegalArgumentException actual = null;
try {
if (input.title != null) {
builder.setTitle(input.title);
} else if (input.description != null) {
builder.setDescription(input.description);
}
} catch (IllegalArgumentException e) {
actual = e;
}
Assert.assertNotNull(errorMessage, actual);
Assert.assertEquals(errorMessage, expected, actual.getMessage());
}
}
@Test
public void valueOverwriteTest() throws Exception {
String title1 = "title1";
String description1 = "description1";
JSONObject metadata1 = new JSONObject();
metadata1.put("key1", "value1");
TriggerOptions.Builder builder = TriggerOptions.Builder.newBuilder();
builder.setTitle(title1).setDescription(description1).
setMetadata(metadata1);
Assert.assertEquals(title1, builder.getTitle());
Assert.assertEquals(description1, builder.getDescription());
assertJSONObject(metadata1, builder.getMetadata());
TriggerOptions options = builder.build();
Assert.assertEquals(title1, options.getTitle());
Assert.assertEquals(description1, options.getDescription());
assertJSONObject(metadata1, options.getMetadata());
String title2 = "title2";
String description2 = "description2";
JSONObject metadata2 = new JSONObject();
metadata2.put("key2", "value2");
builder.setTitle(title2).setDescription(description2).
setMetadata(metadata2);
Assert.assertEquals(title2, builder.getTitle());
Assert.assertEquals(description2, builder.getDescription());
assertJSONObject(metadata2, builder.getMetadata());
options = builder.build();
Assert.assertEquals(title2, options.getTitle());
Assert.assertEquals(description2, options.getDescription());
assertJSONObject(metadata2, options.getMetadata());
}
}
|
package com.messagebird.objects;
import com.messagebird.objects.PhoneNumberFeature;
import java.util.EnumSet;
import java.util.List;
public class PhoneNumber {
private String number;
private String country;
private String region;
private String locality;
private EnumSet<PhoneNumberFeature> features;
private String type;
private List<String> tags;
public String getNumber() {
return this.number;
}
public String getCountry() {
return this.country;
}
public String getRegion() {
return this.region;
}
public String getLocality() {
return this.locality;
}
public EnumSet<PhoneNumberFeature> getFeatures() {
return this.features;
}
public String getType() {
return this.type;
}
public List<String> getTags() {
return this.tags;
}
@Override
public String toString() {
return "PhoneNumber{" +
"number='" + number + "\'" +
", country='" + country + "\'" +
", region='" + region + "\'" +
", locality='" + locality + "\'" +
", features=" + features +
", tags=" + tags +
", type='" + type + "\'" +
"}";
}
}
|
package org.ocpsoft.rewrite;
import java.util.ArrayList;
import java.util.List;
import org.ocpsoft.logging.Logger;
import org.ocpsoft.logging.Logger.Level;
import org.ocpsoft.rewrite.config.Rule;
import org.ocpsoft.rewrite.config.RuleMetadata;
import org.ocpsoft.rewrite.context.Context;
import org.ocpsoft.rewrite.context.ContextBase;
import org.ocpsoft.rewrite.event.Rewrite;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
*/
public abstract class AbstractRewrite implements Rewrite
{
private static final Logger log = Logger.getLogger(AbstractRewrite.class);
private Context context = new ContextBase() {};
@Override
public Context getRewriteContext()
{
return context;
}
@Override
@SuppressWarnings("unchecked")
public List<Rule> getEvaluatedRules()
{
List<Rule> evaluated = (List<Rule>) this.getRewriteContext().get(
AbstractRewrite.class.getName() + "_EVALUATED_RULES");
if (evaluated == null)
{
evaluated = new ArrayList<Rule>();
this.getRewriteContext().put(AbstractRewrite.class.getName() + "_EVALUATED_RULES", evaluated);
}
return evaluated;
}
/**
* Print a log of all {@link Rule} instances evaluated during the given {@link Rewrite} event. This method is a no-op
* if the selected logging {@link Level} is disabled.
*/
public static void logEvaluatedRules(Rewrite event, Level level)
{
switch (level)
{
case INFO:
if (log.isInfoEnabled())
log.info(buildLogOutput(event).toString());
break;
case WARN:
if (log.isWarnEnabled())
log.warn(buildLogOutput(event).toString());
break;
case ERROR:
if (log.isErrorEnabled())
log.error(buildLogOutput(event).toString());
break;
case DEBUG:
if (log.isDebugEnabled())
log.debug(buildLogOutput(event).toString());
break;
case TRACE:
if (log.isTraceEnabled())
log.trace(buildLogOutput(event).toString());
break;
default:
break;
}
}
private static StringBuilder buildLogOutput(Rewrite event)
{
StringBuilder builder = new StringBuilder();
builder.append("Rewrite rule evaluation for event [" + event + "]\n");
int i = 0;
for (Rule rule : event.getEvaluatedRules()) {
builder.append("\tRule " + i + ": " + rule);
if (rule instanceof Context)
{
builder.append(" defined at "
+ ((Context) rule).get(RuleMetadata.PROVIDER_LOCATION) + "\n");
}
i++;
}
return builder;
}
}
|
package se.sics.cooja.contikimote;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import org.apache.log4j.Logger;
import se.sics.cooja.*;
import se.sics.cooja.dialogs.MessageList;
import se.sics.cooja.dialogs.UserPlatformsDialog;
/**
* A dialog for configuring Contiki mote types and compiling Contiki mote type
* libraries. Allows user to change mote type specific data such as
* descriptions, which processes should be started at mote initialization and
* which interfaces the type should support.
*
* The dialog takes a Contiki mote type as argument and pre-selects the values
* already set in that mote type before showing the dialog. Any changes made to
* the settings are written to the mote type if the compilation is successful
* and the user presses OK.
*
* This dialog uses external tools to scan for sources and compile libraries.
*
* @author Fredrik Osterlind
*/
public class ContikiMoteTypeDialog extends JDialog {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(ContikiMoteTypeDialog.class);
private MoteTypeEventHandler myEventHandler = new MoteTypeEventHandler();
private Thread compilationThread;
/**
* Suggested mote type identifier prefix
*/
public static final String ID_PREFIX = "mtype";
private final static int LABEL_WIDTH = 170;
private final static int LABEL_HEIGHT = 15;
private ContikiMoteType myMoteType = null;
private JTextField textID, textOutputFiles, textDescription, textContikiDir,
textCoreDir, textUserPlatforms;
private JButton createButton, testButton, rescanButton;
private JCheckBox symbolsCheckBox;
private JPanel processPanel; // Holds process checkboxes
private JPanel sensorPanel; // Holds sensor checkboxes
private JPanel moteInterfacePanel; // Holds mote interface checkboxes
private JPanel coreInterfacePanel; // Holds core interface checkboxes
private JPanel entireSensorPane; // Holds entire sensor pane (can be hidden)
private JPanel entireCoreInterfacePane; // Holds entire core interface pane
// (can be hidden)
private boolean settingsOK = false; // Do all settings seem correct?
private boolean compilationSucceded = false; // Did compilation succeed?
private boolean libraryCreatedOK = false; // Was a library created?
private PlatformConfig newMoteTypeConfig = null; // Mote type platform config
private Vector<File> moteTypeUserPlatforms = new Vector<File>(); // Mote type
// user
// platforms
private Vector<File> compilationFiles = null;
private Vector<MoteType> allOtherTypes = null; // Used to check for
// conflicting parameters
private GUI myGUI = null;
private ContikiMoteTypeDialog myDialog;
/**
* Shows a dialog for configuring a Contiki mote type and compiling the shared
* library it uses.
*
* @param parentFrame
* Parent frame for dialog
* @param simulation
* Simulation holding (or that will hold) mote type
* @param moteTypeToConfigure
* Mote type to configure
* @return True if compilation succeded and library is ready to be loaded
*/
public static boolean showDialog(Frame parentFrame, Simulation simulation,
ContikiMoteType moteTypeToConfigure) {
final ContikiMoteTypeDialog myDialog = new ContikiMoteTypeDialog(
parentFrame);
myDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
myDialog.myMoteType = moteTypeToConfigure;
myDialog.myGUI = simulation.getGUI();
myDialog.allOtherTypes = simulation.getMoteTypes();
// Set identifier of mote type
if (moteTypeToConfigure.getIdentifier() != null) {
// Identifier already preset, assuming recompilation of mote type library
// Use preset identifier (read-only)
myDialog.textID.setText(moteTypeToConfigure.getIdentifier());
myDialog.textID.setEditable(false);
myDialog.textID.setEnabled(false);
// Change title to indicate this is a recompilation
myDialog.setTitle("Recompile Mote Type");
} else {
// Suggest new identifier
int counter = 0;
String testIdentifier = "";
boolean identifierOK = false;
while (!identifierOK) {
counter++;
testIdentifier = ID_PREFIX + counter;
identifierOK = true;
// Check if identifier is already used by some other type
for (MoteType existingMoteType : myDialog.allOtherTypes) {
if (existingMoteType != myDialog.myMoteType
&& existingMoteType.getIdentifier().equals(testIdentifier)) {
identifierOK = false;
break;
}
}
// Check if library file with given identifier has already been loaded
if (identifierOK
&& CoreComm.hasLibraryFileBeenLoaded(new File(
ContikiMoteType.tempOutputDirectory,
testIdentifier
+ ContikiMoteType.librarySuffix))) {
identifierOK = false;
}
}
myDialog.textID.setText(testIdentifier);
}
// Set preset description of mote type
if (moteTypeToConfigure.getDescription() != null) {
myDialog.textDescription.setText(moteTypeToConfigure.getDescription());
} else {
// Suggest unique description
int counter = 0;
String testDescription = "";
boolean descriptionOK = false;
while (!descriptionOK) {
counter++;
testDescription = "Contiki Mote #" + counter;
descriptionOK = true;
// Check if identifier is already used by some other type
for (MoteType existingMoteType : myDialog.allOtherTypes) {
if (existingMoteType != myDialog.myMoteType
&& existingMoteType.getDescription().equals(testDescription)) {
descriptionOK = false;
break;
}
}
}
myDialog.textDescription.setText(testDescription);
}
// Set preset Contiki base directory of mote type
if (moteTypeToConfigure.getContikiBaseDir() != null) {
myDialog.textContikiDir.setText(moteTypeToConfigure.getContikiBaseDir());
}
// Set preset Contiki core directory of mote type
if (moteTypeToConfigure.getContikiCoreDir() != null) {
myDialog.textCoreDir.setText(moteTypeToConfigure.getContikiCoreDir());
}
// Set preset user platform directories of mote type
if (moteTypeToConfigure.getUserPlatformDirs() != null) {
myDialog.moteTypeUserPlatforms = moteTypeToConfigure
.getUserPlatformDirs();
String userPlatformText = null;
for (File userPlatform : myDialog.moteTypeUserPlatforms) {
if (userPlatformText == null)
userPlatformText = "'" + userPlatform.getPath() + "'";
else
userPlatformText += ", '" + userPlatform.getPath() + "'";
}
myDialog.textUserPlatforms.setText(userPlatformText);
}
// Set preset "use symbols"
if (moteTypeToConfigure.hasSystemSymbols()) {
myDialog.symbolsCheckBox.setSelected(true);
}
// Scan directories for processes, sensors and core interfaces
// TODO Really do this without starting a separate thread?
myDialog.updateVisualFields();
myDialog.rescanDirectories();
// Select preset processes of mote type
if (moteTypeToConfigure.getProcesses() != null) {
for (String presetProcess : moteTypeToConfigure.getProcesses()) {
// Try to find process in current list
boolean foundAndSelectedProcess = false;
for (Component processCheckBox : myDialog.processPanel.getComponents()) {
if (presetProcess.equals(((JCheckBox) processCheckBox).getText())) {
((JCheckBox) processCheckBox).setSelected(true);
foundAndSelectedProcess = true;
break;
}
}
// Warn if not found
if (!foundAndSelectedProcess) {
// Let user choose whether to add process
Object[] options = { "Add", "Cancel" };
String question = "The configuration file contains a process "
+ "(" + presetProcess + ") not found during scan."
+ "\nDo you want to include this anyway?";
String title = "Add process?";
int answer = JOptionPane.showOptionDialog(myDialog, question, title,
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
options, options[0]);
if (answer == JOptionPane.YES_OPTION) {
// Create new check box
JCheckBox newCheckBox = new JCheckBox(presetProcess, true);
myDialog.processPanel.add(newCheckBox);
}
}
}
}
// Select preset sensors
if (moteTypeToConfigure.getSensors() != null) {
// Deselect all sensors already automatically selected
for (Component coreInterfaceCheckBox : myDialog.sensorPanel
.getComponents()) {
((JCheckBox) coreInterfaceCheckBox).setSelected(false);
}
for (String presetSensor : moteTypeToConfigure.getSensors()) {
// Try to find sensor in current list
boolean foundAndSelectedSensor = false;
for (Component sensorCheckBox : myDialog.sensorPanel.getComponents()) {
if (presetSensor.equals(((JCheckBox) sensorCheckBox).getText())) {
((JCheckBox) sensorCheckBox).setSelected(true);
foundAndSelectedSensor = true;
break;
}
}
// Warn if not found
if (!foundAndSelectedSensor) {
// Let user choose whether to add sensor
Object[] options = { "Add", "Cancel" };
String question = "The configuration file contains a sensor "
+ "(" + presetSensor + ") not found during scan."
+ "\nDo you want to include this anyway?";
String title = "Add sensor?";
int answer = JOptionPane.showOptionDialog(myDialog, question, title,
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
options, options[0]);
if (answer == JOptionPane.YES_OPTION) {
// Create new check box
JCheckBox newCheckBox = new JCheckBox(presetSensor, true);
myDialog.sensorPanel.add(newCheckBox);
}
}
}
}
// Select preset core interfaces
if (moteTypeToConfigure.getCoreInterfaces() != null) {
// Deselect all core interfaces already automatically selected
for (Component coreInterfaceCheckBox : myDialog.coreInterfacePanel
.getComponents()) {
((JCheckBox) coreInterfaceCheckBox).setSelected(false);
}
for (String presetCoreInterface : moteTypeToConfigure.getCoreInterfaces()) {
// Try to find core interface in current list
boolean foundAndSelectedCoreInterface = false;
for (Component coreInterfaceCheckBox : myDialog.coreInterfacePanel
.getComponents()) {
if (presetCoreInterface.equals(((JCheckBox) coreInterfaceCheckBox)
.getText())) {
((JCheckBox) coreInterfaceCheckBox).setSelected(true);
foundAndSelectedCoreInterface = true;
break;
}
}
// Warn if not found
if (!foundAndSelectedCoreInterface) {
// Let user choose whether to add interface
Object[] options = { "Add", "Cancel" };
String question = "The configuration file contains a core interface "
+ "(" + presetCoreInterface + ") not found during scan."
+ "\nDo you want to include this anyway?";
String title = "Add core interface?";
int answer = JOptionPane.showOptionDialog(myDialog, question, title,
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
options, options[0]);
if (answer == JOptionPane.YES_OPTION) {
// Create new check box
JCheckBox newCheckBox = new JCheckBox(presetCoreInterface, true);
myDialog.coreInterfacePanel.add(newCheckBox);
}
}
}
}
// Select preset mote interfaces
if (moteTypeToConfigure.getMoteInterfaces() != null) {
// Deselect all mote interfaces already automatically selected
for (Component moteInterfaceCheckBox : myDialog.moteInterfacePanel
.getComponents()) {
((JCheckBox) moteInterfaceCheckBox).setSelected(false);
}
for (Class presetMoteInterface : moteTypeToConfigure.getMoteInterfaces()) {
// Try to find mote interface in current list
boolean foundAndSelectedMoteInterface = false;
for (Component moteInterfaceCheckBox : myDialog.moteInterfacePanel
.getComponents()) {
Class moteInterfaceClass = (Class) ((JCheckBox) moteInterfaceCheckBox)
.getClientProperty("class");
if (presetMoteInterface == moteInterfaceClass) {
((JCheckBox) moteInterfaceCheckBox).setSelected(true);
foundAndSelectedMoteInterface = true;
break;
}
}
// Warn if not found
if (!foundAndSelectedMoteInterface) {
logger.warn("Mote interface was not found in current environment: "
+ presetMoteInterface);
}
}
}
// Set position and focus of dialog
myDialog.pack();
myDialog.setLocationRelativeTo(parentFrame);
myDialog.textDescription.requestFocus();
myDialog.textDescription.select(0, myDialog.textDescription.getText()
.length());
Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
if (maxSize != null &&
(myDialog.getSize().getWidth() > maxSize.getWidth()
|| myDialog.getSize().getHeight() > maxSize.getHeight())) {
Dimension newSize = new Dimension();
newSize.height = Math.min((int) maxSize.getHeight(), (int) myDialog.getSize().getHeight());
newSize.width = Math.min((int) maxSize.getWidth(), (int) myDialog.getSize().getWidth());
logger.info("Resizing dialog: " + myDialog.getSize() + " -> " + newSize);
myDialog.setSize(newSize);
}
myDialog.setVisible(true);
if (myDialog.myMoteType != null) {
// Library was compiled and loaded
return true;
}
return false;
}
private ContikiMoteTypeDialog(Frame frame) {
super(frame, "Add Mote Type", true);
myDialog = this;
JLabel label;
JPanel mainPane = new JPanel();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));
JPanel smallPane;
JTextField textField;
JButton button;
// BOTTOM BUTTON PART
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
button = new JButton("Cancel");
button.setActionCommand("cancel");
button.addActionListener(myEventHandler);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(button);
buttonPane.add(Box.createHorizontalGlue());
button = new JButton("Clean intermediate files");
button.setActionCommand("clean");
button.addActionListener(myEventHandler);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(button);
button = new JButton("Compile & Test");
button.setActionCommand("testsettings");
button.addActionListener(myEventHandler);
testButton = button;
this.getRootPane().setDefaultButton(button);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(button);
button = new JButton("Create");
button.setEnabled(libraryCreatedOK);
button.setActionCommand("create");
button.addActionListener(myEventHandler);
createButton = button;
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(button);
// MAIN PART
// Identifier
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Identifier");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
textField = new JTextField();
textField.setText("");
textField.getDocument().addDocumentListener(myEventHandler);
textID = textField;
label.setLabelFor(textField);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(textField);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Output filenames
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Output files");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
textField = new JTextField();
textField.setText(ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + textID.getText() + ContikiMoteType.mapSuffix
+ ", " + ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + textID.getText() + ContikiMoteType.librarySuffix
+ ", " + ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + textID.getText() + ContikiMoteType.dependSuffix);
textField.setEnabled(false);
textOutputFiles = textField;
label.setLabelFor(textField);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(textField);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Description
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Description");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
textField = new JTextField();
textField.setBackground(Color.GREEN);
textField.setText("[enter description here]");
textField.getDocument().addDocumentListener(myEventHandler);
textDescription = textField;
label.setLabelFor(textField);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(textField);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Contiki dir
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Contiki 2.x OS path");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
textField = new JTextField();
textField.setText(GUI.getExternalToolsSetting("PATH_CONTIKI"));
textField.getDocument().addDocumentListener(myEventHandler);
textContikiDir = textField;
label.setLabelFor(textField);
button = new JButton("Browse");
button.setActionCommand("browsecontiki");
button.addActionListener(myEventHandler);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(textField);
smallPane.add(button);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// COOJA core platform dir
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Core platform path");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
textField = new JTextField();
textField.setText(textContikiDir.getText()
+ GUI.getExternalToolsSetting("PATH_COOJA_CORE_RELATIVE"));
textField.setEditable(false);
textCoreDir = textField;
label.setLabelFor(textField);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(textField);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// COOJA user platform dir
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Mote type user platforms");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
textField = new JTextField();
textField.setText("");
textField.setEditable(false);
textUserPlatforms = textField;
label.setLabelFor(textField);
button = new JButton("Manage");
button.setActionCommand("manageuserplatforms");
button.addActionListener(myEventHandler);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(textField);
smallPane.add(button);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Include symbols selection
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("System symbols");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
symbolsCheckBox = new JCheckBox("Include");
symbolsCheckBox.setSelected(false);
symbolsCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pathsWereUpdated();
}
});
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(symbolsCheckBox);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Separator
mainPane.add(new JSeparator());
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Rescan button
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Scan after entering above information");
rescanButton = new JButton("Scan now");
rescanButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rescanDirectories();
}
});
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(rescanButton);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Separator
mainPane.add(new JSeparator());
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Processes
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Processes");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setAlignmentY(Component.TOP_ALIGNMENT);
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
JPanel processHolder = new JPanel(new BorderLayout());
processHolder.setAlignmentX(Component.LEFT_ALIGNMENT);
processHolder.setAlignmentY(Component.TOP_ALIGNMENT);
button = new JButton("Add process name");
button.setActionCommand("addprocess");
button.addActionListener(myEventHandler);
processHolder.add(BorderLayout.SOUTH, button);
processPanel = new JPanel();
processPanel.setLayout(new BoxLayout(processPanel, BoxLayout.Y_AXIS));
JScrollPane tempPane = new JScrollPane(processPanel);
tempPane.setPreferredSize(new Dimension(300, 200));
processHolder.add(BorderLayout.WEST, tempPane);
label.setLabelFor(processPanel);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(processHolder);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Mote interfaces
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Mote Interfaces");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setAlignmentY(Component.TOP_ALIGNMENT);
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
JPanel moteInterfaceHolder = new JPanel(new BorderLayout());
moteInterfaceHolder.setAlignmentX(Component.LEFT_ALIGNMENT);
moteInterfaceHolder.setAlignmentY(Component.TOP_ALIGNMENT);
moteInterfacePanel = new JPanel();
moteInterfacePanel.setLayout(new BoxLayout(moteInterfacePanel,
BoxLayout.Y_AXIS));
tempPane = new JScrollPane(moteInterfacePanel);
tempPane.setPreferredSize(new Dimension(300, 200));
moteInterfaceHolder.add(BorderLayout.WEST, tempPane);
label.setLabelFor(moteInterfacePanel);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(moteInterfaceHolder);
mainPane.add(smallPane);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Separator with show advanced checkbox
JCheckBox showAdvancedCheckBox = new JCheckBox("Show advanced settings");
showAdvancedCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (entireCoreInterfacePane != null)
entireCoreInterfacePane.setVisible(true);
if (entireSensorPane != null)
entireSensorPane.setVisible(true);
} else {
if (entireCoreInterfacePane != null)
entireCoreInterfacePane.setVisible(false);
if (entireSensorPane != null)
entireSensorPane.setVisible(false);
}
}
});
mainPane.add(new JSeparator());
mainPane.add(showAdvancedCheckBox);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Core sensors
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Sensors");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setAlignmentY(Component.TOP_ALIGNMENT);
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
JPanel sensorHolder = new JPanel(new BorderLayout());
sensorHolder.setAlignmentX(Component.LEFT_ALIGNMENT);
sensorHolder.setAlignmentY(Component.TOP_ALIGNMENT);
// button = new JButton(GUI.lang.getString("motetype_scansens"));
// button.setActionCommand("scansensors");
// button.addActionListener(myEventHandler);
// sensorHolder.add(BorderLayout.NORTH, button);
button = new JButton("Add sensor name");
button.setActionCommand("addsensor");
button.addActionListener(myEventHandler);
sensorHolder.add(BorderLayout.SOUTH, button);
sensorPanel = new JPanel();
sensorPanel.setLayout(new BoxLayout(sensorPanel, BoxLayout.Y_AXIS));
JScrollPane tempPane2 = new JScrollPane(sensorPanel);
tempPane2.setPreferredSize(new Dimension(300, 200));
sensorHolder.add(BorderLayout.WEST, tempPane2);
label.setLabelFor(sensorPanel);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(sensorHolder);
mainPane.add(smallPane);
entireSensorPane = smallPane;
entireSensorPane.setVisible(false);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Core interfaces
smallPane = new JPanel();
smallPane.setAlignmentX(Component.LEFT_ALIGNMENT);
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS));
label = new JLabel("Core Interfaces");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setAlignmentY(Component.TOP_ALIGNMENT);
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
JPanel interfaceHolder = new JPanel(new BorderLayout());
interfaceHolder.setAlignmentX(Component.LEFT_ALIGNMENT);
interfaceHolder.setAlignmentY(Component.TOP_ALIGNMENT);
button = new JButton("Add interface name");
button.setActionCommand("addinterface");
button.addActionListener(myEventHandler);
interfaceHolder.add(BorderLayout.SOUTH, button);
coreInterfacePanel = new JPanel();
coreInterfacePanel.setLayout(new BoxLayout(coreInterfacePanel,
BoxLayout.Y_AXIS));
JScrollPane tempPane3 = new JScrollPane(coreInterfacePanel);
tempPane3.setPreferredSize(new Dimension(300, 200));
interfaceHolder.add(BorderLayout.WEST, tempPane3);
label.setLabelFor(coreInterfacePanel);
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(Box.createHorizontalGlue());
smallPane.add(interfaceHolder);
mainPane.add(smallPane);
entireCoreInterfacePane = smallPane;
entireCoreInterfacePane.setVisible(false);
mainPane.add(Box.createRigidArea(new Dimension(0, 5)));
// Add everything!
mainPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
Container contentPane = getContentPane();
JScrollPane mainScrollPane = new JScrollPane(mainPane);
// mainScrollPane.setPreferredSize(new Dimension(
// mainPane.getPreferredSize().width + 50, 500));
contentPane.add(mainScrollPane, BorderLayout.CENTER);
contentPane.add(buttonPane, BorderLayout.SOUTH);
addWindowListener(new WindowListener() {
public void windowDeactivated(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
myMoteType = null;
dispose();
}
});
}
/**
* Checks which core interfaces are needed by the currently selected mote
* interfaces, and selects only them.
*/
private void recheckInterfaceDependencies() {
// Unselect all core interfaces
for (Component checkBox : coreInterfacePanel.getComponents()) {
((JCheckBox) checkBox).setSelected(false);
}
// Loop through all mote interfaces
for (Component checkBox : moteInterfacePanel.getComponents()) {
JCheckBox moteIntfCheckBox = (JCheckBox) checkBox;
// If the mote interface is selected, select needed core interfaces
if (moteIntfCheckBox.isSelected()) {
String[] neededCoreInterfaces = null;
// Get needed core interfaces (if any)
try {
Class moteInterfaceClass = (Class) moteIntfCheckBox
.getClientProperty("class");
if (ContikiMoteInterface.class.isAssignableFrom(moteInterfaceClass)) {
Method m = moteInterfaceClass.getDeclaredMethod(
"getCoreInterfaceDependencies", (Class[]) null);
neededCoreInterfaces = (String[]) m.invoke(null, (Object[]) null);
}
} catch (NoSuchMethodException e) {
logger.warn("Can't read core interface dependencies of "
+ moteIntfCheckBox.getText() + ", assuming no core dependencies");
} catch (InvocationTargetException e) {
logger.warn("Can't read core interface dependencies of "
+ moteIntfCheckBox.getText() + ": " + e);
} catch (IllegalAccessException e) {
logger.warn("Can't read core interface dependencies of "
+ moteIntfCheckBox.getText() + ": " + e);
}
// If needed core interfaces found, select them
if (neededCoreInterfaces != null) {
// Loop through all needed core interfaces
for (String neededCoreInterface : neededCoreInterfaces) {
int coreInterfacePosition = -1;
// Check that the core interface actually exists
for (int j = 0; j < coreInterfacePanel.getComponentCount(); j++) {
JCheckBox coreCheckBox = (JCheckBox) coreInterfacePanel
.getComponent(j);
if (coreCheckBox.getText().equals(neededCoreInterface)) {
coreInterfacePosition = j;
coreCheckBox.setSelected(true);
break;
}
}
// Was the core interface found?
if (coreInterfacePosition < 0) {
logger.warn("Warning! " + moteIntfCheckBox.getText()
+ " needs non-existing core interface " + neededCoreInterface
+ " (rescan?)");
}
}
}
}
}
}
/**
* Tries to compile library using current settings.
*/
public void doTestSettings() {
libraryCreatedOK = false;
JPanel progressPanel = new JPanel(new BorderLayout());
final JDialog progressDialog = new JDialog(myDialog, (String) null);
JProgressBar progressBar;
JButton button;
final MessageList taskOutput;
progressDialog.setLocationRelativeTo(myDialog);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
taskOutput = new MessageList();
button = new JButton("Close/Abort");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (compilationThread != null && compilationThread.isAlive()) {
compilationThread.interrupt();
}
if (progressDialog != null && progressDialog.isVisible()) {
progressDialog.dispose();
}
}
});
progressPanel.add(BorderLayout.CENTER, new JScrollPane(taskOutput));
progressPanel.add(BorderLayout.NORTH, progressBar);
progressPanel.add(BorderLayout.SOUTH, button);
progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
progressPanel.setVisible(true);
progressDialog.getContentPane().add(progressPanel);
progressDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
progressDialog.pack();
progressDialog.getRootPane().setDefaultButton(button);
progressDialog.setVisible(true);
// Create temp output directory if not already exists
if (!ContikiMoteType.tempOutputDirectory.exists())
ContikiMoteType.tempOutputDirectory.mkdir();
// Parse selected sensors
Vector<String> sensors = new Vector<String>();
for (Component checkBox : sensorPanel.getComponents()) {
if (((JCheckBox) checkBox).isSelected()) {
sensors.add(((JCheckBox) checkBox).getText());
}
}
// Parse selected core interfaces
Vector<String> coreInterfaces = new Vector<String>();
for (Component checkBox : coreInterfacePanel.getComponents()) {
if (((JCheckBox) checkBox).isSelected()) {
coreInterfaces.add(((JCheckBox) checkBox).getText());
}
}
// Parse selected user processes
Vector<String> userProcesses = new Vector<String>();
for (Component checkBox : processPanel.getComponents()) {
if (((JCheckBox) checkBox).isSelected()) {
userProcesses.add(((JCheckBox) checkBox).getText());
}
}
// Generate main contiki source file
String filename = null;
try {
filename = generateSourceFile(textID.getText(), sensors, coreInterfaces,
userProcesses);
} catch (Exception e) {
libraryCreatedOK = false;
progressBar.setBackground(Color.ORANGE);
progressBar.setString(e.getMessage());
progressBar.setIndeterminate(false);
progressBar.setValue(0);
createButton.setEnabled(libraryCreatedOK);
return;
}
// Test compile shared library
progressBar.setString("..compiling..");
final File contikiDir = new File(textContikiDir.getText());
final String identifier = textID.getText();
File libFile = new File(ContikiMoteType.tempOutputDirectory,
identifier + ContikiMoteType.librarySuffix);
File mapFile = new File(ContikiMoteType.tempOutputDirectory,
identifier + ContikiMoteType.mapSuffix);
File depFile = new File(ContikiMoteType.tempOutputDirectory,
identifier + ContikiMoteType.dependSuffix);
if (libFile.exists()) {
libFile.delete();
}
if (depFile.exists()) {
depFile.delete();
}
if (mapFile.exists()) {
mapFile.delete();
}
compilationThread = new Thread(new Runnable() {
public void run() {
// Add all user platform directories
compilationFiles = (Vector<File>) myGUI
.getUserPlatforms().clone();
compilationFiles.addAll(moteTypeUserPlatforms);
// Add source files from platform configs
String[] projectSourceFiles = newMoteTypeConfig.getStringArrayValue(
ContikiMoteType.class, "C_SOURCES");
for (String projectSourceFile : projectSourceFiles) {
if (!projectSourceFile.equals("")) {
File file = new File(projectSourceFile);
if (file.getParent() != null) {
// Find which user platform added this file
File userPlatform = newMoteTypeConfig.getUserPlatformDefining(
ContikiMoteType.class, "C_SOURCES", projectSourceFile);
if (userPlatform != null) {
// We found a user platform - Add directory
compilationFiles.add(new File(userPlatform.getPath(), file
.getParent()));
}
}
compilationFiles.add(new File(file.getName()));
}
}
// Add selected process source files
for (Component checkBox : processPanel.getComponents()) {
if (((JCheckBox) checkBox).isSelected()) {
String processName = ((JCheckBox) checkBox).getToolTipText();
if (processName != null) {
compilationFiles.add(new File(processName));
}
}
}
compilationSucceded = ContikiMoteTypeDialog.compileLibrary(identifier,
contikiDir, compilationFiles, symbolsCheckBox.isSelected(),
taskOutput.getInputStream(MessageList.NORMAL),
taskOutput.getInputStream(MessageList.ERROR));
}
}, "compilation thread");
compilationThread.start();
while (compilationThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// NOP
}
}
if (!compilationSucceded) {
if (libFile.exists()) {
libFile.delete();
}
if (depFile.exists()) {
depFile.delete();
}
if (mapFile.exists()) {
mapFile.delete();
}
libraryCreatedOK = false;
} else {
libraryCreatedOK = true;
if (!libFile.exists() || !depFile.exists() || !mapFile.exists())
libraryCreatedOK = false;
}
if (libraryCreatedOK) {
progressBar.setBackground(Color.GREEN);
progressBar.setString("compilation succeded");
button.grabFocus();
myDialog.getRootPane().setDefaultButton(createButton);
} else {
progressBar.setBackground(Color.ORANGE);
progressBar.setString("compilation failed");
myDialog.getRootPane().setDefaultButton(testButton);
}
progressBar.setIndeterminate(false);
progressBar.setValue(0);
createButton.setEnabled(libraryCreatedOK);
}
/**
* Generates new source file by reading default source template and replacing
* fields with sensors, core interfaces and processes. Also includes default
* processes from GUI external configuration.
*
* @param id
* Mote type ID (decides name of new source file)
* @param sensors
* Names of sensors
* @param coreInterfaces
* Names of core interfaces
* @param userProcesses
* Names of user processes
* @return New filename
* @throws Exception
* If any error occurs
*/
public static String generateSourceFile(String id, Vector<String> sensors,
Vector<String> coreInterfaces, Vector<String> userProcesses)
throws Exception {
// SENSORS
String sensorString = "";
String externSensorDefs = "";
for (String sensor : sensors) {
if (!sensorString.equals(""))
sensorString += ", ";
sensorString += "&" + sensor;
externSensorDefs += "extern const struct sensors_sensor " + sensor
+ ";\n";
}
if (!sensorString.equals(""))
sensorString = "SENSORS(" + sensorString + ");";
else
sensorString = "SENSORS(NULL);";
// CORE INTERFACES
String interfaceString = "";
String externInterfaceDefs = "";
for (String coreInterface : coreInterfaces) {
if (!interfaceString.equals(""))
interfaceString += ", ";
interfaceString += "&" + coreInterface;
externInterfaceDefs += "SIM_INTERFACE_NAME(" + coreInterface + ");\n";
}
if (!interfaceString.equals(""))
interfaceString = "SIM_INTERFACES(" + interfaceString + ");";
else
interfaceString = "SIM_INTERFACES(NULL);";
// PROCESSES (including any default processes)
String userProcessString = "";
String externProcessDefs = "";
for (String process : userProcesses) {
if (!userProcessString.equals(""))
userProcessString += ", ";
userProcessString += "&" + process;
externProcessDefs += "PROCESS_NAME(" + process + ");\n";
}
String defaultProcessString = "";
String defaultProcesses[] = GUI.getExternalToolsSetting(
"CONTIKI_STANDARD_PROCESSES").split(";");
for (String process : defaultProcesses) {
if (!defaultProcessString.equals(""))
defaultProcessString += ", ";
defaultProcessString += "&" + process;
}
if (userProcessString.equals("")) {
logger
.warn("No application processes specified! Sure you don't want any?");
}
String processString;
if (!defaultProcessString.equals(""))
processString = "PROCINIT(" + defaultProcessString + ");";
else
processString = "PROCINIT(NULL);";
if (!userProcessString.equals(""))
processString += "\nAUTOSTART_PROCESSES(" + userProcessString + ");";
else
processString += "\nAUTOSTART_PROCESSES(NULL);";
// CHECK JNI CLASS AVAILABILITY
String libString = CoreComm.getAvailableClassName();
if (libString == null) {
logger.fatal("No more libraries can be loaded!");
throw new Exception("Maximum number of mote types already exist");
}
// GENERATE NEW FILE
BufferedWriter destFile = null;
BufferedReader sourceFile = null;
String destFilename = null;
try {
Reader reader;
String mainTemplate = GUI
.getExternalToolsSetting("CONTIKI_MAIN_TEMPLATE_FILENAME");
if ((new File(mainTemplate)).exists()) {
reader = new FileReader(mainTemplate);
} else {
InputStream input = ContikiMoteTypeDialog.class
.getResourceAsStream('/' + mainTemplate);
if (input == null) {
throw new FileNotFoundException(mainTemplate + " not found");
}
reader = new InputStreamReader(input);
}
sourceFile = new BufferedReader(reader);
destFilename = ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + id + ".c";
destFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(destFilename)));
// Replace special fields in template
String line;
while ((line = sourceFile.readLine()) != null) {
line = line
.replaceFirst("\\[PROCESS_DEFINITIONS\\]", externProcessDefs);
line = line.replaceFirst("\\[PROCESS_ARRAY\\]", processString);
line = line.replaceFirst("\\[SENSOR_DEFINITIONS\\]", externSensorDefs);
line = line.replaceFirst("\\[SENSOR_ARRAY\\]", sensorString);
line = line.replaceFirst("\\[INTERFACE_DEFINITIONS\\]",
externInterfaceDefs);
line = line.replaceFirst("\\[INTERFACE_ARRAY\\]", interfaceString);
line = line.replaceFirst("\\[CLASS_NAME\\]", libString);
destFile.write(line + "\n");
}
destFile.close();
sourceFile.close();
} catch (Exception e) {
try {
if (destFile != null)
destFile.close();
if (sourceFile != null)
sourceFile.close();
} catch (Exception e2) {
}
// Forward exception
throw e;
}
return destFilename;
}
/**
* Compiles a mote type shared library using the standard Contiki makefile.
*
* @param identifier
* Mote type identifier
* @param contikiDir
* Contiki base directory
* @param sourceFiles
* Source files and directories to include in compilation
* @param includeSymbols
* Generate and include symbols in library file
* @param outputStream
* Output stream from compilation (optional)
* @param errorStream
* Error stream from compilation (optional)
* @return True if compilation succeded, false otherwise
*/
public static boolean compileLibrary(String identifier, File contikiDir,
Vector<File> sourceFiles, boolean includeSymbols, final PrintStream outputStream,
final PrintStream errorStream) {
File libFile = new File(ContikiMoteType.tempOutputDirectory,
identifier + ContikiMoteType.librarySuffix);
File mapFile = new File(ContikiMoteType.tempOutputDirectory,
identifier + ContikiMoteType.mapSuffix);
File depFile = new File(ContikiMoteType.tempOutputDirectory,
identifier + ContikiMoteType.dependSuffix);
// Recheck that contiki path exists
if (!contikiDir.exists()) {
if (errorStream != null)
errorStream.println("Bad Contiki OS path");
logger.fatal("Contiki path does not exist");
return false;
}
if (!contikiDir.isDirectory()) {
if (errorStream != null)
errorStream.println("Bad Contiki OS path");
logger.fatal("Contiki path is not a directory");
return false;
}
if (libFile.exists()) {
if (errorStream != null)
errorStream.println("Bad output filenames");
logger.fatal("Could not overwrite already existing library");
return false;
}
if (CoreComm.hasLibraryFileBeenLoaded(libFile)) {
if (errorStream != null)
errorStream.println("Bad output filenames");
logger
.fatal("A library has already been loaded with the same name before");
return false;
}
if (depFile.exists()) {
if (errorStream != null)
errorStream.println("Bad output filenames");
logger.fatal("Could not overwrite already existing dependency file");
return false;
}
if (mapFile.exists()) {
if (errorStream != null)
errorStream.println("Bad output filenames");
logger.fatal("Could not overwrite already existing map file");
return false;
}
try {
// Let Contiki 2.x regular make file compile
String[] cmd = new String[]{
GUI.getExternalToolsSetting("PATH_MAKE"),
libFile.getPath().replace(File.separatorChar, '/'),
"-f",
contikiDir.getPath().replace(File.separatorChar, '/')
+ "/Makefile.include"};
String sourceDirs = System.getProperty("PROJECTDIRS", "");
String sourceFileNames = "";
String ccFlags = GUI.getExternalToolsSetting("COMPILER_ARGS", "");
for (File sourceFile : sourceFiles) {
if (sourceFile.isDirectory()) {
// Add directory to search path
sourceDirs += " "
+ sourceFile.getPath().replace(File.separatorChar, '/');
ccFlags += " -I"
+ sourceFile.getPath().replace(File.separatorChar, '/');
} else if (sourceFile.isFile()) {
// Add both file name and directory
if (sourceFile.getParent() != null) {
sourceDirs += " "
+ sourceFile.getParent().replace(File.separatorChar, '/');
}
sourceFileNames += " " + sourceFile.getName();
} else {
// Add filename and hope Contiki knows where to find it...
sourceFileNames += " " + sourceFile.getName();
}
}
logger.info("-- Compiling --");
logger.info("Project dirs: " + sourceDirs);
logger.info("Project sources: " + sourceFileNames);
logger.info("Compiler flags: " + ccFlags);
String[] env = new String[]{
"CONTIKI=" + contikiDir.getPath().replace(File.separatorChar, '/'),
"TARGET=cooja", "TYPEID=" + identifier,
"LD_ARGS_1=" + GUI.getExternalToolsSetting("LINKER_ARGS_1", ""),
"LD_ARGS_2=" + GUI.getExternalToolsSetting("LINKER_ARGS_2", ""),
"EXTRA_CC_ARGS=" + ccFlags,
"SYMBOLS=" + (includeSymbols?"1":""),
"CC=" + GUI.getExternalToolsSetting("PATH_C_COMPILER"),
"LD=" + GUI.getExternalToolsSetting("PATH_LINKER"),
"PROJECTDIRS=" + sourceDirs,
"PROJECT_SOURCEFILES=" + sourceFileNames,
"PATH=" + System.getenv("PATH")};
Process p = Runtime.getRuntime().exec(cmd, env, null);
final BufferedReader input = new BufferedReader(new InputStreamReader(p
.getInputStream()));
final BufferedReader err = new BufferedReader(new InputStreamReader(p
.getErrorStream()));
Thread readInput = new Thread(new Runnable() {
public void run() {
String readLine;
try {
while ((readLine = input.readLine()) != null) {
if (outputStream != null && readLine != null)
outputStream.println(readLine);
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read input stream thread");
Thread readError = new Thread(new Runnable() {
public void run() {
String readLine;
try {
while ((readLine = err.readLine()) != null) {
if (errorStream != null && readLine != null)
errorStream.println(readLine);
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read input stream thread");
readInput.start();
readError.start();
while (readInput.isAlive() || readError.isAlive()) {
Thread.sleep(100);
}
input.close();
err.close();
p.waitFor();
if (p.exitValue() != 0) {
logger.fatal("Make file returned error: " + p.exitValue());
return false;
}
} catch (Exception e) {
logger.fatal("Error while compiling library: " + e);
return false;
}
return true;
}
/**
* Scans a directory for sourcefiles which defines a Contiki process.
*
* @param rootDirectory
* Top directory to search in
* @return Process definitions found under rootDirectory, {sourcefile,
* processname}
*/
public static Vector<String[]> scanForProcesses(File rootDirectory) {
if (!rootDirectory.isDirectory()) {
logger.fatal("Not a directory: " + rootDirectory);
return null;
}
if (!rootDirectory.exists()) {
logger.fatal("Does not exist: " + rootDirectory);
return null;
}
Vector<String[]> processes = new Vector<String[]>();
// Scan in rootDirectory
try {
String line;
String cmdString = GUI.getExternalToolsSetting("CMD_GREP_PROCESSES")
+ " '" + rootDirectory.getPath().replace(File.separatorChar, '/')
/**
* Scans a directory and all subdirectories for sourcefiles which defines a
* Contiki sensor.
*
* @param rootDirectory
* Top directory to search in
* @return Sensor definitions found under rootDirectory, {sourcefile,
* sensorname}
*/
public static Vector<String[]> scanForSensors(File rootDirectory) {
if (!rootDirectory.isDirectory()) {
logger.fatal("Not a directory: " + rootDirectory);
return null;
}
if (!rootDirectory.exists()) {
logger.fatal("Does not exist: " + rootDirectory);
return null;
}
Vector<String[]> sensors = new Vector<String[]>();
// Scan in rootDirectory
try {
String line;
String cmdString = GUI.getExternalToolsSetting("CMD_GREP_SENSORS") + " '"
+ rootDirectory.getPath().replace(File.separatorChar, '/') + "'";
Pattern pattern = Pattern.compile(GUI
.getExternalToolsSetting("REGEXP_PARSE_SENSORS"));
String[] cmd = new String[3];
cmd[0] = GUI.getExternalToolsSetting("PATH_SHELL");
cmd[1] = "-c";
cmd[2] = cmdString;
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = input.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
sensors.add(new String[]{matcher.group(1), matcher.group(2)});
}
}
input.close();
BufferedReader err = new BufferedReader(new InputStreamReader(p
.getErrorStream()));
if (err.ready())
logger.warn("Error occured during scan:");
while ((line = err.readLine()) != null) {
logger.warn(line);
}
err.close();
} catch (IOException err) {
logger.fatal("Error while scanning for sensors: " + err);
err.printStackTrace();
} catch (Exception err) {
logger.fatal("Error while scanning for sensors: " + err);
err.printStackTrace();
}
return sensors;
}
/**
* Scans a directory and all subdirectories for sourcefiles which defines a
* COOJA core interface.
*
* @param rootDirectory
* Top directory to search in
* @return Core interface definitions found under rootDirectory, {sourcefile,
* interfacename}
*/
public static Vector<String[]> scanForInterfaces(File rootDirectory) {
if (!rootDirectory.isDirectory()) {
logger.fatal("Not a directory: " + rootDirectory);
return null;
}
if (!rootDirectory.exists()) {
logger.fatal("Does not exist: " + rootDirectory);
return null;
}
Vector<String[]> interfaces = new Vector<String[]>();
// Scan in rootDirectory
try {
String line;
String cmdString = GUI.getExternalToolsSetting("CMD_GREP_INTERFACES")
+ " '" + rootDirectory.getPath().replace(File.separatorChar, '/')
+ "'";
Pattern pattern = Pattern.compile(GUI
.getExternalToolsSetting("REGEXP_PARSE_INTERFACES"));
String[] cmd = new String[3];
cmd[0] = GUI.getExternalToolsSetting("PATH_SHELL");
cmd[1] = "-c";
cmd[2] = cmdString;
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(p
.getInputStream()));
while ((line = input.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
interfaces.add(new String[]{matcher.group(1), matcher.group(2)});
}
}
input.close();
BufferedReader err = new BufferedReader(new InputStreamReader(p
.getErrorStream()));
if (err.ready())
logger.warn("Error occured during scan:");
while ((line = err.readLine()) != null) {
logger.warn(line);
}
err.close();
} catch (IOException err) {
logger.fatal("Error while scanning for interfaces: " + err);
err.printStackTrace();
} catch (Exception err) {
logger.fatal("Error while scanning for interfaces: " + err);
err.printStackTrace();
}
return interfaces;
}
/**
* Scans given file for an autostart expression and returns all process names
* found.
*
* @param sourceFile
* Source file to scan
* @return Autostart process names or null
* @throws FileNotFoundException
* Given file not found
* @throws IOException
* IO Exception
*/
public static Vector<String> parseAutostartProcesses(File sourceFile)
throws FileNotFoundException, IOException {
// Open file for reading
BufferedReader sourceFileReader = new BufferedReader(new FileReader(
sourceFile));
// Find which processes were set to autostart
String line;
String autostartExpression = "^AUTOSTART_PROCESSES([^$]*)$";
Pattern pattern = Pattern.compile(autostartExpression);
Vector<String> foundProcesses = new Vector<String>();
while ((line = sourceFileReader.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
// Parse autostart processes
String[] allProcesses = matcher.group(1).split(",");
for (String autostartProcess : allProcesses) {
foundProcesses.add(autostartProcess.replaceAll("[&; \\(\\)]", ""));
}
}
}
return foundProcesses;
}
private boolean autoSelectDependencyProcesses(String processName,
String sourceFilename, boolean confirmSelection) {
// Locate source file
File sourceFile = new File(textCoreDir.getText(), sourceFilename);
boolean foundFile = sourceFile.exists();
if (!foundFile)
for (File userPlatform : myGUI.getUserPlatforms()) {
sourceFile = new File(userPlatform, sourceFilename);
if (foundFile = sourceFile.exists())
break;
}
if (!foundFile)
for (File userPlatform : moteTypeUserPlatforms) {
sourceFile = new File(userPlatform, sourceFilename);
if (foundFile = sourceFile.exists())
break;
}
if (!foundFile) {
// Die quietly
return false;
}
Vector<String> autostartProcesses = null;
try {
autostartProcesses = parseAutostartProcesses(sourceFile);
} catch (Exception e) {
return false;
}
if (autostartProcesses == null || autostartProcesses.isEmpty()) {
// Die quietly
return true;
}
for (String autostartProcess : autostartProcesses) {
// Does this process already exist?
boolean processAlreadySelected = false;
for (Component checkBox : processPanel.getComponents()) {
JCheckBox checkBox2 = (JCheckBox) checkBox;
String existingProcess = checkBox2.getText();
boolean selected = checkBox2.isSelected();
if (existingProcess.equals(autostartProcess) && selected) {
processAlreadySelected = true;
}
}
if (!processAlreadySelected) {
boolean processShouldBeSelected = false;
if (confirmSelection) {
// Let user choose whether to add process
Object[] options = { "Add", "Cancel" };
String question = "The process " + processName
+ " depends on the following process: " + autostartProcess
+ "\nDo you want to select this as well?";
String title = "Select dependency process?";
int answer = JOptionPane.showOptionDialog(myDialog, question, title,
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
options, options[0]);
if (answer == JOptionPane.YES_OPTION) {
processShouldBeSelected = true;
}
} else {
// Add process
processShouldBeSelected = true;
}
if (processShouldBeSelected) {
// Get checkbox to select
JCheckBox processToSelectCheckBox = null;
for (Component checkBox : processPanel.getComponents()) {
JCheckBox checkBox2 = (JCheckBox) checkBox;
if (checkBox2.getText().equals(autostartProcess)) {
processToSelectCheckBox = checkBox2;
break;
}
}
if (processToSelectCheckBox == null) {
// Create new check box
processToSelectCheckBox = new JCheckBox(autostartProcess, true);
processToSelectCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
processToSelectCheckBox.setActionCommand("process_clicked: "
+ autostartProcess);
processToSelectCheckBox.addActionListener(myEventHandler);
processPanel.add(processToSelectCheckBox);
}
processToSelectCheckBox.setSelected(true);
processPanel.invalidate();
processPanel.revalidate();
}
}
}
return true;
}
private void pathsWereUpdated() {
updateVisualFields();
// Remove all prevously scanned entries
coreInterfacePanel.removeAll();
moteInterfacePanel.removeAll();
processPanel.removeAll();
sensorPanel.removeAll();
coreInterfacePanel.revalidate();
coreInterfacePanel.repaint();
moteInterfacePanel.revalidate();
moteInterfacePanel.repaint();
processPanel.revalidate();
processPanel.repaint();
sensorPanel.revalidate();
sensorPanel.repaint();
createButton.setEnabled(libraryCreatedOK = false);
settingsOK = false;
testButton.setEnabled(settingsOK);
}
private void updateVisualFields() {
settingsOK = true;
// Check for non-unique identifier
textID.setBackground(Color.WHITE);
textID.setToolTipText(null);
for (MoteType otherType : allOtherTypes) {
if (otherType != myMoteType
&& otherType.getIdentifier().equalsIgnoreCase(textID.getText())) {
textID.setBackground(Color.RED);
textID.setToolTipText("Conflicting name - must be unique");
settingsOK = false;
break;
}
}
// Check for non-unique description
textDescription.setBackground(Color.WHITE);
textDescription.setToolTipText(null);
for (MoteType otherType : allOtherTypes) {
if (otherType != myMoteType
&& otherType.getDescription().equals(textDescription.getText())) {
textDescription.setBackground(Color.RED);
textDescription.setToolTipText("Conflicting name - must be unique");
settingsOK = false;
break;
}
}
// Warn if spaces in Contiki path
textContikiDir.setBackground(Color.WHITE);
textContikiDir.setToolTipText(null);
if (textContikiDir.getText().contains(" ")) {
textContikiDir.setBackground(Color.ORANGE);
textContikiDir
.setToolTipText("Compilation may not work correctly with spaced paths");
}
textCoreDir.setText(textContikiDir.getText()
+ GUI.getExternalToolsSetting("PATH_COOJA_CORE_RELATIVE"));
textCoreDir.setBackground(Color.WHITE);
textCoreDir.setToolTipText(null);
if (textCoreDir.getText().contains(" ")) {
textCoreDir.setBackground(Color.ORANGE);
textCoreDir
.setToolTipText("Compilation may not work correctly with spaced paths");
}
// Warn if spaces in a user platform path
textUserPlatforms.setBackground(Color.WHITE);
textUserPlatforms.setToolTipText(null);
for (File userPlatform : moteTypeUserPlatforms) {
if (userPlatform.getPath().contains(" ")) {
textUserPlatforms.setBackground(Color.ORANGE);
textUserPlatforms
.setToolTipText("Compilation may not work correctly with spaced paths");
}
}
// Update output text field
textOutputFiles.setText(ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + textID.getText() + ContikiMoteType.mapSuffix
+ ", " + ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + textID.getText() + ContikiMoteType.librarySuffix
+ ", " + ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + textID.getText() + ContikiMoteType.dependSuffix);
createButton.setEnabled(libraryCreatedOK = false);
testButton.setEnabled(settingsOK);
}
/**
* Scans Contiki base + (optional) user platform for Contiki processes,
* sensors and core interfaces. The new mote type config is recreated every
* time this method is run. If a user platform is specified, it looks for a
* special class config file there, and appends it to the new mote type
* config. By reading that config all available mote interfaces are parsed -
* which will all be selected initially. This method also selects the core
* interfaces needed by the mote interfaces.
*
* Finally any pre-specified processes (via shortcut start) will be selected.
*/
private void rescanDirectories() {
boolean pathErrorFound = false;
// Check that Contiki path is correct
if (!new File(myDialog.textContikiDir.getText()).isDirectory()) {
// Contiki path specified does not exist
textContikiDir.setBackground(Color.RED);
textContikiDir.setToolTipText("Incorrect path");
pathErrorFound = true;
}
// Check that cooja main platform path is correct
if (!new File(myDialog.textCoreDir.getText()).isDirectory()) {
// Cooja main platform specified does not exist
textContikiDir.setBackground(Color.RED);
textContikiDir.setToolTipText("Incorrect path");
textCoreDir.setBackground(Color.RED);
textCoreDir.setToolTipText("Incorrect path");
pathErrorFound = true;
}
// Check that all user platforms are valid
for (File userPlatform : moteTypeUserPlatforms) {
File userPlatformConfig = new File(userPlatform.getPath(),
GUI.PLATFORM_CONFIG_FILENAME);
if (!userPlatformConfig.exists()) {
textUserPlatforms.setBackground(Color.RED);
textUserPlatforms.setToolTipText("Invalid user platform: "
+ userPlatform);
pathErrorFound = true;
}
}
if (pathErrorFound) {
// Remove all prevously scanned entries
coreInterfacePanel.removeAll();
processPanel.removeAll();
sensorPanel.removeAll();
coreInterfacePanel.revalidate();
coreInterfacePanel.repaint();
processPanel.revalidate();
processPanel.repaint();
sensorPanel.revalidate();
sensorPanel.repaint();
testButton.setEnabled(settingsOK = false);
createButton.setEnabled(libraryCreatedOK = false);
return;
}
// Scan for mote interfaces (+ recreate node type class configuration)
myEventHandler.actionPerformed(new ActionEvent(myDialog.createButton,
ActionEvent.ACTION_PERFORMED, "scanmoteinterfaces"));
// Scan for processes
myEventHandler.actionPerformed(new ActionEvent(myDialog.createButton,
ActionEvent.ACTION_PERFORMED, "scanprocesses"));
// Scan for sensors
myDialog.myEventHandler.actionPerformed(new ActionEvent(
myDialog.createButton, ActionEvent.ACTION_PERFORMED, "scansensors"));
// Scan for core interfaces
myDialog.myEventHandler.actionPerformed(new ActionEvent(
myDialog.createButton, ActionEvent.ACTION_PERFORMED,
"scancoreinterfaces"));
// Recheck dependencies between selected mote interfaces and available
// core interfaces
myDialog.myEventHandler.actionPerformed(new ActionEvent(
myDialog.createButton, ActionEvent.ACTION_PERFORMED,
"recheck_interface_dependencies"));
settingsOK = true;
testButton.setEnabled(settingsOK);
}
private class MoteTypeEventHandler
implements
ActionListener,
DocumentListener {
public void insertUpdate(DocumentEvent e) {
if (myDialog.isVisible())
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
pathsWereUpdated();
}
});
}
public void removeUpdate(DocumentEvent e) {
if (myDialog.isVisible())
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
pathsWereUpdated();
}
});
}
public void changedUpdate(DocumentEvent e) {
if (myDialog.isVisible())
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
pathsWereUpdated();
}
});
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("cancel")) {
// Cancel creation of mote type
myMoteType = null;
dispose();
} else if (e.getActionCommand().equals("clean")) {
// Delete any created intermediate files
File objectDir = ContikiMoteType.tempOutputDirectory;
if (objectDir.exists() && objectDir.isDirectory()) {
File[] objectFiles = objectDir.listFiles();
for (File objectFile : objectFiles)
objectFile.delete();
objectDir.delete();
}
} else if (e.getActionCommand().equals("create")) {
// Create mote type and set various data
myMoteType.doInit(textID.getText());
myMoteType.setDescription(textDescription.getText());
myMoteType.setContikiBaseDir(textContikiDir.getText());
myMoteType.setContikiCoreDir(textCoreDir.getText());
myMoteType.setUserPlatformDirs(moteTypeUserPlatforms);
myMoteType.setCompilationFiles(compilationFiles);
myMoteType.setConfig(newMoteTypeConfig);
// Set startup processes
Vector<String> processes = new Vector<String>();
for (Component checkBox : processPanel.getComponents()) {
if (((JCheckBox) checkBox).isSelected()) {
processes.add(((JCheckBox) checkBox).getText());
}
}
myMoteType.setProcesses(processes);
// Set registered sensors
Vector<String> sensors = new Vector<String>();
for (Component checkBox : sensorPanel.getComponents()) {
if (((JCheckBox) checkBox).isSelected()) {
sensors.add(((JCheckBox) checkBox).getText());
}
}
myMoteType.setSensors(sensors);
// Set registered core interfaces
Vector<String> coreInterfaces = new Vector<String>();
for (Component checkBox : coreInterfacePanel.getComponents()) {
if (((JCheckBox) checkBox).isSelected()) {
coreInterfaces.add(((JCheckBox) checkBox).getText());
}
}
myMoteType.setCoreInterfaces(coreInterfaces);
// Set registered mote interfaces
Vector<Class<? extends MoteInterface>> moteInterfaces = new Vector<Class<? extends MoteInterface>>();
for (Component checkBox : moteInterfacePanel.getComponents()) {
JCheckBox interfaceCheckBox = (JCheckBox) checkBox;
if (interfaceCheckBox.isSelected()) {
moteInterfaces
.add((Class<? extends MoteInterface>) interfaceCheckBox
.getClientProperty("class"));
}
}
myMoteType.setMoteInterfaces(moteInterfaces);
// Set "using symbols"
myMoteType.setHasSystemSymbols(symbolsCheckBox.isSelected());
dispose();
} else if (e.getActionCommand().equals("testsettings")) {
testButton.requestFocus();
Thread testSettingsThread = new Thread(new Runnable() {
public void run() {
doTestSettings();
}
}, "test settings thread");
testSettingsThread.start();
} else if (e.getActionCommand().equals("browsecontiki")) {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("."));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setDialogTitle("Contiki OS base directory");
if (fc.showOpenDialog(myDialog) == JFileChooser.APPROVE_OPTION) {
textContikiDir.setText(fc.getSelectedFile().getPath());
}
createButton.setEnabled(libraryCreatedOK = false);
pathsWereUpdated();
} else if (e.getActionCommand().equals("manageuserplatforms")) {
Vector<File> newPlatforms = UserPlatformsDialog.showDialog(
ContikiMoteTypeDialog.this, moteTypeUserPlatforms, myGUI
.getUserPlatforms());
if (newPlatforms != null) {
moteTypeUserPlatforms = newPlatforms;
String userPlatformText = null;
for (File userPlatform : newPlatforms) {
if (userPlatformText == null)
userPlatformText = "'" + userPlatform.getPath() + "'";
else
userPlatformText += " + '" + userPlatform.getPath() + "'";
}
textUserPlatforms.setText(userPlatformText);
createButton.setEnabled(libraryCreatedOK = false);
pathsWereUpdated();
}
} else if (e.getActionCommand().equals("scanprocesses")) {
// Clear process panel
processPanel.removeAll();
Vector<String[]> processes = new Vector<String[]>();
// Scan core platform for processes
processes.addAll(ContikiMoteTypeDialog.scanForProcesses(new File(
textCoreDir.getText())));
// If user platforms exists, scan those too
for (File userPlatform : myGUI.getUserPlatforms()) {
processes
.addAll(ContikiMoteTypeDialog.scanForProcesses(userPlatform));
}
if (moteTypeUserPlatforms != null) {
for (File userPlatform : moteTypeUserPlatforms) {
processes.addAll(ContikiMoteTypeDialog
.scanForProcesses(userPlatform));
}
}
if (processes != null) {
for (String[] processInfo : processes) {
JCheckBox processCheckBox = new JCheckBox(processInfo[1], false);
processCheckBox.setToolTipText(processInfo[0]);
processCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
processCheckBox.setActionCommand("process_clicked: "
+ processInfo[1]);
processCheckBox.addActionListener(myEventHandler);
processPanel.add(processCheckBox);
}
} else {
logger.warn("No processes found during scan");
testButton.setEnabled(settingsOK = false);
}
processPanel.revalidate();
processPanel.repaint();
createButton.setEnabled(libraryCreatedOK = false);
} else if (e.getActionCommand().equals("scansensors")) {
// Clear sensor panel
sensorPanel.removeAll();
Vector<String[]> sensors = new Vector<String[]>();
// Scan core platform for sensors
sensors.addAll(ContikiMoteTypeDialog.scanForSensors(new File(
textCoreDir.getText())));
// If user platforms exists, scan those too
for (File userPlatform : myGUI.getUserPlatforms()) {
sensors.addAll(ContikiMoteTypeDialog.scanForSensors(userPlatform));
}
if (moteTypeUserPlatforms != null) {
for (File userPlatform : moteTypeUserPlatforms) {
sensors.addAll(ContikiMoteTypeDialog.scanForSensors(userPlatform));
}
}
if (sensors != null) {
for (String[] sensorInfo : sensors) {
JCheckBox sensorCheckBox = new JCheckBox(sensorInfo[1], true);
sensorCheckBox.setToolTipText(sensorInfo[0]);
sensorCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
sensorPanel.add(sensorCheckBox);
}
} else {
logger.warn("No sensors found during scan");
testButton.setEnabled(settingsOK = false);
}
sensorPanel.revalidate();
sensorPanel.repaint();
createButton.setEnabled(libraryCreatedOK = false);
} else if (e.getActionCommand().equals("scancoreinterfaces")) {
// Clear core interface panel
coreInterfacePanel.removeAll();
Vector<String[]> interfaces = new Vector<String[]>();
// Scan core platform for core interfaces
interfaces.addAll(ContikiMoteTypeDialog.scanForInterfaces(new File(
textCoreDir.getText())));
// If user platforms exists, scan those too
for (File userPlatform : myGUI.getUserPlatforms()) {
interfaces.addAll(ContikiMoteTypeDialog
.scanForInterfaces(userPlatform));
}
if (moteTypeUserPlatforms != null) {
for (File userPlatform : moteTypeUserPlatforms) {
interfaces.addAll(ContikiMoteTypeDialog
.scanForInterfaces(userPlatform));
}
}
if (interfaces != null) {
for (String[] interfaceInfo : interfaces) {
JCheckBox interfaceCheckBox = new JCheckBox(interfaceInfo[1], false);
interfaceCheckBox.setToolTipText(interfaceInfo[0]);
interfaceCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
coreInterfacePanel.add(interfaceCheckBox);
}
} else {
logger.warn("No core interfaces found during scan");
testButton.setEnabled(settingsOK = false);
}
recheckInterfaceDependencies();
coreInterfacePanel.revalidate();
coreInterfacePanel.repaint();
createButton.setEnabled(libraryCreatedOK = false);
} else if (e.getActionCommand().equals("scanmoteinterfaces")) {
// Clear core interface panel
moteInterfacePanel.removeAll();
// Clone general simulator config
newMoteTypeConfig = myGUI.getPlatformConfig().clone();
// Merge with all user platform configs (if any)
for (File userPlatform : moteTypeUserPlatforms) {
try {
newMoteTypeConfig.appendUserPlatform(userPlatform);
} catch (Exception ex) {
logger.fatal("Error when parsing user platform config: " + ex);
return;
}
}
// Get all mote interfaces available from config
String[] moteInterfaces = newMoteTypeConfig.getStringArrayValue(
ContikiMoteType.class, "MOTE_INTERFACES");
Vector<Class<? extends MoteInterface>> moteIntfClasses = new Vector<Class<? extends MoteInterface>>();
ClassLoader classLoader = myGUI
.createUserPlatformClassLoader(moteTypeUserPlatforms);
// Find and load the mote interface classes
for (String moteInterface : moteInterfaces) {
try {
Class<? extends MoteInterface> newMoteInterfaceClass = classLoader
.loadClass(moteInterface).asSubclass(MoteInterface.class);
moteIntfClasses.add(newMoteInterfaceClass);
// logger.info("Loaded mote interface: " + newMoteInterfaceClass);
} catch (Exception ce) {
logger.warn("Failed to load mote interface: " + moteInterface);
}
}
// Create and add checkboxes for all mote interfaces
if (moteIntfClasses.size() > 0) {
for (Class<? extends MoteInterface> moteIntfClass : moteIntfClasses) {
JCheckBox interfaceCheckBox = new JCheckBox(GUI
.getDescriptionOf(moteIntfClass), true);
interfaceCheckBox.putClientProperty("class", moteIntfClass);
interfaceCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
interfaceCheckBox
.setActionCommand("recheck_interface_dependencies");
interfaceCheckBox.addActionListener(myEventHandler);
moteInterfacePanel.add(interfaceCheckBox);
}
} else {
logger
.warn("Error occured during parsing of mote interfaces (no found)");
testButton.setEnabled(settingsOK = false);
}
moteInterfacePanel.revalidate();
moteInterfacePanel.repaint();
createButton.setEnabled(libraryCreatedOK = false);
} else if (e.getActionCommand().equals("addprocess")) {
String newProcessName = JOptionPane.showInputDialog(myDialog,
"Enter process name");
if (newProcessName != null) {
JCheckBox processCheckBox = new JCheckBox(newProcessName, false);
processCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
processCheckBox.setSelected(true);
processCheckBox
.setActionCommand("process_clicked: " + newProcessName);
processCheckBox.addActionListener(myEventHandler);
processPanel.add(processCheckBox);
processPanel.revalidate();
processPanel.repaint();
}
} else if (e.getActionCommand().equals("addsensor")) {
String newSensorName = JOptionPane.showInputDialog(myDialog,
"Enter sensor name");
if (newSensorName != null) {
JCheckBox sensorCheckBox = new JCheckBox(newSensorName, false);
sensorCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
sensorCheckBox.setSelected(true);
sensorPanel.add(sensorCheckBox);
sensorPanel.revalidate();
sensorPanel.repaint();
}
} else if (e.getActionCommand().equals("addinterface")) {
String newInterfaceName = JOptionPane.showInputDialog(myDialog,
"Enter interface name");
if (newInterfaceName != null) {
JCheckBox interfaceCheckBox = new JCheckBox(newInterfaceName, false);
interfaceCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
interfaceCheckBox.setSelected(true);
coreInterfacePanel.add(interfaceCheckBox);
coreInterfacePanel.revalidate();
coreInterfacePanel.repaint();
}
} else if (e.getActionCommand().equals("recheck_interface_dependencies")) {
recheckInterfaceDependencies();
} else if (e.getActionCommand().startsWith("process_clicked")) {
boolean processWasSelected = false;
String sourceFilename = null;
String processName = e.getActionCommand().split(": ")[1].trim();
// Was the process selected or unselected?
for (Component checkBox : processPanel.getComponents()) {
JCheckBox processCheckbox = (JCheckBox) checkBox;
if (processCheckbox.isSelected()
&& processCheckbox.getText().equals(processName)) {
processWasSelected = true;
sourceFilename = ((JCheckBox) checkBox).getToolTipText();
break;
}
}
if (!processWasSelected || sourceFilename == null)
return;
autoSelectDependencyProcesses(processName, sourceFilename, true);
} else
logger.warn("Unhandled action: " + e.getActionCommand());
createButton.setEnabled(libraryCreatedOK = false);
}
}
}
|
package org.apache.james.transport.mailets;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.james.Constants;
import org.apache.james.core.MailImpl;
import org.apache.james.services.MailServer;
import org.apache.james.services.MailStore;
import org.apache.james.services.SpoolRepository;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.ParseException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.*;
import java.util.*;
public class RemoteDelivery extends GenericMailet implements Runnable {
private SpoolRepository outgoing;
private long delayTime = 21600000; // default is 6*60*60*1000 millis (6 hours)
private int maxRetries = 5; // default number of retries
private long smtpTimeout = 600000; //default number of ms to timeout on smtp delivery
private int deliveryThreadCount = 1; // default number of delivery threads
private String gatewayServer = null; // the server to send all email to
private String gatewayPort = null; //the port of the gateway server to send all email to
private Collection deliveryThreads = new Vector();
private MailServer mailServer;
public void init() throws MessagingException {
try {
if (getInitParameter("delayTime") != null) {
delayTime = Long.parseLong(getInitParameter("delayTime"));
}
} catch (Exception e) {
log("Invalid delayTime setting: " + getInitParameter("delayTime"));
}
try {
if (getInitParameter("maxRetries") != null) {
maxRetries = Integer.parseInt(getInitParameter("maxRetries"));
}
} catch (Exception e) {
log("Invalid maxRetries setting: " + getInitParameter("maxRetries"));
}
try {
if (getInitParameter("timeout") != null) {
smtpTimeout = Integer.parseInt(getInitParameter("timeout"));
}
} catch (Exception e) {
log("Invalid timeout setting: " + getInitParameter("timeout"));
}
gatewayServer = getInitParameter("gateway");
gatewayPort = getInitParameter("gatewayPort");
ComponentManager compMgr = (ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
String outgoingPath = getInitParameter("outgoing");
if (outgoingPath == null) {
outgoingPath = "file:///../var/mail/outgoing";
}
try {
// Instantiate the a MailRepository for outgoing mails
MailStore mailstore = (MailStore) compMgr.lookup("org.apache.james.services.MailStore");
DefaultConfiguration spoolConf
= new DefaultConfiguration("repository", "generated:RemoteDelivery.java");
spoolConf.setAttribute("destinationURL", outgoingPath);
spoolConf.setAttribute("type", "SPOOL");
outgoing = (SpoolRepository) mailstore.select(spoolConf);
} catch (ComponentException cnfe) {
log("Failed to retrieve Store component:" + cnfe.getMessage());
} catch (Exception e) {
log("Failed to retrieve Store component:" + e.getMessage());
}
//Start up a number of threads
try {
deliveryThreadCount = Integer.parseInt(getInitParameter("deliveryThreads"));
} catch (Exception e) {
}
for (int i = 0; i < deliveryThreadCount; i++) {
Thread t = new Thread(this, "Remote delivery thread (" + i + ")");
t.start();
deliveryThreads.add(t);
}
}
private boolean deliver(MailImpl mail, Session session) {
try {
log("attempting to deliver " + mail.getName());
MimeMessage message = mail.getMessage();
//Create an array of the recipients as InternetAddress objects
Collection recipients = mail.getRecipients();
InternetAddress addr[] = new InternetAddress[recipients.size()];
int j = 0;
for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
MailAddress rcpt = (MailAddress)i.next();
addr[j] = rcpt.toInternetAddress();
}
//Figure out which servers to try to send to. This collection
// will hold all the possible target servers
Collection targetServers = null;
if (gatewayServer == null) {
MailAddress rcpt = (MailAddress) recipients.iterator().next();
String host = rcpt.getHost();
//Lookup the possible targets
targetServers = getMailetContext().getMailServers(host);
if (targetServers.size() == 0) {
log("No mail server found for: " + host);
return failMessage(mail, new MessagingException("There are no DNS entries for the hostname " + host + ". I cannot determine where to send this message."), false);
}
} else {
targetServers = new Vector();
targetServers.add(gatewayServer);
}
MessagingException lastError = null;
if (addr.length > 0) {
Iterator i = targetServers.iterator();
while ( i.hasNext()) {
try {
String outgoingmailserver = i.next().toString ();
log("attempting delivery of " + mail.getName() + " to host " + outgoingmailserver + " to " + Arrays.asList(addr));
URLName urlname = new URLName("smtp://" + outgoingmailserver);
Properties props = session.getProperties();
//This was an older version of JavaMail
if (mail.getSender() == null) {
props.put("mail.smtp.user", "<>");
props.put("mail.smtp.from", "<>");
} else {
props.put("mail.smtp.user", mail.getSender().toString());
props.put("mail.smtp.from", mail.getSender().toString());
}
//Many of these properties are only in later JavaMail versions
//"mail.smtp.ehlo" //default true
//"mail.smtp.auth" //default false
//"mail.smtp.dsn.ret" //default to nothing... appended as RET= after MAIL FROM line.
//"mail.smtp.dsn.notify" //default to nothing...appended as NOTIFY= after RCPT TO line.
Transport transport = session.getTransport(urlname);
transport.connect();
transport.sendMessage(message, addr);
transport.close();
log("mail (" + mail.getName() + ") sent successfully to " + outgoingmailserver);
return true;
} catch (MessagingException me) {
//MessagingException are horribly difficult to figure out what actually happened.
log("Exception delivering message (" + mail.getName() + ") - " + me.getMessage());
//Assume it is a permanent exception, or prove ourselves otherwise
boolean permanent = true;
if (me.getNextException() != null && me.getNextException() instanceof java.io.IOException) {
//This is more than likely a temporary failure
//If it's an IO exception with no nested exception, it's probably
// some socket or weird IO related problem.
permanent = false;
}
if (me instanceof SendFailedException) {
SendFailedException sfe = (SendFailedException) me;
//This means there was a partial delivery to certain recipients, so
// whatever caused this exception must have been a permanent error no
// matter what type of exception this was.
if (sfe.getValidSentAddresses() != null && sfe.getValidSentAddresses().length > 0) {
permanent = true;
}
}
//Now take action based on whether this was a permanent or temporary action
if (permanent) {
//If it's permanent, fail immediately.
//Note that this has changed as we have all our logic in the outer block
// for what should happen when we have a delivery failure.
throw me;
} else {
//Record what the last error is and continue the loop in case
// there are other servers we could try.
lastError = me;
continue;
}
}
} // end while
//If we encountered an exception while looping through, send the last exception we got
if (lastError != null) {
throw lastError;
}
} else {
log("no recipients specified... not sure how this could have happened.");
}
} catch (SendFailedException sfe) {
//Would like to log all the types of email addresses
if (sfe.getValidSentAddresses() != null) {
Address[] validSent = sfe.getValidSentAddresses();
Collection recipients = mail.getRecipients();
//Remove these addresses for the recipients
for (int i = 0; i < validSent.length; i++) {
try {
MailAddress addr = new MailAddress(validSent[i].toString());
recipients.remove(addr);
} catch (ParseException pe) {
//ignore once debugging done
pe.printStackTrace();
}
}
}
//The rest of the recipients failed for one reason or another.
//let the fail message handle it like a permanent exception.
return failMessage(mail, sfe, true);
} catch (MessagingException ex) {
//We should do a better job checking this... if the failure is a general
//connect exception, this is less descriptive than more specific SMTP command
//failure... have to lookup and see what are the various Exception
//possibilities
//Unable to deliver message after numerous tries... fail accordingly
return failMessage(mail, ex, false);
}
return true;
}
private boolean failMessage(MailImpl mail, MessagingException ex, boolean permanent) {
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
if (permanent) {
out.print("Permanent");
} else {
out.print("Temporary");
}
out.print(" exception delivering mail (" + mail.getName() + ": ");
ex.printStackTrace(out);
log(sout.toString());
if (!permanent) {
if (!mail.getState().equals(Mail.ERROR)) {
mail.setState(Mail.ERROR);
mail.setErrorMessage("0");
mail.setLastUpdated(new Date());
}
int retries = Integer.parseInt(mail.getErrorMessage());
if (retries < maxRetries) {
log("Storing message " + mail.getName() + " into outgoing after " + retries + " retries");
++retries;
mail.setErrorMessage(retries + "");
mail.setLastUpdated(new Date());
return false;
}
}
bounce(mail, ex);
return true;
}
private void bounce(MailImpl mail, MessagingException ex) {
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
String machine = "[unknown]";
try {
InetAddress me = InetAddress.getLocalHost();
machine = me.getHostName();
} catch(Exception e){
machine = "[address unknown]";
}
out.println("Hi. This is the James mail server at " + machine + ".");
out.println("I'm afraid I wasn't able to deliver your message to the following addresses.");
out.println("This is a permanent error; I've given up. Sorry it didn't work out. Below");
out.println("I include the list of recipients and the reason why I was unable to deliver");
out.println("your message.");
out.println();
for (Iterator i = mail.getRecipients().iterator(); i.hasNext(); ) {
out.println(i.next());
}
if (ex.getNextException() == null) {
out.println(ex.getMessage().trim());
} else {
Exception ex1 = ex.getNextException();
if (ex1 instanceof SendFailedException) {
out.println("Remote mail server told me: " + ex1.getMessage().trim());
} else if (ex1 instanceof UnknownHostException) {
out.println("Unknown host: " + ex1.getMessage().trim());
out.println("This could be a DNS server error, a typo, or a problem with the recipient's mail server.");
} else if (ex1 instanceof ConnectException) {
//Already formatted as "Connection timed out: connect"
out.println(ex1.getMessage().trim());
} else if (ex1 instanceof SocketException) {
out.println("Socket exception: " + ex1.getMessage().trim());
} else {
out.println(ex1.getMessage().trim());
}
}
out.println();
out.println("The original message is attached.");
log("Sending failure message " + mail.getName());
try {
getMailetContext().bounce(mail, sout.toString());
} catch (MessagingException me) {
log("encountered unexpected messaging exception while bouncing message: " + me.getMessage());
} catch (Exception e) {
log("encountered unexpected exception while bouncing message: " + e.getMessage());
}
}
public String getMailetInfo() {
return "RemoteDelivery Mailet";
}
/**
* For this message, we take the list of recipients, organize these into distinct
* servers, and duplicate the message for each of these servers, and then call
* the deliver (messagecontainer) method for each server-specific
* messagecontainer ... that will handle storing it in the outgoing queue if needed.
*
* @param mail org.apache.mailet.Mail
* @return org.apache.mailet.MessageContainer
*/
public void service(Mail genericmail) throws AddressException {
MailImpl mail = (MailImpl)genericmail;
//Do I want to give the internal key, or the message's Message ID
log("Remotely delivering mail " + mail.getName());
Collection recipients = mail.getRecipients();
//Must first organize the recipients into distinct servers (name made case insensitive)
Hashtable targets = new Hashtable();
for (Iterator i = recipients.iterator(); i.hasNext();) {
MailAddress target = (MailAddress)i.next();
String targetServer = target.getHost().toLowerCase();
Collection temp = (Collection)targets.get(targetServer);
if (temp == null) {
temp = new Vector();
targets.put(targetServer, temp);
}
temp.add(target);
}
//We have the recipients organized into distinct servers... put them into the
//delivery store organized like this... this is ultra inefficient I think...
//store the new message containers, organized by server, in the outgoing mail repository
String name = mail.getName();
for (Iterator i = targets.keySet().iterator(); i.hasNext(); ) {
String host = (String) i.next();
Collection rec = (Collection) targets.get(host);
log("sending mail to " + rec + " on host " + host);
mail.setRecipients(rec);
mail.setName(name + "-to-" + host);
outgoing.store(mail);
//Set it to try to deliver (in a separate thread) immediately (triggered by storage)
}
mail.setState(Mail.GHOST);
}
// Need to synchronize to get object monitor for notifyAll()
public synchronized void destroy() {
//Wake up all threads from waiting for an accept
for (Iterator i = deliveryThreads.iterator(); i.hasNext(); ) {
Thread t = (Thread)i.next();
t.interrupt();
}
notifyAll();
}
/**
* Handles checking the outgoing spool for new mail and delivering them if
* there are any
*/
public void run() {
//Checks the pool and delivers a mail message
Properties props = new Properties();
//Not needed for production environment
props.put("mail.debug", "false");
//Prevents problems encountered with 250 OK Messages
props.put("mail.smtp.ehlo", "false");
//Sets timeout on going connections
props.put("mail.smtp.timeout", smtpTimeout + "");
//Set the hostname we'll use as this server
Collection servernames = (Collection) getMailetContext().getAttribute(Constants.SERVER_NAMES);
if (servernames.size() > 0) {
props.put("mail.smtp.localhost", (String) servernames.iterator().next());
}
//If there's a gateway port, we can just set it here
if (gatewayPort != null) {
props.put("mail.smtp.port", gatewayPort);
}
Session session = Session.getInstance(props, null);
while (!Thread.currentThread().interrupted()) {
try {
String key = outgoing.accept(delayTime);
try {
log(Thread.currentThread().getName() + " will process mail " + key);
MailImpl mail = outgoing.retrieve(key);
if (deliver(mail, session)) {
//Message was successfully delivered/fully failed... delete it
outgoing.remove(key);
} else {
//Something happened that will delay delivery. Store any updates
outgoing.store(mail);
}
//Clear the object handle to make sure it recycles this object.
mail = null;
} catch (Exception e) {
// Prevent unexpected exceptions from causing looping by removing
// message from outgoing.
outgoing.remove(key);
throw e;
}
} catch (Exception e) {
log("Exception caught in RemoteDelivery.run(): " + e);
}
}
}
}
|
package com.pspdfkit.vangogh.base;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.animation.Interpolator;
import com.pspdfkit.vangogh.rx.AnimationCompletable;
public class AnimationBuilder {
@NonNull private final View view;
@Nullable private Float alpha;
@Nullable private Float alphaBy;
@Nullable private Float rotation;
@Nullable private Float rotationBy;
@Nullable private Float rotationX;
@Nullable private Float rotationXBy;
@Nullable private Float rotationY;
@Nullable private Float rotationYBy;
@Nullable private Float scaleX;
@Nullable private Float scaleXBy;
@Nullable private Float scaleY;
@Nullable private Float scaleYBy;
@Nullable private Long duration;
@Nullable private Interpolator interpolator;
@Nullable private Long startDelay;
@Nullable private Float translationX;
@Nullable private Float translationXBy;
@Nullable private Float translationY;
@Nullable private Float translationYBy;
@Nullable private Float translationZ;
@Nullable private Float translationZBy;
@Nullable private Float x;
@Nullable private Float xBy;
@Nullable private Float y;
@Nullable private Float yBy;
@Nullable private Float z;
@Nullable private Float zBy;
private AnimationBuilder(@NonNull View view) {
this.view = view;
}
/**
* Creates {@link AnimationBuilder} for the specified view.
* @param view View to be animated.
* @return Instance of {@link AnimationBuilder}.
*/
@NonNull
public static AnimationBuilder forView(@NonNull View view) {
return new AnimationBuilder(view);
}
/**
* Sets view target alpha property.
* @param alpha View target alpha property (from 0f to 1f).
* @return Instance of {@link AnimationBuilder}.
* @see View#setAlpha(float)
*/
@NonNull
public AnimationBuilder alpha(Float alpha) {
this.alpha = alpha;
return this;
}
/**
* Sets view target alpha property change.
* @param alphaBy View target alpha property change, use negative number to fade out.
* The final alpha value will be inside the [0f, 1f] interval.
* @return Instance of {@link AnimationBuilder}.
* @see View#setAlpha(float)
*/
@NonNull
public AnimationBuilder alphaBy(Float alphaBy) {
this.alphaBy = alphaBy;
return this;
}
/**
* Sets view target rotation property.
* @param rotation View target rotation property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setRotation(float)
*/
@NonNull
public AnimationBuilder rotation(Float rotation) {
this.rotation = rotation;
return this;
}
/**
* Sets view target rotation property change.
* @param rotationBy View target rotation property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setRotation(float)
*/
@NonNull
public AnimationBuilder rotationBy(Float rotationBy) {
this.rotationBy = rotationBy;
return this;
}
/**
* Sets view target rotationX property.
* @param rotationX View target rotationX property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setRotationX(float)
*/
@NonNull
public AnimationBuilder rotationX(Float rotationX) {
this.rotationX = rotationX;
return this;
}
/**
* Sets view target rotationX property change.
* @param rotationXBy View target rotationX property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setRotationX(float)
*/
@NonNull
public AnimationBuilder rotationXBy(Float rotationXBy) {
this.rotationXBy = rotationXBy;
return this;
}
/**
* Sets view target rotationY property.
* @param rotationY View target rotationY property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setRotationY(float)
*/
@NonNull
public AnimationBuilder rotationY(Float rotationY) {
this.rotationY = rotationY;
return this;
}
/**
* Sets view target rotationY property change.
* @param rotationYBy View target rotationY property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setRotationY(float)
*/
@NonNull
public AnimationBuilder rotationYBy(Float rotationYBy) {
this.rotationYBy = rotationYBy;
return this;
}
/**
* Sets view target scaleX property.
* @param scaleX View target scaleX property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setScaleX(float)
*/
@NonNull
public AnimationBuilder scaleX(Float scaleX) {
this.scaleX = scaleX;
return this;
}
/**
* Sets view target scaleX property change.
* @param scaleXBy View target scaleX property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setScaleX(float)
*/
@NonNull
public AnimationBuilder scaleXBy(Float scaleXBy) {
this.scaleXBy = scaleXBy;
return this;
}
/**
* Sets view target scaleY property.
* @param scaleY View target scaleY property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setScaleY(float)
*/
@NonNull
public AnimationBuilder scaleY(Float scaleY) {
this.scaleY = scaleY;
return this;
}
/**
* Sets view target scaleY property change.
* @param scaleYBy View target scaleY property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setScaleY(float)
*/
@NonNull
public AnimationBuilder scaleYBy(Float scaleYBy) {
this.scaleYBy = scaleYBy;
return this;
}
/**
* Sets animation duration.
* @param duration Duration of animation in milliseconds.
* @return Instance of {@link AnimationBuilder}.
*/
@NonNull
public AnimationBuilder duration(Long duration) {
this.duration = duration;
return this;
}
/**
* Sets interpolator to be used in this animation.
* @param interpolator Interpolator to be used for time/progress control.
* @return Instance of {@link AnimationBuilder}.
*/
@NonNull
public AnimationBuilder interpolator(Interpolator interpolator) {
this.interpolator = interpolator;
return this;
}
/**
* Sets start delay for the animation.
* @param startDelay Start delay in milliseconds.
* @return Instance of {@link AnimationBuilder}.
*/
@NonNull
public AnimationBuilder startDelay(Long startDelay) {
this.startDelay = startDelay;
return this;
}
/**
* Sets view target translationX property.
* @param translationX View target translationX property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setTranslationX(float)
*/
@NonNull
public AnimationBuilder translationX(Float translationX) {
this.translationX = translationX;
return this;
}
/**
* Sets view target translationX property change.
* @param translationXBy View target translationX property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setTranslationX(float)
*/
@NonNull
public AnimationBuilder translationXBy(Float translationXBy) {
this.translationXBy = translationXBy;
return this;
}
/**
* Sets view target translationY property.
* @param translationY View target translationY property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setTranslationY(float)
*/
@NonNull
public AnimationBuilder translationY(Float translationY) {
this.translationY = translationY;
return this;
}
/**
* Sets view target translationY property change.
* @param translationYBy View target translationY property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setTranslationY(float)
*/
@NonNull
public AnimationBuilder translationYBy(Float translationYBy) {
this.translationYBy = translationYBy;
return this;
}
/**
* Sets view target translationZ property.
* @param translationZ View target translationZ property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setTranslationZ(float)
*/
@NonNull
public AnimationBuilder translationZ(Float translationZ) {
this.translationZ = translationZ;
return this;
}
/**
* Sets view target translationZ property change.
* @param translationZBy View target translationZ property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setTranslationZ(float)
*/
@NonNull
public AnimationBuilder translationZBy(Float translationZBy) {
this.translationZBy = translationZBy;
return this;
}
/**
* Sets view target x property.
* @param x View target x property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setX(float)
*/
@NonNull
public AnimationBuilder x(Float x) {
this.x = x;
return this;
}
/**
* Sets view target x property change.
* @param xBy View target x property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setX(float)
*/
@NonNull
public AnimationBuilder xBy(Float xBy) {
this.xBy = xBy;
return this;
}
/**
* Sets view target y property.
* @param y View target y property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setY(float)
*/
@NonNull
public AnimationBuilder y(Float y) {
this.y = y;
return this;
}
/**
* Sets view target y property change.
* @param yBy View target y property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setY(float)
*/
@NonNull
public AnimationBuilder yBy(Float yBy) {
this.yBy = yBy;
return this;
}
/**
* Sets view target z property.
* @param z View target z property in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setZ(float)
*/
@NonNull
public AnimationBuilder z(Float z) {
this.z = z;
return this;
}
/**
* Sets view target z property change.
* @param zBy View target z property change in degrees.
* @return Instance of {@link AnimationBuilder}.
* @see View#setZ(float)
*/
@NonNull
public AnimationBuilder zBy(Float zBy) {
this.zBy = zBy;
return this;
}
/**
* Build animation from the provided builder parameters.
* @return Animation with parameters set through the builder.
*/
@NonNull
public Animation build() {
return new Animation(view, alpha, alphaBy, rotation, rotationBy, rotationX, rotationXBy, rotationY, rotationYBy,
scaleX, scaleXBy, scaleY, scaleYBy, duration, interpolator, startDelay, translationX, translationXBy,
translationY, translationYBy, translationZ, translationZBy, x, xBy, y, yBy, z, zBy);
}
/**
* Method for directly producing {@link AnimationCompletable}. Just a convenience method
* so you don't have to call <code>.build().toCompletable()</code>.
* @return Completable that will start the specified animation once subscribed to.
*/
@NonNull
public AnimationCompletable buildCompletable() {
return build().toCompletable();
}
}
|
package org.pdxfinder.web.controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.ogm.json.JSONArray;
import org.neo4j.ogm.json.JSONException;
import org.neo4j.ogm.json.JSONObject;
import org.pdxfinder.services.AutoCompleteService;
import org.pdxfinder.services.GraphService;
import org.pdxfinder.services.ds.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;
@Controller
public class SearchController {
private final static Logger logger = LoggerFactory.getLogger(SearchController.class);
private GraphService graphService;
private AutoCompleteService autoCompleteService;
private SearchDS searchDS;
private Map<String, List<String>> facets = new HashMap<>();
List<String> patientAgeOptions = SearchDS.PATIENT_AGE_OPTIONS;
List<String> datasourceOptions = SearchDS.DATASOURCE_OPTIONS;
List<String> cancerBySystemOptions = SearchDS.CANCERS_BY_SYSTEM_OPTIONS;
List<String> patientGenderOptions = SearchDS.PATIENT_GENDERS;
List<String> sampleTumorTypeOptions = SearchDS.SAMPLE_TUMOR_TYPE_OPTIONS;
List<String> diagnosisOptions = SearchDS.DIAGNOSIS_OPTIONS;
public SearchController(GraphService graphService, SearchDS searchDS, AutoCompleteService autoCompleteService) {
this.graphService = graphService;
this.searchDS = searchDS;
this.autoCompleteService = autoCompleteService;
facets.put("datasource_options", datasourceOptions);
facets.put("patient_age_options", patientAgeOptions);
facets.put("patient_gender_options", patientGenderOptions);
facets.put("cancer_system_options", cancerBySystemOptions);
facets.put("sample_tumor_type_options", sampleTumorTypeOptions);
}
@RequestMapping("/search/export")
@ResponseBody
String export(HttpServletResponse response,
@RequestParam("query") Optional<String> query,
@RequestParam("datasource") Optional<List<String>> datasource,
@RequestParam("diagnosis") Optional<List<String>> diagnosis,
@RequestParam("patient_age") Optional<List<String>> patient_age,
@RequestParam("patient_treatment_status") Optional<List<String>> patient_treatment_status,
@RequestParam("patient_gender") Optional<List<String>> patient_gender,
@RequestParam("sample_origin_tissue") Optional<List<String>> sample_origin_tissue,
@RequestParam("cancer_system") Optional<List<String>> cancer_system,
@RequestParam("sample_tumor_type") Optional<List<String>> sample_tumor_type
) {
Map<SearchFacetName, List<String>> configuredFacets = getFacetMap(
query,
datasource,
diagnosis,
patient_age,
patient_treatment_status,
patient_gender,
sample_origin_tissue,
cancer_system,
sample_tumor_type
);
Set<ModelForQuery> results = searchDS.search(configuredFacets);
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper.schemaFor(ModelForQuery.class).withHeader();
String output = "CSV output for configured values " + configuredFacets.toString();
try {
output = mapper.writer(schema).writeValueAsString(results);
} catch (JsonProcessingException e) {
logger.error("Could not convert result set to CSV file. Facetes: {}", configuredFacets.toString(), e);
}
response.setContentType("text/csv;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=pdxfinder_search_export.csv");
return output;
}
@RequestMapping("/search")
String search(Model model,
@RequestParam("query") Optional<String> query,
@RequestParam("datasource") Optional<List<String>> datasource,
@RequestParam("diagnosis") Optional<List<String>> diagnosis,
@RequestParam("patient_age") Optional<List<String>> patient_age,
@RequestParam("patient_treatment_status") Optional<List<String>> patient_treatment_status,
@RequestParam("patient_gender") Optional<List<String>> patient_gender,
@RequestParam("sample_origin_tissue") Optional<List<String>> sample_origin_tissue,
@RequestParam("cancer_system") Optional<List<String>> cancer_system,
@RequestParam("sample_tumor_type") Optional<List<String>> sample_tumor_type,
@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "size", defaultValue = "10") Integer size
) {
Map<SearchFacetName, List<String>> configuredFacets = getFacetMap(
query,
datasource,
diagnosis,
patient_age,
patient_treatment_status,
patient_gender,
sample_origin_tissue,
cancer_system,
sample_tumor_type
);
Set<ModelForQuery> results = searchDS.search(configuredFacets);
List<FacetOption> patientAgeSelected = searchDS.getFacetOptions(SearchFacetName.patient_age, patientAgeOptions, results, patient_age.orElse(null));
List<FacetOption> patientGenderSelected = searchDS.getFacetOptions(SearchFacetName.patient_gender, patientGenderOptions, results, patient_gender.orElse(null));
List<FacetOption> datasourceSelected = searchDS.getFacetOptions(SearchFacetName.datasource, datasourceOptions, results, datasource.orElse(null));
List<FacetOption> cancerSystemSelected = searchDS.getFacetOptions(SearchFacetName.cancer_system, cancerBySystemOptions, results, cancer_system.orElse(null));
List<FacetOption> sampleTumorTypeSelected = searchDS.getFacetOptions(SearchFacetName.sample_tumor_type, sampleTumorTypeOptions, results, sample_tumor_type.orElse(null));
// Only add diagnosisSelected if diagnosis has actually been specified
List<FacetOption> diagnosisSelected = null;
if (diagnosis.isPresent()) {
diagnosisSelected = searchDS.getFacetOptions(SearchFacetName.diagnosis, null, results, diagnosis.orElse(null));
}
// Ensure to add the facet options to this list so the URL encoding retains the configured options
String facetString = getFacetString(
new HashSet<>(
Arrays.asList(
patientAgeSelected,
patientGenderSelected,
datasourceSelected,
cancerSystemSelected,
sampleTumorTypeSelected
)
)
);
// If there is a query, append the query parameter to any configured facet string
if (query.isPresent() && !query.get().isEmpty()) {
facetString = StringUtils.join(Arrays.asList("query=" + query.get(), facetString), "&");
}
// If there is a diagnosis, append the diagnosis parameters to any configured facet string
if (diagnosis.isPresent() && !diagnosis.get().isEmpty()) {
for (String diag : diagnosis.get()) {
facetString = StringUtils.join(Arrays.asList("diagnosis=" + diag, facetString), "&");
}
}
// Num pages is converted to an int using this formula int n = a / b + (a % b == 0) ? 0 : 1;
int numPages = results.size() / size + (results.size() % size == 0 ? 0 : 1);
// If there are no results, default to 1 page (instead of 0 pages)
if (numPages < 1) {
numPages = 1;
}
int current = page;
int begin = Math.max(1, current - 4);
int end = Math.min(begin + 7, numPages);
String textSearchDescription = getTextualDescription(facetString, results);
//auto suggestions for the search field
List<AutoSuggestOption> autoSuggestList = autoCompleteService.getAutoSuggestions();
model.addAttribute("autoCompleteList", autoSuggestList);
model.addAttribute("numPages", numPages);
model.addAttribute("beginIndex", begin);
model.addAttribute("endIndex", end);
model.addAttribute("currentIndex", current);
model.addAttribute("totalResults", results.size());
model.addAttribute("page", page);
model.addAttribute("size", size);
model.addAttribute("facets_string", facetString);
model.addAttribute("text_search_desc", textSearchDescription);
model.addAttribute("patient_age_selected", patientAgeSelected);
model.addAttribute("patient_gender_selected", patientGenderSelected);
model.addAttribute("datasource_selected", datasourceSelected);
model.addAttribute("cancer_system_selected", cancerSystemSelected);
model.addAttribute("sample_tumor_type_selected",sampleTumorTypeSelected);
model.addAttribute("diagnosis_selected", diagnosisSelected);
model.addAttribute("query", query.orElse(""));
model.addAttribute("facet_options", facets);
model.addAttribute("results", new ArrayList<>(results).subList((page - 1) * size, Math.min(((page - 1) * size) + size, results.size())));
return "search";
}
/**
* Get a string representation of all the configured facets
*
* @param allSelectedFacetOptions
* @return
*/
private String getFacetString(Set<List<FacetOption>> allSelectedFacetOptions) {
List<String> pieces = new ArrayList<>();
for (List<FacetOption> facetOptions : allSelectedFacetOptions) {
pieces.add(facetOptions.stream()
.filter(x -> x.getSelected() != null)
.filter(FacetOption::getSelected)
.map(x -> x.getFacetType() + "=" + x.getName())
.collect(Collectors.joining("&")));
}
return pieces.stream().filter(x -> !x.isEmpty()).collect(Collectors.joining("&"));
}
public String getTextualDescription(String facetString, Set<ModelForQuery> results) {
if (StringUtils.isEmpty(facetString)) {
return null;
}
String textDescription = "Your filter for ";
Map<String, Set<String>> filters = new HashMap<>();
for (String urlParams : facetString.split("&")) {
List<String> pieces = Arrays.asList(urlParams.split("="));
String key = pieces.get(0);
String value = pieces.get(1);
if (!filters.containsKey(key)) {
filters.put(key, new TreeSet<>());
}
filters.get(key).add(value);
}
textDescription += StringUtils
.join(filters.keySet()
.stream()
.map(x -> "<b>" + x + ":</b> (" + StringUtils.join(filters.get(x), ", ").replaceAll("\\[", "").replaceAll("\\]", "") + ")")
.collect(Collectors.toList()), ", ");
textDescription += " returned " + results.size() + " result";
textDescription += results.size() == 1 ? "" : "s";
return textDescription;
}
private Map<SearchFacetName, List<String>> getFacetMap(
Optional<String> query,
Optional<List<String>> datasource,
Optional<List<String>> diagnosis,
Optional<List<String>> patientAge,
Optional<List<String>> patientTreatmentStatus,
Optional<List<String>> patientGender,
Optional<List<String>> sampleOriginTissue,
Optional<List<String>> cancerSystem,
Optional<List<String>> sampleTumorType
) {
Map<SearchFacetName, List<String>> configuredFacets = new HashMap<>();
if (query.isPresent() && !query.get().isEmpty()) {
configuredFacets.put(SearchFacetName.query, new ArrayList<>());
configuredFacets.get(SearchFacetName.query).add(query.get());
}
if (datasource.isPresent() && !datasource.get().isEmpty()) {
configuredFacets.put(SearchFacetName.datasource, new ArrayList<>());
for (String s : datasource.get()) {
configuredFacets.get(SearchFacetName.datasource).add(s);
}
}
if (diagnosis.isPresent() && !diagnosis.get().isEmpty()) {
configuredFacets.put(SearchFacetName.diagnosis, new ArrayList<>());
for (String s : diagnosis.get()) {
configuredFacets.get(SearchFacetName.diagnosis).add(s);
}
}
if (patientAge.isPresent() && !patientAge.get().isEmpty()) {
configuredFacets.put(SearchFacetName.patient_age, new ArrayList<>());
for (String s : patientAge.get()) {
configuredFacets.get(SearchFacetName.patient_age).add(s);
}
}
if (patientTreatmentStatus.isPresent() && !patientTreatmentStatus.get().isEmpty()) {
configuredFacets.put(SearchFacetName.patient_treatment_status, new ArrayList<>());
for (String s : patientTreatmentStatus.get()) {
configuredFacets.get(SearchFacetName.patient_treatment_status).add(s);
}
}
if (patientGender.isPresent() && !patientGender.get().isEmpty()) {
configuredFacets.put(SearchFacetName.patient_gender, new ArrayList<>());
for (String s : patientGender.get()) {
configuredFacets.get(SearchFacetName.patient_gender).add(s);
}
}
if (sampleOriginTissue.isPresent() && !sampleOriginTissue.get().isEmpty()) {
configuredFacets.put(SearchFacetName.sample_origin_tissue, new ArrayList<>());
for (String s : sampleOriginTissue.get()) {
configuredFacets.get(SearchFacetName.sample_origin_tissue).add(s);
}
}
if (cancerSystem.isPresent() && !cancerSystem.get().isEmpty()) {
configuredFacets.put(SearchFacetName.cancer_system, new ArrayList<>());
for (String s : cancerSystem.get()) {
configuredFacets.get(SearchFacetName.cancer_system).add(s);
}
}
if (sampleTumorType.isPresent() && !sampleTumorType.get().isEmpty()) {
configuredFacets.put(SearchFacetName.sample_tumor_type, new ArrayList<>());
for (String s : sampleTumorType.get()) {
configuredFacets.get(SearchFacetName.sample_tumor_type).add(s);
}
}
return configuredFacets;
}
@RequestMapping("/search2")
String index(Model model) throws JSONException {
//Cancers by system
JSONArray cancerBySystemDataSeriesArray = new JSONArray();
Map<String, Integer> cancerBySystem = graphService.getModelCountsBySystem();
for (String name : cancerBySystem.keySet()) {
JSONObject dataSeries = new JSONObject();
dataSeries.put("name", name);
dataSeries.put("y", cancerBySystem.get(name));
cancerBySystemDataSeriesArray.put(dataSeries);
}
model.addAttribute("cancerBySystem", cancerBySystemDataSeriesArray.toString());
/**
* Retrieve Mapped NCIT Terms
*
*/
Set<String> autoSuggestList = graphService.getMappedNCITTerms();
model.addAttribute("mappedDOTerm", autoSuggestList);
// Cancers by tissue
JSONArray cancerByTissueDataSeriesArray = new JSONArray();
Map<String, Integer> cancerByTissue = graphService.getModelCountsByTissue();
for (String name : cancerByTissue.keySet()) {
JSONObject dataSeries = new JSONObject();
dataSeries.put("y", cancerByTissue.get(name));
dataSeries.put("name", name);
cancerByTissueDataSeriesArray.put(dataSeries);
}
model.addAttribute("cancerByTissue", cancerByTissueDataSeriesArray.toString());
System.out.println("+++ cancerByTissue" + cancerByTissueDataSeriesArray);
JSONObject dataByCellType = new JSONObject();
/*
Get datasource abbreviations dynamically
*/
List<String> dataSources = graphService.getDataSourceAbbreviations();
model.addAttribute("dataSources", dataSources);
return "search";
}
}
// JSONArray cancerByCellTypeDataSeriesArray = new JSONArray();
// Map<String, Integer> cancerByCellType = graphService.getModelCountsByCellType();
// for (String name : cancerByCellType.keySet()) {
// JSONObject dataSeries = new JSONObject();
// dataSeries.put("name", name);
// dataSeries.put("y", cancerByCellType.get(name));
// cancerByCellTypeDataSeriesArray.put(dataSeries);
// model.addAttribute("cancerByCellType", cancerByCellTypeDataSeriesArray.toString());
// System.out.println("+++ cancerByCellType" + cancerByCellTypeDataSeriesArray);
// The data for producing a highcharts pie chart format
// name: 'IE',
// y: 56.33
// name: 'Chrome',
// y: 24.03
|
package com.intuit.tank.auth;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import com.intuit.tank.util.Messages;
import org.picketlink.Identity;
import org.picketlink.idm.IdentityManager;
import com.intuit.tank.admin.Deleted;
import com.intuit.tank.dao.PreferencesDao;
import com.intuit.tank.dao.UserDao;
import com.intuit.tank.project.Preferences;
import com.intuit.tank.project.User;
import com.intuit.tank.vm.common.PasswordEncoder;
/**
* RequestUser
*
* @author dangleton
*
*/
@Named
@RequestScoped
public class AccountModify implements Serializable {
private static final Logger LOG = LogManager.getLogger(AccountModify.class);
private static final long serialVersionUID = 1L;
@Inject
private Identity identity;
@Inject
private IdentityManager identityManager;
private String passwordConfirm;
private String password;
private boolean succeeded;
private User user;
@Inject
private Messages messages;
@Inject
@Deleted
private Event<Preferences> deletedPrefsEvent;
@PostConstruct
public void init() {
try {
if (identity.isLoggedIn()) {
String loginName = identityManager.lookupById(org.picketlink.idm.model.basic.User.class, identity.getAccount().getId()).getLoginName();
user = new UserDao().findByUserName(loginName);
}
} catch (Exception e) {
LOG.error("Error getting user: " + e, e);
}
}
/**
* @return the passwordConfirm
*/
public String getPasswordConfirm() {
return passwordConfirm;
}
/**
* @return the succeeded
*/
public boolean isSucceeded() {
return succeeded;
}
/**
* @param passwordConfirm
* the passwordConfirm to set
*/
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
/**
*
* @param user
*/
public void resetPreferences() {
try {
PreferencesDao dao = new PreferencesDao();
Preferences prefs = dao.getForOwner(user.getName());
if (prefs != null) {
dao.delete(prefs);
deletedPrefsEvent.fire(prefs);
}
messages.info("Preferences have been reset.");
} catch (HibernateException e) {
LOG.error("Error resetting preferences: " + e, e);
messages.error("Error resetting preferences: " + e);
}
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the user
*/
public User getUser() {
return user;
}
public void generateApiToken() {
if (user.getApiToken() == null) {
user.generateApiToken();
user = new UserDao().saveOrUpdate(user);
}
}
public String save() {
if (user == null) {
messages.error("Cannot find user. Please log in again.");
} else {
if (StringUtils.isNotBlank(password)) {
messages.error("Password is required.");
if (!password.equals(passwordConfirm)) {
messages.error("Passwords do not match.");
return null;
} else {
user.setPassword(PasswordEncoder.encodePassword(passwordConfirm));
}
}
try {
new UserDao().saveOrUpdate(user);
succeeded = true;
messages.info("Your account has been updated.");
} catch (HibernateException e) {
LOG.error("Error saving user: " + e, e);
}
}
return null;
}
}
|
package at.sw2017xp3.regionalo;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import at.sw2017xp3.regionalo.model.Product;
import at.sw2017xp3.regionalo.util.HttpUtils;
import at.sw2017xp3.regionalo.util.JsonObjectMapper;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Arrays;
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayList<View> list_of_elements = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
fillArrayListWithImageButtons();
list_of_elements.addAll(Arrays.asList(
findViewById(R.id.buttonMeat),
findViewById(R.id.buttonVegetables),
findViewById(R.id.buttonFruit),
findViewById(R.id.buttonOthers),
findViewById(R.id.buttonMilk),
findViewById(R.id.buttonCereals),
findViewById(R.id.searchView),
findViewById(R.id.buttonMilk)));
Uri uri = Uri.parse("http://sw-ma-xp3.bplaced.net/MySQLadmin/featured.php");
// .buildUpon()
// .appendQueryParameter("id", "1").build();
new GetProductTask().execute(uri.toString());
for (int i = 0; i < list_of_elements.size(); i++) {
list_of_elements.get(i).setOnClickListener(this);
}
/* LayoutInflater inflater = getLayoutInflater();
LinearLayout inflatedView = (LinearLayout) inflater.inflate(R.layout.product, null);
((TextView) inflatedView.findViewById(R.id.textViewRndProduct1)).setText("Speck");
((TextView) inflatedView.findViewById(R.id.textViewRndProduct2)).setText("2");
((TextView) inflatedView.findViewById(R.id.textViewRndProduct3)).setText("3");
((TextView) inflatedView.findViewById(R.id.textViewRndProduct4)).setText("4");
((TextView) inflatedView.findViewById(R.id.textViewRndProduct5)).setText("5");
LinearLayout inflatedView2 = (LinearLayout) inflater.inflate(R.layout.product, null);
((TextView) inflatedView2.findViewById(R.id.textViewRndProduct1)).setText("Apfel");
((TextView) inflatedView2.findViewById(R.id.textViewRndProduct2)).setText("A");
((TextView) inflatedView2.findViewById(R.id.textViewRndProduct3)).setText("P");
((TextView) inflatedView2.findViewById(R.id.textViewRndProduct3)).setText("F");
((TextView) inflatedView2.findViewById(R.id.textViewRndProduct5)).setText("E");
LinearLayout linearLayoutHome = (LinearLayout) findViewById(R.id.linearLayout_Home_Activity);
linearLayoutHome.addView(inflatedView);
linearLayoutHome.addView(inflatedView2); */
}
private class GetProductTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
return downloadContent(params[0]);
} catch (IOException e) {
return "Unable to retrieve data. URL may be invalid.";
}
}
@Override
protected void onPostExecute(String result) {
try {
JSONArray arr = new JSONArray(result); //featured products
JSONObject mJsonObject = arr.getJSONObject(0);//one product
String allProductNames;
Product p = JsonObjectMapper.CreateProduct(mJsonObject);
LinearLayout linearLayoutHome = (LinearLayout) findViewById(R.id.linearLayout_Home_Activity);
for(int i=0; i<arr.length();i++) {
JSONObject tempJson = (JSONObject) arr.get(i);
LayoutInflater inflater = getLayoutInflater();
LinearLayout inflatedView = (LinearLayout) inflater.inflate(R.layout.product, null);
((TextView) inflatedView.findViewById(R.id.textViewRndProduct1)).setText(tempJson.getString("name"));
//((TextView) inflatedView.findViewById(R.id.textViewRndProduct2)).setText(tempJson.getString("name"));
((TextView) inflatedView.findViewById(R.id.textViewRndProduct3)).setText(tempJson.getString("price"));
((TextView) inflatedView.findViewById(R.id.textViewRndProduct4)).setText(tempJson.getString("quantity"));
((TextView) inflatedView.findViewById(R.id.textViewRndProduct5)).setText(tempJson.getString("unit_Type"));
linearLayoutHome.addView(inflatedView);
}
}
catch (Exception ex) {
}
}
}
private String downloadContent(String myurl) throws IOException {
InputStream is = null;
int length = 10000;
try {
HttpURLConnection conn = HttpUtils.httpGet(myurl);
return HttpUtils.convertInputStreamToString(conn.getInputStream(), length);
} catch (Exception ex) {
return "";
} finally {
if (is != null) {
is.close();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.loginbutton, menu);
return true;
}
@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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.buttonLogin) {
Intent myIntent = new Intent(this, LoginActivity.class);
startActivity(myIntent);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
Intent myIntent = new Intent(this, ProductDetailActivity.class);
startActivity(myIntent);
}
public void fillArrayListWithImageButtons() {
for (int i = 1; i <= 1; i++) {
String rndBtn = "imgButtonRnd" + i;
int idBtn = getResources().getIdentifier(rndBtn, "id", R.class.getPackage().getName());
list_of_elements.add(findViewById(idBtn));
}
}
}
|
package com.afifzafri.studentsdb;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class SearchData extends AppCompatActivity {
// initialize object
DBHelper mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_data);
mydb = new DBHelper(this);
// get intent and data passed
Intent intentPage = getIntent();
String intstudID = intentPage.getStringExtra("STUD_ID");
final EditText sid = (EditText)findViewById(R.id.editSearch);
ImageButton btnSearch = (ImageButton)findViewById(R.id.btnSearch);
ImageButton btnEdit = (ImageButton)findViewById(R.id.btnEdit);
final TextView resID = (TextView)findViewById(R.id.resStudID);
final TextView resName = (TextView)findViewById(R.id.resName);
final TextView resIC = (TextView)findViewById(R.id.resIC);
final TextView resDOB = (TextView)findViewById(R.id.resDOB);
final TextView resAddress = (TextView)findViewById(R.id.resAddress);
final TextView resProgram = (TextView)findViewById(R.id.resProgram);
final TextView resPhone = (TextView)findViewById(R.id.resPhone);
final TextView resEmail = (TextView)findViewById(R.id.resEmail);
// check if intent send an id value, populate the result
if(intstudID != null)
{
sid.setVisibility(View.GONE);
btnSearch.setVisibility(View.GONE);
// access cursor data
Cursor cursor = mydb.searchData(intstudID);
cursor.moveToFirst();
String id = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
String ic = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_IC));
String dob = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DOB));
String address = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ADDRESS));
String program = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PROGRAM));
String phone = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PHONE));
String email = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_EMAIL));
//append all the data
resID.setText(id);
resName.setText(name);
resIC.setText(ic);
resDOB.setText(dob);
resAddress.setText(address);
resProgram.setText(program);
resPhone.setText(phone);
resEmail.setText(email);
// show toast message
Toast.makeText(getApplicationContext(), "Data found",Toast.LENGTH_SHORT).show();
// close cursor
if (!cursor.isClosed()) {
cursor.close();
}
}
// action when search button clicked
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String studid = sid.getText().toString();
// access cursor data
Cursor cursor = mydb.searchData(studid);
cursor.moveToFirst();
// check if cursor return data or not (data found in db or not)
if(cursor.getCount() < 1)
{
// show toast message
Toast.makeText(getApplicationContext(), "No data found",Toast.LENGTH_SHORT).show();
}
else
{
String id = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
String ic = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_IC));
String dob = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DOB));
String address = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ADDRESS));
String program = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PROGRAM));
String phone = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PHONE));
String email = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_EMAIL));
//append all the data
resID.setText(id);
resName.setText(name);
resIC.setText(ic);
resDOB.setText(dob);
resAddress.setText(address);
resProgram.setText(program);
resPhone.setText(phone);
resEmail.setText(email);
// show toast message
Toast.makeText(getApplicationContext(), "Data found",Toast.LENGTH_SHORT).show();
}
// close cursor
if (!cursor.isClosed()) {
cursor.close();
}
}
});
// action when edit button clicked
btnEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String resStudID = resID.getText().toString();
// allow edit only if student id available
if(resStudID != "")
{
// intent to open new activity
Intent intentPage = new Intent(SearchData.this, EditViewData.class);
intentPage.putExtra("STUD_ID",resStudID);
startActivity(intentPage);
}
else
{
// show toast message
Toast.makeText(getApplicationContext(), "No data to edit",Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
package com.dallinc.masstexter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.marvinlabs.widget.floatinglabel.edittext.FloatingLabelEditText;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EditTemplate extends ActionBarActivity {
Boolean disableInsertVariable = true;
int cursor_position = 0;
final String[] variables = new String[]{"date", "time", "first name", "last name", "full name", "custom variable"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_template);
final FloatingLabelEditText bodyInputField = (FloatingLabelEditText) findViewById(R.id.templateBodyInput);
bodyInputField.getInputWidget().setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
disableInsertVariable = !hasFocus;
invalidateOptionsMenu();
}
});
bodyInputField.getInputWidget().addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
ArrayList<Integer[]> variable_indices = getVariableIndices(s.toString());
if(cursorInVariable(start, variable_indices)) {
if(after > count) { // adding characters to the variable name
Toast.makeText(getBaseContext(), "You cannot modify a variable!", Toast.LENGTH_SHORT).show();
} else if(after < count) { // removing characters from the variable name
Toast.makeText(getBaseContext(), "Variable removed", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_edit_template, menu);
menu.findItem(R.id.action_insert_variable).setVisible(!disableInsertVariable);
return true;
}
@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.
int id = item.getItemId();
switch (id) {
case R.id.action_save:
return true;
case R.id.action_insert_variable:
FloatingLabelEditText bodyInputField = (FloatingLabelEditText) findViewById(R.id.templateBodyInput);
cursor_position = bodyInputField.getInputWidget().getSelectionEnd();
selectVariable(bodyInputField.getContext());
return true;
}
return super.onOptionsItemSelected(item);
}
private void insertVariable(String variable) {
FloatingLabelEditText bodyInputField = (FloatingLabelEditText) findViewById(R.id.templateBodyInput);
// variables are inserted with the unique identifying tag: "~!@variable_count%&$"
// This character sequence was chosen arbitrarily in the hope that no one will ever manually enter it.
int counter = 0;
while(bodyInputField.getInputWidgetText().toString().contains("~!@" + variable + "_" + counter + "%&$")) {
counter++;
}
variable = "~!@" + variable + "_" + counter + "%&$";
String new_editable_body = bodyInputField.getInputWidgetText().replace(cursor_position, cursor_position, variable, 0, variable.length()).toString();
System.out.println("variable start position: " + cursor_position);
System.out.println("variable end position: " + (cursor_position+variable.length()));
bodyInputField.setInputWidgetText(new_editable_body);
cursor_position += variable.length();
bodyInputField.getInputWidget().setSelection(cursor_position);
styleEditText();
}
private void styleEditText() {
FloatingLabelEditText bodyInputField = (FloatingLabelEditText) findViewById(R.id.templateBodyInput);
String template_text = bodyInputField.getInputWidgetText().toString();
ArrayList<Integer[]> variable_indices = getVariableIndices(template_text);
SpannableString spanText = new SpannableString(template_text);
for(Integer[] indices : variable_indices) {
spanText.setSpan(new AbsoluteSizeSpan(0), indices[0], indices[0] + 3, 0);
spanText.setSpan(new AbsoluteSizeSpan(0), indices[1]-3, indices[1], 0);
spanText.setSpan(new BackgroundColorSpan(getResources().getColor(R.color.colorPrimaryDark)), indices[0]+3, indices[1]-3, 0);
spanText.setSpan(new ForegroundColorSpan(Color.WHITE), indices[0]+3, indices[1]-3, 0);
}
bodyInputField.setInputWidgetText(spanText, TextView.BufferType.SPANNABLE);
try{
bodyInputField.getInputWidget().setSelection(cursor_position);
} catch(IndexOutOfBoundsException e) {
bodyInputField.getInputWidget().setSelection(bodyInputField.getInputWidgetText().length());
}
}
private ArrayList<Integer[]> getVariableIndices(String text) {
ArrayList<Integer[]> indicesList = new ArrayList<Integer[]>();
Pattern p = Pattern.compile("~!@[a-zA-Z0-9 ]*_\\d+%&\\$");
Matcher m = p.matcher(text);
while (m.find()) {
indicesList.add(new Integer[]{text.indexOf(m.group()), text.indexOf(m.group()) + m.group().length()});
}
return indicesList;
}
private boolean cursorInVariable(int cursor_position, ArrayList<Integer[]> variable_indices) {
for(Integer[] indices : variable_indices) {
if(cursor_position >= indices[0] && cursor_position < indices[1]) {
return true;
}
}
return false;
}
private void selectVariable(final Context context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Insert Variable");
builder.setItems(variables, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int n) {
if(variables[n].equals("custom variable")) {
inputCustomVariable(context);
return;
}
insertVariable(variables[n]);
return;
}
});
builder.create().show();
}
private void inputCustomVariable(final Context context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Insert Variable");
final FloatingLabelEditText customVariable = new FloatingLabelEditText(this);
customVariable.setLabelText("Custom Variable");
customVariable.setLabelColor(getResources().getColor(R.color.colorPrimaryDark));
customVariable.setLabelTextSize(18);
customVariable.setInputWidgetTextSize(18);
customVariable.setPadding(35, 0, 35, 0);
builder.setView(customVariable);
builder.setPositiveButton("Insert", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int n) {
if (customVariable.getInputWidgetText().toString().length() < 1) {
// This should never happen
Toast.makeText(context, "You didn't write a variable name!", Toast.LENGTH_SHORT).show();
return;
}
String var_text = customVariable.getInputWidgetText().toString().replaceAll("[^a-zA-Z0-9 ]","");
if(contains(variables, var_text)) {
Toast.makeText(context, "Input variable cannot be defined as a custom variable", Toast.LENGTH_SHORT).show();
return;
}
insertVariable(var_text);
return;
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int n) {
dialogInterface.dismiss();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
// After show (this is important specially if you have a list, a pager or other view that uses a adapter), clear the flags and set the soft input mode
alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
customVariable.addInputWidgetTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(s.length() > 0);
}
});
}
private boolean contains(String[] vars, String var) {
for(String v : vars) {
if(var.equals(v)) {
return true;
}
}
return false;
}
}
|
package com.riversoft.weixin.app.user;
import static org.junit.Assert.assertNotNull;
import org.junit.Ignore;
import org.junit.Test;
import com.riversoft.weixin.app.base.AppSetting;
/**
* @borball on 11/7/2016.
*/
public class UsersTest {
@Test
@Ignore
public void testCode2Session() {
SessionKey sessionKey = Users.with(new AppSetting("appid", "screctkey"))
.code2Session("011RedXY1NegvX0eLWXY1vVfXY1RedXu");
assertNotNull(sessionKey);
}
}
|
package com.dlka.fireinstaller;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ClipData;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.nononsenseapps.filepicker.FilePickerActivity;
import net.frederico.showtipsview.ShowTipsBuilder;
import net.frederico.showtipsview.ShowTipsView;
import net.frederico.showtipsview.ShowTipsViewInterface;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import cn.pedant.SweetAlert.SweetAlertDialog;
import fr.nicolaspomepuy.discreetapprate.AppRate;
public class MainActivity extends ListActivity implements
OnItemSelectedListener, OnItemClickListener {
public static final String PREFSFILE = "settings2";
public static final String SELECTED = "selected";
private static final String PROPERTY_ID = "App";
private static final String mailtag = BuildConfig.VERSION_NAME;
public String fireip = "";
public boolean debugDisplay = false;
private AdView adView;
public boolean installAPKdirectly = false;
public String encPath = null;
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
static private final String IPV4_REGEX = "(([0-1]?[0-9]{1,2}\\.)|(2[0-4][0-9]\\.)|(25[0-5]\\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))";
static private Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
Drawer drawer = null;
@Override
protected void onCreate(Bundle b) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(b);
setContentView(R.layout.activity_main);
//app drawer
drawer = new DrawerBuilder()
.withActionBarDrawerToggle(false)
.withTranslucentStatusBar(false)
.withSystemUIHidden(false)
.withSelectedItem(-1)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.copy),
new SecondaryDrawerItem().withName(R.string.externalAPK),
new DividerDrawerItem(),
new SecondaryDrawerItem().withName(R.string.mail),
new SecondaryDrawerItem().withName("Help Webpage").withDescription("open in browser"),
new SecondaryDrawerItem().withName(R.string.help),
new SecondaryDrawerItem().withName(R.string.donate),
new DividerDrawerItem(),
new PrimaryDrawerItem().withName(R.string.settings).withDescription("Here you can enter IP-Address.")
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
switch (position) {
case 0: {
dialogBeforeInstall();
break;
}
case 1: {
showFilePicker();
break;
}
case 3: {
sendDeveloperMail();
break;
}
case 4: {
showWebpageHelp();
break;
}
case 5: {
showDialogHelp();
break;
}
case 6: {
showDonationActivity();
break;
}
case 8: {
showPreferences();
break;
}
}
return true; //@TODO change function -> void
}
})
.withActivity(this).build();
//floating action button
findViewById(R.id.multiple_actions).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
drawer.openDrawer();
}
});
ListView listView = getListView();
listView.setOnItemClickListener(this);
Tracker t = (getTracker(
TrackerName.APP_TRACKER));
t.setScreenName("MainView");
t.send(new HitBuilders.AppViewBuilder().build());
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t1 = analytics.newTracker(R.xml.global_tracker);
t.enableExceptionReporting(false);
t1.enableExceptionReporting(false);
LinearLayout layout = (LinearLayout) findViewById(R.id.bannerLayout);
layout.setVisibility(View.INVISIBLE);
if (!BuildConfig.IS_PRO_VERSION) {
// Create the adView.
adView = new AdView(this);
adView.setAdUnitId("ca-app-pub-8761501900041217/6245885681");
adView.setAdSize(AdSize.BANNER);
layout.setVisibility(View.VISIBLE);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("89CADD0B4B609A30ABDCB7ED4E90A8DE")
.addTestDevice("CCCBB7E354C2E6E64DB5A399A77298ED") //current Nexus 4
.addTestDevice("4DA61F48D168C897127AACD506BF35DF") //current Note
.addTestDevice("9190B60D7EC5559B167C1AF6D89D714A") // Nexus 4
//TODO current tablet
.build();
adView.loadAd(adRequest);
} else {
layout.setPadding(0, 0, 0, 0); //free ad-space for donate version
}
//while showing helpdialog we build list in background for ready when user read. //@TODO no helpdialog, so need for loading-dialog here
setListAdapter(new AppAdapter(this, R.layout.app_item,
new ArrayList<SortablePackageInfo>(), R.layout.app_item));
new ListTask(this, R.layout.app_item).execute("");
t1.send(new HitBuilders.AppViewBuilder().build());
SharedPreferences settings = getSharedPreferences(PREFSFILE, 0);
String skipMessage = settings.getString("skipMessage", "NOT checked");
if (!skipMessage.equals("checked"))
showIntroHelp();
}
private void showIntroHelp() {
final ListView listView = getListView();
ShowTipsView showtips = new ShowTipsBuilder(this)
.setTarget(findViewById(R.id.multiple_actions))
.setTitle("Start here")
.setDescription("to open drawer. Then open Settings for entering IP-Address (Networkaddress) of FireTV/FireStick.")
.setDelay(1000)
.build();
final ShowTipsView showtips2 = new ShowTipsBuilder(this)
.setTarget(listView, 100, 150, 200)
.setTitle("select some apps")
.setDescription("from all installed apps or use Sideload-Option in Menu.")
.setDelay(1000)
.build();
final ShowTipsView showtips4 = new ShowTipsBuilder(this)
.setTarget(findViewById(R.id.multiple_actions))
.setTitle("Searching Help?")
.setDescription("Select Help or Help-Webpage from Drawer for more information, like where to find installed apps on Fire-Device, how to know IP-Adress and more.\n" +
"Hope you enjoy my app. Have Fun!\n\nFeeling adventurous? Try Drawer -> Sideloading, push any apk from your phones sd-card.\n\n")
.setDelay(1000)
.build();
showtips.setCallback(new ShowTipsViewInterface() {
@Override
public void gotItClicked() {
showtips2.show(MainActivity.this);
}
});
showtips2.setCallback(new ShowTipsViewInterface() {
@Override
public void gotItClicked() {
showtips4.show(MainActivity.this);
}
});
showtips4.setCallback(new ShowTipsViewInterface() {
@Override
public void gotItClicked() {
SharedPreferences.Editor editor = getSharedPreferences(PREFSFILE, 0).edit();
editor.putString("skipMessage", "checked");
// Commit the edits!
editor.commit();
}
});
showtips.show(this);
}
@Override
public void onDestroy() {
if (!BuildConfig.IS_PRO_VERSION) {
adView.destroy();
}
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
if (!BuildConfig.IS_PRO_VERSION) {
adView.resume();
}
AppRate.with(MainActivity.this).checkAndShow();
}
@Override
public void onPause() {
if (!BuildConfig.IS_PRO_VERSION) {
adView.pause();
}
super.onPause();
SharedPreferences.Editor editor = getSharedPreferences(PREFSFILE, 0).edit();
ListAdapter adapter = getListAdapter();
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
SortablePackageInfo spi = (SortablePackageInfo) adapter.getItem(i);
editor.putBoolean(SELECTED + "." + spi.packageName, spi.selected);
}
editor.commit();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.drawer: {
drawer.openDrawer();
break;
}
case R.id.copy: {
dialogBeforeInstall();
break;
}
case (R.id.deselect_all): {
deselectAllList();
break;
}
case (R.id.item_help): {
showDialogHelp();
break;
}
case (R.id.item_mail): {
sendDeveloperMail();
break;
}
case (R.id.item_donate): {
showDonationActivity();
break;
}
case (R.id.item_settings): {
showPreferences();
break;
}
case (R.id.item_externalAPK): {
showFilePicker();
break;
}
}
return true;
}
private void showPreferences() {
Intent myIntent = new Intent(MainActivity.this, SettingsActivity.class);
MainActivity.this.startActivity(myIntent);
}
private void showDonationActivity() {
Intent myIntent = new Intent(MainActivity.this, DonationsActivity.class);
MainActivity.this.startActivity(myIntent);
}
private void showDialogHelp() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Help Dialog");
Button button = (Button) dialog.findViewById(R.id.Button01);
final CheckBox dontShowAgain = (CheckBox) dialog.findViewById(R.id.checkBox);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String checkBoxResult = "NOT checked";
if (dontShowAgain.isChecked())
checkBoxResult = "checked";
SharedPreferences.Editor editor = getSharedPreferences(PREFSFILE, 0).edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.commit();
dialog.dismiss();
}
});
dialog.show();
}
private void showFilePicker() {
// This always works
Intent i = new Intent(MainActivity.this, FilePickerActivity.class);
// This works if you defined the intent filter
// Intent i = new Intent(Intent.ACTION_GET_CONTENT);
// Set these depending on your use case. These are the defaults.
i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false);
i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE);
// Configure initial directory by specifying a String.
// You could specify a String like "/storage/emulated/0/", but that can
// dangerous. Always use Android's API calls to get paths to the SD-card or
// internal memory.
i.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
startActivityForResult(i, 0);
}
private void sendDeveloperMail() {
StringBuilder buffer;
buffer = new StringBuilder();
buffer.append("mailto:");
buffer.append("feedback@kulsch-it.de");
buffer.append("?subject=");
buffer.append("Fireinstaller" + mailtag);
buffer.append("&body=Please provide Androidversion and Device Model for Bugreport if you know it.");
String uriString = buffer.toString().replace(" ", "%20");
startActivity(Intent.createChooser(new Intent(Intent.ACTION_SENDTO, Uri.parse(uriString)), "Contact Developer"));
}
public void LogToView(String title, String message) {
Log.d(title, message);
}
private void dialogBeforeInstall() {
Map<String, ?> preferences = PreferenceManager.getDefaultSharedPreferences(this).getAll();
fireip = (String) preferences.get("example_text");
if (fireip.isEmpty()) {
Toast.makeText(this, "Target? Fire's IP-Address is empty.", Toast.LENGTH_LONG).show();
showPreferences();
return;
}
if (fireip.equals("192.0.0.0")) {
Toast.makeText(this, "Target? Please enter Fire's IP-Address before.", Toast.LENGTH_LONG).show();
showPreferences();
return;
}
if (isValidIPV4(fireip) == false) {
Toast.makeText(this, "Wrong IP Syntax. Please enter Fire's IP-Address before.", Toast.LENGTH_LONG).show();
showPreferences();
return;
}
new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
.setTitleText("Are you sure?")
.setContentText("Do you want to install at ip " + fireip.toString())
.setCancelText("No,cancel plx!")
.setConfirmText("Yes,do it!")
.showCancelButton(true)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
copyMenuSelect(fireip.toString());
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.show();
}
private void deselectAllList() {
ListAdapter adapter = getListAdapter();
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
SortablePackageInfo spi = (SortablePackageInfo) adapter.getItem(i);
spi.selected = false;
}
((AppAdapter) adapter).notifyDataSetChanged();
}
private void copyMenuSelect(String fireip) {
if ((!isNothingSelected()) || (installAPKdirectly == true)) {
LogToView("Fireinstaller", "IP ausgelesen:" + fireip);
pushFireTv();
} else {
Toast.makeText(this, "no app selected", Toast.LENGTH_LONG).show();
}
}
public void pushFireTv() {
//lets start our long running process Asyncronous Task
new LongRunningTask().execute();
}
public boolean isNothingSelected() {
ListAdapter adapter = getListAdapter();
if (adapter != null) {
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
SortablePackageInfo spi = (SortablePackageInfo) adapter.getItem(i);
if (spi.selected) {
return false;
}
}
}
Toast.makeText(this, R.string.msg_warn_nothing_selected, Toast.LENGTH_LONG)
.show();
return true;
}
@Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
AppAdapter aa = (AppAdapter) getListAdapter();
SortablePackageInfo spi = aa.getItem(position);
spi.selected = !spi.selected;
aa.notifyDataSetChanged();
}
synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID)
: (trackerId == TrackerName.GLOBAL_TRACKER) ? analytics.newTracker(R.xml.global_tracker)
: analytics.newTracker(R.xml.global_tracker);
mTrackers.put(trackerId, t);
}
return mTrackers.get(trackerId);
}
public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.
}
private class LongRunningTask extends AsyncTask<String, String, Void> {
SweetAlertDialog pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.PROGRESS_TYPE);
SweetAlertDialog cDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.PROGRESS_TYPE);
@Override
protected Void doInBackground(String... params) {
Log.d("fireconnector", "doInBackground starting");
// lots of code
publishProgress("Connecting to Fire TV at " + fireip);
Log.e("fireconnector", "0");
//CONNECTING //should work if we call it only once (singleton making)
Log.d("fireconnector", "connecting adb to " + fireip);
Process adb = null;
try {
adb = Runtime.getRuntime().exec("sh");
} catch (IOException e1) {
publishProgress("IOException error e" + e1.toString());
Log.e("fireconnector", "IOException error e " + e1);
}
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String output = "";
if (adb != null) {
outputStream = new DataOutputStream(adb.getOutputStream());
inputStream = new DataInputStream(adb.getInputStream());
} else {
publishProgress("asb == null");
Log.e("fireconnector", "adb == null");
}
try {
if (outputStream != null) {
outputStream.writeBytes("/system/bin/adb" + " connect " + fireip + "\n ");
outputStream.flush();
Log.d("fireconnector", "/system/bin/adb" + " connect " + fireip + "\n ");
int readed = 0;
byte[] buff = new byte[4096];
while (inputStream.available() <= 0) {
try {
Thread.sleep(100); //TODO: does this check every 100ms for output, then continues?
} catch (Exception ex) {
}
}
while (inputStream.available() > 0) {
readed = inputStream.read(buff);
if (readed <= 0) break;
String seg = new String(buff, 0, readed);
output = seg; //result is a string to show in textview
}
publishProgress("adb_output_connect" + output);
} else {
publishProgress("outputStream == null");
Log.e("fireconnector", "outputStream == null");
}
} catch (IOException e1) {
publishProgress("IOException error 1" + e1.toString());
Log.e("fireconnector", "IOException error 1" + e1);
}
//TODO: why we parse everything to string and separate it here, can't we access getListAdapter in onBackground?
ListAdapter adapter = getListAdapter();
int count = adapter.getCount();
publishProgress("connection established at " + fireip + ". Preparing apps to push.");
Log.e("fireconnector", "1");
publishProgress("get packages ready");
Log.e("fireconnector", "2");
if (installAPKdirectly == true) {
if (!(encPath.isEmpty())) {
Log.d("fireconnector", " external install called " + encPath);
publishProgress("Install external APK. " + encPath + " . \n\n" +
" May take long time.\n\n\n" +
"If no progress after some Minutes: Check if IP " + fireip + " is correct on your Fire TV. " +
"If it's wrong, just (force close and) restart this app. " +
"Then open Settings and enter correct IP (see menu: help for more).\n" +
"When this window disappears everything is installed. Thank you for using my app!");
Log.e("fireconnector", "3");
try {
//move apk to fire tv here
//Foreach Entry do and show progress thing:
if (outputStream != null) {
Log.d("fireconnector", "/system/bin/adb install " + encPath + "\n");
outputStream.writeBytes("/system/bin/adb install " + encPath + "\n");
outputStream.flush();
int readed = 0;
byte[] buff = new byte[4096];
while (inputStream.available() > 0) {
readed = inputStream.read(buff);
if (readed <= 0) break;
String seg = new String(buff, 0, readed);
output = seg; //result is a string to show in textview
}
publishProgress("adb_output" + output);
Log.d("adb output directly", output);
} else {
publishProgress("outputStream == null (occurence 2)");
Log.e("fireconnector", "outputStream == null (occurence 2)");
}
} catch (IOException e) {
publishProgress(" IOException error " + e.toString());
Log.e("fireconnector", " IOException error " + e);
}
}
} else {
for (int i = 0; i < count; i++) {
SortablePackageInfo spi = (SortablePackageInfo) adapter.getItem(i);
if (spi.selected) {
Log.d("fireconnector", " ret.append package: " + spi.displayName + ", sourceDir: " + spi.sourceDir);
publishProgress("Install:\"" + spi.displayName + "\" (app number " + (i + 1) + ") from " + spi.sourceDir + " . \n\n" +
" May take long time.\n\n\n" +
"If no progress after some Minutes: Check if IP " + fireip + " is correct on your Fire TV. " +
"If it's wrong, just (force close and) restart this app. " +
"Then open Settings and enter correct IP (see menu: help for more).\n" +
"When this window disappears everything is installed. Thank you for using my app!");
Log.e("fireconnector", "3");
try {
//move apk to fire tv here
//Foreach Entry do and show progress thing:
if (outputStream != null) {
Log.d("fireconnector", "/system/bin/adb install -r " + spi.sourceDir + "\n");
outputStream.writeBytes("/system/bin/adb install -r " + spi.sourceDir + "\n");
outputStream.flush();
int readed = 0;
byte[] buff = new byte[4096];
while (inputStream.available() > 0) {
readed = inputStream.read(buff);
if (readed <= 0) break;
String seg = new String(buff, 0, readed);
output = seg; //result is a string to show in textview
}
publishProgress("adb_output" + output);
Log.d("adb output list", output);
} else {
publishProgress("outputStream == null (occurence 2)");
Log.e("fireconnector", "outputStream == null (occurence 2)");
}
} catch (IOException e) {
publishProgress(" IOException error " + e.toString());
Log.e("fireconnector", " IOException error " + e);
}
}
}
try {
outputStream.writeBytes("exit\n");
outputStream.flush();
} catch (IOException e) {
publishProgress(" IOException error " + e.toString());
Log.e("fireconnector", " IOException error " + e);
}
}//end for loop
//CLOSINGCONNECTION //should work
//TODO better logging with errorcontent too
publishProgress("Waiting... installation running... When finished this Dialog disappears");
Log.e("fireconnector", "closing connections");
//After pushing:
try {
if (outputStream != null) {
Log.d("fireconnector", "closing os");
outputStream.close();
} else {
publishProgress("outputStream closed already ");
Log.e("fireconnector", "outputStream closed already ");
}
if (inputStream != null) {
Log.d("fireconnector", "closing is");
inputStream.close();
} else {
Log.e("fireconnector", "inputStream closed already ");
}
if (adb != null) {
Log.d("fireconnector", "adb waitfor");
adb.waitFor();
Log.d("fireconnector", "adb waitfor finished");
} else {
publishProgress("adb closed already ");
Log.e("fireconnector", "adb closed already ");
}
} catch (IOException e) {
publishProgress("IOException error 2 " + e.toString());
Log.e("fireconnector", "IOException error 2 " + e);
} catch (InterruptedException e) {
publishProgress("InterruptedException error 5 " + e.toString());
Log.e("fireconnector", "InterruptedException error 5 " + e);
}
if (adb != null) {
adb.destroy();
} else {
publishProgress("adb already destroyed ");
Log.e("fireconnector", "adb already destroyed ");
}
//lets call our onProgressUpdate() method which runs on the UI thread
publishProgress("Closing Connections. Installation complete. Thank you!");
Log.e("fireconnector", "100");
return null;
}
@Override
protected void onPreExecute() {
lockScreenOrientation();
pDialog.getProgressHelper().setBarColor(Color.parseColor("#ff9900"));
pDialog.setTitleText("installing on Fire...");
pDialog.setCancelable(false);
pDialog.showCancelButton(true);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setCancelText("Destroy Install-Process!");
pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
cDialog
.setTitleText("Destroy Install-Process!!")
.setContentText("You really sure? ")
.setConfirmText("Yes, sure, kill em, pls")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog cDialog) {
cancel(true);
cDialog.cancel();
}
})
.setCancelText("No, continue Installation")
.changeAlertType(SweetAlertDialog.WARNING_TYPE);
cDialog.show();
}
});
pDialog.show();
}
protected void onProgressUpdate(String... v) {
String passedValues = v[0];
LogToView("fireinstaller", "onProgressUpdate" + " passedValues " + passedValues); //TODO why we used to log v here?
pDialog.setContentText(passedValues);
}
protected void onPostExecute(final Void result) {
installAPKdirectly = false;
//this should be self explanatory
pDialog.setCancelable(true);
pDialog.dismissWithAnimation();
unlockScreenOrientation();
LogToView("fireinstaller", "complete. READY?\n");
AppRate.with(MainActivity.this).checkAndShow();
}
private void lockScreenOrientation() {
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
LogToView("SCREEN_ORIENTATION_PORTRAIT", " calling locking.\n");
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
LogToView("SCREEN_ORIENTATION_LANDSCAPE", " calling locking.\n");
}
}
private void unlockScreenOrientation() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
LogToView("SCREEN_ORIENTATION_SENSOR", " calling unlock.\n");
}
public void onCancelled() {
Log.d("onCancelled", "Killing adb server. Installation canceled :(");
installAPKdirectly = false;
Log.d("onCancelled", "this should not happen...\n");
Process adb2 = null;
try {
adb2 = Runtime.getRuntime().exec("sh");
} catch (IOException e1) {
Log.e("fireconnector", "IOException error e " + e1);
}
DataOutputStream outputStream2 = null;
if (adb2 != null) {
outputStream2 = new DataOutputStream(adb2.getOutputStream());
} else {
Log.e("fireconnector", "adb == null");
}
try {
if (outputStream2 != null) {
outputStream2.writeBytes("/system/bin/adb kill-server" + "\n ");
outputStream2.flush();
Log.d("fireconnector", "/system/bin/adb kill-server" + "\n ");
}
} catch (IOException e) {
Log.e("fireconnector", " IOException error " + e);
}
Log.d("onCancelled", "Closing Connections. Installation canceled :(");
try {
if (outputStream2 != null) {
outputStream2.close();
} else {
Log.e("fireconnector", "outputStream closed already ");
}
if (adb2 != null) {
adb2.waitFor();
} else {
Log.e("fireconnector", "adb closed already ");
}
} catch (IOException e) {
Log.e("fireconnector", "IOException error 2 " + e);
} catch (InterruptedException e) {
Log.e("fireconnector", "InterruptedException error 5 " + e);
}
if (adb2 != null) {
adb2.destroy();
} else {
Log.e("fireconnector", "adb already destroyed ");
}
cancel(true);
//TODO stop installertask
pDialog.setCancelable(true);
pDialog.dismissWithAnimation();
unlockScreenOrientation();
Log.d("onCancel", "finished");
}
}
public void installAPK(String sourceFile) {
if (sourceFile.endsWith(".apk")) {
encPath = sourceFile;
installAPKdirectly = true;
dialogBeforeInstall();
} else {
Toast.makeText(this, "Please select only files with .apk ending", Toast.LENGTH_LONG).show();
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
// For JellyBean and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
ClipData clip = data.getClipData();
if (clip != null) {
for (int i = 0; i < clip.getItemCount(); i++) {
Uri uri = clip.getItemAt(i).getUri();
Log.d("filepickerdebug1", uri.getEncodedPath());
installAPK(uri.getEncodedPath());
}
}
// For Ice Cream Sandwich
} else {
ArrayList<String> paths = data.getStringArrayListExtra
(FilePickerActivity.EXTRA_PATHS);
if (paths != null) {
for (String path : paths) {
Uri uri = Uri.parse(path);
Log.d("filepickerdebug2", uri.getEncodedPath());
installAPK(uri.getEncodedPath());
}
}
}
} else {
Uri uri = data.getData();
Log.d("filepickerdebug3", uri.getEncodedPath());
installAPK(uri.getEncodedPath());
}
}
}
public static boolean isValidIPV4(final String s) {
return IPV4_PATTERN.matcher(s).matches();
}
public void showWebpageHelp() {
String url = "https://kulsch-it.blogspot.de/2015/10/sideloading-firetvfirestick.html";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
|
package com.dpanayotov.gameoflife.life;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.SurfaceHolder;
import com.dpanayotov.gameoflife.life.di.SyncHandlerWrapper;
import com.dpanayotov.gameoflife.life.di.AsyncHandlerWrapper;
import com.dpanayotov.gameoflife.preferences.Preferences;
import com.dpanayotov.gameoflife.util.Resolution;
import java.util.ArrayList;
import java.util.List;
public class Life {
private List<Grid> queue;
private Grid grid;
private Grid previousGrid;
public Grid summedGrid;
private Boolean destroyed = false;
private int screenWidth;
private int screenHeight;
private SurfaceHolder surfaceHolder;
private Resolution resolution;
private int halfCell;
private int tickRate;
private boolean isometricProjection;
private boolean highlife;
private int initialPopulationDensity;
private int minPopulationDensity;
private int minPopulationCount;
private final Runnable drawRunnable = new Runnable() {
@Override
public void run() {
synchronized (destroyed) {
if (!destroyed) {
update();
handlerWrapper.get().postDelayed(drawRunnable, tickRate);
}
}
}
};
private SyncHandlerWrapper handlerWrapper;
private Paint primaryPaint = new Paint(),
secondaryPaint = new Paint(),
backgroundPaint = new Paint();
public Life(int screenWidth, int screenHeight, SurfaceHolder surfaceHolder, boolean preview) {
handlerWrapper = preview ? new AsyncHandlerWrapper() : new SyncHandlerWrapper();
handlerWrapper.init();
initPaint(Preferences.getColor(Preferences.Colors.PRIMARY), primaryPaint);
initPaint(Preferences.getColor(Preferences.Colors.SECONDARY), secondaryPaint);
initPaint(Preferences.getColor(Preferences.Colors.BACKGROUND), backgroundPaint);
getPreferences();
this.screenWidth = (int) ceil(screenWidth, resolution.cellSize);
this.screenHeight = (int) ceil(screenHeight, resolution.cellSize);
this.surfaceHolder = surfaceHolder;
resolution.gridWidth = this.screenWidth / resolution.cellSize;
resolution.gridHeight = this.screenHeight / resolution.cellSize;
minPopulationCount = Math.round(resolution.gridWidth * resolution.gridHeight *
(minPopulationDensity / 100f));
reset();
}
private void initPaint(int color, Paint paint) {
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
}
public void update() {
Grid nextGrid = grid.deriveNextState(highlife);
if (nextGrid.populationCount < minPopulationCount || previousGrid.equals(nextGrid)) {
reset();
drawRestart();
} else {
queue.add(0, new Grid(grid));
queue.remove(queue.size() - 1);
previousGrid = grid;
grid = new Grid(nextGrid);
summedGrid = new Grid(grid);
for (int i = 0; i < resolution.gridWidth; i++) {
for (int j = 0; j < resolution.gridHeight; j++) {
if (summedGrid.cells[i][j] == 0) {
for (int k = 0; k < Constants.QUEUE_SIZE; k++) {
if (queue.get(k).cells[i][j] == 1) {
summedGrid.cells[i][j] = k + 2;
break;
}
}
}
}
}
draw();
}
}
private void resetQueue() {
queue = new ArrayList<>();
for (int i = 0; i < Constants.QUEUE_SIZE; i++) {
queue.add(new Grid(resolution.gridWidth, resolution.gridHeight, 0));
}
}
private void reset() {
previousGrid = new Grid(resolution.gridWidth, resolution.gridHeight, 0);
grid = new Grid(resolution.gridWidth, resolution.gridHeight, initialPopulationDensity);
resetQueue();
}
private void getPreferences() {
resolution = Preferences.getResolutions().get(Preferences.getResolution());
halfCell = resolution.cellSize / 2;
tickRate = Preferences.getTickRates().get(Preferences.getTickRate());
isometricProjection = Preferences.getIsometricProjection();
highlife = Preferences.getHighlife();
minPopulationDensity = Preferences.getMinPopulationDensityOptions().get(Preferences
.getMinPopulationDensity());
initialPopulationDensity = Preferences.getInitialPopulationDensityOptions().get
(Preferences.getInitialPopulationDensity());
}
private void drawRestart() {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
canvas.drawRect(0, 0, screenWidth, screenHeight, backgroundPaint);
}
} finally {
if (canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void draw() {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
if (canvas != null) {
canvas.drawRect(0, 0, screenWidth, screenHeight, backgroundPaint);
for (int i = 0; i < resolution.gridWidth; i++) {
for (int j = 0; j < resolution.gridHeight; j++) {
if (summedGrid.cells[i][j] > 0) {
int cellX = i * resolution.cellSize + halfCell;
int cellY = j * resolution.cellSize + halfCell;
if (isometricProjection) {
cellY = (cellY + i * halfCell) % screenHeight;
}
drawCell(cellX, cellY, summedGrid.cells[i][j], canvas);
}
}
}
//The last cell of every odd column should be duplicated on top of the screen.
// This way half of the cell is displayed on top and half - on bottom.
if (isometricProjection) {
int j, value;
Log.d("zxc", "resolution.gridHeight "+resolution.gridHeight);
for (int i = 1; i < resolution.gridWidth; i += 2) {
j = resolution.gridHeight - 1 - ((i - 1) / 2);
value = summedGrid.cells[i][j];
if (value > 0) {
int cellX = i * resolution.cellSize + halfCell;
int cellY = j * resolution.cellSize + halfCell;
cellY = (cellY + i * halfCell);
drawCell(cellX, cellY, value, canvas);
}
}
}
}
} finally {
if (canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void drawCell(int x, int y, int value, Canvas canvas) {
secondaryPaint.setAlpha((int) (255 * (1 / (float) value)));
int radius = (halfCell - Constants.CELL_PADDING) - Constants
.RADIUS_STEP * (value - 1);
if (value > 1) {
canvas.drawCircle(x, y, radius, secondaryPaint);
} else {
canvas.drawCircle(x, y, radius, primaryPaint);
}
}
public void start() {
synchronized (destroyed) {
if (!destroyed) {
handlerWrapper.get().post(drawRunnable);
}
}
}
public void stop() {
synchronized (destroyed) {
if (!destroyed) {
handlerWrapper.get().removeCallbacks(drawRunnable);
}
}
}
public static double ceil(double input, double step) {
return Math.ceil(input / step) * step;
}
public void destroy() {
synchronized (destroyed) {
stop();
handlerWrapper.destroy();
destroyed = true;
}
}
}
|
package com.nikita.recipiesapp.common;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
import com.nikita.recipiesapp.BuildConfig;
import com.nikita.recipiesapp.common.utils.Check;
public final class Store<State> {
private final MutableLiveData<State> liveData = new MutableLiveData<>();
private final Reducer<State> reducer;
private final Consumer<Action> actionConsumer;
public Store(@NonNull Reducer<State> reducer, @NonNull State initialState) {
this.reducer = reducer;
liveData.setValue(initialState);
this.actionConsumer = this.getStoreConsumer();
}
public Store(@NonNull Reducer<State> reducer, @NonNull Middleware<State>[] middlewares, @NonNull State initialState) {
this.reducer = reducer;
liveData.setValue(initialState);
this.actionConsumer = combineMiddlewares(this, middlewares);
}
@NonNull
public State getState() {
State state = liveData.getValue();
Check.notNull(state);
return state;
}
public <Subscriber extends LifecycleOwner & Renderer<State>> void subscribe(final Subscriber subscriber) {
if (BuildConfig.IS_UI_TESTING) return;
liveData.observe(subscriber, state -> {
Check.notNull(state);
subscriber.render(state);
});
}
public void dispatch(Action action) {
if (BuildConfig.IS_UI_TESTING) return;
actionConsumer.consume(action);
}
private Consumer<Action> getStoreConsumer() {
return action -> liveData.setValue(reducer.reduce(getState(), action));
}
public static class ReducerCombiner<State> implements Reducer<State> {
private final Reducer<State>[] reducers;
public ReducerCombiner(Reducer<State>[] reducers) {
this.reducers = reducers;
}
@NonNull
@Override
public State reduce(@NonNull State previousState, @NonNull Action action) {
State state = previousState;
for (Reducer<State> reducer : reducers) {
state = reducer.reduce(state, action);
}
return state;
}
}
private static <State> Consumer<Action> combineMiddlewares(Store<State> store, Middleware<State>[] middlewares) {
Consumer<Action> currentConsumer = store.getStoreConsumer();
for (Middleware<State> middleware : middlewares) {
middleware.init(store, currentConsumer);
currentConsumer = middleware;
}
return currentConsumer;
}
}
|
package com.samourai.wallet;
import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnticipateInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import org.apache.commons.lang3.tuple.Triple;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.DumpedPrivateKey;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.TransactionWitness;
import org.bitcoinj.crypto.BIP38PrivateKey;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.script.Script;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import com.samourai.wallet.JSONRPC.JSONRPC;
import com.samourai.wallet.JSONRPC.PoW;
import com.samourai.wallet.JSONRPC.TrustedNodeUtil;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.api.Tx;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.bip47.paynym.ClaimPayNymActivity;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.bip69.BIP69OutputComparator;
import com.samourai.wallet.crypto.AESUtil;
import com.samourai.wallet.crypto.DecryptionException;
import com.samourai.wallet.hd.HD_Address;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.permissions.PermissionsUtil;
import com.samourai.wallet.ricochet.RicochetActivity;
import com.samourai.wallet.ricochet.RicochetMeta;
import com.samourai.wallet.segwit.BIP49Util;
import com.samourai.wallet.segwit.BIP84Util;
import com.samourai.wallet.segwit.SegwitAddress;
import com.samourai.wallet.segwit.bech32.Bech32Util;
import com.samourai.wallet.send.BlockedUTXO;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionInput;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.PushTx;
import com.samourai.wallet.send.RBFSpend;
import com.samourai.wallet.send.RBFUtil;
import com.samourai.wallet.send.SendFactory;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.SweepUtil;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.send.boost.CPFPTask;
import com.samourai.wallet.send.boost.RBFTask;
import com.samourai.wallet.service.RefreshService;
import com.samourai.wallet.service.WebSocketService;
import com.samourai.wallet.spend.SendActivity;
import com.samourai.wallet.tx.TxDetailsActivity;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.BlockExplorerUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.DateUtil;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.MessageSignUtil;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.PrivKeyReader;
import com.samourai.wallet.util.TimeOutUtil;
import com.samourai.wallet.util.TorUtil;
import com.samourai.wallet.util.TypefaceUtil;
import org.bitcoinj.script.ScriptBuilder;
import org.bouncycastle.util.encoders.DecoderException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.bouncycastle.util.encoders.Hex;
import net.i2p.android.ext.floatingactionbutton.FloatingActionButton;
import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.yanzhenjie.zbar.Symbol;
import java.io.IOException;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import info.guardianproject.netcipher.proxy.OrbotHelper;
public class BalanceActivity extends Activity {
private final static int SCAN_COLD_STORAGE = 2011;
private final static int SCAN_QR = 2012;
private LinearLayout layoutAlert = null;
private LinearLayout tvBalanceBar = null;
private TextView tvBalanceAmount = null;
private TextView tvBalanceUnits = null;
private ListView txList = null;
private List<Tx> txs = null;
private HashMap<String, Boolean> txStates = null;
private TransactionAdapter txAdapter = null;
private SwipeRefreshLayout swipeRefreshLayout = null;
private FloatingActionsMenu ibQuickSend = null;
private FloatingActionButton actionReceive = null;
private FloatingActionButton actionSend = null;
private FloatingActionButton actionBIP47 = null;
private boolean isBTC = true;
private PoWTask powTask = null;
private RicochetQueueTask ricochetQueueTask = null;
private ProgressDialog progress = null;
public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
if (ACTION_INTENT.equals(intent.getAction())) {
final boolean notifTx = intent.getBooleanExtra("notifTx", false);
final boolean fetch = intent.getBooleanExtra("fetch", false);
final String rbfHash;
final String blkHash;
if (intent.hasExtra("rbf")) {
rbfHash = intent.getStringExtra("rbf");
} else {
rbfHash = null;
}
if (intent.hasExtra("hash")) {
blkHash = intent.getStringExtra("hash");
} else {
blkHash = null;
}
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
refreshTx(notifTx, false, false);
if (BalanceActivity.this != null) {
if (rbfHash != null) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming))
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doExplorerView(rbfHash);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
}
}
});
if (BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) {
// BalanceActivity.this.runOnUiThread(new Runnable() {
// @Override
handler.post(new Runnable() {
public void run() {
if (powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
powTask = new PoWTask();
powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash);
}
}
});
}
}
}
};
public static final String DISPLAY_INTENT = "com.samourai.wallet.BalanceFragment.DISPLAY";
protected BroadcastReceiver receiverDisplay = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
if (DISPLAY_INTENT.equals(intent.getAction())) {
updateDisplay();
List<UTXO> utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false);
for (UTXO utxo : utxos) {
List<MyTransactionOutPoint> outpoints = utxo.getOutpoints();
for (MyTransactionOutPoint out : outpoints) {
byte[] scriptBytes = out.getScriptBytes();
String address = null;
try {
if (Bech32Util.getInstance().isBech32Script(Hex.toHexString(scriptBytes))) {
address = Bech32Util.getInstance().getAddressFromScript(Hex.toHexString(scriptBytes));
} else {
address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
} catch (Exception e) {
;
}
String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address);
if (path != null && path.startsWith("M/1/")) {
continue;
}
final String hash = out.getHash().toString();
final int idx = out.getTxOutputN();
final long amount = out.getValue().longValue();
if (amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD &&
!BlockedUTXO.getInstance().contains(hash, idx) &&
!BlockedUTXO.getInstance().containsNotDusted(hash, idx)) {
// BalanceActivity.this.runOnUiThread(new Runnable() {
// @Override
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
String message = BalanceActivity.this.getString(R.string.dusting_attempt);
message += "\n\n";
message += BalanceActivity.this.getString(R.string.dusting_attempt_amount);
message += " ";
message += Coin.valueOf(amount).toPlainString();
message += " BTC\n";
message += BalanceActivity.this.getString(R.string.dusting_attempt_id);
message += " ";
message += hash + "-" + idx;
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.dusting_tx)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
BlockedUTXO.getInstance().add(hash, idx, amount);
}
}).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
BlockedUTXO.getInstance().addNotDusted(hash, idx);
}
});
if (!isFinishing()) {
dlg.show();
}
}
});
}
}
}
}
}
};
protected BroadcastReceiver torStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("BalanceActivity", "torStatusReceiver onReceive()");
if (OrbotHelper.ACTION_STATUS.equals(intent.getAction())) {
boolean enabled = (intent.getStringExtra(OrbotHelper.EXTRA_STATUS).equals(OrbotHelper.STATUS_ON));
Log.i("BalanceActivity", "status:" + enabled);
TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(enabled);
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
makePaynymAvatarcache();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (SamouraiWallet.getInstance().isTestNet()) {
setTitle(getText(R.string.app_name) + ":" + "TestNet");
}
LayoutInflater inflator = BalanceActivity.this.getLayoutInflater();
tvBalanceBar = (LinearLayout) inflator.inflate(R.layout.balance_layout, null);
tvBalanceBar.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (isBTC) {
isBTC = false;
} else {
isBTC = true;
}
displayBalance();
txAdapter.notifyDataSetChanged();
return false;
}
});
tvBalanceAmount = (TextView) tvBalanceBar.findViewById(R.id.BalanceAmount);
tvBalanceUnits = (TextView) tvBalanceBar.findViewById(R.id.BalanceUnits);
ibQuickSend = (FloatingActionsMenu) findViewById(R.id.wallet_menu);
actionSend = (FloatingActionButton) findViewById(R.id.send);
actionSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("via_menu", true);
startActivity(intent);
}
});
actionReceive = (FloatingActionButton) findViewById(R.id.receive);
actionReceive.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
try {
HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get();
if (hdw != null) {
Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class);
startActivity(intent);
}
} catch (IOException | MnemonicException.MnemonicLengthException e) {
;
}
}
});
actionBIP47 = (FloatingActionButton) findViewById(R.id.bip47);
actionBIP47.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class);
startActivity(intent);
}
});
txs = new ArrayList<Tx>();
txStates = new HashMap<String, Boolean>();
txList = (ListView) findViewById(R.id.txList);
txAdapter = new TransactionAdapter();
txList.setAdapter(txAdapter);
txList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
if (position == 0) {
return;
}
long viewId = view.getId();
View v = (View) view.getParent();
final Tx tx = txs.get(position - 1);
ImageView ivTxStatus = (ImageView) v.findViewById(R.id.TransactionStatus);
TextView tvConfirmationCount = (TextView) v.findViewById(R.id.ConfirmationCount);
if (viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) {
if (txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) {
txStates.put(tx.getHash(), false);
displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
} else {
txStates.put(tx.getHash(), true);
displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
}
} else {
doExplorerView(tx);
}
}
});
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().post(new Runnable() {
@Override
public void run() {
refreshTx(false, true, false);
swipeRefreshLayout.setRefreshing(false);
}
});
}
});
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
IntentFilter filterDisplay = new IntentFilter(DISPLAY_INTENT);
LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiverDisplay, filterDisplay);
// TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false);
registerReceiver(torStatusReceiver, new IntentFilter(OrbotHelper.ACTION_STATUS));
if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || !PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.READ_WRITE_EXTERNAL_PERMISSION_CODE);
}
if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.CAMERA)) {
PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.CAMERA_PERMISSION_CODE);
}
if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false) == false) {
doFeaturePayNymUpdate();
} else if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == false &&
PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false) == false) {
doClaimPayNym();
} else {
;
}
if(RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {
if (ricochetQueueTask == null || ricochetQueueTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
ricochetQueueTask = new RicochetQueueTask();
ricochetQueueTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
}
if (!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) {
doClipboardCheck();
}
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
progress = new ProgressDialog(BalanceActivity.this);
progress.setCancelable(true);
progress.setTitle(R.string.app_name);
progress.setMessage(getText(R.string.refresh_tx_pre));
progress.show();
}
});
final Handler delayedHandler = new Handler();
delayedHandler.postDelayed(new Runnable() {
@Override
public void run() {
boolean notifTx = false;
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("notifTx")) {
notifTx = extras.getBoolean("notifTx");
}
refreshTx(notifTx, false, true);
// updateDisplay();
}
}, 100L);
if (!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
}
@Override
public void onResume() {
super.onResume();
// IntentFilter filter = new IntentFilter(ACTION_INTENT);
// LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
if (TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) {
OrbotHelper.requestStartTor(BalanceActivity.this);
}
AppUtil.getInstance(BalanceActivity.this).checkTimeOut();
Intent intent = new Intent("com.samourai.wallet.MainActivity2.RESTART_SERVICE");
LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent);
}
@Override
public void onPause() {
super.onPause();
ibQuickSend.collapse();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
}
private void makePaynymAvatarcache() {
try {
ArrayList<String> paymentCodes = new ArrayList<>(BIP47Meta.getInstance().getSortedByLabels(false, true));
for (String code : paymentCodes) {
Picasso.with(getBaseContext())
.load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + code + "/avatar").fetch(new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
}
});
}
} catch (Exception ignored) {
}
}
@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver);
LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiverDisplay);
unregisterReceiver(torStatusReceiver);
if (AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) {
menu.findItem(R.id.action_tor).setVisible(false);
} else if (TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) {
OrbotHelper.requestStartTor(BalanceActivity.this);
menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_on);
} else {
menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_off);
}
menu.findItem(R.id.action_refresh).setVisible(false);
menu.findItem(R.id.action_share_receive).setVisible(false);
menu.findItem(R.id.action_ricochet).setVisible(false);
menu.findItem(R.id.action_empty_ricochet).setVisible(false);
menu.findItem(R.id.action_sign).setVisible(false);
menu.findItem(R.id.action_fees).setVisible(false);
menu.findItem(R.id.action_batch).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
@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.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
doSettings();
} else if (id == R.id.action_support) {
doSupport();
} else if (id == R.id.action_sweep) {
if (!AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {
doSweep();
} else {
Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.action_utxo) {
doUTXO();
} else if (id == R.id.action_tor) {
if (!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) {
;
} else if (TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) {
item.setIcon(R.drawable.tor_off);
TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false);
} else {
OrbotHelper.requestStartTor(BalanceActivity.this);
item.setIcon(R.drawable.tor_on);
TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(true);
}
return true;
} else if (id == R.id.action_backup) {
if (SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
try {
if (HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
doBackup();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if (!isFinishing()) {
alert.show();
}
}
} catch (MnemonicException.MnemonicLengthException mle) {
;
} catch (IOException ioe) {
;
}
} else {
Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.action_scan_qr) {
doScan();
} else {
;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
doPrivKey(strResult);
}
} else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) {
;
} else if (resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult));
try {
if (privKeyReader.getFormat() != null) {
doPrivKey(strResult);
} else {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("uri", strResult);
startActivity(intent);
}
} catch (Exception e) {
;
}
}
} else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) {
;
} else {
;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
} catch (MnemonicException.MnemonicLengthException mle) {
;
} catch (JSONException je) {
;
} catch (IOException ioe) {
;
} catch (DecryptionException de) {
;
}
Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP);
BalanceActivity.this.startActivity(intent);
}
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if (!isFinishing()) {
alert.show();
}
return true;
} else {
;
}
return false;
}
private void updateDisplay() {
txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs();
if (txs != null) {
Collections.sort(txs, new APIFactory.TxMostRecentDateComparator());
}
tvBalanceAmount.setText("");
tvBalanceUnits.setText("");
displayBalance();
txAdapter.notifyDataSetChanged();
if (progress != null && progress.isShowing()) {
progress.dismiss();
progress.cancel();
progress = null;
}
}
private void doClaimPayNym() {
Intent intent = new Intent(BalanceActivity.this, ClaimPayNymActivity.class);
startActivity(intent);
}
private void doSettings() {
TimeOutUtil.getInstance().updatePin();
Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class);
startActivity(intent);
}
private void doSupport() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://samourai.kayako.com/"));
startActivity(intent);
}
private void doUTXO() {
Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class);
startActivity(intent);
}
private void doScan() {
Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, SCAN_QR);
}
private void doSweepViaScan() {
Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, SCAN_COLD_STORAGE);
}
private void doSweep() {
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.action_sweep)
.setCancelable(true)
.setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final EditText privkey = new EditText(BalanceActivity.this);
privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.enter_privkey)
.setView(privkey)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String strPrivKey = privkey.getText().toString();
if (strPrivKey != null && strPrivKey.length() > 0) {
doPrivKey(strPrivKey);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if (!isFinishing()) {
dlg.show();
}
}
}).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doSweepViaScan();
}
});
if (!isFinishing()) {
dlg.show();
}
}
private void doPrivKey(final String data) {
PrivKeyReader privKeyReader = null;
String format = null;
try {
privKeyReader = new PrivKeyReader(new CharSequenceX(data), null);
format = privKeyReader.getFormat();
} catch (Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
if (format != null) {
if (format.equals(PrivKeyReader.BIP38)) {
final PrivKeyReader pvr = privKeyReader;
final EditText password38 = new EditText(BalanceActivity.this);
password38.setSingleLine(true);
password38.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip38_pw)
.setView(password38)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = password38.getText().toString();
ProgressDialog progress = new ProgressDialog(BalanceActivity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.decrypting_bip38));
progress.show();
boolean keyDecoded = false;
try {
BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data);
final ECKey ecKey = bip38.decrypt(password);
if (ecKey != null && ecKey.hasPrivKey()) {
if (progress != null && progress.isShowing()) {
progress.cancel();
}
pvr.setPassword(new CharSequenceX(password));
keyDecoded = true;
Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show();
Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
if (progress != null && progress.isShowing()) {
progress.cancel();
}
if (keyDecoded) {
SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, SweepUtil.TYPE_P2PKH);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
});
if (!isFinishing()) {
dlg.show();
}
} else if (privKeyReader != null) {
SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, SweepUtil.TYPE_P2PKH);
} else {
;
}
} else {
Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show();
}
}
private void doBackup() {
try {
final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase();
final String[] export_methods = new String[2];
export_methods[0] = getString(R.string.export_to_clipboard);
export_methods[1] = getString(R.string.export_to_email);
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.options_export)
.setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
} catch (IOException ioe) {
;
} catch (JSONException je) {
;
} catch (DecryptionException de) {
;
} catch (MnemonicException.MnemonicLengthException mle) {
;
}
String encrypted = null;
try {
encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);
} catch (Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (encrypted == null) {
Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();
return;
}
}
JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true);
if (which == 0) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = null;
clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup");
email.putExtra(Intent.EXTRA_TEXT, obj.toString());
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client)));
}
dialog.dismiss();
}
}
).show();
} catch (IOException ioe) {
ioe.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
} catch (MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
}
private void doClipboardCheck() {
final android.content.ClipboardManager clipboard = (android.content.ClipboardManager) BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) {
final ClipData clip = clipboard.getPrimaryClip();
ClipData.Item item = clip.getItemAt(0);
if (item.getText() != null) {
String text = item.getText().toString();
String[] s = text.split("\\s+");
try {
for (int i = 0; i < s.length; i++) {
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i]));
if (privKeyReader.getFormat() != null &&
(privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) ||
privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) ||
privKeyReader.getFormat().equals(PrivKeyReader.BIP38) ||
FormatsUtil.getInstance().isValidXprv(s[i])
)
) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.privkey_clipboard)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clipboard.setPrimaryClip(ClipData.newPlainText("", ""));
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
}
} catch (Exception e) {
;
}
}
}
}
private class TransactionAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private static final int TYPE_ITEM = 0;
private static final int TYPE_BALANCE = 1;
TransactionAdapter() {
inflater = (LayoutInflater) BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
if (txs == null) {
txs = new ArrayList<Tx>();
txStates = new HashMap<String, Boolean>();
}
return txs.size() + 1;
}
@Override
public String getItem(int position) {
if (txs == null) {
txs = new ArrayList<Tx>();
txStates = new HashMap<String, Boolean>();
}
if (position == 0) {
return "";
}
return txs.get(position - 1).toString();
}
@Override
public long getItemId(int position) {
return position - 1;
}
@Override
public int getItemViewType(int position) {
return position == 0 ? TYPE_BALANCE : TYPE_ITEM;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view = null;
int type = getItemViewType(position);
if (convertView == null) {
if (type == TYPE_BALANCE) {
view = tvBalanceBar;
} else {
view = inflater.inflate(R.layout.tx_layout_simple, parent, false);
}
} else {
view = convertView;
}
if (type == TYPE_BALANCE) {
;
} else {
view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
});
Tx tx = txs.get(position - 1);
TextView tvTodayLabel = (TextView) view.findViewById(R.id.TodayLabel);
String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS());
if (position == 1) {
tvTodayLabel.setText(strDateGroup);
tvTodayLabel.setVisibility(View.VISIBLE);
} else {
Tx prevTx = txs.get(position - 2);
String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS());
if (strPrevDateGroup.equals(strDateGroup)) {
tvTodayLabel.setVisibility(View.GONE);
} else {
tvTodayLabel.setText(strDateGroup);
tvTodayLabel.setVisibility(View.VISIBLE);
}
}
String strDetails = null;
String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS());
long _amount = 0L;
if (tx.getAmount() < 0.0) {
_amount = Math.abs((long) tx.getAmount());
strDetails = BalanceActivity.this.getString(R.string.you_sent);
} else {
_amount = (long) tx.getAmount();
strDetails = BalanceActivity.this.getString(R.string.you_received);
}
String strAmount = null;
String strUnits = null;
if (isBTC) {
strAmount = getBTCDisplayAmount(_amount);
strUnits = getBTCDisplayUnits();
} else {
strAmount = getSatoshiDisplayAmount(_amount);
strUnits = getSatoshiDisplayUnits();
}
TextView tvDirection = (TextView) view.findViewById(R.id.TransactionDirection);
TextView tvDirection2 = (TextView) view.findViewById(R.id.TransactionDirection2);
TextView tvDetails = (TextView) view.findViewById(R.id.TransactionDetails);
ImageView ivTxStatus = (ImageView) view.findViewById(R.id.TransactionStatus);
TextView tvConfirmationCount = (TextView) view.findViewById(R.id.ConfirmationCount);
tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface());
if (tx.getAmount() < 0.0) {
tvDirection.setTextColor(Color.RED);
tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up));
} else {
tvDirection.setTextColor(Color.GREEN);
tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down));
}
if (txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) {
txStates.put(tx.getHash(), false);
displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
} else {
txStates.put(tx.getHash(), true);
displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
}
tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits);
if (tx.getPaymentCode() != null) {
String strTaggedTS = strTS + " ";
String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " ";
strTaggedTS += strSubText;
tvDetails.setText(strTaggedTS);
} else {
tvDetails.setText(strTS);
}
}
return view;
}
}
private void refreshTx(final boolean notifTx, final boolean dragged, final boolean launch) {
if (AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {
Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();
/*
CoordinatorLayout coordinatorLayout = new CoordinatorLayout(BalanceActivity.this);
Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.in_offline_mode, Snackbar.LENGTH_LONG);
snackbar.show();
*/
}
Intent intent = new Intent(BalanceActivity.this, RefreshService.class);
intent.putExtra("notifTx", notifTx);
intent.putExtra("dragged", dragged);
intent.putExtra("launch", launch);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
}
private void displayBalance() {
long balance = 0L;
if (SamouraiWallet.getInstance().getShowTotalBalance()) {
if (SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) {
balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance();
} else {
if (APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) {
try {
if (APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) {
balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr());
}
} catch (IOException ioe) {
;
} catch (MnemonicException.MnemonicLengthException mle) {
;
} catch (NullPointerException npe) {
;
}
}
}
} else {
if (APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) {
try {
if (APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) {
balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr());
}
} catch (IOException ioe) {
;
} catch (MnemonicException.MnemonicLengthException mle) {
;
} catch (NullPointerException npe) {
;
}
}
}
if (isBTC) {
tvBalanceAmount.setText(getBTCDisplayAmount(balance));
tvBalanceUnits.setText(getBTCDisplayUnits());
} else {
tvBalanceAmount.setText(getSatoshiDisplayAmount(balance));
tvBalanceUnits.setText(getSatoshiDisplayUnits());
}
}
private String getBTCDisplayAmount(long value) {
return Coin.valueOf(value).toPlainString();
}
private String getSatoshiDisplayAmount(long value) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat("#", symbols);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(16);
df.setGroupingUsed(true);
df.setGroupingSize(3);
return df.format(value);
}
private String getBTCDisplayUnits() {
return MonetaryUtil.getInstance().getBTCUnits();
}
private String getSatoshiDisplayUnits() {
return MonetaryUtil.getInstance().getSatoshiUnits();
}
private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) {
if (heads) {
if (confirmations == 0) {
rotateTxStatus(tvConfirmationCount, true);
ivTxStatus.setVisibility(View.VISIBLE);
ivTxStatus.setImageResource(R.drawable.ic_query_builder_white);
tvConfirmationCount.setVisibility(View.GONE);
} else if (confirmations > 3) {
rotateTxStatus(tvConfirmationCount, true);
ivTxStatus.setVisibility(View.VISIBLE);
ivTxStatus.setImageResource(R.drawable.ic_done_white);
tvConfirmationCount.setVisibility(View.GONE);
} else {
rotateTxStatus(ivTxStatus, false);
tvConfirmationCount.setVisibility(View.VISIBLE);
tvConfirmationCount.setText(Long.toString(confirmations));
ivTxStatus.setVisibility(View.GONE);
}
} else {
if (confirmations < 100) {
rotateTxStatus(ivTxStatus, false);
tvConfirmationCount.setVisibility(View.VISIBLE);
tvConfirmationCount.setText(Long.toString(confirmations));
ivTxStatus.setVisibility(View.GONE);
} else {
rotateTxStatus(ivTxStatus, false);
tvConfirmationCount.setVisibility(View.VISIBLE);
tvConfirmationCount.setText("\u221e");
ivTxStatus.setVisibility(View.GONE);
}
}
}
private void rotateTxStatus(View view, boolean clockwise) {
float degrees = 360f;
if (!clockwise) {
degrees = -360f;
}
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees);
animation.setDuration(1000);
animation.setRepeatCount(0);
animation.setInterpolator(new AnticipateInterpolator());
animation.start();
}
private void doExplorerView(String strHash) {
if (strHash != null) {
String blockExplorer = "https://m.oxt.me/transaction/";
if (SamouraiWallet.getInstance().isTestNet()) {
blockExplorer = "https://blockstream.info/testnet/";
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(blockExplorer + strHash));
startActivity(browserIntent);
}
}
private void doExplorerView(Tx tx) {
// if(strHash != null) {
// int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0);
// if(sel >= BlockExplorerUtil.getInstance().getBlockExplorerTxUrls().length) {
// sel = 0;
// CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerTxUrls()[sel];
Intent txIntent = new Intent(this, TxDetailsActivity.class);
txIntent.putExtra("TX", tx.toJSON().toString());
startActivity(txIntent);
}
private class RicochetQueueTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
if(RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {
final Iterator<JSONObject> itr = RicochetMeta.getInstance(BalanceActivity.this).getIterator();
while(itr.hasNext()) {
try {
JSONObject jObj = itr.next();
JSONArray jHops = jObj.getJSONArray("hops");
if(jHops.length() > 0) {
JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);
String txHash = jHop.getString("hash");
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);
if(txObj != null && txObj.has("block_height") && txObj.getInt("block_height") != -1) {
itr.remove();
continue;
}
}
}
catch(JSONException je) {
;
}
}
}
if(RicochetMeta.getInstance(BalanceActivity.this).getStaggered().size() > 0) {
List<JSONObject> staggered = RicochetMeta.getInstance(BalanceActivity.this).getStaggered();
List<JSONObject> _staggered = new ArrayList<JSONObject>();
for(JSONObject jObj : staggered) {
try {
JSONArray jHops = jObj.getJSONArray("script");
if(jHops.length() > 0) {
JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);
String txHash = jHop.getString("tx");
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);
if(txObj != null && txObj.has("block_height") && txObj.getInt("block_height") != -1) {
continue;
}
else {
_staggered.add(jObj);
}
}
}
catch(JSONException je) {
;
}
}
}
return "OK";
}
@Override
protected void onPostExecute(String result) { ; }
@Override
protected void onPreExecute() {
;
}
}
private class PoWTask extends AsyncTask<String, Void, String> {
private boolean isOK = true;
private String strBlockHash = null;
@Override
protected String doInBackground(String... params) {
strBlockHash = params[0];
JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort());
JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash);
if (nodeObj != null && nodeObj.has("hash")) {
PoW pow = new PoW(strBlockHash);
String hash = pow.calcHash(nodeObj);
if (hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) {
JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash);
if (headerObj != null && headerObj.has("")) {
if (!pow.check(headerObj, nodeObj, hash)) {
isOK = false;
}
}
} else {
isOK = false;
}
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
if (!isOK) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash)
.setCancelable(false)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
}
@Override
protected void onPreExecute() {
;
}
}
private class CPFPTask extends AsyncTask<String, Void, String> {
private List<UTXO> utxos = null;
private Handler handler = null;
@Override
protected void onPreExecute() {
handler = new Handler();
utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true);
}
@Override
protected String doInBackground(String... params) {
Looper.prepare();
Log.d("BalanceActivity", "hash:" + params[0]);
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]);
if (txObj.has("inputs") && txObj.has("outputs")) {
final SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee();
try {
JSONArray inputs = txObj.getJSONArray("inputs");
JSONArray outputs = txObj.getJSONArray("outputs");
int p2pkh = 0;
int p2sh_p2wpkh = 0;
int p2wpkh = 0;
for (int i = 0; i < inputs.length(); i++) {
if (inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) {
String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey");
Script script = new Script(Hex.decode(scriptpubkey));
String address = null;
if (Bech32Util.getInstance().isBech32Script(scriptpubkey)) {
try {
address = Bech32Util.getInstance().getAddressFromScript(scriptpubkey);
} catch (Exception e) {
;
}
} else {
address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
if (FormatsUtil.getInstance().isValidBech32(address)) {
p2wpkh++;
} else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
p2sh_p2wpkh++;
} else {
p2pkh++;
}
}
}
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, outputs.length());
long total_inputs = 0L;
long total_outputs = 0L;
long fee = 0L;
UTXO utxo = null;
for (int i = 0; i < inputs.length(); i++) {
JSONObject obj = inputs.getJSONObject(i);
if (obj.has("outpoint")) {
JSONObject objPrev = obj.getJSONObject("outpoint");
if (objPrev.has("value")) {
total_inputs += objPrev.getLong("value");
}
}
}
for (int i = 0; i < outputs.length(); i++) {
JSONObject obj = outputs.getJSONObject(i);
if (obj.has("value")) {
total_outputs += obj.getLong("value");
String addr = obj.getString("address");
Log.d("BalanceActivity", "checking address:" + addr);
if (utxo == null) {
utxo = getUTXO(addr);
} else {
break;
}
}
}
boolean feeWarning = false;
fee = total_inputs - total_outputs;
if (fee > estimatedFee.longValue()) {
feeWarning = true;
}
Log.d("BalanceActivity", "total inputs:" + total_inputs);
Log.d("BalanceActivity", "total outputs:" + total_outputs);
Log.d("BalanceActivity", "fee:" + fee);
Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue());
Log.d("BalanceActivity", "fee warning:" + feeWarning);
if (utxo != null) {
Log.d("BalanceActivity", "utxo found");
List<UTXO> selectedUTXO = new ArrayList<UTXO>();
selectedUTXO.add(utxo);
int selected = utxo.getOutpoints().size();
long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L;
Log.d("BalanceActivity", "remaining fee:" + remainingFee);
int receiveIdx = AddressFactory.getInstance(BalanceActivity.this).getHighestTxReceiveIdx(0);
Log.d("BalanceActivity", "receive index:" + receiveIdx);
final String addr;
if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == true) {
addr = utxo.getOutpoints().get(0).getAddress();
} else {
addr = outputs.getJSONObject(0).getString("address");
}
final String ownReceiveAddr;
if (FormatsUtil.getInstance().isValidBech32(addr)) {
ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).getBIP84(AddressFactory.RECEIVE_CHAIN).getBech32AsString();
} else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) {
ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString();
} else {
ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString();
}
Log.d("BalanceActivity", "receive address:" + ownReceiveAddr);
long totalAmount = utxo.getValue();
Log.d("BalanceActivity", "amount before fee:" + totalAmount);
Triple<Integer, Integer, Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(utxo.getOutpoints()));
BigInteger cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getMiddle(), outpointTypes.getRight(), 1);
Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue());
p2pkh = outpointTypes.getLeft();
p2sh_p2wpkh = outpointTypes.getMiddle();
p2wpkh = outpointTypes.getRight();
if (totalAmount < (cpfpFee.longValue() + remainingFee)) {
Log.d("BalanceActivity", "selecting additional utxo");
Collections.sort(utxos, new UTXO.UTXOComparator());
for (UTXO _utxo : utxos) {
totalAmount += _utxo.getValue();
selectedUTXO.add(_utxo);
selected += _utxo.getOutpoints().size();
outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(utxo.getOutpoints()));
p2pkh += outpointTypes.getLeft();
p2sh_p2wpkh += outpointTypes.getMiddle();
p2wpkh += outpointTypes.getRight();
cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, 1);
if (totalAmount > (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) {
break;
}
}
if (totalAmount < (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
}
});
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
return "KO";
}
}
cpfpFee = cpfpFee.add(BigInteger.valueOf(remainingFee));
Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue());
final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>();
for (UTXO u : selectedUTXO) {
outPoints.addAll(u.getOutpoints());
}
long _totalAmount = 0L;
for (MyTransactionOutPoint outpoint : outPoints) {
_totalAmount += outpoint.getValue().longValue();
}
Log.d("BalanceActivity", "checked total amount:" + _totalAmount);
assert (_totalAmount == totalAmount);
long amount = totalAmount - cpfpFee.longValue();
Log.d("BalanceActivity", "amount after fee:" + amount);
if (amount < SamouraiWallet.bDust.longValue()) {
Log.d("BalanceActivity", "dust output");
Toast.makeText(BalanceActivity.this, R.string.cannot_output_dust, Toast.LENGTH_SHORT).show();
}
final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>();
receivers.put(ownReceiveAddr, BigInteger.valueOf(amount));
String message = "";
if (feeWarning) {
message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary);
message += "\n\n";
}
message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC";
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outPoints, receivers);
if (tx != null) {
tx = SendFactory.getInstance(BalanceActivity.this).signTransaction(tx);
final String hexTx = new String(Hex.encode(tx.bitcoinSerialize()));
Log.d("BalanceActivity", hexTx);
final String strTxHash = tx.getHashAsString();
Log.d("BalanceActivity", strTxHash);
boolean isOK = false;
try {
isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx);
if (isOK) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cpfp_spent, Toast.LENGTH_SHORT).show();
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(_intent);
}
});
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
}
});
// reset receive index upon tx fail
if (FormatsUtil.getInstance().isValidBech32(addr)) {
int prevIdx = BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1;
BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx);
} else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) {
int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1;
BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx);
} else {
int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1;
HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx);
}
}
} catch (MnemonicException.MnemonicLengthException | DecoderException | IOException e) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "pushTx:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} finally {
;
}
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
if (Bech32Util.getInstance().isBech32Script(addr)) {
int prevIdx = BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1;
BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx);
} else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) {
int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1;
BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx);
} else {
int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1;
HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx);
}
} catch (MnemonicException.MnemonicLengthException | DecoderException | IOException e) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} finally {
dialog.dismiss();
}
}
});
if (!isFinishing()) {
dlg.show();
}
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cannot_create_cpfp, Toast.LENGTH_SHORT).show();
}
});
}
} catch (final JSONException je) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "cpfp:" + je.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show();
}
});
}
Looper.loop();
return "OK";
}
@Override
protected void onPostExecute(String result) {
;
}
@Override
protected void onProgressUpdate(Void... values) {
;
}
private UTXO getUTXO(String address) {
UTXO ret = null;
int idx = -1;
for (int i = 0; i < utxos.size(); i++) {
UTXO utxo = utxos.get(i);
Log.d("BalanceActivity", "utxo address:" + utxo.getOutpoints().get(0).getAddress());
if (utxo.getOutpoints().get(0).getAddress().equals(address)) {
ret = utxo;
idx = i;
break;
}
}
if (ret != null) {
utxos.remove(idx);
return ret;
}
return null;
}
}
private class RBFTask extends AsyncTask<String, Void, String> {
private List<UTXO> utxos = null;
private Handler handler = null;
private RBFSpend rbf = null;
private HashMap<String, Long> input_values = null;
@Override
protected void onPreExecute() {
handler = new Handler();
utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true);
input_values = new HashMap<String, Long>();
}
@Override
protected String doInBackground(final String... params) {
Looper.prepare();
Log.d("BalanceActivity", "hash:" + params[0]);
rbf = RBFUtil.getInstance().get(params[0]);
Log.d("BalanceActivity", "rbf:" + rbf.toJSON().toString());
final Transaction tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams(), Hex.decode(rbf.getSerializedTx()));
Log.d("BalanceActivity", "tx serialized:" + rbf.getSerializedTx());
Log.d("BalanceActivity", "tx inputs:" + tx.getInputs().size());
Log.d("BalanceActivity", "tx outputs:" + tx.getOutputs().size());
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]);
if (tx != null && txObj.has("inputs") && txObj.has("outputs")) {
try {
JSONArray inputs = txObj.getJSONArray("inputs");
JSONArray outputs = txObj.getJSONArray("outputs");
int p2pkh = 0;
int p2sh_p2wpkh = 0;
int p2wpkh = 0;
for (int i = 0; i < inputs.length(); i++) {
if (inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) {
String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey");
Script script = new Script(Hex.decode(scriptpubkey));
String address = null;
if (Bech32Util.getInstance().isBech32Script(scriptpubkey)) {
try {
address = Bech32Util.getInstance().getAddressFromScript(scriptpubkey);
} catch (Exception e) {
;
}
} else {
address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
if (FormatsUtil.getInstance().isValidBech32(address)) {
p2wpkh++;
} else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
p2sh_p2wpkh++;
} else {
p2pkh++;
}
}
}
SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee();
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, outputs.length());
long total_inputs = 0L;
long total_outputs = 0L;
long fee = 0L;
long total_change = 0L;
List<String> selfAddresses = new ArrayList<String>();
for (int i = 0; i < inputs.length(); i++) {
JSONObject obj = inputs.getJSONObject(i);
if (obj.has("outpoint")) {
JSONObject objPrev = obj.getJSONObject("outpoint");
if (objPrev.has("value")) {
total_inputs += objPrev.getLong("value");
String key = objPrev.getString("txid") + ":" + objPrev.getLong("vout");
input_values.put(key, objPrev.getLong("value"));
}
}
}
for (int i = 0; i < outputs.length(); i++) {
JSONObject obj = outputs.getJSONObject(i);
if (obj.has("value")) {
total_outputs += obj.getLong("value");
String _addr = null;
if (obj.has("address")) {
_addr = obj.getString("address");
}
selfAddresses.add(_addr);
if (_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) {
total_change += obj.getLong("value");
}
}
}
boolean feeWarning = false;
fee = total_inputs - total_outputs;
if (fee > estimatedFee.longValue()) {
feeWarning = true;
}
long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L;
Log.d("BalanceActivity", "total inputs:" + total_inputs);
Log.d("BalanceActivity", "total outputs:" + total_outputs);
Log.d("BalanceActivity", "total change:" + total_change);
Log.d("BalanceActivity", "fee:" + fee);
Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue());
Log.d("BalanceActivity", "fee warning:" + feeWarning);
Log.d("BalanceActivity", "remaining fee:" + remainingFee);
List<TransactionOutput> txOutputs = new ArrayList<TransactionOutput>();
txOutputs.addAll(tx.getOutputs());
long remainder = remainingFee;
if (total_change > remainder) {
for (TransactionOutput output : txOutputs) {
Script script = output.getScriptPubKey();
String scriptPubKey = Hex.toHexString(script.getProgram());
Address _p2sh = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams());
Address _p2pkh = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams());
try {
if ((Bech32Util.getInstance().isBech32Script(scriptPubKey) && rbf.getChangeAddrs().contains(Bech32Util.getInstance().getAddressFromScript(scriptPubKey))) || (_p2sh != null && rbf.getChangeAddrs().contains(_p2sh.toString())) || (_p2pkh != null && rbf.getChangeAddrs().contains(_p2pkh.toString()))) {
if (output.getValue().longValue() >= (remainder + SamouraiWallet.bDust.longValue())) {
output.setValue(Coin.valueOf(output.getValue().longValue() - remainder));
remainder = 0L;
break;
} else {
remainder -= output.getValue().longValue();
output.setValue(Coin.valueOf(0L)); // output will be discarded later
}
}
} catch (Exception e) {
;
}
}
}
// original inputs are not modified
List<MyTransactionInput> _inputs = new ArrayList<MyTransactionInput>();
List<TransactionInput> txInputs = tx.getInputs();
for (TransactionInput input : txInputs) {
MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], input.getOutpoint(), input.getOutpoint().getHash().toString(), (int) input.getOutpoint().getIndex());
_input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_VAL.longValue());
_inputs.add(_input);
Log.d("BalanceActivity", "add outpoint:" + _input.getOutpoint().toString());
}
Triple<Integer, Integer, Integer> outpointTypes = null;
if (remainder > 0L) {
List<UTXO> selectedUTXO = new ArrayList<UTXO>();
long selectedAmount = 0L;
int selected = 0;
long _remainingFee = remainder;
Collections.sort(utxos, new UTXO.UTXOComparator());
for (UTXO _utxo : utxos) {
Log.d("BalanceActivity", "utxo value:" + _utxo.getValue());
// do not select utxo that are change outputs in current rbf tx
boolean isChange = false;
boolean isSelf = false;
for (MyTransactionOutPoint outpoint : _utxo.getOutpoints()) {
if (rbf.containsChangeAddr(outpoint.getAddress())) {
Log.d("BalanceActivity", "is change:" + outpoint.getAddress());
Log.d("BalanceActivity", "is change:" + outpoint.getValue().longValue());
isChange = true;
break;
}
if (selfAddresses.contains(outpoint.getAddress())) {
Log.d("BalanceActivity", "is self:" + outpoint.getAddress());
Log.d("BalanceActivity", "is self:" + outpoint.getValue().longValue());
isSelf = true;
break;
}
}
if (isChange || isSelf) {
continue;
}
selectedUTXO.add(_utxo);
selected += _utxo.getOutpoints().size();
Log.d("BalanceActivity", "selected utxo:" + selected);
selectedAmount += _utxo.getValue();
Log.d("BalanceActivity", "selected utxo value:" + _utxo.getValue());
outpointTypes = FeeUtil.getInstance().getOutpointCount(new Vector(_utxo.getOutpoints()));
p2pkh += outpointTypes.getLeft();
p2sh_p2wpkh += outpointTypes.getMiddle();
p2wpkh += outpointTypes.getRight();
_remainingFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2sh_p2wpkh, p2wpkh, outputs.length() == 1 ? 2 : outputs.length()).longValue();
Log.d("BalanceActivity", "_remaining fee:" + _remainingFee);
if (selectedAmount >= (_remainingFee + SamouraiWallet.bDust.longValue())) {
break;
}
}
long extraChange = 0L;
if (selectedAmount < (_remainingFee + SamouraiWallet.bDust.longValue())) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
}
});
return "KO";
} else {
extraChange = selectedAmount - _remainingFee;
Log.d("BalanceActivity", "extra change:" + extraChange);
}
boolean addedChangeOutput = false;
// parent tx didn't have change output
if (outputs.length() == 1 && extraChange > 0L) {
try {
boolean isSegwitChange = (FormatsUtil.getInstance().isValidBech32(outputs.getJSONObject(0).getString("address")) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outputs.getJSONObject(0).getString("address")).isP2SHAddress()) || PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false;
String change_address = null;
if (isSegwitChange) {
int changeIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx();
change_address = BIP49Util.getInstance(BalanceActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, changeIdx).getAddressAsString();
} else {
int changeIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddrIdx();
change_address = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddressAt(changeIdx).getAddressString();
}
Script toOutputScript = ScriptBuilder.createOutputScript(org.bitcoinj.core.Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), change_address));
TransactionOutput output = new TransactionOutput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, Coin.valueOf(extraChange), toOutputScript.getProgram());
txOutputs.add(output);
addedChangeOutput = true;
} catch (MnemonicException.MnemonicLengthException | IOException e) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show();
}
});
return "KO";
}
}
// parent tx had change output
else {
for (TransactionOutput output : txOutputs) {
Script script = output.getScriptPubKey();
String scriptPubKey = Hex.toHexString(script.getProgram());
String _addr = null;
if (Bech32Util.getInstance().isBech32Script(scriptPubKey)) {
try {
_addr = Bech32Util.getInstance().getAddressFromScript(scriptPubKey);
} catch (Exception e) {
;
}
}
if (_addr == null) {
Address _address = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams());
if (_address == null) {
_address = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams());
}
_addr = _address.toString();
}
Log.d("BalanceActivity", "checking for change:" + _addr);
if (rbf.containsChangeAddr(_addr)) {
Log.d("BalanceActivity", "before extra:" + output.getValue().longValue());
output.setValue(Coin.valueOf(extraChange + output.getValue().longValue()));
Log.d("BalanceActivity", "after extra:" + output.getValue().longValue());
addedChangeOutput = true;
break;
}
}
}
// sanity check
if (extraChange > 0L && !addedChangeOutput) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show();
}
});
return "KO";
}
// update keyBag w/ any new paths
final HashMap<String, String> keyBag = rbf.getKeyBag();
for (UTXO _utxo : selectedUTXO) {
for (MyTransactionOutPoint outpoint : _utxo.getOutpoints()) {
MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], outpoint, outpoint.getTxHash().toString(), outpoint.getTxOutputN());
_input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_VAL.longValue());
_inputs.add(_input);
Log.d("BalanceActivity", "add selected outpoint:" + _input.getOutpoint().toString());
String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(outpoint.getAddress());
if (path != null) {
if (FormatsUtil.getInstance().isValidBech32(outpoint.getAddress())) {
rbf.addKey(outpoint.toString(), path + "/84");
} else if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outpoint.getAddress()) != null && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outpoint.getAddress()).isP2SHAddress()) {
rbf.addKey(outpoint.toString(), path + "/49");
} else {
rbf.addKey(outpoint.toString(), path);
}
Log.d("BalanceActivity", "outpoint address:" + outpoint.getAddress());
} else {
String pcode = BIP47Meta.getInstance().getPCode4Addr(outpoint.getAddress());
int idx = BIP47Meta.getInstance().getIdx4Addr(outpoint.getAddress());
rbf.addKey(outpoint.toString(), pcode + "/" + idx);
}
}
}
rbf.setKeyBag(keyBag);
}
// BIP69 sort of outputs/inputs
final Transaction _tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams());
List<TransactionOutput> _txOutputs = new ArrayList<TransactionOutput>();
_txOutputs.addAll(txOutputs);
Collections.sort(_txOutputs, new BIP69OutputComparator());
for (TransactionOutput to : _txOutputs) {
// zero value outputs discarded here
if (to.getValue().longValue() > 0L) {
_tx.addOutput(to);
}
}
List<MyTransactionInput> __inputs = new ArrayList<MyTransactionInput>();
__inputs.addAll(_inputs);
Collections.sort(__inputs, new SendFactory.BIP69InputComparator());
for (TransactionInput input : __inputs) {
_tx.addInput(input);
}
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
String message = "";
if (feeWarning) {
message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary);
message += "\n\n";
}
message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC";
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Transaction __tx = signTx(_tx);
final String hexTx = new String(Hex.encode(__tx.bitcoinSerialize()));
Log.d("BalanceActivity", "hex tx:" + hexTx);
final String strTxHash = __tx.getHashAsString();
Log.d("BalanceActivity", "tx hash:" + strTxHash);
if (__tx != null) {
boolean isOK = false;
try {
isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx);
if (isOK) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.rbf_spent, Toast.LENGTH_SHORT).show();
RBFSpend _rbf = rbf; // includes updated 'keyBag'
_rbf.setSerializedTx(hexTx);
_rbf.setHash(strTxHash);
_rbf.setPrevHash(params[0]);
RBFUtil.getInstance().add(_rbf);
Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(_intent);
}
});
} else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
}
});
}
} catch (final DecoderException de) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} finally {
;
}
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if (!isFinishing()) {
dlg.show();
}
} catch (final JSONException je) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "rbf:" + je.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
} else {
Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show();
}
Looper.loop();
return "OK";
}
@Override
protected void onPostExecute(String result) {
;
}
@Override
protected void onProgressUpdate(Void... values) {
;
}
private Transaction signTx(Transaction tx) {
HashMap<String, ECKey> keyBag = new HashMap<String, ECKey>();
HashMap<String, ECKey> keyBag49 = new HashMap<String, ECKey>();
HashMap<String, ECKey> keyBag84 = new HashMap<String, ECKey>();
HashMap<String, String> keys = rbf.getKeyBag();
for (String outpoint : keys.keySet()) {
ECKey ecKey = null;
String[] s = keys.get(outpoint).split("/");
Log.i("BalanceActivity", "path length:" + s.length);
if (s.length == 4) {
if (s[3].equals("84")) {
HD_Address addr = BIP84Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2]));
ecKey = addr.getECKey();
} else {
HD_Address addr = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2]));
ecKey = addr.getECKey();
}
} else if (s.length == 3) {
HD_Address hd_address = AddressFactory.getInstance(BalanceActivity.this).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2]));
String strPrivKey = hd_address.getPrivateKeyString();
DumpedPrivateKey pk = new DumpedPrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), strPrivKey);
ecKey = pk.getKey();
} else if (s.length == 2) {
try {
PaymentAddress address = BIP47Util.getInstance(BalanceActivity.this).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1]));
ecKey = address.getReceiveECKey();
} catch (Exception e) {
;
}
} else {
;
}
Log.i("BalanceActivity", "outpoint:" + outpoint);
Log.i("BalanceActivity", "path:" + keys.get(outpoint));
// Log.i("BalanceActivity", "ECKey address from ECKey:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
if (ecKey != null) {
if (s.length == 4) {
if (s[3].equals("84")) {
keyBag84.put(outpoint, ecKey);
} else {
keyBag49.put(outpoint, ecKey);
}
} else {
keyBag.put(outpoint, ecKey);
}
} else {
throw new RuntimeException("ECKey error: cannot process private key");
// Log.i("ECKey error", "cannot process private key");
}
}
List<TransactionInput> inputs = tx.getInputs();
for (int i = 0; i < inputs.size(); i++) {
ECKey ecKey = null;
String address = null;
if (inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString()) || keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) {
if (keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) {
ecKey = keyBag84.get(inputs.get(i).getOutpoint().toString());
SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
address = segwitAddress.getBech32AsString();
} else {
ecKey = keyBag49.get(inputs.get(i).getOutpoint().toString());
SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
address = segwitAddress.getAddressAsString();
}
} else {
ecKey = keyBag.get(inputs.get(i).getOutpoint().toString());
address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
Log.d("BalanceActivity", "pubKey:" + Hex.toHexString(ecKey.getPubKey()));
Log.d("BalanceActivity", "address:" + address);
if (inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString()) || keyBag84.containsKey(inputs.get(i).getOutpoint().toString())) {
final SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams());
Script scriptPubKey = segwitAddress.segWitOutputScript();
final Script redeemScript = segwitAddress.segWitRedeemScript();
System.out.println("redeem script:" + Hex.toHexString(redeemScript.getProgram()));
final Script scriptCode = redeemScript.scriptCode();
System.out.println("script code:" + Hex.toHexString(scriptCode.getProgram()));
TransactionSignature sig = tx.calculateWitnessSignature(i, ecKey, scriptCode, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Transaction.SigHash.ALL, false);
final TransactionWitness witness = new TransactionWitness(2);
witness.setPush(0, sig.encodeToBitcoin());
witness.setPush(1, ecKey.getPubKey());
tx.setWitness(i, witness);
if (!FormatsUtil.getInstance().isValidBech32(address) && Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
final ScriptBuilder sigScript = new ScriptBuilder();
sigScript.data(redeemScript.getProgram());
tx.getInput(i).setScriptSig(sigScript.build());
tx.getInput(i).getScriptSig().correctlySpends(tx, i, scriptPubKey, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Script.ALL_VERIFY_FLAGS);
}
} else {
Log.i("BalanceActivity", "sign outpoint:" + inputs.get(i).getOutpoint().toString());
Log.i("BalanceActivity", "ECKey address from keyBag:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString());
Log.i("BalanceActivity", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())));
Log.i("BalanceActivity", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram()));
TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram(), Transaction.SigHash.ALL, false);
tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey));
}
}
return tx;
}
}
private void doFeaturePayNymUpdate() {
new Thread(new Runnable() {
private Handler handler = new Handler();
@Override
public void run() {
Looper.prepare();
try {
JSONObject obj = new JSONObject();
obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());
// Log.d("BalanceActivity", obj.toString());
String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/token", obj.toString());
// Log.d("BalanceActivity", res);
JSONObject responseObj = new JSONObject(res);
if (responseObj.has("token")) {
String token = responseObj.getString("token");
String sig = MessageSignUtil.getInstance(BalanceActivity.this).signMessage(BIP47Util.getInstance(BalanceActivity.this).getNotificationAddress().getECKey(), token);
// Log.d("BalanceActivity", sig);
obj = new JSONObject();
obj.put("nym", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());
obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getFeaturePaymentCode().toString());
obj.put("signature", sig);
// Log.d("BalanceActivity", "nym/add:" + obj.toString());
res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", token, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/nym/add", obj.toString());
// Log.d("BalanceActivity", res);
responseObj = new JSONObject(res);
if (responseObj.has("segwit") && responseObj.has("token")) {
PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);
} else if (responseObj.has("claimed") && responseObj.getBoolean("claimed") == true) {
PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);
} else {
;
}
} else {
;
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop();
}
}).start();
}
}
|
package com.samourai.wallet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnticipateInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import org.apache.commons.lang3.tuple.Pair;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.DumpedPrivateKey;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.ScriptException;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.crypto.BIP38PrivateKey;
import org.bitcoinj.crypto.MnemonicException;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import com.samourai.wallet.JSONRPC.JSONRPC;
import com.samourai.wallet.JSONRPC.PoW;
import com.samourai.wallet.JSONRPC.TrustedNodeUtil;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.api.Tx;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.bip47.rpc.*;
import com.samourai.wallet.crypto.AESUtil;
import com.samourai.wallet.crypto.DecryptionException;
import com.samourai.wallet.hd.HD_Address;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionInput;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.RBFSpend;
import com.samourai.wallet.send.RBFUtil;
import com.samourai.wallet.send.SendFactory;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.send.PushTx;
import com.samourai.wallet.service.WebSocketService;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.BlockExplorerUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.DateUtil;
import com.samourai.wallet.util.ExchangeRateFactory;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.PrivKeyReader;
import com.samourai.wallet.util.ReceiveLookAtUtil;
import com.samourai.wallet.util.TimeOutUtil;
import com.samourai.wallet.util.TorUtil;
import com.samourai.wallet.util.TypefaceUtil;
import com.samourai.wallet.util.WebUtil;
import org.bitcoinj.core.Coin;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.spongycastle.util.encoders.Hex;
import org.spongycastle.util.encoders.DecoderException;
import net.i2p.android.ext.floatingactionbutton.FloatingActionButton;
import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu;
import net.sourceforge.zbar.Symbol;
import java.io.IOException;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import info.guardianproject.netcipher.proxy.OrbotHelper;
public class BalanceActivity extends Activity {
private final static int SCAN_COLD_STORAGE = 2011;
private final static int SCAN_QR = 2012;
private LinearLayout tvBalanceBar = null;
private TextView tvBalanceAmount = null;
private TextView tvBalanceUnits = null;
private ListView txList = null;
private List<Tx> txs = null;
private HashMap<String, Boolean> txStates = null;
private TransactionAdapter txAdapter = null;
private SwipeRefreshLayout swipeRefreshLayout = null;
private FloatingActionsMenu ibQuickSend = null;
private FloatingActionButton actionReceive = null;
private FloatingActionButton actionSend = null;
private FloatingActionButton actionBIP47 = null;
private boolean isBTC = true;
public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
final boolean notifTx = intent.getBooleanExtra("notifTx", false);
final boolean fetch = intent.getBooleanExtra("fetch", false);
final String rbfHash;
final String blkHash;
if(intent.hasExtra("rbf")) {
rbfHash = intent.getStringExtra("rbf");
}
else {
rbfHash = null;
}
if(intent.hasExtra("hash")) {
blkHash = intent.getStringExtra("hash");
}
else {
blkHash = null;
}
BalanceActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
tvBalanceAmount.setText("");
tvBalanceUnits.setText("");
refreshTx(notifTx, fetch, false);
if(BalanceActivity.this != null) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
catch(JSONException je) {
;
}
catch(IOException ioe) {
;
}
catch(DecryptionException de) {
;
}
if(rbfHash != null) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming))
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doExplorerView(rbfHash);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
}
}
});
if(BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) {
BalanceActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
new PoWTask().execute(blkHash);
}
});
}
}
}
};
protected BroadcastReceiver torStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("BalanceActivity", "torStatusReceiver onReceive()");
if (OrbotHelper.ACTION_STATUS.equals(intent.getAction())) {
boolean enabled = (intent.getStringExtra(OrbotHelper.EXTRA_STATUS).equals(OrbotHelper.STATUS_ON));
Log.i("BalanceActivity", "status:" + enabled);
TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(enabled);
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
LayoutInflater inflator = BalanceActivity.this.getLayoutInflater();
tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null);
tvBalanceBar.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(isBTC) {
isBTC = false;
}
else {
isBTC = true;
}
displayBalance();
txAdapter.notifyDataSetChanged();
return false;
}
});
tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount);
tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits);
ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu);
actionSend = (FloatingActionButton)findViewById(R.id.send);
actionSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("via_menu", true);
startActivity(intent);
}
});
actionReceive = (FloatingActionButton)findViewById(R.id.receive);
actionReceive.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2 ||
(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0 && SamouraiWallet.getInstance().getShowTotalBalance())
) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.receive2Samourai)
.setCancelable(false)
.setPositiveButton(R.string.generate_receive_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
else {
Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class);
startActivity(intent);
}
}
});
actionBIP47 = (FloatingActionButton)findViewById(R.id.bip47);
actionBIP47.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class);
startActivity(intent);
}
});
txs = new ArrayList<Tx>();
txStates = new HashMap<String, Boolean>();
txList = (ListView)findViewById(R.id.txList);
txAdapter = new TransactionAdapter();
txList.setAdapter(txAdapter);
txList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
if(position == 0) {
return;
}
long viewId = view.getId();
View v = (View)view.getParent();
final Tx tx = txs.get(position - 1);
ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus);
TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount);
if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) {
if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) {
txStates.put(tx.getHash(), false);
displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
}
else {
txStates.put(tx.getHash(), true);
displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
}
}
else {
String message = getString(R.string.options_unconfirmed_tx);
// RBF
if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0 && RBFUtil.getInstance().contains(tx.getHash())) {
AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this);
builder.setTitle(R.string.app_name);
builder.setMessage(message);
builder.setCancelable(true);
builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
RBFTask RBFTask = new RBFTask();
RBFTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, tx.getHash());
}
});
builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
doExplorerView(tx.getHash());
}
});
AlertDialog alert = builder.create();
alert.show();
}
// CPFP receive
else if(tx.getConfirmations() < 1 && tx.getAmount() >= 0.0) {
AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this);
builder.setTitle(R.string.app_name);
builder.setMessage(message);
builder.setCancelable(true);
builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
CPFPTask CPFPTask = new CPFPTask();
CPFPTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, tx.getHash());
}
});
builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
doExplorerView(tx.getHash());
}
});
AlertDialog alert = builder.create();
alert.show();
}
// CPFP spend
else if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0) {
AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this);
builder.setTitle(R.string.app_name);
builder.setMessage(message);
builder.setCancelable(true);
builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
CPFPTask CPFPTask = new CPFPTask();
CPFPTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, tx.getHash());
}
});
builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
doExplorerView(tx.getHash());
}
});
AlertDialog alert = builder.create();
alert.show();
}
else {
doExplorerView(tx.getHash());
return;
}
}
}
});
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().post(new Runnable() {
@Override
public void run() {
refreshTx(false, true, true);
}
});
}
});
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
// TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false);
registerReceiver(torStatusReceiver, new IntentFilter(OrbotHelper.ACTION_STATUS));
refreshTx(false, true, false);
}
@Override
public void onResume() {
super.onResume();
// IntentFilter filter = new IntentFilter(ACTION_INTENT);
// LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) {
OrbotHelper.requestStartTor(BalanceActivity.this);
}
AppUtil.getInstance(BalanceActivity.this).checkTimeOut();
if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
}
@Override
public void onPause() {
super.onPause();
// LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver);
ibQuickSend.collapse();
}
@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver);
unregisterReceiver(torStatusReceiver);
if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) {
menu.findItem(R.id.action_tor).setVisible(false);
}
else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) {
OrbotHelper.requestStartTor(BalanceActivity.this);
menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_on);
}
else {
menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_off);
}
menu.findItem(R.id.action_refresh).setVisible(false);
menu.findItem(R.id.action_share_receive).setVisible(false);
menu.findItem(R.id.action_ricochet).setVisible(false);
menu.findItem(R.id.action_sign).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
@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.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
doSettings();
}
else if (id == R.id.action_sweep) {
doSweep();
}
else if (id == R.id.action_utxo) {
doUTXO();
}
else if (id == R.id.action_fees) {
doFees();
}
else if (id == R.id.action_tor) {
if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) {
;
}
else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) {
item.setIcon(R.drawable.tor_off);
TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false);
}
else {
OrbotHelper.requestStartTor(BalanceActivity.this);
item.setIcon(R.drawable.tor_on);
TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(true);
}
return true;
}
else if (id == R.id.action_backup) {
if(SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
try {
if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
doBackup();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}});
if(!isFinishing()) {
alert.show();
}
}
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
catch(IOException ioe) {
;
}
}
else {
Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show();
}
}
else if (id == R.id.action_scan_qr) {
doScan();
}
else {
;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) {
if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
PrivKeyReader privKeyReader = null;
String format = null;
try {
privKeyReader = new PrivKeyReader(new CharSequenceX(strResult), null);
format = privKeyReader.getFormat();
}
catch(Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
if(format != null) {
if(format.equals(PrivKeyReader.BIP38)) {
final PrivKeyReader pvr = privKeyReader;
final EditText password38 = new EditText(BalanceActivity.this);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip38_pw)
.setView(password38)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = password38.getText().toString();
ProgressDialog progress = new ProgressDialog(BalanceActivity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.decrypting_bip38));
progress.show();
boolean keyDecoded = false;
try {
BIP38PrivateKey bip38 = new BIP38PrivateKey(MainNetParams.get(), strResult);
final ECKey ecKey = bip38.decrypt(password);
if(ecKey != null && ecKey.hasPrivKey()) {
if(progress != null && progress.isShowing()) {
progress.cancel();
}
pvr.setPassword(new CharSequenceX(password));
keyDecoded = true;
Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show();
Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(MainNetParams.get()).toString(), Toast.LENGTH_SHORT).show();
}
}
catch(Exception e) {
e.printStackTrace();
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
if(progress != null && progress.isShowing()) {
progress.cancel();
}
if(keyDecoded) {
doSweep(pvr);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
});
if(!isFinishing()) {
dlg.show();
}
}
else if(privKeyReader != null) {
doSweep(privKeyReader);
}
else {
;
}
}
}
}
else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) {
;
}
else if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) {
if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("uri", strResult);
startActivity(intent);
}
}
else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) {
;
}
else {
;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
catch(JSONException je) {
;
}
catch(IOException ioe) {
;
}
catch(DecryptionException de) {
;
}
Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP);
BalanceActivity.this.startActivity(intent);
}});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if(!isFinishing()) {
alert.show();
}
return true;
}
else {
;
}
return false;
}
private void doScan() {
Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } );
startActivityForResult(intent, SCAN_QR);
}
private void doSettings() {
TimeOutUtil.getInstance().updatePin();
Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class);
startActivity(intent);
}
private void doUTXO() {
Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class);
startActivity(intent);
}
private void doFees() {
SuggestedFee highFee = FeeUtil.getInstance().getHighFee();
SuggestedFee normalFee = FeeUtil.getInstance().getNormalFee();
SuggestedFee lowFee = FeeUtil.getInstance().getLowFee();
String message = getText(R.string.current_fee_selection) + " " + (FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_hi_fee_value) + " " + (highFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_mid_fee_value) + " " + (normalFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
message += "\n";
message += getText(R.string.current_lo_fee_value) + " " + (lowFee.getDefaultPerKB().longValue() / 1000L) + " " + getText(R.string.slash_sat);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
}
private void doSweep() {
Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } );
startActivityForResult(intent, SCAN_COLD_STORAGE);
}
private void doSweep(final PrivKeyReader privKeyReader) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
try {
if(privKeyReader == null || privKeyReader.getKey() == null || !privKeyReader.getKey().hasPrivKey()) {
Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show();
return;
}
String address = privKeyReader.getKey().toAddress(MainNetParams.get()).toString();
UTXO utxo = APIFactory.getInstance(BalanceActivity.this).getUnspentOutputsForSweep(address);
if(utxo != null) {
long total_value = 0L;
final List<MyTransactionOutPoint> outpoints = utxo.getOutpoints();
for(MyTransactionOutPoint outpoint : outpoints) {
total_value += outpoint.getValue().longValue();
}
final BigInteger fee = FeeUtil.getInstance().estimatedFee(outpoints.size(), 1);
final long amount = total_value - fee.longValue();
// Log.d("BalanceActivity", "Total value:" + total_value);
// Log.d("BalanceActivity", "Amount:" + amount);
// Log.d("BalanceActivity", "Fee:" + fee.toString());
String message = "Sweep " + Coin.valueOf(amount).toPlainString() + " from " + address + " (fee:" + Coin.valueOf(fee.longValue()).toPlainString() + ")?";
AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this);
builder.setTitle(R.string.app_name);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
final ProgressDialog progress = new ProgressDialog(BalanceActivity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait_sending));
progress.show();
String receive_address = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString();
final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>();
receivers.put(receive_address, BigInteger.valueOf(amount));
org.bitcoinj.core.Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outpoints, receivers);
tx = SendFactory.getInstance(BalanceActivity.this).signTransactionForSweep(tx, privKeyReader);
final String hexTx = new String(Hex.encode(tx.bitcoinSerialize()));
// Log.d("BalanceActivity", hexTx);
try {
String response = WebUtil.getInstance(null).postURL(WebUtil.BLOCKCHAIN_DOMAIN + "pushtx", "tx=" + hexTx);
Log.d("BalanceActivity", "pushTx:" + response);
if(response.contains("Transaction Submitted")) {
Toast.makeText(BalanceActivity.this, R.string.tx_sent, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(BalanceActivity.this, R.string.cannot_sweep_privkey, Toast.LENGTH_SHORT).show();
}
}
catch(Exception e) {
Toast.makeText(BalanceActivity.this, R.string.cannot_sweep_privkey, Toast.LENGTH_SHORT).show();
}
if(progress != null && progress.isShowing()) {
progress.dismiss();
}
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
;
}
});
AlertDialog alert = builder.create();
alert.show();
}
else {
Toast.makeText(BalanceActivity.this, R.string.cannot_find_unspents, Toast.LENGTH_SHORT).show();
}
}
catch(Exception e) {
Toast.makeText(BalanceActivity.this, R.string.cannot_sweep_privkey, Toast.LENGTH_SHORT).show();
}
Looper.loop();
}
}).start();
}
private void doBackup() {
try {
final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase();
final String[] export_methods = new String[2];
export_methods[0] = getString(R.string.export_to_clipboard);
export_methods[1] = getString(R.string.export_to_email);
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.options_export)
.setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
}
catch (IOException ioe) {
;
}
catch (JSONException je) {
;
}
catch (DecryptionException de) {
;
}
catch (MnemonicException.MnemonicLengthException mle) {
;
}
String encrypted = null;
try {
encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);
} catch (Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (encrypted == null) {
Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();
return;
}
}
if (which == 0) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = null;
clip = android.content.ClipData.newPlainText("Wallet backup", encrypted);
clipboard.setPrimaryClip(clip);
Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup");
email.putExtra(Intent.EXTRA_TEXT, encrypted);
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client)));
}
dialog.dismiss();
}
}
).show();
}
catch(IOException ioe) {
ioe.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
catch(MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
}
private class TransactionAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private static final int TYPE_ITEM = 0;
private static final int TYPE_BALANCE = 1;
TransactionAdapter() {
inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
if(txs == null) {
txs = new ArrayList<Tx>();
txStates = new HashMap<String, Boolean>();
}
return txs.size() + 1;
}
@Override
public String getItem(int position) {
if(txs == null) {
txs = new ArrayList<Tx>();
txStates = new HashMap<String, Boolean>();
}
if(position == 0) {
return "";
}
return txs.get(position - 1).toString();
}
@Override
public long getItemId(int position) {
return position - 1;
}
@Override
public int getItemViewType(int position) {
return position == 0 ? TYPE_BALANCE : TYPE_ITEM;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view = null;
int type = getItemViewType(position);
if(convertView == null) {
if(type == TYPE_BALANCE) {
view = tvBalanceBar;
}
else {
view = inflater.inflate(R.layout.tx_layout_simple, parent, false);
}
}
else {
view = convertView;
}
if(type == TYPE_BALANCE) {
;
}
else {
view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((ListView)parent).performItemClick(v, position, 0);
}
});
view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((ListView)parent).performItemClick(v, position, 0);
}
});
Tx tx = txs.get(position - 1);
TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel);
String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS());
if(position == 1) {
tvTodayLabel.setText(strDateGroup);
tvTodayLabel.setVisibility(View.VISIBLE);
}
else {
Tx prevTx = txs.get(position - 2);
String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS());
if(strPrevDateGroup.equals(strDateGroup)) {
tvTodayLabel.setVisibility(View.GONE);
}
else {
tvTodayLabel.setText(strDateGroup);
tvTodayLabel.setVisibility(View.VISIBLE);
}
}
String strDetails = null;
String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS());
long _amount = 0L;
if(tx.getAmount() < 0.0) {
_amount = Math.abs((long)tx.getAmount());
strDetails = BalanceActivity.this.getString(R.string.you_sent);
}
else {
_amount = (long)tx.getAmount();
strDetails = BalanceActivity.this.getString(R.string.you_received);
}
String strAmount = null;
String strUnits = null;
if(isBTC) {
strAmount = getBTCDisplayAmount(_amount);
strUnits = getBTCDisplayUnits();
}
else {
strAmount = getFiatDisplayAmount(_amount);
strUnits = getFiatDisplayUnits();
}
TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection);
TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2);
TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails);
ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus);
TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount);
tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface());
if(tx.getAmount() < 0.0) {
tvDirection.setTextColor(Color.RED);
tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up));
}
else {
tvDirection.setTextColor(Color.GREEN);
tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down));
}
if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) {
txStates.put(tx.getHash(), false);
displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
}
else {
txStates.put(tx.getHash(), true);
displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus);
}
tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits);
if(tx.getPaymentCode() != null) {
String strTaggedTS = strTS + " ";
String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " ";
strTaggedTS += strSubText;
tvDetails.setText(strTaggedTS);
} else {
tvDetails.setText(strTS);
}
}
return view;
}
}
private void refreshTx(final boolean notifTx, final boolean fetch, final boolean dragged) {
RefreshTask refreshTask = new RefreshTask(dragged);
refreshTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, notifTx ? "1" : "0", fetch ? "1" : "0");
}
private void displayBalance() {
String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD");
double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat);
long balance = 0L;
if(SamouraiWallet.getInstance().getShowTotalBalance()) {
if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) {
balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance();
}
else {
if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) {
try {
if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) {
balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr());
}
}
catch(IOException ioe) {
;
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
}
}
}
else {
if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) {
try {
if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) {
balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr());
}
}
catch(IOException ioe) {
;
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
}
}
double btc_balance = (((double)balance) / 1e8);
double fiat_balance = btc_fx * btc_balance;
if(isBTC) {
tvBalanceAmount.setText(getBTCDisplayAmount(balance));
tvBalanceUnits.setText(getBTCDisplayUnits());
}
else {
tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance));
tvBalanceUnits.setText(strFiat);
}
}
private String getBTCDisplayAmount(long value) {
String strAmount = null;
DecimalFormat df = new DecimalFormat("
df.setMinimumIntegerDigits(1);
df.setMinimumFractionDigits(1);
df.setMaximumFractionDigits(8);
int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC);
switch(unit) {
case MonetaryUtil.MICRO_BTC:
strAmount = df.format(((double)(value * 1000000L)) / 1e8);
break;
case MonetaryUtil.MILLI_BTC:
strAmount = df.format(((double)(value * 1000L)) / 1e8);
break;
default:
strAmount = Coin.valueOf(value).toPlainString();
break;
}
return strAmount;
}
private String getBTCDisplayUnits() {
return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)];
}
private String getFiatDisplayAmount(long value) {
String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD");
double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat);
String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8));
return strAmount;
}
private String getFiatDisplayUnits() {
return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD");
}
private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) {
if(heads) {
if(confirmations == 0) {
rotateTxStatus(tvConfirmationCount, true);
ivTxStatus.setVisibility(View.VISIBLE);
ivTxStatus.setImageResource(R.drawable.ic_query_builder_white);
tvConfirmationCount.setVisibility(View.GONE);
}
else if(confirmations > 3) {
rotateTxStatus(tvConfirmationCount, true);
ivTxStatus.setVisibility(View.VISIBLE);
ivTxStatus.setImageResource(R.drawable.ic_done_white);
tvConfirmationCount.setVisibility(View.GONE);
}
else {
rotateTxStatus(ivTxStatus, false);
tvConfirmationCount.setVisibility(View.VISIBLE);
tvConfirmationCount.setText(Long.toString(confirmations));
ivTxStatus.setVisibility(View.GONE);
}
}
else {
if(confirmations < 100) {
rotateTxStatus(ivTxStatus, false);
tvConfirmationCount.setVisibility(View.VISIBLE);
tvConfirmationCount.setText(Long.toString(confirmations));
ivTxStatus.setVisibility(View.GONE);
}
else {
rotateTxStatus(ivTxStatus, false);
tvConfirmationCount.setVisibility(View.VISIBLE);
tvConfirmationCount.setText("\u221e");
ivTxStatus.setVisibility(View.GONE);
}
}
}
private void rotateTxStatus(View view, boolean clockwise) {
float degrees = 360f;
if(!clockwise) {
degrees = -360f;
}
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees);
animation.setDuration(1000);
animation.setRepeatCount(0);
animation.setInterpolator(new AnticipateInterpolator());
animation.start();
}
private void doExplorerView(String strHash) {
if(strHash != null) {
int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0);
CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerTxUrls()[sel];
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strHash));
startActivity(browserIntent);
}
}
private class RefreshTask extends AsyncTask<String, Void, String> {
private String strProgressTitle = null;
private String strProgressMessage = null;
ProgressDialog progress = null;
Handler handler = null;
private boolean dragged = false;
public RefreshTask(boolean dragged) {
super();
Log.d("BalanceActivity", "RefreshTask, dragged==" + dragged);
handler = new Handler();
this.dragged = dragged;
}
@Override
protected void onPreExecute() {
Log.d("BalanceActivity", "RefreshTask.preExecute()");
if(!dragged) {
strProgressTitle = BalanceActivity.this.getText(R.string.app_name).toString();
strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx_pre).toString();
progress = new ProgressDialog(BalanceActivity.this);
progress.setCancelable(true);
progress.setTitle(strProgressTitle);
progress.setMessage(strProgressMessage);
progress.show();
}
}
@Override
protected String doInBackground(String... params) {
Log.d("BalanceActivity", "doInBackground()");
final boolean notifTx = params[0].equals("1") ? true : false;
final boolean fetch = params[1].equals("1") ? true : false;
// TBD: check on lookahead/lookbehind for all incoming payment codes
if(fetch || txs.size() == 0) {
Log.d("BalanceActivity", "initWallet()");
APIFactory.getInstance(BalanceActivity.this).initWallet();
}
try {
int acc = 0;
if(SamouraiWallet.getInstance().getShowTotalBalance()) {
if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) {
txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs();
}
else {
acc = SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1;
txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).xpubstr());
}
}
else {
txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).xpubstr());
}
if(txs != null) {
Collections.sort(txs, new APIFactory.TxMostRecentDateComparator());
}
if(AddressFactory.getInstance().getHighestTxReceiveIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().getAddrIdx()) {
HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(acc));
}
if(AddressFactory.getInstance().getHighestTxChangeIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().getAddrIdx()) {
HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().setAddrIdx(AddressFactory.getInstance().getHighestTxChangeIdx(acc));
}
}
catch(IOException ioe) {
ioe.printStackTrace();
}
catch(MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
}
finally {
;
}
if(!dragged) {
strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx).toString();
publishProgress();
}
handler.post(new Runnable() {
public void run() {
if(dragged) {
swipeRefreshLayout.setRefreshing(false);
}
tvBalanceAmount.setText("");
tvBalanceUnits.setText("");
displayBalance();
txAdapter.notifyDataSetChanged();
}
});
PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false);
if(notifTx) {
// check for incoming payment code notification tx
try {
PaymentCode pcode = BIP47Util.getInstance(BalanceActivity.this).getPaymentCode();
APIFactory.getInstance(BalanceActivity.this).getNotifAddress(pcode.notificationAddress().getAddressString());
// Log.i("BalanceFragment", "payment code:" + pcode.toString());
// Log.i("BalanceFragment", "notification address:" + pcode.notificationAddress().getAddressString());
}
catch (AddressFormatException afe) {
afe.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
strProgressMessage = BalanceActivity.this.getText(R.string.refresh_incoming_notif_tx).toString();
publishProgress();
// check on outgoing payment code notification tx
List<Pair<String,String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed();
// Log.i("BalanceFragment", "outgoingUnconfirmed:" + outgoingUnconfirmed.size());
for(Pair<String,String> pair : outgoingUnconfirmed) {
// Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft());
// Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight());
int confirmations = APIFactory.getInstance(BalanceActivity.this).getNotifTxConfirmations(pair.getRight());
if(confirmations > 0) {
BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM);
}
if(confirmations == -1) {
BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT);
}
}
if(!dragged) {
strProgressMessage = BalanceActivity.this.getText(R.string.refresh_outgoing_notif_tx).toString();
publishProgress();
}
Intent intent = new Intent("com.samourai.wallet.BalanceActivity.RESTART_SERVICE");
LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent);
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
if(!dragged) {
if(progress != null && progress.isShowing()) {
progress.dismiss();
}
}
}
@Override
protected void onProgressUpdate(Void... values) {
if(!dragged) {
progress.setTitle(strProgressTitle);
progress.setMessage(strProgressMessage);
}
}
}
private class PoWTask extends AsyncTask<String, Void, String> {
private boolean isOK = true;
private String strBlockHash = null;
@Override
protected String doInBackground(String... params) {
strBlockHash = params[0];
JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort());
JSONObject jsonObj = jsonrpc.getBlock(strBlockHash);
if(jsonObj != null && jsonObj.has("hash")) {
PoW pow = new PoW(strBlockHash);
String hash = pow.calcHash(jsonObj);
if(hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) {
if(!pow.check(jsonObj, hash)) {
isOK = false;
}
}
else {
isOK = false;
}
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
if(!isOK) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash)
.setCancelable(false)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
}
@Override
protected void onPreExecute() {
;
}
}
private class CPFPTask extends AsyncTask<String, Void, String> {
private List<UTXO> utxos = null;
private Handler handler = null;
@Override
protected void onPreExecute() {
handler = new Handler();
utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos();
}
@Override
protected String doInBackground(String... params) {
Looper.prepare();
Log.d("BalanceActivity", "hash:" + params[0]);
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]);
if(txObj.has("inputs") && txObj.has("out")) {
try {
JSONArray inputs = txObj.getJSONArray("inputs");
JSONArray outputs = txObj.getJSONArray("out");
SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee();
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
BigInteger estimatedFee = FeeUtil.getInstance().estimatedFee(inputs.length(), outputs.length());
long total_inputs = 0L;
long total_outputs = 0L;
long fee = 0L;
UTXO utxo = null;
for(int i = 0; i < inputs.length(); i++) {
JSONObject obj = inputs.getJSONObject(i);
if(obj.has("prev_out")) {
JSONObject objPrev = obj.getJSONObject("prev_out");
if(objPrev.has("value")) {
total_inputs += objPrev.getLong("value");
}
}
}
for(int i = 0; i < outputs.length(); i++) {
JSONObject obj = outputs.getJSONObject(i);
if(obj.has("value")) {
total_outputs += obj.getLong("value");
String addr = obj.getString("addr");
Log.d("BalanceActivity", "checking address:" + addr);
if(utxo == null) {
utxo = getUTXO(addr);
}
}
}
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
boolean feeWarning = false;
fee = total_inputs - total_outputs;
if(fee > estimatedFee.longValue()) {
feeWarning = true;
}
Log.d("BalanceActivity", "total inputs:" + total_inputs);
Log.d("BalanceActivity", "total outputs:" + total_outputs);
Log.d("BalanceActivity", "fee:" + fee);
Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue());
Log.d("BalanceActivity", "fee warning:" + feeWarning);
if(utxo != null) {
Log.d("BalanceActivity", "utxo found");
List<UTXO> selectedUTXO = new ArrayList<UTXO>();
selectedUTXO.add(utxo);
int selected = utxo.getOutpoints().size();
long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L;
Log.d("BalanceActivity", "remaining fee:" + remainingFee);
int receiveIdx = AddressFactory.getInstance(BalanceActivity.this).getHighestTxReceiveIdx(0);
Log.d("BalanceActivity", "receive index:" + receiveIdx);
final String ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString();
Log.d("BalanceActivity", "receive address:" + ownReceiveAddr);
long totalAmount = utxo.getValue();
Log.d("BalanceActivity", "amount before fee:" + totalAmount);
BigInteger cpfpFee = FeeUtil.getInstance().estimatedFee(selected, 1);
Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue());
if(totalAmount < (cpfpFee.longValue() + remainingFee)) {
Log.d("BalanceActivity", "selecting additional utxo");
Collections.sort(utxos, new UTXO.UTXOComparator());
for(UTXO _utxo : utxos) {
totalAmount += _utxo.getValue();
selectedUTXO.add(_utxo);
selected += _utxo.getOutpoints().size();
cpfpFee = FeeUtil.getInstance().estimatedFee(selected, 1);
if(totalAmount >= (cpfpFee.longValue() + remainingFee)) {
break;
}
}
if(totalAmount < (cpfpFee.longValue() + remainingFee)) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
}
});
return "KO";
}
}
cpfpFee.add(BigInteger.valueOf(remainingFee));
Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue());
final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>();
for(UTXO u : selectedUTXO) {
outPoints.addAll(u.getOutpoints());
}
long _totalAmount = 0L;
for(MyTransactionOutPoint outpoint : outPoints) {
_totalAmount += outpoint.getValue().longValue();
}
Log.d("BalanceActivity", "checked total amount:" + _totalAmount);
assert(_totalAmount == totalAmount);
long amount = totalAmount - cpfpFee.longValue();
Log.d("BalanceActivity", "amount after fee:" + amount);
if(amount < SamouraiWallet.bDust.longValue()) {
Log.d("BalanceActivity", "dust output");
Toast.makeText(BalanceActivity.this, R.string.cannot_output_dust, Toast.LENGTH_SHORT).show();
}
final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>();
receivers.put(ownReceiveAddr, BigInteger.valueOf(amount));
String message = "";
if(feeWarning) {
message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary);
message += "\n\n";
}
message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC";
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ReceiveLookAtUtil.getInstance().add(ownReceiveAddr);
if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outPoints, receivers);
if(tx != null) {
tx = SendFactory.getInstance(BalanceActivity.this).signTransaction(tx);
final String hexTx = new String(Hex.encode(tx.bitcoinSerialize()));
Log.d("BalanceActivity", hexTx);
final String strTxHash = tx.getHashAsString();
Log.d("BalanceActivity", strTxHash);
boolean isOK = false;
try {
isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx);
if(isOK) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cpfp_spent, Toast.LENGTH_SHORT).show();
Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(_intent);
}
});
}
else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
}
});
// reset receive index upon tx fail
int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1;
HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx);
}
}
catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "pushTx:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
finally {
;
}
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
// reset receive index upon tx fail
int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1;
HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx);
}
catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
finally {
dialog.dismiss();
}
}
});
if(!isFinishing()) {
dlg.show();
}
}
else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cannot_create_cpfp, Toast.LENGTH_SHORT).show();
}
});
}
}
catch(final JSONException je) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "cpfp:" + je.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show();
}
});
}
Looper.loop();
return "OK";
}
@Override
protected void onPostExecute(String result) {
;
}
@Override
protected void onProgressUpdate(Void... values) {
;
}
private UTXO getUTXO(String address) {
UTXO ret = null;
int idx = -1;
for(int i = 0; i < utxos.size(); i++) {
UTXO utxo = utxos.get(i);
Log.d("BalanceActivity", "utxo address:" + utxo.getOutpoints().get(0).getAddress());
if(utxo.getOutpoints().get(0).getAddress().equals(address)) {
ret = utxo;
idx = i;
break;
}
}
if(ret != null) {
utxos.remove(idx);
return ret;
}
return null;
}
}
private class RBFTask extends AsyncTask<String, Void, String> {
private List<UTXO> utxos = null;
private Handler handler = null;
private RBFSpend rbf = null;
@Override
protected void onPreExecute() {
handler = new Handler();
utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos();
}
@Override
protected String doInBackground(final String... params) {
Looper.prepare();
Log.d("BalanceActivity", "hash:" + params[0]);
rbf = RBFUtil.getInstance().get(params[0]);
Log.d("BalanceActivity", "rbf:" + ((rbf == null) ? "null" : "not null"));
final Transaction tx = new Transaction(MainNetParams.get(), Hex.decode(rbf.getSerializedTx()));
Log.d("BalanceActivity", "tx serialized:" + rbf.getSerializedTx());
Log.d("BalanceActivity", "tx inputs:" + tx.getInputs().size());
Log.d("BalanceActivity", "tx outputs:" + tx.getOutputs().size());
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]);
if(tx != null && txObj.has("inputs") && txObj.has("out")) {
try {
JSONArray inputs = txObj.getJSONArray("inputs");
JSONArray outputs = txObj.getJSONArray("out");
SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee();
FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee());
BigInteger estimatedFee = FeeUtil.getInstance().estimatedFee(tx.getInputs().size(), tx.getOutputs().size());
long total_inputs = 0L;
long total_outputs = 0L;
long fee = 0L;
long total_change = 0L;
List<String> selfAddresses = new ArrayList<String>();
for(int i = 0; i < inputs.length(); i++) {
JSONObject obj = inputs.getJSONObject(i);
if(obj.has("prev_out")) {
JSONObject objPrev = obj.getJSONObject("prev_out");
if(objPrev.has("value")) {
total_inputs += objPrev.getLong("value");
}
}
}
for(int i = 0; i < outputs.length(); i++) {
JSONObject obj = outputs.getJSONObject(i);
if(obj.has("value")) {
total_outputs += obj.getLong("value");
String _addr = obj.getString("addr");
selfAddresses.add(_addr);
if(_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) {
total_change += obj.getLong("value");
}
}
}
boolean feeWarning = false;
fee = total_inputs - total_outputs;
if(fee > estimatedFee.longValue()) {
feeWarning = true;
}
long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L;
Log.d("BalanceActivity", "total inputs:" + total_inputs);
Log.d("BalanceActivity", "total outputs:" + total_outputs);
Log.d("BalanceActivity", "total change:" + total_change);
Log.d("BalanceActivity", "fee:" + fee);
Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue());
Log.d("BalanceActivity", "fee warning:" + feeWarning);
Log.d("BalanceActivity", "remaining fee:" + remainingFee);
List<TransactionOutput> txOutputs = new ArrayList<TransactionOutput>();
txOutputs.addAll(tx.getOutputs());
long remainder = remainingFee;
if(total_change > remainder) {
for(TransactionOutput output : txOutputs) {
if(rbf.getChangeAddrs().contains(output.getAddressFromP2PKHScript(MainNetParams.get()).toString())) {
if(output.getValue().longValue() >= (remainder + SamouraiWallet.bDust.longValue())) {
output.setValue(Coin.valueOf(output.getValue().longValue() - remainder));
remainder = 0L;
break;
}
else {
remainder -= output.getValue().longValue();
output.setValue(Coin.valueOf(0L)); // output will be discarded later
}
}
}
}
// original inputs are not modified
List<MyTransactionInput> _inputs = new ArrayList<MyTransactionInput>();
List<TransactionInput> txInputs = tx.getInputs();
for(TransactionInput input : txInputs) {
MyTransactionInput _input = new MyTransactionInput(MainNetParams.get(), null, new byte[0], input.getOutpoint(), input.getOutpoint().getHash().toString(), (int)input.getOutpoint().getIndex());
_input.setSequenceNumber(1L);
_inputs.add(_input);
Log.d("BalanceActivity", "add outpoint:" + _input.getOutpoint().toString());
}
if(remainder > 0L) {
List<UTXO> selectedUTXO = new ArrayList<UTXO>();
long selectedAmount = 0L;
int selected = 0;
long _remainingFee = remainder;
Collections.sort(utxos, new UTXO.UTXOComparator());
for(UTXO _utxo : utxos) {
Log.d("BalanceActivity", "utxo value:" + _utxo.getValue());
// do not select utxo that are change outputs in current rbf tx
boolean isChange = false;
boolean isSelf = false;
for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) {
if(rbf.containsChangeAddr(outpoint.getAddress())) {
Log.d("BalanceActivity", "is change:" + outpoint.getAddress());
Log.d("BalanceActivity", "is change:" + outpoint.getValue().longValue());
isChange = true;
break;
}
if(selfAddresses.contains(outpoint.getAddress())) {
Log.d("BalanceActivity", "is self:" + outpoint.getAddress());
Log.d("BalanceActivity", "is self:" + outpoint.getValue().longValue());
isSelf = true;
break;
}
}
if(isChange || isSelf) {
continue;
}
selectedUTXO.add(_utxo);
selected += _utxo.getOutpoints().size();
Log.d("BalanceActivity", "selected utxo:" + selected);
selectedAmount += _utxo.getValue();
Log.d("BalanceActivity", "selected utxo value:" + _utxo.getValue());
_remainingFee = FeeUtil.getInstance().estimatedFee(inputs.length() + selected, outputs.length() == 1 ? 2 : outputs.length()).longValue();
Log.d("BalanceActivity", "_remaining fee:" + _remainingFee);
if(selectedAmount >= (_remainingFee + SamouraiWallet.bDust.longValue())) {
break;
}
}
long extraChange = 0L;
if(selectedAmount < (_remainingFee + SamouraiWallet.bDust.longValue())) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show();
}
});
return "KO";
}
else {
extraChange = selectedAmount - _remainingFee;
Log.d("BalanceActivity", "extra change:" + extraChange);
}
boolean addedChangeOutput = false;
// parent tx didn't have change output
if(outputs.length() == 1 && extraChange > 0L) {
try {
int changeIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddrIdx();
String change_address = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddressAt(changeIdx).getAddressString();
Script toOutputScript = ScriptBuilder.createOutputScript(org.bitcoinj.core.Address.fromBase58(MainNetParams.get(), change_address));
TransactionOutput output = new TransactionOutput(MainNetParams.get(), null, Coin.valueOf(extraChange), toOutputScript.getProgram());
txOutputs.add(output);
addedChangeOutput = true;
}
catch(MnemonicException.MnemonicLengthException | IOException e) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show();
}
});
return "KO";
}
}
// parent tx had change output
else {
for(TransactionOutput output : txOutputs) {
Log.d("BalanceActivity", "checking for change:" + output.getAddressFromP2PKHScript(MainNetParams.get()).toString());
if(rbf.containsChangeAddr(output.getAddressFromP2PKHScript(MainNetParams.get()).toString())) {
Log.d("BalanceActivity", "before extra:" + output.getValue().longValue());
output.setValue(Coin.valueOf(extraChange + output.getValue().longValue()));
Log.d("BalanceActivity", "after extra:" + output.getValue().longValue());
addedChangeOutput = true;
break;
}
}
}
// sanity check
if(extraChange > 0L && !addedChangeOutput) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show();
}
});
return "KO";
}
// update keyBag w/ any new paths
final HashMap<String,String> keyBag = rbf.getKeyBag();
for(UTXO _utxo : selectedUTXO) {
for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) {
MyTransactionInput _input = new MyTransactionInput(MainNetParams.get(), null, new byte[0], outpoint, outpoint.getTxHash().toString(), outpoint.getTxOutputN());
_input.setSequenceNumber(1L);
_inputs.add(_input);
Log.d("BalanceActivity", "add selected outpoint:" + _input.getOutpoint().toString());
String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(outpoint.getAddress());
if(path != null) {
rbf.addKey(outpoint.toString(), path);
}
else {
String pcode = BIP47Meta.getInstance().getPCode4Addr(outpoint.getAddress());
int idx = BIP47Meta.getInstance().getIdx4Addr(outpoint.getAddress());
rbf.addKey(outpoint.toString(), pcode + "/" + idx);
}
}
}
rbf.setKeyBag(keyBag);
}
// BIP69 sort of outputs/inputs
final Transaction _tx = new Transaction(MainNetParams.get());
List<TransactionOutput> _txOutputs = new ArrayList<TransactionOutput>();
_txOutputs.addAll(txOutputs);
Collections.sort(_txOutputs, new SendFactory.BIP69OutputComparator());
for(TransactionOutput to : _txOutputs) {
// zero value outputs discarded here
if(to.getValue().longValue() > 0L) {
_tx.addOutput(to);
}
}
List<MyTransactionInput> __inputs = new ArrayList<MyTransactionInput>();
__inputs.addAll(_inputs);
Collections.sort(__inputs, new SendFactory.BIP69InputComparator());
for(TransactionInput input : __inputs) {
_tx.addInput(input);
}
FeeUtil.getInstance().setSuggestedFee(suggestedFee);
String message = "";
if(feeWarning) {
message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary);
message += "\n\n";
}
message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC";
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Transaction __tx = signTx(_tx);
final String hexTx = new String(Hex.encode(__tx.bitcoinSerialize()));
Log.d("BalanceActivity", hexTx);
final String strTxHash = __tx.getHashAsString();
Log.d("BalanceActivity", strTxHash);
if(__tx != null) {
boolean isOK = false;
try {
isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx);
if(isOK) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.rbf_spent, Toast.LENGTH_SHORT).show();
RBFSpend _rbf = rbf; // includes updated 'keyBag'
_rbf.setSerializedTx(hexTx);
_rbf.setHash(strTxHash);
_rbf.setPrevHash(params[0]);
RBFUtil.getInstance().add(_rbf);
Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(_intent);
}
});
}
else {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show();
}
});
}
}
catch(final DecoderException de) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
finally {
;
}
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if(!isFinishing()) {
dlg.show();
}
}
catch(final JSONException je) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(BalanceActivity.this, "rbf:" + je.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
else {
Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show();
}
Looper.loop();
return "OK";
}
@Override
protected void onPostExecute(String result) {
;
}
@Override
protected void onProgressUpdate(Void... values) {
;
}
private Transaction signTx(Transaction tx) {
HashMap<String,ECKey> keyBag = new HashMap<String,ECKey>();
HashMap<String,String> keys = rbf.getKeyBag();
for(String outpoint : keys.keySet()) {
ECKey ecKey = null;
String[] s = keys.get(outpoint).split("/");
if(s.length == 3) {
HD_Address hd_address = AddressFactory.getInstance(BalanceActivity.this).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2]));
String strPrivKey = hd_address.getPrivateKeyString();
DumpedPrivateKey pk = new DumpedPrivateKey(MainNetParams.get(), strPrivKey);
ecKey = pk.getKey();
}
else if(s.length == 2) {
try {
PaymentAddress address = BIP47Util.getInstance(BalanceActivity.this).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1]));
ecKey = address.getReceiveECKey();
}
catch(Exception e) {
;
}
}
else {
;
}
Log.i("BalanceActivity", "outpoint:" + outpoint);
Log.i("BalanceActivity", "ECKey address from ECKey:" + ecKey.toAddress(MainNetParams.get()).toString());
if(ecKey != null) {
keyBag.put(outpoint, ecKey);
}
else {
throw new RuntimeException("ECKey error: cannot process private key");
// Log.i("ECKey error", "cannot process private key");
}
}
List<TransactionInput> inputs = tx.getInputs();
for (int i = 0; i < inputs.size(); i++) {
ECKey ecKey = keyBag.get(inputs.get(i).getOutpoint().toString());
Log.i("BalanceActivity", "sign outpoint:" + inputs.get(i).getOutpoint().toString());
Log.i("BalanceActivity", "ECKey address from keyBag:" + ecKey.toAddress(MainNetParams.get()).toString());
Log.i("BalanceActivity", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(MainNetParams.get())));
Log.i("BalanceActivity", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(MainNetParams.get())).getProgram()));
TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(MainNetParams.get())).getProgram(), Transaction.SigHash.ALL, false);
tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey));
}
return tx;
}
}
}
|
package jp.ddo.masm11.cplayer;
import android.app.Service;
import android.media.MediaPlayer;
import android.net.Uri;
import android.content.Intent;
import android.os.IBinder;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class PlayerService extends Service {
private String topDir;
private String playingPath, nextPath;
private MediaPlayer curPlayer, nextPlayer;
@Override
public void onCreate() {
topDir = "/sdcard/Music";
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent != null ? intent.getAction() : null;
if (action != null) {
String path;
int ctxt;
switch (action) {
case "PLAY":
path = intent.getStringExtra("path");
if (path == null)
break;
play(path);
enqueueNext();
break;
case "SET_TOPDIR":
path = intent.getStringExtra("path");
if (path == null)
break;
// setTopDir(path);
break;
}
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void play(String path) {
android.util.Log.i("PlayerService", "path=" + path);
playingPath = path;
try {
if (curPlayer != null) {
curPlayer.release();
curPlayer = null;
}
} catch (Exception e) {
android.util.Log.e("cplayer", "exception", e);
}
try {
if (nextPlayer != null) {
nextPlayer.release();
nextPlayer = null;
}
} catch (Exception e) {
android.util.Log.e("cplayer", "exception", e);
}
HashSet<String> tested = new HashSet<>();
while (true) {
try {
if (tested.contains(playingPath)) {
break;
}
tested.add(playingPath);
curPlayer = MediaPlayer.create(this, Uri.parse("file://" + playingPath));
if (curPlayer == null) {
android.util.Log.w("PlayerService", "MediaPlayer.create() failed: " + playingPath);
playingPath = selectNext(playingPath);
continue;
}
curPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
playingPath = nextPath;
curPlayer = nextPlayer;
mp.release();
nextPath = null;
nextPlayer = null;
enqueueNext();
}
});
curPlayer.start();
break;
} catch (Exception e) {
android.util.Log.e("cplayer", "exception", e);
}
}
}
private void enqueueNext() {
try {
if (nextPlayer != null) {
nextPlayer.release();
nextPlayer = null;
}
} catch (Exception e) {
android.util.Log.e("cplayer", "exception", e);
}
HashSet<String> tested = new HashSet<>();
nextPath = selectNext(playingPath);
while (true) {
try {
if (tested.contains(nextPath)) {
break;
}
tested.add(nextPath);
nextPlayer = MediaPlayer.create(this, Uri.parse("file://" + nextPath));
if (nextPlayer == null) {
android.util.Log.w("PlayerService", "MediaPlayer.create() failed: " + nextPath);
nextPath = selectNext(nextPath);
continue;
}
nextPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
playingPath = nextPath;
curPlayer = nextPlayer;
mp.release();
nextPath = null;
nextPlayer = null;
enqueueNext();
}
});
curPlayer.setNextMediaPlayer(nextPlayer);
break;
} catch (Exception e) {
android.util.Log.e("cplayer", "exception", e);
}
}
}
private String selectNext(String nextOf) {
// fixme:
ArrayList<String> list = new ArrayList<>();
scan(new File(topDir), list);
Collections.sort(list);
for (String path: list) {
if (path.compareTo(nextOf) > 0)
return path;
}
try {
// loop.
return list.get(0);
} catch (IndexOutOfBoundsException e) {
return null;
}
}
private void scan(File dir, ArrayList<String> scanResult) {
for (File file: dir.listFiles()) {
if (file.isDirectory())
scan(file, scanResult);
else
scanResult.add(file.getAbsolutePath());
}
}
}
|
package org.redcross.openmapkit;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.TouchDelegate;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.cocoahero.android.geojson.FeatureCollection;
import com.mapbox.mapboxsdk.geometry.BoundingBox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.overlay.LocationXMLParser;
import com.mapbox.mapboxsdk.overlay.Marker;
import com.mapbox.mapboxsdk.overlay.PathOverlay;
import com.mapbox.mapboxsdk.util.DataLoadingUtils;
import com.mapbox.mapboxsdk.views.MapView;
import com.spatialdev.osm.events.OSMSelectionListener;
import com.spatialdev.osm.model.OSMElement;
import com.vividsolutions.jts.geom.Point;
import org.redcross.openmapkit.odkcollect.ODKCollectHandler;
import org.redcross.openmapkit.tagswipe.TagSwipeActivity;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
public class MapActivity extends ActionBarActivity implements OSMSelectionListener {
private static double boundRadius;
protected static final String PREVIOUS_LAT = "org.redcross.openmapkit.PREVIOUS_LAT";
protected static final String PREVIOUS_LNG = "org.redcross.openmapkit.PREVIOUS_LNG";
protected static final String PREVIOUS_ZOOM = "org.redcross.openmapkit.PREVIOUS_ZOOM";
private static String version = "";
protected MapView mapView;
protected ListView mTagListView;
protected ImageButton mCloseListViewButton;
protected LinearLayout mTopLinearLayout;
protected LinearLayout mBottomLinearLayout;
protected TextView mTagTextView;
protected Basemap basemap;
protected TagListAdapter tagListAdapter;
/**
* intent request codes
*/
private static final int ODK_COLLECT_TAG_ACTIVITY_CODE = 2015;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
determineVersion();
if (android.os.Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.osm_light_green));
}
// create directory structure for app if needed
ExternalStorage.checkOrCreateAppDirs();
// Register the intent to the ODKCollect handler
// This will determine if we are in ODK Collect Mode or not.
ODKCollectHandler.registerIntent(getIntent());
//set layout
setContentView(R.layout.activity_map);
//get the layout the ListView is nested in
mBottomLinearLayout = (LinearLayout) findViewById(R.id.bottomLinearLayout);
//the ListView from layout
mTagListView = (ListView) findViewById(R.id.tagListView);
//the ListView close image button
mCloseListViewButton = (ImageButton) findViewById(R.id.imageViewCloseList);
//get the layout the Map is nested in
mTopLinearLayout = (LinearLayout) findViewById(R.id.topLinearLayout);
//get map from layout
mapView = (MapView) findViewById(R.id.mapView);
// initialize basemap object
basemap = new Basemap(this);
initializeOsmXml();
//add user location toggle button
initializeLocationButton();
positionMap();
addGeojsonOverlay();
initializeListView();
//Initialize location settings.
try {
LocationXMLParser.parseXML(this);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
saveMapPosition();
}
protected void saveMapPosition() {
LatLng c = mapView.getCenter();
float lat = (float) c.getLatitude();
float lng = (float) c.getLongitude();
float z = mapView.getZoomLevel();
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putFloat(PREVIOUS_LAT, lat);
editor.putFloat(PREVIOUS_LNG, lng);
editor.putFloat(PREVIOUS_ZOOM, z);
editor.apply();
}
protected void positionMap() {
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
double lat = (double) pref.getFloat(PREVIOUS_LAT, -999);
double lng = (double) pref.getFloat(PREVIOUS_LNG, -999);
float z = pref.getFloat(PREVIOUS_ZOOM, -999);
// no shared pref
if (lat == -999 || lng == -999 || z == -999) {
mapView.setUserLocationEnabled(true);
mapView.goToUserLocation(true);
if (z == -999) {
mapView.setUserLocationRequiredZoom(50);
} else {
mapView.setUserLocationRequiredZoom(z);
}
}
// there is a shared pref
else {
LatLng c = new LatLng(lat, lng);
mapView.setCenter(c);
mapView.setZoom(z);
mapView.setUserLocationEnabled(true);
}
}
protected void addGeojsonOverlay() {
mapView.loadFromGeoJSONURL("http://api.mspray.onalabs.org/buffers.json?target_area=408_257");
mapView.loadFromGeoJSONURL("http://api.mspray.onalabs.org/targetareas.json?target_area=408_257");
mapView.loadFromGeoJSONURL("http://api.mspray.onalabs.org/spraydays.json?spray_date=&target_area=408_257");
mapView.loadFromGeoJSONURL("http://api.mspray.onalabs.org/districts.json?district=Milenge");
}
/**
* For initializing the ListView of tags
*/
protected void initializeListView() {
//the ListView title
mTagTextView = (TextView) findViewById(R.id.tagTextView);
mTagTextView.setText(R.string.tagListViewTitle);
//hide the ListView by default
proportionMapAndList(100, 0);
//handle when user taps on the close button in the list view
mCloseListViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
proportionMapAndList(100, 0);
}
});
//increase the 'hit area' of the down arrow
View parent = findViewById(R.id.bottomLinearLayout);
parent.post(new Runnable() {
public void run() {
Rect delegateArea = new Rect();
ImageButton delegate = mCloseListViewButton;
delegate.getHitRect(delegateArea);
delegateArea.top -= 100;
delegateArea.bottom += 100;
delegateArea.left -= 100;
delegateArea.right += 100;
TouchDelegate expandedArea = new TouchDelegate(delegateArea, delegate);
if (View.class.isInstance(delegate.getParent())) {
((View) delegate.getParent()).setTouchDelegate(expandedArea);
}
}
});
//handle list view item taps
mTagListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tappedKey = tagListAdapter.getTagKeyForIndex(position);
//launch the TagSwipeActivity and pass the key
Intent tagSwipe = new Intent(getApplicationContext(), TagSwipeActivity.class);
tagSwipe.putExtra("TAG_KEY", tappedKey);
startActivityForResult(tagSwipe, ODK_COLLECT_TAG_ACTIVITY_CODE);
}
});
}
/**
* For identifying an OSM element and presenting it's tags in the ListView
*
* @param osmElement The target OSMElement.
*/
protected void identifyOSMFeature(OSMElement osmElement) {
//pass the tags to the list adapter
tagListAdapter = new TagListAdapter(this, osmElement);
if (!tagListAdapter.isEmpty()) {
//set the ListView's adapter
mTagListView.setAdapter(tagListAdapter);
//show the ListView under the map
proportionMapAndList(50, 50);
}
}
/**
* For setting the proportions of the Map weight and the ListView weight for dual display
*
* @param topWeight Refers to the layout weight. Note, topWeight + bottomWeight must equal the weight sum of 100
* @param bottomWeight Referes to the layotu height. Note, bottomWeight + topWeight must equal the weight sum of 100
*/
protected void proportionMapAndList(int topWeight, int bottomWeight) {
LinearLayout.LayoutParams topLayoutParams = (LinearLayout.LayoutParams) mTopLinearLayout.getLayoutParams();
LinearLayout.LayoutParams bottomLayoutParams = (LinearLayout.LayoutParams) mBottomLinearLayout.getLayoutParams();
//update weight of top and bottom linear layouts
mTopLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(topLayoutParams.width, topLayoutParams.height, topWeight));
mBottomLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(bottomLayoutParams.width, bottomLayoutParams.height, bottomWeight));
}
/**
* Loads OSM XML stored on the device.
*/
protected void initializeOsmXml() {
try {
OSMMapBuilder.buildMapFromExternalStorage(this);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* For instantiating the location button and setting up its tap event handler
*/
protected void initializeLocationButton() {
//instantiate location button
final ImageButton locationButton = (ImageButton) findViewById(R.id.locationButton);
//set tap event - centres map on the user location.
locationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mapView.setUserLocationEnabled(true);
mapView.goToUserLocation(true);
}
});
}
/**
* For presenting a dialog to allow the user to choose which OSM XML files to use that have been uploaded to their device's openmapkit/osm folder
*/
private void presentOSMOptions() {
final File[] osmFiles = ExternalStorage.fetchOSMXmlFiles();
String[] osmFileNames = ExternalStorage.fetchOSMXmlFileNames();
final boolean[] checkedOsmFiles = OSMMapBuilder.isFileArraySelected(osmFiles);
final Set<File> filesToAdd = new HashSet<>();
final Set<File> filesToRemove = new HashSet<>();
if (osmFileNames.length > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.osmChooserDialogTitle));
builder.setMultiChoiceItems(osmFileNames, checkedOsmFiles, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
// load the file
if (isChecked) {
File fileToAdd = osmFiles[i];
filesToAdd.add(fileToAdd);
}
// remove the file
else {
File fileToRemove = osmFiles[i];
filesToRemove.add(fileToRemove);
}
}
});
//handle OK tap event of dialog
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
OSMMapBuilder.removeOSMFilesFromModel(filesToRemove);
OSMMapBuilder.addOSMFilesToModel(filesToAdd);
}
});
//handle cancel button tap event of dialog
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//user clicked cancel
}
});
builder.show();
} else {
Toast prompt = Toast.makeText(getApplicationContext(), "Please add .osm files to " + ExternalStorage.getOSMDir(), Toast.LENGTH_LONG);
prompt.show();
}
}
private void downloadOSM() {
BoundingBox bbox = mapView.getBoundingBox();
OSMDownloader downloader = new OSMDownloader(this, bbox);
downloader.execute();
}
/**
* For adding action items to the action bar
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_map, menu);
return true;
}
/**
* For handling when a user taps on a menu item (top right)
*/
@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.
super.onOptionsItemSelected(item);
int id = item.getItemId();
if (id == R.id.osmdownloader) {
downloadOSM();
return true;
} else if (id == R.id.mbtilessettings) {
basemap.presentMBTilesOptions();
return true;
} else if (id == R.id.osmsettings) {
presentOSMOptions();
return true;
}
return false;
}
@Override
public void selectedElementsChanged(LinkedList<OSMElement> selectedElements) {
if (selectedElements != null && selectedElements.size() > 0) {
//tagsButton.setVisibility(View.VISIBLE);
//fetch the tapped feature
OSMElement tappedOSMElement = selectedElements.get(0);
boolean userLocationIsEnabled = mapView.getUserLocationEnabled();
if (userLocationIsEnabled && LocationXMLParser.isProximityEnabled()) {
//Checks whether tappedElement is within select range.
if (isWithinDistance(tappedOSMElement)) {
//present OSM Feature tags in bottom ListView
identifyOSMFeature(tappedOSMElement);
} else {
//Ignore points outside proximity boundary.
tappedOSMElement.deselectAll();
}
} else {
//If GPS is disabled, user can select any point.
identifyOSMFeature(tappedOSMElement);
}
}
}
/**
* @param tappedOSMElement selected point
* @return true if the element is within specified radius.
*/
private boolean isWithinDistance(OSMElement tappedOSMElement) {
LatLng userPos = getUserLocation();
double userLat = userPos.getLatitude();
double userLong = userPos.getLongitude();
Point cPoint = tappedOSMElement.getJTSGeom().getCentroid();
double osmElemLat = cPoint.getY();
double osmElemLong = cPoint.getX();
/**GeometryFactory geometryFactory = new GeometryFactory();
Coordinate cord = new Coordinate(userLong, userLat);
Geometry geo = geometryFactory.createPoint(cord);
return tappedOSMElement.getJTSGeom().isWithinDistance(geo, boundRadius);*/
boundRadius = LocationXMLParser.getProximityRadius();
return distance(userLat, osmElemLat, userLong, osmElemLong) <= boundRadius;
}
/**
* @param lat1
* @param lat2
* @param lng1
* @param lng2
* @return distance between 2 points in map.
*/
public double distance(double lat1, double lat2, double lng1, double lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = (double) (earthRadius * c);
return dist;
}
/**
* @return current location of user.
*/
public LatLng getUserLocation() {
return mapView.getUserLocation();
}
/**
* For sending results from the 'create tag' or 'edit tag' activities back to a third party app (e.g. ODK Collect)
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ODK_COLLECT_TAG_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
String osmXmlFileFullPath = ODKCollectHandler.getODKCollectData().getOSMFileFullPath();
String osmXmlFileName = ODKCollectHandler.getODKCollectData().getOSMFileName();
Intent resultIntent = new Intent();
resultIntent.putExtra("OSM_PATH", osmXmlFileFullPath);
resultIntent.putExtra("OSM_FILE_NAME", osmXmlFileName);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
}
public MapView getMapView() {
return mapView;
}
private void determineVersion() {
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
public static String getVersion() {
return version;
}
}
|
package me.openphoto.android.app;
import java.util.ArrayList;
import me.openphoto.android.app.bitmapfun.util.ImageCache;
import me.openphoto.android.app.bitmapfun.util.ImageFetcher;
import me.openphoto.android.app.bitmapfun.util.ImageWorker;
import me.openphoto.android.app.model.Photo;
import me.openphoto.android.app.net.PhotoResponse;
import me.openphoto.android.app.net.ReturnSizes;
import me.openphoto.android.app.ui.adapter.PhotosEndlessAdapter;
import me.openphoto.android.app.ui.widget.ViewPagerWithDisableSupport;
import me.openphoto.android.app.ui.widget.ViewPagerWithDisableSupport.GesturesEnabledHandler;
import me.openphoto.android.app.util.GuiUtils;
import me.openphoto.android.app.util.LoadingControl;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.WazaBe.HoloEverywhere.LayoutInflater;
import com.WazaBe.HoloEverywhere.sherlock.SActivity;
import com.polites.android.GestureImageView;
/**
* The general photo viewing screen
*
* @author pboos
* @version 05.10.2012 <br>
* - removed action bar reference <br>
* - removed custom onClick listener from the ImageView
* <p>
* 03.10.2012 <br>
* - added initial support for album photos filter
*/
public class PhotoDetailsActivity extends SActivity {
public static final String EXTRA_PHOTO = "EXTRA_PHOTO";
public static final String EXTRA_ADAPTER_PHOTOS = "EXTRA_ADAPTER_PHOTOS";
public static final String EXTRA_ADAPTER_POSITION = "EXTRA_ADAPTER_POSITION";
public static final String EXTRA_ADAPTER_TAGS = "EXTRA_ADAPTER_TAGS";
public static final String EXTRA_ADAPTER_ALBUM = "EXTRA_ADAPTER_ALBUM";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new UiFragment())
.commit();
}
}
public static class UiFragment extends CommonFrargmentWithImageWorker
{
private static final String TAG = PhotoDetailsActivity.class.getSimpleName();
private static final String IMAGE_CACHE_DIR = HomeFragment.IMAGE_CACHE_DIR;
private ViewPagerWithDisableSupport mViewPager;
private PhotoDetailPagerAdapter mAdapter;
private ImageWorker mImageWorker;
private ReturnSizes returnSizes;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.activity_photo_details, container, false);
return v;
}
@Override
public void onViewCreated(View view) {
super.onViewCreated(view);
init(view);
}
void init(View v)
{
Intent intent = getActivity().getIntent();
if (intent.hasExtra(EXTRA_PHOTO)) {
Photo photo = intent.getParcelableExtra(EXTRA_PHOTO);
ArrayList<Photo> photos = new ArrayList<Photo>();
photos.add(photo);
mAdapter = new PhotoDetailPagerAdapter(new PhotosAdapter(getActivity(), photos));
} else if (getActivity().getIntent().hasExtra(EXTRA_ADAPTER_PHOTOS)) {
ArrayList<Photo> photos = intent.getParcelableArrayListExtra(
EXTRA_ADAPTER_PHOTOS);
String tags = intent.getStringExtra(EXTRA_ADAPTER_TAGS);
String album = intent.getStringExtra(EXTRA_ADAPTER_ALBUM);
mAdapter = new PhotoDetailPagerAdapter(new PhotosAdapter(getActivity(),
photos, tags, album));
}
mViewPager = (ViewPagerWithDisableSupport) v.findViewById(R.id.photos);
mViewPager.setAdapter(mAdapter);
mViewPager.setGesturesEnabledHandler(new GesturesEnabledHandler() {
@Override
public boolean isEnabled() {
return !mAdapter.isCurrentImageZoomed();
}
});
int position = intent.getIntExtra(EXTRA_ADAPTER_POSITION, 0);
if (position > 0) {
mViewPager.setCurrentItem(position);
}
}
@Override
protected void initImageWorker()
{
returnSizes = PhotosEndlessAdapter.SIZE_BIG;
mImageWorker = new ImageFetcher(getActivity(), null, returnSizes.getWidth(),
returnSizes.getHeight());
mImageWorker.setImageCache(ImageCache.findOrCreateCache(getActivity(),
IMAGE_CACHE_DIR));
mImageWorker.setImageFadeIn(false);
}
private class PhotoDetailPagerAdapter extends PagerAdapter {
private final LayoutInflater mInflator;
private final PhotosAdapter mAdapter;
private View mCurrentView;
private final DataSetObserver mObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
super.onInvalidated();
notifyDataSetChanged();
}
};
public PhotoDetailPagerAdapter(PhotosAdapter adatper) {
mAdapter = adatper;
mAdapter.registerDataSetObserver(mObserver);
mInflator = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mAdapter.getCount();
}
@Override
public Object instantiateItem(View collection, int position) {
if (getCount() > 1 && position > getCount() - 6) {
mAdapter.loadNextPage();
}
Photo photo = (Photo) mAdapter.getItem(position);
final View view = mInflator.inflate(R.layout.item_photo_detail,
((ViewPager) collection), false);
final ImageView imageView = (ImageView) view.findViewById(R.id.image);
TextView titleText = (TextView) view.findViewById(R.id.image_title);
TextView descriptionText = (TextView) view.findViewById(R.id.image_description);
titleText.setText(photo.getTitle());
descriptionText.setText(photo.getDescription());
if (TextUtils.isEmpty(photo.getTitle())) {
titleText.setVisibility(View.GONE);
if (TextUtils.isEmpty(photo.getDescription())) {
view.findViewById(R.id.image_details).setVisibility(View.GONE);
}
}
if (TextUtils.isEmpty(photo.getDescription())) {
descriptionText.setVisibility(View.GONE);
}
LoadingControl loadingControl = new LoadingControl() {
private int mLoaders = 0;
@Override
public void stopLoading() {
if (--mLoaders == 0)
{
try
{
view.findViewById(R.id.loading).setVisibility(View.GONE);
} catch (Exception ex)
{
GuiUtils.noAlertError(TAG, null, ex);
}
}
}
@Override
public void startLoading() {
if (mLoaders++ == 0)
{
try
{
view.findViewById(R.id.loading).setVisibility(View.VISIBLE);
} catch (Exception ex)
{
GuiUtils.noAlertError(TAG, null, ex);
}
}
}
};
loadingControl.startLoading();
String url = photo.getUrl(returnSizes.toString());
if (url != null) {
mImageWorker.loadImage(url, imageView, loadingControl);
} else {
new LoadImageTask(photo, imageView, loadingControl).execute();
}
loadingControl.stopLoading();
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View collection, int position, Object view) {
View theView = (View) view;
ImageView imageView = (ImageView) theView.findViewById(R.id.image);
ImageWorker.cancelWork(imageView);
imageView.setImageBitmap(null);
((ViewPager) collection).removeView(theView);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((View) object);
}
@Override
public void finishUpdate(View arg0) {
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
mCurrentView = (View) object;
}
boolean isCurrentImageZoomed()
{
if (mCurrentView != null)
{
GestureImageView giv = (GestureImageView)
mCurrentView.findViewById(R.id.image);
return giv.isZoomed();
}
return false;
}
}
private class PhotosAdapter extends PhotosEndlessAdapter {
public PhotosAdapter(Context context, ArrayList<Photo> photos) {
super(context, photos);
}
public PhotosAdapter(Context context, ArrayList<Photo> photos,
String tags,
String album)
{
super(context, photos, tags, album);
}
@Override
protected void onStartLoading() {
}
@Override
protected void onStoppedLoading() {
}
@Override
public View getView(Photo item, View convertView, ViewGroup parent) {
return null;
}
}
private class LoadImageTask extends AsyncTask<Void, Void, Boolean> {
private Photo mPhoto;
private final ImageView mImageView;
private final LoadingControl loadingControl;
public LoadImageTask(Photo photo, ImageView imageView, LoadingControl loadingControl) {
mPhoto = photo;
mImageView = imageView;
this.loadingControl = loadingControl;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingControl.startLoading();
}
@Override
protected Boolean doInBackground(Void... params) {
try {
PhotoResponse response = Preferences.getApi(getActivity())
.getPhoto(
mPhoto.getId(), returnSizes);
mPhoto = response.getPhoto();
return true;
} catch (Exception e) {
GuiUtils.error(TAG, R.string.errorCouldNotGetPhoto, e);
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result.booleanValue())
{
String url = mPhoto.getUrl(returnSizes.toString());
mImageWorker.loadImage(url, mImageView, loadingControl);
}
loadingControl.stopLoading();
}
}
}
}
|
package org.commcare.preferences;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.widget.Toast;
import org.commcare.CommCareApp;
import org.commcare.CommCareApplication;
import org.commcare.activities.SessionAwarePreferenceActivity;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.google.services.analytics.GoogleAnalyticsFields;
import org.commcare.google.services.analytics.GoogleAnalyticsUtils;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.utils.TemplatePrinterUtils;
import org.javarosa.core.services.locale.Localization;
import java.util.HashMap;
import java.util.Map;
public class DeveloperPreferences extends SessionAwarePreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final int RESULT_SYNC_CUSTOM = Activity.RESULT_FIRST_USER + 1;
public static final int REQUEST_SYNC_FILE = 1;
public final static String PREFS_CUSTOM_RESTORE_DOC_LOCATION = "cc-custom-restore-doc-location";
public static final String SUPERUSER_ENABLED = "cc-superuser-enabled";
public static final String NAV_UI_ENABLED = "cc-nav-ui-enabled";
public static final String CSS_ENABLED = "cc-css-enabled";
public static final String MARKDOWN_ENABLED = "cc-markdown-enabled";
public static final String ACTION_BAR_ENABLED = "cc-action-nav-enabled";
public static final String LIST_REFRESH_ENABLED = "cc-list-refresh";
public static final String HOME_REPORT_ENABLED = "cc-home-report";
public static final String AUTO_PURGE_ENABLED = "cc-auto-purge";
public static final String LOAD_FORM_PAYLOAD_AS = "cc-form-payload-status";
public static final String DETAIL_TAB_SWIPE_ACTION_ENABLED = "cc-detail-final-swipe-enabled";
public static final String USE_ROOT_MENU_AS_HOME_SCREEN = "cc-use-root-menu-as-home-screen";
public static final String SHOW_ADB_ENTITY_LIST_TRACES = "cc-show-entity-trace-outputs";
public static final String USE_OBFUSCATED_PW = "cc-use-pw-obfuscation";
public static final String ENABLE_BULK_PERFORMANCE = "cc-enable-bulk-performance";
public static final String SHOW_UPDATE_OPTIONS_SETTING = "cc-show-update-target-options";
/**
* Stores last used password and performs auto-login when that password is
* present
*/
public final static String ENABLE_AUTO_LOGIN = "cc-enable-auto-login";
public final static String ENABLE_SAVE_SESSION = "cc-enable-session-saving";
/**
* Stores the navigation and form entry sessions as one string for user manipulation
*/
public final static String EDIT_SAVE_SESSION = "__edit_session_save";
/**
* Spacer to distinguish between the saved navigation session and form entry session
*/
private static final String NAV_AND_FORM_SESSION_SPACER = "@@@@@";
public final static String ALTERNATE_QUESTION_LAYOUT_ENABLED = "cc-alternate-question-text-format";
public final static String OFFER_PIN_FOR_LOGIN = "cc-offer-pin-for-login";
private static final Map<String, String> prefKeyToAnalyticsEvent = new HashMap<>();
private Preference savedSessionEditTextPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleAnalyticsUtils.reportPrefActivityEntry(GoogleAnalyticsFields.CATEGORY_DEV_PREFS);
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName((CommCareApplication.instance().getCurrentApp().getPreferencesFilename()));
addPreferencesFromResource(R.xml.preferences_developer);
setTitle("Developer Preferences");
populatePrefKeyToEventLabelMapping();
GoogleAnalyticsUtils.createPreferenceOnClickListeners(
prefMgr, prefKeyToAnalyticsEvent, GoogleAnalyticsFields.CATEGORY_DEV_PREFS);
savedSessionEditTextPreference = findPreference(EDIT_SAVE_SESSION);
setSessionEditText();
createOnCustomRestoreOption(prefMgr);
hideDangerousDeveloperPrefsIfNeeded();
}
private void createOnCustomRestoreOption(PreferenceManager prefMgr) {
Preference pref = prefMgr.findPreference(PREFS_CUSTOM_RESTORE_DOC_LOCATION);
pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
GoogleAnalyticsUtils.reportPrefItemClick(
GoogleAnalyticsFields.CATEGORY_DEV_PREFS,
GoogleAnalyticsFields.LABEL_CUSTOM_RESTORE);
startFileBrowser();
return true;
}
});
}
private void startFileBrowser() {
Intent chooseTemplateIntent = new Intent()
.setAction(Intent.ACTION_GET_CONTENT)
/**
* Try to lookup key in app preferences and test equality of the result to
* matchingValue. If either the app or preference key don't exist, just
* compare defaultValue to matchingValue
*
* @param key is a potential entry in the app preferences
* @param defaultValue use this value if key not found
* @param matchingValue compare this to key lookup or defaultValue
* @return boolean
*/
private static boolean doesPropertyMatch(String key, String defaultValue, String matchingValue) {
CommCareApp app = CommCareApplication.instance().getCurrentApp();
if (app == null) {
return defaultValue.equals(matchingValue);
}
SharedPreferences properties = app.getAppPreferences();
return properties.getString(key, defaultValue).equals(matchingValue);
}
/**
* Lookup superuser preference; if debug build, superuser is enabled by
* default.
*
* @return is the superuser developer preference enabled?
*/
public static boolean isSuperuserEnabled() {
return doesPropertyMatch(SUPERUSER_ENABLED, BuildConfig.DEBUG ? CommCarePreferences.YES : CommCarePreferences.NO, CommCarePreferences.YES);
}
public static boolean isActionBarEnabled() {
return doesPropertyMatch(ACTION_BAR_ENABLED, CommCarePreferences.YES, CommCarePreferences.YES);
}
public static boolean isNewNavEnabled() {
SharedPreferences properties = CommCareApplication.instance().getCurrentApp().getAppPreferences();
return properties.getString(NAV_UI_ENABLED, CommCarePreferences.YES).equals(CommCarePreferences.YES);
}
public static boolean isCssEnabled() {
return doesPropertyMatch(CSS_ENABLED, CommCarePreferences.NO, CommCarePreferences.YES);
}
public static boolean isListRefreshEnabled() {
SharedPreferences properties = CommCareApplication.instance().getCurrentApp().getAppPreferences();
return properties.getString(LIST_REFRESH_ENABLED, CommCarePreferences.NO).equals(CommCarePreferences.YES);
}
public static boolean isAutoLoginEnabled() {
SharedPreferences properties = CommCareApplication.instance().getCurrentApp().getAppPreferences();
return properties.getString(ENABLE_AUTO_LOGIN, CommCarePreferences.NO).equals(CommCarePreferences.YES);
}
public static boolean isSessionSavingEnabled() {
if (CommCareApplication.instance().getCurrentApp() == null) {
// null check needed for corner case in robolectric tests
return false;
} else {
SharedPreferences properties = CommCareApplication.instance().getCurrentApp().getAppPreferences();
return properties.getString(ENABLE_SAVE_SESSION, CommCarePreferences.NO).
equals(CommCarePreferences.YES);
}
}
public static void enableSessionSaving() {
CommCareApplication.instance().getCurrentApp().getAppPreferences()
.edit()
.putString(DeveloperPreferences.ENABLE_SAVE_SESSION, CommCarePreferences.YES)
.apply();
}
public static boolean isMarkdownEnabled() {
return doesPropertyMatch(MARKDOWN_ENABLED, CommCarePreferences.NO, CommCarePreferences.YES);
}
public static boolean imageAboveTextEnabled() {
return doesPropertyMatch(ALTERNATE_QUESTION_LAYOUT_ENABLED, CommCarePreferences.NO,
CommCarePreferences.YES);
}
public static boolean isHomeReportEnabled() {
return doesPropertyMatch(HOME_REPORT_ENABLED, CommCarePreferences.NO,
CommCarePreferences.YES);
}
public static boolean shouldOfferPinForLogin() {
return doesPropertyMatch(OFFER_PIN_FOR_LOGIN, CommCarePreferences.NO,
CommCarePreferences.YES);
}
public static boolean isAutoPurgeEnabled() {
return doesPropertyMatch(AUTO_PURGE_ENABLED, CommCarePreferences.NO,
CommCarePreferences.YES);
}
public static String formLoadPayloadStatus() {
SharedPreferences properties = CommCareApplication.instance().getCurrentApp().getAppPreferences();
return properties.getString(LOAD_FORM_PAYLOAD_AS, FormRecord.STATUS_SAVED);
}
/**
* Feature flag to control whether swiping in case detail tabs can trigger
* exit from the case detail screen
*/
public static boolean isDetailTabSwipeActionEnabled() {
return doesPropertyMatch(DETAIL_TAB_SWIPE_ACTION_ENABLED, CommCarePreferences.YES, CommCarePreferences.YES);
}
public static boolean useRootModuleMenuAsHomeScreen() {
return doesPropertyMatch(USE_ROOT_MENU_AS_HOME_SCREEN, CommCarePreferences.NO, CommCarePreferences.YES);
}
public static boolean collectAndDisplayEntityTrances() {
return doesPropertyMatch(SHOW_ADB_ENTITY_LIST_TRACES, CommCarePreferences.NO, CommCarePreferences.YES);
}
public static boolean useObfuscatedPassword() {
return doesPropertyMatch(USE_OBFUSCATED_PW, CommCarePreferences.NO, CommCarePreferences.YES);
}
public static boolean isBulkPerformanceEnabled() {
return doesPropertyMatch(ENABLE_BULK_PERFORMANCE, CommCarePreferences.NO, CommCarePreferences.YES);
}
public static boolean shouldShowUpdateOptionsSetting() {
return doesPropertyMatch(SHOW_UPDATE_OPTIONS_SETTING, CommCarePreferences.NO,
CommCarePreferences.YES) || BuildConfig.DEBUG;
}
/**
* TODO: IMPORTANT -- Once the mobile privileges framework is updated to allow for multiple
* flags, we should change this to be controlled by its own flag, instead of piggy-backing
* off of the multiple apps one
*/
private void hideDangerousDeveloperPrefsIfNeeded() {
if (!GlobalPrivilegesManager.isMultipleAppsPrivilegeEnabled() && !BuildConfig.DEBUG) {
// Dangerous privileges should not be showing
PreferenceScreen prefScreen = getPreferenceScreen();
for (Preference pref : getDangerousDeveloperPrefs()) {
if (pref != null) {
prefScreen.removePreference(pref);
}
}
}
}
private Preference[] getDangerousDeveloperPrefs() {
Preference autoLoginPref =
getPreferenceManager().findPreference(ENABLE_AUTO_LOGIN);
Preference sessionSavingPref =
getPreferenceManager().findPreference(ENABLE_SAVE_SESSION);
Preference editSavedSessionPref =
getPreferenceManager().findPreference(EDIT_SAVE_SESSION);
Preference customUserRestorePref =
getPreferenceManager().findPreference(PREFS_CUSTOM_RESTORE_DOC_LOCATION);
Preference performanceImprovementsPref =
getPreferenceManager().findPreference(ENABLE_BULK_PERFORMANCE);
return new Preference[]{autoLoginPref, sessionSavingPref, editSavedSessionPref,
customUserRestorePref, performanceImprovementsPref};
}
}
|
package net.somethingdreadful.MAL.profile;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import net.somethingdreadful.MAL.Card;
import net.somethingdreadful.MAL.MALDateTools;
import net.somethingdreadful.MAL.NfcHelper;
import net.somethingdreadful.MAL.PrefManager;
import net.somethingdreadful.MAL.ProfileActivity;
import net.somethingdreadful.MAL.R;
import net.somethingdreadful.MAL.Theme;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.response.User;
import org.apache.commons.lang3.text.WordUtils;
public class ProfileDetailsMAL extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
Context context;
View view;
Card imagecard;
Card animecard;
Card mangacard;
public SwipeRefreshLayout swipeRefresh;
ProgressBar progressBar;
Card networkCard;
private ProfileActivity activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
view = inflater.inflate(R.layout.fragment_profile_mal, container, false);
imagecard = ((Card) view.findViewById(R.id.name_card));
imagecard.setContent(R.layout.card_image);
((Card) view.findViewById(R.id.details_card)).setContent(R.layout.card_profile_details);
animecard = (Card) view.findViewById(R.id.Anime_card);
animecard.setContent(R.layout.card_profile_anime);
mangacard = (Card) view.findViewById(R.id.Manga_card);
mangacard.setContent(R.layout.card_profile_manga);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
networkCard = (Card) view.findViewById(R.id.network_Card);
swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
swipeRefresh.setOnRefreshListener(this);
swipeRefresh.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
swipeRefresh.setEnabled(true);
TextView tv25 = (TextView) view.findViewById(R.id.websitesmall);
tv25.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri webstiteclick = Uri.parse(activity.record.getProfile().getDetails().getWebsite());
startActivity(new Intent(Intent.ACTION_VIEW, webstiteclick));
}
});
activity.setDetails(this);
if (activity.record == null)
toggle(1);
NfcHelper.disableBeam(activity);
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (ProfileActivity) activity;
}
public void card() { //settings for hide a card and text userprofile
if (PrefManager.getHideAnime()) {
animecard.setVisibility(View.GONE);
}
if (PrefManager.getHideManga()) {
mangacard.setVisibility(View.GONE);
}
if (activity.record.getProfile().getMangaStats().getTotalEntries() < 1) { //if manga (total entry) is beneath the int then hide
mangacard.setVisibility(View.GONE);
}
if (activity.record.getProfile().getAnimeStats().getTotalEntries() < 1) { //if anime (total entry) is beneath the int then hide
animecard.setVisibility(View.GONE);
}
Card namecard = (Card) view.findViewById(R.id.name_card);
namecard.Header.setText(WordUtils.capitalize(activity.record.getName()));
}
public void setcolor() {
TextView tv8 = (TextView) view.findViewById(R.id.accessranksmall);
String name = activity.record.getName();
String rank = activity.record.getProfile().getDetails().getAccessRank() != null ? activity.record.getProfile().getDetails().getAccessRank() : "";
if (!PrefManager.getTextColor()) {
setColor(true);
setColor(false);
if (rank.contains("Administrator")) {
tv8.setTextColor(Color.parseColor("#850000"));
} else if (rank.contains("Moderator")) {
tv8.setTextColor(Color.parseColor("#003385"));
} else {
tv8.setTextColor(Color.parseColor("#0D8500")); //normal user
}
TextView tv11 = (TextView) view.findViewById(R.id.websitesmall);
tv11.setTextColor(Color.parseColor("#002EAB"));
}
if (User.isDeveloperRecord(name)) {
tv8.setText(R.string.access_rank_atarashii_developer); //Developer
tv8.setTextColor(getResources().getColor(R.color.primary)); //Developer
}
}
public void setColor(boolean type) {
int Hue;
TextView textview;
if (type) {
textview = (TextView) view.findViewById(R.id.atimedayssmall); //anime
Hue = (int) (activity.record.getProfile().getAnimeStats().getTimeDays() * 2.5);
} else {
textview = (TextView) view.findViewById(R.id.mtimedayssmall); // manga
Hue = (int) (activity.record.getProfile().getMangaStats().getTimeDays() * 5);
}
if (Hue > 359) {
Hue = 359;
}
textview.setTextColor(Color.HSVToColor(new float[]{Hue, 1, (float) 0.7}));
}
private String getStringFromResourceArray(int resArrayId, int notFoundStringId, int index) {
try { // getResources will cause a crash if an users clicks the profile fast away
Resources res = getResources();
try {
String[] types = res.getStringArray(resArrayId);
if (index < 0 || index >= types.length) // make sure to have a valid array index
return res.getString(notFoundStringId);
else
return types[index];
}catch (Exception e) {
return res.getString(notFoundStringId);
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "ProfileDetailsMAL.getStringFromResourceArray(): " + e.getMessage());
return "Error: could not receive resources";
}
}
public void toggle(int number) {
swipeRefresh.setVisibility(number == 0 ? View.VISIBLE : View.GONE);
progressBar.setVisibility(number == 1 ? View.VISIBLE : View.GONE);
networkCard.setVisibility(number == 2 ? View.VISIBLE : View.GONE);
}
public void setText() {
TextView tv1 = (TextView) view.findViewById(R.id.birthdaysmall);
if (activity.record.getProfile().getDetails().getBirthday() == null) {
tv1.setText(R.string.not_specified);
} else {
String birthday = MALDateTools.formatDateString(activity.record.getProfile().getDetails().getBirthday(), activity, false);
tv1.setText(birthday.equals("") ? activity.record.getProfile().getDetails().getBirthday() : birthday);
}
TextView tv2 = (TextView) view.findViewById(R.id.locationsmall);
if (activity.record.getProfile().getDetails().getLocation() == null) {
tv2.setText(R.string.not_specified);
} else {
tv2.setText(activity.record.getProfile().getDetails().getLocation());
}
TextView tv25 = (TextView) view.findViewById(R.id.websitesmall);
TextView tv26 = (TextView) view.findViewById(R.id.websitefront);
Card tv36 = (Card) view.findViewById(R.id.details_card);
if (activity.record.getProfile().getDetails().getWebsite() != null && activity.record.getProfile().getDetails().getWebsite().contains("http://") && activity.record.getProfile().getDetails().getWebsite().contains(".")) { // filter fake websites
tv25.setText(activity.record.getProfile().getDetails().getWebsite().replace("http:
} else {
tv25.setVisibility(View.GONE);
tv26.setVisibility(View.GONE);
}
TextView tv3 = (TextView) view.findViewById(R.id.commentspostssmall);
tv3.setText(String.valueOf(activity.record.getProfile().getDetails().getComments()));
TextView tv4 = (TextView) view.findViewById(R.id.forumpostssmall);
tv4.setText(String.valueOf(activity.record.getProfile().getDetails().getForumPosts()));
TextView tv5 = (TextView) view.findViewById(R.id.lastonlinesmall);
if (activity.record.getProfile().getDetails().getLastOnline() != null) {
String lastOnline = MALDateTools.formatDateString(activity.record.getProfile().getDetails().getLastOnline(), activity, true);
tv5.setText(lastOnline.equals("") ? activity.record.getProfile().getDetails().getLastOnline() : lastOnline);
} else
tv5.setText("-");
TextView tv6 = (TextView) view.findViewById(R.id.gendersmall);
tv6.setText(getStringFromResourceArray(R.array.gender, R.string.not_specified, activity.record.getProfile().getDetails().getGenderInt()));
TextView tv7 = (TextView) view.findViewById(R.id.joindatesmall);
if (activity.record.getProfile().getDetails().getJoinDate() != null) {
String joinDate = MALDateTools.formatDateString(activity.record.getProfile().getDetails().getJoinDate(), activity, false);
tv7.setText(joinDate.equals("") ? activity.record.getProfile().getDetails().getJoinDate() : joinDate);
} else
tv7.setText("-");
TextView tv8 = (TextView) view.findViewById(R.id.accessranksmall);
tv8.setText(activity.record.getProfile().getDetails().getAccessRank());
TextView tv9 = (TextView) view.findViewById(R.id.animelistviewssmall);
tv9.setText(String.valueOf(activity.record.getProfile().getDetails().getAnimeListViews()));
TextView tv10 = (TextView) view.findViewById(R.id.mangalistviewssmall);
tv10.setText(String.valueOf(activity.record.getProfile().getDetails().getMangaListViews()));
TextView tv11 = (TextView) view.findViewById(R.id.atimedayssmall);
tv11.setText(activity.record.getProfile().getAnimeStats().getTimeDays().toString());
TextView tv12 = (TextView) view.findViewById(R.id.awatchingsmall);
tv12.setText(String.valueOf(activity.record.getProfile().getAnimeStats().getWatching()));
TextView tv13 = (TextView) view.findViewById(R.id.acompletedpostssmall);
tv13.setText(String.valueOf(activity.record.getProfile().getAnimeStats().getCompleted()));
TextView tv14 = (TextView) view.findViewById(R.id.aonholdsmall);
tv14.setText(String.valueOf(activity.record.getProfile().getAnimeStats().getOnHold()));
TextView tv15 = (TextView) view.findViewById(R.id.adroppedsmall);
tv15.setText(String.valueOf(activity.record.getProfile().getAnimeStats().getDropped()));
TextView tv16 = (TextView) view.findViewById(R.id.aplantowatchsmall);
tv16.setText(String.valueOf(activity.record.getProfile().getAnimeStats().getPlanToWatch()));
TextView tv17 = (TextView) view.findViewById(R.id.atotalentriessmall);
tv17.setText(String.valueOf(activity.record.getProfile().getAnimeStats().getTotalEntries()));
TextView tv18 = (TextView) view.findViewById(R.id.mtimedayssmall);
tv18.setText(activity.record.getProfile().getMangaStats().getTimeDays().toString());
TextView tv19 = (TextView) view.findViewById(R.id.mwatchingsmall);
tv19.setText(String.valueOf(activity.record.getProfile().getMangaStats().getReading()));
TextView tv20 = (TextView) view.findViewById(R.id.mcompletedpostssmall);
tv20.setText(String.valueOf(activity.record.getProfile().getMangaStats().getCompleted()));
TextView tv21 = (TextView) view.findViewById(R.id.monholdsmall);
tv21.setText(String.valueOf(activity.record.getProfile().getMangaStats().getOnHold()));
TextView tv22 = (TextView) view.findViewById(R.id.mdroppedsmall);
tv22.setText(String.valueOf(activity.record.getProfile().getMangaStats().getDropped()));
TextView tv23 = (TextView) view.findViewById(R.id.mplantowatchsmall);
tv23.setText(String.valueOf(activity.record.getProfile().getMangaStats().getPlanToRead()));
TextView tv24 = (TextView) view.findViewById(R.id.mtotalentriessmall);
tv24.setText(String.valueOf(activity.record.getProfile().getMangaStats().getTotalEntries()));
}
public void refresh() {
if (activity.record == null) {
if (MALApi.isNetworkAvailable(context)) {
Theme.Snackbar(activity, R.string.toast_error_UserRecord);
} else {
toggle(2);
}
} else {
card();
setText();
setcolor();
Picasso.with(context)
.load(activity.record.getProfile()
.getAvatarUrl())
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
imagecard.wrapImage(bitmap.getWidth(), bitmap.getHeight());
((ImageView) view.findViewById(R.id.Image)).setImageBitmap(bitmap);
toggle(0);
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
toggle(0);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
toggle(0);
}
});
toggle(0);
}
}
@Override
public void onRefresh() {
activity.getRecords();
}
}
|
package com.purdue.CampusFeed.Activities;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.purdue.CampusFeed.API.Event;
import com.purdue.CampusFeed.R;
public class GCMMessageHandler extends IntentService {
public static final int NOTIFICATION_ID = 1;
private static final String TAG = "PRANAV";
public static Event event_updated = null;
NotificationCompat.Builder builder;
private NotificationManager mNotificationManager;
public GCMMessageHandler() {
super("GCMMessageHandler");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "Processing Notification!");
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString(),extras);
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString(),extras);
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Post notification of received message.
sendNotification("Event Coming Up Soon!", extras);
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GCMReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg, Bundle extras) {
Log.d(TAG, "sending notification!");
/* mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());*/
if(extras.getString("mode").equals("update_event")){
String event_id = extras.getString("response");
Intent intent = new Intent(this, SingleFragmentActivity.class);
Log.d("campusfeed", "creating pending intent with event id " + event_id);
SingleFragmentActivity.event_id = Long.parseLong(event_id);
intent.putExtra("update", event_id);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new Notification.Builder(this).setContentTitle(this.getResources().getString(R.string.app_name))
.setContentText(msg).setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).getNotification();
NotificationManager notificationManager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
else
{
// invite event notification
}
}
}
|
package org.gluu.oxauth.client.uma.wrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.gluu.oxauth.client.AuthorizationRequest;
import org.gluu.oxauth.client.AuthorizationResponse;
import org.gluu.oxauth.client.AuthorizeClient;
import org.gluu.oxauth.client.TokenClient;
import org.gluu.oxauth.client.TokenRequest;
import org.gluu.oxauth.client.TokenResponse;
import org.gluu.oxauth.client.uma.exception.UmaException;
import org.gluu.oxauth.model.common.AuthenticationMethod;
import org.gluu.oxauth.model.common.GrantType;
import org.gluu.oxauth.model.common.Prompt;
import org.gluu.oxauth.model.common.ResponseType;
import org.gluu.oxauth.model.crypto.OxAuthCryptoProvider;
import org.gluu.oxauth.model.crypto.signature.SignatureAlgorithm;
import org.gluu.oxauth.model.uma.UmaScopeType;
import org.gluu.oxauth.model.uma.wrapper.Token;
import org.gluu.oxauth.model.util.Util;
import org.gluu.util.StringHelper;
import org.jboss.resteasy.client.jaxrs.ClientHttpEngine;
/**
* @author Yuriy Zabrovarnyy
*/
public class UmaClient {
public static Token requestPat(final String tokenUrl, final String clientKeyStoreFile, final String clientKeyStorePassword, final String clientId, final String keyId) throws UmaException {
TokenRequest tokenRequest = TokenRequest.builder().pat().grantType(GrantType.CLIENT_CREDENTIALS).build();
return request(tokenUrl, clientKeyStoreFile, clientKeyStorePassword, clientId, keyId, tokenRequest);
}
@Deprecated
public static Token requestPat(final String authorizeUrl, final String tokenUrl,
final String umaUserId, final String umaUserSecret,
final String umaClientId, final String umaClientSecret,
final String umaRedirectUri, String... scopeArray) throws Exception {
return request(authorizeUrl, tokenUrl, umaUserId, umaUserSecret, umaClientId, umaClientSecret, umaRedirectUri, UmaScopeType.PROTECTION, scopeArray);
}
public static Token requestPat(final String tokenUrl, final String umaClientId, final String umaClientSecret, String... scopeArray) throws Exception {
return requestPat(tokenUrl, umaClientId, umaClientSecret, null, scopeArray);
}
public static Token requestPat(final String tokenUrl, final String umaClientId, final String umaClientSecret, ClientHttpEngine engine, String... scopeArray) throws Exception {
return request(tokenUrl, umaClientId, umaClientSecret, UmaScopeType.PROTECTION, engine, scopeArray);
}
@Deprecated
public static Token request(final String authorizeUrl, final String tokenUrl,
final String umaUserId, final String umaUserSecret,
final String umaClientId, final String umaClientSecret,
final String umaRedirectUri, UmaScopeType p_type, String... scopeArray) throws Exception {
// 1. Request authorization and receive the authorization code.
List<ResponseType> responseTypes = new ArrayList<ResponseType>();
responseTypes.add(ResponseType.CODE);
responseTypes.add(ResponseType.ID_TOKEN);
List<String> scopes = new ArrayList<String>();
scopes.add(p_type.getValue());
if (scopeArray != null && scopeArray.length > 0) {
scopes.addAll(Arrays.asList(scopeArray));
}
String state = UUID.randomUUID().toString();
AuthorizationRequest request = new AuthorizationRequest(responseTypes, umaClientId, scopes, umaRedirectUri, null);
request.setState(state);
request.setAuthUsername(umaUserId);
request.setAuthPassword(umaUserSecret);
request.getPrompts().add(Prompt.NONE);
AuthorizeClient authorizeClient = new AuthorizeClient(authorizeUrl);
authorizeClient.setRequest(request);
AuthorizationResponse response1 = authorizeClient.exec();
String scope = response1.getScope();
String authorizationCode = response1.getCode();
if (Util.allNotBlank(authorizationCode)) {
// 2. Request access token using the authorization code.
TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
tokenRequest.setCode(authorizationCode);
tokenRequest.setRedirectUri(umaRedirectUri);
tokenRequest.setAuthUsername(umaClientId);
tokenRequest.setAuthPassword(umaClientSecret);
tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
tokenRequest.setScope(scope);
TokenClient tokenClient1 = new TokenClient(tokenUrl);
tokenClient1.setRequest(tokenRequest);
TokenResponse response2 = tokenClient1.exec();
if (response2.getStatus() == 200) {
final String patToken = response2.getAccessToken();
final String patRefreshToken = response2.getRefreshToken();
final Integer expiresIn = response2.getExpiresIn();
if (Util.allNotBlank(patToken, patRefreshToken)) {
return new Token(authorizationCode, patRefreshToken, patToken, scope, expiresIn);
}
}
}
return null;
}
public static Token request(final String tokenUrl, final String umaClientId, final String umaClientSecret, UmaScopeType scopeType,
ClientHttpEngine engine, String... scopeArray) throws Exception {
String scope = scopeType.getValue();
if (scopeArray != null && scopeArray.length > 0) {
for (String s : scopeArray) {
scope = scope + " " + s;
}
}
TokenClient tokenClient = new TokenClient(tokenUrl);
if (engine != null) {
tokenClient.setExecutor(engine);
}
TokenResponse response = tokenClient.execClientCredentialsGrant(scope, umaClientId, umaClientSecret);
if (response.getStatus() == 200) {
final String patToken = response.getAccessToken();
final Integer expiresIn = response.getExpiresIn();
if (Util.allNotBlank(patToken)) {
return new Token(null, null, patToken, scopeType.getValue(), expiresIn);
}
}
return null;
}
public static Token requestWithClientSecretJwt(final String tokenUrl,
final String umaClientId,
final String umaClientSecret,
AuthenticationMethod authenticationMethod,
SignatureAlgorithm signatureAlgorithm,
String audience,
UmaScopeType scopeType,
String... scopeArray) throws Exception {
String scope = scopeType.getValue();
if (scopeArray != null && scopeArray.length > 0) {
for (String s : scopeArray) {
scope = scope + " " + s;
}
}
TokenRequest request = new TokenRequest(GrantType.CLIENT_CREDENTIALS);
request.setAuthUsername(umaClientId);
request.setAuthPassword(umaClientSecret);
request.setScope(scope);
request.setAuthenticationMethod(authenticationMethod);
request.setAlgorithm(signatureAlgorithm);
request.setAudience(audience);
return request(tokenUrl, request);
}
public static Token request(final String tokenUrl, final TokenRequest tokenRequest) throws Exception {
if (tokenRequest.getGrantType() != GrantType.CLIENT_CREDENTIALS) {
return null;
}
TokenClient tokenClient = new TokenClient(tokenUrl);
tokenClient.setRequest(tokenRequest);
TokenResponse response = tokenClient.exec();
if (response.getStatus() == 200) {
final String patToken = response.getAccessToken();
final Integer expiresIn = response.getExpiresIn();
if (Util.allNotBlank(patToken)) {
return new Token(null, null, patToken, response.getScope(), expiresIn);
}
}
return null;
}
private static Token request(final String tokenUrl, final String clientKeyStoreFile,
final String clientKeyStorePassword, final String clientId, final String keyId, TokenRequest tokenRequest)
throws UmaException {
OxAuthCryptoProvider cryptoProvider;
try {
cryptoProvider = new OxAuthCryptoProvider(clientKeyStoreFile, clientKeyStorePassword, null);
} catch (Exception ex) {
throw new UmaException("Failed to initialize crypto provider");
}
try {
String tmpKeyId = keyId;
if (StringHelper.isEmpty(keyId)) {
// Get first key
tmpKeyId = cryptoProvider.getKeys().stream().filter(k -> k.contains("_sig_")).findFirst().orElse(null);
if (keyId == null) {
throw new UmaException("Unable to find a key in the keystore with use = sig");
}
} else if (keyId.contains("_enc_")) {
throw new UmaException("Encryption keys not allowed. Supply a key having use = sig");
}
SignatureAlgorithm algorithm = cryptoProvider.getSignatureAlgorithm(tmpKeyId);
tokenRequest.setAuthenticationMethod(AuthenticationMethod.PRIVATE_KEY_JWT);
tokenRequest.setAuthUsername(clientId);
tokenRequest.setCryptoProvider(cryptoProvider);
tokenRequest.setAlgorithm(algorithm);
tokenRequest.setKeyId(tmpKeyId);
tokenRequest.setAudience(tokenUrl);
Token umaPat = UmaClient.request(tokenUrl, tokenRequest);
return umaPat;
} catch (Exception ex) {
throw new UmaException("Failed to obtain valid UMA PAT token", ex);
}
}
}
|
package eu.theunitry.fabula.UNGameEngine.graphics;
import eu.theunitry.fabula.UNGameEngine.launcher.UNLauncher;
import eu.theunitry.fabula.UNGameEngine.objects.UNObject;
import kuusisto.tinysound.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* UNGameScreen is the frame where the game is displayed.
*/
public class UNGameScreen extends UNObject
{
private UNWindow window;
private UNLauncher launcher;
private UNView splash;
private JPanel currentPanel;
private ArrayList<Music> music;
private ArrayList<Sound> sounds;
private ArrayList<Image> sprites, backgrounds;
private int level, levelMax;
public UNGameScreen()
{
music = new ArrayList<Music>();
sounds = new ArrayList<Sound>();
sprites = new ArrayList<Image>();
backgrounds = new ArrayList<Image>();
this.window = new UNWindow("Fabula", 768, 512);
this.launcher = new UNLauncher(this);
this.splash = new UNView(this, false);
try {
this.splash.setBackgroundImage(ImageIO.read(new File("res/backgrounds/splash_unitry.png")));
} catch (IOException e) {
e.printStackTrace();
}
this.window.addPanel(splash);
this.window.getFrame().setVisible(true);
TinySound.init();
preload();
music.get(0).play(true);
music.get(0).setVolume(0.1);
this.window.removePanel(splash);
this.window.addPanel(launcher);
this.currentPanel = launcher;
this.window.getFrame().setVisible(true);
this.level = 1;
this.levelMax = 5;
}
public void switchPanel(JPanel panel)
{
this.window.removePanel(currentPanel);
this.window.addPanel(panel);
this.currentPanel = panel;
this.window.getFrame().setVisible(true);
}
public UNWindow getWindow()
{
return this.window;
}
public void switchMusic(int index, boolean loop)
{
music.get(0).stop();
music.get(index).play(loop);
}
public ArrayList<Music> getMusic()
{
return this.music;
}
public ArrayList<Sound> getSounds()
{
return this.sounds;
}
public ArrayList<Image> getSprites()
{
return this.sprites;
}
public ArrayList<Image> getBackgrounds()
{
return this.backgrounds;
}
public int getLevel()
{
return level;
}
public int getLevelMax()
{
return levelMax;
}
public void addLevel()
{
this.level++;
}
public void resetProgress()
{
this.level = 1;
}
public void preload()
{
/**
* Font Preload
*/
try
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("res/fonts/Minecraftia.ttf")));
}
catch (IOException|FontFormatException e)
{
e.printStackTrace();
}
/**
* Music Preload
*/
music.add(0, TinySound.loadMusic("audio/intro.wav"));
music.add(1, TinySound.loadMusic("audio/song2.wav"));
/**
* Sound Effects Preload
*/
sounds.add(0, TinySound.loadSound("audio/gibberish.wav"));
/**
* Sprites Preload
*/
try
{
//BACKGROUND PRELOAD
backgrounds.add(0, ImageIO.read(new File("res/backgrounds/underwater.png")));
backgrounds.add(1, ImageIO.read(new File("res/backgrounds/moon.png")));
backgrounds.add(2, ImageIO.read(new File("res/backgrounds/space.png")));
backgrounds.add(3, ImageIO.read(new File("res/backgrounds/supermarket.png")));
//SPRITE PRELOAD
//TUILTJE IDLE
sprites.add(0, ImageIO.read(new File("res/animations/tuiltje/idle/idle0.png")));
sprites.add(1, ImageIO.read(new File("res/animations/tuiltje/idle/idle1.png")));
sprites.add(2, ImageIO.read(new File("res/animations/tuiltje/idle/idle2.png")));
sprites.add(3, ImageIO.read(new File("res/animations/tuiltje/idle/idle3.png")));
sprites.add(4, ImageIO.read(new File("res/animations/tuiltje/idle/idle4.png")));
sprites.add(5, ImageIO.read(new File("res/animations/tuiltje/idle/idle5.png")));
//TUILTJE FLAPPING
sprites.add(6, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping0.png")));
sprites.add(7, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping1.png")));
sprites.add(8, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping2.png")));
sprites.add(9, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping3.png")));
sprites.add(10, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping4.png")));
sprites.add(11, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping5.png")));
//TUILTJE SAD
sprites.add(12, ImageIO.read(new File("res/animations/tuiltje/sad/sad0.png")));
sprites.add(13, ImageIO.read(new File("res/animations/tuiltje/sad/sad1.png")));
sprites.add(14, ImageIO.read(new File("res/animations/tuiltje/sad/sad2.png")));
sprites.add(15, ImageIO.read(new File("res/animations/tuiltje/sad/sad3.png")));
sprites.add(16, ImageIO.read(new File("res/animations/tuiltje/sad/sad4.png")));
sprites.add(17, ImageIO.read(new File("res/animations/tuiltje/sad/sad5.png")));
//TUILTJE HAPPY
sprites.add(18, ImageIO.read(new File("res/animations/tuiltje/happy/happy0.png")));
sprites.add(19, ImageIO.read(new File("res/animations/tuiltje/happy/happy1.png")));
sprites.add(20, ImageIO.read(new File("res/animations/tuiltje/happy/happy2.png")));
sprites.add(21, ImageIO.read(new File("res/animations/tuiltje/happy/happy3.png")));
sprites.add(22, ImageIO.read(new File("res/animations/tuiltje/happy/happy4.png")));
sprites.add(23, ImageIO.read(new File("res/animations/tuiltje/happy/happy5.png")));
sprites.add(24, ImageIO.read(new File("res/animations/tuiltje/happy/happy6.png")));
sprites.add(25, ImageIO.read(new File("res/animations/tuiltje/happy/happy7.png")));
sprites.add(26, ImageIO.read(new File("res/animations/tuiltje/happy/happy8.png")));
sprites.add(27, ImageIO.read(new File("res/animations/tuiltje/happy/happy9.png")));
//TUILTJE QUESTIONING
sprites.add(28, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning0.png")));
sprites.add(29, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning1.png")));
sprites.add(30, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning2.png")));
sprites.add(31, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning3.png")));
sprites.add(32, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning4.png")));
sprites.add(33, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning5.png")));
sprites.add(34, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning6.png")));
sprites.add(35, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning7.png")));
sprites.add(36, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning8.png")));
sprites.add(37, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning9.png")));
//LEVEL0
sprites.add(38, ImageIO.read(new File("res/sprites/apple.png")));
sprites.add(39, ImageIO.read(new File("res/sprites/basket.png")));
sprites.add(40, ImageIO.read(new File("res/sprites/snowball.png")));
//LEVEL3
sprites.add(41, ImageIO.read(new File("res/sprites/rocket0.png")));
sprites.add(42, ImageIO.read(new File("res/sprites/rocket1.png")));
sprites.add(43, ImageIO.read(new File("res/sprites/rocket2.png")));
sprites.add(44, ImageIO.read(new File("res/sprites/rocket3.png")));
sprites.add(45, ImageIO.read(new File("res/sprites/moon0.png")));
sprites.add(46, ImageIO.read(new File("res/sprites/moon1.png")));
sprites.add(47, ImageIO.read(new File("res/sprites/ufoBlue.png")));
sprites.add(48, ImageIO.read(new File("res/sprites/ufoGreen.png")));
sprites.add(49, ImageIO.read(new File("res/sprites/ufoPink.png")));
sprites.add(50, ImageIO.read(new File("res/sprites/snowball.png")));
//LEVEL7
sprites.add(51, ImageIO.read(new File("res/sprites/kist_dicht.png")));
sprites.add(52, ImageIO.read(new File("res/sprites/kist_open.png")));
sprites.add(53, ImageIO.read(new File("res/sprites/muntje.png")));
//LEVEL8
sprites.add(54, ImageIO.read(new File("res/sprites/klomp.png")));
sprites.add(55, ImageIO.read(new File("res/sprites/pickaxe.png")));
//LEVEL11
sprites.add(56, ImageIO.read(new File("res/sprites/appel.png")));
sprites.add(57, ImageIO.read(new File("res/sprites/peer.png")));
sprites.add(58, ImageIO.read(new File("res/sprites/druif.png")));
sprites.add(59, ImageIO.read(new File("res/sprites/sinaasappel.png")));
sprites.add(60, ImageIO.read(new File("res/sprites/banaan.png")));
sprites.add(61, ImageIO.read(new File("res/sprites/kassa.png")));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
|
package fredboat.command.maintenance;
import fredboat.Config;
import fredboat.FredBoat;
import fredboat.commandmeta.abs.Command;
import fredboat.commandmeta.abs.IMaintenanceCommand;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import java.util.ArrayList;
import java.util.List;
public class ShardsCommand extends Command implements IMaintenanceCommand {
private static final int SHARDS_PER_MESSAGE = 30;
@SuppressWarnings("ConstantConditions")
@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
MessageBuilder mb = null;
List<MessageBuilder> builders = new ArrayList<>();
//do a full report? or just a summary
boolean full = false;
if (args.length > 1 && ("full".equals(args[1]) || "all".equals(args[1]))) {
full = true;
}
//make a copy to avoid concurrent modification errors
List<FredBoat> shards = new ArrayList<>(FredBoat.getShards());
int borkenShards = 0;
int healthyGuilds = 0;
int healthyUsers = 0;
for (FredBoat fb : shards) {
if (fb.getJda().getStatus() == JDA.Status.CONNECTED && !full) {
healthyGuilds += fb.getJda().getGuilds().size();
healthyUsers += fb.getJda().getUsers().size();
} else {
if (borkenShards % SHARDS_PER_MESSAGE == 0) {
mb = new MessageBuilder()
.append("```diff\n");
builders.add(mb);
}
mb.append(fb.getJda().getStatus() == JDA.Status.CONNECTED ? "+" : "-")
.append(" ")
.append(fb.getShardInfo().getShardString())
.append(" ")
.append(fb.getJda().getStatus())
.append(" -- Guilds: ")
.append(String.format("%04d", fb.getJda().getGuilds().size()))
.append(" -- Users: ")
.append(fb.getJda().getUsers().size())
.append("\n");
borkenShards++;
}
}
//healthy shards summary, contains sensible data only if we aren't doing a full report
if (!full) {
channel.sendMessage("```diff\n+ "
+ (shards.size() - borkenShards) + "/" + Config.CONFIG.getNumShards() + " shards are " + JDA.Status.CONNECTED
+ " -- Guilds: " + healthyGuilds + " -- Users: " + healthyUsers + "\n```").queue();
}
//detailed shards
for(MessageBuilder builder : builders){
builder.append("```");
channel.sendMessage(builder.build()).queue();
}
}
@Override
public String help(Guild guild) {
return "{0}{1} [full]\n#Show information about the shards of the bot as a summary or in a detailed report.";
}
}
|
package alma.acs.logging.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.cosylab.CDB.DALOperations;
import com.cosylab.CDB.RecordDoesNotExist;
import com.cosylab.CDB.XMLerror;
/**
* Class that encapsulates all configuration sources (defaults, properties, CDB) for Java logging,
* and supports runtime updates of logging configuration based on these sources.
*
* @author hsommer
*/
public class LogConfig {
// /** property file with default logger settings to be found on the classpath */
// private static final String DEFAULT_LOG_PROPERTY_FILE = "almalogging.properties";
// /** property whose value is the property file with user settings */
// private static final String USER_LOG_PROPERTY_FILE_PROPERTY = "java.util.logging.config.file";
/**
* The logger for messages logged by this class.
* Note that this field will be null at first, until the Logger gets provided,
* so better use {@link #log(Level, String, Throwable)} for safe access.
*/
private Logger logger;
// private LogManager m_logManager;
/**
* The ACS CDB. This value is null unless it gets set in {@link #setCDB(DAL)}.
*/
private DALOperations cdb;
/**
* Path in the CDB to the container logging configuration,
* which is also used for component loggers as a default
*/
private String cdbContainerPath;
/**
* key = component logger name, value = path in the CDB to logger configuration
*/
private Map<String, String> cdbComponentPaths;
private LogConfigData defaultLogConfigData;
/**
* key = component logger name, value = LogConfigData for the named logger
*/
private Map<String, LogConfigData> namedLogConfigData;
private List<LogConfigSubscriber> subscriberList;
public LogConfig() {
cdbComponentPaths = new HashMap<String, String>();
namedLogConfigData = new HashMap<String, LogConfigData>();
subscriberList = new ArrayList<LogConfigSubscriber>();
defaultLogConfigData = new LogConfigData();
// m_logManager = LogManager.getLogManager();
}
/**
* Sets the reference to the CDB, which will then be used for configuration.
* Before this method is called, default values are used instead of CDB values.
* <p>
* Note that the reference is only set, but the CDB is not read automatically;
* for this, call {@link #initialize()}.
* @param cdb a reference to the CDB. Will be ignored if == null.
*/
public void setCDB(DALOperations cdb) {
if (cdb != null) {
this.cdb = cdb;
}
}
/**
* Sets the path to the CDB's node that configures all loggers.
* Currently this is the <Container> element, but in the future
* we should have a <Logging> element as its child;
* then the same XML type could be used to specifically configure component's logger,
* overwriting the default values.
* TODO: get the schemas changed ACS-wide
* @param curl
*/
public void setCDBContainerPath(String curl) {
cdbContainerPath = curl;
}
public void setCDBComponentPath(String compLoggerName, String curl) {
cdbComponentPaths.put(compLoggerName, curl);
}
/**
* Initializes the values based on CDB settings, logging properties, etc.
* All subscribing classes are notified of the new configuration,
* see {@link LogConfigSubscriber#configureLogging(LogConfig)}.
* <p>
* This method can be called more than once: if some settings have changed,
* should be read in, and the logging classes should be notified of these changes.
* For example, the container could call this method when it gets notified
* that the logging configuration in the CDB has been changed at runtime.
*
* @throws LogConfigException if reading the configuration data failed and thus default values were used,
* or if there were problems during configuration even though some
* of the configuring went ok (best-effort approach).
*/
public void initialize() throws LogConfigException {
StringBuffer errMsg = new StringBuffer();
// setDefaultLogConfiguration();
// setUserLogConfiguration();
String containerConfigXML = null;
if (cdb != null) {
if (cdbContainerPath != null) {
try {
containerConfigXML = cdb.get_DAO(cdbContainerPath);
defaultLogConfigData.takeCdbContainerXml(containerConfigXML);
} catch (LogConfigException ex) {
errMsg.append(ex.getMessage());
} catch (Throwable thr) { // XMLerror, RecordDoesNotExist, etc
errMsg.append("Failed to read node " + cdbContainerPath + " from the CDB (msg='" + thr.getMessage() + "'). ");
}
}
else {
errMsg.append("CDB reference was set, but not the path to the container logging configuration. ");
}
namedLogConfigData.clear();
// parse component logger configs and thus populate namedLogConfigData
for (Iterator<String> iter = cdbComponentPaths.keySet().iterator(); iter.hasNext();) {
String loggerName = iter.next();
try {
getLogConfigData(loggerName);
} catch (LogConfigException ex) {
errMsg.append(ex.getMessage());
} catch (Throwable thr) { // XMLerror, RecordDoesNotExist, etc
errMsg.append("Failed to read config for logger " + loggerName + " from the CDB (msg='" + thr.getMessage() + "'). ");
}
}
}
notifySubscribers();
// now that the subscribers had a chance to adjust their log levels according to the changes from the CDB (if present), we can publish a trace log
if (containerConfigXML != null) {
log(Level.FINER, "Updated default logging configuration based on CDB settings " + containerConfigXML, null);
// TODO: also log something for named loggers
}
else {
log(Level.FINER, "LogConfig was initialized, but not from CDB settings.", null);
}
if (errMsg.length() > 0) {
throw new LogConfigException("Log config initialization at least partially failed. " + errMsg.toString());
}
}
/**
* Gets the default logging configuration data.
* <p>
* Note that a copy of the config data is returned, so changes to it
* will not affect any other object's configuration.
*/
public LogConfigData getLogConfigData() {
return new LogConfigData(defaultLogConfigData);
}
/**
* Gets the specialized logging configuration data for a given logger.
* Resorts to the default configuration if a specialized configuration is not available.
* <p>
* Note that a copy of the config data is returned, so changes to it
* will not affect any other object's configuration.
* @throws RecordDoesNotExist
* @throws XMLerror
* @throws LogConfigException
*/
public LogConfigData getLogConfigData(String loggerName) throws XMLerror, RecordDoesNotExist, LogConfigException {
if (loggerName == null) {
return getLogConfigData();
}
LogConfigData ret = namedLogConfigData.get(loggerName);
if (ret == null) {
// in any case we can use the default config
ret = getLogConfigData();
// check if we have a CDB path for this particular logger which should modify the default settings
String cdbPath = cdbComponentPaths.get(loggerName);
if (cdbPath != null) {
// CDB should have specialized config for this logger
String componentConfigXML = cdb.get_DAO(cdbPath);
ret.takeCdbComponentXml(componentConfigXML);
setLogConfigData(loggerName, ret);
}
}
return ret;
}
public void setLogConfigData(String loggerName, LogConfigData logConfigData) {
namedLogConfigData.put(loggerName, logConfigData);
}
/**
* Sets the Logger to be used by this class and dependent classes for internal tracing.
* <p>
* Note that in the current design of ClientLogManager and LogConfig,
* the Logger can not be provided already in the constructor,
* because the Logger first must be configured, which in turn requires a LogConfig instance.
* That's why we have this setter method.
*/
public void setInternalLogger(Logger logger) {
this.logger = logger;
defaultLogConfigData.setInternalLogger(logger);
for (Iterator<LogConfigData> iter = namedLogConfigData.values().iterator(); iter.hasNext();) {
iter.next().setInternalLogger(logger);
}
}
protected void log(Level level, String msg, Throwable thr) {
if (logger != null) {
logger.log(level, msg, thr);
}
else {
System.out.println(level.toString() + ": " + msg + (thr != null ? thr.toString() : ""));
}
}
// configuration based on JDK logging property files
// /**
// * Sets the default logging configuration.
// * It is taken from the file almalogging.properties that comes with ACS.
// */
// private void setDefaultLogConfiguration()
// InputStream is = null;
// try
// // Matej: Here we use getClass().getResourceAsStream() and
// // NOT ClassLoader.getSystemResourceAsStream()
// // This method is not compatible with WebStart
// // '/' means from the root (e.g. jar file)
// is = getClass().getResourceAsStream("/"+DEFAULT_LOG_PROPERTY_FILE);
// m_logManager.readConfiguration(is);
// catch (Exception e)
// System.err.println("failed to read default log configuration");
// e.printStackTrace(System.err);
// /**
// * Sets the user-specific logging configuration.
// */
// void setUserLogConfiguration()
// String userConfigFile = System.getProperty(USER_LOG_PROPERTY_FILE_PROPERTY);
// if (userConfigFile != null)
// try
// InputStream in = new FileInputStream(userConfigFile);
// BufferedInputStream bin = new BufferedInputStream(in);
// m_logManager.readConfiguration(bin);
//// System.out.println("configured logging from user-supplied properties file " + userConfigFile);
// catch (Exception e)
// System.err.println("failed to read user log configuration file '" + userConfigFile + "': ");
// e.printStackTrace(System.err);
// /**
// * Method getLoggerLevel. Needed for setting the level of each logger
// * if it has been defined in the properties file.
// * @param ns namespace
// * @return Level
// */
// public Level getLoggerLevel(String ns)
// String lev = m_logManager.getProperty(ns + ".level");
// if (lev == null)
// return Level.ALL;
// if (lev.indexOf(".") == -1)
// String startName = lev.substring(0, 1);
// String name = startName + lev.substring(1).toUpperCase();
// return Level.parse(name);
// else if (lev.startsWith("Level."))
// int start = lev.indexOf('.');
// String lvl = lev.substring(start);
// String name = lvl.substring(1).toUpperCase();
// return Level.parse(name);
// else
// System.err.println("Please set the logger's level according to the Java Logging API!");
// return Level.parse("OFF");
// Propagation of configuration updates to various logging classes
public void addSubscriber(LogConfigSubscriber subscriber) {
if (!subscriberList.contains(subscriber)) {
subscriberList.add(subscriber);
}
}
void notifySubscribers() {
for (Iterator<LogConfigSubscriber> iter = subscriberList.iterator(); iter.hasNext();) {
LogConfigSubscriber subscriber = iter.next();
subscriber.configureLogging(this);
}
}
public void removeSubscriber(LogConfigSubscriber subscriber) {
subscriberList.remove(subscriber);
}
}
|
package com.elmakers.mine.bukkit.utility;
/**
* Used by RandomUtils to create a randomly-selectable set of objects, based on each
* category having a weight.
*
* <p>This class may be used with any base type, so that a String may be randomly selected,
* or a numeric value.
*
* <p>RandomUtils also supports return linearly interpolated (lerp'd) values for numeric-based
* weighted pairs, for a smoothly sliding scale of weighted values.
*
* @param <T> The type of Object to randomly select
*/
public class WeightedPair<T extends Object> implements Comparable<WeightedPair<? extends Object>> {
private final Float threshold;
private final Float rawThreshold;
private final T value;
@SuppressWarnings("unchecked")
public WeightedPair(Float threshold, Float rawThreshold, String value, Class<T> parseAs) {
this.threshold = threshold;
this.rawThreshold = rawThreshold;
// This is pretty ugly, but not as ugly as trying to
// infer the generic type argument.
if (parseAs == Integer.class) {
this.value = (T)(Integer)Integer.parseInt(value);
} else if (parseAs == Float.class) {
this.value = (T)(Float)Float.parseFloat(value);
} else if (parseAs == Double.class) {
this.value = (T)(Double)Double.parseDouble(value);
} else if (parseAs == String.class) {
this.value = (T)value;
} else {
this.value = null;
}
}
public WeightedPair(T value) {
this(1.0f, 1.0f, value);
}
public WeightedPair(Float threshold, T value) {
this(threshold, threshold, value);
}
public WeightedPair(Float threshold, Float rawThreshold, T value) {
this.threshold = threshold;
this.value = value;
this.rawThreshold = rawThreshold;
}
public WeightedPair(WeightedPair<?> weights, T value) {
this.threshold = weights.threshold;
this.value = value;
this.rawThreshold = weights.rawThreshold;
}
public Float getThreshold() {
return threshold;
}
public Float getRawThreshold() {
return rawThreshold;
}
public T getValue() {
return value;
}
@Override
public int compareTo(WeightedPair<? extends Object> other) {
return this.threshold.compareTo(other.threshold);
}
}
|
package com.pennapps.labs.pennmobile;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.pennapps.labs.pennmobile.classes.GSR;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import butterknife.Bind;
import butterknife.ButterKnife;
import static butterknife.ButterKnife.findById;
public class gsrFragment extends Fragment {
//list that holds all GSR rooms
private Map<String, Integer> gsrHashMap = new HashMap<String, Integer>();
ArrayList<GSR> mGSRS = new ArrayList<GSR>();
RecyclerView gsrRoomListRecylerView;
@Bind(R.id.select_date) Button calendarButton;
@Bind(R.id.select_start_time) Button startButton;
@Bind(R.id.select_end_time) Button endButton;
@Bind(R.id.search_GSR) Button searchGSR;
@Bind(R.id.gsr_building_selection) Spinner gsrDropDown;
@Bind(R.id.instructions) TextView instructions;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MainActivity) getActivity()).closeKeyboard();
getActivity().setTitle(R.string.gsr);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_gsr, container, false);
ButterKnife.bind(this, v);
setUpHashMap();
//gsr location options. Dental sem does not work right now
String[] gsrs = new String[]{
"Weigle",
"VP GSR",
"Lippincott",
"Edu Commons",
"Levin Building",
"VP Sem. Rooms",
"Lippincott Sem. Rooms",
"Glossberg Recording Room",
//"Dental Sem",
"Biomedical Lib."
};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, gsrs);
gsrDropDown.setAdapter(adapter);
// Get calendar time and date
Calendar calendar = Calendar.getInstance();
int minutes = calendar.get(Calendar.MINUTE);
int hour = calendar.get(Calendar.HOUR);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
int ampm = calendar.get(Calendar.AM_PM);
calendarButton.setText(year + "-" + month + "-" + day);
// Set default start/end times for GSR booking
String[] ampmTimes = getStartEndTimes(hour, minutes, ampm);
startButton.setText(ampmTimes[0]);
endButton.setText(ampmTimes[1]);
// Set up recycler view for list of GSR rooms
gsrRoomListRecylerView = (RecyclerView) v.findViewById(R.id.gsr_rooms_list);
/**
*
*
* START on click functions for buttons
*
*/
//set start time button
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get Current Time
final Calendar c = Calendar.getInstance();
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
String AM_PM ;
if(hourOfDay < 12) {
AM_PM = "AM";
} else {
AM_PM = "PM";
}
String hourString = Integer.toString(hourOfDay);
if (hourOfDay == 0) {
hourString = "12";
}
//convert to nonmilitary time
if (hourOfDay > 12) {
hourString = Integer.toString(hourOfDay - 12);
}
String minuteString = Integer.toString(minute);
//Android treats minutes less than 10 as single digit
if (minute < 10) {
minuteString = "0" + minute;
}
//display selected time
startButton.setText(hourString + ":" + minuteString + " " + AM_PM);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
});
//end time button
endButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get Current Time
final Calendar c = Calendar.getInstance();
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
String AM_PM ;
if(hourOfDay < 12) {
AM_PM = "AM";
} else {
AM_PM = "PM";
}
String hourString = Integer.toString(hourOfDay);
if (hourOfDay == 0) {
hourString = "12";
}
if (hourOfDay > 12) {
hourString = Integer.toString(hourOfDay - 12);
}
String minuteString = Integer.toString(minute);
if (minute < 10) {
minuteString = "0" + minute;
}
endButton.setText(hourString + ":" + minuteString + " " + AM_PM);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
});
//day for gsr
calendarButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get Current Date
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
//acount for index starting at 0
int entryMonth = monthOfYear + 1;
calendarButton.setText(year + "-" + entryMonth + "-" + dayOfMonth);
}
}, mYear, mMonth, mDay);
//set min and max choices for dates. Want to limit to week.
Date today = new Date();
c.setTime(today);
long minDate = c.getTime().getTime();
c.setTime(today);
c.add( Calendar.DAY_OF_MONTH, +6 );
long maxDate = c.getTime().getTime();
datePickerDialog.getDatePicker().setMaxDate(maxDate);
datePickerDialog.getDatePicker().setMinDate(minDate);
datePickerDialog.show();
}
});
//execute the seatch
searchGSR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Loading...", Toast.LENGTH_SHORT).show();
instructions.setText(getString(R.string.select_intrusctions));
//get vars
String dateBooking = calendarButton.getText().toString();
String startTime = startButton.getText().toString();
String endTime = endButton.getText().toString();
int location = mapGSR(gsrDropDown.getSelectedItem().toString());
if (location == -1) {
Toast.makeText(getActivity(), "Sorry, an error has occurred", Toast.LENGTH_LONG).show();
}
else {
//get the hours
String[] asyncTaskParams = { Integer.toString(location), dateBooking, startTime, endTime};
new getHours().execute(asyncTaskParams);
}
}
});
/**
*
*
* END on click functions for buttons
*
*/
//load initial data
loadInitialData();
return v;
}
@Override
public void onResume() {
super.onResume();
getActivity().setTitle(R.string.gsr);
((MainActivity) getActivity()).setNav(R.id.nav_gsr);
}
public void setUpHashMap() {
gsrHashMap.put("Weigle", 1722);
gsrHashMap.put("VP GSR", 1799);
gsrHashMap.put("Lippincott", 1768);
gsrHashMap.put("Edu Commons", 848);
gsrHashMap.put("Levin Building", 13489);
gsrHashMap.put("VP Sem. Rooms", 4409);
gsrHashMap.put("Lippincott Sem. Rooms", 2587);
gsrHashMap.put("Glossberg Recording Room", 1819);
//gsrHashMap.put("Dental Sem", 13532);
gsrHashMap.put("Biomedical Lib.", 505);
}
//takes the name of the gsr and returns an int for the corresponding code
public int mapGSR(String name) {
return gsrHashMap.get(name);
}
// Parameters: the starting time's hour, minutes, and AM/PM as formatted by Java.utils.Calendar
// AM = 0, PM = 1
// Returns a string array of length 2 where first element is properly formatted starting time
// Second element is properly formatted ending time, which is one hour after starting time
public static String[] getStartEndTimes(int hour, int minutes, int ampm) {
String[] results = new String[2];
String strampm = (ampm == 0) ? "AM" : "PM";
results[0] = hour + ":00" + " " + strampm;
results[1] = "11:59 PM";
return results;
}
//async task that gets the hours of the given gsr and time options
public class getHours extends AsyncTask<String, Void, String[]> {
protected void onPreExecute(){}
//interacts with penn's servers using a post request
protected String[] doInBackground(String... pParams) {
try {
String gsrCode = pParams[0];
String date = pParams[1];
String startTime = pParams[2];
String endTime = pParams[3];
URL url = new URL("http://libcal.library.upenn.edu/process_roombookings.php?m=calscroll&gid=" + gsrCode + "&date=" + date);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Referer","http://libcal.library.upenn.edu/booking/vpdlc");
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//put the information into a string builder
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
total.append(line).append('\n');
}
//return response and inputs for onPost
in.close();
String[] returnArray = {total.toString(), gsrCode, date, startTime, endTime};
return returnArray;
}
else {
String[] returnArray = {"failed"};
return returnArray;
}
}
catch(Exception e){
String[] returnArray = {"failed"};
return returnArray;
}
}
//take the html, parse it, and populate recycler views
@Override
protected void onPostExecute(String[] result) {
String gsrCode = result[1];
String dayOfWeek = result[2];
String startTime = result[3];
String endTime = result[4];
Document doc = Jsoup.parse(result[0]);
//each time block has associated tag below:
Elements elements = doc.body().select("a.lc_rm_a");
if (elements.size() == 0) {
Toast.makeText(getActivity(), "No GSRs available", Toast.LENGTH_LONG).show();
//populate recyclerview
LinearLayoutManager gsrRoomListLayoutManager = new LinearLayoutManager(getContext());
gsrRoomListLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
gsrRoomListRecylerView.setLayoutManager(gsrRoomListLayoutManager);
gsrRoomListRecylerView.setAdapter(new GsrBuildingAdapter(getContext(), mGSRS, gsrCode));
} else {
for (Element element : elements) {
String element_entry = element.attr("onclick") + "\n";
String[] parsed_data = parseEntry(element_entry).split("&");
String gsrName = parsed_data[0].replace("'", "");
String dateTime = parsed_data[1].replace("'", "");
String elementId = element.attr("id") + "\n";
//parse datetime further
String[] dateDataBrokenUp = parseEntry(element_entry).split(",");
String timeRange = dateDataBrokenUp[0].split("&")[1];
String dayDate = dateDataBrokenUp[1];
String dateNum = dateDataBrokenUp[2];
String duration = parsed_data[2].replace("'", "");
String AMPM = "";
if (timeRange.contains("AM")) {
AMPM = "AM";
}
else {AMPM = "PM";}
//time block times
String localStartTime = timeRange.split("-")[0].replace("'", "");
String localEndTime = timeRange.split("-")[1];
Boolean startDateCondition = false;
Boolean endDateCondition = false;
//convert all times
//local is for time block and global refers to the user's parameters' times
SimpleDateFormat localFormat = new SimpleDateFormat("hh:mmaa");
SimpleDateFormat globalFormat = new SimpleDateFormat("hh:mm aa");
try {
//now convert all times to date objects to compare
Date localStartDate = localFormat.parse(localStartTime);
Date globalStartDate = globalFormat.parse(startTime);
Date localEndDate = localFormat.parse(localEndTime);
Date globalEndDate = globalFormat.parse(endTime);
//now compare
Calendar calendarLocalStart = Calendar.getInstance();
Calendar calendarGlobalStart = Calendar.getInstance();
Calendar calendarLocalEnd = Calendar.getInstance();
Calendar calendarGlobalEnd = Calendar.getInstance();
calendarLocalEnd.setTime(localEndDate);
calendarGlobalEnd.setTime(globalEndDate);
calendarLocalStart.setTime(localStartDate);
calendarGlobalStart.setTime(globalStartDate);
//if end time is greater than time block's end time
if (calendarGlobalEnd.getTimeInMillis() - calendarLocalEnd.getTimeInMillis() >= 0 )
{
endDateCondition = true;
}
//if start time is less than time start end time
if ((calendarLocalStart.after(calendarGlobalStart)) || calendarLocalStart.equals(calendarGlobalStart)) {
startDateCondition = true;
}
} catch (ParseException e) {
}
if (startDateCondition && endDateCondition) {
//now populate mGSRs
insertGSRSlot(gsrName, dateTime, timeRange, dayDate, dateNum, duration, elementId);
}
}
//now change the ui
if (mGSRS.size() == 0)
{
Toast.makeText(getActivity(), "No GSRs available", Toast.LENGTH_LONG).show();
}
LinearLayoutManager gsrRoomListLayoutManager = new LinearLayoutManager(getContext());
gsrRoomListLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
gsrRoomListRecylerView.setLayoutManager(gsrRoomListLayoutManager);
gsrRoomListRecylerView.setAdapter(new GsrBuildingAdapter(getContext(), mGSRS, gsrCode));
//reset var
mGSRS = new ArrayList<GSR>();
}
}
}
//this function clicks the search button to load initial results on the screen
public void loadInitialData() {
searchGSR.performClick();
searchGSR.setPressed(true);
searchGSR.invalidate();
searchGSR.setPressed(false);
searchGSR.invalidate();
}
//helper function to parse the HTML response
public String parseEntry(String gsr_entry) {
//get the name of gsr
Pattern p = Pattern.compile("([\"'])(?:(?=(\\\\?))\\2.)*?\\1");
Matcher m = p.matcher(gsr_entry);
String final_return = "";
while(m.find()) {
if (final_return.equals("")) {
final_return = m.group();
}
else {
final_return = final_return + "&" + m.group();
}
}
return final_return;
}
//function that takes all available GSR sessions and populates mGSRs
public void insertGSRSlot(String gsrName, String GSRTimeRange, String GSRDateTime,
String GSRDayDate, String GSRDateNum, String GSRDuration, String GSRElementId) {
boolean encountered = false;
for(int i=0; i<mGSRS.size(); i++) {
GSR currentGSR = mGSRS.get(i);
//if there is GSR, add the available session to the GSR Object
if (currentGSR.getGsrName().equals(gsrName)) {
currentGSR.addGSRSlot(GSRTimeRange, GSRDateTime, GSRDayDate, GSRDateNum, GSRDuration, GSRElementId);
encountered = true;
}
}
//can't find existing GSR. Create new object
if (encountered == false) {
GSR newGSRObject = new GSR(gsrName, GSRTimeRange, GSRDateTime, GSRDayDate, GSRDateNum, GSRDuration, GSRElementId);
mGSRS.add(newGSRObject);
}
}
}
|
package edu.pdx.cs410J.chances;
import edu.pdx.cs410J.AbstractAppointmentBook;
import edu.pdx.cs410J.AppointmentBookParser;
import edu.pdx.cs410J.ParserException;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.function.Consumer;
/**
* @author chancesnow
*/
public class TextParser implements AppointmentBookParser
{
private File file;
/**
* Create a new appt book parser given a file path.
*
* @param filePath The file path
*/
public TextParser(String filePath)
{
file = new File(filePath);
// Exceptional state when file doesn't exist or file is a directory
if (!file.exists() || file.isDirectory()) {
file = null;
}
}
/**
* Parse an appointment book from a file.
*
* @return Parsed appointment book
* @throws ParserException
*/
@Override
public AbstractAppointmentBook parse() throws ParserException
{
if (file != null) {
try (
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file))
)
) {
String owner = br.readLine();
AppointmentBook book = new AppointmentBook(owner);
// Parse appointments
// Long lists of triplets of data, three lines each:
// 1. Description
// 2. Begin date
// 3. End date
int step = 0;
Date beginTime = null;
Date endTime = null;
String line = br.readLine();
while (line != null) {
switch (step) {
case 0:
case 1:
Date date;
try {
date = Appointment.DATE_FORMAT.parse(line);
} catch (Exception ex) {
throw new ParserException(
"Could not parse date \"" +
line + "\"",
ex
);
}
if (date != null) {
if (step == 0) {
beginTime = date;
} else {
endTime = date;
}
}
step = (step == 0) ? 1 : 2;
break;
case 2:
String description = line;
// Unescape double quotes and newlines
description = description.replaceAll(""", "\"");
description = description.replaceAll(" ", "\r");
description = description.replaceAll(" ", "\n");
// Finished with appointment, add to the appt book
Appointment appointment = new Appointment(description);
appointment.setBeginTime(beginTime);
appointment.setEndTime(endTime);
book.getAppointments().add(appointment);
beginTime = null;
endTime = null;
step = 0;
break;
}
line = br.readLine();
}
boolean unfinished = step != 0;
if (unfinished) {
throw new ParserException("Reached malformed appointment " +
"(missing required data)");
}
return book;
} catch (IOException ex) {
throw new ParserException(ex.getMessage(), ex);
}
}
return null;
}
}
|
package com.neopixl.restpixlsample;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.neopixl.logger.NPLog;
import com.neopixl.restpixl.async.NPBackgroundLoadingManager;
import com.neopixl.restpixl.request.NPGETRequest;
import com.neopixl.restpixl.request.NPPOSTRequest;
import com.neopixl.restpixl.request.NPRequest;
import com.neopixl.restpixl.request.NPRequestListener;
import com.neopixl.restpixlsample.domain.Mooder;
public class MainActivity extends Activity implements NPRequestListener {
private static String RESTPIXL_SAMPLE_GET_URL = "http://intent.alwaysdata.net/mooders.json";
private static String RESTPIXL_SAMPLE_POST_URL = "http://posttestserver.com/post.php";
private Context context;
//View element
private TextView textViewContentJson;
private Button buttonGet;
private Button buttonPost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContext(this);
textViewContentJson = (TextView) findViewById(R.id.txtViewJsonContent);
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonGet.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
launchGETRequest();
}
});
buttonPost = (Button) findViewById(R.id.buttonPost);
buttonPost.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
launchPOSTRequest();
}
});
}
private void launchGETRequest()
{
textViewContentJson.setText("");
//Get Request
NPGETRequest request = new NPGETRequest(getContext(),RESTPIXL_SAMPLE_GET_URL,null,true,null,null,null);
request.setListener(this);
NPBackgroundLoadingManager.queueInteractiveRequest(request);
}
private void launchPOSTRequest()
{
textViewContentJson.setText("");
//Post Request
Mooder aMooder = new Mooder("id", "Demolliens", "Olivier", "http://noUrl", null, null);
Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create();
String value = gson.toJson(aMooder);
NPPOSTRequest request = new NPPOSTRequest(getContext(),RESTPIXL_SAMPLE_POST_URL,null,true,null,value,null);
request.setListener(this);
NPBackgroundLoadingManager.queueInteractiveRequest(request);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void requestFailedNoNetwork(NPRequest rQ) {
NPLog.e("");
textViewContentJson.setText("No network");
}
@Override
public void requestFailedWithErrorCode(NPRequest rQ) {
NPLog.e("");
textViewContentJson.setText(rQ.getHttpCode());
}
@Override
public void requestSuccess(NPRequest rQ) {
NPLog.i("");
if(rQ.getUrl().equals(RESTPIXL_SAMPLE_GET_URL)){
Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create();
List<Mooder> mooderList = gson.fromJson(rQ.getmResponse().body, new TypeToken<List<Mooder>>(){}.getType());
textViewContentJson.setText(mooderList.toString());
mooderList = null;
}else if(rQ.getUrl().equals(RESTPIXL_SAMPLE_POST_URL)){
textViewContentJson.setText(rQ.getmResponse().body);
}
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
|
package org.openas2.processor.sender;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Locale;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.net.ssl.SSLHandshakeException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openas2.OpenAS2Exception;
import org.openas2.Session;
import org.openas2.cert.CertificateFactory;
import org.openas2.lib.helper.ICryptoHelper;
import org.openas2.message.AS2Message;
import org.openas2.message.AS2MessageMDN;
import org.openas2.message.DataHistoryItem;
import org.openas2.message.FileAttribute;
import org.openas2.message.Message;
import org.openas2.message.MessageMDN;
import org.openas2.message.NetAttribute;
import org.openas2.params.InvalidParameterException;
import org.openas2.partner.AS2Partnership;
import org.openas2.partner.Partnership;
import org.openas2.partner.SecurePartnership;
import org.openas2.processor.resender.ResenderModule;
import org.openas2.util.AS2Util;
import org.openas2.util.DateUtil;
import org.openas2.util.DispositionOptions;
import org.openas2.util.HTTPUtil;
import org.openas2.util.IOUtilOld;
import org.openas2.util.Profiler;
import org.openas2.util.ProfilerStub;
import org.openas2.util.Properties;
public class AS2SenderModule extends HttpSenderModule {
private Log logger = LogFactory.getLog(AS2SenderModule.class.getSimpleName());
public boolean canHandle(String action, Message msg, Map<Object, Object> options)
{
if (!action.equals(SenderModule.DO_SEND))
{
return false;
}
return (msg instanceof AS2Message);
}
@SuppressWarnings("unchecked")
public void handle(String action, Message msg, Map<Object, Object> options) throws OpenAS2Exception
{
if (logger.isInfoEnabled())
{
logger.info("message sender invoked" + msg.getLogMsgID());
}
boolean isResend = Message.MSG_STATUS_MSG_RESEND.equals(msg.getStatus());
options.put("DIRECTION", "SEND");
options.put("IS_RESEND", isResend ? "Y" : "N");
if (!(msg instanceof AS2Message))
{
throw new OpenAS2Exception("Can't send non-AS2 message");
}
// verify all required information is present for sending
checkRequired(msg);
// Store options on the message object
if (options != null)
{
msg.getOptions().putAll(options);
}
if (logger.isTraceEnabled())
{
logger.trace("Retry count from options: " + options);
}
// Get the resend retry count
String retries = AS2Util.retries(options, getParameter(SenderModule.SOPT_RETRIES, false));
// Get any static custom headers
String customHeaders = msg.getPartnership().getAttribute(AS2Partnership.PA_CUSTOM_MIME_HEADERS);
if (customHeaders != null && customHeaders.length() > 0)
{
if (logger.isTraceEnabled())
{
logger.trace("Adding custom header attribute to custom headers map..." + msg.getLogMsgID());
}
String[] headers = customHeaders.split("\\s*;\\s*");
for (int i = 0; i < headers.length; i++)
{
String[] header = headers[i].split("\\s*:\\s*");
if (logger.isTraceEnabled())
{
logger.trace("Adding custom header: " + headers[i]
+ " :::Split count:" + header.length + msg.getLogMsgID());
}
if (header.length != 2)
{
throw new OpenAS2Exception("Invalid custom header: " + headers[i]);
}
msg.addCustomOuterMimeHeader(header[0].replaceAll(" ", ""), header[1]);
}
}
// encrypt and/or sign and/or compress the message if needed
MimeBodyPart securedData;
try
{
securedData = secure(msg);
//Add any additional headers since this will be the outermost Mime body part if configured
addCustomOuterMimeHeaders(msg, securedData);
storePendingInfo((AS2Message) msg, isResend);
} catch (Exception e)
{
msg.setLogMsg(org.openas2.logging.Log.getExceptionMsg(e));
logger.error(msg, e);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_SEND_EXCEPTION);
msg.trackMsgState(getSession());
throw new OpenAS2Exception("Error setting up message for sending.", e);
}
if (logger.isTraceEnabled())
{
try
{
logger.trace("Message object in sender module. Content-Disposition: " + msg.getContentDisposition()
+ "\n Content-Type : " + msg.getContentType() + "\n HEADERS : " + AS2Util.printHeaders(msg.getData().getAllHeaders())
+ "\n Content-Disposition in MSG getData() MIMEPART: " + msg.getData().getContentType()
+ msg.getLogMsgID());
} catch (Exception e)
{
}
}
HttpURLConnection conn = null;
try
{
try
{
// Create the HTTP connection and set up headers
String url = msg.getPartnership().getAttribute(AS2Partnership.PA_AS2_URL);
conn = getConnection(url, true, true, false, "POST");
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_SEND_START);
msg.trackMsgState(getSession());
sendMessage(conn, msg, securedData, retries);
} catch (HttpResponseException hre)
{
// Will have been logged so just resend
resend(msg, hre, retries);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_SEND_EXCEPTION);
msg.trackMsgState(getSession());
return;
} catch (SSLHandshakeException e)
{
msg.setLogMsg("Failed to connect to partner using SSL certificate. Please run the SSL certificate checker utility to identify the issue: " + conn.getURL());
logger.error(msg, e);
msg.setOption("STATE", Message.MSG_STATE_SEND_FAIL);
msg.trackMsgState(getSession());
return;
} catch (Exception e)
{
msg.setLogMsg("Unexpected error sending file: " + org.openas2.logging.Log.getExceptionMsg(e));
logger.error(msg, e);
resend(msg, new OpenAS2Exception(org.openas2.logging.Log.getExceptionMsg(e)), retries);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_SEND_EXCEPTION);
msg.trackMsgState(getSession());
return;
}
if (logger.isTraceEnabled())
{
logger.trace("Message sent. Checking if MDN will be returned..." + msg.getLogMsgID());
}
// Receive an MDN
if (msg.isConfiguredForMDN())
{
msg.setStatus(Message.MSG_STATUS_MDN_WAIT);
// Check if it will be an AsyncMDN
if (msg.getPartnership().getAttribute(AS2Partnership.PA_AS2_RECEIPT_OPTION) == null)
{
if (logger.isTraceEnabled())
{
logger.trace("Waiting for synchronous MDN response..." + msg.getLogMsgID());
}
// Create a MessageMDN and copy HTTP headers
if (logger.isTraceEnabled())
{
logger.trace("Awaiting sync MDN. Orig msg contains headers:" + AS2Util.printHeaders(msg.getHeaders().getAllHeaders()) + msg.getLogMsgID());
}
MessageMDN mdn = new AS2MessageMDN((AS2Message) msg, false);
if (logger.isTraceEnabled())
{
logger.trace("MDN msg initalised for inbound contains headers:" + AS2Util.printHeaders(mdn.getHeaders().getAllHeaders()) + msg.getLogMsgID());
}
HTTPUtil.copyHttpHeaders(conn, mdn.getHeaders());
// Receive the MDN data
InputStream connIn = null;
try
{
connIn = conn.getInputStream();
} catch (IOException e1)
{
msg.setLogMsg("Failed to get input stream for receiving MDN: "
+ org.openas2.logging.Log.getExceptionMsg(e1));
logger.error(msg, e1);
resend(msg, new OpenAS2Exception(org.openas2.logging.Log.getExceptionMsg(e1)), retries);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_RECEIVING_EXCEPTION);
msg.trackMsgState(getSession());
}
ByteArrayOutputStream mdnStream = new ByteArrayOutputStream();
try
{
String contentLength = mdn.getHeader("Content-Length");
// Retrieve the message content
if (contentLength != null)
{
try
{
IOUtils.copy(connIn, mdnStream);
} catch (NumberFormatException nfe)
{
IOUtils.copy(connIn, mdnStream);
}
} else
{
IOUtils.copy(connIn, mdnStream);
}
} catch (IOException ioe)
{
msg.setLogMsg("IO exception receiving MDN: "
+ org.openas2.logging.Log.getExceptionMsg(ioe));
logger.error(msg, ioe);
// What to do???
resend(msg, new OpenAS2Exception(org.openas2.logging.Log.getExceptionMsg(ioe)), retries);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MDN_RECEIVING_EXCEPTION);
msg.trackMsgState(getSession());
} finally
{
try
{
if (connIn != null)
{
connIn.close();
}
} catch (IOException e)
{
}
}
if (logger.isTraceEnabled())
{
logger.trace("Synchronous MDN received. Start processing..." + msg.getLogMsgID());
}
msg.setStatus(Message.MSG_STATUS_MDN_PROCESS_INIT);
try
{
AS2Util.processMDN((AS2Message) msg, mdnStream.toByteArray(), null, false, getSession(), this);
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_MSG_SENT_MDN_RECEIVED_OK);
msg.trackMsgState(getSession());
} catch (Exception e)
{
if (Message.MSG_STATUS_MDN_PROCESS_INIT.equals(msg.getStatus())
|| Message.MSG_STATUS_MDN_PARSE.equals(msg.getStatus())
|| !(e instanceof OpenAS2Exception))
{
/*
* Cannot identify the target if in init or parse
* state so not sure what the best course of action
* is apart from do nothing
*/
msg.setLogMsg("Unhandled error condition receiving synchronous MDN. Message and asociated files cleanup will be attempted but may be in an unknown state.");
logger.error(msg, e);
}
/*
* Most likely a resend abort of max resend reached if
* OpenAS2Exception so do not log as should have been
* logged upstream ... just clean up the mess
*/
else
{
// Must have received MDN successfully
msg.setLogMsg("Exception receiving synchronous MDN. Message and asociated files cleanup will be attempted but may be in an unknown state.");
logger.error(msg, e);
}
// Log significant msg state
msg.setOption("STATE", Message.MSG_STATE_SEND_FAIL);
msg.trackMsgState(getSession());
AS2Util.cleanupFiles(msg, true);
}
}
}
} finally
{
if (conn != null)
{
conn.disconnect();
}
}
}
protected void checkRequired(Message msg) throws InvalidParameterException
{
Partnership partnership = msg.getPartnership();
try
{
InvalidParameterException.checkValue(msg, "ContentType", msg.getContentType());
InvalidParameterException.checkValue(msg, "Attribute: " + AS2Partnership.PA_AS2_URL,
partnership.getAttribute(AS2Partnership.PA_AS2_URL));
InvalidParameterException.checkValue(msg, "Receiver: " + AS2Partnership.PID_AS2,
partnership.getReceiverID(AS2Partnership.PID_AS2));
InvalidParameterException.checkValue(msg, "Sender: " + AS2Partnership.PID_AS2,
partnership.getSenderID(AS2Partnership.PID_AS2));
InvalidParameterException.checkValue(msg, "Subject", msg.getSubject());
InvalidParameterException.checkValue(msg, "Sender: " + Partnership.PID_EMAIL,
partnership.getSenderID(Partnership.PID_EMAIL));
InvalidParameterException.checkValue(msg, "Message Data", msg.getData());
} catch (InvalidParameterException rpe)
{
rpe.addSource(OpenAS2Exception.SOURCE_MESSAGE, msg);
throw rpe;
}
}
private void sendMessage(HttpURLConnection conn, Message msg, MimeBodyPart securedData, String retries)
throws Exception
{
updateHttpHeaders(conn, msg, securedData);
msg.setAttribute(NetAttribute.MA_DESTINATION_IP, conn.getURL().getHost());
msg.setAttribute(NetAttribute.MA_DESTINATION_PORT, Integer.toString(conn.getURL().getPort()));
if (logger.isInfoEnabled())
{
logger.info("Connecting to: " + conn.getURL() + msg.getLogMsgID());
}
// Note: closing this stream causes connection abort errors on some AS2
// servers
OutputStream messageOut = conn.getOutputStream();
// Transfer the data
InputStream messageIn = securedData.getInputStream();
try
{
ProfilerStub transferStub = Profiler.startProfile();
int bytes = IOUtils.copy(messageIn, messageOut);
Profiler.endProfile(transferStub);
if (logger.isInfoEnabled())
{
logger.info("transferred " + IOUtilOld.getTransferRate(bytes, transferStub) + msg.getLogMsgID());
}
} finally
{
messageIn.close();
}
// Check the HTTP Response code
int rc = conn.getResponseCode();
if ((rc != HttpURLConnection.HTTP_OK) && (rc != HttpURLConnection.HTTP_CREATED)
&& (rc != HttpURLConnection.HTTP_ACCEPTED) && (rc != HttpURLConnection.HTTP_PARTIAL)
&& (rc != HttpURLConnection.HTTP_NO_CONTENT))
{
msg.setLogMsg("Error sending message. URL: " + conn.getURL().toString() + " ::: Response Code: " + rc
+ " ::: Response Message: " + conn.getResponseMessage());
logger.error(msg);
throw new HttpResponseException(conn.getURL().toString(), rc, conn.getResponseMessage());
}
}
private void resend(Message msg, OpenAS2Exception cause, String tries) throws OpenAS2Exception
{
AS2Util.resend(getSession(), this, SenderModule.DO_SEND, msg, cause, tries, false);
}
/**
* Returns a MimeBodyPart or MimeMultipart object
* @param msg The message object carried around containing necessary information
* @return The secured mimebodypart
* @throws Exception some unforseen issue has occurred
*/
protected MimeBodyPart secure(Message msg) throws Exception
{
// Set up encrypt/sign variables
MimeBodyPart dataBP = msg.getData();
/*
* Based on RFC4130, RFC6362 and RFC5042, the MIC is calculated as
* follows: Signed message - MIME header fields and content that is to
* be signed which may or may not be encrypted and/or compressed.
*
* Unsigned encrypted message - data content including all MIME header
* fields and any applied Content-Transfer-Encoding prior to encryption
* and/or compression
*
* So essentially, calculate the MIC before doing any compression or
* encryption if message not being signed otherwise calculate right
* before signing of the message but include headers for unsigned
* messages (see RFC4130 section 7.3.1 for details)
*/
Partnership partnership = msg.getPartnership();
String contentTxfrEncoding = partnership.getAttribute(Partnership.PA_CONTENT_TRANSFER_ENCODING);
if (contentTxfrEncoding == null)
{
contentTxfrEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
}
boolean encrypt = partnership.getAttribute(SecurePartnership.PA_ENCRYPT) != null;
boolean sign = partnership.getAttribute(SecurePartnership.PA_SIGN) != null;
if (!sign)
{
calcAndStoreMic(msg, dataBP, (sign || encrypt));
}
// Check if compression is enabled
String compressionType = msg.getPartnership().getAttribute("compression_type");
if (logger.isTraceEnabled())
{
logger.trace("Compression type from config: " + compressionType);
}
boolean isCompress = false;
if (compressionType != null && !"NONE".equalsIgnoreCase(compressionType))
{
if (compressionType.equalsIgnoreCase(ICryptoHelper.COMPRESSION_ZLIB))
{
isCompress = true;
}
else
{
throw new OpenAS2Exception("Unsupported compression type: " + compressionType);
}
}
String compressionMode = msg.getPartnership().getAttribute("compression_mode");
boolean isCompressBeforeSign = true; // Defaults to compressing the
// entire message before signing
// and encryption
if (compressionMode != null && compressionMode.equalsIgnoreCase("compress-after-signing"))
{
isCompressBeforeSign = false;
}
if (isCompress && isCompressBeforeSign)
{
if (logger.isTraceEnabled())
{
logger.trace("Compressing outbound message before signing...");
}
if (!sign && !encrypt)
{
//Add any additional headers since this will be the outermost Mime body part if configured
addCustomOuterMimeHeaders(msg, dataBP);
}
dataBP = AS2Util.getCryptoHelper().compress(msg, dataBP, compressionType, contentTxfrEncoding);
}
// Encrypt and/or sign the data if requested
CertificateFactory certFx = getSession().getCertificateFactory();
// Sign the data if requested
if (sign)
{
if (!encrypt && !(isCompress && !isCompressBeforeSign))
{
//Add any additional headers since this will be the outermost Mime body part if configured
addCustomOuterMimeHeaders(msg, dataBP);
}
calcAndStoreMic(msg, dataBP, (sign || encrypt));
X509Certificate senderCert = certFx.getCertificate(msg, Partnership.PTYPE_SENDER);
PrivateKey senderKey = certFx.getPrivateKey(msg, senderCert);
String digest = partnership.getAttribute(SecurePartnership.PA_SIGN);
if (logger.isDebugEnabled())
{
logger.debug("Params for creating signed body part:: DATA: " + dataBP + "\n SIGN DIGEST: " + digest
+ "\n CERT ALG NAME EXTRACTED: " + senderCert.getSigAlgName()
+ "\n CERT PUB KEY ALG NAME EXTRACTED: " + senderCert.getPublicKey().getAlgorithm()
+ msg.getLogMsgID());
}
boolean isRemoveCmsAlgorithmProtectionAttr = "true".equalsIgnoreCase(partnership.getAttribute(Partnership.PA_REMOVE_PROTECTION_ATTRIB));
dataBP = AS2Util.getCryptoHelper().sign(dataBP, senderCert, senderKey, digest
, contentTxfrEncoding, msg.getPartnership().isRenameDigestToOldName(), isRemoveCmsAlgorithmProtectionAttr);
DataHistoryItem historyItem = new DataHistoryItem(dataBP.getContentType());
msg.getHistory().getItems().add(historyItem);
if (logger.isDebugEnabled())
{
logger.debug("signed data" + msg.getLogMsgID());
}
}
if (isCompress && !isCompressBeforeSign)
{
if (!encrypt)
{
//Add any additional headers since this will be the outermost Mime body part if configured
addCustomOuterMimeHeaders(msg, dataBP);
}
if (logger.isTraceEnabled())
{
logger.trace("Compressing outbound message after signing...");
}
dataBP = AS2Util.getCryptoHelper().compress(msg, dataBP, compressionType, contentTxfrEncoding);
}
// Encrypt the data if requested
if (encrypt)
{
//Add any additional headers since this will be the outermost Mime body part if configured
addCustomOuterMimeHeaders(msg, dataBP);
String algorithm = partnership.getAttribute(SecurePartnership.PA_ENCRYPT);
X509Certificate receiverCert = certFx.getCertificate(msg, Partnership.PTYPE_RECEIVER);
dataBP = AS2Util.getCryptoHelper().encrypt(dataBP, receiverCert, algorithm, contentTxfrEncoding);
// Asynch MDN 2007-03-12
DataHistoryItem historyItem = new DataHistoryItem(dataBP.getContentType());
msg.getHistory().getItems().add(historyItem);
if (logger.isDebugEnabled())
{
logger.debug("encrypted data" + msg.getLogMsgID());
}
}
String t = dataBP.getEncoding();
if ((t == null || t.length() < 1) && "true".equalsIgnoreCase(partnership.getAttribute(Partnership.PA_SET_CONTENT_TRANSFER_ENCODING_OMBP)))
{
dataBP.setHeader("Content-Transfer-Encoding", contentTxfrEncoding);
}
return dataBP;
}
protected void addCustomOuterMimeHeaders(Message msg, MimeBodyPart dataBP) throws MessagingException
{
if (logger.isTraceEnabled())
{
logger.trace("Adding custom headers to outer MBP...." + msg.getLogMsgID());
}
Map<String, String> hdrs = msg.getCustomOuterMimeHeaders();
if (hdrs == null)
{
return;
}
for (Map.Entry<String, String> entry : hdrs.entrySet())
{
dataBP.addHeader(entry.getKey(), entry.getValue());
if (logger.isTraceEnabled())
{
logger.trace("Added custom headers to outer MBP: " + entry.getKey() + "--->" + entry.getValue() + msg.getLogMsgID());
}
}
}
protected void updateHttpHeaders(HttpURLConnection conn, Message msg, MimeBodyPart securedData)
{
Partnership partnership = msg.getPartnership();
conn.setRequestProperty("Connection", "close, TE");
conn.setRequestProperty("User-Agent", msg.getAppTitle() + " (AS2Sender)");
// Ensure date is formatted in english so there are only USASCII chars to avoid error
conn.setRequestProperty("Date",
DateUtil.formatDate(
Properties.getProperty("HTTP_HEADER_DATE_FORMAT", "EEE, dd MMM yyyy HH:mm:ss Z")
, Locale.ENGLISH));
conn.setRequestProperty("Message-ID", msg.getMessageID());
conn.setRequestProperty("Mime-Version", "1.0"); // make sure this is the
// encoding used in the
// msg, run TBF1
try
{
conn.setRequestProperty("Content-type", securedData.getContentType());
} catch (MessagingException e)
{
conn.setRequestProperty("Content-type", msg.getContentType());
}
conn.setRequestProperty("AS2-Version", "1.1"); // RFC6017 - AS2 V1.1 supports compression
// AS2 V1.2 additionally supports EDIINT-Features
// conn.setRequestProperty("EDIINT-Features",
// "CEM,multiple-attachments"); // TODO (possibly implement???)
String cte = null;
try
{
cte = securedData.getEncoding();
} catch (MessagingException e1)
{
e1.printStackTrace();
}
if (cte == null)
{
cte = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
}
conn.setRequestProperty("Content-Transfer-Encoding", cte);
conn.setRequestProperty("Recipient-Address", partnership.getAttribute(AS2Partnership.PA_AS2_URL));
conn.setRequestProperty("AS2-To", partnership.getReceiverID(AS2Partnership.PID_AS2));
conn.setRequestProperty("AS2-From", partnership.getSenderID(AS2Partnership.PID_AS2));
conn.setRequestProperty("Subject", msg.getSubject());
conn.setRequestProperty("From", partnership.getSenderID(Partnership.PID_EMAIL));
String dispTo = partnership.getAttribute(AS2Partnership.PA_AS2_MDN_TO);
if (dispTo != null)
{
conn.setRequestProperty("Disposition-Notification-To", dispTo);
}
String dispOptions = partnership.getAttribute(AS2Partnership.PA_AS2_MDN_OPTIONS);
if (dispOptions != null)
{
conn.setRequestProperty("Disposition-Notification-Options", dispOptions);
}
String receiptOption = partnership.getAttribute(AS2Partnership.PA_AS2_RECEIPT_OPTION);
if (receiptOption != null)
{
conn.setRequestProperty("Receipt-Delivery-Option", receiptOption);
}
String contentDisp;
try
{
contentDisp = securedData.getDisposition();
} catch (MessagingException e)
{
contentDisp = msg.getContentDisposition();
}
if (contentDisp != null)
{
conn.setRequestProperty("Content-Disposition", contentDisp);
}
if ("true".equalsIgnoreCase((partnership.getAttribute(AS2Partnership.PA_ADD_CUSTOM_MIME_HEADERS_TO_HTTP))))
{
if (logger.isTraceEnabled())
{
logger.trace("Adding custom headers to HTTP..." + msg.getLogMsgID());
}
for (Map.Entry<String, String> entry : msg.getCustomOuterMimeHeaders().entrySet())
{
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
}
/**
* Stores metadata into pending information file and storing
* message object from first send attempt. The message object
* is written to a separate file to avoid repeated rewrites of
* possibly very large objects since it contains the original
* file data
* @param msg AS2Message structure
* @param isResend Boolean to determine if this is a resend of an already sent message or not
* @throws Exception some unforseen issue has occurred
*
*/
protected void storePendingInfo(AS2Message msg, boolean isResend) throws Exception
{
ObjectOutputStream oos = null;
try
{
String pendingInfoFile = AS2Util.buildPendingFileName(msg, getSession().getProcessor(), "pendingmdninfo");
String pendingFile = msg.getAttribute(FileAttribute.MA_PENDINGFILE);
msg.setAttribute(FileAttribute.MA_PENDINGFILE, pendingFile);
if (!isResend)
{
// Write the object to a file to keep a lot of the original
// static metadata intact for resends
String pendingMsgObjFile = pendingFile + ".object";
oos = new ObjectOutputStream(new FileOutputStream(pendingMsgObjFile));
oos.writeObject(msg);
oos.flush();
oos.close();
}
msg.setAttribute(FileAttribute.MA_PENDINGINFO, pendingInfoFile);
oos = new ObjectOutputStream(new FileOutputStream(pendingInfoFile));
oos.writeObject(msg.getCalculatedMIC());
String retries = (String) msg.getOption(ResenderModule.OPTION_RETRIES);
oos.writeObject((retries == null ? "" : retries));
if (logger.isInfoEnabled())
{
logger.info("Save Original mic & message id information into file: " + pendingInfoFile
+ msg.getLogMsgID());
}
oos.writeObject(msg.getAttribute(FileAttribute.MA_FILENAME));
oos.writeObject(pendingFile);
oos.writeObject(msg.getAttribute(FileAttribute.MA_ERROR_DIR));
String sentDir = msg.getAttribute(FileAttribute.MA_SENT_DIR);
oos.writeObject((sentDir == null ? "" : sentDir));
oos.writeObject(msg.getAttributes());
if (logger.isTraceEnabled())
{
logger.trace("Pending info file written to:" + pendingInfoFile + "\n\tOriginal MIC: "
+ msg.getCalculatedMIC() + "\n\tRetry Count: " + retries
+ "\n\tOriginal file name : " + msg.getAttribute(FileAttribute.MA_FILENAME)
+ "\n\tPending message file : " + pendingFile + "\n\tError directory: "
+ msg.getAttribute(FileAttribute.MA_ERROR_DIR) + "\n\tSent directory: "
+ msg.getAttribute(FileAttribute.MA_SENT_DIR) + msg.getLogMsgID());
}
msg.setAttribute(FileAttribute.MA_STATUS, FileAttribute.MA_PENDING);
} catch (Exception e)
{
msg.setLogMsg("Error setting up pending information files: " + org.openas2.logging.Log.getExceptionMsg(e));
logger.error(msg, e);
throw new Exception("Unable to set up pending information files.");
} finally
{
if (oos != null)
{
try
{
oos.close();
} catch (IOException e)
{
}
}
}
}
protected void calcAndStoreMic(Message msg, MimeBodyPart mbp, boolean includeHeaders) throws Exception
{
// Calculate and get the original mic
// includeHeaders = (msg.getHistory().getItems().size() > 1);
DispositionOptions dispOptions = new DispositionOptions(msg.getPartnership().getAttribute(
AS2Partnership.PA_AS2_MDN_OPTIONS));
msg.setCalculatedMIC(AS2Util.getCryptoHelper().calculateMIC(mbp, dispOptions.getMicalg()
, includeHeaders, msg.getPartnership().isPreventCanonicalization()));
if (logger.isTraceEnabled())
{
// Generate some alternative MIC's to see if the partner is somehow using a different default
String tmic = AS2Util.getCryptoHelper().calculateMIC(mbp, dispOptions.getMicalg()
, includeHeaders, !msg.getPartnership().isPreventCanonicalization());
logger.trace("MIC outbound with forced reversed prevent canocalization: " + tmic + msg.getLogMsgID());
tmic = AS2Util.getCryptoHelper().calculateMIC(msg.getData(), dispOptions.getMicalg(),
false, msg.getPartnership().isPreventCanonicalization());
logger.trace("MIC outbound with forced exclude headers flag: " + tmic + msg.getLogMsgID());
}
}
}
|
package com.dreiri.stolpersteine.activities;
import java.util.List;
import java.util.ListIterator;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import com.dreiri.stolpersteine.R;
import com.dreiri.stolpersteine.api.NetworkService;
import com.dreiri.stolpersteine.api.RetrieveStolpersteineRequest.Callback;
import com.dreiri.stolpersteine.api.SearchData;
import com.dreiri.stolpersteine.api.SynchronizationController;
import com.dreiri.stolpersteine.api.model.Stolperstein;
import com.dreiri.stolpersteine.utils.AndroidVersionsUnification;
import com.dreiri.stolpersteine.utils.LocationFinder;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.maps.android.clustering.ClusterManager;
public class MapActivity extends Activity implements OnInfoWindowClickListener, SynchronizationController.Listener {
private LatLng berlinLatLng;
private int berlinZoom;
private final int autoCompleteDropDownListSize = 10;
private final int autoCompleteActivationMinLength = 3;
private NetworkService networkService;
private SynchronizationController synchronizationController;
private GoogleMap map;
private ClusterManager<Stolperstein> clusterManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Set up map and clustering
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.fragmentMap)).getMap();
if (map != null) {
berlinLatLng = getLocationLatLng(R.array.Berlin);
berlinZoom = 12;
CameraUpdate region = CameraUpdateFactory.newLatLngZoom(berlinLatLng, berlinZoom);
map.moveCamera(region);
// map.setOnInfoWindowClickListener(this);
clusterManager = new ClusterManager<Stolperstein>(this, map);
map.setOnCameraChangeListener(clusterManager);
// map.setOnMarkerClickListener(clusterManager);
}
// Start synchronizing data
networkService = new NetworkService(this);
synchronizationController = new SynchronizationController(networkService);
synchronizationController.setListener(this);
synchronizationController.synchronize();
// Search interface
final AutoCompleteTextView autoCompleteTextViewQuery = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewQuery);
Drawable background = new ColorDrawable(Color.GRAY);
background.setAlpha(128);
AndroidVersionsUnification.setBackgroundForView(autoCompleteTextViewQuery, background);
autoCompleteTextViewQuery.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
SearchData searchData = new SearchData();
searchData.setKeyword(s.toString());
networkService.retrieveStolpersteine(searchData, 0, autoCompleteDropDownListSize, new Callback() {
@Override
public void onStolpersteineRetrieved(List<Stolperstein> stolpersteine) {
String[] suggestions = new String[stolpersteine.size()];
ListIterator<Stolperstein> iterator = stolpersteine.listIterator();
while (iterator.hasNext()) {
int idx = iterator.nextIndex();
Stolperstein matchedStolperstein = iterator.next();
String name = matchedStolperstein.getPerson().getNameAsString();
String street = matchedStolperstein.getLocation().getStreet();
suggestions[idx] = name + ", " + street;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MapActivity.this, android.R.layout.simple_dropdown_item_1line, suggestions);
autoCompleteTextViewQuery.setThreshold(autoCompleteActivationMinLength);
autoCompleteTextViewQuery.setAdapter(adapter);
}
});
}
});
}
private LatLng getLocationLatLng(int location) {
String[] locationCoordinates = getResources().getStringArray(location);
double lat = Double.valueOf(locationCoordinates[0]);
double lng = Double.valueOf(locationCoordinates[1]);
return new LatLng(lat, lng);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_positioning:
LocationFinder locationFinder = new LocationFinder(MapActivity.this);
LatLng currentLocation = new LatLng(locationFinder.getLat(), locationFinder.getLng());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 15));
map.animateCamera(CameraUpdateFactory.zoomTo(16), 2000, null);
break;
default:
break;
}
return true;
}
@Override
public void onInfoWindowClick(Marker marker) {
// ArrayList<Stolperstein> stolpersteine = mapClusterController.getItems(marker);
// if (!stolpersteine.isEmpty()) {
// Intent intent = new Intent(MapActivity.this, InfoActivity.class);
// intent.putParcelableArrayListExtra("stolpersteine", stolpersteine);
// startActivity(intent);
}
@Override
public void onStolpersteineAdded(List<Stolperstein> stolpersteine) {
if (stolpersteine != null) {
clusterManager.addItems(stolpersteine);
clusterManager.cluster();
}
}
}
|
package com.armandgray.taap.detail;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import com.armandgray.taap.BuildConfig;
import com.armandgray.taap.R;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowAlertDialog;
import static com.armandgray.taap.detail.DetailSummaryDialog.DIALOG;
import static junit.framework.Assert.assertNotNull;
import static org.robolectric.Shadows.shadowOf;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class TimerDialogTest {
private ActivityController<DrillDetailActivity> activityController;
private DrillDetailActivity activity;
private TimerDialog dialog;
@Before
public void setUp() {
System.out.println("Running Set Up!");
activityController = Robolectric.buildActivity(DrillDetailActivity.class);
activity = activityController.create().visible().get();
dialog = new TimerDialog();
dialog.show(activity.getSupportFragmentManager(), DIALOG);
}
@Test
public void canTimerDialog() {
assertNotNull(new TimerDialog());
}
@Test
public void canCreateTimerDialog_TestOnCreateDialog() {
Bundle savedInstanceState = new Bundle();
assertNotNull(dialog.onCreateDialog(savedInstanceState));
}
@Test
public void doesImplementDialogFragment() {
DialogFragment dialogFragment = dialog;
assertNotNull(dialogFragment);
}
@Test
public void existsLayout_TimerDialogLayout() {
LinearLayout TimerDialogLayout = (LinearLayout) View
.inflate(activity, R.layout.timer_dialog_layout, null);
assertNotNull(TimerDialogLayout);
}
@Test
public void existsView_Chronometer_TimerDialogLayout() {
LinearLayout TimerDialogLayout = (LinearLayout) View
.inflate(activity, R.layout.timer_dialog_layout, null);
assertNotNull(TimerDialogLayout.findViewById(R.id.chronometer));
}
@Test
public void doesHaveCustomView_TestOnCreateDialog() {
Bundle savedInstanceState = new Bundle();
AlertDialog resultDialog = (AlertDialog) dialog.onCreateDialog(savedInstanceState);
ShadowAlertDialog shadowDialog = shadowOf(resultDialog);
assertNotNull(resultDialog);
assertNotNull(shadowDialog);
assertNotNull(shadowDialog.getView());
assertNotNull(shadowDialog.getView().findViewById(R.id.timerDialogContainer));
}
@Test
public void doesStartTimer_TestOnCreateDialog() {
Bundle savedInstanceState = new Bundle();
AlertDialog resultDialog = (AlertDialog) dialog.onCreateDialog(savedInstanceState);
ShadowAlertDialog shadowDialog = shadowOf(resultDialog);
Chronometer chronometer = (Chronometer) shadowDialog.getView()
.findViewById(R.id.chronometer);
// TODO add test for chronometer started
assertNotNull(chronometer);
}
@After
public void tearDown() {
System.out.println("Running TearDown!");
dialog.dismiss();
activityController.pause().stop().destroy();
activity = null;
dialog = null;
}
}
|
package org.herac.tuxguitar.gui.editors.matrix;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Resource;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.herac.tuxguitar.gui.TuxGuitar;
import org.herac.tuxguitar.gui.actions.ActionLock;
import org.herac.tuxguitar.gui.actions.caret.GoLeftAction;
import org.herac.tuxguitar.gui.actions.caret.GoRightAction;
import org.herac.tuxguitar.gui.actions.duration.DecrementDurationAction;
import org.herac.tuxguitar.gui.actions.duration.IncrementDurationAction;
import org.herac.tuxguitar.gui.editors.TGPainter;
import org.herac.tuxguitar.gui.editors.TGRedrawListener;
import org.herac.tuxguitar.gui.editors.tab.Caret;
import org.herac.tuxguitar.gui.editors.tab.TGNoteImpl;
import org.herac.tuxguitar.gui.system.config.TGConfigKeys;
import org.herac.tuxguitar.gui.system.icons.IconLoader;
import org.herac.tuxguitar.gui.system.language.LanguageLoader;
import org.herac.tuxguitar.gui.undo.undoables.measure.UndoableMeasureGeneric;
import org.herac.tuxguitar.gui.util.DialogUtils;
import org.herac.tuxguitar.gui.util.TGMusicKeyUtils;
import org.herac.tuxguitar.player.base.MidiPercussion;
import org.herac.tuxguitar.song.managers.TGSongManager;
import org.herac.tuxguitar.song.models.TGBeat;
import org.herac.tuxguitar.song.models.TGChannel;
import org.herac.tuxguitar.song.models.TGDuration;
import org.herac.tuxguitar.song.models.TGMeasure;
import org.herac.tuxguitar.song.models.TGNote;
import org.herac.tuxguitar.song.models.TGString;
import org.herac.tuxguitar.song.models.TGTrack;
import org.herac.tuxguitar.song.models.TGVelocities;
import org.herac.tuxguitar.song.models.TGVoice;
public class MatrixEditor implements TGRedrawListener,IconLoader,LanguageLoader{
private static final int BORDER_HEIGHT = 20;
private static final int SCROLL_INCREMENT = 50;
private static final String[] NOTE_NAMES = TGMusicKeyUtils.getSharpKeyNames(TGMusicKeyUtils.PREFIX_MATRIX);
private static final MidiPercussion[] PERCUSSIONS = TuxGuitar.instance().getPlayer().getPercussions();
protected static final int[] DIVISIONS = new int[] {1,2,3,4,6,8,16};
private MatrixConfig config;
private MatrixListener listener;
private Shell dialog;
private Composite composite;
private Composite toolbar;
private Composite editor;
private Rectangle clientArea;
private Image buffer;
private BufferDisposer bufferDisposer;
private Label durationLabel;
private Label gridsLabel;
private Button settings;
private float width;
private float height;
private float bufferWidth;
private float bufferHeight;
private float timeWidth;
private float lineHeight;
private int leftSpacing;
private int minNote;
private int maxNote;
private int selection;
private int grids;
private int playedTrack;
private int playedMeasure;
private TGBeat playedBeat;
private Image selectionBackBuffer;
private int selectionX;
private int selectionY;
private int duration;
public MatrixEditor(){
this.grids = this.loadGrids();
this.listener = new MatrixListener();
}
public void show(){
this.config = new MatrixConfig();
this.config.load();
this.dialog = DialogUtils.newDialog(TuxGuitar.instance().getShell(),SWT.DIALOG_TRIM | SWT.RESIZE);
this.dialog.setText(TuxGuitar.getProperty("matrix.editor"));
this.dialog.setImage(TuxGuitar.instance().getIconManager().getAppIcon());
this.dialog.setLayout(new GridLayout());
this.dialog.addDisposeListener(new DisposeListenerImpl());
this.bufferDisposer = new BufferDisposer();
this.composite = new Composite(this.dialog,SWT.NONE);
this.composite.setLayout(new GridLayout());
this.composite.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
this.initToolBar();
this.initEditor();
this.loadIcons();
this.addListeners();
this.dialog.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
removeListeners();
TuxGuitar.instance().updateCache(true);
}
});
DialogUtils.openDialog(this.dialog,DialogUtils.OPEN_STYLE_CENTER);
}
public void addListeners(){
TuxGuitar.instance().getkeyBindingManager().appendListenersTo(this.toolbar);
TuxGuitar.instance().getkeyBindingManager().appendListenersTo(this.editor);
TuxGuitar.instance().getIconManager().addLoader(this);
TuxGuitar.instance().getLanguageManager().addLoader(this);
TuxGuitar.instance().getEditorManager().addRedrawListener( this );
}
public void removeListeners(){
TuxGuitar.instance().getIconManager().removeLoader(this);
TuxGuitar.instance().getLanguageManager().removeLoader(this);
TuxGuitar.instance().getEditorManager().removeRedrawListener( this );
}
private void initToolBar() {
GridLayout layout = new GridLayout();
layout.makeColumnsEqualWidth = false;
layout.numColumns = 0;
layout.marginWidth = 0;
layout.marginHeight = 0;
this.toolbar = new Composite(this.composite, SWT.NONE);
// position
layout.numColumns ++;
Button goLeft = new Button(this.toolbar, SWT.ARROW | SWT.LEFT);
goLeft.addSelectionListener(TuxGuitar.instance().getAction(GoLeftAction.NAME));
layout.numColumns ++;
Button goRight = new Button(this.toolbar, SWT.ARROW | SWT.RIGHT);
goRight.addSelectionListener(TuxGuitar.instance().getAction(GoRightAction.NAME));
// separator
layout.numColumns ++;
makeToolSeparator(this.toolbar);
// duration
layout.numColumns ++;
Button decrement = new Button(this.toolbar, SWT.ARROW | SWT.MIN);
decrement.addSelectionListener(TuxGuitar.instance().getAction(DecrementDurationAction.NAME));
layout.numColumns ++;
this.durationLabel = new Label(this.toolbar, SWT.BORDER);
layout.numColumns ++;
Button increment = new Button(this.toolbar, SWT.ARROW | SWT.MAX);
increment.addSelectionListener(TuxGuitar.instance().getAction(IncrementDurationAction.NAME));
// separator
layout.numColumns ++;
makeToolSeparator(this.toolbar);
// grids
layout.numColumns ++;
this.gridsLabel = new Label(this.toolbar,SWT.NONE);
this.gridsLabel.setText(TuxGuitar.getProperty("matrix.grids"));
layout.numColumns ++;
final Combo divisionsCombo = new Combo(this.toolbar, SWT.DROP_DOWN | SWT.READ_ONLY);
divisionsCombo.setLayoutData(new GridData(SWT.FILL,SWT.CENTER,false, true));
for(int i = 0; i < DIVISIONS.length; i ++){
divisionsCombo.add(Integer.toString(DIVISIONS[i]));
if(this.grids == DIVISIONS[i]){
divisionsCombo.select(i);
}
}
if(this.grids == 0){
divisionsCombo.select(0);
}
divisionsCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int index = divisionsCombo.getSelectionIndex();
if(index >= 0 && index < DIVISIONS.length){
setGrids(DIVISIONS[index]);
}
}
});
// settings
layout.numColumns ++;
this.settings = new Button(this.toolbar, SWT.PUSH);
this.settings.setImage(TuxGuitar.instance().getIconManager().getSettings());
this.settings.setToolTipText(TuxGuitar.getProperty("settings"));
this.settings.setLayoutData(new GridData(SWT.RIGHT,SWT.FILL,true,true));
this.settings.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
configure();
}
});
this.toolbar.setLayout(layout);
this.toolbar.setLayoutData(new GridData(SWT.FILL,SWT.TOP,true,false));
}
private void makeToolSeparator(Composite parent){
Label separator = new Label(parent,SWT.SEPARATOR);
separator.setLayoutData(new GridData(20,20));
}
private void loadDurationImage(boolean force) {
int duration = TuxGuitar.instance().getTablatureEditor().getTablature().getCaret().getDuration().getValue();
if(force || this.duration != duration){
this.duration = duration;
this.durationLabel.setImage(TuxGuitar.instance().getIconManager().getDuration(this.duration));
}
}
public void initEditor(){
this.selection = -1;
this.editor = new Composite(this.composite,SWT.DOUBLE_BUFFERED | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
this.editor.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
this.editor.setLayout(new FillLayout());
this.editor.setFocus();
this.editor.addPaintListener(this.listener);
this.editor.addMouseListener(this.listener);
this.editor.addMouseMoveListener(this.listener);
this.editor.addMouseTrackListener(this.listener);
this.editor.getHorizontalBar().setIncrement(SCROLL_INCREMENT);
this.editor.getHorizontalBar().addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
redrawLocked();
}
});
this.editor.getVerticalBar().setIncrement(SCROLL_INCREMENT);
this.editor.getVerticalBar().addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
redrawLocked();
}
});
}
protected void updateScroll(){
if( this.clientArea != null ){
int borderWidth = this.editor.getBorderWidth();
ScrollBar vBar = this.editor.getVerticalBar();
ScrollBar hBar = this.editor.getHorizontalBar();
vBar.setMaximum(Math.round(this.height + (borderWidth * 2)));
vBar.setThumb(Math.round(Math.min(this.height + (borderWidth * 2), this.clientArea.height)));
hBar.setMaximum(Math.round(this.width + (borderWidth * 2)));
hBar.setThumb(Math.round(Math.min(this.width + (borderWidth * 2), this.clientArea.width)));
}
}
protected int getValueAt(float y){
if(this.clientArea == null || (y - BORDER_HEIGHT) < 0 || y + BORDER_HEIGHT > this.clientArea.height){
return -1;
}
int scroll = this.editor.getVerticalBar().getSelection();
int value = (this.maxNote - ((int)( (y + scroll - BORDER_HEIGHT) / this.lineHeight)) );
return value;
}
protected long getStartAt(float x){
TGMeasure measure = getMeasure();
float posX = (x + this.editor.getHorizontalBar().getSelection());
long start =(long) (measure.getStart() + (((posX - this.leftSpacing) * measure.getLength()) / (this.timeWidth * measure.getTimeSignature().getNumerator())));
return start;
}
protected void paintEditor(TGPainter painter){
if(!TuxGuitar.instance().getPlayer().isRunning()){
this.resetPlayed();
}
this.disposeSelectionBuffer();
this.clientArea = this.editor.getClientArea();
if( this.clientArea != null ){
Image buffer = getBuffer();
this.width = this.bufferWidth;
this.height = (this.bufferHeight + (BORDER_HEIGHT *2));
this.updateScroll();
int scrollX = this.editor.getHorizontalBar().getSelection();
int scrollY = this.editor.getVerticalBar().getSelection();
painter.drawImage(buffer,-scrollX,(BORDER_HEIGHT - scrollY));
this.paintMeasure(painter,(-scrollX), (BORDER_HEIGHT - scrollY) );
this.paintBorders(painter,(-scrollX),0);
this.paintPosition(painter,(-scrollX),0);
this.paintSelection(painter, (-scrollX), (BORDER_HEIGHT - scrollY) );
}
}
protected Image getBuffer(){
if( this.clientArea != null ){
this.bufferDisposer.update(this.clientArea.width, this.clientArea.height);
if(this.buffer == null || this.buffer.isDisposed()){
String[] names = null;
TGMeasure measure = getMeasure();
boolean percussion = measure.getTrack().isPercussionTrack();
this.maxNote = 0;
this.minNote = 127;
if(percussion){
names = new String[PERCUSSIONS.length];
for(int i = 0; i < names.length;i ++){
this.minNote = Math.min(this.minNote,PERCUSSIONS[i].getValue());
this.maxNote = Math.max(this.maxNote,PERCUSSIONS[i].getValue());
names[i] = PERCUSSIONS[names.length - i -1].getName();
}
}else{
for(int sNumber = 1; sNumber <= measure.getTrack().stringCount();sNumber ++){
TGString string = measure.getTrack().getString(sNumber);
this.minNote = Math.min(this.minNote,string.getValue());
this.maxNote = Math.max(this.maxNote,(string.getValue() + 20));
}
names = new String[this.maxNote - this.minNote + 1];
for(int i = 0; i < names.length;i ++){
names[i] = (NOTE_NAMES[ (this.maxNote - i) % 12] + ((this.maxNote - i) / 12 ) );
}
}
int minimumNameWidth = 110;
int minimumNameHeight = 0;
TGPainter painter = new TGPainter(new GC(this.dialog.getDisplay()));
painter.setFont(this.config.getFont());
for(int i = 0; i < names.length;i ++){
Point size = painter.getStringExtent(names[i]);
if( size.x > minimumNameWidth ){
minimumNameWidth = size.x;
}
if( size.y > minimumNameHeight ){
minimumNameHeight = size.y ;
}
}
painter.dispose();
int cols = measure.getTimeSignature().getNumerator();
int rows = (this.maxNote - this.minNote);
this.leftSpacing = minimumNameWidth + 10;
this.lineHeight = Math.max(minimumNameHeight,( (this.clientArea.height - (BORDER_HEIGHT * 2.0f))/ (rows + 1.0f)));
this.timeWidth = Math.max((10 * (TGDuration.SIXTY_FOURTH / measure.getTimeSignature().getDenominator().getValue())),( (this.clientArea.width-this.leftSpacing) / cols) );
this.bufferWidth = this.leftSpacing + (this.timeWidth * cols);
this.bufferHeight = (this.lineHeight * (rows + 1));
this.buffer = new Image(this.editor.getDisplay(),Math.round( this.bufferWidth),Math.round(this.bufferHeight));
painter = new TGPainter(new GC(this.buffer));
painter.setFont(this.config.getFont());
painter.setForeground(this.config.getColorForeground());
for(int i = 0; i <= rows; i++){
painter.setBackground(this.config.getColorLine( i % 2 ) );
painter.initPath(TGPainter.PATH_FILL);
painter.addRectangle(0 ,(i * this.lineHeight),this.bufferWidth ,this.lineHeight);
painter.closePath();
painter.drawString(names[i],5,( Math.round( (i * this.lineHeight) ) + Math.round( (this.lineHeight - minimumNameHeight) / 2 ) ) );
}
for(int i = 0; i < cols; i ++){
float colX = this.leftSpacing + (i * this.timeWidth);
float divisionWidth = ( this.timeWidth / this.grids );
for( int j = 0; j < this.grids; j ++ ){
painter.setLineStyle( j == 0 ? SWT.LINE_SOLID : SWT.LINE_DOT);
painter.initPath();
painter.moveTo(Math.round( colX + (j * divisionWidth) ),0);
painter.lineTo(Math.round( colX + (j * divisionWidth) ),this.bufferHeight);
painter.closePath();
}
}
painter.dispose();
}
}
return this.buffer;
}
protected void paintMeasure(TGPainter painter,float fromX, float fromY){
if( this.clientArea != null ){
TGMeasure measure = getMeasure();
if(measure != null){
Iterator it = measure.getBeats().iterator();
while(it.hasNext()){
TGBeat beat = (TGBeat)it.next();
paintBeat(painter, measure, beat, fromX, fromY);
}
}
}
}
protected void paintBeat(TGPainter painter,TGMeasure measure,TGBeat beat,float fromX, float fromY){
if( this.clientArea != null ){
int minimumY = BORDER_HEIGHT;
int maximumY = (this.clientArea.height - BORDER_HEIGHT);
for( int v = 0; v < beat.countVoices(); v ++ ){
TGVoice voice = beat.getVoice(v);
for( int i = 0 ; i < voice.countNotes() ; i ++){
TGNoteImpl note = (TGNoteImpl)voice.getNote(i);
float x1 = (fromX + this.leftSpacing + (((beat.getStart() - measure.getStart()) * (this.timeWidth * measure.getTimeSignature().getNumerator())) / measure.getLength()) + 1);
float y1 = (fromY + (((this.maxNote - this.minNote) - (note.getRealValue() - this.minNote)) * this.lineHeight) + 1 );
float x2 = (x1 + ((voice.getDuration().getTime() * this.timeWidth) / measure.getTimeSignature().getDenominator().getTime()) - 2 );
float y2 = (y1 + this.lineHeight - 2 );
if( y1 >= maximumY || y2 <= minimumY){
continue;
}
y1 = ( y1 < minimumY ? minimumY : y1 );
y2 = ( y2 > maximumY ? maximumY : y2 );
if((x2 - x1) > 0 && (y2 - y1) > 0){
painter.setBackground( (note.getBeatImpl().isPlaying(TuxGuitar.instance().getTablatureEditor().getTablature().getViewLayout()) ? this.config.getColorPlay():this.config.getColorNote() ) );
painter.initPath(TGPainter.PATH_FILL);
painter.addRectangle(x1,y1, (x2 - x1), (y2 - y1));
painter.closePath();
}
}
}
}
}
protected void paintBorders(TGPainter painter,float fromX, float fromY){
if( this.clientArea != null ){
painter.setBackground(this.config.getColorBorder());
painter.initPath(TGPainter.PATH_FILL);
painter.addRectangle(fromX,fromY,this.bufferWidth ,BORDER_HEIGHT);
painter.addRectangle(fromX,fromY + (this.clientArea.height - BORDER_HEIGHT),this.bufferWidth ,BORDER_HEIGHT);
painter.closePath();
painter.initPath();
painter.addRectangle(fromX,fromY,this.width,this.clientArea.height);
painter.closePath();
}
}
protected void paintPosition(TGPainter painter,float fromX, float fromY){
if( this.clientArea != null && !TuxGuitar.instance().getPlayer().isRunning()){
Caret caret = getCaret();
TGMeasure measure = getMeasure();
TGBeat beat = caret.getSelectedBeat();
if(beat != null){
float x = (((beat.getStart() - measure.getStart()) * (this.timeWidth * measure.getTimeSignature().getNumerator())) / measure.getLength());
float width = ((beat.getVoice(caret.getVoice()).getDuration().getTime() * this.timeWidth) / measure.getTimeSignature().getDenominator().getTime());
painter.setBackground(this.config.getColorPosition());
painter.initPath(TGPainter.PATH_FILL);
painter.addRectangle(fromX + (this.leftSpacing + x),fromY , width,BORDER_HEIGHT);
painter.closePath();
painter.initPath(TGPainter.PATH_FILL);
painter.addRectangle(fromX + (this.leftSpacing + x),fromY + (this.clientArea.height - BORDER_HEIGHT), width,BORDER_HEIGHT);
painter.closePath();
}
}
}
protected void paintSelection(TGPainter painter, float fromX, float fromY){
if( this.clientArea != null && !TuxGuitar.instance().getPlayer().isRunning()){
selectionFinish();
if(this.selection >= 0 ){
int x = Math.round( fromX );
int y = Math.round( fromY + ((this.maxNote - this.selection) * this.lineHeight) );
int width = Math.round( this.bufferWidth );
int height = Math.round( this.lineHeight );
this.selectionBackBuffer = new Image(this.editor.getDisplay(),width,height);
painter.copyArea(this.selectionBackBuffer,x,y);
painter.setAlpha(100);
painter.setBackground(this.config.getColorLine(2));
painter.initPath(TGPainter.PATH_FILL);
painter.addRectangle(x,y,width,height);
painter.closePath();
this.selectionX = x;
this.selectionY = y;
}
}
}
protected void updateSelection(float y){
if(!TuxGuitar.instance().getPlayer().isRunning()){
int selection = getValueAt(y);
if(this.selection != selection){
this.selection = selection;
int scrollX = this.editor.getHorizontalBar().getSelection();
int scrollY = this.editor.getVerticalBar().getSelection();
TGPainter painter = new TGPainter(new GC(this.editor));
this.paintSelection(painter, (-scrollX), (BORDER_HEIGHT - scrollY) );
painter.dispose();
}
}
}
public void selectionFinish(){
if(this.selectionBackBuffer != null && !this.selectionBackBuffer.isDisposed()){
TGPainter painter = new TGPainter(new GC(this.editor));
painter.drawImage(this.selectionBackBuffer,this.selectionX, this.selectionY);
painter.dispose();
}
disposeSelectionBuffer();
}
protected void disposeSelectionBuffer(){
if(this.selectionBackBuffer != null && !this.selectionBackBuffer.isDisposed()){
this.selectionBackBuffer.dispose();
this.selectionBackBuffer = null;
}
}
protected void hit(float x, float y){
if(!TuxGuitar.instance().getPlayer().isRunning()){
TGMeasure measure = getMeasure();
Caret caret = getCaret();
int value = getValueAt(y);
long start = getStartAt(x);
if(start >= measure.getStart() && start < (measure.getStart() + measure.getLength())){
caret.update(caret.getTrack().getNumber(),start,caret.getStringNumber());
TuxGuitar.instance().updateCache(true);
}
if(value >= this.minNote || value <= this.maxNote){
if(start >= measure.getStart()){
TGVoice voice = TuxGuitar.instance().getSongManager().getMeasureManager().getVoiceIn(measure, start, caret.getVoice());
if( voice != null ){
if(!removeNote(voice.getBeat(), value)){
addNote(voice.getBeat(), start, value);
}
}
}else{
play(value);
}
}
}
}
private boolean removeNote(TGBeat beat,int value) {
Caret caret = TuxGuitar.instance().getTablatureEditor().getTablature().getCaret();
TGMeasure measure = getMeasure();
for(int v = 0; v < beat.countVoices(); v ++){
TGVoice voice = beat.getVoice( v );
Iterator it = voice.getNotes().iterator();
while (it.hasNext()) {
TGNoteImpl note = (TGNoteImpl) it.next();
if (note.getRealValue() == value) {
caret.update(measure.getTrack().getNumber(),beat.getStart(),note.getString());
//comienza el undoable
UndoableMeasureGeneric undoable = UndoableMeasureGeneric.startUndo();
TGSongManager manager = TuxGuitar.instance().getSongManager();
manager.getMeasureManager().removeNote(note);
//termia el undoable
TuxGuitar.instance().getUndoableManager().addEdit(undoable.endUndo());
TuxGuitar.instance().getFileHistory().setUnsavedFile();
this.afterAction();
return true;
}
}
}
return false;
}
private boolean addNote(TGBeat beat,long start, int value) {
if(beat != null){
TGMeasure measure = getMeasure();
Caret caret = TuxGuitar.instance().getTablatureEditor().getTablature().getCaret();
List strings = measure.getTrack().getStrings();
for(int i = 0;i < strings.size();i ++){
TGString string = (TGString)strings.get(i);
if(value >= string.getValue()){
boolean emptyString = true;
for(int v = 0; v < beat.countVoices(); v ++){
TGVoice voice = beat.getVoice( v );
Iterator it = voice.getNotes().iterator();
while (it.hasNext()) {
TGNoteImpl note = (TGNoteImpl) it.next();
if (note.getString() == string.getNumber()) {
emptyString = false;
break;
}
}
}
if(emptyString){
TGSongManager manager = TuxGuitar.instance().getSongManager();
//comienza el undoable
UndoableMeasureGeneric undoable = UndoableMeasureGeneric.startUndo();
TGNote note = manager.getFactory().newNote();
note.setValue((value - string.getValue()));
note.setVelocity(caret.getVelocity());
note.setString(string.getNumber());
TGDuration duration = manager.getFactory().newDuration();
caret.getDuration().copy(duration);
manager.getMeasureManager().addNote(beat,note,duration,start,caret.getVoice());
caret.moveTo(caret.getTrack(),caret.getMeasure(),note.getVoice().getBeat(),note.getString());
//termia el undoable
TuxGuitar.instance().getUndoableManager().addEdit(undoable.endUndo());
TuxGuitar.instance().getFileHistory().setUnsavedFile();
//reprodusco las notas en el pulso
caret.getSelectedBeat().play();
this.afterAction();
return true;
}
}
}
}
return false;
}
protected void afterAction() {
TuxGuitar.instance().getTablatureEditor().getTablature().getViewLayout().fireUpdate(getMeasure().getNumber());
TuxGuitar.instance().updateCache(true);
this.editor.redraw();
}
protected void play(final int value){
new Thread(new Runnable() {
public void run() {
TGTrack track = getMeasure().getTrack();
int volume = TGChannel.DEFAULT_VOLUME;
int balance = TGChannel.DEFAULT_BALANCE;
int chorus = track.getChannel().getChorus();
int reverb = track.getChannel().getReverb();
int phaser = track.getChannel().getPhaser();
int tremolo = track.getChannel().getTremolo();
int channel = track.getChannel().getChannel();
int program = track.getChannel().getInstrument();
int[][] beat = new int[][]{ new int[]{ (track.getOffset() + value) , TGVelocities.DEFAULT } };
TuxGuitar.instance().getPlayer().playBeat(channel,program, volume, balance,chorus,reverb,phaser,tremolo,beat);
}
}).start();
}
protected int loadGrids(){
int grids = TuxGuitar.instance().getConfig().getIntConfigValue(TGConfigKeys.MATRIX_GRIDS);
// check if is valid value
for(int i = 0 ; i < DIVISIONS.length ; i ++ ){
if(grids == DIVISIONS[i]){
return grids;
}
}
return DIVISIONS[1];
}
protected void setGrids(int grids){
this.grids = grids;
this.disposeBuffer();
this.redrawLocked();
}
public int getGrids(){
return this.grids;
}
protected TGMeasure getMeasure(){
if(TuxGuitar.instance().getPlayer().isRunning()){
TGMeasure measure = TuxGuitar.instance().getEditorCache().getPlayMeasure();
if(measure != null){
return measure;
}
}
return TuxGuitar.instance().getTablatureEditor().getTablature().getCaret().getMeasure();
}
protected Caret getCaret(){
return TuxGuitar.instance().getTablatureEditor().getTablature().getCaret();
}
public boolean isDisposed(){
return (this.dialog == null || this.dialog.isDisposed());
}
protected void resetPlayed(){
this.playedBeat = null;
this.playedMeasure = -1;
this.playedTrack = -1;
}
public void redrawLocked(){
if(!TuxGuitar.instance().isLocked()){
TuxGuitar.instance().lock();
this.redraw();
TuxGuitar.instance().unlock();
}
}
public void redraw(){
if(!isDisposed() && !TuxGuitar.instance().isLocked()){
//TuxGuitar.instance().lock();
this.editor.redraw();
this.loadDurationImage(false);
//TuxGuitar.instance().unlock();
}
}
public void redrawPlayingMode(){
if(!isDisposed() && !TuxGuitar.instance().isLocked() && TuxGuitar.instance().getPlayer().isRunning()){
//TuxGuitar.instance().lock();
TGMeasure measure = TuxGuitar.instance().getEditorCache().getPlayMeasure();
TGBeat beat = TuxGuitar.instance().getEditorCache().getPlayBeat();
if(measure != null && beat != null){
int currentMeasure = measure.getNumber();
int currentTrack = measure.getTrack().getNumber();
boolean changed = (currentMeasure != this.playedMeasure || currentTrack != this.playedTrack);
if(changed){
this.resetPlayed();
this.editor.redraw();
}
else{
TGPainter painter = new TGPainter(new GC(this.editor));
int scrollX = this.editor.getHorizontalBar().getSelection();
int scrollY = this.editor.getVerticalBar().getSelection();
if(this.playedBeat != null){
this.paintBeat(painter,measure,this.playedBeat,(-scrollX), (BORDER_HEIGHT - scrollY));
}
this.paintBeat(painter,measure,beat,(-scrollX), (BORDER_HEIGHT - scrollY));
painter.dispose();
}
this.playedMeasure = currentMeasure;
this.playedTrack = currentTrack;
this.playedBeat = beat;
}
//TuxGuitar.instance().unlock();
}
}
protected void configure(){
this.config.configure(this.dialog);
this.disposeBuffer();
this.redrawLocked();
}
private void layout(){
if( !isDisposed() ){
this.toolbar.layout();
this.editor.layout();
this.composite.layout(true,true);
}
}
public void loadIcons(){
if( !isDisposed() ){
this.dialog.setImage(TuxGuitar.instance().getIconManager().getAppIcon());
this.settings.setImage(TuxGuitar.instance().getIconManager().getSettings());
this.loadDurationImage(true);
this.layout();
this.redraw();
}
}
public void loadProperties() {
if( !isDisposed() ){
this.dialog.setText(TuxGuitar.getProperty("matrix.editor"));
this.gridsLabel.setText(TuxGuitar.getProperty("matrix.grids"));
this.settings.setToolTipText(TuxGuitar.getProperty("settings"));
this.disposeBuffer();
this.layout();
this.redraw();
}
}
public void dispose(){
if(!isDisposed()){
this.dialog.dispose();
}
}
protected void disposeBuffer(){
if(this.buffer != null && !this.buffer.isDisposed()){
this.buffer.dispose();
this.buffer = null;
}
}
protected void dispose(Resource[] resources){
if(resources != null){
for(int i = 0; i < resources.length; i ++){
dispose(resources[i]);
}
}
}
protected void dispose(Resource resource){
if(resource != null){
resource.dispose();
}
}
protected void disposeAll(){
this.disposeBuffer();
this.disposeSelectionBuffer();
this.config.dispose();
}
protected Composite getEditor(){
return this.editor;
}
protected class BufferDisposer{
private int numerator;
private int denominator;
private int track;
private boolean percussion;
private int width;
private int height;
public void update(int width, int height){
TGMeasure measure = getMeasure();
int track = measure.getTrack().getNumber();
int numerator = measure.getTimeSignature().getNumerator();
int denominator = measure.getTimeSignature().getDenominator().getValue();
boolean percussion = measure.getTrack().isPercussionTrack();
if(width != this.width || height != this.height || this.track != track || this.numerator != numerator || this.denominator != denominator || this.percussion != percussion){
disposeBuffer();
}
this.track = track;
this.numerator = numerator;
this.denominator = denominator;
this.percussion = percussion;
this.width = width;
this.height = height;
}
}
protected class DisposeListenerImpl implements DisposeListener{
public void widgetDisposed(DisposeEvent e) {
disposeAll();
}
}
protected class MatrixListener implements PaintListener,MouseListener,MouseMoveListener,MouseTrackListener {
public MatrixListener(){
super();
}
public void paintControl(PaintEvent e) {
if(!TuxGuitar.instance().isLocked()){
TuxGuitar.instance().lock();
TGPainter painter = new TGPainter(e.gc);
paintEditor(painter);
TuxGuitar.instance().unlock();
}
}
public void mouseUp(MouseEvent e) {
getEditor().setFocus();
if(e.button == 1){
if(!TuxGuitar.instance().isLocked() && !ActionLock.isLocked()){
ActionLock.lock();
hit(e.x,e.y);
ActionLock.unlock();
}
}
}
public void mouseMove(MouseEvent e) {
if(!TuxGuitar.instance().isLocked() && !ActionLock.isLocked()){
updateSelection(e.y);
}
}
public void mouseExit(MouseEvent e) {
if(!TuxGuitar.instance().isLocked() && !ActionLock.isLocked()){
updateSelection(-1);
}
}
public void mouseEnter(MouseEvent e) {
if(!TuxGuitar.instance().isLocked() && !ActionLock.isLocked()){
redrawLocked();
}
}
public void mouseDoubleClick(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseDown(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseHover(MouseEvent e) {
// TODO Auto-generated method stub
}
}
public void doRedraw(int type) {
if( type == TGRedrawListener.NORMAL ){
this.redraw();
}else if( type == TGRedrawListener.PLAYING_NEW_BEAT ){
this.redrawPlayingMode();
}
}
}
|
package edu.wustl.catissuecore.domain;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import edu.wustl.catissuecore.actionForm.AbstractActionForm;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.common.util.logger.Logger;
/**
* An event that results in the collection
* of one or more specimen from a participant.
* @hibernate.class table="CATISSUE_SPECIMEN_COLLECTION_GROUP"
* @author gautam_shetty
*/
public class SpecimenCollectionGroup extends AbstractDomainObject implements Serializable
{
private static final long serialVersionUID = 1234567890L;
/**
* System generated unique systemIdentifier.
*/
protected Long systemIdentifier;
/**
* Participant's clinical diagnosis at
* this collection event (e.g. Prostate Adenocarcinoma).
*/
protected String clinicalDiagnosis;
/**
* The clinical status of the participant at the time of specimen collection.
* (e.g. New DX, pre-RX, pre-OP, post-OP, remission, relapse)
*/
protected String clinicalStatus;
/**
* Defines whether this record can be queried (Active)
* or not queried (Inactive) by any actor.
*/
protected String activityStatus;
/**
* A physical location associated with biospecimen collection,
* storage, processing, or utilization.
*/
protected Site site;
/**
* A required specimen collection event associated with a Collection Protocol.
*/
protected CollectionProtocolEvent collectionProtocolEvent;
/**
* A clinical report associated with the participant at the
* time of the SpecimenCollection Group receipt.
*/
protected ClinicalReport clinicalReport;
/**
* The Specimens in this SpecimenCollectionGroup.
*/
protected Collection specimenCollection = new HashSet();
/**
* A registration of a Participant to a Collection Protocol.
*/
protected CollectionProtocolRegistration collectionProtocolRegistration;
public SpecimenCollectionGroup(){
}
public SpecimenCollectionGroup(AbstractActionForm form)
{
System.out.println("<<< Before setting Values >>>");
setAllValues(form);
}
/**
* Returns the system generated unique systemIdentifier.
* @hibernate.id name="systemIdentifier" column="IDENTIFIER" type="long" length="30"
* unsaved-value="null" generator-class="native"
* @return the system generated unique systemIdentifier.
* @see #setSystemIdentifier(Long)
*/
public Long getSystemIdentifier() {
return systemIdentifier;
}
/**
* @param systemIdentifier
*/
public void setSystemIdentifier(Long systemIdentifier) {
this.systemIdentifier = systemIdentifier;
}
/**
* Returns the participant's clinical diagnosis at
* this collection event (e.g. Prostate Adenocarcinoma).
* @hibernate.property name="clinicalDiagnosis" type="string"
* column="CLINICAL_DIAGNOSIS" length="50"
* @return the participant's clinical diagnosis at
* this collection event (e.g. Prostate Adenocarcinoma).
* @see #setClinicalDiagnosis(String)
*/
public String getClinicalDiagnosis()
{
return clinicalDiagnosis;
}
/**
* Sets the participant's clinical diagnosis at
* this collection event (e.g. Prostate Adenocarcinoma).
* @param clinicalDiagnosis the participant's clinical diagnosis at
* this collection event (e.g. Prostate Adenocarcinoma).
* @see #getClinicalDiagnosis()
*/
public void setClinicalDiagnosis(String clinicalDiagnosis)
{
this.clinicalDiagnosis = clinicalDiagnosis;
}
/**
* Returns the clinical status of the participant at the time of specimen collection.
* (e.g. New DX, pre-RX, pre-OP, post-OP, remission, relapse)
* @hibernate.property name="clinicalStatus" type="string"
* column="CLINICAL_STATUS" length="50"
* @return clinical status of the participant at the time of specimen collection.
* @see #setClinicalStatus(String)
*/
public String getClinicalStatus()
{
return clinicalStatus;
}
/**
* Sets the clinical status of the participant at the time of specimen collection.
* (e.g. New DX, pre-RX, pre-OP, post-OP, remission, relapse)
* @param clinicalStatus the clinical status of the participant at the time of specimen collection.
* @see #getClinicalStatus()
*/
public void setClinicalStatus(String clinicalStatus)
{
this.clinicalStatus = clinicalStatus;
}
/**
* Returns whether this record can be queried (Active)
* or not queried (Inactive) by any actor.
* @hibernate.property name="activityStatus" type="string"
* column="ACTIVITY_STATUS" length="50"
* @return Active if this record can be queried else returns InActive.
* @see #setActivityStatus(String)
*/
public String getActivityStatus()
{
return activityStatus;
}
/**
* Sets whether this record can be queried (Active)
* or not queried (Inactive) by any actor.
* @param activityStatus Active if this record can be queried else returns InActive.
* @see #getActivityStatus()
*/
public void setActivityStatus(String activityStatus)
{
this.activityStatus = activityStatus;
}
/**
* Returns the physical location associated with biospecimen collection,
* storage, processing, or utilization.
* @hibernate.many-to-one column="SITE_ID"
* class="edu.wustl.catissuecore.domain.Site" constrained="true"
* @return the physical location associated with biospecimen collection,
* storage, processing, or utilization.
* @see #setSite(Site)
*/
public Site getSite()
{
return site;
}
/**
* Sets the physical location associated with biospecimen collection,
* storage, processing, or utilization.
* @param site physical location associated with biospecimen collection,
* storage, processing, or utilization.
* @see #getSite()
*/
public void setSite(Site site)
{
this.site = site;
}
/**
* Returns the required specimen collection event
* associated with a Collection Protocol.
* @hibernate.many-to-one column="COLLECTION_PROTOCOL_EVENT_ID"
* class="edu.wustl.catissuecore.domain.CollectionProtocolEvent" constrained="true"
* @return the required specimen collection event
* associated with a Collection Protocol.
* @see #setCollectionProtocolEvent(CollectionProtocolEvent)
*/
public CollectionProtocolEvent getCollectionProtocolEvent()
{
return collectionProtocolEvent;
}
/**
* Sets the required specimen collection event
* associated with a Collection Protocol.
* @param collectionProtocolEvent the required specimen collection event
* associated with a Collection Protocol.
* @see #getCollectionProtocolEvent()
*/
public void setCollectionProtocolEvent(CollectionProtocolEvent collectionProtocolEvent)
{
this.collectionProtocolEvent = collectionProtocolEvent;
}
/**
* Returns the clinical report associated with the participant at the
* time of the SpecimenCollection Group receipt.
* @hibernate.many-to-one column="CLINICAL_REPORT_ID"
* class="edu.wustl.catissuecore.domain.ClinicalReport" constrained="true"
* @return the clinical report associated with the participant at the
* time of the SpecimenCollection Group receipt.
* @see #setClinicalReport(ClinicalReport)
*/
public ClinicalReport getClinicalReport()
{
return clinicalReport;
}
/**
* Sets the clinical report associated with the participant at the
* time of the SpecimenCollection Group receipt.
* @param clinicalReport the clinical report associated with the participant at the
* time of the SpecimenCollection Group receipt.
* @see #getClinicalReport()
*/
public void setClinicalReport(ClinicalReport clinicalReport)
{
this.clinicalReport = clinicalReport;
}
/**
* Returns the collection Specimens in this SpecimenCollectionGroup.
* @hibernate.set name="specimenCollection" table="CATISSUE_SPECIMEN"
* cascade="save-update" inverse="true" lazy="false"
* @hibernate.collection-key column="SPECIMEN_COLLECTION_GROUP_ID"
* @hibernate.collection-one-to-many class="edu.wustl.catissuecore.domain.Specimen"
* @return the collection Specimens in this SpecimenCollectionGroup.
* @see #setSpecimenCollection(Collection)
*/
public Collection getSpecimenCollection()
{
return specimenCollection;
}
/**
* Sets the collection Specimens in this SpecimenCollectionGroup.
* @param specimenCollection the collection Specimens in this SpecimenCollectionGroup.
* @see #getSpecimenCollection()
*/
public void setSpecimenCollection(Collection specimenCollection)
{
this.specimenCollection = specimenCollection;
}
/**
* Returns the registration of a Participant to a Collection Protocol.
* @hibernate.many-to-one column="COLLECTION_PROTOCOL_REGISTRATION_ID"
* class="edu.wustl.catissuecore.domain.CollectionProtocolRegistration" constrained="true"
* @return the registration of a Participant to a Collection Protocol.
* @see #setCollectionProtocolRegistration(CollectionProtocolRegistration)
*/
public CollectionProtocolRegistration getCollectionProtocolRegistration()
{
return collectionProtocolRegistration;
}
/**
* Sets the registration of a Participant to a Collection Protocol.
* @param collectionProtocolRegistration the registration of a Participant
* to a Collection Protocol.
* @see #getCollectionProtocolRegistration()
*/
public void setCollectionProtocolRegistration(
CollectionProtocolRegistration collectionProtocolRegistration)
{
this.collectionProtocolRegistration = collectionProtocolRegistration;
}
/* (non-Javadoc)
* @see edu.wustl.catissuecore.domain.AbstractDomainObject#setAllValues(edu.wustl.catissuecore.actionForm.AbstractActionForm)
*/
public void setAllValues(AbstractActionForm abstractForm) {
SpecimenCollectionGroupForm form = (SpecimenCollectionGroupForm)abstractForm;
try
{
System.out.println("Inside SEtallValues method....");
this.systemIdentifier = new Long(form.getSystemIdentifier());
this.setClinicalDiagnosis(form.getClinicalDiagnosis());
this.setClinicalStatus(form.getClinicalStatus());
this.setActivityStatus(form.getActivityStatus());
clinicalReport = new ClinicalReport();
clinicalReport.setSurgicalPathologyNumber(form.getSurgicalPathologyNumber());
ParticipantMedicalIdentifier participantMedicalIdentifier = new ParticipantMedicalIdentifier();
participantMedicalIdentifier.setSystemIdentifier(new Long(form.getParticipantsMedicalIdentifierId()));
clinicalReport.setParticipantMedicalIdentifier(participantMedicalIdentifier);
site = new Site();
site.setSystemIdentifier(new Long(form.getSiteId()));
collectionProtocolEvent= new CollectionProtocolEvent();
collectionProtocolEvent.setSystemIdentifier(new Long(form.getCollectionProtocolEventId()));
collectionProtocolRegistration = new CollectionProtocolRegistration();
if(form.getCheckedButton() == 1){ //value of radio button is 2 when participant name is selected
Participant participant = new Participant();
participant.setSystemIdentifier(new Long(form.getParticipantId()));
collectionProtocolRegistration.setParticipant(participant);
System.out.println("INSIDE IF PART (PARTICIPANTNAME)");
}else{
collectionProtocolRegistration.setProtocolParticipantIdentifier(form.getProtocolParticipantIdentifier());
System.out.println("INSIDE ELSE PART (PARTICIPANTNUMBER)");
}
CollectionProtocol collectionProtocol = new CollectionProtocol();
collectionProtocol.setSystemIdentifier(new Long(form.getCollectionProtocolId()));
collectionProtocolRegistration.setCollectionProtocol(collectionProtocol);
System.out.println("<<<<<END OF SETALLVALUES METHOD>>>");
}
catch(Exception e)
{
Logger.out.error(e.getMessage());
e.printStackTrace();
}
}
}
|
package com.pintersudoplz.rnbugsnag;
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableNativeArray;
import com.facebook.react.bridge.Promise;
//BUGSNAG ANDROID API HERE : http://docs.bugsnag.com/platforms/android/#installation
import com.bugsnag.android.Bugsnag;
import com.bugsnag.android.MetaData;
import com.bugsnag.android.Severity;
class RNBugsnagModule extends ReactContextBaseJavaModule {
private Context context;
public RNBugsnagModule(ReactApplicationContext reactContext) {
super(reactContext);
this.context = reactContext;
Bugsnag.init(reactContext);
}
/**
* @return the name of this module. This will be the name used to {@code require()} this module
* from javascript.
*/
@Override
public String getName() {
return "RNBugsnag";
}
@ReactMethod
public void setIdentifier(String userId, String email, String fullName, Promise promise) {
//This gets called whenever setIdentifier is invoked from javascript
Bugsnag.setUser(userId, email, fullName);
promise.resolve("Done!");
}
@ReactMethod
public void reportException(String errorMessage, ReadableArray stacktrace, Integer exceptionId, ReadableMap otherData, Boolean isFatal, Promise promise) {
//This gets called whenever a js error gets thrown
// ArrayList<Object> stack = ((ReadableNativeArray ) stacktrace).toArrayList();
Error error = new Error(errorMessage);
error.setStackTrace(stackTraceToStackTraceElement(stacktrace));
MetaData metaData = new MetaData();
metaData.addToTab("Custom", "exceptionId", exceptionId);
if(isFatal){
Bugsnag.notify(error, Severity.ERROR, metaData);
}else{
Bugsnag.notify(error, Severity.WARNING, metaData);
}
promise.resolve("Done!");
}
private StackTraceElement[] stackTraceToStackTraceElement(ReadableArray stack) {
StackTraceElement[] stackTraceElements = new StackTraceElement[stack.size()];
for (int i = 0; i < stack.size(); i++) {
ReadableMap frame = stack.getMap(i);
stackTraceElements[i] = new StackTraceElement(
"ReactJS",
frame.getString("methodName"),
new File(frame.getString("file")).getName(),
frame.getInt("lineNumber")
);
}
return stackTraceElements;
}
// private String stackTraceToString(ReadableArray stack) {
// StringBuilder stringBuilder = new StringBuilder();
// for (int i = 0; i < stack.size(); i++) {
// ReadableMap frame = stack.getMap(i);
// stringBuilder.append(frame.getString("methodName"));
// stringBuilder.append("\n ");
// stringBuilder.append(new File(frame.getString("file")).getName());
// stringBuilder.append(":");
// stringBuilder.append(frame.getInt("lineNumber"));
// if (frame.hasKey("column") && !frame.isNull("column")) {
// stringBuilder
// .append(":")
// .append(frame.getInt("column"));
// stringBuilder.append("\n");
// return stringBuilder.toString();
// private StackTraceElement[] stackTraceToStackTraceElement(ArrayList<Object> stack) {
// StackTraceElement[] stackTraceElements = new StackTraceElement[stack.size()];
// for (int i = 0; i < stack.size(); i++) {
// HashMap<String, Object> frame = (HashMap<String, Object>) stack.get(i);
// stackTraceElements[i] = new StackTraceElement(
// "ReactJS",
// (String) frame.get("methodName"),
// new File((String) frame.get("file")).getName(),
// (Integer) ((Double) frame.get("lineNumber")).intValue()
// return stackTraceElements;
// private String stackTraceToString(ArrayList<Object> stack) {
// StringBuilder stringBuilder = new StringBuilder();
// for (int i = 0; i < stack.size(); i++) {
// HashMap<String, Object> frame = (HashMap<String, Object>) stack.get(i);
// stringBuilder.append((String) frame.get("methodName"));
// stringBuilder.append("\n ");
// stringBuilder.append(new File((String) frame.get("file")).getName());
// stringBuilder.append(":");
// stringBuilder.append( (Integer) ((Double) frame.get("lineNumber")).intValue());
// if (frame.containsKey("column") && frame.get("column")!=null) {
// stringBuilder
// .append(":")
// .append((Integer) ((Double) frame.get("column")).intValue());
// stringBuilder.append("\n");
// return stringBuilder.toString();
}
|
package org.appcelerator.titanium.kroll;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.appcelerator.kroll.KrollEvaluator;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.TiMessageQueue;
import org.appcelerator.titanium.TiScriptRunner;
import org.appcelerator.titanium.io.TiBaseFile;
import org.appcelerator.titanium.io.TiFileFactory;
import org.appcelerator.titanium.util.AsyncResult;
import org.appcelerator.titanium.util.Log;
import org.appcelerator.titanium.util.TiConfig;
import org.appcelerator.titanium.util.TiFileHelper2;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.EcmaError;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.commonjs.module.ModuleScript;
import org.mozilla.javascript.commonjs.module.ModuleScriptProvider;
import org.mozilla.javascript.commonjs.module.Require;
import org.mozilla.javascript.commonjs.module.RequireBuilder;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
public class KrollContext implements Handler.Callback, ModuleScriptProvider
{
private static final String LCAT = "KrollContext";
private static boolean DBG = TiConfig.DEBUG;
private static final int MSG_EVAL_STRING = 1000;
private static final int MSG_EVAL_FILE = 1001;
private static final String STRING_SOURCE = "<anonymous>";
public static final String CONTEXT_KEY = "krollContext";
private static AtomicInteger instanceCounter;
private static KrollEvaluator defaultEvaluator = new DefaultEvaluator();
private static KrollEvaluator evaluator = defaultEvaluator;
private static KrollThreadListener threadListener;
private KrollHandlerThread thread;
private Require commonJsRequire;
private TiContext tiContext;
private ScriptableObject jsScope;
private String sourceUrl;
private int krollThreadId;
private CountDownLatch initialized;
private TiMessageQueue messageQueue;
private boolean useOptimization;
protected KrollContext(TiContext tiContext, String sourceUrl)
{
this.tiContext = tiContext;
this.sourceUrl = sourceUrl;
this.krollThreadId = getInstanceCounter().incrementAndGet();
StringBuilder threadName = new StringBuilder();
threadName.append("kroll$").append(krollThreadId);
if (sourceUrl != null) {
threadName.append(": ").append(sourceUrl);
}
// allow a configurable stack size to avoid StackOverflowErrors in some larger apps
thread = new KrollHandlerThread(
threadName.toString(),
Process.THREAD_PRIORITY_DEFAULT,
tiContext.getTiApp().getThreadStackSize(), this);
initialized = new CountDownLatch(1);
// force to true to test compiled JS
// this.useOptimization = true;
TiApplication app = tiContext.getTiApp();
this.useOptimization =
app.getDeployType() == TiApplication.DEPLOY_TYPE_PRODUCTION || app.forceCompileJS();
thread.start();
requireInitialized();
}
public static final class DefaultEvaluator implements KrollEvaluator
{
@Override
public Object evaluateFile(Context context, Scriptable scope,
TiBaseFile file, String filename, int lineNo, Object securityDomain)
{
BufferedReader br = null;
Object result = Scriptable.NOT_FOUND;
try {
br = new BufferedReader(new InputStreamReader(file.getInputStream()), 4000);
Log.d(LCAT, "Running evaluated script: " + filename);
result = context.evaluateReader(scope, br, filename, 1, null);
} catch (IOException e) {
Log.e(LCAT, "IOException reading file: " + filename, e);
Context.throwAsScriptRuntimeEx(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
@Override
public Object evaluateString(Context context, Scriptable scope,
String src, String sourceName, int lineNo, Object securityDomain)
{
return context.evaluateString(scope, src, sourceName, lineNo, securityDomain);
}
@Override
public void handleEcmaError(EcmaError error)
{
Log.e(LCAT, "ECMA Error evaluating source: " + error.getMessage(), error);
Context.reportRuntimeError(error.getMessage(), error.sourceName(),
error.lineNumber(), error.lineSource(), error.columnNumber());
}
@Override
public void handleEvaluatorException(EvaluatorException ex)
{
Log.e(LCAT, "Error evaluating source: " + ex.getMessage(), ex);
Context.reportRuntimeError(ex.getMessage(), ex.sourceName(),
ex.lineNumber(), ex.lineSource(), ex.columnNumber());
}
@Override
public void handleException(Exception ex)
{
Log.e(LCAT, "Error: " + ex.getMessage(), ex);
Context.throwAsScriptRuntimeEx(ex);
}
}
public static KrollEvaluator getDefaultKrollEvaluator()
{
return defaultEvaluator;
}
public static KrollEvaluator getKrollEvaluator()
{
return evaluator;
}
public static void setKrollEvaluator(KrollEvaluator e)
{
evaluator = e;
}
public static void setThreadListener(KrollThreadListener l)
{
threadListener = l;
}
protected void initContext()
{
if (DBG) {
Log.d(LCAT, "Context Thread: " + Thread.currentThread().getName());
}
if (threadListener != null) {
threadListener.threadStarted(thread);
}
messageQueue = TiMessageQueue.getMessageQueue();
messageQueue.setCallback(this);
Context ctx = enter();
try {
if (DBG) {
Log.d(LCAT, "Context entered, preparing scope");
}
this.jsScope = ctx.initStandardObjects();
if (DBG) {
Log.d(LCAT, "Initialized scope: " + jsScope);
}
this.commonJsRequire = buildCommonJsRequire(ctx);
if (DBG) {
Log.d(LCAT, "Initialized commonJS require() function: " + this.commonJsRequire);
}
initialized.countDown();
} finally {
exit();
}
}
private Require buildCommonJsRequire(Context ctx)
{
RequireBuilder builder = new RequireBuilder();
builder.setModuleScriptProvider(this);
return builder.createRequire(ctx, jsScope);
}
@Override
public ModuleScript getModuleScript(Context context, String moduleId,
Scriptable paths) throws Exception
{
Script script = null;
String uri;
StringBuilder sb = new StringBuilder();
sb.append(TiC.URL_APP_PREFIX)
.append(moduleId)
.append(".js");
uri = sb.toString();
if (useOptimization) {
// get Script from compiled script class
script = TiScriptRunner.getInstance()
.getScript(context, jsScope, moduleId);
if (script == null) {
Log.e(LCAT, "Could not retrieve a Script object for module '" + moduleId + "'.");
Context.throwAsScriptRuntimeEx(new Exception("Unable to load Script for module '" + moduleId + "'."));
}
} else {
// make Script from JS source
TiBaseFile file = TiFileFactory.createTitaniumFile(tiContext, new String[] { uri }, false);
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(file.getInputStream()), 4000);
script = context.compileReader(br, uri, 1, null);
} catch (IOException e) {
Log.e(LCAT, "IOException reading module file: " + uri, e);
Context.throwAsScriptRuntimeEx(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// Ignore
}
}
}
}
return new ModuleScript(script, uri);
}
public Object callCommonJsRequire(String path)
{
Context ctx = enter();
try {
return commonJsRequire.call(ctx, jsScope, jsScope, new String[] { path });
} finally {
exit();
}
}
protected void threadEnded()
{
if (threadListener != null) {
threadListener.threadEnded(thread);
}
}
public boolean handleMessage(Message msg)
{
switch(msg.what)
{
case MSG_EVAL_STRING : {
AsyncResult result = (AsyncResult) msg.obj;
String src = msg.getData().getString(TiC.MSG_PROPERTY_SRC);
result.setResult(handleEval(src));
return true;
}
case MSG_EVAL_FILE : {
AsyncResult result = (AsyncResult) msg.obj;
String filename = msg.getData().getString(TiC.MSG_PROPERTY_FILENAME);
result.setResult(handleEvalFile(filename));
return true;
}
}
return false;
}
public void post(Runnable r)
{
messageQueue.post(r);
//contextHandler.post(r);
}
protected boolean isOurThread()
{
if (DBG) {
Log.d(LCAT, "ThreadId: " + thread.getId() + " currentThreadId: " + Thread.currentThread().getId());
}
return thread.getId() == Thread.currentThread().getId();
}
public KrollHandlerThread getThread()
{
return thread;
}
public TiContext getTiContext()
{
return tiContext;
}
public String getSourceUrl()
{
return sourceUrl;
}
public int getKrollThreadId()
{
return krollThreadId;
}
public Scriptable getScope()
{
requireInitialized();
return jsScope;
}
public Object evalFile(String filename)
{
if (DBG) {
Log.i(LCAT, "evalFile: " + filename);
}
if (isOurThread()) {
return handleEvalFile(filename);
}
AsyncResult result = new AsyncResult();
Message msg = messageQueue.getHandler().obtainMessage(MSG_EVAL_FILE, result);
msg.getData().putString(TiC.MSG_PROPERTY_FILENAME, filename);
return TiMessageQueue.getMessageQueue().sendBlockingMessage(msg, messageQueue, result);
}
protected Object runCompiledScript(String filename)
{
String relativePath = TiFileHelper2.getResourceRelativePath(filename);
if (relativePath == null) {
// we can only handle pre-compiled app:// and file:///android_asset/Resources/ scripts here
return evaluateScript(filename);
}
Context context = enter(true);
try {
Log.d(LCAT, "Running pre-compiled script: " + relativePath);
return TiScriptRunner.getInstance().runScript(context, jsScope, relativePath);
} catch (ClassNotFoundException e) {
Log.e(LCAT, "Couldn't find pre-compiled class for script: " + relativePath, e);
} finally {
exit();
}
return ScriptableObject.NOT_FOUND;
}
public Object evaluateScript(String filename)
{
String[] parts = { filename };
TiBaseFile tbf = TiFileFactory.createTitaniumFile(tiContext, parts, false);
Context context = enter(false);
return evaluator.evaluateFile(context, jsScope, tbf, filename, 1, null);
}
public Object handleEvalFile(String filename)
{
requireInitialized();
Object result = null;
try {
if (useOptimization) {
result = runCompiledScript(filename);
} else {
result = evaluateScript(filename);
}
} catch (EcmaError e) {
evaluator.handleEcmaError(e);
} catch (EvaluatorException e) {
evaluator.handleEvaluatorException(e);
} catch (Exception e) {
evaluator.handleException(e);
}
return result;
}
public Object eval(String src)
{
if (isOurThread()) {
return handleEval(src);
}
AsyncResult result = new AsyncResult();
Message msg = messageQueue.getHandler().obtainMessage(MSG_EVAL_STRING, result);
msg.getData().putString(TiC.MSG_PROPERTY_SRC, src);
return TiMessageQueue.getMessageQueue().sendBlockingMessage(msg, messageQueue, result);
}
public Object handleEval(String src)
{
requireInitialized();
Object result = null;
Context ctx = enter(false);
try {
result = evaluator.evaluateString(ctx, jsScope, src, STRING_SOURCE, 1, null);
} catch (EcmaError e) {
evaluator.handleEcmaError(e);
} catch (EvaluatorException e) {
evaluator.handleEvaluatorException(e);
} catch (Exception e) {
evaluator.handleException(e);
} finally {
exit();
}
return result;
}
public InputStream getResourcesInputStream(String filename)
throws IOException
{
InputStream is = null;
Activity activity = tiContext.getActivity();
if (activity != null) {
is = activity.getAssets().open(TiFileHelper2.getResourcesPath(filename));
}
return is;
}
public void put(String name, Scriptable object)
{
jsScope.put(name, jsScope, object);
}
public Context enter()
{
return enter(this.useOptimization);
}
public Context enter(boolean useOptimization)
{
Context ctx = Context.enter();
if (!useOptimization) {
ctx.setOptimizationLevel(-1);
}
ctx.setErrorReporter(getTiContext());
ctx.putThreadLocal(CONTEXT_KEY, this);
return ctx;
}
public void exit()
{
Context.exit();
}
public static KrollContext getKrollContext(Context context)
{
return (KrollContext) context.getThreadLocal(CONTEXT_KEY);
}
public static KrollContext getCurrentKrollContext()
{
Context ctx = Context.getCurrentContext();
if (ctx == null) {
return null;
}
return getKrollContext(ctx);
}
private void requireInitialized()
{
try {
initialized.await();
} catch (InterruptedException e) {
// Ignore
}
}
protected static AtomicInteger getInstanceCounter()
{
if (instanceCounter == null) {
instanceCounter = new AtomicInteger();
}
return instanceCounter;
}
public static final KrollContext createContext(TiContext tiContext, String loadFile)
{
return new KrollContext(tiContext, loadFile);
}
public TiMessageQueue getMessageQueue()
{
return messageQueue;
}
public void release()
{
if (thread.getLooper() != null) {
thread.getLooper().quit();
}
}
}
|
package server.ui;
import com.jme3.app.SimpleApplication;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Quad;
import com.jme3.shadow.DirectionalLightShadowFilter;
import com.jme3.shadow.DirectionalLightShadowRenderer;
import com.jme3.system.AppSettings;
import com.jme3.util.SkyFactory;
import jme3tools.optimize.GeometryBatchFactory;
import server.model.Cell;
import server.model.WorldManager;
import java.util.Observer;
import java.util.Set;
public class VisualGUI extends SimpleApplication {
private static final float SCALE = 0.2f;
private static final double MIN_DELAY = 0.01;
private Node cellsNode;
private double delay;
//which dimensions are rendered
private static int xdim;
private static int ydim;
private static int zdim;
private boolean isPaused = false;
private Geometry floor;
public static void main(String[] args) {
VisualGUI app = new VisualGUI();
AppSettings settings = new AppSettings(true);
settings.setStereo3D(false);
app.setSettings(settings);
xdim = 0;
ydim = 1;
zdim = 2;
app.start();
}
@Override
public void simpleInitApp() {
delay = 0;
flyCam.setMoveSpeed(10);
addSkySphere();
addCells();
addFloor();
addShadows();
addEventHandlers();
}
private void addSkySphere() {
getRootNode().attachChild(SkyFactory.createSky(getAssetManager(),
"assets/Textures/Skysphere.jpg", SkyFactory.EnvMapType.SphereMap));
}
private void addEventHandlers() {
inputManager.addMapping("PAUSE", new KeyTrigger(KeyInput.KEY_SPACE));
inputManager.addMapping("PREVDIM", new KeyTrigger(KeyInput.KEY_MINUS));
inputManager.addMapping("NEXTDIM", new KeyTrigger(KeyInput.KEY_EQUALS));
inputManager.addListener(pauseActionListener, "PAUSE");
inputManager.addListener(prevDimActionListener, "PREVDIM");
inputManager.addListener(nextDimActionListener, "NEXTDIM");
}
private void addCells() {
cellsNode = new Node();
cellsNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive);
rootNode.setShadowMode(RenderQueue.ShadowMode.Off);
rootNode.attachChild(cellsNode);
Set<Cell> cells = WorldManager.getInstance().getRule().getCells();
for (Cell cell : cells) {
Box b = new Box(0.1f, 0.1f, 0.1f);
Spatial node = new Geometry("Box", b);
node.setShadowMode(RenderQueue.ShadowMode.CastAndReceive);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
node.setMaterial(mat);
node.setLocalTranslation(
cell.getPosition().getComponent(xdim) * SCALE,
cell.getPosition().getComponent(ydim) * SCALE,
cell.getPosition().getComponent(zdim) * SCALE);
cellsNode.attachChild(node);
}
GeometryBatchFactory.optimize(cellsNode);
}
private void addShadows() {
DirectionalLight sun = new DirectionalLight();
sun.setColor(ColorRGBA.White);
sun.setDirection(new Vector3f(-.5f,-.5f,-.5f).normalizeLocal());
rootNode.addLight(sun);
/* Drop shadows */
final int SHADOWMAP_SIZE=1024;
DirectionalLightShadowRenderer dlsr = new DirectionalLightShadowRenderer(assetManager, SHADOWMAP_SIZE, 3);
dlsr.setLight(sun);
viewPort.addProcessor(dlsr);
DirectionalLightShadowFilter dlsf = new DirectionalLightShadowFilter(assetManager, SHADOWMAP_SIZE, 3);
dlsf.setLight(sun);
dlsf.setEnabled(true);
FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
fpp.addFilter(dlsf);
viewPort.addProcessor(fpp);
}
private void addFloor() {
floor = new Geometry("Box", new Quad(2000, 2000));
Material unshaded = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
unshaded.setColor("Color", ColorRGBA.White);
floor.setMaterial(unshaded);
floor.setShadowMode(RenderQueue.ShadowMode.Receive);
Quaternion q = new Quaternion();
floor.setLocalRotation(q.fromAngleAxis(-FastMath.PI / 2, new Vector3f(1, 0, 0)));
floor.setLocalTranslation(-1000, -0.1f, 1000);
rootNode.attachChild(floor);
}
@Override
public void simpleUpdate(float tpf) {
if (!isPaused) {
updateDelay(tpf);
updateCells();
updateFloor();
}
}
private void updateFloor() {
float minimumY = 0; // should be at least at the sea level
for (Cell cell : WorldManager.getInstance().getCells()) {
minimumY = Math.min(minimumY, cell.getPosition().getComponent(ydim) * SCALE);
}
Vector3f floorTranslation = floor.getLocalTranslation();
Vector3f nextFloorTranslation = floorTranslation.setY(minimumY);
floor.setLocalTranslation(nextFloorTranslation);
}
private ActionListener pauseActionListener = (name, pressed, tpf) -> {
if (pressed) {
isPaused = !isPaused;
}
};
private ActionListener prevDimActionListener = new ActionListener(){
public void onAction(String name, boolean pressed, float tpf){
if (pressed) {
int dim = WorldManager.getInstance().dim;
xdim = (xdim - 1+dim) % dim;
ydim = (ydim - 1+dim) % dim;
zdim = (zdim - 1+dim) % dim;
updateCells();
}
}
};
private ActionListener nextDimActionListener = new ActionListener(){
public void onAction(String name, boolean pressed, float tpf){
if (pressed) {
int dim = WorldManager.getInstance().dim;
xdim = (xdim + 1) % dim;
ydim = (ydim + 1) % dim;
zdim = (zdim + 1) % dim;
updateCells();
}
}
};
private void updateDelay(float tpf) {
delay += tpf;
if (delay <= MIN_DELAY) {
return;
}
delay = 0;
}
private void updateCells() {
cellsNode.getChildren().clear();
addCells();
GeometryBatchFactory.optimize(cellsNode);
WorldManager.getInstance().getRule().tick();
}
}
|
package ch.epfl.sweng.project;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import ch.epfl.sweng.project.Firebase.FirebaseHelper;
import ch.epfl.sweng.project.Model.Message;
/**
* Test suite for FirebaseHelper, has to be run completely to maintain remote database intact
*/
public class FirebaseHelperTest {
private FirebaseHelper firebaseHelper;
@Before
public void instantiation() {
firebaseHelper = new FirebaseHelper();
}
@Test
public void DBcorrectInstantiationAndRootOrganization() {
firebaseHelper.getDatabase().addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Assert.assertTrue(dataSnapshot.exists());
Assert.assertTrue(dataSnapshot.hasChild("messages"));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Test
public void sendingMessageCorrectlyUpdatesDatabase() {
String to = "you";
Message msg = new Message("me", to, Message.MessageType.TEXT, "Hello, world!");
firebaseHelper.send(msg);
firebaseHelper.getDatabase().child("messages").child(to)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot = dataSnapshot.getChildren().iterator().next();
Assert.assertTrue(dataSnapshot.exists());
Assert.assertTrue(dataSnapshot.hasChild("from"));
Assert.assertTrue(dataSnapshot.hasChild("type"));
Assert.assertTrue(dataSnapshot.hasChild("message"));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Test
public void fetchingMessageCorrectlyReadsDatabase() {
final List<Message> msgs = new ArrayList<>();
firebaseHelper.fetchMessages("you", new FirebaseHelper.Handler() {
@Override
public void handleRetrievedMessages(List<Message> messages) {
for (Message m : messages) {
msgs.add(m);
}
Assert.assertFalse(msgs.isEmpty());
}
});
}
@Test
public void deletingMessageCorrectlyReadsDatabase() {
final List<Message> msgs = new ArrayList<>();
firebaseHelper.fetchMessages("you", new FirebaseHelper.Handler() {
@Override
public void handleRetrievedMessages(List<Message> messages1) {
Assert.assertFalse(messages1.isEmpty());
final String messageUid = messages1.get(0).getUid();
firebaseHelper.delete(messages1.get(0));
firebaseHelper.fetchMessages("you", new FirebaseHelper.Handler() {
@Override
public void handleRetrievedMessages(List<Message> messages2) {
for (Message m : messages2) {
Assert.assertFalse(m.getUid().equals(messageUid));
}
}
});
}
});
}
}
|
package com.afwsamples.testdpc;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.CrossProfileApps;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.UserHandle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.afwsamples.testdpc.common.ReflectionUtil;
import java.util.List;
// TODO: Replace it with P.
@TargetApi(28)
public class CrossProfileAppsFragment extends Fragment {
private static final String TAG = "CrossProfileAppsFragmen";
private View mInflatedView;
private TextView mSwitchProfileTextView;
private TextView mDescriptionTextView;
private ImageView mSwitchProfileImageView;
private Object mCrossProfileApps;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflatedView = inflater.inflate(R.layout.cross_profile_apps, container, false);
mSwitchProfileTextView = mInflatedView.findViewById(R.id.cross_profile_app_label);
mSwitchProfileImageView = mInflatedView.findViewById(R.id.cross_profile_app_icon);
mDescriptionTextView = mInflatedView.findViewById(R.id.cross_profile_app_description);
return mInflatedView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mCrossProfileApps = getActivity().getSystemService(Context.CROSS_PROFILE_APPS_SERVICE);
}
@Override
public void onResume() {
super.onResume();
refreshUi();
}
private void refreshUi() {
try {
List<UserHandle> targetUserProfiles =
(List<UserHandle>) ReflectionUtil.invoke(
mCrossProfileApps,
"getTargetUserProfiles");
if (targetUserProfiles.isEmpty()) {
showNoTargetUserUi();
} else {
showHasTargetUserUi(targetUserProfiles.get(0));
}
} catch (ReflectionUtil.ReflectionIsTemporaryException ex) {
Log.e(TAG, "Failed to call CrossProfileApps API: ", ex);
}
}
private void showNoTargetUserUi() {
mDescriptionTextView.setText(R.string.cross_profile_apps_not_available);
mSwitchProfileTextView.setText("");
mSwitchProfileImageView.setImageDrawable(null);
mSwitchProfileImageView.setOnClickListener(null);
}
private void showHasTargetUserUi(UserHandle userHandle)
throws ReflectionUtil.ReflectionIsTemporaryException {
mSwitchProfileTextView.setText((String)
ReflectionUtil.invoke(
mCrossProfileApps, "getProfileSwitchingLabel", userHandle));
mSwitchProfileImageView.setImageDrawable((Drawable) ReflectionUtil.invoke(
mCrossProfileApps, "getProfileSwitchingIconDrawable", userHandle));
mDescriptionTextView.setText(R.string.cross_profile_apps_available);
mSwitchProfileImageView.setOnClickListener(
view -> {
try {
ReflectionUtil.invoke(
mCrossProfileApps, "startMainActivity",
new ComponentName(getActivity(), PolicyManagementActivity.class),
userHandle);
} catch (ReflectionUtil.ReflectionIsTemporaryException e) {
e.printStackTrace();
}
});
}
}
|
package com.dlsu.getbetter.getbetter.objects;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class CaseRecord {
@SerializedName("record_status_id")
private int caseRecordStatusId;
@SerializedName("user_id")
private int userId;
@SerializedName("health_center_id")
private int healthCenterId;
@SerializedName("complaint")
private String caseRecordComplaint;
@SerializedName("additional_notes")
private String caseRecordAdditionalNotes;
@SerializedName("control_number")
private String caseRecordControlNumber;
@SerializedName("updated_on")
private String caseRecordUpdatedOn;
@SerializedName("updated_by")
private int caseRecordUpdatedBy;
@SerializedName("case_record_id")
private int caseRecordId;
private int caseId;
private String caseRecordStatus;
private String healthCenter;
private String patientName;
private String profilePic;
private ArrayList<Attachment> attachments;
private boolean checked = false;
public CaseRecord() {
}
//constructor for getCaseRecordHistory db query function
public CaseRecord(int caseRecordId, int caseRecordStatusId, int caseRecordUpdatedBy, String caseRecordUpdatedOn) {
this.caseRecordId = caseRecordId;
this.caseRecordStatusId = caseRecordStatusId;
this.caseRecordUpdatedBy = caseRecordUpdatedBy;
this.caseRecordUpdatedOn = caseRecordUpdatedOn;
}
public CaseRecord(int caseRecordId, String caseRecordComplaint, String caseRecordUpdatedOn, int caseRecordStatusId) {
this.caseRecordId = caseRecordId;
this.caseRecordComplaint = caseRecordComplaint;
this.caseRecordUpdatedOn = caseRecordUpdatedOn;
this.caseRecordStatusId = caseRecordStatusId;
}
public CaseRecord(int caseRecordId, String patientName, String caseRecordControlNumber,
String caseRecordComplaint, String caseRecordAdditionalNotes,
String healthCenter, String caseRecordStatus, String caseRecordUpdatedOn) {
this.caseRecordId = caseRecordId;
this.patientName = patientName;
this.caseRecordControlNumber = caseRecordControlNumber;
this.caseRecordComplaint = caseRecordComplaint;
this.caseRecordAdditionalNotes = caseRecordAdditionalNotes;
this.healthCenter = healthCenter;
this.caseRecordStatus = caseRecordStatus;
this.caseRecordUpdatedOn = caseRecordUpdatedOn;
}
public CaseRecord(int caseRecordId, int userId, String caseRecordComplaint, String caseRecordUpdatedOn) {
this.caseRecordId = caseRecordId;
this.userId = userId;
this.caseRecordComplaint = caseRecordComplaint;
this.caseRecordUpdatedOn = caseRecordUpdatedOn;
}
public CaseRecord(int caseRecordId, String complaint, int userId, String caseRecordControlNumber, String caseRecordAdditionalNotes) {
this.caseRecordId = caseRecordId;
this.caseRecordComplaint = complaint;
this.userId = userId;
this.caseRecordControlNumber = caseRecordControlNumber;
this.caseRecordAdditionalNotes = caseRecordAdditionalNotes;
}
public CaseRecord(int caseRecordId, int caseId, int userId, int caseRecordStatusId, String caseRecordComplaint,
String caseRecordAdditionalNotes, String caseRecordControlNumber, String caseRecordUpdatedOn) {
this.caseRecordId = caseRecordId;
this.caseId = caseId;
this.userId = userId;
this.caseRecordStatusId = caseRecordStatusId;
this.caseRecordComplaint = caseRecordComplaint;
this.caseRecordAdditionalNotes = caseRecordAdditionalNotes;
this.caseRecordControlNumber = caseRecordControlNumber;
this.caseRecordUpdatedOn = caseRecordUpdatedOn;
}
public int getHealthCenterId() {
return healthCenterId;
}
public void setHealthCenterId(int healthCenterId) {
this.healthCenterId = healthCenterId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public void setCaseRecordStatus(String caseRecordStatus) {
this.caseRecordStatus = caseRecordStatus;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public void setCaseRecordId(int caseRecordId) {
this.caseRecordId = caseRecordId;
}
public int getCaseRecordStatusId() {
return caseRecordStatusId;
}
public int getCaseId() {
return caseId;
}
public void setCaseId(int caseId) {
this.caseId = caseId;
}
public void setCaseRecordStatusId(int caseRecordStatusId) {
this.caseRecordStatusId = caseRecordStatusId;
}
public void setCaseRecordComplaint(String caseRecordComplaint) {
this.caseRecordComplaint = caseRecordComplaint;
}
public void setCaseRecordControlNumber(String caseRecordControlNumber) {
this.caseRecordControlNumber = caseRecordControlNumber;
}
public String getCaseRecordUpdatedOn() {
return caseRecordUpdatedOn;
}
public void setCaseRecordUpdatedOn(String caseRecordUpdatedOn) {
this.caseRecordUpdatedOn = caseRecordUpdatedOn;
}
public int getCaseRecordUpdatedBy() {
return caseRecordUpdatedBy;
}
public void setCaseRecordUpdatedBy(int caseRecordUpdatedBy) {
this.caseRecordUpdatedBy = caseRecordUpdatedBy;
}
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getHealthCenter() {
return healthCenter;
}
public void setHealthCenter(String healthCenter) {
this.healthCenter = healthCenter;
}
public int getCaseRecordId() {
return caseRecordId;
}
public String getCaseRecordComplaint() {
return caseRecordComplaint;
}
public String getCaseRecordControlNumber() {
return caseRecordControlNumber;
}
public String getCaseRecordStatus() {
return caseRecordStatus;
}
public String getCaseRecordAdditionalNotes() {
return caseRecordAdditionalNotes;
}
public void setCaseRecordAdditionalNotes(String caseRecordAdditionalNotes) {
this.caseRecordAdditionalNotes = caseRecordAdditionalNotes;
}
public ArrayList<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<Attachment> attachments) {
this.attachments = attachments;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public void toggleChecked() {
checked = !checked;
}
}
|
package com.mikepenz.unsplash.activities;
import android.animation.Animator;
import android.annotation.TargetApi;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.transition.Transition;
import android.util.Log;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.lzyzsd.circleprogress.DonutProgress;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.ProgressCallback;
import com.koushikdutta.ion.Response;
import com.koushikdutta.ion.future.ResponseFuture;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.typeface.FontAwesome;
import com.mikepenz.unsplash.R;
import com.mikepenz.unsplash.fragments.ImagesFragment;
import com.mikepenz.unsplash.models.Image;
import com.mikepenz.unsplash.other.CustomAnimatorListener;
import com.mikepenz.unsplash.other.CustomTransitionListener;
import com.mikepenz.unsplash.views.Utils;
import java.io.File;
import java.io.InputStream;
public class DetailActivity extends ActionBarActivity {
private static final int ACTIVITY_CROP = 13451;
private static final int ANIMATION_DURATION_MEDIUM = 400;
private static final int ANIMATION_DURATION_LONG = 750;
private static final int ANIMATION_DURATION_EXTRA_LONG = 1000;
private ImageView mFabButton;
private DonutProgress mFabProgress;
private View mTitleContainer;
private View mTitlesContainer;
private Image mSelectedImage;
private Drawable mDrawablePhoto;
private Drawable mDrawableClose;
private Drawable mDrawableSuccess;
private ResponseFuture<InputStream> future = null;
private int mWallpaperWidth;
private int mWallpaperHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
findViewById(R.id.container).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
//get the desired wallpaper size so older phones won't die :D
mWallpaperWidth = WallpaperManager.getInstance(DetailActivity.this).getDesiredMinimumWidth();
mWallpaperHeight = WallpaperManager.getInstance(DetailActivity.this).getDesiredMinimumHeight();
// Recover items from the intent
final int position = getIntent().getIntExtra("position", 0);
mSelectedImage = (Image) getIntent().getSerializableExtra("selected_image");
mDrawablePhoto = new IconicsDrawable(this, FontAwesome.Icon.faw_photo).color(Color.WHITE).sizeDp(24);
mDrawableClose = new IconicsDrawable(this, FontAwesome.Icon.faw_close).color(Color.WHITE).sizeDp(24);
mDrawableSuccess = new IconicsDrawable(this, FontAwesome.Icon.faw_check).color(Color.WHITE).sizeDp(24);
mTitlesContainer = findViewById(R.id.activity_detail_titles);
// Fab progress
mFabProgress = (DonutProgress) findViewById(R.id.activity_detail_progress);
mFabProgress.setMax(100);
mFabProgress.setScaleX(0);
mFabProgress.setScaleY(0);
// Fab button
mFabButton = (ImageView) findViewById(R.id.activity_detail_fab);
mFabButton.setScaleX(0);
mFabButton.setScaleY(0);
mFabButton.setImageDrawable(mDrawablePhoto);
mFabButton.setOnClickListener(onFabButtonListener);
//just allow the longClickAction on Devices newer than api level v19
if (Build.VERSION.SDK_INT >= 19) {
mFabButton.setOnLongClickListener(onFabButtonLongListener);
}
// Image summary card
FrameLayout contentCard = (FrameLayout) findViewById(R.id.card_view);
Utils.configuredHideYView(contentCard);
// Title container
mTitleContainer = findViewById(R.id.activity_detail_title_container);
Utils.configuredHideYView(mTitleContainer);
// Define toolbar as the shared element
final Toolbar toolbar = (Toolbar) findViewById(R.id.activity_detail_toolbar);
Bitmap imageCoverBitmap = ImagesFragment.photoCache.get(position);
toolbar.setBackground(new BitmapDrawable(getResources(), imageCoverBitmap));
if (Build.VERSION.SDK_INT >= 21) {
toolbar.setTransitionName("cover");
// Add a listener to get noticed when the transition ends to animate the fab button
getWindow().getSharedElementEnterTransition().addListener(sharedTransitionListener);
} else {
Utils.showViewByScale(toolbar).setDuration(ANIMATION_DURATION_LONG).start();
sharedTransitionListener.onTransitionEnd(null);
}
//check if we already had the colors during click
int swatch_title_text_color = getIntent().getIntExtra("swatch_title_text_color", -1);
int swatch_rgb = getIntent().getIntExtra("swatch_rgb", -1);
if (swatch_rgb != -1 && swatch_title_text_color != -1) {
setColors(swatch_title_text_color, swatch_rgb);
} else {
// Generate palette colors
Palette.generateAsync(imageCoverBitmap, paletteListener);
}
}
private View.OnClickListener onFabButtonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (future == null) {
//prepare the call
future = Ion.with(DetailActivity.this)
.load(mSelectedImage.getHighResImage(mWallpaperWidth, mWallpaperHeight))
.progressHandler(progressCallback)
.asInputStream();
animateStart();
mFabButton.animate().rotationBy(360).setDuration(ANIMATION_DURATION_MEDIUM).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
streamAndSetImage();
}
@Override
public void onAnimationCancel(Animator animation) {
streamAndSetImage();
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
} else {
animateReset();
}
}
};
private View.OnLongClickListener onFabButtonLongListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (future == null) {
//prepare the call
future = Ion.with(DetailActivity.this)
.load(mSelectedImage.getHighResImage(mWallpaperWidth, mWallpaperHeight))
.progressHandler(progressCallback)
.asInputStream();
animateStart();
mFabButton.animate().rotationBy(360).setDuration(ANIMATION_DURATION_MEDIUM).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
downloadAndSetImage();
}
@Override
public void onAnimationCancel(Animator animation) {
downloadAndSetImage();
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
} else {
animateReset();
}
return true;
}
};
private ProgressCallback progressCallback = new ProgressCallback() {
@Override
public void onProgress(long downloaded, long total) {
int progress = (int) (downloaded * 100.0 / total);
if (progress < 1) {
progress = progress + 1;
}
mFabProgress.setProgress(progress);
}
};
/**
* download an InputStream of the image and set as Wallpaper
* Animate
*/
private void streamAndSetImage() {
if (future != null) {
//set the callback and start downloading
future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
@Override
public void onCompleted(Exception e, Response<InputStream> result) {
boolean success = false;
if (e == null && result != null && result.getResult() != null) {
try {
WallpaperManager.getInstance(DetailActivity.this).setStream(result.getResult());
//animate the first elements
animateCompleteFirst();
success = true;
} catch (Exception ex) {
Log.e("un:splash", ex.toString());
}
//animate after complete
animateComplete(success);
}
}
});
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void downloadAndSetImage() {
if (future != null) {
//set the callback and start downloading
future.withResponse().setCallback(new FutureCallback<Response<InputStream>>() {
@Override
public void onCompleted(Exception e, Response<InputStream> result) {
boolean success = false;
if (e == null && result != null && result.getResult() != null) {
try {
//create a temporary directory within the cache folder
File dir = new File(DetailActivity.this.getCacheDir() + "/images");
if (!dir.exists()) {
dir.mkdirs();
}
//create the file
File file = new File(dir, "unsplash.jpg");
if (!file.exists()) {
file.createNewFile();
}
//copy the image onto this file
Utils.copyInputStreamToFile(result.getResult(), file);
//get the contentUri for this file and start the intent
Uri contentUri = FileProvider.getUriForFile(DetailActivity.this, "com.mikepenz.fileprovider", file);
Intent intent = WallpaperManager.getInstance(DetailActivity.this).getCropAndSetWallpaperIntent(contentUri);
//start activity for result so we can animate if we finish
DetailActivity.this.startActivityForResult(intent, ACTIVITY_CROP);
success = true;
} catch (Exception ex) {
Log.e("un:splash", ex.toString());
}
}
//animate after complete
animateComplete(success);
}
});
}
}
/**
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_CROP) {
//animate the first elements
animateCompleteFirst();
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* animate the start of the download
*/
private void animateStart() {
//reset progress to prevent jumping
mFabProgress.setProgress(0);
//some nice button animations
Utils.showViewByScale(mFabProgress).setDuration(ANIMATION_DURATION_MEDIUM).start();
mFabProgress.setProgress(1);
mFabButton.setImageDrawable(mDrawableClose);
}
/**
* animate the reset of the view
*/
private void animateReset() {
future.cancel(true);
future = null;
//animating everything back to default :D
Utils.hideViewByScaleXY(mFabProgress).setDuration(ANIMATION_DURATION_MEDIUM).start();
//Utils.animateViewElevation(mFabButton, 0, mElavationPx);
mFabButton.setImageDrawable(mDrawablePhoto);
mFabButton.animate().rotationBy(360).setDuration(ANIMATION_DURATION_MEDIUM).start();
}
/**
* animate the first parts of the UI after the download has successfully finished
*/
private void animateCompleteFirst() {
//some nice animations so the user knows the wallpaper was set properly
mFabButton.animate().rotationBy(720).setDuration(ANIMATION_DURATION_EXTRA_LONG).start();
mFabButton.setImageDrawable(mDrawableSuccess);
//animate the butotn to green. just do it the first time
if (mFabButton.getTag() == null) {
TransitionDrawable transition = (TransitionDrawable) mFabButton.getBackground();
transition.startTransition(ANIMATION_DURATION_LONG);
mFabButton.setTag("");
}
}
/**
* finish the animations of the ui after the download is complete. reset the button to the start
*
* @param success
*/
private void animateComplete(boolean success) {
//hide the progress again :D
Utils.hideViewByScaleXY(mFabProgress).setDuration(ANIMATION_DURATION_MEDIUM).start();
// if we were not successful remove the x again :D
if (!success) {
//Utils.animateViewElevation(mFabButton, 0, mElavationPx);
mFabButton.setImageDrawable(mDrawablePhoto);
mFabButton.animate().rotationBy(360).setDuration(ANIMATION_DURATION_MEDIUM).start();
}
future = null;
}
/**
* I use a listener to get notified when the enter transition ends, and with that notifications
* build my own choreography built with the elements of the UI
* <p/>
* Animations order
* <p/>
* 1. The image is animated automatically by the SharedElementTransition
* 2. The layout that contains the titles
* 3. An alpha transition to show the text of the titles
* 3. A scale animation to show the image info
*/
private CustomTransitionListener sharedTransitionListener = new CustomTransitionListener() {
@Override
public void onTransitionEnd(Transition transition) {
super.onTransitionEnd(transition);
ViewPropertyAnimator showTitleAnimator = Utils.showViewByScale(mTitleContainer);
showTitleAnimator.setListener(new CustomAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mTitlesContainer.startAnimation(AnimationUtils.loadAnimation(DetailActivity.this, R.anim.alpha_on));
mTitlesContainer.setVisibility(View.VISIBLE);
Utils.showViewByScale(mFabButton).start();
//Utils.showViewByScale(imageInfoLayout).start();
}
});
showTitleAnimator.start();
}
};
/**
* @param titleTextColor
* @param rgb
*/
private void setColors(int titleTextColor, int rgb) {
mTitleContainer.setBackgroundColor(rgb);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(titleTextColor);
}
//getWindow().setNavigationBarColor(vibrantSwatch.getRgb());
//TextView summaryTitle = (TextView) findViewById(R.id.activity_detail_summary_title);
//summaryTitle.setTextColor(vibrantSwatch.getRgb());
TextView titleTV = (TextView) mTitleContainer.findViewById(R.id.activity_detail_title);
titleTV.setTextColor(titleTextColor);
titleTV.setText(mSelectedImage.getAuthor());
TextView subtitleTV = (TextView) mTitleContainer.findViewById(R.id.activity_detail_subtitle);
subtitleTV.setTextColor(titleTextColor);
subtitleTV.setText(mSelectedImage.getReadableModified_Date());
((TextView) mTitleContainer.findViewById(R.id.activity_detail_subtitle))
.setTextColor(titleTextColor);
}
private Palette.PaletteAsyncListener paletteListener = new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
Palette.Swatch s = palette.getVibrantSwatch();
if (s == null) {
s = palette.getDarkVibrantSwatch();
}
if (s == null) {
s = palette.getLightVibrantSwatch();
}
if (s == null) {
s = palette.getMutedSwatch();
}
if (s != null) {
setColors(s.getTitleTextColor(), s.getRgb());
}
}
};
@Override
public void onBackPressed() {
ViewPropertyAnimator hideTitleAnimator = Utils.hideViewByScaleXY(mFabButton);
hideTitleAnimator.setDuration(ANIMATION_DURATION_MEDIUM);
Utils.hideViewByScaleXY(mFabProgress).setDuration(ANIMATION_DURATION_MEDIUM).start();
mTitlesContainer.startAnimation(AnimationUtils.loadAnimation(DetailActivity.this, R.anim.alpha_off));
mTitlesContainer.setVisibility(View.INVISIBLE);
//Utils.hideViewByScaleY(imageInfoLayout);
hideTitleAnimator.setListener(new CustomAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
ViewPropertyAnimator hideFabAnimator = Utils.hideViewByScaleY(mTitleContainer);
hideFabAnimator.setListener(new CustomAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
coolBack();
}
});
}
});
hideTitleAnimator.start();
}
private void coolBack() {
try {
super.onBackPressed();
} catch (Exception e) {
// TODO: workaround
}
}
}
|
package com.pr0gramm.app.ui;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.LongSparseArray;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* This implementation has a {@link #getItemId(int)} to identify items
* and fragments, even if they change places between adapter updates.
*
* @see android.support.v4.app.FragmentStatePagerAdapter
*/
public abstract class IdFragmentStatePagerAdapter extends PagerAdapter {
private static final Logger logger = LoggerFactory.getLogger("IdFragmentStatePagerAdapter");
private final FragmentManager mFragmentManager;
// we only cache the most recent few saved states.
private final LinkedHashMap<Long, Fragment.SavedState> mSavedState = new LinkedHashMap<Long, Fragment.SavedState>() {
@Override
protected boolean removeEldestEntry(Entry eldest) {
return size() > 5;
}
};
private final LongSparseArray<Fragment> mFragments = new LongSparseArray<>();
private FragmentTransaction mCurTransaction;
private Fragment mCurrentPrimaryItem;
public IdFragmentStatePagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
/**
* Return the Fragment associated with a specified position.
*/
public abstract Fragment getItem(int position);
@Override
public void startUpdate(ViewGroup container) {
if (container.getId() == View.NO_ID) {
throw new IllegalStateException("ViewPager with adapter " + this
+ " requires a view id");
}
}
/**
* Gets the fragment for the given position, if one already exists.
*
* @param position The position of the fragment to get
*/
public Optional<Fragment> getFragment(int position) {
long itemId = getItemId(position);
return Optional.fromNullable(mFragments.get(itemId));
}
@SuppressLint("CommitTransaction")
@Override
public Object instantiateItem(ViewGroup container, int position) {
long id = getItemId(position);
// If we already have this item instantiated, there is nothing
// to do. This can happen when we are restoring the entire pager
// from its saved state, where the fragment manager has already
// taken care of restoring the fragments we previously had instantiated.
Fragment f = mFragments.get(id);
if (f != null) {
return f;
}
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment fragment = getItem(position);
Fragment.SavedState fss = mSavedState.get(id);
if (fss != null) {
fragment.setInitialSavedState(fss);
}
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
mFragments.put(id, fragment);
mCurTransaction.add(container.getId(), fragment);
return fragment;
}
protected abstract long getItemId(int position);
@SuppressLint("CommitTransaction")
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
long id = getItemId(position);
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
mSavedState.remove(id);
try {
mSavedState.put(id, mFragmentManager.saveFragmentInstanceState(fragment));
} catch (IllegalStateException ignored) {
// looks like this sometimes happen during save if the fragment is not in the
// fragment manager. We will ignore it.
}
mFragments.remove(id);
mCurTransaction.remove(fragment);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
if (fragment != mCurrentPrimaryItem) {
if (mCurrentPrimaryItem != null) {
mCurrentPrimaryItem.setMenuVisibility(false);
mCurrentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
try {
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
} catch (NullPointerException ignored) {
// another workaround:
// support library might access a fragment manager that is null.
}
}
mCurrentPrimaryItem = fragment;
}
}
@Override
public void finishUpdate(ViewGroup container) {
try {
if (mCurTransaction != null) {
mCurTransaction.commitNowAllowingStateLoss();
mCurTransaction = null;
}
} catch (RuntimeException ignored) {
// Sometimes we get a "activity has been destroyed." exception.
}
}
@Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView() == view;
}
@Override
public Parcelable saveState() {
Bundle state = null;
if (mSavedState.size() > 0) {
state = new Bundle();
long[] ids = new long[mSavedState.size()];
Parcelable[] states = new Parcelable[mSavedState.size()];
ImmutableList<Map.Entry<Long, Fragment.SavedState>> entries = ImmutableList.copyOf(mSavedState.entrySet());
for (int idx = 0; idx < entries.size(); idx++) {
ids[idx] = entries.get(idx).getKey();
states[idx] = entries.get(idx).getValue();
}
state.putLongArray("ids", ids);
state.putParcelableArray("states", states);
}
for (int idx = 0; idx < mFragments.size(); idx++) {
Fragment f = mFragments.valueAt(idx);
if (f != null) {
if (state == null) {
state = new Bundle();
}
String key = "f" + mFragments.keyAt(idx);
mFragmentManager.putFragment(state, key, f);
}
}
return state;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
if (state != null) {
Bundle bundle = (Bundle) state;
bundle.setClassLoader(loader);
long[] ids = bundle.getLongArray("ids");
Parcelable[] fss = bundle.getParcelableArray("states");
mSavedState.clear();
mFragments.clear();
if (fss != null) {
for (int i = 0; i < fss.length; i++) {
mSavedState.put(ids[i], (Fragment.SavedState) fss[i]);
}
}
Iterable<String> keys = bundle.keySet();
for (String key : keys) {
if (key.startsWith("f")) {
long id = Long.parseLong(key.substring(1));
Fragment f = mFragmentManager.getFragment(bundle, key);
if (f != null) {
f.setMenuVisibility(false);
mFragments.put(id, f);
} else {
logger.warn("Bad fragment at key " + key);
}
}
}
}
}
}
|
package de.fau.cs.mad.fablab.android.cart;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.github.brnunes.swipeablerecyclerview.SwipeableRecyclerViewTouchListener;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import de.fau.cs.mad.fablab.android.R;
import de.fau.cs.mad.fablab.android.db.DatabaseHelper;
import de.fau.cs.mad.fablab.rest.core.Cart;
import de.fau.cs.mad.fablab.rest.core.CartEntry;
import de.fau.cs.mad.fablab.rest.core.CartStatusEnum;
import de.fau.cs.mad.fablab.rest.core.Product;
public enum CartSingleton {
MYCART;
private List<Boolean> isProductRemoved;
private List<CartEntry> guiProducts;
private RuntimeExceptionDao<CartEntry, Long> cartEntryDao;
private RuntimeExceptionDao<Cart, String> cartDao;
private RuntimeExceptionDao<Product, String> productDao;
private RecyclerViewAdapter adapter;
private Context context;
private View view;
private SlidingUpPanelLayout mLayout;
private boolean slidingUp;
private Cart cart;
private List<CartEntry> products;
CartSingleton(){
}
public Cart getCart()
{
return cart;
}
// initialization of the db - getting all products that are in the cart
// call this method on startup activity
public void init(Context context){
cartDao = DatabaseHelper.getHelper(context).getCartDao();
cartEntryDao = DatabaseHelper.getHelper(context).getCartEntryDao();
productDao = DatabaseHelper.getHelper(context).getProductDao();
QueryBuilder<Cart, String> queryBuilder = cartDao.queryBuilder();
try {
queryBuilder.where().eq("status", CartStatusEnum.SHOPPING).or().eq("status", CartStatusEnum.PENDING);
cart = cartDao.queryForFirst(queryBuilder.prepare());
} catch (SQLException e) {
e.printStackTrace();
}
if(cart == null)
{
cart = new Cart();
cart.setCartCode(Long.toString(new Random().nextLong()));
cartDao.create(cart);
products = new ArrayList<>();
}else{
products = cartEntryDao.queryForEq("cart_id", cart.getCartCode());
}
isProductRemoved = new ArrayList<>();
guiProducts = new ArrayList<>();
for(int i=0;i<products.size();i++){
isProductRemoved.add(false);
guiProducts.add(products.get(i));
}
}
// Setting up the view for every context c including the sliding up panel
public void setSlidingUpPanel(Context c, View v, boolean slidingUp){
this.context = c;
this.view = v;
this.slidingUp = slidingUp;
// Set Layout and Recyclerview
RecyclerView cart_rv = (RecyclerView) v.findViewById(R.id.cart_recycler_view);
LinearLayoutManager llm = new LinearLayoutManager(context);
cart_rv.setLayoutManager(llm);
cart_rv.setHasFixedSize(true);
// Add Entries to view
adapter = new RecyclerViewAdapter(this.context, guiProducts);
cart_rv.setAdapter(adapter);
// Set up listener to be able to swipe to left/right to remove items
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(cart_rv,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
@Override
public boolean canSwipe(int position) {
return true;
}
@Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
View card = recyclerView.getChildAt(position);
LinearLayout ll = (LinearLayout) card.findViewById(R.id.cart_entry_undo);
LinearLayout ll_before = (LinearLayout) card.findViewById(R.id.product_view);
if(isProductRemoved.get(position) == true){
ll_before.setClickable(true);
ll.setClickable(false);
isProductRemoved.remove(position);
guiProducts.remove(position);
adapter.notifyItemRemoved(position);
}else{
isProductRemoved.set(position, true);
CartSingleton.MYCART.removeEntry(guiProducts.get(position));
ll_before.setClickable(false);
ll.setClickable(true);
RemoveCartEntryTimerTask myTask = new RemoveCartEntryTimerTask(card, position);
Timer myTimer = new Timer();
myTimer.schedule(myTask, 0, 70);
}
}
refresh();
adapter.notifyDataSetChanged();
updateVisibility();
}
@Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
View card = recyclerView.getChildAt(position);
LinearLayout ll = (LinearLayout) card.findViewById(R.id.cart_entry_undo);
LinearLayout ll_before = (LinearLayout) card.findViewById(R.id.product_view);
if(ll.getVisibility() == View.VISIBLE){
ll_before.setClickable(true);
ll.setClickable(false);
guiProducts.remove(position);
isProductRemoved.remove(position);
adapter.notifyItemRemoved(position);
}else{
isProductRemoved.set(position, true);
CartSingleton.MYCART.removeEntry(guiProducts.get(position));
ll_before.setClickable(false);
ll.setClickable(true);
RemoveCartEntryTimerTask myTask = new RemoveCartEntryTimerTask(card, position);
Timer myTimer = new Timer();
myTimer.schedule(myTask, 0, 70);
}
}
refresh();
adapter.notifyDataSetChanged();
updateVisibility();
}
});
cart_rv.addOnItemTouchListener(swipeTouchListener);
// Set up listener to show more than just one line of the product name
cart_rv.addOnItemTouchListener(new RecyclerItemClickListener(context, cart_rv, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, final int position, MotionEvent e) {
TextView product_title = (TextView) view.findViewById(R.id.cart_product_name);
Spinner cart_product_quantity_spinner = (Spinner) view.findViewById(R.id.cart_product_quantity_spinner);
Button undo = (Button) view.findViewById(R.id.cart_product_undo);
ImageView undo_img = (ImageView) view.findViewById(R.id.cart_product_undo_img);
LinearLayout ll = (LinearLayout) view.findViewById(R.id.cart_entry_undo);
int x = (int)e.getRawX();
int y = (int)e.getRawY();
// show / hide full text title
if(!inViewInBounds(cart_product_quantity_spinner, x, y) &&
ll.getVisibility() == View.GONE){
if(product_title.getLineCount() == 1){
product_title.setSingleLine(false);
}else{
product_title.setSingleLine(true);
}
}else if(inViewInBounds(undo_img, x, y) && ll.getVisibility() == View.VISIBLE){
// recognize undo click
undo.performClick();
}
}
// check the touch position for quantity change / card click
@Override
public boolean inViewInBounds(View view, int x, int y){
Rect outRect = new Rect();
int[] location = new int[2];
view.getDrawingRect(outRect);
view.getLocationOnScreen(location);
outRect.offset(location[0], location[1]);
return outRect.contains(x, y);
}
@Override
public void onItemLongClick(View view, final int position){
}
}));
// checkout button
Button checkoutButton = (Button) v.findViewById(R.id.cart_button_checkout);
checkoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cart.getProducts().size() == 0) {
Toast.makeText(context, R.string.cart_empty, Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(context, CheckoutActivity2.class);
context.startActivity(intent);
}
});
// set total price
refresh();
// Basket empty? -> show msg if slidinguppanel is not used
if(guiProducts.size() == 0 && !slidingUp){
Toast.makeText(context, R.string.cart_empty, Toast.LENGTH_LONG).show();
}
// Set up Sliding up Panel
if(slidingUp) {
mLayout = (SlidingUpPanelLayout) view.findViewById(R.id.sliding_layout);
// only the top should be draggable
mLayout.setDragView(view.findViewById(R.id.dragPart));
mLayout.setPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
TextView total_price_top = (TextView) view.findViewById(R.id.cart_total_price_preview);
total_price_top.setAlpha(1 - slideOffset);
int diff = (int) (view.getResources().getDimension(R.dimen.slidinguppanel_panel_height) - view.getResources().getDimension(R.dimen.slidinguppanel_panel_height_opened));
LinearLayout drag = (LinearLayout) view.findViewById(R.id.dragPart);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
(int) (view.getResources().getDimension(R.dimen.slidinguppanel_panel_height) -
(diff*slideOffset)));
layoutParams.setMargins((int) view.getResources().getDimension(R.dimen.slidinguppanel_drag_bg_stroke_margin),0,(int) view.getResources().getDimension(R.dimen.slidinguppanel_drag_bg_stroke_margin),0);
drag.setLayoutParams(layoutParams);
}
@Override
public void onPanelExpanded(View panel) {
//Log.i("app", "onPanelExpanded");
}
@Override
public void onPanelCollapsed(View panel) {
//Log.i("app", "onPanelCollapsed");
}
@Override
public void onPanelAnchored(View panel) {
//Log.i("app", "onPanelAnchored");
}
@Override
public void onPanelHidden(View panel) {
//Log.i("app", "onPanelHidden");
}
});
updateVisibility();
}
}
// remove product from deleted list
// re-add product to cart, to the db tables, respectively
public void addRemovedProduct(int position){
if(guiProducts.size() != 0) {
cartEntryDao.create(guiProducts.get(position));
adapter.notifyDataSetChanged();
refresh();
}
}
// Getter for RecyclerViewAdapter class to check whether a product has an active removed view or not
public List<Boolean> getIsProductRemoved(){
return isProductRemoved;
}
// refresh TextView of the total price and #items in cart
public void refresh(){
TextView total_price = (TextView) view.findViewById(R.id.cart_total_price);
total_price.setText(CartSingleton.MYCART.totalPrice());
String base = view.getResources().getString(R.string.bold_start) + guiProducts.size() +
view.getResources().getString(R.string.cart_article_label) +
view.getResources().getString(R.string.cart_preview_delimiter) +
CartSingleton.MYCART.totalPrice() +
view.getResources().getString(R.string.bold_end);
TextView total_price_top = (TextView) view.findViewById(R.id.cart_total_price_preview);
total_price_top.setText(Html.fromHtml(base));
}
// panel only visible if cart is not empty
public void updateVisibility(){
if(this.slidingUp) {
if (guiProducts.size() == 0) {
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN);
mLayout.setPanelHeight((int) (view.getResources().getDimension(R.dimen.zero) / view.getResources().getDisplayMetrics().density));
} else {
mLayout.setPanelHeight((int) view.getResources().getDimension(R.dimen.slidinguppanel_panel_height));
}
}
}
// returns all existing products of the cart
// <-> don't necessarily need to be the same as guiProducts
public List<CartEntry> getProducts(){
return products;
}
// update CartEntry in db table
public void updateProducts(int position){
int pos = products.indexOf(guiProducts.get(position));
products.get(pos).setAmount(guiProducts.get(position).getAmount());
cartEntryDao.update(products.get(pos));
}
// remove CartEntry from db table
public void removeEntry(CartEntry entry){
products.remove(entry);
DeleteBuilder db_entry = cartEntryDao.deleteBuilder();
try {
db_entry.where().eq("id", entry.getId());
cartEntryDao.delete(db_entry.prepare());
}catch(SQLException e) {
e.printStackTrace();
}
}
// remove all entries from GUI and db tables
public void removeAllEntries() {
DeleteBuilder db_cart = cartDao.deleteBuilder();
DeleteBuilder db_entries = cartEntryDao.deleteBuilder();
try {
db_entries.where().eq("cart_id", cart.getCartCode());
cartEntryDao.delete(db_entries.prepare());
}catch(SQLException e) {
e.printStackTrace();
}
try {
db_cart.where().eq("cart_id", cart.getCartCode());
cartDao.delete(db_cart.prepare());
}catch(SQLException e) {
e.printStackTrace();
}
guiProducts.clear();
isProductRemoved.clear();
products.clear();
}
// add product to cart
public void addProduct(Product product, double amount){
// update existing cart entry
for(CartEntry temp : guiProducts){
if (temp.getProduct().getProductId().equals(product.getProductId())){
temp.setAmount(temp.getAmount() + amount);
int pos = products.indexOf(temp);
products.get(pos).setAmount(temp.getAmount());
cartEntryDao.update(products.get(pos));
return;
}
}
// create new one
CartEntry new_entry = new CartEntry(product, amount);
new_entry.setCart(cart);
new_entry.setProduct(product);
cartEntryDao.create(new_entry);
products.add(new_entry);
guiProducts.add(new_entry);
isProductRemoved.add(false);
}
// return total price
public String totalPrice(){
double total = cart.getTotal();
return String.format( "%.2f", total ) + Html.fromHtml(view.getResources().getString(R.string.non_breaking_space)) +
view.getResources().getString(R.string.currency);
}
// Timer Task to show a removed entry 5 sec before removing it permanently
class RemoveCartEntryTimerTask extends TimerTask{
private View view;
private int pos;
// Parameter view represents the card
// Parameter pos represents position in RecyclerView
RemoveCartEntryTimerTask(View view, int pos){
this.view = view;
this.pos = pos;
}
public void run(){
view.setAlpha(view.getAlpha()-0.02f);
if(view.getAlpha() <= 0){
isProductRemoved.remove(pos);
guiProducts.remove(pos);
adapter.notifyItemRemoved(pos);
this.cancel();
}
}
}
}
|
package in.testpress.testpress.ui;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import in.testpress.testpress.R;
public class ZoomableImageActivity extends Activity {
ProgressBar progressBar;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_zoomable_image);
progressBar = (ProgressBar) findViewById(R.id.pb_loading);
final TextView emptyView = (TextView)findViewById(R.id.empty);
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true)
.resetViewBeforeLoading(true)
.build();
ImageLoader.getInstance().loadImage(getIntent().getStringExtra("url"), options,
new SimpleImageLoadingListener() {
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
if(failReason.getType().equals(FailReason.FailType.IO_ERROR)) {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(R.string.no_internet_try_again);
} else {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText(getString(R.string.something_went_wrong_please_try_after));
}
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
progressBar.setVisibility(View.GONE);
((TouchImageView) findViewById(R.id.image)).setImageBitmap(loadedImage);
}
});
}
}
|
package me.devsaki.hentoid.parsers.content;
import org.jsoup.nodes.Element;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.enums.AttributeType;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.parsers.ParseHelper;
import me.devsaki.hentoid.util.AttributeMap;
import me.devsaki.hentoid.util.Helper;
import pl.droidsonroids.jspoon.annotation.Selector;
public class NexusContent extends BaseContentParser {
@Selector(value = "head [property=og:url]", attr = "content", defValue = "")
private String galleryUrl;
@Selector(value = "body img[src*='/cover']", attr = "src", defValue = "")
private String coverUrl;
@Selector(value = "h1.title", defValue = "<no title>")
private String title;
@Selector("table.view-page-details")
private List<Element> information;
@Selector(value = "table.view-page-details a[href*='q=artist']")
private List<Element> artists;
@Selector(value = "table.view-page-details a[href*='q=tag']")
private List<Element> tags;
@Selector(value = "table.view-page-details a[href*='q=parody']")
private List<Element> series;
@Selector(value = "table.view-page-details a[href*='q=language']")
private List<Element> language;
@Selector(value = ".card-image img")
private List<Element> thumbs;
@Nullable
public Content toContent(@Nonnull String url) {
Content result = new Content();
result.setSite(Site.NEXUS);
String theUrl = galleryUrl.isEmpty() ? url : galleryUrl;
if (theUrl.isEmpty() || null == thumbs) return result.setStatus(StatusContent.IGNORED);
result.setUrl(theUrl.replace(Site.NEXUS.getUrl() + "/view", ""));
result.setCoverImageUrl(coverUrl);
result.setTitle(Helper.removeNonPrintableChars(title));
AttributeMap attributes = new AttributeMap();
ParseHelper.parseAttributes(attributes, AttributeType.ARTIST, artists, false, Site.NEXUS);
ParseHelper.parseAttributes(attributes, AttributeType.TAG, tags, false, Site.NEXUS);
ParseHelper.parseAttributes(attributes, AttributeType.SERIE, series, false, Site.NEXUS);
ParseHelper.parseAttributes(attributes, AttributeType.LANGUAGE, language, false, Site.NEXUS);
result.addAttributes(attributes);
result.setQtyPages(thumbs.size()); // We infer there are as many thumbs as actual book pages on the gallery summary webpage
return result;
}
}
|
package net.formula97.fakegpbase;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import net.formula97.fakegpbase.Databases.GunplaInfo;
import net.formula97.fakegpbase.Databases.GunplaInfoModel;
import net.formula97.fakegpbase.fragments.NewItemDialog;
import net.formula97.fakegpbase.fragments.WriteTagDialogs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GunplaRegisterActivity extends Activity implements AdapterView.OnItemSelectedListener,
NewItemDialog.OnInputCompleteListener, WriteTagDialogs.OnTagOperationListener {
private EditText etRegisterBuilderName;
private EditText etRegisterFighterName;
private Spinner spinnerScaleName;
private Spinner spinnerClassName;
private RadioGroup radioGroup1;
private RadioButton radioBtnNonScratch;
private RadioButton radioBtnPartialScratch;
private RadioButton radioBtnFullScratch;
private EditText etRegisterModelName;
private EditText etRegisterGunplaName;
private AdView adView2;
private String mBuiderName;
private String mFighterName;
private int mScaleSelectedPos;
private String mScaleVal;
private int mClassSelectedPos;
private String mClassVal;
private int mScratchSelected;
private String mModelName;
private String mGunplaName;
private String mTagId;
private GunplaInfo mGunplaInfo;
private ArrayAdapter<String> scaleAdapter;
private ArrayAdapter<String> classAapter;
private boolean isScaleSelected = true;
private boolean stopTagRead = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gunpla_register);
initView();
adView2 = (AdView) findViewById(R.id.adView2);
AdRequest adRequest = new AdRequest.Builder().build();
adView2.loadAd(adRequest);
initVariables();
String[] scales = getResources().getStringArray(R.array.scale_list);
List<String> scaleList = new ArrayList<>(Arrays.asList(scales));
scaleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, scaleList);
scaleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerScaleName.setAdapter(scaleAdapter);
spinnerScaleName.setOnItemSelectedListener(this);
String[] classes = getResources().getStringArray(R.array.class_list);
List<String> classList = new ArrayList<>(Arrays.asList(classes));
classAapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, classList);
classAapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerClassName.setAdapter(classAapter);
spinnerClassName.setOnItemSelectedListener(this);
}
private void initView() {
etRegisterBuilderName = (EditText) findViewById(R.id.etRegisterBuilderName);
etRegisterFighterName = (EditText) findViewById(R.id.etRegisterFighterName);
spinnerScaleName = (Spinner) findViewById(R.id.spinnerScaleName);
spinnerClassName = (Spinner) findViewById(R.id.spinnerClassName);
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
radioBtnNonScratch = (RadioButton) findViewById(R.id.radioBtnNonScratch);
radioBtnPartialScratch = (RadioButton) findViewById(R.id.radioBtnPartialScratch);
radioBtnFullScratch = (RadioButton) findViewById(R.id.radioBtnFullScratch);
etRegisterModelName = (EditText) findViewById(R.id.etRegisterModelName);
etRegisterGunplaName = (EditText) findViewById(R.id.etRegisterGunplaName);
}
private void initVariables() {
// Preference
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
mBuiderName = pref.getString(AppConst.PREF_KEY_BUILDER_NAME, "");
mFighterName = pref.getString(AppConst.PREF_KEY_FIGHTER_NAME, "");
mScaleSelectedPos = 0;
mScaleVal = "";
mClassSelectedPos = 0;
mClassVal = "";
mScratchSelected = 0;
mModelName = "";
mGunplaName = "";
mTagId = "";
mGunplaInfo = new GunplaInfo();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_gunpla_register, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_submit:
// SQLite
return true;
case R.id.action_write_tag:
// NFC
stopTagRead = true;
WriteTagDialogs writeTagDialogs = new WriteTagDialogs();
writeTagDialogs.show(getFragmentManager(), WriteTagDialogs.FRAGMENT_TAG);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onResume() {
super.onResume();
adView2.resume();
etRegisterBuilderName.setText(mBuiderName);
etRegisterFighterName.setText(mFighterName);
// ArrayAdapter
// ArrayAdapter
boolean matched = false;
for (int i = 0; i < scaleAdapter.getCount(); i++) {
if (mScaleVal.equals(scaleAdapter.getItem(i))) {
matched = true;
break;
}
}
if (!matched && !TextUtils.isEmpty(mScaleVal)) {
scaleAdapter.insert(mScaleVal, mScaleSelectedPos);
}
matched = false;
for (int i = 0; i < classAapter.getCount(); i++) {
if (mClassVal.equals(classAapter.getItem(i))) {
matched = true;
break;
}
}
if (!matched && !TextUtils.isEmpty(mClassVal)) {
classAapter.insert(mClassVal, mClassSelectedPos);
}
spinnerScaleName.setSelection(mScaleSelectedPos, false);
spinnerClassName.setSelection(mClassSelectedPos, false);
switch (mScratchSelected) {
case AppConst.NO_SCRATCH_BUILT:
radioBtnNonScratch.setChecked(true);
break;
case AppConst.PARTIAL_SCRATCH_BUILT:
radioBtnPartialScratch.setChecked(true);
break;
case AppConst.FULL_SCRATCH_BUILT:
radioBtnFullScratch.setChecked(true);
break;
}
etRegisterModelName.setText(mModelName);
etRegisterGunplaName.setText(mGunplaName);
}
@Override
protected void onPause() {
super.onPause();
adView2.pause();
}
@Override
protected void onDestroy() {
adView2.destroy();
super.onDestroy();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selItem = (String) parent.getAdapter().getItem(position);
if (parent.getAdapter().equals(scaleAdapter)) {
mScaleSelectedPos = position;
mScaleVal = selItem;
isScaleSelected = true;
} else if (parent.getAdapter().equals(classAapter)) {
mClassSelectedPos = position;
mClassVal = selItem;
isScaleSelected = false;
}
if (selItem.equals(getString(R.string.other))) {
NewItemDialog dialog = new NewItemDialog();
dialog.show(getFragmentManager(), NewItemDialog.FRAGMENT_TAG);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onInputCompleted(String inputItem) {
if (isScaleSelected) {
scaleAdapter.insert(inputItem, mScaleSelectedPos);
spinnerScaleName.setSelection(mScaleSelectedPos, false);
scaleAdapter.notifyDataSetChanged();
} else {
classAapter.insert(inputItem, mClassSelectedPos);
spinnerClassName.setSelection(mClassSelectedPos, false);
classAapter.notifyDataSetChanged();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
private GunplaInfo makeGunplaInfo(String tagId) {
GunplaInfo info = new GunplaInfo();
info.setBuilderName(etRegisterBuilderName.getText().toString());
info.setFighterName(etRegisterFighterName.getText().toString());
info.setClassValue((String) spinnerClassName.getSelectedItem());
info.setScaleValue((String) spinnerScaleName.getSelectedItem());
int scratch = 0;
if (radioBtnNonScratch.isChecked()) {
scratch = AppConst.NO_SCRATCH_BUILT;
} else if (radioBtnPartialScratch.isChecked()) {
scratch = AppConst.PARTIAL_SCRATCH_BUILT;
} else if (radioBtnFullScratch.isChecked()) {
scratch = AppConst.FULL_SCRATCH_BUILT;
}
info.setScratchBuiltLevel(scratch);
info.setModelNo(etRegisterModelName.getText().toString());
info.setGunplaName(etRegisterGunplaName.getText().toString());
info.setTagId(tagId);
return info;
}
@Override
public void onTagOperation(int operationCode) {
String logtag = this.getClass().getSimpleName() + "#onTagOperation";
String result = "";
switch (operationCode) {
case WriteTagDialogs.OPERATION_SUCCESS:
result = "OPERATION_SUCCESS";
break;
case WriteTagDialogs.OPERATION_FAILED:
result = "OPERATION_FAILED";
break;
case WriteTagDialogs.OPERATION_CANCELED:
result = "OPERATION_CANCELED";
break;
}
Log.i(logtag, "Received : " + result);
stopTagRead = false;
}
}
|
package org.msf.records.ui.chart;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.common.base.Optional;
import org.msf.records.App;
import org.msf.records.data.app.AppModel;
import org.msf.records.data.app.AppPatient;
import org.msf.records.data.app.AppPatientDelta;
import org.msf.records.events.CreatePatientSucceededEvent;
import org.msf.records.events.CrudEventBus;
import org.msf.records.events.data.PatientUpdateFailedEvent;
import org.msf.records.events.data.SingleItemFetchedEvent;
import org.msf.records.events.sync.SyncSucceededEvent;
import org.msf.records.location.LocationManager;
import org.msf.records.model.Concept;
import org.msf.records.mvcmodels.PatientModel;
import org.msf.records.net.Constants;
import org.msf.records.net.OpenMrsChartServer;
import org.msf.records.net.model.ChartStructure;
import org.msf.records.net.model.ConceptList;
import org.msf.records.net.model.PatientChart;
import org.msf.records.net.model.User;
import org.msf.records.sync.LocalizedChartHelper;
import org.msf.records.sync.LocalizedChartHelper.LocalizedObservation;
import org.msf.records.sync.SyncManager;
import org.msf.records.ui.tentselection.AssignLocationDialog;
import org.msf.records.utils.EventBusRegistrationInterface;
import org.msf.records.utils.EventBusWrapper;
import org.odk.collect.android.model.PrepopulatableFields;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import de.greenrobot.event.EventBus;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.msf.records.ui.tentselection.AssignLocationDialog.TentSelectedCallback;
/**
* Controller for {@link PatientChartActivity}.
*
* <p>Do not add untestable dependencies to this class.
*/
final class PatientChartController {
private static final String TAG = PatientChartController.class.getName();
private static final boolean DEBUG = true;
private static final String KEY_PENDING_UUIDS = "pendingUuids";
/*
* The ODK code for filling in a form has no way of attaching metadata to it This means we can't
* pass which patient is currently being edited. Instead, we keep an array of up to
* MAX_ODK_REQUESTS patientUuids. We then send request code BASE_ODK_REQUEST + index, and roll
* through the array. The array is persisted through activity restart in the savedInstanceState.
*/
private static final int BASE_ODK_REQUEST = 100;
/** Maximum concurrent ODK forms assigned request codes. */
private static final int MAX_ODK_REQUESTS = 10;
private int nextIndex = 0;
// TODO: Use a map for this instead of an array.
private final String[] mPatientUuids;
private AppPatient mPatient = AppPatient.builder().build();
private long mLastObservation = Long.MIN_VALUE;
private String mPatientUuid = "";
public interface Ui {
/** Sets the activity title. */
void setTitle(String title);
/** Updates the UI showing current observation values for this patient. */
void updatePatientVitalsUI(Map<String, LocalizedObservation> observations);
/** Updates the UI showing the historic log of observation values for this patient. */
void setObservationHistory(List<LocalizedObservation> observations);
/** Shows the last time a user interacted with this patient. */
void setLatestEncounter(long latestEncounterTimeMillis);
/** Shows the patient's personal details. */
void setPatient(AppPatient patient);
/** Starts a new form activity to collect observations from the user. */
void fetchAndShowXform(
String formUuid,
int requestCode,
org.odk.collect.android.model.Patient patient,
PrepopulatableFields fields);
}
private final OpenMrsChartServer mServer;
private final EventBusRegistrationInterface mDefaultEventBus;
private final CrudEventBus mCrudEventBus;
private final OdkResultSender mOdkResultSender;
private final Ui mUi;
private final ObservationsProvider mObservationsProvider;
private final AppModel mAppModel;
private final EventSubscriber mEventBusSubscriber = new EventSubscriber();
private final PatientModel mPatientModel;
private final SyncManager mSyncManager;
private AssignLocationDialog mAssignLocationDialog;
/** Sends ODK form data. */
public interface OdkResultSender {
void sendOdkResultToServer(
@Nullable String patientUuid,
int resultCode,
Intent data);
}
public interface ObservationsProvider {
/** Get all observations for a given patient from the local cache, localized to English. */
List<LocalizedObservation> getObservations(String patientUuid);
Map<String, LocalizedChartHelper.LocalizedObservation>
getMostRecentObservations(String patientUuid);
}
public PatientChartController(
AppModel appModel,
OpenMrsChartServer server,
EventBusRegistrationInterface defaultEventBus,
CrudEventBus crudEventBus,
Ui ui,
OdkResultSender odkResultSender,
ObservationsProvider observationsProvider,
@Nullable Bundle savedState,
PatientModel patientModel,
SyncManager syncManager) {
mAppModel = appModel;
mServer = checkNotNull(server);
mDefaultEventBus = defaultEventBus;
mCrudEventBus = crudEventBus;
mUi = ui;
mOdkResultSender = odkResultSender;
mObservationsProvider = observationsProvider;
mPatientModel = patientModel;
if (savedState != null) {
mPatientUuids = savedState.getStringArray(KEY_PENDING_UUIDS);
} else {
mPatientUuids = new String[MAX_ODK_REQUESTS];
}
mSyncManager = syncManager;
}
/** Returns the state of the controller. This should be saved to preserve it over activity restarts. */
public Bundle getState() {
Bundle bundle = new Bundle();
bundle.putStringArray("pendingUuids", mPatientUuids);
return bundle;
}
/** Sets the current patient. This should be called before init. */
public void setPatient(
String patientUuid,
@Nullable String patientName,
@Nullable String patientId) {
mPatientUuid = patientUuid;
if (patientName != null && patientId != null) {
mUi.setTitle(patientName + " (" + patientId + ")");
} else {
mUi.setTitle("");
}
}
/** Initializes the controller, setting async operations going to collect data required by the UI. */
public void init() {
mDefaultEventBus.register(mEventBusSubscriber);
mCrudEventBus.register(mEventBusSubscriber);
prodServer();
mAppModel.fetchSinglePatient(mCrudEventBus, mPatientUuid);
}
/** Releases any resources used by the controller. */
public void suspend() {
mCrudEventBus.unregister(mEventBusSubscriber);
mDefaultEventBus.unregister(mEventBusSubscriber);
}
public void onXFormResult(int requestCode, int resultCode, Intent data) {
String patientUuid = getAndClearPatientUuidForRequestCode(requestCode);
if (patientUuid == null) {
Log.e(TAG, "Received unknown request code: " + requestCode);
return;
}
// This will fire a CreatePatientSucceededEvent.
mOdkResultSender.sendOdkResultToServer(patientUuid, resultCode, data);
}
/** Call when the user has indicated they want to add observation data. */
public void onAddObservationPressed() {
onAddObservationPressed(null);
}
/** Call when the user has indicated they want to add observation data. */
public void onAddObservationPressed(String targetGroup) {
PrepopulatableFields fields = new PrepopulatableFields();
// TODO(dxchen): Re-enable this post v0.2.1.
// fields.encounterTime = DateTime.now();
fields.locationName = "Triage";
User user = App.getUserManager().getActiveUser();
if (user != null) {
fields.clinicianName = user.getFullName();
}
Map<String, LocalizedChartHelper.LocalizedObservation> observations =
mObservationsProvider.getMostRecentObservations(mPatientUuid);
if (observations.containsKey(Concept.PREGNANCY_UUID)
&& Concept.YES_UUID.equals(observations.get(Concept.PREGNANCY_UUID).value)) {
fields.pregnant = PrepopulatableFields.YES;
}
if (observations.containsKey(Concept.IV_UUID)
&& Concept.YES_UUID.equals(observations.get(Concept.IV_UUID).value)) {
fields.ivFitted = PrepopulatableFields.YES;
}
fields.targetGroup = targetGroup;
mUi.fetchAndShowXform(
Constants.ADD_OBSERVATION_UUID,
savePatientUuidForRequestCode(mPatientUuid),
mPatientModel.getOdkPatient(mPatientUuid),
fields);
}
private void prodServer() {
// TODO(dxchen): This doesn't properly handle configuration changes. We should pass this
// into the fragment arguments.
// TODO(nfortescue): get proper caching, and the dictionary working.
// TODO: Document what this does!
mServer.getChart(mPatientUuid, new Response.Listener<PatientChart>() {
@Override
public void onResponse(PatientChart response) {
Log.i(TAG, response.uuid + " " + Arrays.asList(response.encounters));
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Unexpected error on fetching chart", error);
}
});
mServer.getConcepts(
new Response.Listener<ConceptList>() {
@Override
public void onResponse(ConceptList response) {
Log.i(TAG, "Response: " + Integer.toString(response.results.length));
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Unexpected error fetching concepts", error);
}
});
mServer.getChartStructure("ea43f213-66fb-4af6-8a49-70fd6b9ce5d4",
new Response.Listener<ChartStructure>() {
@Override
public void onResponse(ChartStructure response) {
Log.i(TAG, "Response: " + Arrays.asList(response.groups).toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Unexpected error fetching concepts", error);
}
});
}
/** Gets the latest observation values and displays them on the UI. */
private void updatePatientUI() {
// Get the observations
// TODO(dxchen,nfortescue): Background thread this, or make this call async-like.
List<LocalizedObservation> observations = mObservationsProvider.getObservations(mPatientUuid);
Map<String, LocalizedObservation> conceptsToLatestObservations =
new HashMap<>(mObservationsProvider.getMostRecentObservations(mPatientUuid));
// Update timestamp
for (LocalizedObservation observation : observations) {
// TODO(rjlothian): This looks odd. Why do we do this? I'd expect this to be set by getMostRecentObservations instead.
conceptsToLatestObservations.put(observation.conceptUuid, observation);
mLastObservation = Math.max(
mLastObservation,
observation.encounterTimeMillis);
}
if (DEBUG) {
Log.d(TAG, "Showing " + observations.size() + " observations, and "
+ conceptsToLatestObservations.size() + " latest observations");
}
mUi.setLatestEncounter(mLastObservation);
mUi.updatePatientVitalsUI(conceptsToLatestObservations);
mUi.setObservationHistory(observations);
}
/**
* Returns a requestCode that can be sent to ODK Xform activity representing the given UUID.
*/
private int savePatientUuidForRequestCode(String patientUuid) {
mPatientUuids[nextIndex] = patientUuid;
int requestCode = BASE_ODK_REQUEST + nextIndex;
nextIndex = (nextIndex + 1) % MAX_ODK_REQUESTS;
return requestCode;
}
public void showAssignLocationDialog(
Context context,
LocationManager locationManager) {
TentSelectedCallback callback =
new TentSelectedCallback() {
@Override
public boolean onNewTentSelected(String newTentUuid) {
AppPatientDelta patientDelta = new AppPatientDelta();
patientDelta.assignedLocationUuid = Optional.of(newTentUuid);
mAppModel.updatePatient(mCrudEventBus, mPatient.uuid, patientDelta);
return false;
}
};
mAssignLocationDialog = new AssignLocationDialog(
context,
locationManager,
new EventBusWrapper(EventBus.getDefault()),
Optional.of(mPatient.locationUuid),
callback);
mAssignLocationDialog.show();
}
/**
* Converts a requestCode that was previously sent to the ODK Xform activity back to a patient UUID.
*
* <p>Also removes details of that requestCode from the controller's state.
*/
@Nullable private String getAndClearPatientUuidForRequestCode(int requestCode) {
int index = requestCode - BASE_ODK_REQUEST;
String patientUuid = mPatientUuids[index];
mPatientUuids[index] = null;
return patientUuid;
}
@SuppressWarnings("unused") // Called by reflection from EventBus.
private final class EventSubscriber {
public void onEventMainThread(CreatePatientSucceededEvent event) {
mSyncManager.forceSync();
}
public void onEventMainThread(SyncSucceededEvent event) {
updatePatientUI();
}
public void onEventMainThread(SingleItemFetchedEvent<AppPatient> event) {
mPatient = event.item;
mUi.setPatient(mPatient);
if (mAssignLocationDialog != null) {
mAssignLocationDialog.dismiss();
mAssignLocationDialog = null;
}
// TODO(dxchen): This delays rendering of the UI--hopefully long enough for the first
// part of the UI to display
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override public void run() {
updatePatientUI();
}
}, 100);
}
public void onEventMainThread(PatientUpdateFailedEvent event) {
mAssignLocationDialog.onPatientUpdateFailed(event.reason);
}
}
}
|
package org.thoughtcrime.meshmessenger;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class ConversationList extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(R.string.app_name);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_conversation_list, menu);
return true;
}
@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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package org.wikipedia.views;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
public class ItemTouchHelperSwipeAdapter extends ItemTouchHelper.SimpleCallback {
public interface Callback {
void onSwiped(@IntRange(from = 0) int item);
}
public interface SwipeableView { }
@NonNull private final Callback callback;
public ItemTouchHelperSwipeAdapter(@NonNull Callback callback) {
super(0, ItemTouchHelper.END);
this.callback = callback;
}
@Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
return false;
}
@Override public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
if (viewHolder.itemView instanceof SwipeableView) {
return super.getSwipeDirs(recyclerView, viewHolder);
}
return 0;
}
@Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
callback.onSwiped(viewHolder.getAdapterPosition());
}
}
|
package ve.com.abicelis.chefbuddy.database;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import ve.com.abicelis.chefbuddy.database.exceptions.CouldNotDeleteDataException;
import ve.com.abicelis.chefbuddy.database.exceptions.CouldNotGetDataException;
import ve.com.abicelis.chefbuddy.database.exceptions.CouldNotInsertDataException;
import ve.com.abicelis.chefbuddy.database.exceptions.CouldNotUpdateDataException;
import ve.com.abicelis.chefbuddy.model.DailyRecipe;
import ve.com.abicelis.chefbuddy.model.Ingredient;
import ve.com.abicelis.chefbuddy.model.Measurement;
import ve.com.abicelis.chefbuddy.model.PreparationTime;
import ve.com.abicelis.chefbuddy.model.RecipeIngredient;
import ve.com.abicelis.chefbuddy.model.Recipe;
import ve.com.abicelis.chefbuddy.model.Servings;
import ve.com.abicelis.chefbuddy.util.CalendarUtil;
public class ChefBuddyDAO {
private ChefBuddyDbHelper mDatabaseHelper;
public ChefBuddyDAO(ChefBuddyDbHelper chefBuddyDbHelper) {
mDatabaseHelper = chefBuddyDbHelper;
}
/**
* Returns the number of recipes in the db
*/
public int getRecipeCount() throws CouldNotGetDataException {
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(ChefBuddyContract.RecipeTable.TABLE_NAME, null, null, null, null, null, null);
int count = cursor.getCount();
cursor.close();
return count;
}
/**
* Returns the List of Recipes stored in the database without the
*/
public List<Recipe> getRecipes() throws CouldNotGetDataException {
List<Recipe> recipes = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(ChefBuddyContract.RecipeTable.TABLE_NAME, null, null, null, null, null, ChefBuddyContract.RecipeTable.COLUMN_NAME.getName() + " ASC");
try {
while(cursor.moveToNext()) {
Recipe recipe = getRecipeFromCursor(cursor);
recipe.setRecipeIngredients(getRecipeIngredientsOfRecipe(recipe.getId()));
// TODO: 7/7/2017 Add images!
recipes.add(recipe);
}
} finally {
cursor.close();
}
return recipes;
}
/**
* Returns a single Recipe stored in the database
* @param recipeId the ID of the recipe
*/
public Recipe getRecipe(long recipeId) throws CouldNotGetDataException {
Recipe recipe;
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(ChefBuddyContract.RecipeTable.TABLE_NAME, null, ChefBuddyContract.RecipeTable.COLUMN_ID.getName()+"=?", new String[] {String.valueOf(recipeId)}, null, null, null);
try {
if(cursor.getCount() == 0)
throw new CouldNotGetDataException("Recipe not found. ID="+ recipeId);
cursor.moveToNext();
recipe = getRecipeFromCursor(cursor);
recipe.setRecipeIngredients(getRecipeIngredientsOfRecipe(recipe.getId()));
} finally {
cursor.close();
}
return recipe;
}
/**
* Returns the List of Recipes stored in the database without the
*/
public List<Recipe> getFilteredRecipes(String query) throws CouldNotGetDataException {
List<Recipe> recipes = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(ChefBuddyContract.RecipeTable.TABLE_NAME, null, ChefBuddyContract.RecipeTable.COLUMN_NAME.getName() + " LIKE ?", new String[]{"%"+query+"%"}, null, null, null);
try {
while(cursor.moveToNext()) {
Recipe recipe = getRecipeFromCursor(cursor);
recipe.setRecipeIngredients(getRecipeIngredientsOfRecipe(recipe.getId()));
// TODO: 7/7/2017 Add images!
recipes.add(recipe);
}
} finally {
cursor.close();
}
return recipes;
}
/**
* Returns the list of ingredients of a recipe
* @param recipeId The ID of the recipe
* @return A List of ingredients
*/
public List<RecipeIngredient> getRecipeIngredientsOfRecipe(long recipeId) throws CouldNotGetDataException {
List<RecipeIngredient> recipeIngredients = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
String tables = String.format("%1$s INNER JOIN %2$s ON %1$s.%3$s = %2$s.%4$s",
ChefBuddyContract.RecipeIngredientTable.TABLE_NAME,
ChefBuddyContract.IngredientTable.TABLE_NAME,
ChefBuddyContract.RecipeIngredientTable.COLUMN_INGREDIENT_FK.getName(),
ChefBuddyContract.IngredientTable.COLUMN_ID.getName());
String[] selectionArgs = new String[]{String.valueOf(recipeId)};
Cursor cursor = db.query(tables, null, ChefBuddyContract.RecipeIngredientTable.COLUMN_RECIPE_FK.getName()+"=?", selectionArgs, null, null, null);
try {
while (cursor.moveToNext()) {
RecipeIngredient recipeIngredient = getRecipeIngredientFromCursor(cursor);
recipeIngredients.add(recipeIngredient);
}
} finally {
cursor.close();
}
return recipeIngredients;
}
/**
* Returns a full list of ingredients
* @return A List of ingredients
*/
public List<Ingredient> getIngredients() throws CouldNotGetDataException {
List<Ingredient> ingredients = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(ChefBuddyContract.IngredientTable.TABLE_NAME, null, null, null, null, null, null);
try {
while (cursor.moveToNext()) {
Ingredient ingredient = getIngredientFromCursor(cursor);
ingredients.add(ingredient);
}
} finally {
cursor.close();
}
return ingredients;
}
/**
* Returns the complete list of recipe IDs in the wheel_recipe table
* @return An array of recipe IDs
*/
public long[] getWheelRecipeIds() throws CouldNotGetDataException {
long[] ids;
int i = 0;
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(ChefBuddyContract.WheelRecipeTable.TABLE_NAME, null, null, null, null, null, null);
ids = new long[cursor.getCount()];
try {
while (cursor.moveToNext()) {
long recipeId = getRecipeIdFromWheelRecipeCursor(cursor);
ids[i] = recipeId;
i++;
}
} finally {
cursor.close();
}
return ids;
}
/**
* Returns the complete list of recipes in the wheel_recipe table
* @return A list of Recipes
*/
public List<Recipe> getWheelRecipes() throws CouldNotGetDataException {
List<Recipe> recipes = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
String tables = String.format("%1$s INNER JOIN %2$s ON %1$s.%3$s = %2$s.%4$s",
ChefBuddyContract.WheelRecipeTable.TABLE_NAME,
ChefBuddyContract.RecipeTable.TABLE_NAME,
ChefBuddyContract.WheelRecipeTable.COLUMN_RECIPE.getName(),
ChefBuddyContract.RecipeTable.COLUMN_ID.getName());
Cursor cursor = db.query(tables, null, null, null, null, null, null);
try {
while (cursor.moveToNext()) {
Recipe recipe = getRecipeFromCursor(cursor);
recipe.setRecipeIngredients(getRecipeIngredientsOfRecipe(recipe.getId()));
recipes.add(recipe);
}
} finally {
cursor.close();
}
return recipes;
}
/**
* Returns the complete list of daily recipes in the daily_recipe table
* @return A list of Recipes
*/
public List<DailyRecipe> getDailyRecipes() throws CouldNotGetDataException {
List<DailyRecipe> dailyRecipes = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
String tables = String.format("%1$s INNER JOIN %2$s ON %1$s.%3$s = %2$s.%4$s",
ChefBuddyContract.DailyRecipeTable.TABLE_NAME,
ChefBuddyContract.RecipeTable.TABLE_NAME,
ChefBuddyContract.DailyRecipeTable.COLUMN_RECIPE_FK.getName(),
ChefBuddyContract.RecipeTable.COLUMN_ID.getName());
Cursor cursor = db.query(tables, null, null, null, null, null, null);
try {
while (cursor.moveToNext()) {
DailyRecipe dailyRecipe = getDailyRecipeFromCursor(cursor);
dailyRecipe.getRecipe().setRecipeIngredients(getRecipeIngredientsOfRecipe(dailyRecipe.getRecipe().getId()));
dailyRecipes.add(dailyRecipe);
}
} finally {
cursor.close();
}
return dailyRecipes;
}
/**
* Returns the recipe made on a particular day, or none if none was made.
* @param date The date to check
* @return A Recipe or null
*/
public DailyRecipe getDailyRecipeForDate(Calendar date) throws CouldNotGetDataException {
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
String tables = String.format("%1$s INNER JOIN %2$s ON %1$s.%3$s = %2$s.%4$s",
ChefBuddyContract.DailyRecipeTable.TABLE_NAME,
ChefBuddyContract.RecipeTable.TABLE_NAME,
ChefBuddyContract.DailyRecipeTable.COLUMN_RECIPE_FK.getName(),
ChefBuddyContract.RecipeTable.COLUMN_ID.getName());
Cursor cursor = db.query(tables, null,
ChefBuddyContract.DailyRecipeTable.COLUMN_YEAR.getName() + "=? AND " +
ChefBuddyContract.DailyRecipeTable.COLUMN_MONTH.getName() + "=? AND " +
ChefBuddyContract.DailyRecipeTable.COLUMN_DAY.getName() + "=?",
new String[] {String.valueOf(date.get(Calendar.YEAR)),
String.valueOf(date.get(Calendar.MONTH)),
String.valueOf(date.get(Calendar.DAY_OF_MONTH))}, null, null, null);
DailyRecipe dailyRecipe = null;
try {
while (cursor.moveToNext()) {
dailyRecipe = getDailyRecipeFromCursor(cursor);
dailyRecipe.getRecipe().setRecipeIngredients(getRecipeIngredientsOfRecipe(dailyRecipe.getRecipe().getId()));
}
} finally {
cursor.close();
}
return dailyRecipe;
}
/* Insert data into database */
/**
* Inserts a new recipe into the database.
* Will also populate ingredients table if recipe has new ingredients,
* and also insert the recipeIngredients of the recipe.
* @param recipe The recipe to be inserted
*/
public long insertRecipe(Recipe recipe) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ContentValues values = ContentValuesHelper.getValuesForRecipe(recipe);
long newRowId;
newRowId = db.insert(ChefBuddyContract.RecipeTable.TABLE_NAME, null, values);
if (newRowId != -1) { //Recipe inserted successfully, Insert ingredients
insertRecipeIngredientsOfRecipe(newRowId, recipe.getRecipeIngredients());
} else
throw new CouldNotInsertDataException("There was a problem inserting the Recipe: " + recipe.toString());
return newRowId;
}
/**
* Inserts a list of recipeIngredients associated to a recipe.
* @param recipeId The id of the recipe associated to the recipeIngredients
* @param recipeIngredients The list of recipeIngredients to be inserted
*/
public long[] insertRecipeIngredientsOfRecipe(long recipeId, List<RecipeIngredient> recipeIngredients) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Insert new ingredients, update their IDS
for (RecipeIngredient ri : recipeIngredients) {
if(ri.getIngredient().getId() == -1)
ri.getIngredient().setId(insertIngredient(ri.getIngredient()));
}
//Insert RecipeIngredients
long[] newRowIds = new long[recipeIngredients.size()];
for (int i = 0; i < recipeIngredients.size(); i++) {
ContentValues values = ContentValuesHelper.getValuesForRecipeIngredient(recipeId, recipeIngredients.get(i));
newRowIds[i] = db.insert(ChefBuddyContract.RecipeIngredientTable.TABLE_NAME, null, values);
if (newRowIds[i] == -1)
throw new CouldNotInsertDataException("There was a problem inserting the RecipeIngredient: " + recipeIngredients.toString());
}
return newRowIds;
}
// /**
// * Inserts a list of ingredients.
// * @param ingredients The list of ingredients to be inserted
// */
// public long[] insertIngredients(List<Ingredient> ingredients) throws CouldNotInsertDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// long[] newRowIds = new long[ingredients.size()];
// for (int i = 0; i < ingredients.size(); i++) {
// ContentValues values = getValuesForIngredient(ingredients.get(i));
// newRowIds[i] = db.insert(ChefBuddyContract.IngredientTable.TABLE_NAME, null, values);
// if (newRowIds[i] == -1)
// throw new CouldNotInsertDataException("There was a problem inserting the Ingredient: " + ingredients.toString());
// return newRowIds;
/**
* Inserts an ingredient.
* @param ingredient The ingredient to be inserted
*/
public long insertIngredient(Ingredient ingredient) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
long newRowId;
ContentValues values = ContentValuesHelper.getValuesForIngredient(ingredient);
newRowId = db.insert(ChefBuddyContract.IngredientTable.TABLE_NAME, null, values);
if (newRowId == -1)
throw new CouldNotInsertDataException("There was a problem inserting the Ingredient: " + ingredient.toString());
return newRowId;
}
/* Delete data from database */
/**
* Deletes a single Recipe, given its ID, also deletes its RecipeIngredients
* @param recipeId The ID of the recipe to delete
*/
public boolean deleteRecipe(long recipeId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
deleteRecipeIngredientsFromRecipe(recipeId);
return db.delete(ChefBuddyContract.RecipeTable.TABLE_NAME,
ChefBuddyContract.RecipeTable.COLUMN_ID.getName() + " =?",
new String[]{String.valueOf(recipeId)}) > 0;
}
/**
* Deletes a list of RecipeIngredients associated to a recipe
* @param recipeId The ID of the recipe fk
*/
public boolean deleteRecipeIngredientsFromRecipe(long recipeId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
return db.delete(ChefBuddyContract.RecipeIngredientTable.TABLE_NAME,
ChefBuddyContract.RecipeIngredientTable.COLUMN_RECIPE_FK.getName() + " =?",
new String[]{String.valueOf(recipeId)}) > 0;
}
// /* Get data from database */
// /**
// * Returns a List of Tasks (with Reminder and Attachments) which have TaskStatus.UNPROGRAMMED. Sorted Alphabetically by Task Title
// * @return A List of TaskViewModel
// */
// public List<TaskViewModel> getUnprogrammedTasks() throws CouldNotGetDataException {
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// List<TaskViewModel> result = new ArrayList<>();
// List<Task> tasks = new ArrayList<>();
// Cursor cursor = db.query(ChefBuddyContract.TaskTable.TABLE_NAME,
// null, ChefBuddyContract.TaskTable.COLUMN_NAME_STATUS.getName() + "=?",
// new String[]{TaskStatus.UNPROGRAMMED.name()}, null, null, null);
// try {
// while (cursor.moveToNext()) {
// Task current = getTaskFromCursor(cursor);
// //Try to get the attachments, if there are any
// current.setAttachments(getAttachmentsOfTask(current.getId()));
// //If Task !ReminderType.NONE, throw an error.
// if(current.getReminderType() != ReminderType.NONE)
// throw new CouldNotGetDataException("Error, found task with TaskStatus=UNPROGRAMMED with ReminderType != NONE");
// tasks.add(current);
// } finally {
// cursor.close();
// //Sort tasks by title
// Collections.sort(tasks, new UnprogrammedTasksByTitleComparator());
// //Create viewModel
// for (int i = 0; i < tasks.size(); i++) {
// result.add(new TaskViewModel(tasks.get(i), TaskViewModelType.UNPROGRAMMED_REMINDER));
// return result;
// /**
// * Returns a List of Tasks (with Reminder and Attachments) which have TaskStatus.PROGRAMMED AND ReminderType.LOCATION_BASED, sorted by Location
// * @return A List of TaskViewModel
// */
// public List<TaskViewModel> getLocationBasedTasks(Resources resources) throws CouldNotGetDataException, InvalidClassException {
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// List<TaskViewModel> result;
// List<Task> tasks = new ArrayList<>();
// Cursor cursor = db.query(ChefBuddyContract.TaskTable.TABLE_NAME,
// null, ChefBuddyContract.TaskTable.COLUMN_NAME_STATUS.getName() + "=?",
// new String[]{TaskStatus.PROGRAMMED.name()}, null, null, null);
// try {
// while (cursor.moveToNext()) {
// Task current = getTaskFromCursor(cursor);
// if(current.getReminderType() != ReminderType.LOCATION_BASED) //Skip NON location-based task
// continue;
// //Try to get the attachments, if there are any
// current.setAttachments(getAttachmentsOfTask(current.getId()));
// //If Task ReminderType.NONE, throw an error.
// if(current.getReminderType() == ReminderType.NONE)
// throw new CouldNotGetDataException("Error, Task with TaskStatus=PROGRAMMED has ReminderType=NONE");
// else
// current.setReminder(getReminderOfTask(current.getId(), current.getReminderType()));
// tasks.add(current);
// } finally {
// cursor.close();
// //Generate List<TaskViewModel>
// result = new TaskSortingUtil().generateProgrammedTaskHeaderList(tasks, TaskSortType.PLACE, resources);
// return result;
// /**
// * Returns a List of Tasks (with Reminder and Attachments) which have TaskStatus.PROGRAMMED
// * @param sortType TaskSortType enum value with which to sort results. By date or location
// * @return A List of TaskViewModel
// */
// public List<TaskViewModel> getProgrammedTasks(@NonNull TaskSortType sortType, boolean includeLocationBasedTasks, Resources resources) throws CouldNotGetDataException, InvalidClassException {
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// List<TaskViewModel> result;
// List<Task> tasks = new ArrayList<>();
// Cursor cursor = db.query(ChefBuddyContract.TaskTable.TABLE_NAME,
// null, ChefBuddyContract.TaskTable.COLUMN_NAME_STATUS.getName() + "=?",
// new String[]{TaskStatus.PROGRAMMED.name()}, null, null, null);
// try {
// while (cursor.moveToNext()) {
// Task current = getTaskFromCursor(cursor);
// if(!includeLocationBasedTasks && current.getReminderType() == ReminderType.LOCATION_BASED) //Skip location-based task
// continue;
// //Try to get the attachments, if there are any
// current.setAttachments(getAttachmentsOfTask(current.getId()));
// //If Task ReminderType.NONE, throw an error.
// if(current.getReminderType() == ReminderType.NONE)
// throw new CouldNotGetDataException("Error, Task with TaskStatus=PROGRAMMED has ReminderType=NONE");
// else
// current.setReminder(getReminderOfTask(current.getId(), current.getReminderType()));
// tasks.add(current);
// } finally {
// cursor.close();
// //Generate List<TaskViewModel>
// result = new TaskSortingUtil().generateProgrammedTaskHeaderList(tasks, sortType, resources);
// return result;
// /**
// * Returns a List of Tasks (with Reminder and Attachments) which have TaskStatus.DONE
// * @param sortType TaskSortType enum value with which to sort results. By date or location
// * @return A List of TaskViewModel
// */
// public List<TaskViewModel> getDoneTasks(@NonNull TaskSortType sortType, Resources resources) throws CouldNotGetDataException, InvalidClassException {
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// List<TaskViewModel> result = new ArrayList<>();
// List<Task> tasks = new ArrayList<>();
// Cursor cursor = db.query(ChefBuddyContract.TaskTable.TABLE_NAME,
// null, ChefBuddyContract.TaskTable.COLUMN_NAME_STATUS.getName() + "=?",
// new String[]{TaskStatus.DONE.name()}, null, null, null);
// try {
// while (cursor.moveToNext()) {
// Task current = getTaskFromCursor(cursor);
// //Try to get the attachments, if there are any
// current.setAttachments(getAttachmentsOfTask(current.getId()));
// //If Task has reminder, get it
// if(current.getReminderType() != ReminderType.NONE)
// current.setReminder(getReminderOfTask(current.getId(), current.getReminderType()));
// tasks.add(current);
// } finally {
// cursor.close();
// //Generate List<TaskViewModel> This List will be sorted and grouped!
// result = new TaskSortingUtil().generateDoneTaskHeaderList(tasks, sortType, resources);
// return result;
// /**
// * Returns a List of Tasks (Status:PROGRAMMED) which have Location-Based reminders of a particular Place, set to trigger either entering or exiting or both.
// * @param placeId The ID of the place with which to look for Tasks
// */
// public List<Task> getLocationBasedTasksAssociatedWithPlace(int placeId, int geofenceTransition) throws CouldNotGetDataException {
// List<Task> tasks = new ArrayList<>();
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// Cursor cursor = null;
// switch (geofenceTransition) {
// case -1: //Any
// cursor = db.query(ChefBuddyContract.LocationBasedReminderTable.TABLE_NAME, null,
// ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_PLACE_FK.getName() + "=?",
// new String[] {String.valueOf(placeId)}, null, null, null);
// break;
// case Geofence.GEOFENCE_TRANSITION_DWELL:
// case Geofence.GEOFENCE_TRANSITION_ENTER:
// cursor = db.query(ChefBuddyContract.LocationBasedReminderTable.TABLE_NAME, null,
// ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_PLACE_FK.getName() + "=? AND " +
// ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TRIGGER_ENTERING.getName() + "=?",
// new String[] {String.valueOf(placeId), "true"}, null, null, null);
// break;
// case Geofence.GEOFENCE_TRANSITION_EXIT:
// cursor = db.query(ChefBuddyContract.LocationBasedReminderTable.TABLE_NAME, null,
// ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_PLACE_FK.getName() + "=? AND " +
// ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TRIGGER_EXITING.getName() + "=?",
// new String[] {String.valueOf(placeId), "true"}, null, null, null);
// break;
// if(cursor != null) {
// try {
// while (cursor.moveToNext()) {
// int taskId = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TASK_FK.getName()));
// Task task = getTask(taskId);
// if(task.getStatus().equals(TaskStatus.PROGRAMMED))
// tasks.add(task);
// } finally {
// cursor.close();
// return tasks;
// /**
// * Returns the next PROGRAMMED task(With ONE-TIME or REPEATING reminder) to occur
// * @param alreadyTriggeredTaskList an optional task list to not include in the search
// * @return A single TaskTriggerViewModel or null of there are no tasks
// */
// public TaskTriggerViewModel getNextTaskToTrigger(@NonNull List<Integer> alreadyTriggeredTaskList) throws CouldNotGetDataException {
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// Task nextTaskToTrigger = null;
// Calendar triggerDate = null;
// Time triggerTime = null;
// Cursor cursor = db.query(ChefBuddyContract.TaskTable.TABLE_NAME,
// null, ChefBuddyContract.TaskTable.COLUMN_NAME_STATUS.getName() + "=?",
// new String[]{TaskStatus.PROGRAMMED.name()}, null, null, null);
// try {
// while (cursor.moveToNext()) {
// Task current = getTaskFromCursor(cursor);
// if(alreadyTriggeredTaskList.contains(current.getId())) //Skip
// continue;
// try {
// current.setReminder(getReminderOfTask(current.getId(), current.getReminderType()));
// }catch (CouldNotGetDataException | SQLiteConstraintException e ) {
// throw new CouldNotGetDataException("Error fetching reminder for task ID" + current.getId(), e);
// //TODO: this filter could be made on db query.
// if( current.getReminderType().equals(ReminderType.ONE_TIME) || current.getReminderType().equals(ReminderType.REPEATING) ) {
// if(TaskUtil.checkIfOverdue(current.getReminder())) //Skip overdue reminders
// continue;
// if(nextTaskToTrigger == null) {
// nextTaskToTrigger = current;
// triggerDate = (current.getReminderType().equals(ReminderType.ONE_TIME) ? ((OneTimeReminder)current.getReminder() ).getDate() : TaskUtil.getRepeatingReminderNextCalendar( (RepeatingReminder)current.getReminder()) );
// triggerTime = (current.getReminderType().equals(ReminderType.ONE_TIME) ? ((OneTimeReminder)current.getReminder() ).getTime() : ((RepeatingReminder)current.getReminder()).getTime() );
// continue;
// if(current.getReminderType().equals(ReminderType.ONE_TIME)) {
// OneTimeReminder otr = (OneTimeReminder)current.getReminder();
// Calendar currentDate = CalendarUtil.getCalendarFromDateAndTime(otr.getDate(), otr.getTime());
// if(currentDate.compareTo(triggerDate) < 0 ) {
// nextTaskToTrigger = current;
// triggerDate = currentDate;
// triggerTime = otr.getTime();
// continue;
// if(current.getReminderType().equals(ReminderType.REPEATING)) {
// RepeatingReminder rr = (RepeatingReminder)current.getReminder();
// Calendar currentDate = TaskUtil.getRepeatingReminderNextCalendar(rr);
// if(currentDate == null) continue; //Overdue
// if(currentDate.compareTo(triggerDate) < 0 ) {
// nextTaskToTrigger = current;
// triggerDate = currentDate;
// triggerTime = rr.getTime();
// continue;
// } finally {
// cursor.close();
// if(nextTaskToTrigger == null) return null;
// return new TaskTriggerViewModel(nextTaskToTrigger, triggerDate, triggerTime);
// /**
// * Returns a Task (with Reminder and Attachments) given a taskId
// * @param taskId The ID of the Task to get.
// */
// public Task getTask(int taskId) throws CouldNotGetDataException, SQLiteConstraintException {
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// Cursor cursor = db.query(ChefBuddyContract.TaskTable.TABLE_NAME, null, ChefBuddyContract.PlaceTable._ID + "=?",
// new String[]{String.valueOf(taskId)}, null, null, null);
// if (cursor.getCount() == 0)
// throw new CouldNotGetDataException("Specified Task not found in the database. Passed id=" + taskId);
// if (cursor.getCount() > 1)
// throw new SQLiteConstraintException("Database UNIQUE constraint failure, more than one record found. Passed value=" + taskId);
// cursor.moveToNext();
// Task task = getTaskFromCursor(cursor);
// task.setAttachments(getAttachmentsOfTask(taskId));
// if(task.getReminderType() != ReminderType.NONE)
// task.setReminder(getReminderOfTask(taskId, task.getReminderType()));
// return task;
// /**
// * Returns a List of all the Places in the database.
// */
// public List<Place> getPlaces() {
// List<Place> places = new ArrayList<>();
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// Cursor cursor = db.query(ChefBuddyContract.PlaceTable.TABLE_NAME, null, null, null, null, null, null);
// try {
// while (cursor.moveToNext()) {
// places.add(getPlaceFromCursor(cursor));
// } finally {
// cursor.close();
// return places;
// /**
// * Returns a List of Places associated with PROGRAMMED tasks with location-based reminders
// */
// public List<Place> getActivePlaces() {
// List<Place> places = new ArrayList<>();
// int taskCount;
// Place place;
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// Cursor cursor = db.query(ChefBuddyContract.PlaceTable.TABLE_NAME, null, null, null, null, null, null);
// try {
// while (cursor.moveToNext()) {
// place = getPlaceFromCursor(cursor);
// try {
// taskCount = getLocationBasedTasksAssociatedWithPlace(place.getId(), -1).size();
// } catch (CouldNotGetDataException e) {
// taskCount = 0;
// if(taskCount > 0)
// places.add(place);
// } finally {
// cursor.close();
// return places;
// /**
// * Returns a Place given a placeId.
// * @param placeId The id of the place
// */
// public Place getPlace(int placeId) throws PlaceNotFoundException, SQLiteConstraintException {
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// Cursor cursor = db.query(ChefBuddyContract.PlaceTable.TABLE_NAME, null, ChefBuddyContract.PlaceTable._ID + "=?",
// new String[]{String.valueOf(placeId)}, null, null, null);
// if (cursor.getCount() == 0)
// throw new PlaceNotFoundException("Specified Place not found in the database. Passed id=" + placeId);
// if (cursor.getCount() > 1)
// throw new SQLiteConstraintException("Database UNIQUE constraint failure, more than one record found. Passed value=" + placeId);
// cursor.moveToNext();
// return getPlaceFromCursor(cursor);
// /**
// * Returns a List of Attachments associated to a Task.
// * @param taskId The id of the Task
// */
// public ArrayList<Attachment> getAttachmentsOfTask(int taskId) {
// ArrayList<Attachment> attachments = new ArrayList<>();
// SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
// Cursor cursor = db.query(ChefBuddyContract.AttachmentTable.TABLE_NAME, null,
// ChefBuddyContract.AttachmentTable.COLUMN_NAME_TASK_FK.getName() + "=?",
// new String[]{String.valueOf(taskId)}, null, null, null);
// try {
// while (cursor.moveToNext()) {
// attachments.add(getAttachmentFromCursor(cursor));
// } finally {
// cursor.close();
// return attachments;
// /**
// * Returns a Reminder given its taskId and reminderType
// * @param taskId The ID of the task
// * @param reminderType The Type of reminder
// */
// public Reminder getReminderOfTask(int taskId, @NonNull ReminderType reminderType) throws CouldNotGetDataException, SQLiteConstraintException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// Reminder reminder;
// String tableName, whereClause;
// switch (reminderType) {
// case ONE_TIME:
// whereClause = ChefBuddyContract.OneTimeReminderTable.COLUMN_NAME_TASK_FK.getName() + " =?";
// tableName = ChefBuddyContract.OneTimeReminderTable.TABLE_NAME;
// break;
// case REPEATING:
// whereClause = ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_TASK_FK.getName() + " =?";
// tableName = ChefBuddyContract.RepeatingReminderTable.TABLE_NAME;
// break;
// case LOCATION_BASED:
// whereClause = ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TASK_FK.getName() + " =?";
// tableName = ChefBuddyContract.LocationBasedReminderTable.TABLE_NAME;
// break;
// default:
// throw new CouldNotGetDataException("ReminderType is invalid. Type=" + reminderType);
// Cursor cursor = db.query(tableName, null, whereClause, new String[]{String.valueOf(taskId)}, null, null, null);
// try {
// if (cursor.getCount() == 0)
// throw new CouldNotGetDataException("Specified Reminder not found in the database. Passed id=" + taskId);
// if (cursor.getCount() > 1)
// throw new SQLiteConstraintException("Database UNIQUE constraint failure, more than one Reminder found. Passed id=" + taskId);
// cursor.moveToNext();
// switch (reminderType) {
// case ONE_TIME:
// reminder = getOneTimeReminderFromCursor(cursor);
// break;
// case REPEATING:
// reminder = getRepeatingReminderFromCursor(cursor);
// break;
// case LOCATION_BASED:
// reminder = getLocationBasedReminderFromCursor(cursor);
// int placeId = ((LocationBasedReminder)reminder).getPlaceId();
// try {
// ((LocationBasedReminder)reminder).setPlace(getPlace(placeId));
// } catch (PlaceNotFoundException | SQLiteConstraintException e) {
// throw new CouldNotGetDataException("Error trying to get Place for Location-based Reminder", e);
// break;
// default:
// throw new CouldNotGetDataException("ReminderType is invalid. Type=" + reminderType);
// } finally {
// cursor.close();
// return reminder;
// /* Delete data from database */
// /**
// * Deletes a single Place, given its ID, also deletes Location-based reminders associated with place and updates Task ReminderType to NONE
// * @param placeId The ID of the place to delete
// */
// public boolean deletePlace(int placeId) throws CouldNotDeleteDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// List<Task> tasks;
// try {
// tasks = getLocationBasedTasksAssociatedWithPlace(placeId, -1);
// }catch (CouldNotGetDataException e) {
// throw new CouldNotDeleteDataException("Error getting Task list associated with Place. PlaceID=" + placeId, e);
// if(tasks.size() > 0) { //Remove Location-based reminders from task, and update task ReminderType to NONE.
// for (Task task : tasks) {
// deleteReminderOfTask(task.getId());
// task.setStatus(TaskStatus.UNPROGRAMMED);
// task.setReminderType(ReminderType.NONE);
// try {
// updateTask(task);
// } catch (CouldNotUpdateDataException e) {
// throw new CouldNotDeleteDataException("Error updating RemidnerType of Task to NONE. TaskID=" + task.getId(), e);
// return db.delete(ChefBuddyContract.PlaceTable.TABLE_NAME,
// ChefBuddyContract.PlaceTable._ID + " =?",
// new String[]{String.valueOf(placeId)}) > 0;
// /**
// * Deletes all Attachments linked to an Task, given the task's ID
// * @param taskId The ID of the reminder whose attachments will be deleted
// */
// public boolean deleteAttachmentsOfTask(int taskId) throws CouldNotDeleteDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// return db.delete(ChefBuddyContract.AttachmentTable.TABLE_NAME,
// ChefBuddyContract.AttachmentTable.COLUMN_NAME_TASK_FK.getName() + " =?",
// new String[]{String.valueOf(taskId)}) > 0;
// /**
// * Deletes a single attachment, given its ID
// * @param attachmentId The ID of the attachment to be deleted
// */
// public boolean deleteAttachment(int attachmentId) throws CouldNotDeleteDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// return db.delete(ChefBuddyContract.AttachmentTable.TABLE_NAME,
// ChefBuddyContract.AttachmentTable._ID + " =?",
// new String[]{String.valueOf(attachmentId)}) > 0;
// /**
// * Deletes the Reminder of type ReminderType associated to a Task
// * @param taskId The ID of the task
// */
// public void deleteReminderOfTask(int taskId) throws CouldNotDeleteDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// String tableName, whereClause;
// whereClause = ChefBuddyContract.OneTimeReminderTable.COLUMN_NAME_TASK_FK.getName() + " =?";
// tableName = ChefBuddyContract.OneTimeReminderTable.TABLE_NAME;
// db.delete(tableName, whereClause, new String[]{String.valueOf(taskId)});
// whereClause = ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_TASK_FK.getName() + " =?";
// tableName = ChefBuddyContract.RepeatingReminderTable.TABLE_NAME;
// db.delete(tableName, whereClause, new String[]{String.valueOf(taskId)});
// whereClause = ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TASK_FK.getName() + " =?";
// tableName = ChefBuddyContract.LocationBasedReminderTable.TABLE_NAME;
// db.delete(tableName, whereClause, new String[]{String.valueOf(taskId)});
// /**
// * Deletes a Task and associated Attachments and Reminder
// * @param taskId The ID of the task
// */
// public boolean deleteTask(int taskId) throws CouldNotDeleteDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// Task task;
// try {
// task = getTask(taskId);
// } catch (CouldNotGetDataException e) {
// throw new CouldNotDeleteDataException("Failed to get task from database. TaskID=" + taskId, e);
// //Delete task's attachments
// deleteAttachmentsOfTask(taskId);
// //If task has a reminder, delete it
// if(task.getReminderType() != ReminderType.NONE) {
// deleteReminderOfTask(taskId);
// //Finally, delete the task
// return db.delete(ChefBuddyContract.TaskTable.TABLE_NAME,
// ChefBuddyContract.TaskTable._ID + " =?",
// new String[]{String.valueOf(taskId)}) > 0;
/* Update data on database */
/**
* Updates the information stored about a Recipe
* @param recipe The Recipe to update
*/
public long updateRecipe(Recipe recipe) throws CouldNotUpdateDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
try {
deleteRecipeIngredientsFromRecipe(recipe.getId());
insertRecipeIngredientsOfRecipe(recipe.getId(), recipe.getRecipeIngredients());
} catch (CouldNotDeleteDataException e) {
throw new CouldNotUpdateDataException("Error deleting current recipe ingredients", e);
} catch (CouldNotInsertDataException e) {
throw new CouldNotUpdateDataException("Error inserting new recipe ingredients", e);
}
int count = db.update(
ChefBuddyContract.RecipeTable.TABLE_NAME,
ContentValuesHelper.getValuesForRecipe(recipe),
ChefBuddyContract.RecipeTable.COLUMN_ID.getName() + " =? ",
new String[] {String.valueOf(recipe.getId())} );
return count;
}
/**
* Updates the information on WheelRecipeTable
* @param recipes The Recipe IDs to insert into table
*/
public void updateWheelRecipes(List<Recipe> recipes) {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Dump the whole table
db.delete(ChefBuddyContract.WheelRecipeTable.TABLE_NAME, null, null);
for (Recipe r : recipes) {
ContentValues values = ContentValuesHelper.getWheelRecipeValuesForRecipe(r);
db.insert(ChefBuddyContract.WheelRecipeTable.TABLE_NAME, null, values);
}
}
/**
* Updates the information stored about a daily recipe
* @param date The date to update
* @param recipeId The recipeId to set the daily recipe to
*/
public void updateDailyRecipeForDate(Calendar date, long recipeId) {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Delete old data
int rows = db.delete(ChefBuddyContract.DailyRecipeTable.TABLE_NAME,
ChefBuddyContract.DailyRecipeTable.COLUMN_YEAR.getName() + "=? AND " +
ChefBuddyContract.DailyRecipeTable.COLUMN_MONTH.getName() + "=? AND " +
ChefBuddyContract.DailyRecipeTable.COLUMN_DAY.getName() + "=?",
new String[] {String.valueOf(date.get(Calendar.YEAR)),
String.valueOf(date.get(Calendar.MONTH)),
String.valueOf(date.get(Calendar.DAY_OF_MONTH))});
if(recipeId != -1) {
ContentValues contentValues = ContentValuesHelper.getDailyRecipeValues(date, recipeId);
db.insert(ChefBuddyContract.DailyRecipeTable.TABLE_NAME, null, contentValues);
}
}
// /* Update data on database */
// /**
// * Updates the information stored about a Place
// * @param place The Place to update
// */
// public long updatePlace(Place place) throws CouldNotUpdateDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// int count = db.update(
// ChefBuddyContract.PlaceTable.TABLE_NAME,
// getValuesFromPlace(place),
// ChefBuddyContract.PlaceTable._ID + " =? ",
// new String[] {String.valueOf(place.getId())} );
// return count;
// /**
// * Deletes previous attachments of a task and reinserts them
// * @param task The Task whose attachments to delete and reinsert
// */
// public long[] updateAttachmentsOfTask(Task task) throws CouldNotUpdateDataException {
// try {
// deleteAttachmentsOfTask(task.getId());
// } catch (CouldNotDeleteDataException e) {
// throw new CouldNotUpdateDataException("Could not delete attachments while updating.", e.getCause());
// long[] insertedRowIds;
// try {
// insertedRowIds = insertAttachmentsOfTask(task.getId(), task.getAttachments());
// } catch (CouldNotInsertDataException e) {
// throw new CouldNotUpdateDataException("Could not insert attachments while updating.", e.getCause());
// return insertedRowIds;
// /**
// * Updates the information stored about a List of Attachments
// * @param attachments The Attachments to update
// */
// public long[] updateAttachments(ArrayList<Attachment> attachments) throws CouldNotUpdateDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// long[] updatedRowIds = new long[attachments.size()];
// for (int i = 0; i < attachments.size(); i++)
// updatedRowIds[i] = updateAttachment(attachments.get(i));
// return updatedRowIds;
// /**
// * Updates the information stored about an Attachment
// * @param attachment The Attachment to update
// */
// public long updateAttachment(Attachment attachment) throws CouldNotUpdateDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// long updatedRowIds = db.update(ChefBuddyContract.AttachmentTable.TABLE_NAME,
// getValuesFromAttachment(attachment),
// ChefBuddyContract.AttachmentTable._ID + " =? ",
// new String[]{String.valueOf(attachment.getId())});
// return updatedRowIds;
// /**
// * Updates the information stored about a Reminder
// * @param reminder The Reminder to update
// */
// public boolean updateReminderOfTask(Reminder reminder, int taskId) throws CouldNotUpdateDataException {
// //Need to delete old reminder and insert new one
// //Old and New reminderType may be different, which are stored in different tables
// try {
// deleteReminderOfTask(taskId);
// }catch (CouldNotDeleteDataException e) {
// throw new CouldNotUpdateDataException("Error while deleting old reminder in dao.updateReminder(). Reminder=" + reminder.toString(), e);
// if(reminder != null) {
// try {
// insertReminderOfTask(taskId, reminder);
// }catch (CouldNotInsertDataException e) {
// throw new CouldNotUpdateDataException("Error while inserting new reminder in dao.updateReminder(). Reminder=" + reminder.toString(), e);
// return true;
// /**
// * Updates the information stored about a Task, its Reminder and its Attachments.
// * @param task The Task to update
// */
// public long updateTask(Task task) throws CouldNotUpdateDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// updateAttachmentsOfTask(task);
// updateReminderOfTask(task.getReminder(), task.getId());
// return db.update(
// ChefBuddyContract.TaskTable.TABLE_NAME,
// getValuesFromTask(task),
// ChefBuddyContract.TaskTable._ID + " =? ",
// new String[] {String.valueOf(task.getId())} );
// /* Insert data into database */
// /**
// * Inserts a new Place into the database.
// * @param place The Place to be inserted
// */
// public long insertPlace(Place place) throws CouldNotInsertDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// ContentValues values = getValuesFromPlace(place);
// long newRowId;
// newRowId = db.insert(ChefBuddyContract.PlaceTable.TABLE_NAME, null, values);
// if (newRowId == -1)
// throw new CouldNotInsertDataException("There was a problem inserting the Place: " + place.toString());
// return newRowId;
// /**
// * Inserts a List of Attachments associated to an Task, into the database.
// * @param taskId The id of the Task associated to the Attachments
// * @param attachments The List of Attachments to be inserted
// */
// public long[] insertAttachmentsOfTask(int taskId, List<Attachment> attachments) throws CouldNotInsertDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// long[] newRowIds = new long[attachments.size()];
// for (int i = 0; i < attachments.size(); i++) {
// Attachment attachment = attachments.get(i);
// attachment.setTaskId(taskId);
// ContentValues values = getValuesFromAttachment(attachment);
// newRowIds[i] = db.insert(ChefBuddyContract.AttachmentTable.TABLE_NAME, null, values);
// if (newRowIds[i] == -1)
// throw new CouldNotInsertDataException("There was a problem inserting the Attachment: " + attachments.toString());
// return newRowIds;
// /**
// * Inserts a new Reminder into the database.
// * @param taskId The id of the Task associated to the Reminder
// * @param reminder The Reminder to insert
// */
// public long insertReminderOfTask(int taskId, Reminder reminder) throws CouldNotInsertDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// ContentValues values;
// String tableName;
// reminder.setTaskId(taskId);
// switch (reminder.getType()) {
// case ONE_TIME:
// values = getValuesFromOneTimeReminder((OneTimeReminder) reminder);
// tableName = ChefBuddyContract.OneTimeReminderTable.TABLE_NAME;
// break;
// case REPEATING:
// values = getValuesFromRepeatingReminder((RepeatingReminder) reminder);
// tableName = ChefBuddyContract.RepeatingReminderTable.TABLE_NAME;
// break;
// case LOCATION_BASED:
// values = getValuesFromLocationBasedReminder((LocationBasedReminder) reminder);
// tableName = ChefBuddyContract.LocationBasedReminderTable.TABLE_NAME;
// break;
// default:
// throw new CouldNotInsertDataException("ReminderType is invalid. Type=" + reminder.getType());
// long newRowId;
// newRowId = db.insert(tableName, null, values);
// if (newRowId == -1)
// throw new CouldNotInsertDataException("There was a problem inserting the Reminder: " + reminder.toString());
// return newRowId;
// /**
// * Inserts a new Task and its associated Reminder and Attachments into the database.
// * @param task The Task (and associated Reminder and Attachments) to insert
// */
// public long insertTask(Task task) throws CouldNotInsertDataException {
// SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
// ContentValues values = getValuesFromTask(task);
// long newRowId;
// newRowId = db.insert(ChefBuddyContract.TaskTable.TABLE_NAME, null, values);
// if (newRowId == -1)
// throw new CouldNotInsertDataException("There was a problem inserting the Task: " + task.toString());
// //Insert Attachments
// if (task.getAttachments() != null && task.getAttachments().size() > 0) {
// try {
// insertAttachmentsOfTask((int)newRowId, task.getAttachments());
// } catch (CouldNotInsertDataException e) {
// throw new CouldNotInsertDataException("There was a problem inserting the Attachments while inserting the Task: " + task.toString(), e);
// //Insert Reminder if it exists
// if (task.getReminder() != null) {
// try {
// insertReminderOfTask((int)newRowId, task.getReminder());
// } catch (CouldNotInsertDataException e) {
// throw new CouldNotInsertDataException("There was a problem inserting the Reminder while inserting the Task: " + task.toString(), e);
// return newRowId;
/* Cursor to Model */
private Recipe getRecipeFromCursor(Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.RecipeTable.COLUMN_ID.getName()));
String name = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RecipeTable.COLUMN_NAME.getName()));
Servings servings;
try {
servings = Servings.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RecipeTable.COLUMN_SERVINGS.getName())));
} catch (IllegalArgumentException e) {
servings = null;
}
PreparationTime preparationTime;
try {
preparationTime = PreparationTime.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RecipeTable.COLUMN_PREPARATION_TIME.getName())));
} catch (IllegalArgumentException e) {
preparationTime = null;
}
String directions = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RecipeTable.COLUMN_DIRECTIONS.getName()));
String imageFilenamesStr = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RecipeTable.COLUMN_IMAGE_FILENAMES.getName()));
return new Recipe(id, name, servings, preparationTime, directions, imageFilenamesStr);
}
private RecipeIngredient getRecipeIngredientFromCursor(Cursor cursor) {
/* Ingredient fields */
long ingredientId = cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.IngredientTable.COLUMN_ID.getName()));
String ingredientName = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.IngredientTable.COLUMN_NAME.getName()));
/* RecipeIngredient fields */
long recipeIngredientId = cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.RecipeIngredientTable.COLUMN_ID.getName()));
String recipeIngredientAmount = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RecipeIngredientTable.COLUMN_AMOUNT.getName()));
Measurement recipeIngredientMeasurement;
try {
recipeIngredientMeasurement = Measurement.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RecipeIngredientTable.COLUMN_MEASUREMENT.getName())));
} catch (IllegalArgumentException e) {
recipeIngredientMeasurement = Measurement.NONE;
}
return new RecipeIngredient(recipeIngredientId, recipeIngredientAmount, recipeIngredientMeasurement, new Ingredient(ingredientId, ingredientName));
}
private Ingredient getIngredientFromCursor(Cursor cursor) {
long ingredientId = cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.IngredientTable.COLUMN_ID.getName()));
String ingredientName = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.IngredientTable.COLUMN_NAME.getName()));
return new Ingredient(ingredientId, ingredientName);
}
private long getRecipeIdFromWheelRecipeCursor(Cursor cursor) {
long recipeId = cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.WheelRecipeTable.COLUMN_RECIPE.getName()));
return recipeId;
}
private DailyRecipe getDailyRecipeFromCursor(Cursor cursor) {
//This cursor will contain data from recipe and daily_recipe tables
//Grab the recipe
Recipe recipe = getRecipeFromCursor(cursor);
//Grab the daily_recipe data
int year = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.DailyRecipeTable.COLUMN_YEAR.getName()));
int month = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.DailyRecipeTable.COLUMN_MONTH.getName()));
int day = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.DailyRecipeTable.COLUMN_DAY.getName()));
Calendar cal = CalendarUtil.getZeroedCalendarFromYearMonthDay(year, month, day);
return new DailyRecipe(cal, recipe);
}
// /* Cursor to Model */
// private Task getTaskFromCursor(Cursor cursor) {
// int id = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.TaskTable._ID));
// TaskStatus status = TaskStatus.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.TaskTable.COLUMN_NAME_STATUS.getName())));
// String title = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.TaskTable.COLUMN_NAME_TITLE.getName()));
// String description = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.TaskTable.COLUMN_NAME_DESCRIPTION.getName()));
// TaskCategory category = TaskCategory.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.TaskTable.COLUMN_NAME_CATEGORY.getName())));
// ReminderType reminderType;
// try {
// reminderType = ReminderType.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.TaskTable.COLUMN_NAME_REMINDER_TYPE.getName())));
// reminderType = null;
// Calendar doneDate = null;
// if (status == TaskStatus.DONE) {
// long doneDateLong = cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.TaskTable.COLUMN_NAME_DONE_DATE.getName()));
// if (doneDateLong != -1) {
// doneDate = Calendar.getInstance();
// doneDate.setTimeInMillis(doneDateLong);
// return new Task(id, status, title, description, category, reminderType, null, doneDate);
// private OneTimeReminder getOneTimeReminderFromCursor(Cursor cursor) {
// int id = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.OneTimeReminderTable._ID));
// int taskId = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.OneTimeReminderTable.COLUMN_NAME_TASK_FK.getName()));
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.OneTimeReminderTable.COLUMN_NAME_DATE.getName())));
// Time time = new Time(cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.OneTimeReminderTable.COLUMN_NAME_TIME.getName())));
// time.setDisplayTimeFormat(SharedPreferenceUtil.getTimeFormat(mContext));
// return new OneTimeReminder(id, taskId, date, time);
// private RepeatingReminder getRepeatingReminderFromCursor(Cursor cursor) {
// int id = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable._ID));
// int taskId = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_TASK_FK.getName()));
// Calendar date = Calendar.getInstance();
// date.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_DATE.getName())));
// Time time = new Time(cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_TIME.getName())));
// time.setDisplayTimeFormat(SharedPreferenceUtil.getTimeFormat(mContext));
// ReminderRepeatType repeatType = ReminderRepeatType.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_REPEAT_TYPE.getName())));
// int repeatInterval = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_REPEAT_INTERVAL.getName()));
// ReminderRepeatEndType repeatEndType = ReminderRepeatEndType.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_REPEAT_END_TYPE.getName())));
// int repeatEndNumberOfEvents = -1;
// if(repeatEndType == ReminderRepeatEndType.FOR_X_EVENTS)
// repeatEndNumberOfEvents = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_REPEAT_END_NUMBER_OF_EVENTS.getName()));
// Calendar repeatEndDate = null;
// if(repeatEndType == ReminderRepeatEndType.UNTIL_DATE) {
// repeatEndDate = Calendar.getInstance();
// repeatEndDate.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(ChefBuddyContract.RepeatingReminderTable.COLUMN_NAME_REPEAT_END_DATE.getName())));
// return new RepeatingReminder(id, taskId, date, time, repeatType, repeatInterval, repeatEndType, repeatEndNumberOfEvents, repeatEndDate);
// private LocationBasedReminder getLocationBasedReminderFromCursor(Cursor cursor) {
// int id = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.LocationBasedReminderTable._ID));
// int taskId = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TASK_FK.getName()));
// int placeId = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_PLACE_FK.getName()));
// boolean triggerEntering = Boolean.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TRIGGER_ENTERING.getName())));
// boolean triggerExiting = Boolean.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.LocationBasedReminderTable.COLUMN_NAME_TRIGGER_EXITING.getName())));
// return new LocationBasedReminder(id, taskId, placeId, null, triggerEntering, triggerExiting);
// private Place getPlaceFromCursor(Cursor cursor) {
// int id = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.PlaceTable._ID));
// String alias = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.PlaceTable.COLUMN_NAME_ALIAS.getName()));
// String address = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.PlaceTable.COLUMN_NAME_ADDRESS.getName()));
// double latitude = cursor.getDouble(cursor.getColumnIndex(ChefBuddyContract.PlaceTable.COLUMN_NAME_LATITUDE.getName()));
// double longitude = cursor.getDouble(cursor.getColumnIndex(ChefBuddyContract.PlaceTable.COLUMN_NAME_LONGITUDE.getName()));
// int radius = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.PlaceTable.COLUMN_NAME_RADIUS.getName()));
// boolean isOneOff = Boolean.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.PlaceTable.COLUMN_NAME_IS_ONE_OFF.getName())));
// return new Place(id, alias, address, latitude, longitude, radius, isOneOff);
// private Attachment getAttachmentFromCursor(Cursor cursor) {
// int id = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.AttachmentTable._ID));
// int reminderId = cursor.getInt(cursor.getColumnIndex(ChefBuddyContract.AttachmentTable.COLUMN_NAME_TASK_FK.getName()));
// AttachmentType attachmentType = AttachmentType.valueOf(cursor.getString(cursor.getColumnIndex(ChefBuddyContract.AttachmentTable.COLUMN_NAME_TYPE.getName())));
// String textContent = cursor.getString(cursor.getColumnIndex(ChefBuddyContract.AttachmentTable.COLUMN_NAME_CONTENT_TEXT.getName()));
// byte[] blobContent = cursor.getBlob(cursor.getColumnIndex(ChefBuddyContract.AttachmentTable.COLUMN_NAME_CONTENT_BLOB.getName()));
// switch (attachmentType) {
// case AUDIO:
// return new AudioAttachment(id, reminderId, textContent);
// case IMAGE:
// return new ImageAttachment(id, reminderId, blobContent, textContent);
// case TEXT:
// return new TextAttachment(id, reminderId, textContent);
// case LINK:
// return new LinkAttachment(id, reminderId, textContent);
// case LIST:
// return new ListAttachment(id, reminderId, textContent);
// default:
// throw new InvalidParameterException("AttachmentType is invalid. Value = " + attachmentType);
}
|
/**
* Clase Alumno
* @author curso14/7803
* @since 25/11/2015
* @version 1.0
* @since 18/11/2015
* <br>
* <p>
* Esta clase se corresponde con los metodos principales
* de acceso y gestin de la tabla alumnos.
* </p>
*/
package alumnos;
import java.sql.Date;
public class Alumno {
private int idAlumno;
private String nombre;
private String apellidos;
private String DNI;
private String email;
private int telefono;
private String direccion;
private int codigoPostal;
private String municipio;
private String provincia;
private String pais;
private Date fechaNacimiento;
public Alumno(int idAlumno, String nombre, String apellidos, String dNI, String email, int telefono,
String direccion, int codigoPostal, String municipio, String provincia, String pais, Date fechaNacimiento) {
super();
this.idAlumno = idAlumno;
this.nombre = nombre;
this.apellidos = apellidos;
DNI = dNI;
this.email = email;
this.telefono = telefono;
this.direccion = direccion;
this.codigoPostal = codigoPostal;
this.municipio = municipio;
this.provincia = provincia;
this.pais = pais;
this.fechaNacimiento = fechaNacimiento;
}
public int getIdAlumno() {
return idAlumno;
}
public void setIdAlumno(int idAlumno) {
this.idAlumno = idAlumno;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getDNI() {
return DNI;
}
public void setDNI(String dNI) {
DNI = dNI;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getTelefono() {
return telefono;
}
public void setTelefono(int telefono) {
this.telefono = telefono;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public int getCodigoPostal() {
return codigoPostal;
}
public void setCodigoPostal(int codigoPostal) {
this.codigoPostal = codigoPostal;
}
public String getMunicipio() {
return municipio;
}
public void setMunicipio(String municipio) {
this.municipio = municipio;
}
public String getProvincia() {
return provincia;
}
public void setProvincia(String provincia) {
this.provincia = provincia;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public void insertar() {
}
public void modificar(){
}
public void consultar() {
}
public void eliminar(){
}
}
|
package org.lambda.query;
import com.spun.util.ObjectUtils;
import com.spun.util.StringUtils;
import org.approvaltests.Approvals;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.lambda.utils.Range;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class QueryTest
{
@Test
public void testQueryAll() throws Exception
{
List<Integer> numbers = Arrays.asList(3, 5, 7, 9);
assertEquals(true, Query.all(numbers, n -> 3 <= n));
assertEquals(false, Query.all(numbers, n -> 4 <= n));
}
@Test
public void testQueryAllOfNothing() throws Exception
{
// None of the cases return false for empty data sets
List<Integer> numbers = Arrays.asList();
assertEquals(true, Query.all(numbers, n -> 3 <= n));
}
@Test
void queryVsStreamExample()
{
{
// begin-snippet: query_example
Integer[] numbers = Range.get(1, 20);
Integer[] evenQueryNumbers = Query.where(numbers, n -> n % 2 == 0).orderBy(OrderBy.Order.Descending, n -> n)
.asArray();
// end-snippet
// begin-snippet: stream_example
Integer[] evenStreamNumbers = Arrays.stream(numbers).filter(n -> n % 2 == 0)
.sorted((o1, o2) -> o2.compareTo(o1)).toArray(Integer[]::new);
// end-snippet
Assertions.assertArrayEquals(evenQueryNumbers, evenStreamNumbers);
}
{
// begin-snippet: query_sum_example
String[] names = {"Llewellyn", "Scott"};
int lengthsFromQuery = Query.sum(names, n -> n.length()).intValue();
// end-snippet
// begin-snippet: stream_sum_example
int lengthsFromStream = (int) Arrays.stream(names).map(n -> n.length()).reduce(0, (a, b) -> a + b);
// end-snippet
Assertions.assertEquals(lengthsFromQuery, lengthsFromStream);
}
{
Integer[] numbers = Range.get(1, 20);
// begin-snippet: list_is_queryable
List<String> strings = Query.select(numbers, n -> "" + n);
// end-snippet
// begin-snippet: list_from_stream
List<String> strings2 = Arrays.stream(numbers).map(n -> "" + n).collect(Collectors.toList());
// end-snippet
}
}
@Test
void testTakeAndSkip()
{
Integer[] integers = Range.get(1, 10);
Integer[] skip = Query.skip(integers, 3).asArray();
Approvals.verify(Query.take(skip, 4));
}
@Test
void testSkipTooMany()
{
Integer[] integers = Range.get(1, 3);
List<Integer> list = Arrays.asList(integers);
assertEquals(Query.skip(integers, 3).size(), 0);
assertEquals(Query.skip(integers, 4).size(), 0);
integers = null;
assertEquals(Query.skip(integers, 3).size(), 0);
assertEquals(Query.skip(list, 3).size(), 0);
assertEquals(Query.skip(list, 4).size(), 0);
list = null;
assertEquals(Query.skip(list, 3).size(), 0);
}
@Test
void testTakeTooMany()
{
Integer[] integers = Range.get(1, 3);
List<Integer> list = Arrays.asList(integers);
assertEquals(Query.take(integers, 4).size(), 3);
integers = null;
assertEquals(Query.take(integers, 3).size(), 0);
assertEquals(Query.take(list, 4).size(), 3);
list = null;
assertEquals(Query.take(list, 3).size(), 0);
}
@Test
void testMax()
{
Integer[] integers = Range.get(1, 3);
int max = Query.max(Arrays.asList(integers), (i) -> i % 3 * 10);
assertEquals(2, max);
max = Query.max(integers, (i) -> i % 3 * 10);
assertEquals(2, max);
}
@Test
void testArrayAndListParity()
{
Queryable<Method> declaredMethods = Queryable.as(Query.class.getDeclaredMethods())
.where(m -> !m.getName().startsWith("lambda$"));
Queryable<Method> arrays = declaredMethods
.where(m -> m.getParameterTypes().length >= 1 && m.getParameterTypes()[0].isArray());
Queryable<Method> iterables = declaredMethods.where(m -> m.getParameterTypes().length >= 1
&& ObjectUtils.isThisInstanceOfThat(m.getParameterTypes()[0], Iterable.class));
arrays = arrays.where(m -> !hasMatchingMethod(m, declaredMethods, true));
iterables = iterables.where(m -> !hasMatchingMethod(m, declaredMethods, false));
Queryable<String> missingMethods = arrays.combine(iterables).select(this::printMethod).orderBy(m -> m);
Approvals.verifyAll("Methods without a corresponding array or list", missingMethods, m -> m);
}
private boolean hasMatchingMethod(Method method, Queryable<Method> declaredMethods, boolean findIterable)
{
Queryable<Method> where = declaredMethods.where(m -> m.getName().equals(method.getName()))
.where(m -> m.getParameterTypes().length == method.getParameterTypes().length);
if (findIterable)
{
return where.any(m -> ObjectUtils.isThisInstanceOfThat(m.getParameterTypes()[0], Iterable.class));
}
else
{
return where.any(m -> m.getParameterTypes()[0].isArray());
}
}
private String printMethod(Method m)
{
return String.format("%s.%s(%s)", m.getDeclaringClass().getSimpleName(), m.getName(), showParameters(m));
}
private String showParameters(Method m)
{
return StringUtils.join(Query.select(m.getParameters(), p -> String.format("%s", p.getType().getSimpleName())),
",");
}
}
|
package spec;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
/**
* A class to manage your contacts and meetings.
*/
public interface ContactManager {
int addFutureMeeting(Set<Contact> contacts, Calendar date);
PastMeeting getPastMeeting(int id);
FutureMeeting getFutureMeeting(int id);
/**
* Returns the meeting with the requested ID, or null if there is none.
*
* @param id the ID for the meeting
* @return the meeting with the requested ID, or null if there is none.
*/
Meeting getMeeting(int id);
List<Meeting> getFutureMeetingList(Contact contact);
/**
* Returns the list of meetings that are scheduled for, or that took
* place on, the specified date
* <p/>
* If there are none, the returned list will be empty. Otherwise,
* the list will be chronologically sorted and will not contain any
* duplicates.
*
* @param date the date
* @return the list of meetings
* @throws NullPointerException if the date is null
*/
List<Meeting> getMeetingListOn(Calendar date);
List<PastMeeting> getPastMeetingListFor(Contact contact);
void addNewPastMeeting(Set<Contact> contacts, Calendar date, String text);
PastMeeting addMeetingNotes(int id, String text);
int addNewContact(String name, String notes);
/**
* Returns a list with the contacts whose name contains that string.
* If the string is an empty string, this method returns the set that contains all the current contacts
*
* @param name the string to search for
* @return a list with the contacts whose name contains that string.
* @throws NullPointerException if the parameter is null
*/
Set<Contact> getContacts(String name);
Set<Contact> getContacts(int... ids);
/**
* Save all data to disk.
* <p/>
* This method must be executed when the program is
* closed and when/if the user requests it.
*/
void flush();
/**
* Increases the contactId by one when a contact is added to the ContactManager.
*/
void updateContactId();
/**
* Increases the meetingId by one when a contact is added to the ContactManager.
*/
void updateMeetingId();
/**
* Returns the id of the contact
* @return the id of the contact
*/
int getContactId();
/**
* Returns the id of the meeting
* @return the id of the meeting
*/
int getMeetingId();
/**
* Returns the list of meetings in the ContactManager
* @return meetings in the ContactManager of type List<Meeting>
*/
List<Meeting> getMeetings();
/**
* Returns the list of contacts in the ContactManager
* @return contacts in the ContactManager of type Set<Contact>
*/
Set<Contact> getContacts();
}
|
package springies;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import jboxGlue.WorldManager;
import jgame.platform.JGEngine;
import listeners.JGameActionListener;
import masses.FixedMass;
import masses.Mass;
import springs.Spring;
import walls.Wall;
import Parsers.ModelParser;
import Parsers.XMLParserCaller;
@SuppressWarnings("serial")
public class Springies extends JGEngine {
public ArrayList<Assembly> assemblyList;
private HashMap<String, Mass> mMassMap;
private ArrayList<Mass> mMassList;
private ArrayList<Spring> mSpringsList;
private Wall[] mWallArray;
private EnvironmentManager mEnvironmentManager;
private JGameActionListener mActionListener;
public Springies () {
// set the window size
int height = 480;
double aspect = 16.0 / 9.0;
initEngineComponent((int) (height * aspect), height);
mMassMap = new HashMap<String, Mass>();
mSpringsList = (new ArrayList<Spring>());
assemblyList = new ArrayList<Assembly>();
}
@Override
public void initCanvas ()
{
setCanvasSettings(1, // width of the canvas in tiles
1, // height of the canvas in tiles
displayWidth(), // width of one tile
displayHeight(), // height of one tile
null,// foreground colour -> use default colour white
null,// background colour -> use default colour black
null); // standard font -> use default font
}
@Override
public void initGame ()
{
mMassList = new ArrayList<Mass>();
mSpringsList = new ArrayList<Spring>();
// setFrameRate(60, 2); // given
setFrameRate(5, 2);
// NOTE:
// world coordinates have y pointing down
// game coordinates have y pointing up
// so gravity is up in world coords and down in game coords
// so set all directions (e.g., forces, velocities) in world coords
WorldManager.initWorld(this);
String model_filename = "assets/lamp.xml";
String model_filename2 = "assets/daintywalker.xml";
String environment_filename = "assets/myEnvironment.xml";
//addTestSpring();
testSpringForce();
makeModelFromXML(model_filename);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
makeModelFromXML(model_filename2);
mEnvironmentManager = new EnvironmentManager(this);
//mForceManager = new EnvironmentManager(this, environment_filename);
// NEED TO ADD CODE SO WE CAN UPDATE FORCE MANAGER AS NEW MASSES ARE ADDED
mActionListener = new JGameActionListener(mEnvironmentManager);
}
private void makeModelFromXML (String filename) {
XMLParserCaller caller = new XMLParserCaller();
ModelParser parser = new ModelParser(this);
try {
caller.call(filename, parser);
}
catch (Exception e) {
System.out.println("Error: Unable to parse XML file");
e.printStackTrace();
System.exit(1);
}
}
public void testSpringForce() {
double xpos = displayWidth() / 2;
double ypos = displayHeight() / 2;
addMass(xpos, ypos + 200);
addFixedMass(xpos, ypos);
Mass mass1 = this.mMassList.get(0);
Mass mass2 = this.mMassList.get(1);
Spring newSpring1 = new Spring (mass1, mass2, 150, 1);
this.mSpringsList.add(newSpring1);
}
public void addTestSpring() {
double xpos = displayWidth() / 2;
double ypos = displayHeight() / 2;
addMass(xpos, ypos);
addMass(xpos + 100, ypos + 20);
addMass(xpos + 100, ypos - 20);
addMass(xpos - 100, ypos - 20);
Mass mass1 = this.mMassList.get(0);
Mass mass2 = this.mMassList.get(1);
Mass mass3 = this.mMassList.get(2);
Mass mass4 = this.mMassList.get(3);
Spring newSpring1 = new Spring (mass1, mass2);
Spring newSpring2 = new Spring (mass1, mass3, 2);
Spring newSpring3 = new Spring (mass1, mass4, 2);
Spring newSpring4 = new Spring (mass2, mass3, 2);
this.mSpringsList.add(newSpring1);
this.mSpringsList.add(newSpring2);
this.mSpringsList.add(newSpring3);
this.mSpringsList.add(newSpring4);
}
public void addMass (double xpos, double ypos)
{
Mass ball = new Mass("m0", xpos, ypos);
this.mMassList.add(ball);
}
public void addFixedMass (double xpos, double ypos)
{
FixedMass ball = new FixedMass("m0", xpos, ypos);
this.mMassList.add(ball);
}
@Override
/**
* In each frame, Springies will check all the user input events and perform actions accordingly.
* It will also iterate through all the masses and apply the Forces acting upon the masses at the
* moment. Then the JBox world will take 1 time step and update JGame accordingly.
*
*/
public void doFrame ()
{
doListenerEvents();
// update game objects
mEnvironmentManager.doForces();
WorldManager.getWorld().step(1f, 1);
moveObjects();
checkCollision(1 + 2, 1);
/**
* iterate through massmap to do forcemanager.doforces
*/
}
// This is a helper method to call the built in JEngine listeners. This way
// we don't have to worry about coordinates, etc. This method will send the lastKeyPressed
// and the mouseEvents to the Listener class and the Listener class will perform
// the appropriate actions
private void doListenerEvents() {
mActionListener.doKeyEvent(getLastKey());
this.clearLastKey(); // last key has to be cleared every time
mActionListener.doMouseEvent(getMouseButton(1), getMouseButton(3), getMouseX(), getMouseY());
}
@Override
public void paintFrame () {}
public Wall[] getWalls() {
return mWallArray;
}
public List<Mass> getMassList() {
return mMassList;
}
public void addMassMap(HashMap<String, Mass> massList) {
/**
* TODO
*/
}
private static final String ASSETS = "assets/";
public void makeAssembly() {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"XML documents", "xml");
chooser.setFileFilter(filter);
int returnVal = chooser.showDialog(null, "new Assembly file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
this.loadAssemblyFromFile(file);
}
}
public void loadAssemblyFromFile(File file) {
if (file != null && file.getAbsolutePath().equals(ASSETS+"environment.xml")) {
ModelParser factory = new ModelParser(this);
try {
new XMLParserCaller().call(ASSETS+file.getPath(), factory);
Assembly a = new Assembly();
for (Mass mass : factory.getAssemblyMasses().values()) {
a.add(mass);
}
for (Spring spring : factory.getSprings()) {
a.add(spring);
}
//a.addMuscles(factory.getAssemblyMuscles());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setMassMap(HashMap<String, Mass> massList) {
this.mMassMap = massList;
}
public void setMassMap(ArrayList<Mass> mass_list) {
this.mMassList = mass_list;
}
public ArrayList<Spring> getSpringsList () {
return mSpringsList;
}
public void setSpringsList (ArrayList<Spring> springList) {
this.mSpringsList = springList;
}
// public HashMap<String, Mass> getAssemblyMasses() {
// return mMasses;
// public ArrayList<Spring> getAssemblySprings() {
// return mSprings;
public void clearLoadedAssemblies() {
assemblyList = new ArrayList<Assembly>();
}
}
|
package test.java;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import main.java.Board;
import main.java.CannotPlacePieceException;
import main.java.IndexOutsideOfGridException;
import main.java.Piece;
import main.java.PieceColor;
import main.java.PieceType;
import main.java.Position;
import org.junit.Test;
public class BoardTest
{
@Test
public void testDimensionsOfGrid()
{
Board board = getBoard();
assertEquals(board.getGrid().length, 8);
assertEquals(board.getGrid()[0].length, 8);
assertEquals(board.getGrid()[1].length, 8);
assertEquals(board.getGrid()[2].length, 8);
assertEquals(board.getGrid()[3].length, 8);
assertEquals(board.getGrid()[4].length, 8);
assertEquals(board.getGrid()[5].length, 8);
assertEquals(board.getGrid()[6].length, 8);
assertEquals(board.getGrid()[7].length, 8);
}
@Test
public void testNumPiecesOnBoardAtBeginningOfGame()
{
int numPieces = 0;
Board board = getBoard();
Piece[][] grid = board.getGrid();
for (int row = 0; row < 8; row++)
{
for (int column = 0; column < 8; column++)
{
if (!grid[0][0].equals(PieceType.NO_PIECE))
{
numPieces += 1;
}
}
}
assert (numPieces == 32);
}
@Test()
public void testCorrectPiecesAtCorrectLocationsAtBeginningOfGame()
{
Board board = getBoard();
Piece[][] grid = board.getGrid();
/*Top row. Black royalty.*/
assertEquals(grid[0][0].getType(), PieceType.ROOK);
assertEquals(grid[0][0].getColor(), PieceColor.BLACK);
assertEquals(grid[0][1].getType(), PieceType.KNIGHT);
assertEquals(grid[0][1].getColor(), PieceColor.BLACK);
assertEquals(grid[0][2].getType(), PieceType.BISHOP);
assertEquals(grid[0][2].getColor(), PieceColor.BLACK);
assertEquals(grid[0][3].getType(), PieceType.QUEEN);
assertEquals(grid[0][3].getColor(), PieceColor.BLACK);
assertEquals(grid[0][4].getType(), PieceType.KING);
assertEquals(grid[0][4].getColor(), PieceColor.BLACK);
assertEquals(grid[0][5].getType(), PieceType.BISHOP);
assertEquals(grid[0][5].getColor(), PieceColor.BLACK);
assertEquals(grid[0][6].getType(), PieceType.KNIGHT);
assertEquals(grid[0][6].getColor(), PieceColor.BLACK);
assertEquals(grid[0][7].getType(), PieceType.ROOK);
assertEquals(grid[0][7].getColor(), PieceColor.BLACK);
/*Second to top row. Black pawns.*/
for (int column = 0; column < 8; column++)
{
assertEquals(grid[1][column].getType(), PieceType.PAWN);
assertEquals(grid[1][column].getColor(), PieceColor.BLACK);
}
/*Second to bottom row. White pawns.*/
for (int column = 0; column < 8; column++)
{
assertEquals(grid[6][column].getType(), PieceType.PAWN);
assertEquals(grid[6][column].getColor(), PieceColor.WHITE);
}
/*Bottom row. White royalty.*/
assertEquals(grid[7][0].getType(), PieceType.ROOK);
assertEquals(grid[7][0].getColor(), PieceColor.WHITE);
assertEquals(grid[7][1].getType(), PieceType.KNIGHT);
assertEquals(grid[7][1].getColor(), PieceColor.WHITE);
assertEquals(grid[7][2].getType(), PieceType.BISHOP);
assertEquals(grid[7][2].getColor(), PieceColor.WHITE);
assertEquals(grid[7][3].getType(), PieceType.QUEEN);
assertEquals(grid[7][3].getColor(), PieceColor.WHITE);
assertEquals(grid[7][4].getType(), PieceType.KING);
assertEquals(grid[7][4].getColor(), PieceColor.WHITE);
assertEquals(grid[7][5].getType(), PieceType.BISHOP);
assertEquals(grid[7][5].getColor(), PieceColor.WHITE);
assertEquals(grid[7][6].getType(), PieceType.KNIGHT);
assertEquals(grid[7][6].getColor(), PieceColor.WHITE);
assertEquals(grid[7][7].getType(), PieceType.ROOK);
assertEquals(grid[7][7].getColor(), PieceColor.WHITE);
}
@Test
public void testMovePawnsLegally() throws IndexOutsideOfGridException
{
Board board1 = getBoard();
/*ONE(1) space, then ONE(1) space again*/
for (int column = 0; column < 8; column++)
{
/*Black pawns*/
/*First move*/
try
{
board1.movePiece(new Position(1, column), new Position(2, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
/*Second move*/
try
{
board1.movePiece(new Position(2, column), new Position(3, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
/*White pawns*/
/*First move*/
try
{
board1.movePiece(new Position(6, column), new Position(5, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
/*Second move*/
try
{
board1.movePiece(new Position(5, column), new Position(4, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
}
/*New simulation. Generate new board.*/
Board board2 = getBoard();
/*TWO(2) spaces, then ONE(1) space*/
for (int column = 0; column < 8; column++)
{
/*Black pawns*/
/*First move*/
try
{
board2.movePiece(new Position(1, column), new Position(3, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
/*Second move*/
try
{
board2.movePiece(new Position(3, column), new Position(4, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
/*White pawns*/
/*First move*/
try
{
board2.movePiece(new Position(6, column), new Position(4, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
/*Second move*/
try
{
board2.movePiece(new Position(4, column), new Position(3, column));
} catch (CannotPlacePieceException ex)
{
fail(ex.getLocalizedMessage());
}
}
}
@Test
public void testMovePawnsIllegally() throws IndexOutsideOfGridException
{
Board board = getBoard();
int numErrors = 0;
/*ONE(1) space, then TWO(2) spaces*/
for (int column = 0; column < 8; column++)
{
/*Black pawns*/
/*First move*/
try
{
board.movePiece(new Position(1, column), new Position(2, column));
} catch (CannotPlacePieceException ex)
{
numErrors += 1;
}
/*Second move*/
try
{
board.movePiece(new Position(2, column), new Position(4, column));
} catch (CannotPlacePieceException ex)
{
numErrors += 1;
}
/*White pawns*/
/*First move*/
try
{
board.movePiece(new Position(6, column), new Position(5, column));
} catch (CannotPlacePieceException ex)
{
numErrors += 1;
}
/*Second move*/
try
{
board.movePiece(new Position(5, column), new Position(3, column));
} catch (CannotPlacePieceException ex)
{
numErrors += 1;
}
}
assertEquals(numErrors, 16);
}
private Board getBoard()
{
Board board = null;
try
{
board = new Board();
} catch (CannotPlacePieceException | IndexOutsideOfGridException ex)
{
String msg = "Grid failed to be created properly.";
fail(msg);
}
return board;
}
@Test
public void testValidMoveToNewPosition()
{
Board board = getBoard();
/* Moving pawns out of the way for tests of other pieces */
try
{
board.movePiece(new Position(1, 0), new Position(3, 0));
board.movePiece(new Position(1,1), new Position(3,1));
board.movePiece(new Position(1,5), new Position(3,5));
board.movePiece(new Position(0,0), new Position(2,0));
board.movePiece(new Position(0,1), new Position(2,2));
board.movePiece(new Position(0,2), new Position(1,1));
board.movePiece(new Position(0,4), new Position(3,7));
board.movePiece(new Position(0,3), new Position(0,4));
}
catch(CannotPlacePieceException | IndexOutsideOfGridException ex)
{
fail(ex.getLocalizedMessage());
}
}
@Test
public void testInvalidMoveToOutsideGrid()
{
Board board = getBoard();
try
{
int row =0;
for(int col=0; col < 8; col++)
{
board.movePiece(new Position(row, col), new Position(row, col-1));
}
board.movePiece(new Position(0,0), new Position(-1,0));
board.movePiece(new Position(1,0), new Position(-2,0));
board.movePiece(new Position(0,7), new Position(0,8));
board.movePiece(new Position(1,7), new Position(1,8));
}
catch(CannotPlacePieceException | IndexOutsideOfGridException ex)
{
fail(ex.getLocalizedMessage());
}
}
@Test
public void testInvalidMoveOntoOtherPieces()
{
Board board = getBoard();
try
{
board.movePiece(new Position(1,0), new Position(3,0));
board.movePiece(new Position(0,0), new Position(3,0));
board.movePiece(new Position(1,7), new Position(2,7));
board.movePiece(new Position(0,5), new Position(2,7));
board.movePiece(new Position(0,3), new Position(0,4));
board.movePiece(new Position(0,4), new Position(1,5));
}
catch(CannotPlacePieceException | IndexOutsideOfGridException ex)
{
fail(ex.getLocalizedMessage());
}
}
@Test
public void testInvalidMoveThroughPieces()
{
Board board = getBoard();
try
{
board.movePiece(new Position(0,0), new Position(1,0));
board.movePiece(new Position(0,2), new Position(2,0));
board.movePiece(new Position(0,4), new Position(3,4));
}
catch(CannotPlacePieceException | IndexOutsideOfGridException ex)
{
fail(ex.getLocalizedMessage());
}
}
@Test
public void testInvalidMoveNotContainedInList()
{
Board board = getBoard();
try
{
int row =0;
for(int col=0; col < 8; col++)
{
board.movePiece(new Position(row, col), new Position(row, col+2));
}
board.movePiece(new Position(0,0), new Position(2,1));
board.movePiece(new Position(0,1), new Position(1,2));
board.movePiece(new Position(0,2), new Position(1,0));
board.movePiece(new Position(0,3), new Position(2,3));
board.movePiece(new Position(0,4), new Position(2,5));
}
catch(CannotPlacePieceException | IndexOutsideOfGridException ex)
{
fail(ex.getLocalizedMessage());
}
}
}
|
package org.xbill.DNS;
import java.io.*;
/**
* An class for parsing DNS messages.
*
* @author Brian Wellington
*/
public class DNSInput {
private byte [] array;
private int pos;
private int end;
private int saved_pos;
private int saved_end;
/**
* Creates a new DNSInput
* @param input The byte array to read from
*/
public
DNSInput(byte [] input) {
array = input;
pos = 0;
end = array.length;
saved_pos = -1;
saved_end = -1;
}
/**
* Returns the current position.
*/
public int
current() {
return pos;
}
/**
* Returns the number of bytes that can be read from this stream before
* reaching the end.
*/
public int
remaining() {
return end - pos;
}
private void
require(int n) throws WireParseException{
if (n > remaining()) {
throw new WireParseException("end of input");
}
}
public void
setActive(int len) {
if (len > array.length - pos) {
throw new IllegalArgumentException("cannot set active " +
"region past end of input");
}
end = pos + len;
}
/**
* Clears the active region of the string. Further operations are not
* restricted to part of the input.
*/
public void
clearActive() {
end = array.length;
}
public void
jump(int index) {
if (index >= array.length) {
throw new IllegalArgumentException("cannot jump past " +
"end of input");
}
pos = index;
end = array.length;
}
public void
save() {
saved_pos = pos;
saved_end = end;
}
/**
* Restores the input stream to its state before the call to {@link #save}.
*/
public void
restore() {
if (saved_pos < 0) {
throw new IllegalStateException("no previous state");
}
pos = saved_pos;
end = saved_end;
saved_pos = -1;
saved_end = -1;
}
/**
* Reads an unsigned 8 bit value from the stream, as an int.
* @return An unsigned 8 bit value.
* @throws WireParseException The end of the stream was reached.
*/
public int
readU8() throws WireParseException {
require(1);
return (array[pos++] & 0xFF);
}
/**
* Reads an unsigned 16 bit value from the stream, as an int.
* @return An unsigned 16 bit value.
* @throws WireParseException The end of the stream was reached.
*/
public int
readU16() throws WireParseException {
require(2);
int b1 = array[pos++] & 0xFF;
int b2 = array[pos++] & 0xFF;
return ((b1 << 8) + b2);
}
/**
* Reads an unsigned 32 bit value from the stream, as a long.
* @return An unsigned 32 bit value.
* @throws WireParseException The end of the stream was reached.
*/
public long
readU32() throws WireParseException {
require(4);
int b1 = array[pos++] & 0xFF;
int b2 = array[pos++] & 0xFF;
int b3 = array[pos++] & 0xFF;
int b4 = array[pos++] & 0xFF;
return (((long)b1 << 24) + (b2 << 16) + (b3 << 8) + b4);
}
/**
* Reads a byte array of a specified length from the stream into an existing
* array.
* @param b The array to read into.
* @param off The offset of the array to start copying data into.
* @param len The number of bytes to copy.
* @throws WireParseException The end of the stream was reached.
*/
public void
readByteArray(byte [] b, int off, int len) throws WireParseException {
require(len);
System.arraycopy(array, pos, b, off, len);
pos += len;
}
/**
* Reads a byte array of a specified length from the stream.
* @return The byte array.
* @throws WireParseException The end of the stream was reached.
*/
public byte []
readByteArray(int len) throws WireParseException {
require(len);
byte [] out = new byte[len];
System.arraycopy(array, pos, out, 0, len);
pos += len;
return out;
}
/**
* Reads a byte array consisting of the remainder of the stream (or the
* active region, if one is set.
* @return The byte array.
*/
public byte []
readByteArray() {
int len = remaining();
byte [] out = new byte[len];
System.arraycopy(array, pos, out, 0, len);
pos += len;
return out;
}
/**
* Reads a counted string from the stream. A counted string is a one byte
* value indicating string length, followed by bytes of data.
* @return A byte array containing the string.
* @throws WireParseException The end of the stream was reached.
*/
public byte []
readCountedString() throws WireParseException {
require(1);
int len = array[pos++] & 0xFF;
return readByteArray(len);
}
}
|
package org.eclipse.ice.item.nuclear;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.ice.datastructures.ICEObject.Component;
import org.eclipse.ice.datastructures.ICEObject.IUpdateable;
import org.eclipse.ice.datastructures.form.AllowedValueType;
import org.eclipse.ice.datastructures.form.BasicEntryContentProvider;
import org.eclipse.ice.datastructures.form.DataComponent;
import org.eclipse.ice.datastructures.form.Entry;
import org.eclipse.ice.datastructures.form.Form;
import org.eclipse.ice.datastructures.form.FormStatus;
import org.eclipse.ice.datastructures.form.IEntryContentProvider;
import org.eclipse.ice.datastructures.form.ResourceComponent;
import org.eclipse.ice.datastructures.form.TableComponent;
import org.eclipse.ice.datastructures.form.TreeComposite;
import org.eclipse.ice.datastructures.form.iterator.BreadthFirstTreeCompositeIterator;
import org.eclipse.ice.datastructures.resource.ICEResource;
import org.eclipse.ice.item.Item;
import org.eclipse.ice.item.jobLauncher.JobLauncherForm;
import org.eclipse.ice.item.messaging.Message;
import org.eclipse.ice.item.utilities.moose.MOOSEFileHandler;
import org.eclipse.remote.core.IRemoteConnection;
import org.eclipse.remote.core.IRemoteConnectionHostService;
/**
* The MOOSE Item represents a unification of the MOOSEModel and MOOSELauncher.
* This Item essentially provides a Composite Item composed of the model and
* launcher, and as such brokers the data necessary for user input during an
* entire MOOSE workflow, ie input generation to launching and data
* visualization.
*
* @author Alex McCaskey
*
*/
@XmlRootElement(name = "MOOSE")
public class MOOSE extends Item {
/**
* Reference to the MOOSE Input Model for this MOOSE workflow.
*/
@XmlTransient()
private MOOSEModel mooseModel;
/**
* Reference to the MOOSELauncher used in executing a constructed MOOSE
* input file.
*/
@XmlTransient()
private MOOSELauncher mooseLauncher;
/**
* Reference to the Model's list of files.
*/
@XmlTransient()
private DataComponent modelFiles;
/**
* Reference to the DataComponent containing the Postprocessors to display
* automatically.
*/
@XmlTransient()
private DataComponent postProcessorsData;
/**
* Reference to the Model's input tree.
*/
@XmlTransient()
private TreeComposite modelTree;
/**
* Reference to teh mapping between created Postprocessor VizResources and
* their names.
*/
@XmlTransient()
private HashMap<String, ICEResource> postProcessorResources;
/**
* This map keeps track of File Entries in the modelFiles DataComponent and
* their corresponding parent TreeComposites so that we can keep them in
* sync.
*/
@XmlTransient()
private HashMap<String, TreeComposite> fileEntryTreeMapping;
/**
* Reference to the id of the DataComponent containign the Postprocessors
* the user would like to automatically display.
*/
@XmlTransient()
public static final int ppDataId = 10;
/**
* Boolean to indicate whether this Item has already registered with the
* necessary Tree blocks.
*/
@XmlTransient()
private boolean registered = false;
/**
* Nullary constructor.
*/
public MOOSE() {
this(null);
mooseModel = new MOOSEModel(null);
mooseLauncher = new MOOSELauncher(null);
addComponents();
}
/**
* The constructor.
*
* @param projectSpace
*/
public MOOSE(IProject projectSpace) {
super(projectSpace);
mooseModel = new MOOSEModel(projectSpace);
mooseLauncher = new MOOSELauncher(projectSpace);
addComponents();
}
private void addComponents() {
// Loop over all components and add them to this form
for (Component c : mooseModel.getForm().getComponents()) {
if (c.getName().equals("Mesh")) {
c.setName("Mesh and Output Files");
}
form.addComponent(c);
}
// Grab an explicit reference to the files component from the Model
modelFiles = (DataComponent) form.getComponent(1);
// Register this Item as a listener to the MOOSE-Based Application
// Entry so that if it changes to Remote, we can grab the
// IRemoteConnection
modelFiles.retrieveEntry("MOOSE-Based Application").register(this);
// Add the parallel execution component
form.addComponent(mooseLauncher.getForm().getComponent(3));
// Get a handle to the model input tree
modelTree = (TreeComposite) form.getComponent(2);
fileEntryTreeMapping = new HashMap<String, TreeComposite>();
// Initialize the postProcessor Mapping
postProcessorResources = new HashMap<String, ICEResource>();
// Create the Postprocessors DataComponent
postProcessorsData = new DataComponent();
postProcessorsData.setName("Show Postprocessors?");
postProcessorsData.setDescription("Enable the Postprocessors you would like to monitor in real time.");
postProcessorsData.setId(MOOSE.ppDataId);
form.addComponent(postProcessorsData);
TreeComposite ppTree;
if ((ppTree = getTreeByName("Postprocessors")) != null) {
setupPostprocessorData(ppTree);
}
}
/**
* Very simply, this method just creates a new Form that we will populate
* later in the constructor.
*/
@Override
protected void setupForm() {
form = new Form();
}
/**
* Sets the information that identifies the MOOSE Item.
*/
@Override
protected void setupItemInfo() {
// Local declarations
String description = "The Multiphysics Object-Oriented Simulation "
+ "Environment (MOOSE) is a multiphysics framework developed " + "by Idaho National Laboratory.";
// Set the model defaults
setName("MOOSE Workflow");
setDescription(description);
setItemBuilderName("MOOSE Workflow");
// Setup the action list. Remove key-value pair support.
allowedActions.remove(taggedExportActionString);
allowedActions.remove(nativeExportActionString);
allowedActions.add("Launch the Job");
allowedActions.add("Write MOOSE File");
return;
}
/**
* (non-Javadoc)
*
* @see org.eclipse.ice.item.Item#cancelProcess()
*/
@Override
public FormStatus cancelProcess() {
// Only cancel if the Item is actuallly processing
if (status.equals(FormStatus.Processing)) {
// Try to cancel the action
mooseLauncher.cancelProcess();
// Reset the state to "ready" since it was clearly able to process.
status = FormStatus.ReadyToProcess;
}
return status;
}
/**
* (non-Javadoc)
*
* @see org.eclipse.ice.item.Item#reviewEntries(org.eclipse.ice.datastructures.form.Form)
*/
@Override
protected FormStatus reviewEntries(Form preparedForm) {
// Tell the model to review its entries
FormStatus status = mooseModel.reviewEntries(preparedForm);
// If the Model finished correctly, clear the old
// file entries and load new ones.
if (status.equals(FormStatus.ReadyToProcess)) {
//clearModelFiles();
// loadFileEntries();
}
// Register this Item as a listener to the Variables block
// this is so we can use the variables to populate things like
// kernel variable entries.
TreeComposite variablesTree = getTreeByName("Variables");
if (!registered && variablesTree != null) {
variablesTree.register(this);
modelTree.register(this);
registered = true;
}
TreeComposite ppTree;
if ((ppTree = getTreeByName("Postprocessors")) != null) {
setupPostprocessorData(ppTree);
}
return status;
}
/**
* (non-Javadoc)
*
* @see org.eclipse.ice.item.Item#process(java.lang.String)
*/
@Override
public FormStatus process(String actionName) {
// Local Declarations
FormStatus retStatus = FormStatus.InfoError;
// Set our outputFile as the MooseLauncher's output file
// so we can see the streaming output
outputFile = mooseLauncher.getOutputFile();
// Parse the action name
if ("Launch the Job".equals(actionName)) {
// FIXME WE NEED TO DO A CHECK FOR ALL THE REQUIRED BLOCKS!!!!
// Add the ICEUpdater tree block to Outputs
TreeComposite outputs = getTreeByName("Outputs");
TreeComposite postProcessors = getTreeByName("Postprocessors");
// First check to see if we have any post processors to
// watch for.
if (postProcessors.isActive() && postProcessors.getNumberOfChildren() > 0) {
// If we do, we should add an ICEUpdater
boolean iNeedUpdater = true;
// If we already have one, then we shouldn't add another one
for (int i = 0; i < outputs.getNumberOfChildren(); i++) {
if ("ICEUpdater".equals(outputs.getChildAtIndex(i).getName())) {
// But if the current one is not configured correctly
// then we should add a new one, Here we make sure the
// Item Id is correct...
TreeComposite iceUpdater = outputs.getChildAtIndex(i);
DataComponent data = (DataComponent) iceUpdater.getDataNodes().get(0);
Entry itemIdEntry = data.retrieveEntry("item_id");
if (Integer.valueOf(itemIdEntry.getValue()) != getId()) {
itemIdEntry.setValue(String.valueOf(getId()));
}
// Now we have a valid ICEUpdater, so we don't need
// to create a new one.
iNeedUpdater = false;
break;
}
}
if (iNeedUpdater) {
for (int i = 0; i < outputs.getChildExemplars().size(); i++) {
if ("ICEUpdater".equals(outputs.getChildExemplars().get(i).getName())) {
TreeComposite updater = (TreeComposite) outputs.getChildExemplars().get(i).clone();
outputs.setNextChild(updater);
DataComponent data = (DataComponent) updater.getDataNodes().get(0);
data.retrieveEntry("item_id").setValue(String.valueOf(getId()));
data.retrieveEntry("url").setValue("http://localhost:"
+ System.getProperty("org.eclipse.equinox.http.jetty.http.port") + "/ice/update");
updater.setActive(true);
updater.setActiveDataNode(data);
break;
}
}
}
}
// Get a reference to the Launchers files component
DataComponent launcherFiles = (DataComponent) mooseLauncher.getForm().getComponent(1);
// Grab the file name the user has specified for the input file
String fileName = modelFiles.retrieveEntry("Output File Name").getValue();
// Write the Moose file if it doesn't exist
retStatus = mooseModel.process("Write MOOSE File");
if (!retStatus.equals(FormStatus.Processed)) {
return retStatus;
}
// Set the value of the input file to the user-specified
// file name
launcherFiles.retrieveEntry("Input File").setValue(fileName);
// Update the MooseLauncher's set of input files...
mooseLauncher.update(launcherFiles.retrieveEntry("Input File"));
for (Entry e : getFileEntries()) {
Entry launcherFile = launcherFiles.retrieveEntry(e.getName());
if (launcherFile != null) {
launcherFile.setValue(e.getValue());
}
}
// Get the application URI
URI appUri = URI.create(modelFiles.retrieveEntry("MOOSE-Based Application").getValue());
// Check if we're local or remote
if ("ssh".equals(appUri.getScheme())) {
mooseLauncher.setExecutable(Paths.get(appUri.getRawPath()).getFileName().toString(), "",
appUri.getRawPath() + " -i ${inputFile} --no-color");
// Setup the hosts table to use the remote host
TableComponent hostsTable = (TableComponent) mooseLauncher.getForm()
.getComponent(JobLauncherForm.parallelId + 1);
IRemoteConnection remoteConnection = mooseLauncher.getRemoteConnection(appUri.getHost());
String hostname = remoteConnection.getService(IRemoteConnectionHostService.class).getHostname();
int index = hostsTable.addRow();
ArrayList<Entry> row = hostsTable.getRow(index);
ArrayList<Integer> selected = new ArrayList<Integer>();
selected.add(new Integer(index));
row.get(0).setValue(hostname);
hostsTable.setSelectedRows(selected);
} else {
// Set the executable string
mooseLauncher.setExecutable(new File(appUri).getName(), "",
appUri.getPath() + " -i ${inputFile} --no-color");
}
// Register as a listener of the resource component
// so we can add the resources to our resource component
((ResourceComponent) mooseLauncher.getForm().getComponent(JobLauncherForm.outputId)).register(this);
// Launch the Moose application
retStatus = mooseLauncher.process(actionName);
} else if ("Write MOOSE File".equals(actionName)) {
// Simply pass this along to the Model
retStatus = mooseModel.process(actionName);
}
// Set the status flag.
status = retStatus;
// Keep the status in sync
if (status.equals(FormStatus.Processing)) {
Thread statusThread = new Thread(new Runnable() {
@Override
public void run() {
while (!status.equals(FormStatus.Processed)) {
// Sleep for a bit
Thread.currentThread();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
logger.error(getClass().getName() + " Exception!",e);
}
// Set the status
status = mooseLauncher.getStatus();
}
return;
}
});
statusThread.start();
}
return retStatus;
}
/**
* This method just clears the Model Files DataComponent of its Entries so
* that we can populate it with new Entries.
*/
private void clearModelFiles() {
ArrayList<String> toBeRemoved = new ArrayList<String>();
for (Entry e : modelFiles.retrieveAllEntries()) {
String name = e.getName();
if (!"MOOSE-Based Application".equals(name) && !"Output File Name".equals(name)) {
toBeRemoved.add(name);
}
}
for (String e : toBeRemoved) {
modelFiles.deleteEntry(e);
}
}
/**
* (non-Javadoc)
*
* @see org.eclipse.ice.item.Item#loadInput(java.lang.String)
*/
@Override
public void loadInput(String input) {
mooseModel.loadInput(input);
form = new Form();
String description = "The Multiphysics Object-Oriented Simulation "
+ "Environment (MOOSE) is a multiphysics framework developed " + "by Idaho National Laboratory.";
// Set the model defaults
form.setName("MOOSE Workflow");
form.setDescription(description);
form.setItemID(getId());
form.setActionList(allowedActions);
// Loop over all components and add them to this form
for (Component c : mooseModel.getForm().getComponents()) {
form.addComponent(c);
}
// Add the model files component
modelFiles = (DataComponent) form.getComponent(1);
// Loop over all components and add the parallel exec and output
// components only
for (Component c : mooseLauncher.getForm().getComponents()) {
if ("Parallel Execution".equals(c.getName()) || "Output Files and Data".equals(c.getName())) {
form.addComponent(c);
}
}
// Set up the postProcessorData DataComponent to contain
// a list of Boolean Discrete Entries for each Postprocessor
postProcessorsData = new DataComponent();
postProcessorsData.setName("Show Postprocessors?");
postProcessorsData.setDescription("Enable the Postprocessors you would like to monitor in real time.");
postProcessorsData.setId(MOOSE.ppDataId);
form.addComponent(postProcessorsData);
TreeComposite ppTree;
if ((ppTree = getTreeByName("Postprocessors")) != null) {
setupPostprocessorData(ppTree);
}
// Get a handle to the model input tree
modelTree = (TreeComposite) form.getComponent(2);
//loadFileEntries();
// Register this Item as a listener to the Variables block
// this is so we can use the variables to populate things like
// kernel variable entries.
TreeComposite vars = getTreeByName("Variables");
if (vars != null) {
vars.register(this);
}
TreeComposite aux = getTreeByName("AuxVariables");
if (aux != null) {
aux.register(this);
}
modelTree.register(this);
registered = true;
return;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ice.item.Item#update(org.eclipse.ice.datastructures.ICEObject
* .IUpdateable)
*/
@Override
public void update(IUpdateable updateable) {
if (updateable instanceof ResourceComponent) {
ResourceComponent comp = (ResourceComponent) updateable;
ResourceComponent ourComp = (ResourceComponent) form.getComponent(3);
ArrayList<String> names = new ArrayList<String>();
// Get a list of all our Resource Names:
for (ICEResource r : ourComp.getResources()) {
names.add(r.getName());
}
for (ICEResource r : comp.getResources()) {
if (!names.contains(r.getName())) {
logger.info("Adding Resource to Moose: " + r.getName());
ourComp.add(r);
}
}
} else if (updateable instanceof TreeComposite) {
// If this is a tree composite we should reset our variables
Thread varThread = new Thread(new Runnable() {
@Override
public void run() {
new MOOSEFileHandler().setupVariables(modelTree);
new MOOSEFileHandler().setupAuxVariables(modelTree);
}
});
varThread.start();
} else if (updateable instanceof Entry) {
Entry entry = (Entry) updateable;
// If we get here, then we have a file Entry that
// has been changed on the modelFiles component
// and we need to sync up the tree with it.
// Grab the DataComponent
/*if (fileEntryTreeMapping.containsKey(entry.getName())) {
DataComponent data = (DataComponent) fileEntryTreeMapping.get(entry.getName()).getDataNodes().get(0);
// If not null, loop over the Entries til we find
// the file Entry.
if (data != null) {
for (Entry e : data.retrieveAllEntries()) {
// If the Entry's tag is "false" it is a commented
// out
// parameter.
if (!"false".equals(e.getTag()) && e.getValue() != null && !e.getValue().isEmpty()
&& (e.getName() + " = " + e.getValue())
.matches(mooseLauncher.getFileDependenciesSearchString())) {
// Set the value of the tree's file entry.
e.setValue(entry.getValue());
break;
}
}
}
}*/
}
}
/**
* This method finds the child TreeComposite of modelTree that has the given
* String name.
*
* @param name
* @return
*/
private TreeComposite getTreeByName(String name) {
for (int i = 0; i < modelTree.getNumberOfChildren(); i++) {
TreeComposite child = modelTree.getChildAtIndex(i);
if (child.getName().equals(name)) {
return child;
}
}
return null;
}
/**
* This method searches the Model input tree and locates all file Entries
* and loads them on the Model File DataComponent.
*/
private ArrayList<Entry> getFileEntries() {
//protected void loadFileEntries() {
// Walk the tree and get all Entries that may represent a file
ArrayList<Entry> files = new ArrayList<Entry>();
BreadthFirstTreeCompositeIterator iter = new BreadthFirstTreeCompositeIterator(modelTree);
while (iter.hasNext()) {
TreeComposite child = iter.next();
// Make sure we have a valid DataComponent
if (child.getActiveDataNode() != null && child.isActive()) {
DataComponent data = (DataComponent) child.getActiveDataNode();
for (Entry e : data.retrieveAllEntries()) {
// If the Entry's tag is "false" it is a commented out
// parameter.
if (!"false".equals(e.getTag()) && e.getValue() != null && !e.getValue().isEmpty()
&& (e.getName() + " = " + e.getValue())
.matches(mooseLauncher.getFileDependenciesSearchString())) {
Entry clonedEntry = (Entry) e.clone();
files.add(clonedEntry);
// // If this Entry does not have a very descriptive
// // name
// // we should reset its name to the block it belongs
// if ("file".equals(clonedEntry.getName().toLowerCase())
// || "data_file".equals(clonedEntry.getName().toLowerCase())) {
// clonedEntry.setName(child.getName());
// if (!clonedEntry.getValueType().equals(AllowedValueType.File)) {
// mooseModel.convertToFileEntry(clonedEntry);
// // Setup allowed values correctly
// String extension = FilenameUtils
// .getExtension(project.getFile(clonedEntry.getValue()).getLocation().toOSString());
// // Create a new content provider with the new file
// // in the allowed values list
// IEntryContentProvider prov = new BasicEntryContentProvider();
// ArrayList<String> valueList = clonedEntry.getAllowedValues();
// for (String file : getProjectFileNames(extension)) {
// if (!valueList.contains(file)) {
// valueList.add(file);
// prov.setAllowedValueType(AllowedValueType.File);
// // Finish setting the allowed values and default
// // value
// prov.setAllowedValues(valueList);
// // Set the new provider
// clonedEntry.setContentProvider(prov);
// // Set the value
// clonedEntry.setValue(e.getValue());
// fileEntryTreeMapping.put(clonedEntry.getName(), child);
// clonedEntry.register(this);
// // Add it to the list of model files.
// modelFiles.addEntry(clonedEntry);
}
}
}
}
return files;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ice.item.Item#update(org.eclipse.ice.item.messaging.Message)
*/
@Override
public boolean update(Message message) {
// Get the message type and string text
String type = message.getType();
String text = message.getMessage();
// Parse the message type
if ("MESSAGE_POSTED".equals(type)) {
// If its a message posted, we expect it to
// be of the format pp_name:time:value
String[] data = text.split(":");
String name = data[0];
Double time = Double.valueOf(data[1]);
Double value = Double.valueOf(data[2]);
// We need the jobLaunch directory to create new VizResources
String directory = mooseLauncher.getJobLaunchDirectory();
// Get a reference to the VizResource file we are going
// to create and populate
File dataFile = new File(directory + System.getProperty("file.separator") + name + ".csv");
// Get a reference to the ResourceComponent
ResourceComponent comp = (ResourceComponent) form.getComponent(3);
try {
if (!dataFile.exists()) {
// If the file hasn't been created yet, we need to create
// it and start filling it with post processor data
dataFile.createNewFile();
// Write the new incoming data
PrintWriter printWriter = new PrintWriter(new FileOutputStream(dataFile, true));
printWriter.write("Time, " + name + "\n");
printWriter.write(time + ", " + value + "\n");
printWriter.close();
// Create the VizResource, and add it to the
// ResourceComponent
ICEResource resource = getResource(dataFile.getAbsolutePath());
comp.add(resource);
// Remember the name of the resource for next time
postProcessorResources.put(name, resource);
} else {
// Write the data to the existing resource
PrintWriter printWriter = new PrintWriter(new FileOutputStream(dataFile, true));
printWriter.write(time + ", " + value + "\n");
// Update the ICEResource
ICEResource r = postProcessorResources.get(name);
// Here we are faking a VizResource notification
// by setting the name with its current name
r.setName(r.getName());
// Close the writer
printWriter.close();
}
} catch (IOException e) {
logger.error(getClass().getName() + " Exception!",e);
}
}
return true;
}
/**
* This private method takes the Postprocessor tree node and populates the
* postProcessorData DataComponent.
*
* @param ppTree
*/
private void setupPostprocessorData(TreeComposite ppTree) {
postProcessorsData.clearEntries();
for (int i = 0; i < ppTree.getNumberOfChildren(); i++) {
Entry ppEntry = new Entry() {
@Override
public void setup() {
allowedValueType = AllowedValueType.Discrete;
allowedValues.add("yes");
allowedValues.add("no");
defaultValue = "no";
}
};
ppEntry.setName(ppTree.getChildAtIndex(i).getName());
ppEntry.setDescription("Select whether this Postprocessor should be displayed in real-time.");
ppEntry.setId(i);
postProcessorsData.addEntry(ppEntry);
}
}
/**
* This operation is used to check equality between the MOOSE Item and
* another MOOSE Item. It returns true if the Items are equal and false if
* they are not.
*
* @param otherMoose
* The MOOSE Item that should be checked for equality.
* @return True if the launchers are equal, false if not
*/
@Override
public boolean equals(Object other) {
boolean retVal;
// Check if they are the same reference in memory
if (this == other) {
return true;
}
// Check that the object is not null, and that it is an Item
// Check that these objects have the same ICEObject data
if (other == null || !(other instanceof MOOSE) || !super.equals(other)) {
return false;
}
// Check data
MOOSE otherMoose = (MOOSE) other;
retVal = (this.allowedActions.equals(otherMoose.allowedActions)) && (this.form.equals(otherMoose.form))
&& (this.itemType == otherMoose.itemType) && (this.status.equals(otherMoose.status));
// Check project
if (this.project != null && otherMoose.project != null && (!(this.project.equals(otherMoose.project)))) {
return false;
}
// Check project - set to null
if (this.project == null && otherMoose.project != null || this.project != null && otherMoose.project == null) {
return false;
}
if (!mooseModel.equals(otherMoose.mooseModel) && !mooseLauncher.equals(otherMoose.mooseLauncher)) {
return false;
}
return retVal;
}
/**
* This operation returns the hashcode value of the MooseItem.
*
* @return
* <p>
* The hashcode
* </p>
*/
@Override
public int hashCode() {
// Local Declaration
int hash = 9;
// Compute hash code from Item data
hash = 31 * hash + super.hashCode();
hash = 31 * hash + mooseModel.hashCode();
hash = 31 * hash + mooseLauncher.hashCode();
return hash;
}
/**
* Copy the provided Item into this Item.
*
* @param otherMoose
* <p>
* This operation performs a deep copy of the attributes of
* another MOOSE Item into the current MOOSE Item.
* </p>
*/
@Override
public void copy(Item otherItem) {
// Return if otherMoose is null
if (otherItem == null) {
return;
}
// Cast to a MOOSE Item
MOOSE otherMoose = (MOOSE) otherItem;
// Copy contents into super and current object
super.copy(otherMoose);
// Add the model files component
modelFiles = (DataComponent) form.getComponent(1);
// Get a handle to the model input tree
modelTree = (TreeComposite) form.getComponent(2);
// Must do this or we can't walk the tree to
// get file entries correctly
mooseModel.setActiveDataNodes(modelTree);
return;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ice.item.Item#setProject(org.eclipse.core.resources.IProject)
*/
@Override
public void setProject(IProject projectSpace) {
super.setProject(projectSpace);
mooseModel.setProject(projectSpace);
mooseLauncher.setProject(projectSpace);
}
/**
* <p>
* This operation provides a deep copy of the MOOSE Item.
* </p>
*
* @return
* <p>
* A clone of the Moose Item.
* </p>
*/
@Override
public Object clone() {
// Create a new instance of JobLauncher and copy the contents
MOOSE clone = new MOOSE();
clone.copy(this);
return clone;
}
}
|
package org.javarosa.xform.parse;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Hashtable;
import org.javarosa.core.model.Constants;
import org.javarosa.core.model.DataBinding;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.GroupDef;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.instance.DataModelTree;
import org.javarosa.core.model.instance.QuestionDataElement;
import org.javarosa.core.model.instance.QuestionDataGroup;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.utils.Localizer;
import org.javarosa.model.xform.XPathReference;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParser;
/**
* Provides conversion from xform to epihandy object model and vice vasa.
*
* @author Daniel Kayiwa
*
*/
public class XFormParser {
public static final String NAMESPACE_JAVAROSA = "http://openrosa.org/javarosa";
private static Hashtable topLevelHandlers;
private static Hashtable groupLevelHandlers;
private static Hashtable typeMappings;
/* THIS CLASS IS NOT THREAD-SAFE */
//state variables -- not a good idea since this class is static, but that's not really a good idea either, now is it
private static boolean modelFound;
private static Hashtable bindingsByID;
private static Hashtable bindingsByRef;
private static Element instanceNode;
static {
initProcessingRules();
initTypeMappings();
}
/**
* Default Constructor
*
*/
public XFormParser(){
}
private static void initProcessingRules () {
IElementHandler title = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseTitle(f, e); } };
IElementHandler model = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseModel(f, e); } };
IElementHandler input = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseControl((IFormElement)parent, e, f, Constants.CONTROL_INPUT); } };
IElementHandler select = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseControl((IFormElement)parent, e, f, Constants.CONTROL_SELECT_MULTI); } };
IElementHandler select1 = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseControl((IFormElement)parent, e, f, Constants.CONTROL_SELECT_ONE); } };
IElementHandler group = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseGroup((IFormElement)parent, e, f, CONTAINER_GROUP); } };
IElementHandler repeat = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseGroup((IFormElement)parent, e, f, CONTAINER_REPEAT); } };
IElementHandler groupLabel = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseGroupLabel(f, (GroupDef)parent, e); } };
groupLevelHandlers = new Hashtable();
groupLevelHandlers.put("input", input);
groupLevelHandlers.put("select", select);
groupLevelHandlers.put("select1", select1);
groupLevelHandlers.put("group", group);
groupLevelHandlers.put("repeat", repeat);
topLevelHandlers = new Hashtable();
for (Enumeration en = groupLevelHandlers.keys(); en.hasMoreElements(); ) {
String key = (String)en.nextElement();
topLevelHandlers.put(key, groupLevelHandlers.get(key));
}
topLevelHandlers.put("model", model);
topLevelHandlers.put("title", title);
groupLevelHandlers.put("label", groupLabel);
}
private static void initTypeMappings () {
typeMappings = new Hashtable();
typeMappings.put("xsd:string", new Integer(Constants.DATATYPE_TEXT));
typeMappings.put("xsd:integer", new Integer(Constants.DATATYPE_INTEGER));
typeMappings.put("xsd:int", new Integer(Constants.DATATYPE_INTEGER));
typeMappings.put("xsd:decimal", new Integer(Constants.DATATYPE_DECIMAL));
typeMappings.put("xsd:double", new Integer(Constants.DATATYPE_DECIMAL));
typeMappings.put("xsd:float", new Integer(Constants.DATATYPE_DECIMAL));
typeMappings.put("xsd:dateTime", new Integer(Constants.DATATYPE_DATE_TIME));
typeMappings.put("xsd:date", new Integer(Constants.DATATYPE_DATE));
typeMappings.put("xsd:time", new Integer(Constants.DATATYPE_TIME));
typeMappings.put("xsd:gYear", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gMonth", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gDay", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gYearMonth", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gMonthDay", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:boolean", new Integer(Constants.DATATYPE_BOOLEAN));
typeMappings.put("xsd:base64Binary", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:hexBinary", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:anyURI", new Integer(Constants.DATATYPE_UNSUPPORTED));
}
private static void initStateVars () {
modelFound = false;
bindingsByID = new Hashtable();
bindingsByRef = new Hashtable();
instanceNode = null;
}
public static FormDef getFormDef (Reader reader) {
Document doc = getXMLDocument(reader);
try {
return getFormDef(doc);
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
public static Document getXMLDocument(Reader reader){
Document doc = new Document();
try{
KXmlParser parser = new KXmlParser();
parser.setInput(reader);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
doc.parse(parser);
} catch(Exception e){
e.printStackTrace();
}
return doc;
}
public static FormDef getFormDef(Document doc){
FormDef formDef = new FormDef();
initStateVars();
// Hashtable id2VarNameMap = new Hashtable();
// Hashtable relevants = new Hashtable();
parseElement(formDef, doc.getRootElement(), formDef, topLevelHandlers);
// addSkipRules(formDef,id2VarNameMap,relevants);
if(instanceNode != null) {
parseInstance(formDef, instanceNode);
}
initStateVars();
return formDef;
}
private static final int CONTAINER_GROUP = 1;
private static final int CONTAINER_REPEAT = 2;
private static void parseElement (FormDef f, Element e, Object parent, Hashtable handlers) {
// boolean allowUnknownElements, boolean allowText, boolean recurseUnknown) {
String name = e.getName();
IElementHandler eh = (IElementHandler)handlers.get(name);
if (eh != null) {
eh.handle(f, e, parent);
} else {
System.err.println("XForm Parse: Unrecognized element [" + name + "]. Ignoring and processing children...");
for (int i = 0; i < e.getChildCount(); i++) {
if (e.getType(i) == Element.ELEMENT) {
parseElement(f, e.getElement(i), parent, handlers);
}
}
}
}
private static void parseTitle (FormDef f, Element e) {
//Removed a line here about the form title not being null. Couldn't possibly think
//of why that would make sense. CTS - 7/21/2008
f.setName(getXMLText(e, true));
}
//for ease of parsing, we assume a model comes before the controls, which isn't necessarily mandated by the xforms spec
private static void parseModel (FormDef f, Element e) {
if (modelFound) {
System.err.println("Multiple models not supported. Ignoring subsequent models.");
return;
}
modelFound = true;
for (int i = 0; i < e.getChildCount(); i++) {
int type = e.getType(i);
Element child = (type == Node.ELEMENT ? e.getElement(i) : null);
String childName = (child != null ? child.getName() : null);
if ("itext".equals(childName)) {
parseIText(f, child);
} else if ("instance".equals(childName)) {
//Remove the parsing of instance nodes here in favor of parsing them
//at the end of the process. That will allow us to properly deal with
//bind types. ctsims@dimagi.com - Jul 23, 2008
instanceNode = child;
} else if ("bind".equals(childName)) {
parseBind(f, child);
} else {
if (type == Node.ELEMENT || type == Node.TEXT && getXMLText(e, i, true).length() != 0) {
throw new XFormParseException("Unrecognized context found within <model>");
}
}
}
}
private static void parseControl (IFormElement parent, Element e, FormDef f, int controlType) {
QuestionDef question = new QuestionDef();
DataBinding binding;
String ref = e.getAttributeValue(null, "ref");
String bind = e.getAttributeValue(null, "bind");
//for now we assume that all <bind>s and <ref>s specify one and only one node in their nodeset,
//and that a given data node is referenced by at most one <bind>
if (bind != null) {
binding = (DataBinding)bindingsByID.get(bind);
if (binding == null) {
throw new XFormParseException("XForm Parse: invalid binding ID");
}
} else if (ref != null) {
question.setBind(new XPathReference(ref));
binding = (DataBinding)bindingsByRef.get(ref);
//in the future, we may have multiple <bind>s that must be applied in succession
} else {
throw new XFormParseException("XForm Parse: input control with neither 'ref' nor 'bind'");
}
if (binding != null) {
attachBind(f, question, binding);
}
question.setControlType(controlType);
question.setAppearanceAttr(e.getAttributeValue(null, "appearance"));
for (int i = 0; i < e.getChildCount(); i++) {
int type = e.getType(i);
Element child = (type == Node.ELEMENT ? e.getElement(i) : null);
String childName = (child != null ? child.getName() : null);
if ("label".equals(childName)) {
parseQuestionLabel(f, question, child);
} else if ("hint".equals(childName)) {
parseHint(f, question, child);
} else if ((controlType == Constants.CONTROL_SELECT_MULTI ||
controlType == Constants.CONTROL_SELECT_ONE) && "item".equals(childName)) {
parseItem(f, question, child);
}
}
parent.addChild(question);
}
private static void parseQuestionLabel (FormDef f, QuestionDef q, Element e) {
String label = getXMLText(e, true);
String ref = e.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
String textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!(hasITextMapping(f, textRef) ||
(hasITextMapping(f, textRef + ";long") && hasITextMapping(f, textRef + ";short"))))
throw new XFormParseException("<label> text is not localizable for all locales");
q.setLongTextID(textRef + ";long", null);
q.setShortTextID(textRef + ";short", null);
} else {
throw new RuntimeException("malformed ref for <label>");
}
} else {
q.setLongText(label);
q.setShortText(label);
}
}
private static void parseGroupLabel (FormDef f, GroupDef g, Element e) {
String label = getXMLText(e, true);
String ref = e.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
String textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!(hasITextMapping(f, textRef) ||
(hasITextMapping(f, textRef + ";long") && hasITextMapping(f, textRef + ";short"))))
throw new XFormParseException("<label> text is not localizable for all locales");
g.setLongTextID(textRef + ";long", null);
g.setShortTextID(textRef + ";short", null);
} else {
throw new RuntimeException("malformed ref for <label>");
}
} else {
g.setLongText(label);
g.setShortText(label);
}
}
private static void parseHint (FormDef f, QuestionDef q, Element e) {
String hint = getXMLText(e, true);
String ref = e.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
String textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!hasITextMapping(f, textRef))
throw new XFormParseException("<hint> text is not localizable for all locales");
q.setHelpTextID(textRef, null);
} else {
throw new RuntimeException("malformed ref for <hint>");
}
} else {
q.setHelpText(hint);
}
}
private static void parseItem (FormDef f, QuestionDef q, Element e) {
String label = null;
String textRef = null;
String value = null;
for (int i = 0; i < e.getChildCount(); i++) {
int type = e.getType(i);
Element child = (type == Node.ELEMENT ? e.getElement(i) : null);
String childName = (child != null ? child.getName() : null);
if ("label".equals(childName)) {
label = getXMLText(child, true);
String ref = child.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!hasITextMapping(f, textRef))
throw new XFormParseException("<label> text is not localizable for all locales");
} else {
throw new XFormParseException("malformed ref for <hint>");
}
}
} else if ("value".equals(childName)) {
value = getXMLText(child, true);
}
}
if ((textRef == null && label == null) || value == null) {
throw new XFormParseException("<item> without proper <label> or <value>");
}
if (textRef != null) {
q.addSelectItemID(textRef, true, value);
} else {
q.addSelectItemID(label, false, value);
}
}
private static void parseGroup (IFormElement parent, Element e, FormDef f, int groupType) {
GroupDef group = new GroupDef();
if (groupType == CONTAINER_REPEAT) {
group.setRepeat(true);
}
//binding
parseElement(f, e, group, groupLevelHandlers);
parent.addChild(group);
}
/**
* KNOWN ISSUES WITH ITEXT
*
* 'long' and 'short' forms of text are only supported for input control labels at this time. all other
* situations (<hint> tags, <label>s within <item>s, etc.) should only reference text handles that have
* only the single, default form.
*/
private static void parseIText (FormDef f, Element itext) {
Localizer l = new Localizer(true, true);
f.setLocalizer(l);
l.registerLocalizable(f);
for (int i = 0; i < itext.getChildCount(); i++) {
Element trans = itext.getElement(i);
if (trans == null || !trans.getName().equals("translation"))
continue;
parseTranslation(l, trans);
}
if (l.getAvailableLocales().length == 0)
throw new XFormParseException("no <translation>s defined");
if (l.getDefaultLocale() == null)
l.setDefaultLocale(l.getAvailableLocales()[0]);
}
private static void parseTranslation (Localizer l, Element trans) {
String lang = trans.getAttributeValue("", "lang");
if (lang == null || lang.length() == 0)
throw new XFormParseException("no language specified for <translation>");
String isDefault = trans.getAttributeValue("", "default");
if (!l.addAvailableLocale(lang))
throw new XFormParseException("duplicate <translation> for same language");
if (isDefault != null) {
if (l.getDefaultLocale() != null)
throw new XFormParseException("more than one <translation> set as default");
l.setDefaultLocale(lang);
}
for (int j = 0; j < trans.getChildCount(); j++) {
Element text = trans.getElement(j);
if (text == null || !text.getName().equals("text"))
continue;
parseTextHandle(l, lang, text);
}
}
private static void parseTextHandle (Localizer l, String locale, Element text) {
String id = text.getAttributeValue("", "id");
if (id == null || id.length() == 0)
throw new XFormParseException("no id defined for <text>");
for (int k = 0; k < text.getChildCount(); k++) {
Element value = text.getElement(k);
if (value == null || !value.getName().equals("value"))
continue;
String form = value.getAttributeValue("", "form");
if (form != null && form.length() == 0)
form = null;
String data = getXMLText(value, 0, true);
if (data == null)
data = "";
String textID = (form == null ? id : id + ";" + form); //kind of a hack
if (l.hasMapping(locale, textID))
throw new XFormParseException("duplicate definition for text ID and form");
l.setLocaleMapping(locale, textID, data);
}
}
private static boolean hasITextMapping (FormDef form, String textID) {
Localizer l = form.getLocalizer();
return l.hasMapping(l.getDefaultLocale(), textID);
}
private static void parseBind (FormDef f, Element e) {
DataBinding binding = new DataBinding();
binding.setId(e.getAttributeValue("", "id"));
String nodeset = e.getAttributeValue(null, "nodeset");
if (nodeset == null) {
throw new XFormParseException("XForm Parse: <bind> without nodeset");
}
binding.setReference(new XPathReference(nodeset));
binding.setDataType(getDataType(e.getAttributeValue(null, "type")));
//constraints
//conditions
// if(child.getAttributeValue(null, "relevant") != null) {
// //#if debug.output==verbose
// System.out.println("Relevant!" + child.getAttributeValue(null,"relevant"));
// //#endif
// String relevancy = child.getAttributeValue(null, "relevant");
// relevants.put(relevancy, binding);
binding.setRequired("true()".equals(e.getAttributeValue(null, "required")));
binding.setPreload(e.getAttributeValue(NAMESPACE_JAVAROSA, "preload"));
binding.setPreloadParams(e.getAttributeValue(NAMESPACE_JAVAROSA, "preloadParams"));
addBinding(f, binding);
}
private static void addBinding (FormDef f, DataBinding binding) {
f.addBinding(binding);
if (binding.getId() != null) {
if (bindingsByID.put(binding.getId(), binding) != null) {
throw new XFormParseException("XForm Parse: <bind>s with duplicate ID");
}
}
bindingsByRef.put(binding.getId(), binding);
}
private static void parseInstance (FormDef f, Element e) {
Element dataElement = null;
for (int i = 0; i < e.getChildCount(); i++) {
if (e.getType(i) == Node.ELEMENT) {
if (dataElement != null) {
throw new XFormParseException("XForm Parse: <instance> has more than one child element");
} else {
dataElement = e.getElement(i);
}
}
}
TreeElement root = parseInstanceNodes(dataElement, "/").getRoot();
DataModelTree instanceModel = new DataModelTree(root);
instanceModel.setName(f.getName());
f.setDataModel(instanceModel);
}
private static TreeElement parseInstanceNodes (Element node, String currentPath) {
int childNum = node.getChildCount();
TreeElement element;
if(childNum == 0) {
XPathReference reference = new XPathReference(currentPath + node.getName());
element = new QuestionDataElement(node.getName(), reference);
} else {
element = new QuestionDataGroup(node.getName());
for(int i = 0 ; i < childNum ; ++i ) {
if (node.getType(i) != Node.ELEMENT)
continue;
String newPath = currentPath + node.getName() + "/";
((QuestionDataGroup)element).addChild(parseInstanceNodes(node.getElement(i), newPath));
}
}
return element;
}
private static void attachBind(FormDef f, QuestionDef q, DataBinding binding) {
if (q.getBind() == null) {
q.setBind(binding.getReference());
}
q.setDataType(binding.getDataType());
//constraints?
//conditions?
q.setRequired(binding.isRequired());
}
private static int getDataType (String type) {
int dataType = -1;
if (type != null && typeMappings.containsKey(type)) {
dataType = ((Integer)typeMappings.get(type)).intValue();
}
if (dataType <= 0) {
if (type != null) {
System.err.println("XForm Parse: unrecognized data type; default to string");
}
dataType = Constants.DATATYPE_TEXT;
}
return dataType;
}
public static String getXMLText (Node n, boolean trim) {
return (n.getChildCount() == 0 ? null : getXMLText(n, 0, trim));
}
//reads all subsequent text nodes and returns the combined string
//needed because escape sequences are parsed into consecutive text nodes
//e.g. "abc&123" --> (abc)(&)(123)
public static String getXMLText (Node node, int i, boolean trim) {
StringBuffer strBuff = null;
String text = node.getText(i);
if (text == null)
return null;
for (i++; i < node.getChildCount() && node.getType(i) == Node.TEXT; i++) {
if (strBuff == null)
strBuff = new StringBuffer(text);
strBuff.append(node.getText(i));
}
if (strBuff != null)
text = strBuff.toString();
if (trim)
text = text.trim();
return text;
}
// private static void addSkipRules(FormDef formDef, Hashtable map, Hashtable relevants){
// Vector rules = new Vector();
// //Rules is vector of strings that contain the "relevant=" thing
// Enumeration en = relevants.keys();
// byte ruleId = 0;
// while(en.hasMoreElements()) {
// String relevant = (String)en.nextElement();
// DataBinding bind = (DataBinding)relevants.get(relevant);
// int split = relevant.indexOf("=");
// if(split != -1) {
// //TODO: Consolidate these by the relevant element: Many questionss depend on the same condition
// String relevantQuestionPath = relevant.substring(0, split);
// String relevantAnswer = relevant.substring(split+1, relevant.length()-1);
// QuestionDef thetarget = (QuestionDef) formDef.getQuestion(relevantQuestionPath);
// if (thetarget != null) {
// Vector conditions = new Vector();
// Vector actionTargets = new Vector();
// Condition condition = new Condition(ruleId, thetarget.getId(), Constants.OPERATOR_EQUAL, relevantAnswer);
// conditions.addElement(condition);
// XPathReference reference = (XPathReference)bind.getReference();
// actionTargets.addElement(reference.getReference());
// SkipRule rule = new SkipRule(ruleId, conditions,
// Constants.ACTION_ENABLE, actionTargets, relevant);
// rules.addElement(rule);
// ruleId++;
// //#if debug.output==verbose
// System.out.println("New rule added: id: " + ruleId
// + " Conditions: " + conditions.toString()
// + " actionTargets : " + actionTargets.toString());
// //#endif
// else {
// //Is there a form of relevancy that isn't an equality?
// formDef.setRules(rules);
// private static void setDefaultValues(Element dataNode,FormDef formDef,Hashtable id2VarNameMap){
// String id, val;
// Enumeration keys = id2VarNameMap.keys();
// while(keys.hasMoreElements()){
// id = (String)keys.nextElement();
// val = getNodeTextValue(dataNode,id);
// if(val == null || val.trim().length() == 0) //we are not allowing empty strings for now.
// continue;
// QuestionDef def = formDef.getQuestion((String)id2VarNameMap.get(id));
// if(def != null)
// def.setDefaultValue(val);
// private static String getNodeTextValue(Element dataNode,String name){
// Element node = getNode(dataNode,name);
// return getTextValue(node);
// private static String getTextValue(Element node){
// int numOfEntries = node.getChildCount();
// for (int i = 0; i < numOfEntries; i++) {
// if (node.isText(i))
// return node.getText(i);
// if(node.getType(i) == Element.ELEMENT){
// String val = getTextValue(node.getElement(i));
// if(val != null)
// return val;
// return null;
// /**
// * Gets a child element of a parent node with a given name.
// *
// * @param parent - the parent element
// * @param name - the name of the child.
// * @return - the child element.
// */
// private static Element getNode(Element parent, String name){
// for(int i=0; i<parent.getChildCount(); i++){
// if(parent.getType(i) != Element.ELEMENT)
// continue;
// Element child = (Element)parent.getChild(i);
// if(child.getName().equals(name))
// return child;
// child = getNode(child,name);
// if(child != null)
// return child;
// return null;
}
|
package org.javarosa.xform.parse;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Hashtable;
import org.javarosa.core.model.Constants;
import org.javarosa.core.model.DataBinding;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.GroupDef;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.instance.DataModelTree;
import org.javarosa.core.model.instance.QuestionDataElement;
import org.javarosa.core.model.instance.QuestionDataGroup;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.utils.Localizer;
import org.javarosa.model.xform.XPathReference;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParser;
/**
* Provides conversion from xform to epihandy object model and vice vasa.
*
* @author Daniel Kayiwa
*
*/
public class XFormParser {
public static final String NAMESPACE_JAVAROSA = "http://openrosa.org/javarosa";
private static Hashtable topLevelHandlers;
private static Hashtable groupLevelHandlers;
private static Hashtable typeMappings;
/* THIS CLASS IS NOT THREAD-SAFE */
//state variables -- not a good idea since this class is static, but that's not really a good idea either, now is it
private static boolean modelFound;
private static Hashtable bindingsByID;
private static Hashtable bindingsByRef;
static {
initProcessingRules();
initTypeMappings();
}
/**
* Default Constructor
*
*/
public XFormParser(){
}
private static void initProcessingRules () {
IElementHandler title = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseTitle(f, e); } };
IElementHandler model = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseModel(f, e); } };
IElementHandler input = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseControl((IFormElement)parent, e, f, Constants.CONTROL_INPUT); } };
IElementHandler select = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseControl((IFormElement)parent, e, f, Constants.CONTROL_SELECT_MULTI); } };
IElementHandler select1 = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseControl((IFormElement)parent, e, f, Constants.CONTROL_SELECT_ONE); } };
IElementHandler group = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseGroup((IFormElement)parent, e, f, CONTAINER_GROUP); } };
IElementHandler repeat = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseGroup((IFormElement)parent, e, f, CONTAINER_REPEAT); } };
IElementHandler groupLabel = new IElementHandler () {
public void handle (FormDef f, Element e, Object parent) { parseGroupLabel(f, (GroupDef)parent, e); } };
groupLevelHandlers = new Hashtable();
groupLevelHandlers.put("input", input);
groupLevelHandlers.put("select", select);
groupLevelHandlers.put("select1", select1);
groupLevelHandlers.put("group", group);
groupLevelHandlers.put("repeat", repeat);
topLevelHandlers = new Hashtable();
for (Enumeration en = groupLevelHandlers.keys(); en.hasMoreElements(); ) {
String key = (String)en.nextElement();
topLevelHandlers.put(key, groupLevelHandlers.get(key));
}
topLevelHandlers.put("model", model);
topLevelHandlers.put("title", title);
groupLevelHandlers.put("label", groupLabel);
}
private static void initTypeMappings () {
typeMappings = new Hashtable();
typeMappings.put("xsd:string", new Integer(Constants.DATATYPE_TEXT));
typeMappings.put("xsd:integer", new Integer(Constants.DATATYPE_INTEGER));
typeMappings.put("xsd:int", new Integer(Constants.DATATYPE_INTEGER));
typeMappings.put("xsd:decimal", new Integer(Constants.DATATYPE_DECIMAL));
typeMappings.put("xsd:double", new Integer(Constants.DATATYPE_DECIMAL));
typeMappings.put("xsd:float", new Integer(Constants.DATATYPE_DECIMAL));
typeMappings.put("xsd:dateTime", new Integer(Constants.DATATYPE_DATE_TIME));
typeMappings.put("xsd:date", new Integer(Constants.DATATYPE_DATE));
typeMappings.put("xsd:time", new Integer(Constants.DATATYPE_TIME));
typeMappings.put("xsd:gYear", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gMonth", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gDay", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gYearMonth", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:gMonthDay", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:boolean", new Integer(Constants.DATATYPE_BOOLEAN));
typeMappings.put("xsd:base64Binary", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:hexBinary", new Integer(Constants.DATATYPE_UNSUPPORTED));
typeMappings.put("xsd:anyURI", new Integer(Constants.DATATYPE_UNSUPPORTED));
}
private static void initStateVars () {
modelFound = false;
bindingsByID = new Hashtable();
bindingsByRef = new Hashtable();
}
public static FormDef getFormDef (Reader reader) {
Document doc = getXMLDocument(reader);
try {
return getFormDef(doc);
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
public static Document getXMLDocument(Reader reader){
Document doc = new Document();
try{
KXmlParser parser = new KXmlParser();
parser.setInput(reader);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
doc.parse(parser);
} catch(Exception e){
e.printStackTrace();
}
return doc;
}
public static FormDef getFormDef(Document doc){
FormDef formDef = new FormDef();
initStateVars();
// Hashtable id2VarNameMap = new Hashtable();
// Hashtable relevants = new Hashtable();
parseElement(formDef, doc.getRootElement(), formDef, topLevelHandlers);
// addSkipRules(formDef,id2VarNameMap,relevants);
initStateVars();
return formDef;
}
private static final int CONTAINER_GROUP = 1;
private static final int CONTAINER_REPEAT = 2;
private static void parseElement (FormDef f, Element e, Object parent, Hashtable handlers) {
// boolean allowUnknownElements, boolean allowText, boolean recurseUnknown) {
String name = e.getName();
IElementHandler eh = (IElementHandler)handlers.get(name);
if (eh != null) {
eh.handle(f, e, parent);
} else {
System.err.println("XForm Parse: Unrecognized element [" + name + "]. Ignoring and processing children...");
for (int i = 0; i < e.getChildCount(); i++) {
if (e.getType(i) == Element.ELEMENT) {
parseElement(f, e.getElement(i), parent, handlers);
}
}
}
}
private static void parseTitle (FormDef f, Element e) {
//Removed a line here about the form title not being null. Couldn't possibly think
//of why that would make sense. CTS - 7/21/2008
f.setName(getXMLText(e, true));
}
//for ease of parsing, we assume a model comes before the controls, which isn't necessarily mandated by the xforms spec
private static void parseModel (FormDef f, Element e) {
if (modelFound) {
System.err.println("Multiple models not supported. Ignoring subsequent models.");
return;
}
modelFound = true;
for (int i = 0; i < e.getChildCount(); i++) {
int type = e.getType(i);
Element child = (type == Node.ELEMENT ? e.getElement(i) : null);
String childName = (child != null ? child.getName() : null);
if ("itext".equals(childName)) {
parseIText(f, child);
} else if ("instance".equals(childName)) {
parseInstance(f, child);
} else if ("bind".equals(childName)) {
parseBind(f, child);
} else {
if (type == Node.ELEMENT || type == Node.TEXT && getXMLText(e, i, true).length() != 0) {
throw new XFormParseException("Unrecognized context found within <model>");
}
}
}
}
private static void parseControl (IFormElement parent, Element e, FormDef f, int controlType) {
QuestionDef question = new QuestionDef();
DataBinding binding;
String ref = e.getAttributeValue(null, "ref");
String bind = e.getAttributeValue(null, "bind");
//for now we assume that all <bind>s and <ref>s specify one and only one node in their nodeset,
//and that a given data node is referenced by at most one <bind>
if (bind != null) {
binding = (DataBinding)bindingsByID.get(bind);
if (binding == null) {
throw new XFormParseException("XForm Parse: invalid binding ID");
}
} else if (ref != null) {
question.setBind(new XPathReference(ref));
binding = (DataBinding)bindingsByRef.get(ref);
//in the future, we may have multiple <bind>s that must be applied in succession
} else {
throw new XFormParseException("XForm Parse: input control with neither 'ref' nor 'bind'");
}
if (binding != null) {
attachBind(f, question, binding);
}
question.setControlType(controlType);
question.setAppearanceAttr(e.getAttributeValue(null, "appearance"));
for (int i = 0; i < e.getChildCount(); i++) {
int type = e.getType(i);
Element child = (type == Node.ELEMENT ? e.getElement(i) : null);
String childName = (child != null ? child.getName() : null);
if ("label".equals(childName)) {
parseQuestionLabel(f, question, child);
} else if ("hint".equals(childName)) {
parseHint(f, question, child);
} else if ((controlType == Constants.CONTROL_SELECT_MULTI ||
controlType == Constants.CONTROL_SELECT_ONE) && "item".equals(childName)) {
parseItem(f, question, child);
}
}
parent.addChild(question);
}
private static void parseQuestionLabel (FormDef f, QuestionDef q, Element e) {
String label = getXMLText(e, true);
String ref = e.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
String textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!(hasITextMapping(f, textRef) ||
(hasITextMapping(f, textRef + ";long") && hasITextMapping(f, textRef + ";short"))))
throw new XFormParseException("<label> text is not localizable for all locales");
q.setLongTextID(textRef + ";long", null);
q.setShortTextID(textRef + ";short", null);
} else {
throw new RuntimeException("malformed ref for <label>");
}
} else {
q.setLongText(label);
q.setShortText(label);
}
}
private static void parseGroupLabel (FormDef f, GroupDef g, Element e) {
String label = getXMLText(e, true);
String ref = e.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
String textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!(hasITextMapping(f, textRef) ||
(hasITextMapping(f, textRef + ";long") && hasITextMapping(f, textRef + ";short"))))
throw new XFormParseException("<label> text is not localizable for all locales");
g.setLongTextID(textRef + ";long", null);
g.setShortTextID(textRef + ";short", null);
} else {
throw new RuntimeException("malformed ref for <label>");
}
} else {
g.setLongText(label);
g.setShortText(label);
}
}
private static void parseHint (FormDef f, QuestionDef q, Element e) {
String hint = getXMLText(e, true);
String ref = e.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
String textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!hasITextMapping(f, textRef))
throw new XFormParseException("<hint> text is not localizable for all locales");
q.setHelpTextID(textRef, null);
} else {
throw new RuntimeException("malformed ref for <hint>");
}
} else {
q.setHelpText(hint);
}
}
private static void parseItem (FormDef f, QuestionDef q, Element e) {
String label = null;
String textRef = null;
String value = null;
for (int i = 0; i < e.getChildCount(); i++) {
int type = e.getType(i);
Element child = (type == Node.ELEMENT ? e.getElement(i) : null);
String childName = (child != null ? child.getName() : null);
if ("label".equals(childName)) {
label = getXMLText(child, true);
String ref = child.getAttributeValue("", "ref");
if (ref != null) {
if (ref.startsWith("jr:itext('") && ref.endsWith("')")) {
textRef = ref.substring("jr:itext('".length(), ref.indexOf("')"));
if (!hasITextMapping(f, textRef))
throw new XFormParseException("<label> text is not localizable for all locales");
} else {
throw new XFormParseException("malformed ref for <hint>");
}
}
} else if ("value".equals(childName)) {
value = getXMLText(child, true);
}
}
if ((textRef == null && label == null) || value == null) {
throw new XFormParseException("<item> without proper <label> or <value>");
}
if (textRef != null) {
q.addSelectItemID(textRef, true, value);
} else {
q.addSelectItemID(label, false, value);
}
}
private static void parseGroup (IFormElement parent, Element e, FormDef f, int groupType) {
GroupDef group = new GroupDef();
if (groupType == CONTAINER_REPEAT) {
group.setRepeat(true);
}
//binding
parseElement(f, e, group, groupLevelHandlers);
parent.addChild(group);
}
/**
* KNOWN ISSUES WITH ITEXT
*
* 'long' and 'short' forms of text are only supported for input control labels at this time. all other
* situations (<hint> tags, <label>s within <item>s, etc.) should only reference text handles that have
* only the single, default form.
*/
private static void parseIText (FormDef f, Element itext) {
Localizer l = new Localizer(true, true);
f.setLocalizer(l);
l.registerLocalizable(f);
for (int i = 0; i < itext.getChildCount(); i++) {
Element trans = itext.getElement(i);
if (trans == null || !trans.getName().equals("translation"))
continue;
parseTranslation(l, trans);
}
if (l.getAvailableLocales().length == 0)
throw new XFormParseException("no <translation>s defined");
if (l.getDefaultLocale() == null)
l.setDefaultLocale(l.getAvailableLocales()[0]);
}
private static void parseTranslation (Localizer l, Element trans) {
String lang = trans.getAttributeValue("", "lang");
if (lang == null || lang.length() == 0)
throw new XFormParseException("no language specified for <translation>");
String isDefault = trans.getAttributeValue("", "default");
if (!l.addAvailableLocale(lang))
throw new XFormParseException("duplicate <translation> for same language");
if (isDefault != null) {
if (l.getDefaultLocale() != null)
throw new XFormParseException("more than one <translation> set as default");
l.setDefaultLocale(lang);
}
for (int j = 0; j < trans.getChildCount(); j++) {
Element text = trans.getElement(j);
if (text == null || !text.getName().equals("text"))
continue;
parseTextHandle(l, lang, text);
}
}
private static void parseTextHandle (Localizer l, String locale, Element text) {
String id = text.getAttributeValue("", "id");
if (id == null || id.length() == 0)
throw new XFormParseException("no id defined for <text>");
for (int k = 0; k < text.getChildCount(); k++) {
Element value = text.getElement(k);
if (value == null || !value.getName().equals("value"))
continue;
String form = value.getAttributeValue("", "form");
if (form != null && form.length() == 0)
form = null;
String data = getXMLText(value, 0, true);
if (data == null)
data = "";
String textID = (form == null ? id : id + ";" + form); //kind of a hack
if (l.hasMapping(locale, textID))
throw new XFormParseException("duplicate definition for text ID and form");
l.setLocaleMapping(locale, textID, data);
}
}
private static boolean hasITextMapping (FormDef form, String textID) {
Localizer l = form.getLocalizer();
return l.hasMapping(l.getDefaultLocale(), textID);
}
private static void parseBind (FormDef f, Element e) {
DataBinding binding = new DataBinding();
binding.setId(e.getAttributeValue("", "id"));
String nodeset = e.getAttributeValue(null, "nodeset");
if (nodeset == null) {
throw new XFormParseException("XForm Parse: <bind> without nodeset");
}
binding.setReference(new XPathReference(nodeset));
binding.setDataType(getDataType(e.getAttributeValue(null, "type")));
//constraints
//conditions
// if(child.getAttributeValue(null, "relevant") != null) {
// //#if debug.output==verbose
// System.out.println("Relevant!" + child.getAttributeValue(null,"relevant"));
// //#endif
// String relevancy = child.getAttributeValue(null, "relevant");
// relevants.put(relevancy, binding);
binding.setRequired("true()".equals(e.getAttributeValue(null, "required")));
binding.setPreload(e.getAttributeValue(NAMESPACE_JAVAROSA, "preload"));
binding.setPreloadParams(e.getAttributeValue(NAMESPACE_JAVAROSA, "preloadParams"));
addBinding(f, binding);
}
private static void addBinding (FormDef f, DataBinding binding) {
f.addBinding(binding);
if (binding.getId() != null) {
if (bindingsByID.put(binding.getId(), binding) != null) {
throw new XFormParseException("XForm Parse: <bind>s with duplicate ID");
}
}
bindingsByRef.put(binding.getId(), binding);
}
private static void parseInstance (FormDef f, Element e) {
Element dataElement = null;
for (int i = 0; i < e.getChildCount(); i++) {
if (e.getType(i) == Node.ELEMENT) {
if (dataElement != null) {
throw new XFormParseException("XForm Parse: <instance> has more than one child element");
} else {
dataElement = e.getElement(i);
}
}
}
TreeElement root = parseInstanceNodes(dataElement, "/").getRoot();
DataModelTree instanceModel = new DataModelTree(root);
f.setDataModel(instanceModel);
}
private static TreeElement parseInstanceNodes (Element node, String currentPath) {
int childNum = node.getChildCount();
TreeElement element;
if(childNum == 0) {
XPathReference reference = new XPathReference(currentPath + node.getName());
element = new QuestionDataElement(node.getName(), reference);
} else {
element = new QuestionDataGroup(node.getName());
for(int i = 0 ; i < childNum ; ++i ) {
if (node.getType(i) != Node.ELEMENT)
continue;
String newPath = currentPath + node.getName() + "/";
((QuestionDataGroup)element).addChild(parseInstanceNodes(node.getElement(i), newPath));
}
}
return element;
}
private static void attachBind(FormDef f, QuestionDef q, DataBinding binding) {
if (q.getBind() == null) {
q.setBind(binding.getReference());
}
q.setDataType(binding.getDataType());
//constraints?
//conditions?
q.setRequired(binding.isRequired());
}
private static int getDataType (String type) {
int dataType = -1;
if (type != null && typeMappings.containsKey(type)) {
dataType = ((Integer)typeMappings.get(type)).intValue();
}
if (dataType <= 0) {
if (type != null) {
System.err.println("XForm Parse: unrecognized data type; default to string");
}
dataType = Constants.DATATYPE_TEXT;
}
return dataType;
}
public static String getXMLText (Node n, boolean trim) {
return (n.getChildCount() == 0 ? null : getXMLText(n, 0, trim));
}
//reads all subsequent text nodes and returns the combined string
//needed because escape sequences are parsed into consecutive text nodes
//e.g. "abc&123" --> (abc)(&)(123)
public static String getXMLText (Node node, int i, boolean trim) {
StringBuffer strBuff = null;
String text = node.getText(i);
if (text == null)
return null;
for (i++; i < node.getChildCount() && node.getType(i) == Node.TEXT; i++) {
if (strBuff == null)
strBuff = new StringBuffer(text);
strBuff.append(node.getText(i));
}
if (strBuff != null)
text = strBuff.toString();
if (trim)
text = text.trim();
return text;
}
// private static void addSkipRules(FormDef formDef, Hashtable map, Hashtable relevants){
// Vector rules = new Vector();
// //Rules is vector of strings that contain the "relevant=" thing
// Enumeration en = relevants.keys();
// byte ruleId = 0;
// while(en.hasMoreElements()) {
// String relevant = (String)en.nextElement();
// DataBinding bind = (DataBinding)relevants.get(relevant);
// int split = relevant.indexOf("=");
// if(split != -1) {
// //TODO: Consolidate these by the relevant element: Many questionss depend on the same condition
// String relevantQuestionPath = relevant.substring(0, split);
// String relevantAnswer = relevant.substring(split+1, relevant.length()-1);
// QuestionDef thetarget = (QuestionDef) formDef.getQuestion(relevantQuestionPath);
// if (thetarget != null) {
// Vector conditions = new Vector();
// Vector actionTargets = new Vector();
// Condition condition = new Condition(ruleId, thetarget.getId(), Constants.OPERATOR_EQUAL, relevantAnswer);
// conditions.addElement(condition);
// XPathReference reference = (XPathReference)bind.getReference();
// actionTargets.addElement(reference.getReference());
// SkipRule rule = new SkipRule(ruleId, conditions,
// Constants.ACTION_ENABLE, actionTargets, relevant);
// rules.addElement(rule);
// ruleId++;
// //#if debug.output==verbose
// System.out.println("New rule added: id: " + ruleId
// + " Conditions: " + conditions.toString()
// + " actionTargets : " + actionTargets.toString());
// //#endif
// else {
// //Is there a form of relevancy that isn't an equality?
// formDef.setRules(rules);
// private static void setDefaultValues(Element dataNode,FormDef formDef,Hashtable id2VarNameMap){
// String id, val;
// Enumeration keys = id2VarNameMap.keys();
// while(keys.hasMoreElements()){
// id = (String)keys.nextElement();
// val = getNodeTextValue(dataNode,id);
// if(val == null || val.trim().length() == 0) //we are not allowing empty strings for now.
// continue;
// QuestionDef def = formDef.getQuestion((String)id2VarNameMap.get(id));
// if(def != null)
// def.setDefaultValue(val);
// private static String getNodeTextValue(Element dataNode,String name){
// Element node = getNode(dataNode,name);
// return getTextValue(node);
// private static String getTextValue(Element node){
// int numOfEntries = node.getChildCount();
// for (int i = 0; i < numOfEntries; i++) {
// if (node.isText(i))
// return node.getText(i);
// if(node.getType(i) == Element.ELEMENT){
// String val = getTextValue(node.getElement(i));
// if(val != null)
// return val;
// return null;
// /**
// * Gets a child element of a parent node with a given name.
// *
// * @param parent - the parent element
// * @param name - the name of the child.
// * @return - the child element.
// */
// private static Element getNode(Element parent, String name){
// for(int i=0; i<parent.getChildCount(); i++){
// if(parent.getType(i) != Element.ELEMENT)
// continue;
// Element child = (Element)parent.getChild(i);
// if(child.getName().equals(name))
// return child;
// child = getNode(child,name);
// if(child != null)
// return child;
// return null;
}
// /**
// * Loads JavaRosa pre-loadable values into defaults for questions. A lot of this needs serious refactoring so
// * we're going to rely on it not functioning properly until it's been integrated better.
// *
// * @param loadMode
// * @param loadParams
// * @return
// */
// public static Object getPreloadValue (String loadMode, String loadParams) {
// Object preloadVal = null;
// if (loadMode.equals("date")) {
// Date d = null;
// if (loadParams.equals("today")) {
// d = new Date();
// } else if (loadParams.substring(0, 11).equals("prevperiod-")) {
// //String[] params = J2MEUtil.split(loadParams.substring(11), "-");
// //try {
// // String type = params[0];
// // String start = params[1];
// // boolean beginning;
// // if (params[2].equals("head")) beginning = true;
// // else if (params[2].equals("tail")) beginning = false;
// // else throw new RuntimeException();
// // boolean includeToday;
// // if (params.length >= 4) {
// // if (params[3].equals("x")) includeToday = true;
// // else if (params[3].equals("")) includeToday = false;
// // else throw new RuntimeException();
// // } else {
// // includeToday = false;
// // int nAgo;
// // if (params.length >= 5) {
// // nAgo = Integer.parseInt(params[4]);
// // } else {
// // nAgo = 1;
// // d = getPastPeriodDate(new Date(), type, start, beginning, includeToday, nAgo);
// //} catch (Exception e) {
// //preloadVal = d;
// } else if (loadMode.equals("property")) {
// String propname = loadParams;
// //String propval = PropertyManager.instance().getSingularProperty(propname);
// //if (propval != null && propval.length() > 0)
// // preloadVal = propval;
// } else if (loadMode.equals("timestamp")) {
// //if (loadParams.equals("start"))
// // preloadVal = J2MEUtil.formatDateToTimeStamp(new Date());
// } else {
// return preloadVal;
|
package MWC.GUI.JFreeChart;
import java.awt.Color;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimePeriod;
import org.jfree.data.time.TimeSeriesDataItem;
import MWC.GUI.Editable;
// add a coloru to the data item pair
public class ColouredDataItem extends TimeSeriesDataItem implements AttractiveDataItem {
public static interface OffsetProvider {
/**
* offset the provided time by the desired amount
*
* @param val the actual time value
* @return the processed time value
*/
public long offsetTimeFor(long val);
}
/**
* marker interface for data sources for which it's reasonable to optionally
* show markers
*
*/
public static interface ShowMarker {
}
private static final long serialVersionUID = 1L;
/**
* the color for this item
*/
private Color _myColor;
/**
* whether to connect this data item to the previous one
*
*/
private final boolean _connectToPrevious;
/**
* the provider for the time offset
*
*/
private transient OffsetProvider _provider;
/**
* whether the symbol is visible in the parent object for this data item
*/
private final boolean _parentSymVisible;
private final boolean _isFilled;
/**
* (optionally) store the Debrief item that is being represented by this chart
* point
*/
private transient Editable _payload;
/**
* Constructs a new data pair.
*
* @param period the time period.
* @param value the value associated with the time period.
* @param myColor the color for this point
* @param connectToPrevious whether to connect to the previous point (used when
* we're passing through zero)
* @param provider If we're plotting relative times, this is an object
* which can supply the zero time to use
* @param parentSymVisible whether the parent object this relates to is visible
* @param isFilled whether we want this shape to be filled
* @see ColouredDataItem#ColouredDataItem(TimePeriod period,double value,Color
* myColor,boolean connectToPrevious)
*/
public ColouredDataItem(final RegularTimePeriod period, final double value, final Color myColor,
final boolean connectToPrevious, final OffsetProvider provider, final boolean parentSymVisible,
final boolean isFilled) {
this(period, value, myColor, connectToPrevious, provider, parentSymVisible, isFilled, null);
}
/**
* Constructs a new data pair.
*
* @param period the time period.
* @param value the value associated with the time period.
* @param myColor the color for this point
* @param connectToPrevious whether to connect to the previous point (used when
* we're passing through zero)
* @param provider If we're plotting relative times, this is an object
* which can supply the zero time to use
* @param parentSymVisible whether the parent object this relates to is visible
* @param isFilled whether we want this shape to be filled
* @see ColouredDataItem#ColouredDataItem(TimePeriod period,double value,Color
* myColor,boolean connectToPrevious)
*/
public ColouredDataItem(final RegularTimePeriod period, final double value, final Color myColor,
final boolean connectToPrevious, final OffsetProvider provider, final boolean parentSymVisible,
final boolean isFilled, final Editable payload) {
super(period, value);
_myColor = myColor;
_connectToPrevious = connectToPrevious;
_provider = provider;
_parentSymVisible = parentSymVisible;
_isFilled = isFilled;
_payload = payload;
}
/**
* whether to connect this data point to the previous one
*
* @return yes/no to connect
*/
@Override
public boolean connectToPrevious() {
return _connectToPrevious;
}
/**
* get the color for this point
*
* @return the color
*/
@Override
public final Color getColor() {
return _myColor;
}
/**
* the data item that we're rendering
*
* @return
*/
public Editable getPayload() {
return _payload;
}
/**
* Returns the time period.
*
* @return the time period.
*/
@Override
public RegularTimePeriod getPeriod() {
RegularTimePeriod res = super.getPeriod();
if (_provider != null) {
res = new FixedMillisecond(_provider.offsetTimeFor(res.getMiddleMillisecond()));
}
return res;
}
/**
* whether the parent object this item refers to is visible
*
* @return
*/
public boolean isParentSymVisible() {
return _parentSymVisible;
}
/**
* whether we wish this shape to be filled
*
* @return
*/
public boolean isShapeFilled() {
return _isFilled;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.