answer
stringlengths
17
10.2M
package com.jme3.texture; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.texture.image.ColorSpace; import java.io.IOException; /** * @author Joshua Slack */ public class Texture2D extends Texture { private WrapMode wrapS = WrapMode.EdgeClamp; private WrapMode wrapT = WrapMode.EdgeClamp; /** * Creates a new two-dimensional texture with default attributes. */ public Texture2D(){ super(); } /** * Creates a new two-dimensional texture using the given image. * @param img The image to use. */ public Texture2D(Image img){ super(); setImage(img); if (img.getData(0) == null) { setMagFilter(MagFilter.Nearest); setMinFilter(MinFilter.NearestNoMipMaps); } } /** * Creates a new two-dimensional texture for the purpose of offscreen * rendering. * * @see com.jme3.texture.FrameBuffer * * @param width * @param height * @param format */ public Texture2D(int width, int height, Image.Format format){ this(new Image(format, width, height, null, ColorSpace.Linear)); } /** * Creates a new two-dimensional texture for the purpose of offscreen * rendering. * * @see com.jme3.texture.FrameBuffer * * @param width * @param height * @param format * @param numSamples */ public Texture2D(int width, int height, int numSamples, Image.Format format){ this(new Image(format, width, height, null, ColorSpace.Linear)); getImage().setMultiSamples(numSamples); } @Override public Texture createSimpleClone() { Texture2D clone = new Texture2D(); createSimpleClone(clone); return clone; } @Override public Texture createSimpleClone(Texture rVal) { rVal.setWrap(WrapAxis.S, wrapS); rVal.setWrap(WrapAxis.T, wrapT); return super.createSimpleClone(rVal); } public void setWrap(WrapAxis axis, WrapMode mode) { if (mode == null) { throw new IllegalArgumentException("mode can not be null."); } else if (axis == null) { throw new IllegalArgumentException("axis can not be null."); } switch (axis) { case S: this.wrapS = mode; break; case T: this.wrapT = mode; break; default: throw new IllegalArgumentException("Not applicable for 2D textures"); } } public void setWrap(WrapMode mode) { if (mode == null) { throw new IllegalArgumentException("mode can not be null."); } this.wrapS = mode; this.wrapT = mode; } public WrapMode getWrap(WrapAxis axis) { switch (axis) { case S: return wrapS; case T: return wrapT; default: throw new IllegalArgumentException("invalid WrapAxis: " + axis); } } @Override public Type getType() { return Type.TwoDimensional; } @Override public boolean equals(Object other) { if (!(other instanceof Texture2D)) { return false; } Texture2D that = (Texture2D) other; if (this.getWrap(WrapAxis.S) != that.getWrap(WrapAxis.S)) return false; if (this.getWrap(WrapAxis.T) != that.getWrap(WrapAxis.T)) return false; return super.equals(other); } @Override public int hashCode() { int hash = super.hashCode(); hash = 79 * hash + (this.wrapS != null ? this.wrapS.hashCode() : 0); hash = 79 * hash + (this.wrapT != null ? this.wrapT.hashCode() : 0); return hash; } @Override public void write(JmeExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(wrapS, "wrapS", WrapMode.EdgeClamp); capsule.write(wrapT, "wrapT", WrapMode.EdgeClamp); } @Override public void read(JmeImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); wrapS = capsule.readEnum("wrapS", WrapMode.class, WrapMode.EdgeClamp); wrapT = capsule.readEnum("wrapT", WrapMode.class, WrapMode.EdgeClamp); } }
package com.constantcontact.v2; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.jackson.JacksonConverterFactory; import java.util.concurrent.TimeUnit; /** * @author woogienoogie */ public class CCApi2 { /** * The correct formatting of a Date using SimpleDateFormat */ public final static String DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ss.ss'Z'"; public static OkHttpClient.Builder createDefaultOkHttpClientBuilder(final String apiKey, final String token) { return createDefaultOkHttpClientBuilder(apiKey, token, false); } public static OkHttpClient.Builder createDefaultOkHttpClientBuilder(final String apiKey, final String token, boolean debug) { OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .readTimeout(10, TimeUnit.SECONDS) .connectTimeout(5, TimeUnit.SECONDS) .addInterceptor(createDefaultInterceptor(apiKey, token)); if (debug) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); builder.addInterceptor(interceptor); } return builder; } public static Interceptor createDefaultInterceptor(final String apiKey, final String token) { return new CCApiInterceptor(apiKey, token); } public static Retrofit.Builder createDefaultRetrofitBuilder(OkHttpClient client) { return new Retrofit.Builder().baseUrl(BASE_URL) .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()); } private static final String BASE_URL = "https://api.constantcontact.com/"; private final Retrofit _retrofit; protected AccountService _accountService; protected CampaignService _campaignService; protected ContactService _contactService; protected LibraryService _libraryService; protected CampaignTrackingService _campaignTrackingService; protected ContactTrackingService _contactTrackingService; public CCApi2(final String apiKey, final String token) { OkHttpClient client = createDefaultOkHttpClientBuilder(apiKey, token).build(); _retrofit = createDefaultRetrofitBuilder(client).build(); _accountService = _retrofit.create(AccountService.class); _campaignService = _retrofit.create(CampaignService.class); _contactService = _retrofit.create(ContactService.class); _libraryService = _retrofit.create(LibraryService.class); _campaignTrackingService = _retrofit.create(CampaignTrackingService.class); _contactTrackingService = _retrofit.create(ContactTrackingService.class); } public CCApi2(Retrofit retrofit) { _retrofit = retrofit; _accountService = _retrofit.create(AccountService.class); _campaignService = _retrofit.create(CampaignService.class); _contactService = _retrofit.create(ContactService.class); _libraryService = _retrofit.create(LibraryService.class); _campaignTrackingService = _retrofit.create(CampaignTrackingService.class); _contactTrackingService = _retrofit.create(ContactTrackingService.class); } public Retrofit getRestAdapter() { return _retrofit; } public AccountService getAccountService() { return _accountService; } public CampaignService getCampaignService() { return _campaignService; } public ContactService getContactService() { return _contactService; } public LibraryService getLibraryService() { return _libraryService; } public CampaignTrackingService getCampaignTrackingService() { return _campaignTrackingService; } public ContactTrackingService getContactTrackingService() { return _contactTrackingService; } }
package com.rey.material.widget; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; import org.xmlpull.v1.XmlPullParserException; import android.annotation.TargetApi; import android.content.ClipboardManager; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.view.GravityCompat; import android.text.Editable; import android.text.InputFilter; import android.text.Layout; import android.text.Spannable; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.text.TextWatcher; import android.text.method.KeyListener; import android.text.method.MovementMethod; import android.text.method.PasswordTransformationMethod; import android.text.method.TransformationMethod; import android.text.style.URLSpan; import android.util.AttributeSet; import android.util.TypedValue; import android.view.ActionMode; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.CorrectionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import android.widget.*; import com.rey.material.R; import com.rey.material.drawable.DividerDrawable; import com.rey.material.util.ThemeUtil; import com.rey.material.util.ViewUtil; public class EditText extends FrameLayout { private boolean mLabelEnable; private int mSupportMode; private int mAutoCompleteMode; public static final int SUPPORT_MODE_NONE = 0; public static final int SUPPORT_MODE_HELPER = 1; public static final int SUPPORT_MODE_HELPER_WITH_ERROR = 2; public static final int SUPPORT_MODE_CHAR_COUNTER = 3; public static final int AUTOCOMPLETE_MODE_NONE = 0; public static final int AUTOCOMPLETE_MODE_SINGLE = 1; public static final int AUTOCOMPLETE_MODE_MULTI = 2; private ColorStateList mDividerColors; private ColorStateList mDividerErrorColors; private boolean mDividerCompoundPadding; private ColorStateList mSupportColors; private ColorStateList mSupportErrorColors; private int mSupportMaxChars; private CharSequence mSupportHelper; private CharSequence mSupportError; private int mLabelInAnimId; private int mLabelOutAnimId; protected LabelView mLabelView; protected android.widget.EditText mInputView; protected LabelView mSupportView; private DividerDrawable mDivider; private TextView.OnSelectionChangedListener mOnSelectionChangedListener; public EditText(Context context) { super(context); init(context, null, 0, 0); } public EditText(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public EditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } public EditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, defStyleRes); } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EditText, defStyleAttr, defStyleRes); mLabelEnable = a.getBoolean(R.styleable.EditText_et_labelEnable, false); mSupportMode = a.getInteger(R.styleable.EditText_et_supportMode, SUPPORT_MODE_NONE); mAutoCompleteMode = a.getInteger(R.styleable.EditText_et_autoCompleteMode, AUTOCOMPLETE_MODE_NONE); switch (mAutoCompleteMode){ case AUTOCOMPLETE_MODE_SINGLE: mInputView = new InternalAutoCompleteTextView(context, attrs, defStyleAttr); break; case AUTOCOMPLETE_MODE_MULTI: mInputView = new InternalMultiAutoCompleteTextView(context, attrs, defStyleAttr); break; default: mInputView = new InternalEditText(context, attrs, defStyleAttr); break; } int inputId = a.getResourceId(R.styleable.EditText_et_inputId, 0); mInputView.setId(inputId != 0 ? inputId : ViewUtil.generateViewId()); mInputView.setFocusableInTouchMode(true); mDividerColors = a.getColorStateList(R.styleable.EditText_et_dividerColor); mDividerErrorColors = a.getColorStateList(R.styleable.EditText_et_dividerErrorColor); if(mDividerColors == null){ int[][] states = new int[][]{ new int[]{-android.R.attr.state_focused}, new int[]{android.R.attr.state_focused, android.R.attr.state_enabled}, }; int[] colors = new int[]{ ThemeUtil.colorControlNormal(context, 0xFF000000), ThemeUtil.colorControlActivated(context, 0xFF000000), }; mDividerColors = new ColorStateList(states, colors); } if(mDividerErrorColors == null) mDividerErrorColors = ColorStateList.valueOf(ThemeUtil.colorAccent(context, 0xFFFF0000)); int dividerHeight = a.getDimensionPixelOffset(R.styleable.EditText_et_dividerHeight, 0); int dividerPadding = a.getDimensionPixelOffset(R.styleable.EditText_et_dividerPadding, 0); int dividerAnimDuration = a.getInteger(R.styleable.EditText_et_dividerAnimDuration, context.getResources().getInteger(android.R.integer.config_shortAnimTime)); mDividerCompoundPadding = a.getBoolean(R.styleable.EditText_et_dividerCompoundPadding, true); mInputView.setPadding(0, 0, 0, dividerPadding + dividerHeight); System.out.println("a " + mInputView.getTotalPaddingLeft() + " " + mInputView.getTotalPaddingRight()); mDivider = new DividerDrawable(dividerHeight, mDividerCompoundPadding ? mInputView.getTotalPaddingLeft() : 0, mDividerCompoundPadding ? mInputView.getTotalPaddingRight() : 0, mDividerColors, dividerAnimDuration); mDivider.setInEditMode(isInEditMode()); mDivider.setAnimEnable(false); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) mInputView.setBackground(mDivider); else mInputView.setBackgroundDrawable(mDivider); mDivider.setAnimEnable(true); mInputView.addTextChangedListener(new InputTextWatcher()); addView(mInputView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); if(mLabelEnable){ mLabelView = new LabelView(context); mLabelView.setGravity(GravityCompat.START); mLabelView.setSingleLine(true); int labelPadding = a.getDimensionPixelOffset(R.styleable.EditText_et_labelPadding, 0); int labelTextSize = a.getDimensionPixelSize(R.styleable.EditText_et_labelTextSize, 0); ColorStateList labelTextColor = a.getColorStateList(R.styleable.EditText_et_labelTextColor); int labelTextAppearance = a.getResourceId(R.styleable.EditText_et_labelTextAppearance, 0); int labelEllipsize = a.getInteger(R.styleable.EditText_et_labelEllipsize, 0); mLabelInAnimId = a.getResourceId(R.styleable.EditText_et_labelInAnim, 0); mLabelOutAnimId = a.getResourceId(R.styleable.EditText_et_labelOutAnim, 0); mLabelView.setPadding(mDivider.getPaddingLeft(), 0, mDivider.getPaddingRight(), labelPadding); if(labelTextAppearance > 0) mLabelView.setTextAppearance(context, labelTextAppearance); if(labelTextSize > 0) mLabelView.setTextSize(TypedValue.COMPLEX_UNIT_PX, labelTextSize); if(labelTextColor != null) mLabelView.setTextColor(labelTextColor); switch (labelEllipsize) { case 1: mLabelView.setEllipsize(TruncateAt.START); break; case 2: mLabelView.setEllipsize(TruncateAt.MIDDLE); break; case 3: mLabelView.setEllipsize(TruncateAt.END); break; case 4: mLabelView.setEllipsize(TruncateAt.MARQUEE); break; default: mLabelView.setEllipsize(TruncateAt.END); break; } addView(mLabelView, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } if(mSupportMode != SUPPORT_MODE_NONE){ mSupportView = new LabelView(context); int supportPadding = a.getDimensionPixelOffset(R.styleable.EditText_et_supportPadding, 0); int supportTextSize = a.getDimensionPixelSize(R.styleable.EditText_et_supportTextSize, 0); mSupportColors = a.getColorStateList(R.styleable.EditText_et_supportTextColor); mSupportErrorColors = a.getColorStateList(R.styleable.EditText_et_supportTextErrorColor); int supportTextAppearance = a.getResourceId(R.styleable.EditText_et_supportTextAppearance, 0); int supportEllipsize = a.getInteger(R.styleable.EditText_et_supportEllipsize, 0); int supportMaxLines = a.getInteger(R.styleable.EditText_et_supportMaxLines, 0); int supportLines = a.getInteger(R.styleable.EditText_et_supportLines, 0); boolean supportSingleLine = a.getBoolean(R.styleable.EditText_et_supportSingleLine, false); mSupportView.setPadding(mDivider.getPaddingLeft(), supportPadding, mDivider.getPaddingRight(), 0); mSupportView.setTextSize(TypedValue.COMPLEX_UNIT_PX, supportTextSize); mSupportView.setTextColor(mSupportColors); if(supportTextAppearance > 0) mSupportView.setTextAppearance(context, supportTextAppearance); mSupportView.setSingleLine(supportSingleLine); if(supportMaxLines > 0) mSupportView.setMaxLines(supportMaxLines); if(supportLines > 0) mSupportView.setLines(supportLines); switch (supportEllipsize) { case 1: mSupportView.setEllipsize(TruncateAt.START); break; case 2: mSupportView.setEllipsize(TruncateAt.MIDDLE); break; case 3: mSupportView.setEllipsize(TruncateAt.END); break; case 4: mSupportView.setEllipsize(TruncateAt.MARQUEE); break; default: mSupportView.setEllipsize(TruncateAt.END); break; } switch (mSupportMode) { case SUPPORT_MODE_CHAR_COUNTER: mSupportMaxChars = a.getInteger(R.styleable.EditText_et_supportMaxChars, 0); mSupportView.setGravity(GravityCompat.END); updateCharCounter(mInputView.getText().length()); break; case SUPPORT_MODE_HELPER: case SUPPORT_MODE_HELPER_WITH_ERROR: mSupportView.setGravity(GravityCompat.START); mSupportHelper = a.getString(R.styleable.EditText_et_helper); setError(a.getString(R.styleable.EditText_et_error)); break; } addView(mSupportView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } a.recycle(); if(mLabelEnable){ mLabelView.setText(mInputView.getHint()); mLabelView.setVisibility(TextUtils.isEmpty(mInputView.getText().toString()) ? View.INVISIBLE : View.VISIBLE); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int tempWidthSpec = widthMode == MeasureSpec.UNSPECIFIED ? widthMeasureSpec : MeasureSpec.makeMeasureSpec(widthSize - getPaddingLeft() - getPaddingRight(), widthMode); int tempHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); int labelWidth = 0; int labelHeight = 0; int inputWidth = 0; int inputHeight = 0; int supportWidth = 0; int supportHeight = 0; if(mLabelView != null){ mLabelView.measure(tempWidthSpec, tempHeightSpec); labelWidth = mLabelView.getMeasuredWidth(); labelHeight = mLabelView.getMeasuredHeight(); } mInputView.measure(tempWidthSpec, tempHeightSpec); inputWidth = mInputView.getMeasuredWidth(); inputHeight = mInputView.getMeasuredHeight(); if(mSupportView != null){ mSupportView.measure(tempWidthSpec, tempHeightSpec); supportWidth = mSupportView.getMeasuredWidth(); supportHeight = mSupportView.getMeasuredHeight(); } int width = 0; int height = 0; switch (widthMode) { case MeasureSpec.UNSPECIFIED: width = Math.max(labelWidth, Math.max(inputWidth, supportWidth)) + getPaddingLeft() + getPaddingRight(); break; case MeasureSpec.AT_MOST: width = Math.min(widthSize, Math.max(labelWidth, Math.max(inputWidth, supportWidth)) + getPaddingLeft() + getPaddingRight()); break; case MeasureSpec.EXACTLY: width = widthSize; break; } switch (heightMode) { case MeasureSpec.UNSPECIFIED: height = labelHeight + inputHeight + supportHeight + getPaddingTop() + getPaddingBottom(); break; case MeasureSpec.AT_MOST: height = Math.min(heightSize, labelHeight + inputHeight + supportHeight + getPaddingTop() + getPaddingBottom()); break; case MeasureSpec.EXACTLY: height = heightSize; break; } setMeasuredDimension(width, height); tempWidthSpec = MeasureSpec.makeMeasureSpec(width - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY); if(mLabelView != null) mLabelView.measure(tempWidthSpec, tempHeightSpec); mInputView.measure(tempWidthSpec, tempHeightSpec); if(mSupportView != null) mSupportView.measure(tempWidthSpec, tempHeightSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childLeft = getPaddingLeft(); int childRight = r - l - getPaddingRight(); int childTop = getPaddingTop(); int childBottom = b - t - getPaddingBottom(); if(mLabelView != null){ mLabelView.layout(childLeft, childTop, childRight, childTop + mLabelView.getMeasuredHeight()); childTop += mLabelView.getMeasuredHeight(); } if(mSupportView != null){ mSupportView.layout(childLeft, childBottom - mSupportView.getMeasuredHeight(), childRight, childBottom); childBottom -= mSupportView.getMeasuredHeight(); } mInputView.layout(childLeft, childTop, childRight, childBottom); } public void setHelper(CharSequence helper){ mSupportHelper = helper; setError(mSupportError); } public CharSequence getHelper(){ return mSupportHelper; } public void setError(CharSequence error){ mSupportError = error; if(mSupportMode != SUPPORT_MODE_HELPER && mSupportMode != SUPPORT_MODE_HELPER_WITH_ERROR) return; if(mSupportError != null){ mSupportView.setTextColor(mSupportErrorColors); mDivider.setColor(mDividerErrorColors); mSupportView.setText(mSupportMode == SUPPORT_MODE_HELPER ? mSupportError : TextUtils.concat(mSupportHelper, ", ", mSupportError)); } else{ mSupportView.setTextColor(mSupportColors); mDivider.setColor(mDividerColors); mSupportView.setText(mSupportHelper); } } public CharSequence getError(){ return mSupportError; } public void clearError(){ setError(null); } private void updateCharCounter(int count){ if(count == 0){ mSupportView.setTextColor(mSupportColors); mDivider.setColor(mDividerColors); mSupportView.setText(null); } else{ if(mSupportMaxChars > 0){ mSupportView.setTextColor(count > mSupportMaxChars ? mSupportErrorColors : mSupportColors); mDivider.setColor(count > mSupportMaxChars ? mDividerErrorColors : mDividerColors); mSupportView.setText(count + " / " + mSupportMaxChars); } else mSupportView.setText(String.valueOf(count)); } } /* protected method of AutoCompleteTextView */ /** * <p>Converts the selected item from the drop down list into a sequence * of character that can be used in the edit box.</p> * * @param selectedItem the item selected by the user for completion * * @return a sequence of characters representing the selected suggestion */ protected CharSequence convertSelectionToString(Object selectedItem) { switch (mAutoCompleteMode){ case AUTOCOMPLETE_MODE_SINGLE: return ((InternalAutoCompleteTextView)mInputView).superConvertSelectionToString(selectedItem); case AUTOCOMPLETE_MODE_MULTI: return ((InternalMultiAutoCompleteTextView)mInputView).superConvertSelectionToString(selectedItem); default: return null; } } /** * <p>Starts filtering the content of the drop down list. The filtering * pattern is the content of the edit box. Subclasses should override this * method to filter with a different pattern, for instance a substring of * <code>text</code>.</p> * * @param text the filtering pattern * @param keyCode the last character inserted in the edit box; beware that * this will be null when text is being added through a soft input method. */ protected void performFiltering(CharSequence text, int keyCode) { switch (mAutoCompleteMode){ case AUTOCOMPLETE_MODE_SINGLE: ((InternalAutoCompleteTextView)mInputView).superPerformFiltering(text, keyCode); break; case AUTOCOMPLETE_MODE_MULTI: ((InternalMultiAutoCompleteTextView)mInputView).superPerformFiltering(text, keyCode); break; } } /** * <p>Performs the text completion by replacing the current text by the * selected item. Subclasses should override this method to avoid replacing * the whole content of the edit box.</p> * * @param text the selected suggestion in the drop down list */ protected void replaceText(CharSequence text) { switch (mAutoCompleteMode){ case AUTOCOMPLETE_MODE_SINGLE: ((InternalAutoCompleteTextView)mInputView).superReplaceText(text); break; case AUTOCOMPLETE_MODE_MULTI: ((InternalMultiAutoCompleteTextView)mInputView).superReplaceText(text); break; } } /** * Returns the Filter obtained from {@link Filterable#getFilter}, * or <code>null</code> if {@link #setAdapter} was not called with * a Filterable. */ protected Filter getFilter() { switch (mAutoCompleteMode){ case AUTOCOMPLETE_MODE_SINGLE: return ((InternalAutoCompleteTextView)mInputView).superGetFilter(); case AUTOCOMPLETE_MODE_MULTI: return ((InternalMultiAutoCompleteTextView)mInputView).superGetFilter(); default: return null; } } /** * <p>Starts filtering the content of the drop down list. The filtering * pattern is the specified range of text from the edit box. Subclasses may * override this method to filter with a different pattern, for * instance a smaller substring of <code>text</code>.</p> */ protected void performFiltering(CharSequence text, int start, int end, int keyCode) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_MULTI) ((InternalMultiAutoCompleteTextView)mInputView).superPerformFiltering(text, start, end, keyCode); } /* public method of AutoCompleteTextView */ /** * <p>Sets the optional hint text that is displayed at the bottom of the * the matching list. This can be used as a cue to the user on how to * best use the list, or to provide extra information.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param hint the text to be displayed to the user * * @see #getCompletionHint() * * @attr ref android.R.styleable#AutoCompleteTextView_completionHint */ public void setCompletionHint(CharSequence hint) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setCompletionHint(hint); } /** * Gets the optional hint text displayed at the bottom of the the matching list. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return The hint text, if any * * @see #setCompletionHint(CharSequence) * * @attr ref android.R.styleable#AutoCompleteTextView_completionHint */ public CharSequence getCompletionHint() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return null; return ((AutoCompleteTextView)mInputView).getCompletionHint(); } /** * <p>Returns the current width for the auto-complete drop down list. This can * be a fixed width, or {@link ViewGroup.LayoutParams#MATCH_PARENT} to fill the screen, or * {@link ViewGroup.LayoutParams#WRAP_CONTENT} to fit the width of its anchor view.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the width for the drop down list * * @attr ref android.R.styleable#AutoCompleteTextView_dropDownWidth */ public int getDropDownWidth() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return 0; return ((AutoCompleteTextView)mInputView).getDropDownWidth(); } /** * <p>Sets the current width for the auto-complete drop down list. This can * be a fixed width, or {@link ViewGroup.LayoutParams#MATCH_PARENT} to fill the screen, or * {@link ViewGroup.LayoutParams#WRAP_CONTENT} to fit the width of its anchor view.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param width the width to use * * @attr ref android.R.styleable#AutoCompleteTextView_dropDownWidth */ public void setDropDownWidth(int width) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setDropDownWidth(width); } /** * <p>Returns the current height for the auto-complete drop down list. This can * be a fixed height, or {@link ViewGroup.LayoutParams#MATCH_PARENT} to fill * the screen, or {@link ViewGroup.LayoutParams#WRAP_CONTENT} to fit the height * of the drop down's content.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the height for the drop down list * * @attr ref android.R.styleable#AutoCompleteTextView_dropDownHeight */ public int getDropDownHeight() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return 0; return ((AutoCompleteTextView)mInputView).getDropDownHeight(); } /** * <p>Sets the current height for the auto-complete drop down list. This can * be a fixed height, or {@link ViewGroup.LayoutParams#MATCH_PARENT} to fill * the screen, or {@link ViewGroup.LayoutParams#WRAP_CONTENT} to fit the height * of the drop down's content.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param height the height to use * * @attr ref android.R.styleable#AutoCompleteTextView_dropDownHeight */ public void setDropDownHeight(int height) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setDropDownHeight(height); } /** * <p>Returns the id for the view that the auto-complete drop down list is anchored to.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the view's id, or {@link View#NO_ID} if none specified * * @attr ref android.R.styleable#AutoCompleteTextView_dropDownAnchor */ public int getDropDownAnchor() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return 0; return ((AutoCompleteTextView)mInputView).getDropDownAnchor(); } /** * <p>Sets the view to which the auto-complete drop down list should anchor. The view * corresponding to this id will not be loaded until the next time it is needed to avoid * loading a view which is not yet instantiated.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param id the id to anchor the drop down list view to * * @attr ref android.R.styleable#AutoCompleteTextView_dropDownAnchor */ public void setDropDownAnchor(int id) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setDropDownAnchor(id); } /** * <p>Gets the background of the auto-complete drop-down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the background drawable * * @attr ref android.R.styleable#PopupWindow_popupBackground */ public Drawable getDropDownBackground() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return null; return ((AutoCompleteTextView)mInputView).getDropDownBackground(); } /** * <p>Sets the background of the auto-complete drop-down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param d the drawable to set as the background * * @attr ref android.R.styleable#PopupWindow_popupBackground */ public void setDropDownBackgroundDrawable(Drawable d) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setDropDownBackgroundDrawable(d); } /** * <p>Sets the background of the auto-complete drop-down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param id the id of the drawable to set as the background * * @attr ref android.R.styleable#PopupWindow_popupBackground */ public void setDropDownBackgroundResource(int id) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setDropDownBackgroundResource(id); } /** * <p>Sets the vertical offset used for the auto-complete drop-down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param offset the vertical offset * * @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset */ public void setDropDownVerticalOffset(int offset) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setDropDownVerticalOffset(offset); } /** * <p>Gets the vertical offset used for the auto-complete drop-down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the vertical offset * * @attr ref android.R.styleable#ListPopupWindow_dropDownVerticalOffset */ public int getDropDownVerticalOffset() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return 0; return ((AutoCompleteTextView)mInputView).getDropDownVerticalOffset(); } /** * <p>Sets the horizontal offset used for the auto-complete drop-down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param offset the horizontal offset * * @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset */ public void setDropDownHorizontalOffset(int offset) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setDropDownHorizontalOffset(offset); } /** * <p>Gets the horizontal offset used for the auto-complete drop-down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the horizontal offset * * @attr ref android.R.styleable#ListPopupWindow_dropDownHorizontalOffset */ public int getDropDownHorizontalOffset() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return 0; return ((AutoCompleteTextView)mInputView).getDropDownHorizontalOffset(); } /** * <p>Returns the number of characters the user must type before the drop * down list is shown.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the minimum number of characters to type to show the drop down * * @see #setThreshold(int) * * @attr ref android.R.styleable#AutoCompleteTextView_completionThreshold */ public int getThreshold() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return 0; return ((AutoCompleteTextView)mInputView).getThreshold(); } /** * <p>Specifies the minimum number of characters the user has to type in the * edit box before the drop down list is shown.</p> * * <p>When <code>threshold</code> is less than or equals 0, a threshold of * 1 is applied.</p> * * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param threshold the number of characters to type before the drop down * is shown * * @see #getThreshold() * * @attr ref android.R.styleable#AutoCompleteTextView_completionThreshold */ public void setThreshold(int threshold) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setThreshold(threshold); } /** * <p>Sets the listener that will be notified when the user clicks an item * in the drop down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param l the item click listener */ public void setOnItemClickListener(AdapterView.OnItemClickListener l) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setOnItemClickListener(l); } /** * <p>Sets the listener that will be notified when the user selects an item * in the drop down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param l the item selected listener */ public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener l) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setOnItemSelectedListener(l); } /** * <p>Returns the listener that is notified whenever the user clicks an item * in the drop down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the item click listener */ public AdapterView.OnItemClickListener getOnItemClickListener() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return null; return ((AutoCompleteTextView)mInputView).getOnItemClickListener(); } /** * <p>Returns the listener that is notified whenever the user selects an * item in the drop down list.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the item selected listener */ public AdapterView.OnItemSelectedListener getOnItemSelectedListener() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return null; return ((AutoCompleteTextView)mInputView).getOnItemSelectedListener(); } /** * <p>Returns a filterable list adapter used for auto completion.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return a data adapter used for auto completion */ public ListAdapter getAdapter() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return null; return ((AutoCompleteTextView)mInputView).getAdapter(); } /** * <p>Changes the list of data used for auto completion. The provided list * must be a filterable list adapter.</p> * * <p>The caller is still responsible for managing any resources used by the adapter. * Notably, when the AutoCompleteTextView is closed or released, the adapter is not notified. * A common case is the use of {@link android.widget.CursorAdapter}, which * contains a {@link android.database.Cursor} that must be closed. This can be done * automatically (see * {@link android.app.Activity#startManagingCursor(android.database.Cursor) * startManagingCursor()}), * or by manually closing the cursor when the AutoCompleteTextView is dismissed.</p> * * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param adapter the adapter holding the auto completion data * * @see #getAdapter() * @see android.widget.Filterable * @see android.widget.ListAdapter */ public <T extends ListAdapter & Filterable> void setAdapter(T adapter) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setAdapter(adapter); } /** * Returns <code>true</code> if the amount of text in the field meets * or exceeds the {@link #getThreshold} requirement. You can override * this to impose a different standard for when filtering will be * triggered. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> */ public boolean enoughToFilter() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return false; return ((AutoCompleteTextView)mInputView).enoughToFilter(); } /** * <p>Indicates whether the popup menu is showing.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return true if the popup menu is showing, false otherwise */ public boolean isPopupShowing() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return false; return ((AutoCompleteTextView)mInputView).isPopupShowing(); } /** * <p>Clear the list selection. This may only be temporary, as user input will often bring * it back. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> */ public void clearListSelection() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).clearListSelection(); } /** * Set the position of the dropdown view selection. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param position The position to move the selector to. */ public void setListSelection(int position) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setListSelection(position); } /** * Get the position of the dropdown view selection, if there is one. Returns * {@link android.widget.ListView#INVALID_POSITION ListView.INVALID_POSITION} if there is no dropdown or if * there is no selection. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @return the position of the current selection, if there is one, or * {@link android.widget.ListView#INVALID_POSITION ListView.INVALID_POSITION} if not. * * @see android.widget.ListView#getSelectedItemPosition() */ public int getListSelection() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return 0; return ((AutoCompleteTextView)mInputView).getListSelection(); } /** * <p>Performs the text completion by converting the selected item from * the drop down list into a string, replacing the text box's content with * this string and finally dismissing the drop down menu.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> */ public void performCompletion() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).performCompletion(); } /** * Identifies whether the view is currently performing a text completion, so subclasses * can decide whether to respond to text changed events. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> */ public boolean isPerformingCompletion() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return false; return ((AutoCompleteTextView)mInputView).isPerformingCompletion(); } /** <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> */ public void onFilterComplete(int count) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) ((InternalAutoCompleteTextView)mInputView).superOnFilterComplete(count); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_MULTI) ((InternalMultiAutoCompleteTextView)mInputView).superOnFilterComplete(count); } /** * <p>Closes the drop down if present on screen.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> */ public void dismissDropDown() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).dismissDropDown(); } /** * <p>Displays the drop down on screen.</p> * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> */ public void showDropDown() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).showDropDown(); } /** * Sets the validator used to perform text validation. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @param validator The validator used to validate the text entered in this widget. * * @see #getValidator() * @see #performValidation() */ public void setValidator(AutoCompleteTextView.Validator validator) { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).setValidator(validator); } /** * Returns the Validator set with {@link #setValidator}, * or <code>null</code> if it was not set. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @see #setValidator(android.widget.AutoCompleteTextView.Validator) * @see #performValidation() */ public AutoCompleteTextView.Validator getValidator() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return null; return ((AutoCompleteTextView)mInputView).getValidator(); } /** * If a validator was set on this view and the current string is not valid, * ask the validator to fix it. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_SINGLE or AUTOCOMPLETE_MODE_MULTI</p> * * @see #getValidator() * @see #setValidator(android.widget.AutoCompleteTextView.Validator) */ public void performValidation() { if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return; ((AutoCompleteTextView)mInputView).performValidation(); } /** * Sets the Tokenizer that will be used to determine the relevant * range of the text where the user is typing. * <p>Only work when autoCompleMode is AUTOCOMPLETE_MODE_MULTI</p> */ public void setTokenizer(MultiAutoCompleteTextView.Tokenizer t) { if(mAutoCompleteMode != AUTOCOMPLETE_MODE_MULTI) return; ((MultiAutoCompleteTextView)mInputView).setTokenizer(t); } /* public method of EditText */ @Override public void setEnabled(boolean enabled){ mInputView.setEnabled(enabled); } /** * Convenience for {@link android.text.Selection#extendSelection}. */ public void extendSelection (int index){ mInputView.extendSelection(index); } public Editable getText (){ return mInputView.getText(); } public void selectAll (){ mInputView.selectAll(); } public void setEllipsize (TruncateAt ellipsis){ mInputView.setEllipsize(ellipsis); } /** * Convenience for {@link android.text.Selection#setSelection(android.text.Spannable, int)}. */ public void setSelection (int index){ mInputView.setSelection(index); } /** * Convenience for {@link android.text.Selection#setSelection(android.text.Spannable, int, int)}. */ public void setSelection (int start, int stop){ mInputView.setSelection(start, stop); } public void setText (CharSequence text, android.widget.TextView.BufferType type){ mInputView.setText(text, type); } /** * Adds a TextWatcher to the list of those whose methods are called * whenever this TextView's text changes. * <p> * In 1.0, the {@link android.text.TextWatcher#afterTextChanged} method was erroneously * not called after {@link #setText} calls. Now, doing {@link #setText} * if there are any text changed listeners forces the buffer type to * Editable if it would not otherwise be and does call this method. */ public void addTextChangedListener(TextWatcher textWatcher){ mInputView.addTextChangedListener(textWatcher); } /** * Convenience method: Append the specified text to the TextView's * display buffer, upgrading it to BufferType.EDITABLE if it was * not already editable. */ public final void append (CharSequence text){ mInputView.append(text); } /** * Convenience method: Append the specified text slice to the TextView's * display buffer, upgrading it to BufferType.EDITABLE if it was * not already editable. */ public void append (CharSequence text, int start, int end){ mInputView.append(text, start, end); } public void beginBatchEdit (){ mInputView.beginBatchEdit(); } /** * Move the point, specified by the offset, into the view if it is needed. * This has to be called after layout. Returns true if anything changed. */ public boolean bringPointIntoView (int offset){ return mInputView.bringPointIntoView(offset); } public void cancelLongPress (){ mInputView.cancelLongPress(); } /** * Use {@link android.view.inputmethod.BaseInputConnection#removeComposingSpans * BaseInputConnection.removeComposingSpans()} to remove any IME composing * state from this text view. */ public void clearComposingText (){ mInputView.clearComposingText(); } @Override public void computeScroll (){ mInputView.computeScroll(); } @Override public void debug (int depth){ mInputView.debug(depth); } /** * Returns true, only while processing a touch gesture, if the initial * touch down event caused focus to move to the text view and as a result * its selection changed. Only valid while processing the touch gesture * of interest, in an editable text view. */ public boolean didTouchFocusSelect (){ return mInputView.didTouchFocusSelect(); } public void endBatchEdit (){ mInputView.endBatchEdit(); } /** * If this TextView contains editable content, extract a portion of it * based on the information in <var>request</var> in to <var>outText</var>. * @return Returns true if the text was successfully extracted, else false. */ public boolean extractText (ExtractedTextRequest request, ExtractedText outText){ return mInputView.extractText(request, outText); } @Override @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void findViewsWithText (ArrayList<View> outViews, CharSequence searched, int flags){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) mInputView.findViewsWithText(outViews, searched, flags); } /** * Gets the autolink mask of the text. See {@link * android.text.util.Linkify#ALL Linkify.ALL} and peers for * possible values. * * @attr ref android.R.styleable#TextView_autoLink */ public final int getAutoLinkMask (){ return mInputView.getAutoLinkMask(); } @Override public int getBaseline (){ return mInputView.getBaseline(); } /** * Returns the padding between the compound drawables and the text. * * @attr ref android.R.styleable#TextView_drawablePadding */ public int getCompoundDrawablePadding (){ return mInputView.getCompoundDrawablePadding(); } /** * Returns drawables for the left, top, right, and bottom borders. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ public Drawable[] getCompoundDrawables (){ return mInputView.getCompoundDrawables(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public Drawable[] getCompoundDrawablesRelative (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) return mInputView.getCompoundDrawablesRelative(); return mInputView.getCompoundDrawables(); } /** * Returns the bottom padding of the view, plus space for the bottom * Drawable if any. */ public int getCompoundPaddingBottom (){ return mInputView.getCompoundPaddingBottom(); } /** * Returns the end padding of the view, plus space for the end * Drawable if any. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public int getCompoundPaddingEnd (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) return mInputView.getCompoundPaddingEnd(); return mInputView.getCompoundPaddingRight(); } /** * Returns the left padding of the view, plus space for the left * Drawable if any. */ public int getCompoundPaddingLeft (){ return mInputView.getCompoundPaddingLeft(); } /** * Returns the right padding of the view, plus space for the right * Drawable if any. */ public int getCompoundPaddingRight (){ return mInputView.getCompoundPaddingRight(); } /** * Returns the start padding of the view, plus space for the start * Drawable if any. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public int getCompoundPaddingStart (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) return mInputView.getCompoundPaddingStart(); return mInputView.getCompoundPaddingLeft(); } /** * Returns the top padding of the view, plus space for the top * Drawable if any. */ public int getCompoundPaddingTop (){ return mInputView.getCompoundPaddingTop(); } /** * <p>Return the current color selected to paint the hint text.</p> * * @return Returns the current hint text color. */ public final int getCurrentHintTextColor (){ return mInputView.getCurrentHintTextColor(); } /** * <p>Return the current color selected for normal text.</p> * * @return Returns the current text color. */ public final int getCurrentTextColor (){ return mInputView.getCurrentTextColor(); } /** * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. * * @return The current custom selection callback. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public ActionMode.Callback getCustomSelectionActionModeCallback (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) return mInputView.getCustomSelectionActionModeCallback(); return null; } /** * Return the text the TextView is displaying as an Editable object. If * the text is not editable, null is returned. * * @see #getText */ public Editable getEditableText (){ return mInputView.getEditableText(); } /** * Returns where, if anywhere, words that are longer than the view * is wide should be ellipsized. */ public TruncateAt getEllipsize (){ return mInputView.getEllipsize(); } /** * Returns the extended bottom padding of the view, including both the * bottom Drawable if any and any extra space to keep more than maxLines * of text from showing. It is only valid to call this after measuring. */ public int getExtendedPaddingBottom (){ return mInputView.getExtendedPaddingBottom(); } /** * Returns the extended top padding of the view, including both the * top Drawable if any and any extra space to keep more than maxLines * of text from showing. It is only valid to call this after measuring. */ public int getExtendedPaddingTop (){ return mInputView.getExtendedPaddingTop(); } /** * Returns the current list of input filters. * * @attr ref android.R.styleable#TextView_maxLength */ public InputFilter[] getFilters (){ return mInputView.getFilters(); } @Override public void getFocusedRect (@NonNull Rect r){ mInputView.getFocusedRect(r); } /** * @return the currently set font feature settings. Default is null. * * @see #setFontFeatureSettings(String) * @see android.graphics.Paint#setFontFeatureSettings */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public String getFontFeatureSettings (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) return mInputView.getFontFeatureSettings(); return null; } /** * Return whether this text view is including its entire text contents * in frozen icicles. * * @return Returns true if text is included, false if it isn't. * * @see #setFreezesText */ public boolean getFreezesText (){ return mInputView.getFreezesText(); } /** * Returns the horizontal and vertical alignment of this TextView. * * @see android.view.Gravity * @attr ref android.R.styleable#TextView_gravity */ public int getGravity (){ return mInputView.getGravity(); } /** * @return the color used to display the selection highlight * * @see #setHighlightColor(int) * * @attr ref android.R.styleable#TextView_textColorHighlight */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getHighlightColor (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getHighlightColor(); return 0; } /** * Returns the hint that is displayed when the text of the TextView * is empty. * * @attr ref android.R.styleable#TextView_hint */ public CharSequence getHint (){ return mInputView.getHint(); } /** * @return the color of the hint text, for the different states of this TextView. * * @see #setHintTextColor(android.content.res.ColorStateList) * @see #setHintTextColor(int) * @see #setTextColor(android.content.res.ColorStateList) * @see #setLinkTextColor(android.content.res.ColorStateList) * * @attr ref android.R.styleable#TextView_textColorHint */ public final ColorStateList getHintTextColors (){ return mInputView.getHintTextColors(); } /** * Get the IME action ID previous set with {@link #setImeActionLabel}. * * @see #setImeActionLabel * @see android.view.inputmethod.EditorInfo */ public int getImeActionId (){ return mInputView.getImeActionId(); } /** * Get the IME action label previous set with {@link #setImeActionLabel}. * * @see #setImeActionLabel * @see android.view.inputmethod.EditorInfo */ public CharSequence getImeActionLabel (){ return mInputView.getImeActionLabel(); } /** * Get the type of the IME editor. * * @see #setImeOptions(int) * @see android.view.inputmethod.EditorInfo */ public int getImeOptions (){ return mInputView.getImeOptions(); } /** * Gets whether the TextView includes extra top and bottom padding to make * room for accents that go above the normal ascent and descent. * * @see #setIncludeFontPadding(boolean) * * @attr ref android.R.styleable#TextView_includeFontPadding */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public boolean getIncludeFontPadding (){ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && mInputView.getIncludeFontPadding(); } /** * Retrieve the input extras currently associated with the text view, which * can be viewed as well as modified. * * @param create If true, the extras will be created if they don't already * exist. Otherwise, null will be returned if none have been created. * @see #setInputExtras(int) * @see android.view.inputmethod.EditorInfo#extras * @attr ref android.R.styleable#TextView_editorExtras */ public Bundle getInputExtras (boolean create){ return mInputView.getInputExtras(create); } /** * Get the type of the editable content. * * @see #setInputType(int) * @see android.text.InputType */ public int getInputType (){ return mInputView.getInputType(); } /** * @return the current key listener for this TextView. * This will frequently be null for non-EditText TextViews. * * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText */ public final KeyListener getKeyListener (){ return mInputView.getKeyListener(); } /** * @return the Layout that is currently being used to display the text. * This can be null if the text or width has recently changes. */ public final Layout getLayout (){ return mInputView.getLayout(); } /** * @return the extent by which text is currently being letter-spaced. * This will normally be 0. * * @see #setLetterSpacing(float) * @see android.graphics.Paint#setLetterSpacing */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public float getLetterSpacing (){ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? mInputView.getLetterSpacing() : 0; } /** * Return the baseline for the specified line (0...getLineCount() - 1) * If bounds is not null, return the top, left, right, bottom extents * of the specified line in it. If the internal Layout has not been built, * return 0 and set bounds to (0, 0, 0, 0) * @param line which line to examine (0..getLineCount() - 1) * @param bounds Optional. If not null, it returns the extent of the line * @return the Y-coordinate of the baseline */ public int getLineBounds (int line, Rect bounds){ return mInputView.getLineBounds(line, bounds); } /** * Return the number of lines of text, or 0 if the internal Layout has not * been built. */ public int getLineCount (){ return mInputView.getLineCount(); } /** * @return the height of one standard line in pixels. Note that markup * within the text can cause individual lines to be taller or shorter * than this height, and the layout may contain additional first- * or last-line padding. */ public int getLineHeight (){ return mInputView.getLineHeight(); } /** * Gets the line spacing extra space * * @return the extra space that is added to the height of each lines of this TextView. * * @see #setLineSpacing(float, float) * @see #getLineSpacingMultiplier() * * @attr ref android.R.styleable#TextView_lineSpacingExtra */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public float getLineSpacingExtra (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getLineSpacingExtra(); return 0f; } /** * Gets the line spacing multiplier * * @return the value by which each line's height is multiplied to get its actual height. * * @see #setLineSpacing(float, float) * @see #getLineSpacingExtra() * * @attr ref android.R.styleable#TextView_lineSpacingMultiplier */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public float getLineSpacingMultiplier (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getLineSpacingMultiplier(); return 0f; } /** * @return the list of colors used to paint the links in the text, for the different states of * this TextView * * @see #setLinkTextColor(android.content.res.ColorStateList) * @see #setLinkTextColor(int) * * @attr ref android.R.styleable#TextView_textColorLink */ public final ColorStateList getLinkTextColors (){ return mInputView.getLinkTextColors(); } /** * Returns whether the movement method will automatically be set to * {@link android.text.method.LinkMovementMethod} if {@link #setAutoLinkMask} has been * set to nonzero and links are detected in {@link #setText}. * The default is true. * * @attr ref android.R.styleable#TextView_linksClickable */ public final boolean getLinksClickable (){ return mInputView.getLinksClickable(); } /** * Gets the number of times the marquee animation is repeated. Only meaningful if the * TextView has marquee enabled. * * @return the number of times the marquee animation is repeated. -1 if the animation * repeats indefinitely * * @see #setMarqueeRepeatLimit(int) * * @attr ref android.R.styleable#TextView_marqueeRepeatLimit */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMarqueeRepeatLimit (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMarqueeRepeatLimit(); return -1; } /** * @return the maximum width of the TextView, expressed in ems or -1 if the maximum width * was set in pixels instead (using {@link #setMaxWidth(int)} or {@link #setWidth(int)}). * * @see #setMaxEms(int) * @see #setEms(int) * * @attr ref android.R.styleable#TextView_maxEms */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMaxEms (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMaxEms(); return -1; } /** * @return the maximum height of this TextView expressed in pixels, or -1 if the maximum * height was set in number of lines instead using {@link #setMaxLines(int) or #setLines(int)}. * * @see #setMaxHeight(int) * * @attr ref android.R.styleable#TextView_maxHeight */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMaxHeight (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMaxHeight(); return -1; } /** * @return the maximum number of lines displayed in this TextView, or -1 if the maximum * height was set in pixels instead using {@link #setMaxHeight(int) or #setHeight(int)}. * * @see #setMaxLines(int) * * @attr ref android.R.styleable#TextView_maxLines */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMaxLines (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMaxLines(); return -1; } /** * @return the maximum width of the TextView, in pixels or -1 if the maximum width * was set in ems instead (using {@link #setMaxEms(int)} or {@link #setEms(int)}). * * @see #setMaxWidth(int) * @see #setWidth(int) * * @attr ref android.R.styleable#TextView_maxWidth */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMaxWidth (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMaxWidth(); return -1; } /** * @return the minimum width of the TextView, expressed in ems or -1 if the minimum width * was set in pixels instead (using {@link #setMinWidth(int)} or {@link #setWidth(int)}). * * @see #setMinEms(int) * @see #setEms(int) * * @attr ref android.R.styleable#TextView_minEms */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMinEms (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMinEms(); return -1; } /** * @return the minimum height of this TextView expressed in pixels, or -1 if the minimum * height was set in number of lines instead using {@link #setMinLines(int) or #setLines(int)}. * * @see #setMinHeight(int) * * @attr ref android.R.styleable#TextView_minHeight */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMinHeight (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMinHeight(); return -1; } /** * @return the minimum number of lines displayed in this TextView, or -1 if the minimum * height was set in pixels instead using {@link #setMinHeight(int) or #setHeight(int)}. * * @see #setMinLines(int) * * @attr ref android.R.styleable#TextView_minLines */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMinLines (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMinLines(); return -1; } /** * @return the minimum width of the TextView, in pixels or -1 if the minimum width * was set in ems instead (using {@link #setMinEms(int)} or {@link #setEms(int)}). * * @see #setMinWidth(int) * @see #setWidth(int) * * @attr ref android.R.styleable#TextView_minWidth */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getMinWidth (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getMinWidth(); return -1; } /** * @return the movement method being used for this TextView. * This will frequently be null for non-EditText TextViews. */ public final MovementMethod getMovementMethod (){ return mInputView.getMovementMethod(); } /** * Get the character offset closest to the specified absolute position. A typical use case is to * pass the result of {@link android.view.MotionEvent#getX()} and {@link android.view.MotionEvent#getY()} to this method. * * @param x The horizontal absolute position of a point on screen * @param y The vertical absolute position of a point on screen * @return the character offset for the character whose position is closest to the specified * position. Returns -1 if there is no layout. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public int getOffsetForPosition (float x, float y){ if (getLayout() == null) return -1; final int line = getLineAtCoordinate(y); final int offset = getOffsetAtCoordinate(line, x); return offset; } protected float convertToLocalHorizontalCoordinate(float x) { x -= getTotalPaddingLeft(); // Clamp the position to inside of the view. x = Math.max(0.0f, x); x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); x += getScrollX(); return x; } protected int getLineAtCoordinate(float y) { y -= getTotalPaddingTop(); // Clamp the position to inside of the view. y = Math.max(0.0f, y); y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); y += getScrollY(); return getLayout().getLineForVertical((int) y); } protected int getOffsetAtCoordinate(int line, float x) { x = convertToLocalHorizontalCoordinate(x); return getLayout().getOffsetForHorizontal(line, x); } /** * @return the base paint used for the text. Please use this only to * consult the Paint's properties and not to change them. */ public TextPaint getPaint (){ return mInputView.getPaint(); } /** * @return the flags on the Paint being used to display the text. * @see android.graphics.Paint#getFlags */ public int getPaintFlags (){ return mInputView.getPaintFlags(); } /** * Get the private type of the content. * * @see #setPrivateImeOptions(String) * @see android.view.inputmethod.EditorInfo#privateImeOptions */ public String getPrivateImeOptions (){ return mInputView.getPrivateImeOptions(); } /** * Convenience for {@link android.text.Selection#getSelectionEnd}. */ public int getSelectionEnd (){ return mInputView.getSelectionEnd(); } /** * Convenience for {@link android.text.Selection#getSelectionStart}. */ public int getSelectionStart (){ return mInputView.getSelectionStart(); } /** * @return the color of the shadow layer * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowColor */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public int getShadowColor (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getShadowColor(); return 0; } /** * @return the horizontal offset of the shadow layer * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowDx */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public float getShadowDx (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getShadowDx(); return 0; } /** * @return the vertical offset of the shadow layer * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowDy */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public float getShadowDy (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getShadowDy(); return 0; } /** * Gets the radius of the shadow layer. * * @return the radius of the shadow layer. If 0, the shadow layer is not visible * * @see #setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowRadius */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public float getShadowRadius (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) return mInputView.getShadowRadius(); return 0; } /** * Returns whether the soft input method will be made visible when this * TextView gets focused. The default is true. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public final boolean getShowSoftInputOnFocus (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) return mInputView.getShowSoftInputOnFocus(); return true; } /** * Gets the text colors for the different states (normal, selected, focused) of the TextView. * * @see #setTextColor(android.content.res.ColorStateList) * @see #setTextColor(int) * * @attr ref android.R.styleable#TextView_textColor */ public final ColorStateList getTextColors (){ return mInputView.getTextColors(); } /** * Get the default {@link java.util.Locale} of the text in this TextView. * @return the default {@link java.util.Locale} of the text in this TextView. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public Locale getTextLocale (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) return mInputView.getTextLocale(); return Locale.getDefault(); } /** * @return the extent by which text is currently being stretched * horizontally. This will usually be 1. */ public float getTextScaleX (){ return mInputView.getTextScaleX(); } /** * @return the size (in pixels) of the default text size in this TextView. */ public float getTextSize (){ return mInputView.getTextSize(); } /** * Returns the total bottom padding of the view, including the bottom * Drawable if any, the extra space to keep more than maxLines * from showing, and the vertical offset for gravity, if any. */ public int getTotalPaddingBottom (){ return getPaddingBottom() + mInputView.getTotalPaddingBottom() + (mSupportMode != SUPPORT_MODE_NONE ? mSupportView.getHeight() : 0); } /** * Returns the total end padding of the view, including the end * Drawable if any. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public int getTotalPaddingEnd (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) return getPaddingEnd() + mInputView.getTotalPaddingEnd(); return getTotalPaddingRight(); } /** * Returns the total left padding of the view, including the left * Drawable if any. */ public int getTotalPaddingLeft (){ return getPaddingLeft() + mInputView.getTotalPaddingLeft(); } /** * Returns the total right padding of the view, including the right * Drawable if any. */ public int getTotalPaddingRight (){ return getPaddingRight() + mInputView.getTotalPaddingRight(); } /** * Returns the total start padding of the view, including the start * Drawable if any. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public int getTotalPaddingStart (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) return getPaddingStart() + mInputView.getTotalPaddingStart(); return getTotalPaddingLeft(); } /** * Returns the total top padding of the view, including the top * Drawable if any, the extra space to keep more than maxLines * from showing, and the vertical offset for gravity, if any. */ public int getTotalPaddingTop (){ return getPaddingTop() + mInputView.getTotalPaddingTop() + (mLabelEnable ? mLabelView.getHeight() : 0); } /** * @return the current transformation method for this TextView. * This will frequently be null except for single-line and password * fields. * * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine */ public final TransformationMethod getTransformationMethod (){ return mInputView.getTransformationMethod(); } /** * @return the current typeface and style in which the text is being * displayed. * * @see #setTypeface(android.graphics.Typeface) * * @attr ref android.R.styleable#TextView_fontFamily * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ public Typeface getTypeface (){ return mInputView.getTypeface(); } /** * Returns the list of URLSpans attached to the text * (by {@link android.text.util.Linkify} or otherwise) if any. You can call * {@link android.text.style.URLSpan#getURL} on them to find where they link to * or use {@link android.text.Spanned#getSpanStart} and {@link android.text.Spanned#getSpanEnd} * to find the region of the text they are attached to. */ public URLSpan[] getUrls (){ return mInputView.getUrls(); } @Override @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public boolean hasOverlappingRendering (){ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && mInputView.hasOverlappingRendering(); } /** * Return true iff there is a selection inside this text view. */ public boolean hasSelection (){ return mInputView.hasSelection(); } /** * @return whether or not the cursor is visible (assuming this TextView is editable) * * @see #setCursorVisible(boolean) * * @attr ref android.R.styleable#TextView_cursorVisible */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public boolean isCursorVisible (){ return Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN || mInputView.isCursorVisible(); } /** * Returns whether this text view is a current input method target. The * default implementation just checks with {@link android.view.inputmethod.InputMethodManager}. */ public boolean isInputMethodTarget (){ return mInputView.isInputMethodTarget(); } /** * Return whether or not suggestions are enabled on this TextView. The suggestions are generated * by the IME or by the spell checker as the user types. This is done by adding * {@link android.text.style.SuggestionSpan}s to the text. * * When suggestions are enabled (default), this list of suggestions will be displayed when the * user asks for them on these parts of the text. This value depends on the inputType of this * TextView. * * The class of the input type must be {@link android.text.InputType#TYPE_CLASS_TEXT}. * * In addition, the type variation must be one of * {@link android.text.InputType#TYPE_TEXT_VARIATION_NORMAL}, * {@link android.text.InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT}, * {@link android.text.InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE}, * {@link android.text.InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or * {@link android.text.InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}. * * And finally, the {@link android.text.InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set. * * @return true if the suggestions popup window is enabled, based on the inputType. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public boolean isSuggestionsEnabled (){ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && mInputView.isSuggestionsEnabled(); } /** * * Returns the state of the {@code textIsSelectable} flag (See * {@link #setTextIsSelectable setTextIsSelectable()}). Although you have to set this flag * to allow users to select and copy text in a non-editable TextView, the content of an * {@link EditText} can always be selected, independently of the value of this flag. * <p> * * @return True if the text displayed in this TextView can be selected by the user. * * @attr ref android.R.styleable#TextView_textIsSelectable */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public boolean isTextSelectable (){ return Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || mInputView.isTextSelectable(); } /** * Returns the length, in characters, of the text managed by this TextView */ public int length (){ return mInputView.length(); } /** * Move the cursor, if needed, so that it is at an offset that is visible * to the user. This will not move the cursor if it represents more than * one character (a selection range). This will only work if the * TextView contains spannable text; otherwise it will do nothing. * * @return True if the cursor was actually moved, false otherwise. */ public boolean moveCursorToVisibleOffset (){ return mInputView.moveCursorToVisibleOffset(); } /** * Called by the framework in response to a text completion from * the current input method, provided by it calling * {@link android.view.inputmethod.InputConnection#commitCompletion * InputConnection.commitCompletion()}. The default implementation does * nothing; text views that are supporting auto-completion should override * this to do their desired behavior. * * @param text The auto complete text the user has selected. */ public void onCommitCompletion (CompletionInfo text){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) ((InternalEditText)mInputView).superOnCommitCompletion(text); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) ((InternalAutoCompleteTextView)mInputView).superOnCommitCompletion(text); else ((InternalMultiAutoCompleteTextView)mInputView).superOnCommitCompletion(text); } /** * Called by the framework in response to a text auto-correction (such as fixing a typo using a * a dictionnary) from the current input method, provided by it calling * {@link android.view.inputmethod.InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default * implementation flashes the background of the corrected word to provide feedback to the user. * * @param info The auto correct info about the text that was corrected. */ public void onCommitCorrection (CorrectionInfo info){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) ((InternalEditText)mInputView).superOnCommitCorrection(info); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) ((InternalAutoCompleteTextView)mInputView).superOnCommitCorrection(info); else ((InternalMultiAutoCompleteTextView)mInputView).superOnCommitCorrection(info); } @Override public InputConnection onCreateInputConnection (EditorInfo outAttrs){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return ((InternalEditText)mInputView).superOnCreateInputConnection(outAttrs); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) return ((InternalAutoCompleteTextView)mInputView).superOnCreateInputConnection(outAttrs); else return ((InternalMultiAutoCompleteTextView)mInputView).superOnCreateInputConnection(outAttrs); } /** * Called when an attached input method calls * {@link android.view.inputmethod.InputConnection#performEditorAction(int) * InputConnection.performEditorAction()} * for this text view. The default implementation will call your action * listener supplied to {@link #setOnEditorActionListener}, or perform * a standard operation for {@link android.view.inputmethod.EditorInfo#IME_ACTION_NEXT * EditorInfo.IME_ACTION_NEXT}, {@link android.view.inputmethod.EditorInfo#IME_ACTION_PREVIOUS * EditorInfo.IME_ACTION_PREVIOUS}, or {@link android.view.inputmethod.EditorInfo#IME_ACTION_DONE * EditorInfo.IME_ACTION_DONE}. * * <p>For backwards compatibility, if no IME options have been set and the * text view would not normally advance focus on enter, then * the NEXT and DONE actions received here will be turned into an enter * key down/up pair to go through the normal key handling. * * @param actionCode The code of the action being performed. * * @see #setOnEditorActionListener */ public void onEditorAction (int actionCode){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) ((InternalEditText)mInputView).superOnEditorAction(actionCode); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) ((InternalAutoCompleteTextView)mInputView).superOnEditorAction(actionCode); else ((InternalMultiAutoCompleteTextView)mInputView).superOnEditorAction(actionCode); } @Override public boolean onKeyDown (int keyCode, KeyEvent event){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return ((InternalEditText)mInputView).superOnKeyDown(keyCode, event); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) return ((InternalAutoCompleteTextView)mInputView).superOnKeyDown(keyCode, event); else return ((InternalMultiAutoCompleteTextView)mInputView).superOnKeyDown(keyCode, event); } @Override public boolean onKeyMultiple (int keyCode, int repeatCount, KeyEvent event){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return ((InternalEditText)mInputView).superOnKeyMultiple(keyCode, repeatCount, event); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) return ((InternalAutoCompleteTextView)mInputView).superOnKeyMultiple(keyCode, repeatCount, event); else return ((InternalMultiAutoCompleteTextView)mInputView).superOnKeyMultiple(keyCode, repeatCount, event); } @Override public boolean onKeyPreIme (int keyCode, KeyEvent event){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return ((InternalEditText)mInputView).superOnKeyPreIme(keyCode, event); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) return ((InternalAutoCompleteTextView)mInputView).superOnKeyPreIme(keyCode, event); else return ((InternalMultiAutoCompleteTextView)mInputView).superOnKeyPreIme(keyCode, event); } @Override public boolean onKeyShortcut (int keyCode, KeyEvent event){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return ((InternalEditText)mInputView).superOnKeyShortcut(keyCode, event); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) return ((InternalAutoCompleteTextView)mInputView).superOnKeyShortcut(keyCode, event); else return ((InternalMultiAutoCompleteTextView)mInputView).superOnKeyShortcut(keyCode, event); } @Override public boolean onKeyUp (int keyCode, KeyEvent event){ if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) return ((InternalEditText)mInputView).superOnKeyUp(keyCode, event); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) return ((InternalAutoCompleteTextView)mInputView).superOnKeyUp(keyCode, event); else return ((InternalMultiAutoCompleteTextView)mInputView).superOnKeyUp(keyCode, event); } public void setOnSelectionChangedListener(TextView.OnSelectionChangedListener listener){ mOnSelectionChangedListener = listener; } /** * This method is called when the selection has changed, in case any * subclasses would like to know. * * @param selStart The new selection start location. * @param selEnd The new selection end location. */ protected void onSelectionChanged(int selStart, int selEnd) { if(mInputView == null) return; if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE) ((InternalEditText)mInputView).superOnSelectionChanged(selStart, selEnd); else if(mAutoCompleteMode == AUTOCOMPLETE_MODE_SINGLE) ((InternalAutoCompleteTextView)mInputView).superOnSelectionChanged(selStart, selEnd); else ((InternalMultiAutoCompleteTextView)mInputView).superOnSelectionChanged(selStart, selEnd); if(mOnSelectionChangedListener != null) mOnSelectionChangedListener.onSelectionChanged(this, selStart, selEnd); } /** * Removes the specified TextWatcher from the list of those whose * methods are called * whenever this TextView's text changes. */ public void removeTextChangedListener (TextWatcher watcher){ mInputView.removeTextChangedListener(watcher); } /** * Sets the properties of this field to transform input to ALL CAPS * display. This may use a "small caps" formatting if available. * This setting will be ignored if this field is editable or selectable. * * This call replaces the current transformation method. Disabling this * will not necessarily restore the previous behavior from before this * was enabled. * * @see #setTransformationMethod(android.text.method.TransformationMethod) * @attr ref android.R.styleable#TextView_textAllCaps */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void setAllCaps (boolean allCaps){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) mInputView.setAllCaps(allCaps); } /** * Sets the autolink mask of the text. See {@link * android.text.util.Linkify#ALL Linkify.ALL} and peers for * possible values. * * @attr ref android.R.styleable#TextView_autoLink */ public final void setAutoLinkMask (int mask){ mInputView.setAutoLinkMask(mask); } /** * Sets the size of the padding between the compound drawables and * the text. * * @attr ref android.R.styleable#TextView_drawablePadding */ public void setCompoundDrawablePadding (int pad){ mInputView.setCompoundDrawablePadding(pad); if(mDividerCompoundPadding) { mDivider.setPadding(mInputView.getTotalPaddingLeft(), mInputView.getTotalPaddingRight()); if(mLabelEnable) mLabelView.setPadding(mDivider.getPaddingLeft(), mLabelView.getPaddingTop(), mDivider.getPaddingRight(), mLabelView.getPaddingBottom()); if(mSupportMode != SUPPORT_MODE_NONE) mSupportView.setPadding(mDivider.getPaddingLeft(), mSupportView.getPaddingTop(), mDivider.getPaddingRight(), mSupportView.getPaddingBottom()); } } /** * Sets the Drawables (if any) to appear to the left of, above, to the * right of, and below the text. Use {@code null} if you do not want a * Drawable there. The Drawables must already have had * {@link android.graphics.drawable.Drawable#setBounds} called. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawablesRelative} or related methods. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ public void setCompoundDrawables (Drawable left, Drawable top, Drawable right, Drawable bottom){ mInputView.setCompoundDrawables(left, top, right, bottom); if(mDividerCompoundPadding) { mDivider.setPadding(mInputView.getTotalPaddingLeft(), mInputView.getTotalPaddingRight()); if(mLabelEnable) mLabelView.setPadding(mDivider.getPaddingLeft(), mLabelView.getPaddingTop(), mDivider.getPaddingRight(), mLabelView.getPaddingBottom()); if(mSupportMode != SUPPORT_MODE_NONE) mSupportView.setPadding(mDivider.getPaddingLeft(), mSupportView.getPaddingTop(), mDivider.getPaddingRight(), mSupportView.getPaddingBottom()); } } /** * Sets the Drawables (if any) to appear to the start of, above, to the end * of, and below the text. Use {@code null} if you do not want a Drawable * there. The Drawables must already have had {@link android.graphics.drawable.Drawable#setBounds} * called. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawables} or related methods. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void setCompoundDrawablesRelative (Drawable start, Drawable top, Drawable end, Drawable bottom){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) mInputView.setCompoundDrawablesRelative(start, top, end, bottom); else mInputView.setCompoundDrawables(start, top, end, bottom); } /** * Sets the Drawables (if any) to appear to the start of, above, to the end * of, and below the text. Use {@code null} if you do not want a Drawable * there. The Drawables' bounds will be set to their intrinsic bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawables} or related methods. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void setCompoundDrawablesRelativeWithIntrinsicBounds (Drawable start, Drawable top, Drawable end, Drawable bottom){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) mInputView.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); else mInputView.setCompoundDrawablesWithIntrinsicBounds(start, top, end, bottom); } /** * Sets the Drawables (if any) to appear to the start of, above, to the end * of, and below the text. Use 0 if you do not want a Drawable there. The * Drawables' bounds will be set to their intrinsic bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawables} or related methods. * * @param start Resource identifier of the start Drawable. * @param top Resource identifier of the top Drawable. * @param end Resource identifier of the end Drawable. * @param bottom Resource identifier of the bottom Drawable. * * @attr ref android.R.styleable#TextView_drawableStart * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableEnd * @attr ref android.R.styleable#TextView_drawableBottom */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void setCompoundDrawablesRelativeWithIntrinsicBounds (int start, int top, int end, int bottom){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) mInputView.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); else mInputView.setCompoundDrawablesWithIntrinsicBounds(start, top, end, bottom); } /** * Sets the Drawables (if any) to appear to the left of, above, to the * right of, and below the text. Use {@code null} if you do not want a * Drawable there. The Drawables' bounds will be set to their intrinsic * bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawablesRelative} or related methods. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ public void setCompoundDrawablesWithIntrinsicBounds (Drawable left, Drawable top, Drawable right, Drawable bottom){ mInputView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } /** * Sets the Drawables (if any) to appear to the left of, above, to the * right of, and below the text. Use 0 if you do not want a Drawable there. * The Drawables' bounds will be set to their intrinsic bounds. * <p> * Calling this method will overwrite any Drawables previously set using * {@link #setCompoundDrawablesRelative} or related methods. * * @param left Resource identifier of the left Drawable. * @param top Resource identifier of the top Drawable. * @param right Resource identifier of the right Drawable. * @param bottom Resource identifier of the bottom Drawable. * * @attr ref android.R.styleable#TextView_drawableLeft * @attr ref android.R.styleable#TextView_drawableTop * @attr ref android.R.styleable#TextView_drawableRight * @attr ref android.R.styleable#TextView_drawableBottom */ public void setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom){ mInputView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } /** * Set whether the cursor is visible. The default is true. Note that this property only * makes sense for editable TextView. * * @see #isCursorVisible() * * @attr ref android.R.styleable#TextView_cursorVisible */ public void setCursorVisible (boolean visible){ mInputView.setCursorVisible(visible); } /** * If provided, this ActionMode.Callback will be used to create the ActionMode when text * selection is initiated in this View. * * The standard implementation populates the menu with a subset of Select All, Cut, Copy and * Paste actions, depending on what this View supports. * * A custom implementation can add new entries in the default menu in its * {@link android.view.ActionMode.Callback#onPrepareActionMode(android.view.ActionMode, android.view.Menu)} method. The * default actions can also be removed from the menu using {@link android.view.Menu#removeItem(int)} and * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} * or {@link android.R.id#paste} ids as parameters. * * Returning false from * {@link android.view.ActionMode.Callback#onCreateActionMode(android.view.ActionMode, android.view.Menu)} will prevent * the action mode from being started. * * Action click events should be handled by the custom implementation of * {@link android.view.ActionMode.Callback#onActionItemClicked(android.view.ActionMode, android.view.MenuItem)}. * * Note that text selection mode is not started when a TextView receives focus and the * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in * that case, to allow for quick replacement. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void setCustomSelectionActionModeCallback (ActionMode.Callback actionModeCallback){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) mInputView.setCustomSelectionActionModeCallback(actionModeCallback); } /** * Sets the Factory used to create new Editables. */ public final void setEditableFactory (Editable.Factory factory){ mInputView.setEditableFactory(factory); } /** * Set the TextView's elegant height metrics flag. This setting selects font * variants that have not been compacted to fit Latin-based vertical * metrics, and also increases top and bottom bounds to provide more space. * * @param elegant set the paint's elegant metrics flag. * * @attr ref android.R.styleable#TextView_elegantTextHeight */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void setElegantTextHeight (boolean elegant){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mInputView.setElegantTextHeight(elegant); } /** * Makes the TextView exactly this many ems wide * * @see #setMaxEms(int) * @see #setMinEms(int) * @see #getMinEms() * @see #getMaxEms() * * @attr ref android.R.styleable#TextView_ems */ public void setEms (int ems){ mInputView.setEms(ems); } /** * Apply to this text view the given extracted text, as previously * returned by {@link #extractText(android.view.inputmethod.ExtractedTextRequest, android.view.inputmethod.ExtractedText)}. */ public void setExtractedText (ExtractedText text){ mInputView.setExtractedText(text); } /** * Sets the list of input filters that will be used if the buffer is * Editable. Has no effect otherwise. * * @attr ref android.R.styleable#TextView_maxLength */ public void setFilters (InputFilter[] filters){ mInputView.setFilters(filters); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void setFontFeatureSettings (String fontFeatureSettings){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mInputView.setFontFeatureSettings(fontFeatureSettings); } /** * Control whether this text view saves its entire text contents when * freezing to an icicle, in addition to dynamic state such as cursor * position. By default this is false, not saving the text. Set to true * if the text in the text view is not being saved somewhere else in * persistent storage (such as in a content provider) so that if the * view is later thawed the user will not lose their data. * * @param freezesText Controls whether a frozen icicle should include the * entire text data: true to include it, false to not. * * @attr ref android.R.styleable#TextView_freezesText */ public void setFreezesText (boolean freezesText){ mInputView.setFreezesText(freezesText); } /** * Sets the horizontal alignment of the text and the * vertical gravity that will be used when there is extra space * in the TextView beyond what is required for the text itself. * * @see android.view.Gravity * @attr ref android.R.styleable#TextView_gravity */ public void setGravity (int gravity){ mInputView.setGravity(gravity); } /** * Sets the color used to display the selection highlight. * * @attr ref android.R.styleable#TextView_textColorHighlight */ public void setHighlightColor (int color){ mInputView.setHighlightColor(color); } /** * Sets the text to be displayed when the text of the TextView is empty. * Null means to use the normal empty text. The hint does not currently * participate in determining the size of the view. * * @attr ref android.R.styleable#TextView_hint */ public final void setHint (CharSequence hint){ mInputView.setHint(hint); if(mLabelView != null) mLabelView.setText(hint); } /** * Sets the text to be displayed when the text of the TextView is empty, * from a resource. * * @attr ref android.R.styleable#TextView_hint */ public final void setHint (int resid){ mInputView.setHint(resid); if(mLabelView != null) mLabelView.setText(resid); } /** * Sets the color of the hint text. * * @see #getHintTextColors() * @see #setHintTextColor(int) * @see #setTextColor(android.content.res.ColorStateList) * @see #setLinkTextColor(android.content.res.ColorStateList) * * @attr ref android.R.styleable#TextView_textColorHint */ public final void setHintTextColor (ColorStateList colors){ mInputView.setHintTextColor(colors); } /** * Sets the color of the hint text for all the states (disabled, focussed, selected...) of this * TextView. * * @see #setHintTextColor(android.content.res.ColorStateList) * @see #getHintTextColors() * @see #setTextColor(int) * * @attr ref android.R.styleable#TextView_textColorHint */ public final void setHintTextColor (int color){ mInputView.setHintTextColor(color); } /** * Sets whether the text should be allowed to be wider than the * View is. If false, it will be wrapped to the width of the View. * * @attr ref android.R.styleable#TextView_scrollHorizontally */ public void setHorizontallyScrolling (boolean whether){ mInputView.setHorizontallyScrolling(whether); } /** * Change the custom IME action associated with the text view, which * will be reported to an IME with {@link android.view.inputmethod.EditorInfo#actionLabel} * and {@link android.view.inputmethod.EditorInfo#actionId} when it has focus. * @see #getImeActionLabel * @see #getImeActionId * @see android.view.inputmethod.EditorInfo * @attr ref android.R.styleable#TextView_imeActionLabel * @attr ref android.R.styleable#TextView_imeActionId */ public void setImeActionLabel (CharSequence label, int actionId){ mInputView.setImeActionLabel(label, actionId); } /** * Change the editor type integer associated with the text view, which * will be reported to an IME with {@link android.view.inputmethod.EditorInfo#imeOptions} when it * has focus. * @see #getImeOptions * @see android.view.inputmethod.EditorInfo * @attr ref android.R.styleable#TextView_imeOptions */ public void setImeOptions (int imeOptions){ mInputView.setImeOptions(imeOptions); } /** * Set whether the TextView includes extra top and bottom padding to make * room for accents that go above the normal ascent and descent. * The default is true. * * @see #getIncludeFontPadding() * * @attr ref android.R.styleable#TextView_includeFontPadding */ public void setIncludeFontPadding (boolean includepad){ mInputView.setIncludeFontPadding(includepad); } /** * Set the extra input data of the text, which is the * {@link android.view.inputmethod.EditorInfo#extras TextBoxAttribute.extras} * Bundle that will be filled in when creating an input connection. The * given integer is the resource ID of an XML resource holding an * {@link android.R.styleable#InputExtras &lt;input-extras&gt;} XML tree. * * @see #getInputExtras(boolean) * @see android.view.inputmethod.EditorInfo#extras * @attr ref android.R.styleable#TextView_editorExtras */ public void setInputExtras (int xmlResId) throws XmlPullParserException, IOException{ mInputView.setInputExtras(xmlResId); } /** * Set the type of the content with a constant as defined for {@link android.view.inputmethod.EditorInfo#inputType}. This * will take care of changing the key listener, by calling {@link #setKeyListener(android.text.method.KeyListener)}, * to match the given content type. If the given content type is {@link android.view.inputmethod.EditorInfo#TYPE_NULL} * then a soft keyboard will not be displayed for this text view. * * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be * modified if you change the {@link android.view.inputmethod.EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input * type. * * @see #getInputType() * @see #setRawInputType(int) * @see android.text.InputType * @attr ref android.R.styleable#TextView_inputType */ public void setInputType (int type){ mInputView.setInputType(type); } /** * Sets the key listener to be used with this TextView. This can be null * to disallow user input. Note that this method has significant and * subtle interactions with soft keyboards and other input method: * see {@link android.text.method.KeyListener#getInputType() KeyListener.getContentType()} * for important details. Calling this method will replace the current * content type of the text view with the content type returned by the * key listener. * <p> * Be warned that if you want a TextView with a key listener or movement * method not to be focusable, or if you want a TextView without a * key listener or movement method to be focusable, you must call * {@link #setFocusable} again after calling this to get the focusability * back the way you want it. * * @attr ref android.R.styleable#TextView_numeric * @attr ref android.R.styleable#TextView_digits * @attr ref android.R.styleable#TextView_phoneNumber * @attr ref android.R.styleable#TextView_inputMethod * @attr ref android.R.styleable#TextView_capitalize * @attr ref android.R.styleable#TextView_autoText */ public void setKeyListener (KeyListener input){ mInputView.setKeyListener(input); } /** * Sets text letter-spacing. The value is in 'EM' units. Typical values * for slight expansion will be around 0.05. Negative values tighten text. * * @see #getLetterSpacing() * @see android.graphics.Paint#getLetterSpacing * * @attr ref android.R.styleable#TextView_letterSpacing */ public void setLetterSpacing (float letterSpacing){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mInputView.setLetterSpacing(letterSpacing); } /** * Sets line spacing for this TextView. Each line will have its height * multiplied by <code>mult</code> and have <code>add</code> added to it. * * @attr ref android.R.styleable#TextView_lineSpacingExtra * @attr ref android.R.styleable#TextView_lineSpacingMultiplier */ public void setLineSpacing (float add, float mult){ mInputView.setLineSpacing(add, mult); } /** * Makes the TextView exactly this many lines tall. * * Note that setting this value overrides any other (minimum / maximum) number of lines or * height setting. A single line TextView will set this value to 1. * * @attr ref android.R.styleable#TextView_lines */ public void setLines (int lines){ mInputView.setLines(lines); } /** * Sets the color of links in the text. * * @see #setLinkTextColor(int) * @see #getLinkTextColors() * @see #setTextColor(android.content.res.ColorStateList) * @see #setHintTextColor(android.content.res.ColorStateList) * * @attr ref android.R.styleable#TextView_textColorLink */ public final void setLinkTextColor (ColorStateList colors){ mInputView.setLinkTextColor(colors); } /** * Sets the color of links in the text. * * @see #setLinkTextColor(int) * @see #getLinkTextColors() * @see #setTextColor(android.content.res.ColorStateList) * @see #setHintTextColor(android.content.res.ColorStateList) * * @attr ref android.R.styleable#TextView_textColorLink */ public final void setLinkTextColor (int color){ mInputView.setLinkTextColor(color); } /** * Sets whether the movement method will automatically be set to * {@link android.text.method.LinkMovementMethod} if {@link #setAutoLinkMask} has been * set to nonzero and links are detected in {@link #setText}. * The default is true. * * @attr ref android.R.styleable#TextView_linksClickable */ public final void setLinksClickable (boolean whether){ mInputView.setLinksClickable(whether); } /** * Sets how many times to repeat the marquee animation. Only applied if the * TextView has marquee enabled. Set to -1 to repeat indefinitely. * * @see #getMarqueeRepeatLimit() * * @attr ref android.R.styleable#TextView_marqueeRepeatLimit */ public void setMarqueeRepeatLimit (int marqueeLimit){ mInputView.setMarqueeRepeatLimit(marqueeLimit); } /** * Makes the TextView at most this many ems wide * * @attr ref android.R.styleable#TextView_maxEms */ public void setMaxEms (int maxems){ mInputView.setMaxEms(maxems); } /** * Makes the TextView at most this many pixels tall. This option is mutually exclusive with the * {@link #setMaxLines(int)} method. * * Setting this value overrides any other (maximum) number of lines setting. * * @attr ref android.R.styleable#TextView_maxHeight */ public void setMaxHeight (int maxHeight){ mInputView.setMaxHeight(maxHeight); } /** * Makes the TextView at most this many lines tall. * * Setting this value overrides any other (maximum) height setting. * * @attr ref android.R.styleable#TextView_maxLines */ public void setMaxLines (int maxlines){ mInputView.setMaxLines(maxlines); } /** * Makes the TextView at most this many pixels wide * * @attr ref android.R.styleable#TextView_maxWidth */ public void setMaxWidth (int maxpixels){ mInputView.setMaxWidth(maxpixels); } /** * Makes the TextView at least this many ems wide * * @attr ref android.R.styleable#TextView_minEms */ public void setMinEms (int minems){ mInputView.setMinEms(minems); } /** * Makes the TextView at least this many pixels tall. * * Setting this value overrides any other (minimum) number of lines setting. * * @attr ref android.R.styleable#TextView_minHeight */ public void setMinHeight (int minHeight){ mInputView.setMinHeight(minHeight); } /** * Makes the TextView at least this many lines tall. * * Setting this value overrides any other (minimum) height setting. A single line TextView will * set this value to 1. * * @see #getMinLines() * * @attr ref android.R.styleable#TextView_minLines */ public void setMinLines (int minlines){ mInputView.setMinLines(minlines); } /** * Makes the TextView at least this many pixels wide * * @attr ref android.R.styleable#TextView_minWidth */ public void setMinWidth (int minpixels){ mInputView.setMinWidth(minpixels); } /** * Sets the movement method (arrow key handler) to be used for * this TextView. This can be null to disallow using the arrow keys * to move the cursor or scroll the view. * <p> * Be warned that if you want a TextView with a key listener or movement * method not to be focusable, or if you want a TextView without a * key listener or movement method to be focusable, you must call * {@link #setFocusable} again after calling this to get the focusability * back the way you want it. */ public final void setMovementMethod (MovementMethod movement){ mInputView.setMovementMethod(movement); } /** * Set a special listener to be called when an action is performed * on the text view. This will be called when the enter key is pressed, * or when an action supplied to the IME is selected by the user. Setting * this means that the normal hard key event will not insert a newline * into the text view, even if it is multi-line; holding down the ALT * modifier will, however, allow the user to insert a newline character. */ public void setOnEditorActionListener (android.widget.TextView.OnEditorActionListener l){ mInputView.setOnEditorActionListener(l); } /** * Register a callback to be invoked when a hardware key is pressed in this view. * Key presses in software input methods will generally not trigger the methods of * this listener. * @param l the key listener to attach to this view */ @Override public void setOnKeyListener(OnKeyListener l) { mInputView.setOnKeyListener(l); } /** * Register a callback to be invoked when focus of this view changed. * * @param l The callback that will run. */ @Override public void setOnFocusChangeListener(OnFocusChangeListener l) { mInputView.setOnFocusChangeListener(l); } /** * Directly change the content type integer of the text view, without * modifying any other state. * @see #setInputType(int) * @see android.text.InputType * @attr ref android.R.styleable#TextView_inputType */ public void setRawInputType (int type){ mInputView.setRawInputType(type); } public void setScroller (Scroller s){ mInputView.setScroller(s); } /** * Set the TextView so that when it takes focus, all the text is * selected. * * @attr ref android.R.styleable#TextView_selectAllOnFocus */ public void setSelectAllOnFocus (boolean selectAllOnFocus){ mInputView.setSelectAllOnFocus(selectAllOnFocus); } @Override public void setSelected (boolean selected){ mInputView.setSelected(selected); } /** * Gives the text a shadow of the specified blur radius and color, the specified * distance from its drawn position. * <p> * The text shadow produced does not interact with the properties on view * that are responsible for real time shadows, * {@link android.view.View#getElevation() elevation} and * {@link android.view.View#getTranslationZ() translationZ}. * * @see android.graphics.Paint#setShadowLayer(float, float, float, int) * * @attr ref android.R.styleable#TextView_shadowColor * @attr ref android.R.styleable#TextView_shadowDx * @attr ref android.R.styleable#TextView_shadowDy * @attr ref android.R.styleable#TextView_shadowRadius */ public void setShadowLayer (float radius, float dx, float dy, int color){ mInputView.setShadowLayer(radius, dx, dy, color); } /** * Sets whether the soft input method will be made visible when this * TextView gets focused. The default is true. */ public final void setShowSoftInputOnFocus (boolean show){ mInputView.setShowSoftInputOnFocus(show); } /** * Sets the properties of this field (lines, horizontally scrolling, * transformation method) to be for a single-line input. * * @attr ref android.R.styleable#TextView_singleLine */ public void setSingleLine (){ mInputView.setSingleLine(); } /** * Sets the Factory used to create new Spannables. */ public final void setSpannableFactory (Spannable.Factory factory){ mInputView.setSpannableFactory(factory); } public final void setText (int resid){ mInputView.setText(resid); } public final void setText (char[] text, int start, int len){ mInputView.setText(text, start, len); } public final void setText (int resid, android.widget.TextView.BufferType type){ mInputView.setText(resid, type); } public final void setText (CharSequence text){ mInputView.setText(text); } /** * Sets the text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setTextAppearance (Context context, int resid){ mInputView.setTextAppearance(context, resid); } /** * Sets the text color. * * @see #setTextColor(int) * @see #getTextColors() * @see #setHintTextColor(android.content.res.ColorStateList) * @see #setLinkTextColor(android.content.res.ColorStateList) * * @attr ref android.R.styleable#TextView_textColor */ public void setTextColor (ColorStateList colors){ mInputView.setTextColor(colors); } /** * Sets the text color for all the states (normal, selected, * focused) to be this color. * * @see #setTextColor(android.content.res.ColorStateList) * @see #getTextColors() * * @attr ref android.R.styleable#TextView_textColor */ public void setTextColor (int color){ mInputView.setTextColor(color); } /** * Sets whether the content of this view is selectable by the user. The default is * {@code false}, meaning that the content is not selectable. * <p> * When you use a TextView to display a useful piece of information to the user (such as a * contact's address), make it selectable, so that the user can select and copy its * content. You can also use set the XML attribute * {@link android.R.styleable#TextView_textIsSelectable} to "true". * <p> * When you call this method to set the value of {@code textIsSelectable}, it sets * the flags {@code focusable}, {@code focusableInTouchMode}, {@code clickable}, * and {@code longClickable} to the same value. These flags correspond to the attributes * {@link android.R.styleable#View_focusable android:focusable}, * {@link android.R.styleable#View_focusableInTouchMode android:focusableInTouchMode}, * {@link android.R.styleable#View_clickable android:clickable}, and * {@link android.R.styleable#View_longClickable android:longClickable}. To restore any of these * flags to a state you had set previously, call one or more of the following methods: * {@link #setFocusable(boolean) setFocusable()}, * {@link #setFocusableInTouchMode(boolean) setFocusableInTouchMode()}, * {@link #setClickable(boolean) setClickable()} or * {@link #setLongClickable(boolean) setLongClickable()}. * * @param selectable Whether the content of this TextView should be selectable. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void setTextIsSelectable (boolean selectable){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) mInputView.setTextIsSelectable(selectable); } /** * Like {@link #setText(CharSequence)}, * except that the cursor position (if any) is retained in the new text. * * @param text The new text to place in the text view. * * @see #setText(CharSequence) */ public final void setTextKeepState (CharSequence text){ mInputView.setTextKeepState(text); } /** * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)}, * except that the cursor position (if any) is retained in the new text. * * @see #setText(CharSequence, android.widget.TextView.BufferType) */ public final void setTextKeepState (CharSequence text, android.widget.TextView.BufferType type){ mInputView.setTextKeepState(text, type); } /** * Set the default {@link java.util.Locale} of the text in this TextView to the given value. This value * is used to choose appropriate typefaces for ambiguous characters. Typically used for CJK * locales to disambiguate Hanzi/Kanji/Hanja characters. * * @param locale the {@link java.util.Locale} for drawing text, must not be null. * * @see android.graphics.Paint#setTextLocale */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void setTextLocale (Locale locale){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) mInputView.setTextLocale(locale); } /** * Sets the extent by which text should be stretched horizontally. * * @attr ref android.R.styleable#TextView_textScaleX */ public void setTextScaleX (float size){ mInputView.setTextScaleX(size); } /** * Set the default text size to the given value, interpreted as "scaled * pixel" units. This size is adjusted based on the current density and * user font size preference. * * @param size The scaled pixel size. * * @attr ref android.R.styleable#TextView_textSize */ public void setTextSize (float size){ mInputView.setTextSize(size); } /** * Set the default text size to a given unit and value. See {@link * android.util.TypedValue} for the possible dimension units. * * @param unit The desired dimension unit. * @param size The desired size in the given units. * * @attr ref android.R.styleable#TextView_textSize */ public void setTextSize (int unit, float size){ mInputView.setTextSize(unit, size); } /** * Sets the transformation that is applied to the text that this * TextView is displaying. * * @attr ref android.R.styleable#TextView_password * @attr ref android.R.styleable#TextView_singleLine */ public final void setTransformationMethod (TransformationMethod method){ mInputView.setTransformationMethod(method); } /** * Sets the typeface and style in which the text should be displayed, * and turns on the fake bold and italic bits in the Paint if the * Typeface that you provided does not have all the bits in the * style that you specified. * * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ public void setTypeface (Typeface tf, int style){ mInputView.setTypeface(tf, style); } /** * Sets the typeface and style in which the text should be displayed. * Note that not all Typeface families actually have bold and italic * variants, so you may need to use * {@link #setTypeface(android.graphics.Typeface, int)} to get the appearance * that you actually want. * * @see #getTypeface() * * @attr ref android.R.styleable#TextView_fontFamily * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ public void setTypeface (Typeface tf){ mInputView.setTypeface(tf); } /** * It would be better to rely on the input type for everything. A password inputType should have * a password transformation. We should hence use isPasswordInputType instead of this method. * * We should: * - Call setInputType in setKeyListener instead of changing the input type directly (which * would install the correct transformation). * - Refuse the installation of a non-password transformation in setTransformation if the input * type is password. * * However, this is like this for legacy reasons and we cannot break existing apps. This method * is useful since it matches what the user can see (obfuscated text or not). * * @return true if the current transformation method is of the password type. */ private boolean hasPasswordTransformationMethod() { return getTransformationMethod() != null && getTransformationMethod() instanceof PasswordTransformationMethod; } public boolean canCut() { return !hasPasswordTransformationMethod() && getText().length() > 0 && hasSelection() && getKeyListener() != null; } public boolean canCopy() { return !hasPasswordTransformationMethod() && getText().length() > 0 && hasSelection(); } public boolean canPaste() { return (getKeyListener() != null && getSelectionStart() >= 0 && getSelectionEnd() >= 0 && ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)).hasPrimaryClip()); } /* Inner class */ private class InputTextWatcher implements TextWatcher { @Override public void afterTextChanged(Editable s) { if(!mLabelEnable) return; int count = s.length(); if(count == 0){ if(mLabelView.getVisibility() == View.VISIBLE){ if(mLabelOutAnimId > 0){ Animation anim = AnimationUtils.loadAnimation(getContext(), mLabelOutAnimId); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { mLabelView.setVisibility(View.INVISIBLE); } }); mLabelView.startAnimation(anim); } else mLabelView.setVisibility(View.INVISIBLE); } if(mSupportMode == SUPPORT_MODE_CHAR_COUNTER) updateCharCounter(count); } else{ if(mLabelView.getVisibility() == View.INVISIBLE){ if(mLabelInAnimId > 0){ Animation anim = AnimationUtils.loadAnimation(getContext(), mLabelInAnimId); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mLabelView.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) {} }); mLabelView.startAnimation(anim); } else mLabelView.setVisibility(View.VISIBLE); } if(mSupportMode == SUPPORT_MODE_CHAR_COUNTER) updateCharCounter(count); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} } private class LabelView extends android.widget.TextView{ public LabelView(Context context) { super(context); } @Override protected int[] onCreateDrawableState(int extraSpace) { return mInputView.getDrawableState(); } } private class InternalEditText extends android.widget.EditText{ public InternalEditText(Context context) { super(context); } public InternalEditText(Context context, AttributeSet attrs) { super(context, attrs); } public InternalEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void refreshDrawableState() { super.refreshDrawableState(); if(mLabelView != null) mLabelView.refreshDrawableState(); if(mSupportView != null) mSupportView.refreshDrawableState(); } @Override public void onCommitCompletion(CompletionInfo text) { EditText.this.onCommitCompletion(text); } @Override public void onCommitCorrection(CorrectionInfo info) { EditText.this.onCommitCorrection(info); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return EditText.this.onCreateInputConnection(outAttrs); } @Override public void onEditorAction(int actionCode) { EditText.this.onEditorAction(actionCode); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return EditText.this.onKeyDown(keyCode, event); } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return EditText.this.onKeyMultiple(keyCode, repeatCount, event); } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { return EditText.this.onKeyPreIme(keyCode, event); } @Override public boolean onKeyShortcut(int keyCode, KeyEvent event) { return EditText.this.onKeyShortcut(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return EditText.this.onKeyUp(keyCode, event); } @Override protected void onSelectionChanged(int selStart, int selEnd) { EditText.this.onSelectionChanged(selStart, selEnd); } void superOnCommitCompletion(CompletionInfo text) { super.onCommitCompletion(text); } void superOnCommitCorrection(CorrectionInfo info) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) super.onCommitCorrection(info); } InputConnection superOnCreateInputConnection(EditorInfo outAttrs) { return super.onCreateInputConnection(outAttrs); } void superOnEditorAction(int actionCode) { super.onEditorAction(actionCode); } boolean superOnKeyDown(int keyCode, KeyEvent event) { return super.onKeyDown(keyCode, event); } boolean superOnKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return super.onKeyMultiple(keyCode, repeatCount, event); } boolean superOnKeyPreIme(int keyCode, KeyEvent event) { return super.onKeyPreIme(keyCode, event); } boolean superOnKeyShortcut(int keyCode, KeyEvent event) { return super.onKeyShortcut(keyCode, event); } boolean superOnKeyUp(int keyCode, KeyEvent event) { return super.onKeyUp(keyCode, event); } void superOnSelectionChanged(int selStart, int selEnd) { super.onSelectionChanged(selStart, selEnd); } } private class InternalAutoCompleteTextView extends android.widget.AutoCompleteTextView{ public InternalAutoCompleteTextView(Context context) { super(context); } public InternalAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); } public InternalAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void refreshDrawableState() { super.refreshDrawableState(); if(mLabelView != null) mLabelView.refreshDrawableState(); if(mSupportView != null) mSupportView.refreshDrawableState(); } @Override public void onCommitCompletion(CompletionInfo text) { EditText.this.onCommitCompletion(text); } @Override public void onCommitCorrection(CorrectionInfo info) { EditText.this.onCommitCorrection(info); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return EditText.this.onCreateInputConnection(outAttrs); } @Override public void onEditorAction(int actionCode) { EditText.this.onEditorAction(actionCode); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return EditText.this.onKeyDown(keyCode, event); } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return EditText.this.onKeyMultiple(keyCode, repeatCount, event); } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { return EditText.this.onKeyPreIme(keyCode, event); } @Override public boolean onKeyShortcut(int keyCode, KeyEvent event) { return EditText.this.onKeyShortcut(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return EditText.this.onKeyUp(keyCode, event); } @Override protected void onSelectionChanged(int selStart, int selEnd) { EditText.this.onSelectionChanged(selStart, selEnd); } @Override protected CharSequence convertSelectionToString(Object selectedItem) { return EditText.this.convertSelectionToString(selectedItem); } @Override protected void performFiltering(CharSequence text, int keyCode) { EditText.this.performFiltering(text, keyCode); } @Override protected void replaceText(CharSequence text) { EditText.this.replaceText(text); } @Override protected Filter getFilter() { return EditText.this.getFilter(); } @Override public void onFilterComplete(int count) { EditText.this.onFilterComplete(count); } void superOnCommitCompletion(CompletionInfo text) { super.onCommitCompletion(text); } void superOnCommitCorrection(CorrectionInfo info) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) super.onCommitCorrection(info); } InputConnection superOnCreateInputConnection(EditorInfo outAttrs) { return super.onCreateInputConnection(outAttrs); } void superOnEditorAction(int actionCode) { super.onEditorAction(actionCode); } boolean superOnKeyDown(int keyCode, KeyEvent event) { return super.onKeyDown(keyCode, event); } boolean superOnKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return super.onKeyMultiple(keyCode, repeatCount, event); } boolean superOnKeyPreIme(int keyCode, KeyEvent event) { return super.onKeyPreIme(keyCode, event); } boolean superOnKeyShortcut(int keyCode, KeyEvent event) { return super.onKeyShortcut(keyCode, event); } boolean superOnKeyUp(int keyCode, KeyEvent event) { return super.onKeyUp(keyCode, event); } void superOnFilterComplete(int count) { super.onFilterComplete(count); } CharSequence superConvertSelectionToString(Object selectedItem) { return super.convertSelectionToString(selectedItem); } void superPerformFiltering(CharSequence text, int keyCode) { super.performFiltering(text, keyCode); } void superReplaceText(CharSequence text) { super.replaceText(text); } Filter superGetFilter() { return super.getFilter(); } void superOnSelectionChanged(int selStart, int selEnd) { super.onSelectionChanged(selStart, selEnd); } } private class InternalMultiAutoCompleteTextView extends android.widget.MultiAutoCompleteTextView{ public InternalMultiAutoCompleteTextView(Context context) { super(context); } public InternalMultiAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); } public InternalMultiAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void refreshDrawableState() { super.refreshDrawableState(); if(mLabelView != null) mLabelView.refreshDrawableState(); if(mSupportView != null) mSupportView.refreshDrawableState(); } @Override public void onCommitCompletion(CompletionInfo text) { EditText.this.onCommitCompletion(text); } @Override public void onCommitCorrection(CorrectionInfo info) { EditText.this.onCommitCorrection(info); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return EditText.this.onCreateInputConnection(outAttrs); } @Override public void onEditorAction(int actionCode) { EditText.this.onEditorAction(actionCode); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return EditText.this.onKeyDown(keyCode, event); } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return EditText.this.onKeyMultiple(keyCode, repeatCount, event); } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { return EditText.this.onKeyPreIme(keyCode, event); } @Override public boolean onKeyShortcut(int keyCode, KeyEvent event) { return EditText.this.onKeyShortcut(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return EditText.this.onKeyUp(keyCode, event); } @Override protected void onSelectionChanged(int selStart, int selEnd) { EditText.this.onSelectionChanged(selStart, selEnd); } @Override public void onFilterComplete(int count) { EditText.this.onFilterComplete(count); } @Override protected CharSequence convertSelectionToString(Object selectedItem) { return EditText.this.convertSelectionToString(selectedItem); } @Override protected void performFiltering(CharSequence text, int keyCode) { EditText.this.performFiltering(text, keyCode); } @Override protected void replaceText(CharSequence text) { EditText.this.replaceText(text); } @Override protected Filter getFilter() { return EditText.this.getFilter(); } @Override protected void performFiltering(CharSequence text, int start, int end, int keyCode){ EditText.this.performFiltering(text, start, end, keyCode); } void superOnCommitCompletion(CompletionInfo text) { super.onCommitCompletion(text); } void superOnCommitCorrection(CorrectionInfo info) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) super.onCommitCorrection(info); } InputConnection superOnCreateInputConnection(EditorInfo outAttrs) { return super.onCreateInputConnection(outAttrs); } void superOnEditorAction(int actionCode) { super.onEditorAction(actionCode); } boolean superOnKeyDown(int keyCode, KeyEvent event) { return super.onKeyDown(keyCode, event); } boolean superOnKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return super.onKeyMultiple(keyCode, repeatCount, event); } boolean superOnKeyPreIme(int keyCode, KeyEvent event) { return super.onKeyPreIme(keyCode, event); } boolean superOnKeyShortcut(int keyCode, KeyEvent event) { return super.onKeyShortcut(keyCode, event); } boolean superOnKeyUp(int keyCode, KeyEvent event) { return super.onKeyUp(keyCode, event); } void superOnFilterComplete(int count) { super.onFilterComplete(count); } CharSequence superConvertSelectionToString(Object selectedItem) { return super.convertSelectionToString(selectedItem); } void superPerformFiltering(CharSequence text, int keyCode) { super.performFiltering(text, keyCode); } void superReplaceText(CharSequence text) { super.replaceText(text); } Filter superGetFilter() { return super.getFilter(); } void superPerformFiltering(CharSequence text, int start, int end, int keyCode){ super.performFiltering(text, start, end, keyCode); } void superOnSelectionChanged(int selStart, int selEnd) { super.onSelectionChanged(selStart, selEnd); } } }
package com.hannesdorfmann.swipeback; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.view.animation.Interpolator; import com.hannesdorfmann.swipeback.interpolator.SmoothInterpolator; import com.hannesdorfmann.swipeback.transformer.DefaultSwipeBackTransformer; import com.hannesdorfmann.swipeback.transformer.SwipeBackTransformer; public abstract class SwipeBack extends ViewGroup { /** * Callback interface for changing state of the swipe back. */ public interface OnStateChangeListener { /** * Called when the internal state has changed. * * @param oldState * The old drawer state. * @param newState * The new drawer state. */ void onStateChanged(int oldState, int newState); /** * Called when the swipe back slides. * * @param openRatio * Ratio for how open the swipe back view is. * @param offsetPixels * Current offset of the swipe back view in pixels. */ void onSlide(float openRatio, int offsetPixels); } /** * Callback that is invoked when the drawer is in the process of deciding whether it should intercept the touch * event. This lets the listener decide if the pointer is on a view that would disallow dragging of the drawer. * This is only called when the touch mode is {@link #TOUCH_MODE_FULLSCREEN}. */ public interface OnInterceptMoveEventListener { /** * Called for each child the pointer i on when the drawer is deciding whether to intercept the touch event. * * @param v View to test for draggability * @param delta Delta drag in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if view is draggable by delta dx. */ boolean isViewDraggable(View v, int delta, int x, int y); } public enum Type { /** * Positions the drawer behind the content. */ BEHIND, // /** // * A static drawer that can not be dragged. // */ //STATIC, /** * Positions the drawer on top of the content. */ OVERLAY, } /** * Tag used when logging. */ private static final String TAG = "SwipeBack"; /** * Indicates whether debug code should be enabled. */ private static final boolean DEBUG = false; /** * The time between each frame when animating the drawer. */ protected static final int ANIMATION_DELAY = 1000 / 60; /** * The default touch bezel size of the drawer in dp. */ private static final int DEFAULT_DRAG_BEZEL_DP = 24; /** * The default drop shadow size in dp. */ private static final int DEFAULT_DIVIDER_SIZE_DP = 6; /** * Drag mode for sliding only the content view. */ public static final int DRAG_CONTENT = 0; /** * Drag mode for sliding the entire window. */ public static final int DRAG_WINDOW = 1; /** * Disallow opening the drawer by dragging the screen. */ public static final int TOUCH_MODE_NONE = 0; /** * Allow opening drawer only by dragging on the edge of the screen. */ public static final int TOUCH_MODE_BEZEL = 1; /** * Allow opening drawer by dragging anywhere on the screen. */ public static final int TOUCH_MODE_FULLSCREEN = 2; /** * Indicates that the drawer is currently closed. */ public static final int STATE_CLOSED = 0; /** * Indicates that the drawer is currently closing. */ public static final int STATE_CLOSING = 1; /** * Indicates that the drawer is currently being dragged by the user. */ public static final int STATE_DRAGGING = 2; /** * Indicates that the drawer is currently opening. */ public static final int STATE_OPENING = 4; /** * Indicates that the drawer is currently open. */ public static final int STATE_OPEN = 8; /** * Indicates whether to use {@link android.view.View#setTranslationX(float)} when positioning views. */ static final boolean USE_TRANSLATIONS = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; /** * The maximum animation duration. */ private static final int DEFAULT_ANIMATION_DURATION = 500; /** * Interpolator used when animating the drawer open/closed. */ protected static final Interpolator SMOOTH_INTERPOLATOR = new SmoothInterpolator(); /** * The default size of the swipe back view in dp */ private static final int DEFAULT_SIZE = 50; /** * Drawable used as swipe back view overlay. */ protected Drawable mSwipeBackOverlay; /** * Defines if the divider is enabled (will be drawn) */ protected boolean mDividerEnabled; /** * The color of the shadow that will be used as divider . */ protected int mDividerAsShadowColor; /** * Drawable used as content to swipe back view divider. */ protected Drawable mDividerDrawable; private boolean mCustomDivider; /** * The size (width) of the content to swipe back view divider. */ protected int mDividerSize; /** * The currently active view. */ protected View mActiveView; /** * Position of the active view. This is compared to View#getTag(R.id.mdActiveViewPosition) when drawing the * indicator. */ protected int mActivePosition; /** * Used when reading the position of the active view. */ protected final Rect mActiveRect = new Rect(); /** * Temporary {@link android.graphics.Rect} used for deciding whether the view should be invalidated so the indicator can be redrawn. */ private final Rect mTempRect = new Rect(); /** * The custom swipe back view set by the user. */ private View mSwipeBackView; /** * The parent of the swipe back view. */ protected BuildLayerFrameLayout mSwipeBackContainer; /** * The parent of the content view. */ protected BuildLayerFrameLayout mContentContainer; /** * The size of the swipe back view (width or height depending on the * gravity). */ protected int mSwipeBackViewSize; /** * Indicates whether the swipe back view is currently visible. */ protected boolean mSwipeBackViewVisible; /** * The drag mode of the drawer. Can be either {@link #DRAG_CONTENT} or {@link #DRAG_WINDOW}. */ private int mDragMode = DRAG_WINDOW; /** * The current drawer state. * * @see #STATE_CLOSED * @see #STATE_CLOSING * @see #STATE_DRAGGING * @see #STATE_OPENING * @see #STATE_OPEN */ protected int mDrawerState = STATE_CLOSED; /** * The touch bezel size of the swipe back in px. */ protected int mTouchBezelSize; /** * The touch area size of the swipe back in px. */ protected int mTouchSize; /** * Listener used to dispatch state change events. */ private OnStateChangeListener mOnStateChangeListener; /** * An additional {@link OnStateChangeListener} which will be plugged in to * the internal delegate to allow to observe the internal state from outside */ private OnStateChangeListener mAdditionalOnStateChangeListener; /** * Touch mode for the Drawer. * Possible values are {@link #TOUCH_MODE_NONE}, {@link #TOUCH_MODE_BEZEL} or {@link #TOUCH_MODE_FULLSCREEN} * Default: {@link #TOUCH_MODE_BEZEL} */ protected int mTouchMode = TOUCH_MODE_FULLSCREEN; /** * Indicates whether to use {@link android.view.View#LAYER_TYPE_HARDWARE} when animating the drawer. */ protected boolean mHardwareLayersEnabled = true; /** * The Activity the drawer is attached to. */ private Activity mActivity; /** * Bundle used to hold the drawers state. */ protected Bundle mState; /** * The maximum duration of open/close animations. */ protected int mMaxAnimationDuration = DEFAULT_ANIMATION_DURATION; /** * Callback that lets the listener override intercepting of touch events. */ protected OnInterceptMoveEventListener mOnInterceptMoveEventListener; /** * The position of the drawer. */ private Position mPosition; private Position mResolvedPosition; protected boolean mIsStatic = false; protected final Rect mDividerRect = new Rect(); /** * Current offset. */ protected float mOffsetPixels; /** * Whether an overlay should be drawn as the drawer is opened and closed. */ protected boolean mDrawOverlay; /** * The SwipeBackTransformer */ protected SwipeBackTransformer mSwipeBackTransformer; /** * Attaches the SwipeBack to the Activity. * * @param activity The activity that the SwipeBack will be attached to. * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity) { return attach(activity, Type.BEHIND); } /** * Attaches the SwipeBack to the Activity. * * @param activity The activity that the SwipeBack will be attached to. * @param transformer the transformer * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity, SwipeBackTransformer transformer) { return attach(activity, Type.BEHIND, transformer); } /** * Attaches the SwipeBack to the Activity. * * @param activity * The activity the Swipe Back will be attached to. * @param type * The {@link SwipeBack.Type} of the drawer. * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity, Type type) { return attach(activity, type, Position.START); } /** * Attaches the SwipeBack to the Activity. * * @param activity * The activity the swipe back will be attached to. * @param type * The {@link SwipeBack.Type} of the drawer. * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity, Type type, SwipeBackTransformer transformer) { return attach(activity, type, Position.START); } /** * Attaches the SwipeBack to the Activity. * * @param activity * The activity the swipe back will be attached to. * @param position * Where to position the swipe back. * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity, Position position, SwipeBackTransformer transformer) { return attach(activity, Type.BEHIND, position, transformer); } /** * Attaches the SwipeBack to the Activity. * * @param activity * The activity the swipe back will be attached to. * @param position * Where to position the swipe back. * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity, Position position) { return attach(activity, Type.BEHIND, position); } /** * Attaches the SwipeBack to the Activity. * * @param activity * The activity the swipe back will be attached to. * @param type * The {@link SwipeBack.Type} of the drawer. * @param position * Where to position the swipe back. * @param transformer * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity, Type type, Position position, SwipeBackTransformer transformer) { return attach(activity, type, position, DRAG_WINDOW, transformer); } /** * Attaches the SwipeBack to the Activity * * @param activity * @param type * @param position * @param dragMode * The dragMode which is {@link #DRAG_CONTENT} or * {@link #DRAG_WINDOW} * @return The created SwipeBack instance */ public static SwipeBack attach(Activity activity, Type type, Position position, int dragMode) { return attach(activity, type, position, dragMode, new DefaultSwipeBackTransformer()); } /** * Attaches the SwipeBack to the Activity * * @param activity * @param type * @param position * @return The created SwipeBack instance */ public static SwipeBack attach(Activity activity, Type type, Position position) { return attach(activity, type, position, DRAG_WINDOW); } /** * Attaches the SwipeBack to the Activity. * * @param activity * The activity the swipe back will be attached to. * @param type * The {@link SwipeBack.Type} of the drawer. * @param position * Where to position the swipe back. * @param dragMode * The drag mode of the drawer. Can be either * {@link SwipeBack#DRAG_CONTENT} or * {@link SwipeBack#DRAG_WINDOW}. * @return The created SwipeBack instance. */ public static SwipeBack attach(Activity activity, Type type, Position position, int dragMode, SwipeBackTransformer transformer) { SwipeBack swipeBack = createSwipeBack(activity, dragMode, position, type, transformer); swipeBack.setId(R.id.sb__swipeBack); switch (dragMode) { case SwipeBack.DRAG_CONTENT: attachToContent(activity, swipeBack); break; case SwipeBack.DRAG_WINDOW: attachToDecor(activity, swipeBack); break; default: throw new RuntimeException("Unknown drag mode: " + dragMode); } return swipeBack; } /** * Constructs the appropriate SwipeBack based on the position. */ private static SwipeBack createSwipeBack(Activity activity, int dragMode, Position position, Type type, SwipeBackTransformer transformer) { SwipeBack drawerHelper; if (type == Type.OVERLAY) { drawerHelper = new OverlaySwipeBack(activity, dragMode); } else { drawerHelper = new SlidingSwipeBack(activity, dragMode); } final SwipeBack drawer = drawerHelper; drawer.mDragMode = dragMode; drawer.setPosition(position); drawer.mSwipeBackTransformer = transformer; drawer.initSwipeListener(); return drawer; } /** * Determines if the activity has been destroyed or finished. This is useful * to dertermine if a * * @return */ @SuppressLint("NewApi") protected boolean isActivitiyDestroyed() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { return mActivity.isFinishing() || mActivity.isDestroyed(); } else { return mActivity.isFinishing(); } } private void initSwipeListener() { mOnStateChangeListener = new OnStateChangeListener() { @Override public void onStateChanged(int oldState, int newState) { if (!isActivitiyDestroyed()) { if (mSwipeBackTransformer != null) { if (STATE_OPEN == newState){ mSwipeBackTransformer.onSwipeBackCompleted( SwipeBack.this, mActivity); } else if (STATE_CLOSED == newState){ mSwipeBackTransformer.onSwipeBackReseted( SwipeBack.this, mActivity); } } else { Log.w(TAG, "Internal state changed, but no " + SwipeBackTransformer.class.getSimpleName() + " is registered"); } // Inform additional listener if (mAdditionalOnStateChangeListener != null) { mAdditionalOnStateChangeListener.onStateChanged( oldState, newState); } } } @Override public void onSlide(float openRatio, int offsetPixels) { if (!isActivitiyDestroyed()) { if (mSwipeBackTransformer != null) { mSwipeBackTransformer.onSwiping(SwipeBack.this, openRatio, offsetPixels); } else { Log.w(TAG, "Swiping, but no " + SwipeBackTransformer.class.getSimpleName() + " is registered"); } if (mAdditionalOnStateChangeListener != null) { mAdditionalOnStateChangeListener.onSlide(openRatio, offsetPixels); } } } }; } /** * Attaches the swipe back to the content view. */ private static void attachToContent(Activity activity, SwipeBack swipeBack) { /** * Do not call mActivity#setContentView. * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to * SwipeBack#setContentView, which then again would call Activity#setContentView. */ ViewGroup content = (ViewGroup) activity .findViewById(android.R.id.content); content.removeAllViews(); content.addView(swipeBack, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } /** * Attaches the swipe back drawer to the window. */ private static void attachToDecor(Activity activity, SwipeBack swipeBack) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0); decorView.removeAllViews(); decorView.addView(swipeBack, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); swipeBack.mContentContainer.addView(decorChild, decorChild.getLayoutParams()); } SwipeBack(Activity activity, int dragMode) { this(activity); mActivity = activity; mDragMode = dragMode; } public SwipeBack(Context context) { this(context, null); } public SwipeBack(Context context, AttributeSet attrs) { this(context, attrs, R.attr.swipeBackStyle); } public SwipeBack(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } @SuppressWarnings("deprecation") @SuppressLint("NewApi") protected void init(Context context, AttributeSet attrs, int defStyle) { setWillNotDraw(false); setFocusable(false); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeBack, R.attr.swipeBackStyle, R.style.Widget_SwipeBack); final Drawable contentBackground = a.getDrawable(R.styleable.SwipeBack_sbContentBackground); final Drawable swipeBackBackground = a.getDrawable(R.styleable.SwipeBack_sbSwipeBackBackground); mSwipeBackViewSize = a.getDimensionPixelSize(R.styleable.SwipeBack_sbSwipeBackSize, dpToPx(DEFAULT_SIZE)); mDividerEnabled = a.getBoolean(R.styleable.SwipeBack_sbDividerEnabled, false); mDividerDrawable = a.getDrawable(R.styleable.SwipeBack_sbDivider); if (mDividerDrawable == null) { mDividerAsShadowColor = a.getColor(R.styleable.SwipeBack_sbDividerAsShadowColor, 0xFF000000); } else { mCustomDivider = true; } mDividerSize = a.getDimensionPixelSize(R.styleable.SwipeBack_sbDividerSize, dpToPx(DEFAULT_DIVIDER_SIZE_DP)); mTouchBezelSize = a.getDimensionPixelSize(R.styleable.SwipeBack_sbBezelSize, dpToPx(DEFAULT_DRAG_BEZEL_DP)); mMaxAnimationDuration = a.getInt(R.styleable.SwipeBack_sbMaxAnimationDuration, DEFAULT_ANIMATION_DURATION); mDrawOverlay = a.getBoolean(R.styleable.SwipeBack_sbDrawOverlay, false); final int position = a.getInt(R.styleable.SwipeBack_sbSwipeBackPosition, 0); setPosition(Position.fromValue(position)); a.recycle(); mSwipeBackOverlay = new ColorDrawable(0xFF000000); mSwipeBackContainer = new NoClickThroughFrameLayout(context); mSwipeBackContainer.setId(R.id.sb__swipeBackContainer); mContentContainer = new NoClickThroughFrameLayout(context); mContentContainer.setId(R.id.sb__content); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mContentContainer.setBackgroundDrawable(contentBackground); mSwipeBackContainer.setBackgroundDrawable(swipeBackBackground); } else { mContentContainer.setBackground(contentBackground); mSwipeBackContainer.setBackground(swipeBackBackground); } initSwipeListener(); } @Override protected void onFinishInflate() { super.onFinishInflate(); View swipeBackView = findViewById(R.id.sbSwipeBackView); if (swipeBackView != null) { removeView(swipeBackView); setSwipeBackView(swipeBackView); } View content = findViewById(R.id.sbContent); if (content != null) { removeView(content); setContentView(content); } if (getChildCount() > 2) { throw new IllegalStateException( "swipe back and content view added in xml must have id's @id/sbSwipeBackView and @id/sbContent"); } } public int dpToPx(int dp) { return (int) (getResources().getDisplayMetrics().density * dp + 0.5f); } protected boolean isViewDescendant(View v) { ViewParent parent = v.getParent(); while (parent != null) { if (parent == this) { return true; } parent = parent.getParent(); } return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); getViewTreeObserver().addOnScrollChangedListener(mScrollListener); } @Override protected void onDetachedFromWindow() { Log.d(TAG, "detach from window"); getViewTreeObserver().removeOnScrollChangedListener(mScrollListener); super.onDetachedFromWindow(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); final int offsetPixels = (int) mOffsetPixels; if (mDrawOverlay && offsetPixels != 0) { drawOverlay(canvas); } if (mDividerEnabled && (offsetPixels != 0 || mIsStatic)) { drawDivider(canvas); } } protected abstract void drawOverlay(Canvas canvas); private void drawDivider(Canvas canvas) { // Can't pass the position to the constructor, so wait with loading the drawable until the divider is // actually drawn. if (mDividerDrawable == null) { setDividerAsShadowColor(mDividerAsShadowColor); } updateDividerRect(); mDividerDrawable.setBounds(mDividerRect); mDividerDrawable.draw(canvas); } protected void updateDividerRect() { // This updates the rect for the static and sliding drawer. The overlay drawer has its own implementation. switch (getPosition()) { case LEFT: mDividerRect.top = 0; mDividerRect.bottom = getHeight(); mDividerRect.right = ViewHelper.getLeft(mContentContainer); mDividerRect.left = mDividerRect.right - mDividerSize; break; case TOP: mDividerRect.left = 0; mDividerRect.right = getWidth(); mDividerRect.bottom = ViewHelper.getTop(mContentContainer); mDividerRect.top = mDividerRect.bottom - mDividerSize; break; case RIGHT: mDividerRect.top = 0; mDividerRect.bottom = getHeight(); mDividerRect.left = ViewHelper.getRight(mContentContainer); mDividerRect.right = mDividerRect.left + mDividerSize; break; case BOTTOM: mDividerRect.left = 0; mDividerRect.right = getWidth(); mDividerRect.top = ViewHelper.getBottom(mContentContainer); mDividerRect.bottom = mDividerRect.top + mDividerSize; break; } } private void setPosition(Position position) { mPosition = position; mResolvedPosition = getPosition(); } protected Position getPosition() { final int layoutDirection = ViewHelper.getLayoutDirection(this); switch (mPosition) { case START: if (layoutDirection == LAYOUT_DIRECTION_RTL) { return Position.RIGHT; } else { return Position.LEFT; } case END: if (layoutDirection == LAYOUT_DIRECTION_RTL) { return Position.LEFT; } else { return Position.RIGHT; } } return mPosition; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public void onRtlPropertiesChanged(int layoutDirection) { super.onRtlPropertiesChanged(layoutDirection); if (!mCustomDivider) { setDividerAsShadowColor(mDividerAsShadowColor); } if (getPosition() != mResolvedPosition) { mResolvedPosition = getPosition(); setOffsetPixels(mOffsetPixels * -1); } requestLayout(); invalidate(); } /** * Sets the number of pixels the content should be offset. * * @param offsetPixels The number of pixels to offset the content by. */ protected void setOffsetPixels(float offsetPixels) { final int oldOffset = (int) mOffsetPixels; final int newOffset = (int) offsetPixels; mOffsetPixels = offsetPixels; if (newOffset != oldOffset) { onOffsetPixelsChanged(newOffset); mSwipeBackViewVisible = newOffset != 0; // Notify any attached listeners of the current open ratio final float openRatio = ((float) Math.abs(newOffset)) / mSwipeBackViewSize; dispatchOnDrawerSlide(openRatio, newOffset); } } /** * Called when the number of pixels the content should be offset by has changed. * * @param offsetPixels The number of pixels to offset the content by. */ protected abstract void onOffsetPixelsChanged(int offsetPixels); /** * Toggles the swipe back open and close with animation. */ public SwipeBack toggle() { return toggle(true); } /** * Toggles the swipe back open and close. * * @param animate * Whether open/close should be animated. */ public abstract SwipeBack toggle(boolean animate); /** * Animates the swipe back open. */ public SwipeBack open() { return open(true); } /** * Opens the swipe back. * * @param animate * Whether open/close should be animated. */ public abstract SwipeBack open(boolean animate); /** * Set the background color of the swipe back view container (The container * where the swipe back view is inflated into) * * @param color * The color (not resource id) * @return */ public SwipeBack setSwipeBackContainerBackgroundColor(int color) { mSwipeBackContainer.setBackgroundColor(color); return this; } /** * Set the background of the wipe swipe back view container (The container * where the swipe back view is inflated into) * * @param d * @return */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public SwipeBack setSwipeBackContainerBackgroundDrawable(Drawable d) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mSwipeBackContainer.setBackgroundDrawable(d); } else { mSwipeBackContainer.setBackground(d); } return this; } /** * Set the background of the wipe swipe back view container (The container * where the swipe back view is inflated into) * * @param resId * The resource id of the drawable. Will interanlly call * getResources().getDrawable(resId) * @return */ public SwipeBack setSwipeBackContainerBackgroundDrawable(int resId) { return setSwipeBackContainerBackgroundDrawable(getResources() .getDrawable(resId)); } /** * Animates the swipe back closed. */ public SwipeBack close() { return close(true); } /** * Closes the swipe back. * * @param animate Whether open/close should be animated. */ public abstract SwipeBack close(boolean animate); /** * Indicates whether the swipe back is currently visible. * * @return True if the swipe back is open, false otherwise. */ public abstract boolean isVisible(); /** * Set the size of the swipe back when open. * * @param size * The size of the swipe back. */ public abstract SwipeBack setSize(int size); /** * Returns the size of the swipe back. * * @return The size of the swipe back. */ public int getSize() { return mSwipeBackViewSize; } /** * Scroll listener that checks whether the active view has moved before the drawer is invalidated. */ private final ViewTreeObserver.OnScrollChangedListener mScrollListener = new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (mActiveView != null && isViewDescendant(mActiveView)) { mActiveView.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(mActiveView, mTempRect); if (mTempRect.left != mActiveRect.left || mTempRect.top != mActiveRect.top || mTempRect.right != mActiveRect.right || mTempRect.bottom != mActiveRect.bottom) { invalidate(); } } } }; /** * Compute the touch area based on the touch mode. */ protected void updateTouchAreaSize() { if (mTouchMode == TOUCH_MODE_BEZEL) { mTouchSize = mTouchBezelSize; } else if (mTouchMode == TOUCH_MODE_FULLSCREEN) { mTouchSize = getMeasuredWidth(); } else { mTouchSize = 0; } } /** * Enables or disables offsetting the swipe back when dragging the drawer. * * @param offsetEnabled * True to offset the swipe back, false otherwise. */ public abstract void setOffsetSwipeBackViewEnabled(boolean offsetEnabled); /** * Indicates whether the swipe back is being offset when dragging the * drawer. * * @return True if the swipe back is being offset, false otherwise. */ public abstract boolean getOffsetSwipeBackEnabled(); /** * Get the current state of the drawer. * * @return The state of the drawer. */ public int getState() { return mDrawerState; } /** * Register a callback that will be invoked when the drawer is about to intercept touch events. * * @param listener The callback that will be invoked. */ public void setOnInterceptMoveEventListener(OnInterceptMoveEventListener listener) { mOnInterceptMoveEventListener = listener; } /** * Defines whether the drop shadow is enabled. * * @param enabled Whether the drop shadow is enabled. */ public SwipeBack setDividerEnabled(boolean enabled) { mDividerEnabled = enabled; invalidate(); return this; } protected GradientDrawable.Orientation getDividerOrientation() { // Gets the orientation for the static and sliding drawer. The overlay drawer provides its own implementation. switch (getPosition()) { case TOP: return GradientDrawable.Orientation.BOTTOM_TOP; case RIGHT: return GradientDrawable.Orientation.LEFT_RIGHT; case BOTTOM: return GradientDrawable.Orientation.TOP_BOTTOM; default: return GradientDrawable.Orientation.RIGHT_LEFT; } } /** * Sets the color of the divider, if you have set the option to use a shadow * gradient as divider * * You must enable the divider by calling * {@link #setDividerEnabled(boolean)} * * @param color * The color of the divider shadow. */ public SwipeBack setDividerAsShadowColor(int color) { GradientDrawable.Orientation orientation = getDividerOrientation(); final int endColor = color & 0x00FFFFFF; GradientDrawable gradient = new GradientDrawable(orientation, new int[] { color, endColor, }); setDivider(gradient); return this; } /** * Sets the drawable of the divider. You must enable the divider by calling * {@link #setDividerEnabled(boolean)} * * @param drawable * The drawable of the divider. */ public SwipeBack setDivider(Drawable drawable) { mDividerDrawable = drawable; mCustomDivider = drawable != null; invalidate(); return this; } /** * Sets the drawable resource id of the divider . You must enable the * divider by calling {@link #setDividerEnabled(boolean)} * * @param resId * The resource identifier of the the drawable. * */ public SwipeBack setDivider(int resId) { return setDivider(getResources().getDrawable(resId)); } /** * Returns the drawable of the divider. */ public Drawable getDivider() { return mDividerDrawable; } /** * Sets the size (width) of the divider. The value is a dp value * * @param size * The size (width) of the divider in dp (device independent * pixel = dp = dip). * @see #setDividerSizeInPixel(int) */ public SwipeBack setDividerSize(int dp) { mDividerSize = dpToPx(dp); invalidate(); return this; } /** * Sets the size (width) of the divider. The value is in pixel. * * @param pixel * The size (widht) of the divider in pixels * @return * @see #setDividerSize(int) */ public SwipeBack setDividerSizeInPixel(int pixel) { mDividerSize = pixel; invalidate(); return this; } /** * Draw the divider as solid color (using {@link ColorDrawable}). * * You must enable the divider by calling * {@link #setDividerEnabled(boolean)} * * @param color * @return */ public SwipeBack setDividerAsSolidColor(int color) { setDivider(new ColorDrawable(color)); return this; } /** * Animates the swipe back view slightly open until the user opens it completely. */ public abstract SwipeBack peekSwipeBack(); /** * Animates the swipe back view slightly open. If delay is larger than 0, this happens until the user opens the drawer. * * @param delay The delay (in milliseconds) between each run of the animation. If 0, this animation is only run * once. */ public abstract SwipeBack peekSwipeBack(long delay); /** * Animates the swipe back view slightly open. If delay is larger than 0, this happens until the user opens the drawer. * * @param startDelay The delay (in milliseconds) until the animation is first run. * @param delay The delay (in milliseconds) between each run of the animation. If 0, this animation is only run * once. */ public abstract SwipeBack peekSwipeBack(long startDelay, long delay); /** * Enables or disables the user of {@link android.view.View#LAYER_TYPE_HARDWARE} when animations views. * * @param enabled Whether hardware layers are enabled. */ public abstract SwipeBack setHardwareLayerEnabled(boolean enabled); /** * Sets the maximum duration of open/close animations. * * @param duration The maximum duration in milliseconds. */ public SwipeBack setMaxAnimationDuration(int duration) { mMaxAnimationDuration = duration; return this; } /** * Sets whether an overlay should be drawn when sliding the swipe back view. * * @param drawOverlay Whether an overlay should be drawn when sliding the drawer. */ public SwipeBack setDrawOverlay(boolean drawOverlay) { mDrawOverlay = drawOverlay; return this; } /** * Gets whether an overlay is drawn when sliding the swipe back view. * * @return Whether an overlay is drawn when sliding the drawer. */ public boolean getDrawOverlay() { return mDrawOverlay; } /** * Returns the ViewGroup used as a parent for the swipe back view. * * @return The swipe back view's parent. */ public ViewGroup getSwipeBackContainer() { return mSwipeBackContainer; } /** * Returns the ViewGroup used as a parent for the content view. * * @return The content view's parent. */ public ViewGroup getContentContainer() { if (mDragMode == DRAG_CONTENT) { return mContentContainer; } else { return (ViewGroup) findViewById(android.R.id.content); } } /** * Set the swipe back view from a layout resource. * * @param layoutResId * Resource ID to be inflated. */ public SwipeBack setSwipeBackView(int layoutResId) { mSwipeBackContainer.removeAllViews(); mSwipeBackView = LayoutInflater.from(getContext()).inflate(layoutResId, mSwipeBackContainer, false); mSwipeBackContainer.addView(mSwipeBackView); notifySwipeBackViewCreated(mSwipeBackView); return this; } /** * Set the swipe back view to an explicit view. * * @param view * The swipe back view. */ public SwipeBack setSwipeBackView(View view) { setSwipeBackView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); return this; } /** * Set the swipe back view to an explicit view. * * @param view * The swipe back view. * @param params * Layout parameters for the view. */ public SwipeBack setSwipeBackView(View view, LayoutParams params) { mSwipeBackView = view; mSwipeBackContainer.removeAllViews(); mSwipeBackContainer.addView(view, params); notifySwipeBackViewCreated(mSwipeBackView); return this; } /** * Notify the {@link SwipeBackTransformer} that the swipe back has been * created (inflated and ready to use) * * @param view */ private void notifySwipeBackViewCreated(View view) { if (mSwipeBackTransformer != null) { mSwipeBackTransformer.onSwipeBackViewCreated(this, mActivity, view); } } /** * Returns the swipe back view. * * @return The swipe back view. */ public View getSwipeBackView() { return mSwipeBackView; } /** * Set the content from a layout resource. * * @param layoutResId Resource ID to be inflated. */ public SwipeBack setContentView(int layoutResId) { switch (mDragMode) { case SwipeBack.DRAG_CONTENT: mContentContainer.removeAllViews(); LayoutInflater.from(getContext()).inflate(layoutResId, mContentContainer, true); break; case SwipeBack.DRAG_WINDOW: mActivity.setContentView(layoutResId); break; } return this; } /** * Set the content to an explicit view. * * @param view The desired content to display. */ public SwipeBack setContentView(View view) { setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); return this; } /** * Set the content to an explicit view. * * @param view The desired content to display. * @param params Layout parameters for the view. */ public SwipeBack setContentView(View view, LayoutParams params) { switch (mDragMode) { case SwipeBack.DRAG_CONTENT: mContentContainer.removeAllViews(); mContentContainer.addView(view, params); break; case SwipeBack.DRAG_WINDOW: // mActivity can be null if inflated from xml, so retrieve activity // if (mActivity == null) { // mActivity = (Activity) getContext(); mActivity.setContentView(view, params); break; } return this; } protected SwipeBack setDrawerState(int state) { if (state != mDrawerState) { final int oldState = mDrawerState; mDrawerState = state; if (mOnStateChangeListener != null) { mOnStateChangeListener.onStateChanged(oldState, state); } if (DEBUG) { logDrawerState(state); } } return this; } protected SwipeBack logDrawerState(int state) { switch (state) { case STATE_CLOSED: Log.d(TAG, "[DrawerState] STATE_CLOSED"); break; case STATE_CLOSING: Log.d(TAG, "[DrawerState] STATE_CLOSING"); break; case STATE_DRAGGING: Log.d(TAG, "[DrawerState] STATE_DRAGGING"); break; case STATE_OPENING: Log.d(TAG, "[DrawerState] STATE_OPENING"); break; case STATE_OPEN: Log.d(TAG, "[DrawerState] STATE_OPEN"); break; default: Log.d(TAG, "[DrawerState] Unknown: " + state); } return this; } /** * Returns the touch mode. */ public abstract int getTouchMode(); /** * Sets the drawer touch mode. Possible values are {@link #TOUCH_MODE_NONE}, {@link #TOUCH_MODE_BEZEL} or * {@link #TOUCH_MODE_FULLSCREEN}. * * @param mode The touch mode. */ public abstract SwipeBack setTouchMode(int mode); /** * Sets the size of the touch bezel. * * @param size The touch bezel size in px. */ public abstract SwipeBack setTouchBezelSize(int size); /** * Returns the size of the touch bezel in px. */ public abstract int getTouchBezelSize(); /** * Set the {@link SwipeBackTransformer} * * @param transformer */ public SwipeBack setSwipeBackTransformer(SwipeBackTransformer transformer) { mSwipeBackTransformer = transformer; if (mSwipeBackView != null) { notifySwipeBackViewCreated(mSwipeBackView); } return this; } /** * Get the {@link SwipeBackTransformer} * * @return */ public SwipeBackTransformer getSwipeBackTransformer() { return mSwipeBackTransformer; } /** * An additional {@link OnStateChangeListener} which will be plugged in to * the internal delegate to allow to observe the internal state from outside * * @param listener * The {@link OnStateChangeListener} listener * @return */ public SwipeBack setOnStateChangeListener(OnStateChangeListener listener) { this.mAdditionalOnStateChangeListener = listener; return this; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void postOnAnimation(Runnable action) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { super.postOnAnimation(action); } else { postDelayed(action, ANIMATION_DELAY); } } @Override protected boolean fitSystemWindows(Rect insets) { if (mDragMode == DRAG_WINDOW && mPosition != Position.BOTTOM) { mSwipeBackContainer.setPadding(0, insets.top, 0, 0); } return super.fitSystemWindows(insets); } protected void dispatchOnDrawerSlide(float openRatio, int offsetPixels) { if (mOnStateChangeListener != null) { mOnStateChangeListener.onSlide(openRatio, offsetPixels); } } /** * Saves the state of the drawer. * * @return Returns a Parcelable containing the drawer state. */ public final Parcelable saveState() { if (mState == null) { mState = new Bundle(); } saveState(mState); return mState; } void saveState(Bundle state) { // State saving isn't required for subclasses. } /** * Restores the state of the drawer. * * @param in A parcelable containing the drawer state. */ public void restoreState(Parcelable in) { mState = (Bundle) in; } @Override protected Parcelable onSaveInstanceState() { return super.onSaveInstanceState(); // Parcelable superState = super.onSaveInstanceState(); // SavedState state = new SavedState(superState); // if (mState == null) { // mState = new Bundle(); // saveState(mState); // state.mState = mState; // return state; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); restoreState(savedState.mState); } static class SavedState extends BaseSavedState { Bundle mState; public SavedState(Parcelable superState) { super(superState); } public SavedState(Parcel in) { super(in); mState = in.readBundle(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeBundle(mState); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package com.bloatit.web.pages; import static com.bloatit.framework.webserver.Context.tr; import com.bloatit.framework.exceptions.lowlevel.RedirectException; import com.bloatit.framework.utils.Image; import com.bloatit.framework.utils.PageIterable; import com.bloatit.framework.webserver.annotations.ParamContainer; import com.bloatit.framework.webserver.components.HtmlDiv; import com.bloatit.framework.webserver.components.HtmlImage; import com.bloatit.framework.webserver.components.HtmlTitle; import com.bloatit.model.HighlightFeature; import com.bloatit.model.managers.HighlightFeatureManager; import com.bloatit.web.WebConfiguration; import com.bloatit.web.components.IndexFeatureBlock; import com.bloatit.web.linkable.documentation.SideBarDocumentationBlock; import com.bloatit.web.linkable.metabugreport.SideBarBugReportBlock; import com.bloatit.web.pages.master.Breadcrumb; import com.bloatit.web.pages.master.MasterPage; import com.bloatit.web.pages.master.TwoColumnLayout; import com.bloatit.web.url.IndexPageUrl; @ParamContainer("index") public final class IndexPage extends MasterPage { private final IndexPageUrl url; public IndexPage(final IndexPageUrl url) { super(url); this.url = url; } @Override protected void doCreate() throws RedirectException { final HtmlDiv globalDescription = new HtmlDiv("global_description"); { HtmlTitle title = new HtmlTitle("Get paid to create free software", 1); globalDescription.add(title); HtmlImage image = new HtmlImage(new Image(WebConfiguration.getImgPresentation()), tr("Elveos's presentation")); globalDescription.add(image); } add(globalDescription); TwoColumnLayout twoColumnLayout = new TwoColumnLayout(true); twoColumnLayout.addLeft(new HtmlTitle(tr("Hightlighted features"), 1)); final HtmlDiv featureList = new HtmlDiv("feature_list"); { final int featureCount = 6; final PageIterable<HighlightFeature> hightlightFeatureList = HighlightFeatureManager.getAll(); final HighlightFeature[] hightlightFeatureArray = new HighlightFeature[featureCount]; for (final HighlightFeature highlightFeature : hightlightFeatureList) { final int position = highlightFeature.getPosition() - 1; if (position < featureCount) { if (hightlightFeatureArray[position] == null) { hightlightFeatureArray[position] = highlightFeature; } else { if (hightlightFeatureArray[position].getActivationDate().before(highlightFeature.getActivationDate())) { hightlightFeatureArray[position] = highlightFeature; } } } } for (int i = 0; i < (featureCount + 1) / 2; i++) { final HtmlDiv featureListRow = new HtmlDiv("feature_list_row"); { final HtmlDiv featureListLeftCase = new HtmlDiv("feature_list_left_case"); { HighlightFeature highlightFeature = hightlightFeatureArray[i * 2]; if (highlightFeature != null) { featureListLeftCase.add(new IndexFeatureBlock(highlightFeature)); } } featureListRow.add(featureListLeftCase); final HtmlDiv featureListRightCase = new HtmlDiv("feature_list_right_case"); { HighlightFeature highlightFeature = hightlightFeatureArray[i * 2 + 1]; if (highlightFeature != null) { featureListRightCase.add(new IndexFeatureBlock(highlightFeature)); } } featureListRow.add(featureListRightCase); } featureList.add(featureListRow); } } twoColumnLayout.addLeft(featureList); twoColumnLayout.addRight(new SideBarDocumentationBlock("home")); twoColumnLayout.addRight(new SideBarBugReportBlock(url)); add(twoColumnLayout); } @Override protected String getPageTitle() { return "Finance free software"; } @Override public boolean isStable() { return true; } public static Breadcrumb generateBreadcrumb() { Breadcrumb breadcrumb = new Breadcrumb(); IndexPageUrl pageUrl = new IndexPageUrl(); breadcrumb.pushLink(pageUrl.getHtmlLink(tr("Home"))); return breadcrumb; } @Override protected Breadcrumb getBreadcrumb() { return generateBreadcrumb(); } }
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.cert.CRL; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.X509CRL; import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.Collection; import java.util.Iterator; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DEREnumerated; import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; import org.bouncycastle.asn1.x509.CRLReason; import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.jce.X509KeyUsage; import org.bouncycastle.jce.X509Principal; import org.bouncycastle.x509.X509V1CertificateGenerator; import org.bouncycastle.x509.X509V2CRLGenerator; import org.bouncycastle.x509.X509V3CertificateGenerator; import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; import org.bouncycastle.x509.extension.X509ExtensionUtil; import org.bouncycastle.jce.interfaces.ECPointEncoder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.jce.spec.GOST3410ParameterSpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; public class CertTest extends SimpleTest { // server.crt byte[] cert1 = Base64.decode( "MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU2MjFaFw0wMTA2" + "MDIwNzU2MjFaMIG4MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxFzAVBgNVBAsTDldlYnNlcnZlciBUZWFtMR0wGwYDVQQDExR3d3cyLmNvbm5l" + "Y3Q0LmNvbS5hdTEoMCYGCSqGSIb3DQEJARYZd2VibWFzdGVyQGNvbm5lY3Q0LmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArvDxclKAhyv7Q/Wmr2re" + "Gw4XL9Cnh9e+6VgWy2AWNy/MVeXdlxzd7QAuc1eOWQkGQEiLPy5XQtTY+sBUJ3AO" + "Rvd2fEVJIcjf29ey7bYua9J/vz5MG2KYo9/WCHIwqD9mmG9g0xLcfwq/s8ZJBswE" + "7sb85VU+h94PTvsWOsWuKaECAwEAAaN3MHUwJAYDVR0RBB0wG4EZd2VibWFzdGVy" + "QGNvbm5lY3Q0LmNvbS5hdTA6BglghkgBhvhCAQ0ELRYrbW9kX3NzbCBnZW5lcmF0" + "ZWQgY3VzdG9tIHNlcnZlciBjZXJ0aWZpY2F0ZTARBglghkgBhvhCAQEEBAMCBkAw" + "DQYJKoZIhvcNAQEEBQADgYEAotccfKpwSsIxM1Hae8DR7M/Rw8dg/RqOWx45HNVL" + "iBS4/3N/TO195yeQKbfmzbAA2jbPVvIvGgTxPgO1MP4ZgvgRhasaa0qCJCkWvpM4" + "yQf33vOiYQbpv4rTwzU8AmRlBG45WdjyNIigGV+oRc61aKCTnLq7zB8N3z1TF/bF" + "5/8="); // ca.crt byte[] cert2 = Base64.decode( "MIIDbDCCAtWgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU1MzNaFw0wMTA2" + "MDIwNzU1MzNaMIG3MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEVMBMGA1UEAxMMQ29u" + "bmVjdCA0IENBMSgwJgYJKoZIhvcNAQkBFhl3ZWJtYXN0ZXJAY29ubmVjdDQuY29t" + "LmF1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgs5ptNG6Qv1ZpCDuUNGmv" + "rhjqMDPd3ri8JzZNRiiFlBA4e6/ReaO1U8ASewDeQMH6i9R6degFdQRLngbuJP0s" + "xcEE+SksEWNvygfzLwV9J/q+TQDyJYK52utb++lS0b48A1KPLwEsyL6kOAgelbur" + "ukwxowprKUIV7Knf1ajetQIDAQABo4GFMIGCMCQGA1UdEQQdMBuBGXdlYm1hc3Rl" + "ckBjb25uZWN0NC5jb20uYXUwDwYDVR0TBAgwBgEB/wIBADA2BglghkgBhvhCAQ0E" + "KRYnbW9kX3NzbCBnZW5lcmF0ZWQgY3VzdG9tIENBIGNlcnRpZmljYXRlMBEGCWCG" + "SAGG+EIBAQQEAwICBDANBgkqhkiG9w0BAQQFAAOBgQCsGvfdghH8pPhlwm1r3pQk" + "msnLAVIBb01EhbXm2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz" + "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ" + "DhkaJ8VqOMajkQFma2r9iA=="); // testx509.pem byte[] cert3 = Base64.decode( "MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV" + "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz" + "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM" + "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF" + "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO" + "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE" + "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ" + "zl9HYIMxATFyqSiD9jsx"); // v3-cert1.pem byte[] cert4 = Base64.decode( "MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx" + "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz" + "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw" + "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu" + "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2" + "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp" + "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C" + "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK" + "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x" + "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR" + "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB" + "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21" + "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3" + "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO"); // v3-cert2.pem byte[] cert5 = Base64.decode( "MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD" + "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0" + "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu" + "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1" + "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV" + "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx" + "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA" + "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT" + "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ" + "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm" + "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc" + "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz" + "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap" + "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU="); // pem encoded pkcs7 byte[] cert6 = Base64.decode( "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIJbzCCAj0w" + "ggGmAhEAzbp/VvDf5LxU/iKss3KqVTANBgkqhkiG9w0BAQIFADBfMQswCQYDVQQGEwJVUzEXMBUG" + "A1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGljIFByaW1hcnkgQ2Vy" + "dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTYwMTI5MDAwMDAwWhcNMjgwODAxMjM1OTU5WjBfMQsw" + "CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVi" + "bGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0A" + "MIGJAoGBAOUZv22jVmEtmUhx9mfeuY3rt56GgAqRDvo4Ja9GiILlc6igmyRdDR/MZW4MsNBWhBiH" + "mgabEKFz37RYOWtuwfYV1aioP6oSBo0xrH+wNNePNGeICc0UEeJORVZpH3gCgNrcR5EpuzbJY1zF" + "4Ncth3uhtzKwezC6Ki8xqu6jZ9rbAgMBAAEwDQYJKoZIhvcNAQECBQADgYEATD+4i8Zo3+5DMw5d" + "6abLB4RNejP/khv0Nq3YlSI2aBFsfELM85wuxAc/FLAPT/+Qknb54rxK6Y/NoIAK98Up8YIiXbix" + "3YEjo3slFUYweRb46gVLlH8dwhzI47f0EEA8E8NfH1PoSOSGtHuhNbB7Jbq4046rPzidADQAmPPR" + "cZQwggMuMIICl6ADAgECAhEA0nYujRQMPX2yqCVdr+4NdTANBgkqhkiG9w0BAQIFADBfMQswCQYD" + "VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGlj" + "IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTgwNTEyMDAwMDAwWhcNMDgwNTEy" + "MjM1OTU5WjCBzDEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy" + "dXN0IE5ldHdvcmsxRjBEBgNVBAsTPXd3dy52ZXJpc2lnbi5jb20vcmVwb3NpdG9yeS9SUEEgSW5j" + "b3JwLiBCeSBSZWYuLExJQUIuTFREKGMpOTgxSDBGBgNVBAMTP1ZlcmlTaWduIENsYXNzIDEgQ0Eg" + "SW5kaXZpZHVhbCBTdWJzY3JpYmVyLVBlcnNvbmEgTm90IFZhbGlkYXRlZDCBnzANBgkqhkiG9w0B" + "AQEFAAOBjQAwgYkCgYEAu1pEigQWu1X9A3qKLZRPFXg2uA1Ksm+cVL+86HcqnbnwaLuV2TFBcHqB" + "S7lIE1YtxwjhhEKrwKKSq0RcqkLwgg4C6S/7wju7vsknCl22sDZCM7VuVIhPh0q/Gdr5FegPh7Yc" + "48zGmo5/aiSS4/zgZbqnsX7vyds3ashKyAkG5JkCAwEAAaN8MHowEQYJYIZIAYb4QgEBBAQDAgEG" + "MEcGA1UdIARAMD4wPAYLYIZIAYb4RQEHAQEwLTArBggrBgEFBQcCARYfd3d3LnZlcmlzaWduLmNv" + "bS9yZXBvc2l0b3J5L1JQQTAPBgNVHRMECDAGAQH/AgEAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0B" + "AQIFAAOBgQCIuDc73dqUNwCtqp/hgQFxHpJqbS/28Z3TymQ43BuYDAeGW4UVag+5SYWklfEXfWe0" + "fy0s3ZpCnsM+tI6q5QsG3vJWKvozx74Z11NMw73I4xe1pElCY+zCphcPXVgaSTyQXFWjZSAA/Rgg" + "5V+CprGoksVYasGNAzzrw80FopCubjCCA/gwggNhoAMCAQICEBbbn/1G1zppD6KsP01bwywwDQYJ" + "KoZIhvcNAQEEBQAwgcwxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln" + "biBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3JlcG9zaXRvcnkvUlBB" + "IEluY29ycC4gQnkgUmVmLixMSUFCLkxURChjKTk4MUgwRgYDVQQDEz9WZXJpU2lnbiBDbGFzcyAx" + "IENBIEluZGl2aWR1YWwgU3Vic2NyaWJlci1QZXJzb25hIE5vdCBWYWxpZGF0ZWQwHhcNMDAxMDAy" + "MDAwMDAwWhcNMDAxMjAxMjM1OTU5WjCCAQcxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYD" + "VQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3Jl" + "cG9zaXRvcnkvUlBBIEluY29ycC4gYnkgUmVmLixMSUFCLkxURChjKTk4MR4wHAYDVQQLExVQZXJz" + "b25hIE5vdCBWYWxpZGF0ZWQxJzAlBgNVBAsTHkRpZ2l0YWwgSUQgQ2xhc3MgMSAtIE1pY3Jvc29m" + "dDETMBEGA1UEAxQKRGF2aWQgUnlhbjElMCMGCSqGSIb3DQEJARYWZGF2aWRAbGl2ZW1lZGlhLmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqxBsdeNmSvFqhMNwhQgNzM8mdjX9eSXb" + "DawpHtQHjmh0AKJSa3IwUY0VIsyZHuXWktO/CgaMBVPt6OVf/n0R2sQigMP6Y+PhEiS0vCJBL9aK" + "0+pOo2qXrjVBmq+XuCyPTnc+BOSrU26tJsX0P9BYorwySiEGxGanBNATdVL4NdUCAwEAAaOBnDCB" + "mTAJBgNVHRMEAjAAMEQGA1UdIAQ9MDswOQYLYIZIAYb4RQEHAQgwKjAoBggrBgEFBQcCARYcaHR0" + "cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTARBglghkgBhvhCAQEEBAMCB4AwMwYDVR0fBCwwKjAo" + "oCagJIYiaHR0cDovL2NybC52ZXJpc2lnbi5jb20vY2xhc3MxLmNybDANBgkqhkiG9w0BAQQFAAOB" + "gQBC8yIIdVGpFTf8/YiL14cMzcmL0nIRm4kGR3U59z7UtcXlfNXXJ8MyaeI/BnXwG/gD5OKYqW6R" + "yca9vZOxf1uoTBl82gInk865ED3Tej6msCqFzZffnSUQvOIeqLxxDlqYRQ6PmW2nAnZeyjcnbI5Y" + "syQSM2fmo7n6qJFP+GbFezGCAkUwggJBAgEBMIHhMIHMMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j" + "LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazFGMEQGA1UECxM9d3d3LnZlcmlzaWdu" + "LmNvbS9yZXBvc2l0b3J5L1JQQSBJbmNvcnAuIEJ5IFJlZi4sTElBQi5MVEQoYyk5ODFIMEYGA1UE" + "AxM/VmVyaVNpZ24gQ2xhc3MgMSBDQSBJbmRpdmlkdWFsIFN1YnNjcmliZXItUGVyc29uYSBOb3Qg" + "VmFsaWRhdGVkAhAW25/9Rtc6aQ+irD9NW8MsMAkGBSsOAwIaBQCggbowGAYJKoZIhvcNAQkDMQsG" + "CSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDAxMDAyMTczNTE4WjAjBgkqhkiG9w0BCQQxFgQU" + "gZjSaBEY2oxGvlQUIMnxSXhivK8wWwYJKoZIhvcNAQkPMU4wTDAKBggqhkiG9w0DBzAOBggqhkiG" + "9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwBwYFKw4DAh0w" + "DQYJKoZIhvcNAQEBBQAEgYAzk+PU91/ZFfoiuKOECjxEh9fDYE2jfDCheBIgh5gdcCo+sS1WQs8O" + "HreQ9Nop/JdJv1DQMBK6weNBBDoP0EEkRm1XCC144XhXZC82jBZohYmi2WvDbbC//YN58kRMYMyy" + "srrfn4Z9I+6kTriGXkrpGk9Q0LSGjmG2BIsqiF0dvwAAAAAAAA=="); // dsaWithSHA1 cert byte[] cert7 = Base64.decode( "MIIEXAYJKoZIhvcNAQcCoIIETTCCBEkCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCAsMwggK/MIIB4AIBADCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7" + "d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULjw3GobwaJX13kquPh" + "fVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABj" + "TUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/z" + "m8Q12PFp/PjOhh+nMA4xDDAKBgNVBAMTA0lEMzAeFw05NzEwMDEwMDAwMDBa" + "Fw0zODAxMDEwMDAwMDBaMA4xDDAKBgNVBAMTA0lEMzCB8DCBpwYFKw4DAhsw" + "gZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULj" + "w3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FE" + "WA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3" + "SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nA0QAAkEAkYkXLYMtGVGWj9OnzjPn" + "sB9sefSRPrVegZJCZbpW+Iv0/1RP1u04pHG9vtRpIQLjzUiWvLMU9EKQTThc" + "eNMmWDCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxg" + "Y61TX5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/Q" + "F4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jH" + "SqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nAy8AMCwC" + "FBY3dBSdeprGcqpr6wr3xbG+6WW+AhRMm/facKJNxkT3iKgJbp7R8Xd3QTGC" + "AWEwggFdAgEBMBMwDjEMMAoGA1UEAxMDSUQzAgEAMAkGBSsOAwIaBQCgXTAY" + "BgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMjA1" + "MjQyMzEzMDdaMCMGCSqGSIb3DQEJBDEWBBS4WMsoJhf7CVbZYCFcjoTRzPkJ" + "xjCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61T" + "X5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BU" + "j+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqji" + "jUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nBC8wLQIVALID" + "dt+MHwawrDrwsO1Z6sXBaaJsAhRaKssrpevmLkbygKPV07XiAKBG02Zvb2Jh" + "cg=="); // testcrl.pem byte[] crl1 = Base64.decode( "MIICjTCCAfowDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMxIDAeBgNVBAoT" + "F1JTQSBEYXRhIFNlY3VyaXR5LCBJbmMuMS4wLAYDVQQLEyVTZWN1cmUgU2VydmVy" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5Fw05NTA1MDIwMjEyMjZaFw05NTA2MDEw" + "MDAxNDlaMIIBaDAWAgUCQQAABBcNOTUwMjAxMTcyNDI2WjAWAgUCQQAACRcNOTUw" + "MjEwMDIxNjM5WjAWAgUCQQAADxcNOTUwMjI0MDAxMjQ5WjAWAgUCQQAADBcNOTUw" + "MjI1MDA0NjQ0WjAWAgUCQQAAGxcNOTUwMzEzMTg0MDQ5WjAWAgUCQQAAFhcNOTUw" + "MzE1MTkxNjU0WjAWAgUCQQAAGhcNOTUwMzE1MTk0MDQxWjAWAgUCQQAAHxcNOTUw" + "MzI0MTk0NDMzWjAWAgUCcgAABRcNOTUwMzI5MjAwNzExWjAWAgUCcgAAERcNOTUw" + "MzMwMDIzNDI2WjAWAgUCQQAAIBcNOTUwNDA3MDExMzIxWjAWAgUCcgAAHhcNOTUw" + "NDA4MDAwMjU5WjAWAgUCcgAAQRcNOTUwNDI4MTcxNzI0WjAWAgUCcgAAOBcNOTUw" + "NDI4MTcyNzIxWjAWAgUCcgAATBcNOTUwNTAyMDIxMjI2WjANBgkqhkiG9w0BAQIF" + "AAN+AHqOEJXSDejYy0UwxxrH/9+N2z5xu/if0J6qQmK92W0hW158wpJg+ovV3+wQ" + "wvIEPRL2rocL0tKfAsVq1IawSJzSNgxG0lrcla3MrJBnZ4GaZDu4FutZh72MR3Gt" + "JaAL3iTJHJD55kK2D/VoyY1djlsPuNh6AEgdVwFAyp0v"); // ecdsa cert with extra octet string. byte[] oldEcdsa = Base64.decode( "MIICljCCAkCgAwIBAgIBATALBgcqhkjOPQQBBQAwgY8xCzAJBgNVBAYTAkFVMSgwJ" + "gYDVQQKEx9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIwEAYDVQQHEw" + "lNZWxib3VybmUxETAPBgNVBAgTCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWV" + "kYmFjay1jcnlwdG9AYm91bmN5Y2FzdGxlLm9yZzAeFw0wMTEyMDcwMTAwMDRaFw0w" + "MTEyMDcwMTAxNDRaMIGPMQswCQYDVQQGEwJBVTEoMCYGA1UEChMfVGhlIExlZ2lvb" + "iBvZiB0aGUgQm91bmN5IENhc3RsZTESMBAGA1UEBxMJTWVsYm91cm5lMREwDwYDVQ" + "QIEwhWaWN0b3JpYTEvMC0GCSqGSIb3DQEJARYgZmVlZGJhY2stY3J5cHRvQGJvdW5" + "jeWNhc3RsZS5vcmcwgeQwgb0GByqGSM49AgEwgbECAQEwKQYHKoZIzj0BAQIef + "////////////f///////gAAAAAAAf///////MEAEHn///////////////3///////" + "4AAAAAAAH///////AQeawFsO9zxiUHQ1lSSFHXKcanbL7J9HTd5YYXClCwKBB8CD/" + "qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqvAh5///////////////9///+eXpq" + "fXZBx+9FSJoiQnQsDIgAEHwJbbcU7xholSP+w9nFHLebJUhqdLSU05lq/y9X+DHAw" + "CwYHKoZIzj0EAQUAA0MAMEACHnz6t4UNoVROp74ma4XNDjjGcjaqiIWPZLK8Bdw3G" + "QIeLZ4j3a6ividZl344UH+UPUE7xJxlYGuy7ejTsqRR"); byte[] uncompressedPtEC = Base64.decode( "MIIDKzCCAsGgAwIBAgICA+kwCwYHKoZIzj0EAQUAMGYxCzAJBgNVBAYTAkpQ" + "MRUwEwYDVQQKEwxuaXRlY2guYWMuanAxDjAMBgNVBAsTBWFpbGFiMQ8wDQYD" + "VQQDEwZ0ZXN0Y2ExHzAdBgkqhkiG9w0BCQEWEHRlc3RjYUBsb2NhbGhvc3Qw" + "HhcNMDExMDEzMTE1MzE3WhcNMjAxMjEyMTE1MzE3WjBmMQswCQYDVQQGEwJK" + "UDEVMBMGA1UEChMMbml0ZWNoLmFjLmpwMQ4wDAYDVQQLEwVhaWxhYjEPMA0G" + "A1UEAxMGdGVzdGNhMR8wHQYJKoZIhvcNAQkBFhB0ZXN0Y2FAbG9jYWxob3N0" + "MIIBczCCARsGByqGSM49AgEwggEOAgEBMDMGByqGSM49AQECKEdYWnajFmnZ" + "tzrukK2XWdle2v+GsD9l1ZiR6g7ozQDbhFH/bBiMDQcwVAQoJ5EQKrI54/CT" + "xOQ2pMsd/fsXD+EX8YREd8bKHWiLz8lIVdD5cBNeVwQoMKSc6HfI7vKZp8Q2" + "zWgIFOarx1GQoWJbMcSt188xsl30ncJuJT2OoARRBAqJ4fD+q6hbqgNSjTQ7" + "htle1KO3eiaZgcJ8rrnyN8P+5A8+5K+H9aQ/NbBR4Gs7yto5PXIUZEUgodHA" + "TZMSAcSq5ZYt4KbnSYaLY0TtH9CqAigEwZ+hglbT21B7ZTzYX2xj0x+qooJD" + "hVTLtIPaYJK2HrMPxTw6/zfrAgEPA1IABAnvfFcFDgD/JicwBGn6vR3N8MIn" + "mptZf/mnJ1y649uCF60zOgdwIyI7pVSxBFsJ7ohqXEHW0x7LrGVkdSEiipiH" + "LYslqh3xrqbAgPbl93GUo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB" + "/wQEAwIBxjAdBgNVHQ4EFgQUAEo62Xm9H6DcsE0zUDTza4BRG90wCwYHKoZI" + "zj0EAQUAA1cAMFQCKAQsCHHSNOqfJXLgt3bg5+k49hIBGVr/bfG0B9JU3rNt" + "Ycl9Y2zfRPUCKAK2ccOQXByAWfsasDu8zKHxkZv7LVDTFjAIffz3HaCQeVhD" + "z+fauEg="); byte[] keyUsage = Base64.decode( "MIIE7TCCBFagAwIBAgIEOAOR7jANBgkqhkiG9w0BAQQFADCByTELMAkGA1UE" + "BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgYDVQQLFD93d3cuZW50" + "cnVzdC5uZXQvQ2xpZW50X0NBX0luZm8vQ1BTIGluY29ycC4gYnkgcmVmLiBs" + "aW1pdHMgbGlhYi4xJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExp" + "bWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENsaWVudCBDZXJ0aWZpY2F0" + "aW9uIEF1dGhvcml0eTAeFw05OTEwMTIxOTI0MzBaFw0xOTEwMTIxOTU0MzBa" + "MIHJMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxSDBGBgNV" + "BAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0FfSW5mby9DUFMgaW5jb3Jw" + "LiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UECxMcKGMpIDE5OTkgRW50" + "cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5uZXQgQ2xpZW50" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GL" + "ADCBhwKBgQDIOpleMRffrCdvkHvkGf9FozTC28GoT/Bo6oT9n3V5z8GKUZSv" + "x1cDR2SerYIbWtp/N3hHuzeYEpbOxhN979IMMFGpOZ5V+Pux5zDeg7K6PvHV" + "iTs7hbqqdCz+PzFur5GVbgbUB01LLFZHGARS2g4Qk79jkJvh34zmAqTmT173" + "iwIBA6OCAeAwggHcMBEGCWCGSAGG+EIBAQQEAwIABzCCASIGA1UdHwSCARkw" + "ggEVMIHkoIHhoIHepIHbMIHYMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50" + "cnVzdC5uZXQxSDBGBgNVBAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0Ff" + "SW5mby9DUFMgaW5jb3JwLiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UE" + "CxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50" + "cnVzdC5uZXQgQ2xpZW50IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYD" + "VQQDEwRDUkwxMCygKqAohiZodHRwOi8vd3d3LmVudHJ1c3QubmV0L0NSTC9D" + "bGllbnQxLmNybDArBgNVHRAEJDAigA8xOTk5MTAxMjE5MjQzMFqBDzIwMTkx" + "MDEyMTkyNDMwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUxPucKXuXzUyW" + "/O5bs8qZdIuV6kwwHQYDVR0OBBYEFMT7nCl7l81MlvzuW7PKmXSLlepMMAwG" + "A1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI" + "hvcNAQEEBQADgYEAP66K8ddmAwWePvrqHEa7pFuPeJoSSJn59DXeDDYHAmsQ" + "OokUgZwxpnyyQbJq5wcBoUv5nyU7lsqZwz6hURzzwy5E97BnRqqS5TvaHBkU" + "ODDV4qIxJS7x7EU47fgGWANzYrAQMY9Av2TgXD7FTx/aEkP/TOYGJqibGapE" + "PHayXOw="); byte[] nameCert = Base64.decode( "MIIEFjCCA3+gAwIBAgIEdS8BozANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJE"+ "RTERMA8GA1UEChQIREFURVYgZUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRQ0Eg"+ "REFURVYgRDAzIDE6UE4wIhgPMjAwMTA1MTAxMDIyNDhaGA8yMDA0MDUwOTEwMjI0"+ "OFowgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIFAZCYXllcm4xEjAQBgNVBAcUCU7I"+ "dXJuYmVyZzERMA8GA1UEChQIREFURVYgZUcxHTAbBgNVBAUTFDAwMDAwMDAwMDA4"+ "OTU3NDM2MDAxMR4wHAYDVQQDFBVEaWV0bWFyIFNlbmdlbmxlaXRuZXIwgaEwDQYJ"+ "KoZIhvcNAQEBBQADgY8AMIGLAoGBAJLI/LJLKaHoMk8fBECW/od8u5erZi6jI8Ug"+ "C0a/LZyQUO/R20vWJs6GrClQtXB+AtfiBSnyZOSYzOdfDI8yEKPEv8qSuUPpOHps"+ "uNCFdLZF1vavVYGEEWs2+y+uuPmg8q1oPRyRmUZ+x9HrDvCXJraaDfTEd9olmB/Z"+ "AuC/PqpjAgUAwAAAAaOCAcYwggHCMAwGA1UdEwEB/wQCMAAwDwYDVR0PAQH/BAUD"+ "AwdAADAxBgNVHSAEKjAoMCYGBSskCAEBMB0wGwYIKwYBBQUHAgEWD3d3dy56cy5k"+ "YXRldi5kZTApBgNVHREEIjAggR5kaWV0bWFyLnNlbmdlbmxlaXRuZXJAZGF0ZXYu"+ "ZGUwgYQGA1UdIwR9MHuhc6RxMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1"+ "bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0"+ "MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE6CBACm8LkwDgYHAoIG"+ "AQoMAAQDAQEAMEcGA1UdHwRAMD4wPKAUoBKGEHd3dy5jcmwuZGF0ZXYuZGWiJKQi"+ "MCAxCzAJBgNVBAYTAkRFMREwDwYDVQQKFAhEQVRFViBlRzAWBgUrJAgDBAQNMAsT"+ "A0VVUgIBBQIBATAdBgNVHQ4EFgQUfv6xFP0xk7027folhy+ziZvBJiwwLAYIKwYB"+ "BQUHAQEEIDAeMBwGCCsGAQUFBzABhhB3d3cuZGlyLmRhdGV2LmRlMA0GCSqGSIb3"+ "DQEBBQUAA4GBAEOVX6uQxbgtKzdgbTi6YLffMftFr2mmNwch7qzpM5gxcynzgVkg"+ "pnQcDNlm5AIbS6pO8jTCLfCd5TZ5biQksBErqmesIl3QD+VqtB+RNghxectZ3VEs"+ "nCUtcE7tJ8O14qwCb3TxS9dvIUFiVi4DjbxX46TdcTbTaK8/qr6AIf+l"); byte[] probSelfSignedCert = Base64.decode( "MIICxTCCAi6gAwIBAgIQAQAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQUFADBF" + "MScwJQYDVQQKEx4gRElSRUNUSU9OIEdFTkVSQUxFIERFUyBJTVBPVFMxGjAYBgNV" + "BAMTESBBQyBNSU5FRkkgQiBURVNUMB4XDTA0MDUwNzEyMDAwMFoXDTE0MDUwNzEy" + "MDAwMFowRTEnMCUGA1UEChMeIERJUkVDVElPTiBHRU5FUkFMRSBERVMgSU1QT1RT" + "MRowGAYDVQQDExEgQUMgTUlORUZJIEIgVEVTVDCBnzANBgkqhkiG9w0BAQEFAAOB" + "jQAwgYkCgYEAveoCUOAukZdcFCs2qJk76vSqEX0ZFzHqQ6faBPZWjwkgUNwZ6m6m" + "qWvvyq1cuxhoDvpfC6NXILETawYc6MNwwxsOtVVIjuXlcF17NMejljJafbPximEt" + "DQ4LcQeSp4K7FyFlIAMLyt3BQ77emGzU5fjFTvHSUNb3jblx0sV28c0CAwEAAaOB" + "tTCBsjAfBgNVHSMEGDAWgBSEJ4bLbvEQY8cYMAFKPFD1/fFXlzAdBgNVHQ4EFgQU" + "hCeGy27xEGPHGDABSjxQ9f3xV5cwDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIB" + "AQQEAwIBBjA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vYWRvbmlzLnBrNy5jZXJ0" + "cGx1cy5uZXQvZGdpLXRlc3QuY3JsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN" + "AQEFBQADgYEAmToHJWjd3+4zknfsP09H6uMbolHNGG0zTS2lrLKpzcmkQfjhQpT9" + "LUTBvfs1jdjo9fGmQLvOG+Sm51Rbjglb8bcikVI5gLbclOlvqLkm77otjl4U4Z2/" + "Y0vP14Aov3Sn3k+17EfReYUZI4liuB95ncobC4e8ZM++LjQcIM0s+Vs="); byte[] gost34102001base = Base64.decode( "MIIB1DCCAYECEEjpVKXP6Wn1yVz3VeeDQa8wCgYGKoUDAgIDBQAwbTEfMB0G" + "A1UEAwwWR29zdFIzNDEwLTIwMDEgZXhhbXBsZTESMBAGA1UECgwJQ3J5cHRv" + "UHJvMQswCQYDVQQGEwJSVTEpMCcGCSqGSIb3DQEJARYaR29zdFIzNDEwLTIw" + "MDFAZXhhbXBsZS5jb20wHhcNMDUwMjAzMTUxNjQ2WhcNMTUwMjAzMTUxNjQ2" + "WjBtMR8wHQYDVQQDDBZHb3N0UjM0MTAtMjAwMSBleGFtcGxlMRIwEAYDVQQK" + "DAlDcnlwdG9Qcm8xCzAJBgNVBAYTAlJVMSkwJwYJKoZIhvcNAQkBFhpHb3N0" + "UjM0MTAtMjAwMUBleGFtcGxlLmNvbTBjMBwGBiqFAwICEzASBgcqhQMCAiQA" + "BgcqhQMCAh4BA0MABECElWh1YAIaQHUIzROMMYks/eUFA3pDXPRtKw/nTzJ+" + "V4/rzBa5lYgD0Jp8ha4P5I3qprt+VsfLsN8PZrzK6hpgMAoGBiqFAwICAwUA" + "A0EAHw5dw/aw/OiNvHyOE65kvyo4Hp0sfz3csM6UUkp10VO247ofNJK3tsLb" + "HOLjUaqzefrlGb11WpHYrvWFg+FcLA=="); byte[] gost341094base = Base64.decode( "MIICDzCCAbwCEBcxKsIb0ghYvAQeUjfQdFAwCgYGKoUDAgIEBQAwaTEdMBsG" + "A1UEAwwUR29zdFIzNDEwLTk0IGV4YW1wbGUxEjAQBgNVBAoMCUNyeXB0b1By" + "bzELMAkGA1UEBhMCUlUxJzAlBgkqhkiG9w0BCQEWGEdvc3RSMzQxMC05NEBl" + "eGFtcGxlLmNvbTAeFw0wNTAyMDMxNTE2NTFaFw0xNTAyMDMxNTE2NTFaMGkx" + "HTAbBgNVBAMMFEdvc3RSMzQxMC05NCBleGFtcGxlMRIwEAYDVQQKDAlDcnlw" + "dG9Qcm8xCzAJBgNVBAYTAlJVMScwJQYJKoZIhvcNAQkBFhhHb3N0UjM0MTAt" + "OTRAZXhhbXBsZS5jb20wgaUwHAYGKoUDAgIUMBIGByqFAwICIAIGByqFAwIC" + "HgEDgYQABIGAu4Rm4XmeWzTYLIB/E6gZZnFX/oxUJSFHbzALJ3dGmMb7R1W+" + "t7Lzk2w5tUI3JoTiDRCKJA4fDEJNKzsRK6i/ZjkyXJSLwaj+G2MS9gklh8x1" + "G/TliYoJgmjTXHemD7aQEBON4z58nJHWrA0ILD54wbXCtrcaqCqLRYGTMjJ2" + "+nswCgYGKoUDAgIEBQADQQBxKNhOmjgz/i5CEgLOyKyz9pFGkDcaymsWYQWV" + "v7CZ0pTM8IzMzkUBW3GHsUjCFpanFZDfg2zuN+3kT+694n9B"); byte[] gost341094A = Base64.decode( "MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOZGVmYXVsdDM0MTAtOTQx" + "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1vbGExDDAKBgNVBAgT" + "A01FTDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx" + "MzExNTdaFw0wNjAzMjkxMzExNTdaMIGBMRcwFQYDVQQDEw5kZWZhdWx0MzQxMC05NDENMAsGA1UE" + "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLW9sYTEMMAoGA1UECBMDTUVMMQsw" + "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq" + "hQMCAiACBgcqhQMCAh4BA4GEAASBgIQACDLEuxSdRDGgdZxHmy30g/DUYkRxO9Mi/uSHX5NjvZ31" + "b7JMEMFqBtyhql1HC5xZfUwZ0aT3UnEFDfFjLP+Bf54gA+LPkQXw4SNNGOj+klnqgKlPvoqMGlwa" + "+hLPKbS561WpvB2XSTgbV+pqqXR3j6j30STmybelEV3RdS2Now8wDTALBgNVHQ8EBAMCB4AwCgYG" + "KoUDAgIEBQADQQBCFy7xWRXtNVXflKvDs0pBdBuPzjCMeZAXVxK8vUxsxxKu76d9CsvhgIFknFRi" + "wWTPiZenvNoJ4R1uzeX+vREm"); byte[] gost341094B = Base64.decode( "MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOcGFyYW0xLTM0MTAtOTQx" + "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNVBAgT" + "A01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx" + "MzEzNTZaFw0wNjAzMjkxMzEzNTZaMIGBMRcwFQYDVQQDEw5wYXJhbTEtMzQxMC05NDENMAsGA1UE" + "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMDTWVsMQsw" + "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq" + "hQMCAiADBgcqhQMCAh4BA4GEAASBgEa+AAcZmijWs1M9x5Pn9efE8D9ztG1NMoIt0/hNZNqln3+j" + "lMZjyqPt+kTLIjtmvz9BRDmIDk6FZz+4LhG2OTL7yGpWfrMxMRr56nxomTN9aLWRqbyWmn3brz9Y" + "AUD3ifnwjjIuW7UM84JNlDTOdxx0XRUfLQIPMCXe9cO02Xskow8wDTALBgNVHQ8EBAMCB4AwCgYG" + "KoUDAgIEBQADQQBzFcnuYc/639OTW+L5Ecjw9KxGr+dwex7lsS9S1BUgKa3m1d5c+cqI0B2XUFi5" + "4iaHHJG0dCyjtQYLJr0OZjRw"); byte[] gost34102001A = Base64.decode( "MIICCzCCAbigAwIBAgIBATAKBgYqhQMCAgMFADCBhDEaMBgGA1UEAxMRZGVmYXVsdC0zNDEwLTIw" + "MDExDTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNV" + "BAgTA01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAz" + "MjkxMzE4MzFaFw0wNjAzMjkxMzE4MzFaMIGEMRowGAYDVQQDExFkZWZhdWx0LTM0MTAtMjAwMTEN" + "MAsGA1UEChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMD" + "TWVsMQswCQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MGMwHAYGKoUDAgIT" + "MBIGByqFAwICIwEGByqFAwICHgEDQwAEQG/4c+ZWb10IpeHfmR+vKcbpmSOClJioYmCVgnojw0Xn" + "ned0KTg7TJreRUc+VX7vca4hLQaZ1o/TxVtfEApK/O6jDzANMAsGA1UdDwQEAwIHgDAKBgYqhQMC" + "AgMFAANBAN8y2b6HuIdkD3aWujpfQbS1VIA/7hro4vLgDhjgVmev/PLzFB8oTh3gKhExpDo82IEs" + "ZftGNsbbyp1NFg7zda0="); byte[] gostCA1 = Base64.decode( "MIIDNDCCAuGgAwIBAgIQZLcKDcWcQopF+jp4p9jylDAKBgYqhQMCAgQFADBm" + "MQswCQYDVQQGEwJSVTEPMA0GA1UEBxMGTW9zY293MRcwFQYDVQQKEw5PT08g" + "Q3J5cHRvLVBybzEUMBIGA1UECxMLRGV2ZWxvcG1lbnQxFzAVBgNVBAMTDkNQ" + "IENTUCBUZXN0IENBMB4XDTAyMDYwOTE1NTIyM1oXDTA5MDYwOTE1NTkyOVow" + "ZjELMAkGA1UEBhMCUlUxDzANBgNVBAcTBk1vc2NvdzEXMBUGA1UEChMOT09P" + "IENyeXB0by1Qcm8xFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5D" + "UCBDU1AgVGVzdCBDQTCBpTAcBgYqhQMCAhQwEgYHKoUDAgIgAgYHKoUDAgIe" + "AQOBhAAEgYAYglywKuz1nMc9UiBYOaulKy53jXnrqxZKbCCBSVaJ+aCKbsQm" + "glhRFrw6Mwu8Cdeabo/ojmea7UDMZd0U2xhZFRti5EQ7OP6YpqD0alllo7za" + "4dZNXdX+/ag6fOORSLFdMpVx5ganU0wHMPk67j+audnCPUj/plbeyccgcdcd" + "WaOCASIwggEeMAsGA1UdDwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud" + "DgQWBBTe840gTo4zt2twHilw3PD9wJaX0TCBygYDVR0fBIHCMIG/MDygOqA4" + "hjYtaHR0cDovL2ZpZXdhbGwvQ2VydEVucm9sbC9DUCUyMENTUCUyMFRlc3Ql" + "MjBDQSgzKS5jcmwwRKBCoECGPmh0dHA6Ly93d3cuY3J5cHRvcHJvLnJ1L0Nl" + "cnRFbnJvbGwvQ1AlMjBDU1AlMjBUZXN0JTIwQ0EoMykuY3JsMDmgN6A1hjMt" + "ZmlsZTovL1xcZmlld2FsbFxDZXJ0RW5yb2xsXENQIENTUCBUZXN0IENBKDMp" + "LmNybC8wEgYJKwYBBAGCNxUBBAUCAwMAAzAKBgYqhQMCAgQFAANBAIJi7ni7" + "9rwMR5rRGTFftt2k70GbqyUEfkZYOzrgdOoKiB4IIsIstyBX0/ne6GsL9Xan" + "G2IN96RB7KrowEHeW+k="); byte[] gostCA2 = Base64.decode( "MIIC2DCCAoWgAwIBAgIQe9ZCugm42pRKNcHD8466zTAKBgYqhQMCAgMFADB+" + "MRowGAYJKoZIhvcNAQkBFgtzYmFAZGlndC5ydTELMAkGA1UEBhMCUlUxDDAK" + "BgNVBAgTA01FTDEUMBIGA1UEBxMLWW9zaGthci1PbGExDTALBgNVBAoTBERp" + "Z3QxDzANBgNVBAsTBkNyeXB0bzEPMA0GA1UEAxMGc2JhLUNBMB4XDTA0MDgw" + "MzEzMzE1OVoXDTE0MDgwMzEzNDAxMVowfjEaMBgGCSqGSIb3DQEJARYLc2Jh" + "QGRpZ3QucnUxCzAJBgNVBAYTAlJVMQwwCgYDVQQIEwNNRUwxFDASBgNVBAcT" + "C1lvc2hrYXItT2xhMQ0wCwYDVQQKEwREaWd0MQ8wDQYDVQQLEwZDcnlwdG8x" + "DzANBgNVBAMTBnNiYS1DQTBjMBwGBiqFAwICEzASBgcqhQMCAiMBBgcqhQMC" + "Ah4BA0MABEDMSy10CuOH+i8QKG2UWA4XmCt6+BFrNTZQtS6bOalyDY8Lz+G7" + "HybyipE3PqdTB4OIKAAPsEEeZOCZd2UXGQm5o4HaMIHXMBMGCSsGAQQBgjcU" + "AgQGHgQAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud" + "DgQWBBRJJl3LcNMxkZI818STfoi3ng1xoDBxBgNVHR8EajBoMDGgL6Athito" + "dHRwOi8vc2JhLmRpZ3QubG9jYWwvQ2VydEVucm9sbC9zYmEtQ0EuY3JsMDOg" + "MaAvhi1maWxlOi8vXFxzYmEuZGlndC5sb2NhbFxDZXJ0RW5yb2xsXHNiYS1D" + "QS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwCgYGKoUDAgIDBQADQQA+BRJHbc/p" + "q8EYl6iJqXCuR+ozRmH7hPAP3c4KqYSC38TClCgBloLapx/3/WdatctFJW/L" + "mcTovpq088927shE"); private PublicKey dudPublicKey = new PublicKey() { public String getAlgorithm() { return null; } public String getFormat() { return null; } public byte[] getEncoded() { return null; } }; public String getName() { return "CertTest"; } public void checkCertificate( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); Certificate cert = fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkNameCertificate( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); if (!cert.getIssuerDN().toString().equals("C=DE,O=DATEV eG,0.2.262.1.10.7.20=1+CN=CA DATEV D03 1:PN")) { fail(id + " failed - name test."); } // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkKeyUsage( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); if (cert.getKeyUsage()[7]) { fail("error generating cert - key usage wrong."); } // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkSelfSignedCertificate( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); Certificate cert = fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); cert.verify(k); // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } /** * we generate a self signed certificate for the sake of testing - RSA */ public void checkCreation1() throws Exception { // a sample key pair. RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // set up the keys SecureRandom rand = new SecureRandom(); PrivateKey privKey; PublicKey pubKey; KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); privKey = fact.generatePrivate(privKeySpec); pubKey = fact.generatePublic(pubKeySpec); // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); Vector ord = new Vector(); Vector values = new Vector(); ord.addElement(X509Principal.C); ord.addElement(X509Principal.O); ord.addElement(X509Principal.L); ord.addElement(X509Principal.ST); ord.addElement(X509Principal.E); values.addElement("AU"); values.addElement("The Legion of the Bouncy Castle"); values.addElement("Melbourne"); values.addElement("Victoria"); values.addElement("feedback-crypto@bouncycastle.org"); // extensions // create the certificate - version 3 - without extensions X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); X509Certificate cert = certGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); Set dummySet = cert.getNonCriticalExtensionOIDs(); dummySet = cert.getNonCriticalExtensionOIDs(); // create the certificate - version 3 - with extensions certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); certGen.addExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.encipherOnly)); certGen.addExtension("2.5.29.37", true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); certGen.addExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); cert = certGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream sbIn = new ByteArrayInputStream(cert.getEncoded()); ASN1InputStream sdIn = new ASN1InputStream(sbIn); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)certFact.generateCertificate(bIn); if (!cert.getKeyUsage()[7]) { fail("error generating cert - key usage wrong."); } List l = cert.getExtendedKeyUsage(); if (!l.get(0).equals(KeyPurposeId.anyExtendedKeyUsage.getId())) { fail("failed extended key usage test"); } Collection c = cert.getSubjectAlternativeNames(); Iterator it = c.iterator(); while (it.hasNext()) { List gn = (List)it.next(); if (!gn.get(1).equals("test@test.test")) { fail("failed subject alternative names test"); } } // System.out.println(cert); // create the certificate - version 1 X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); certGen1.setSerialNumber(BigInteger.valueOf(1)); certGen1.setIssuerDN(new X509Principal(ord, attrs)); certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen1.setSubjectDN(new X509Principal(ord, values)); certGen1.setPublicKey(pubKey); certGen1.setSignatureAlgorithm("MD5WithRSAEncryption"); cert = certGen1.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); bIn = new ByteArrayInputStream(cert.getEncoded()); certFact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)certFact.generateCertificate(bIn); // System.out.println(cert); if (!cert.getIssuerDN().equals(cert.getSubjectDN())) { fail("name comparison fails"); } } /** * we generate a self signed certificate for the sake of testing - DSA */ public void checkCreation2() { // set up the keys PrivateKey privKey; PublicKey pubKey; try { KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); privKey = p.getPrivate(); pubKey = p.getPublic(); } catch (Exception e) { fail("error setting up keys - " + e.toString()); return; } // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); // extensions // create the certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("SHA1withDSA"); try { X509Certificate cert = certGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); // System.out.println(cert); } catch (Exception e) { fail("error setting generating cert - " + e.toString()); } // create the certificate - version 1 X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); certGen1.setSerialNumber(BigInteger.valueOf(1)); certGen1.setIssuerDN(new X509Principal(attrs)); certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen1.setSubjectDN(new X509Principal(attrs)); certGen1.setPublicKey(pubKey); certGen1.setSignatureAlgorithm("SHA1withDSA"); try { X509Certificate cert = certGen1.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); //System.out.println(cert); } catch (Exception e) { fail("error setting generating cert - " + e.toString()); } // exception test try { certGen.setPublicKey(dudPublicKey); fail("key without encoding not detected in v1"); } catch (IllegalArgumentException e) { // expected } } /** * we generate a self signed certificate for the sake of testing - ECDSA */ public void checkCreation3() { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), spec); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), spec); // set up the keys PrivateKey privKey; PublicKey pubKey; try { KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC"); privKey = fact.generatePrivate(privKeySpec); pubKey = fact.generatePublic(pubKeySpec); } catch (Exception e) { fail("error setting up keys - " + e.toString()); return; } // distinguished name table. Hashtable attrs = new Hashtable(); Vector order = new Vector(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); order.addElement(X509Principal.C); order.addElement(X509Principal.O); order.addElement(X509Principal.L); order.addElement(X509Principal.ST); order.addElement(X509Principal.E); // toString test X509Principal p = new X509Principal(order, attrs); String s = p.toString(); if (!s.equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,E=feedback-crypto@bouncycastle.org")) { fail("ordered X509Principal test failed - s = " + s + "."); } p = new X509Principal(attrs); s = p.toString(); // we need two of these as the hash code for strings changed... if (!s.equals("O=The Legion of the Bouncy Castle,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU") && !s.equals("ST=Victoria,L=Melbourne,C=AU,E=feedback-crypto@bouncycastle.org,O=The Legion of the Bouncy Castle")) { fail("unordered X509Principal test failed."); } // create the certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(order, attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(order, attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("ECDSAwithSHA1"); try { X509Certificate cert = certGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); // try with point compression turned off ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); certGen.setPublicKey(pubKey); cert = certGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); bIn = new ByteArrayInputStream(cert.getEncoded()); fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); // System.out.println(cert); } catch (Exception e) { fail("error setting generating cert - " + e.toString()); } X509Principal pr = new X509Principal("O=\"The Bouncy Castle, The Legion of\",E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU"); if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU")) { fail("string based X509Principal test failed."); } pr = new X509Principal("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU"); if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU")) { fail("string based X509Principal test failed."); } } private void checkCRL( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CRL cert = fact.generateCRL(bIn); // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkCRLCreation() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); Date now = new Date(); KeyPair pair = kpGen.generateKeyPair(); crlGen.setIssuerDN(new X500Principal("CN=Test CA")); crlGen.setThisUpdate(now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); crlGen.addCRLEntry(BigInteger.ONE, now, CRLReason.privilegeWithdrawn); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); X509CRL crl = crlGen.generateX509CRL(pair.getPrivate(), "BC"); if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) { fail("failed CRL issuer test"); } byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (authExt == null) { fail("failed to find CRL extension"); } AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt); X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE); if (entry == null) { fail("failed to find CRL entry"); } if (!entry.getSerialNumber().equals(BigInteger.ONE)) { fail("CRL cert serial number does not match"); } if (!entry.hasExtensions()) { fail("CRL entry extension not found"); } byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId()); if (ext != null) { DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong"); } } else { fail("CRL entry reasonCode not found"); } } /** * we generate a self signed certificate for the sake of testing - GOST3410 */ public void checkCreation4() throws Exception { // set up the keys PrivateKey privKey; PublicKey pubKey; KeyPairGenerator g = KeyPairGenerator.getInstance("GOST3410", "BC"); GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A"); g.initialize(gost3410P, new SecureRandom()); KeyPair p = g.generateKeyPair(); privKey = p.getPrivate(); pubKey = p.getPublic(); // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); // extensions // create the certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("GOST3411withGOST3410"); X509Certificate cert = certGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); // check verifies in general cert.verify(pubKey); // check verifies with contained key cert.verify(cert.getPublicKey()); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); //System.out.println(cert); //check getEncoded() byte[] bytesch = cert.getEncoded(); } public void checkCreation5() throws Exception { // a sample key pair. RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // set up the keys SecureRandom rand = new SecureRandom(); PrivateKey privKey; PublicKey pubKey; KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); privKey = fact.generatePrivate(privKeySpec); pubKey = fact.generatePublic(pubKeySpec); // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); Vector ord = new Vector(); Vector values = new Vector(); ord.addElement(X509Principal.C); ord.addElement(X509Principal.O); ord.addElement(X509Principal.L); ord.addElement(X509Principal.ST); ord.addElement(X509Principal.E); values.addElement("AU"); values.addElement("The Legion of the Bouncy Castle"); values.addElement("Melbourne"); values.addElement("Victoria"); values.addElement("feedback-crypto@bouncycastle.org"); // create base certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); certGen.addExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.encipherOnly)); certGen.addExtension("2.5.29.37", true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); certGen.addExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509Certificate baseCert = certGen.generateX509Certificate(privKey); // copy certificate certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); certGen.copyAndAddExtension(new DERObjectIdentifier("2.5.29.15"), true, baseCert); certGen.copyAndAddExtension("2.5.29.37", false, baseCert); X509Certificate cert = certGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); if (!areEqual(baseCert.getExtensionValue("2.5.29.15"), cert.getExtensionValue("2.5.29.15"))) { fail("2.5.29.15 differs"); } if (!areEqual(baseCert.getExtensionValue("2.5.29.37"), cert.getExtensionValue("2.5.29.37"))) { fail("2.5.29.37 differs"); } // exception test try { certGen.copyAndAddExtension("2.5.99.99", true, baseCert); fail("exception not thrown on dud extension copy"); } catch (CertificateParsingException e) { // expected } try { certGen.setPublicKey(dudPublicKey); certGen.generateX509Certificate(privKey); fail("key without encoding not detected in v3"); } catch (IllegalArgumentException e) { // expected } } public void performTest() throws Exception { checkCertificate(1, cert1); checkCertificate(2, cert2); checkCertificate(4, cert4); checkCertificate(5, cert5); checkCertificate(6, oldEcdsa); checkCertificate(7, cert7); checkKeyUsage(8, keyUsage); checkSelfSignedCertificate(9, uncompressedPtEC); checkNameCertificate(10, nameCert); checkSelfSignedCertificate(11, probSelfSignedCert); checkSelfSignedCertificate(12, gostCA1); checkSelfSignedCertificate(13, gostCA2); checkSelfSignedCertificate(14, gost341094base); checkSelfSignedCertificate(15, gost34102001base); checkSelfSignedCertificate(16, gost341094A); checkSelfSignedCertificate(17, gost341094B); checkSelfSignedCertificate(17, gost34102001A); checkCRL(1, crl1); checkCreation1(); checkCreation2(); checkCreation3(); checkCreation4(); checkCreation5(); checkCRLCreation(); } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new CertTest()); } }
package com.monolith.api; import com.monolith.engine.MeshManager; /** * Provides important engine features. Instance of this class is passed everywhere around the * engine. * <p/> * Contains global application functionality, such as scene changing and * other more specific objects containing the specific data or functionality. */ public abstract class Application { public abstract Renderer getRenderer(); public abstract TouchInput getTouchInput(); public abstract MeshManager getMeshManager(); public abstract Messenger getMessenger(); public abstract CollisionSystem getCollisionSystem(); public abstract Time getTime(); public abstract Debug getDebug(); /** * Keep in mind that this method can return different instance in different frames. * And therefore result of this method should not be cached. * This can happen due to change in screen orientation. * * @return Instance of Display relevant for current frame. */ public abstract Display getDisplay(); public abstract void changeScene(String newSceneName); public abstract String getCurrentSceneName(); }
package org.jscep.client; import java.net.URL; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.security.auth.x500.X500Principal; import org.jscep.client.Client; import org.jscep.x509.X509Util; import org.junit.Before; import org.junit.BeforeClass; //@Ignore public abstract class AbstractClientTest { protected Client client; protected KeyPair keyPair; protected X509Certificate identity; protected char[] password = "INBOUND_TLSuscl99".toCharArray(); @Before public void setUp() throws Exception { keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); identity = X509Util.createEphemeralCertificate(new X500Principal("CN=example.org"), keyPair); Client.Builder builder = new Client.Builder(); builder.url(new URL("https://engtest66-2.eu.ubiquity.net/ejbca/publicweb/apply/scep/pkiclient.exe")); builder.caFingerprint(new byte[] {-93, -44, 23, 25, -106, 116, 80, -113, 36, 23, 76, -89, -36, -18, 89, -59}, "MD5"); builder.identity(identity, keyPair); builder.caIdentifier("foo"); client = builder.build(); } /** * Removes any trust checking for SSL connections. * * @throws Exception if any error occurs. */ @BeforeClass public static void setUpTrustManager() throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] {new X509TrustManager() { public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }}, null); HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory()); } }
package org.jetel.component; import java.io.IOException; import org.jetel.data.Defaults; import org.jetel.exception.AttributeNotFoundException; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPortDirect; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.graph.runtime.tracker.BasicComponentTokenTracker; import org.jetel.graph.runtime.tracker.ComponentTokenTracker; import org.jetel.util.SynchronizeUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.property.ComponentXMLAttributes; import org.w3c.dom.Element; /** * <h3>Simple Gather Component</h3> * * <!-- All records from all input ports are gathered and copied onto output port [0] --> * * <table border="1"> * <th>Component:</th> * <tr> * <td> * <h4><i>Name:</i></h4></td> * <td>Simple Gather</td> * </tr> * <tr> * <td> * <h4><i>Category:</i></h4></td> * <td></td> * </tr> * <tr> * <td> * <h4><i>Description:</i></h4></td> * <td>All records from all input ports are gathered and copied onto output port [0].<br> * It goes port by port (waiting/blocked) if there is currently no data on port.<br> * Implements inverse RoundRobin.<br> * </td> * </tr> * <tr> * <td> * <h4><i>Inputs:</i></h4></td> * <td>At least one connected output port.</td> * </tr> * <tr> * <td> * <h4><i>Outputs:</i></h4></td> * <td>[0]- output records (gathered)</td> * </tr> * <tr> * <td> * <h4><i>Comment:</i></h4></td> * <td></td> * </tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr> * <td><b>type</b></td> * <td>"SIMPLE_GATHER"</td> * </tr> * <tr> * <td><b>id</b></td> * <td>component identification</td> * </tr> * </table> * * @author dpavlis * @since April 4, 2002 */ public class SimpleGather extends Node { /** Description of the Field */ public final static String COMPONENT_TYPE = "SIMPLE_GATHER"; /** * how many empty loops till thread wait() is called */ private final static int NUM_EMPTY_LOOPS_TRESHOLD = 5; /** * how many millis to wait if we reached the specified number of empty loops (when no data has been read). */ private final static int EMPTY_LOOPS_WAIT = 20; public SimpleGather(String id, TransformationGraph graph) { super(id, graph); } @Override public Result execute() throws Exception { InputPortDirect inPort; /* * we need to keep track of all input ports - it they contain data or signalized that they are empty. */ int numActive; int emptyLoopCounter = 0; /* * we need to keep track of all input ports - it they contain data or signalized that they are empty. */ int readFromPort; boolean[] isEOF = new boolean[getInPorts().size()]; for (int i = 0; i < isEOF.length; i++) { isEOF[i] = false; } InputPortDirect inputPorts[] = (InputPortDirect[]) getInPorts().toArray(new InputPortDirect[0]); numActive = inputPorts.length;// counter of still active ports - those without EOF status // the metadata is taken from output port definition CloverBuffer recordBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE); readFromPort = 0; inPort = inputPorts[readFromPort]; int lastReadPort = 0; while (runIt && numActive > 0) { if (!isEOF[readFromPort] && (inPort.hasData() || numActive == 1)) { emptyLoopCounter = 0; if (inPort.readRecordDirect(recordBuffer)) { writeRecordToOutputPorts(recordBuffer); lastReadPort = readFromPort; } else { isEOF[readFromPort] = true; numActive } SynchronizeUtils.cloverYield(); } else { readFromPort = (++readFromPort) % (inputPorts.length); inPort = inputPorts[readFromPort]; // have we reached the maximum empty loops count ? if (lastReadPort == readFromPort) { if (emptyLoopCounter > NUM_EMPTY_LOOPS_TRESHOLD) { Thread.sleep(getSleepTime()); emptyLoopCounter } else { emptyLoopCounter++; } } } } return runIt ? Result.FINISHED_OK : Result.ABORTED; } protected void writeRecordToOutputPorts(CloverBuffer recordBuffer) throws IOException, InterruptedException { writeRecordBroadcastDirect(recordBuffer); } protected long getSleepTime() { return EMPTY_LOOPS_WAIT; } public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException, AttributeNotFoundException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); return new SimpleGather(xattribs.getString(XML_ID_ATTRIBUTE), graph); } /** Description of the Method */ @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if (!checkInputPorts(status, 1, Integer.MAX_VALUE) || !checkOutputPorts(status, 1, Integer.MAX_VALUE)) { return status; } checkMetadata(status, getInMetadata(), getOutMetadata(), false); return status; } @Override public String getType() { return COMPONENT_TYPE; } @Override protected ComponentTokenTracker createComponentTokenTracker() { return new BasicComponentTokenTracker(this); } }
import java.io.File; import java.sql.Connection; import java.sql.Statement; import java.sql.SQLException; import java.util.Collection; import java.util.Random; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.entitymanager.EntityManager; import edu.common.dynamicextensions.entitymanager.EntityManagerInterface; public class MaskUsingDEMetatdata { private static int randomNumber; public static void main(String[] args) { MaskUsingDEMetatdata mask=new MaskUsingDEMetatdata(); mask.maskIdentifiedData(); } public void maskIdentifiedData() { Random generator = new Random(); while(randomNumber==0) { randomNumber=generator.nextInt(200); } try { EntityManagerInterface entityManager = EntityManager.getInstance(); Collection<EntityInterface> entities = entityManager.getAllEntities(); int totalNoOfEntities = entities.size(); System.out.println("No Of entities:"+totalNoOfEntities); Configuration cfg = new Configuration(); File file = new File(".//classes//hibernate.cfg.xml"); File file1 = new File(file.getAbsolutePath()); System.out.println(file.getAbsolutePath()); cfg.configure(file1); SessionFactory sf = cfg.buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); for(EntityInterface entity: entities) { Collection<AttributeInterface> attributeCollection = entity.getAttributeCollection(); for (AttributeInterface attribute: attributeCollection) { if(attribute.getIsIdentified()!=null && attribute.getIsIdentified()==true && attribute.getAttributeTypeInformation().getDataType().equalsIgnoreCase("String")) { maskString(attribute.getColumnProperties().getName(),entity.getTableProperties().getName(), session); } else if(attribute.getAttributeTypeInformation().getDataType().equalsIgnoreCase("Date")) { maskDate(attribute.getColumnProperties().getName(),entity.getTableProperties().getName(), session); } } } // sql String to update ParticipantMedicalIdentifier table String sqlString="truncate table CATISSUE_PART_MEDICAL_ID"; executeQuery(sqlString, session); // sql String to delete ReportQueue table sqlString="truncate table CATISSUE_REPORT_QUEUE"; executeQuery(sqlString, session); // sql String to delete ReportQueue table sqlString="truncate table CATISSUE_REPORT_PARTICIP_REL"; executeQuery(sqlString, session); maskReportText(session); tx.commit(); session.close(); } catch (Exception e) { System.out.println(e); } } private void maskDate(String columnName, String tableName, Session session) throws SQLException { String sqlString=null; String dbType=session.connection().getMetaData().getDatabaseProductName(); if(dbType.equalsIgnoreCase("oracle")) { sqlString="update "+tableName+" set "+columnName+"=add_months("+columnName+", -"+randomNumber+")"; } if(dbType.equalsIgnoreCase("mysql")) { sqlString="update "+tableName+" set "+columnName+"=date_add("+columnName+", INTERVAL -"+randomNumber+" MONTH);"; } executeQuery(sqlString, session); } private void maskString(String columnName, String tableName, Session session) { String sqlString="update "+tableName+" set "+columnName+"=null"; executeQuery(sqlString, session); } private void maskReportText(Session session) throws SQLException { String sqlString=null; String dbType=session.connection().getMetaData().getDatabaseProductName(); if(dbType.equalsIgnoreCase("oracle")) { sqlString="update catissue_report_content set report_data=NULL where identifier in(select a.identifier from catissue_report_content a join catissue_report_textcontent b on a.identifier=b.identifier join catissue_pathology_report c on c.identifier=b.report_id where c.REPORT_STATUS in ('DEIDENTIFIED','DEID_PROCESS_FAILED','PENDING_FOR_DEID'))"; } if(dbType.equalsIgnoreCase("mysql")) { sqlString="update CATISSUE_REPORT_CONTENT as rc, CATISSUE_REPORT_TEXTCONTENT as rt, CATISSUE_PATHOLOGY_REPORT as pr set rc.REPORT_DATA=NULL where pr.IDENTIFIER=rt.report_id and rt.IDENTIFIER=rc.IDENTIFIER and pr.REPORT_STATUS in ('DEIDENTIFIED','DEID_PROCESS_FAILED','PENDING_FOR_DEID')"; } executeQuery(sqlString, session); } private void executeQuery(String sqlString, Session session) { try { System.out.println(sqlString); Connection con=session.connection(); Statement stmt=con.createStatement(); stmt.execute(sqlString); } catch (Exception e) { System.out.println("Error in maskString "); e.printStackTrace(); } } }
package com.mindoo.domino.jna; import java.text.Collator; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import com.mindoo.domino.jna.CollectionDataCache.CacheState; import com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action; import com.mindoo.domino.jna.NotesViewEntryData.CacheableViewEntryData; import com.mindoo.domino.jna.constants.FTSearch; import com.mindoo.domino.jna.constants.Find; import com.mindoo.domino.jna.constants.Navigate; import com.mindoo.domino.jna.constants.ReadMask; import com.mindoo.domino.jna.constants.UpdateCollectionFilters; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.gc.IRecyclableNotesObject; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.internal.NotesCAPI; import com.mindoo.domino.jna.internal.NotesJNAContext; import com.mindoo.domino.jna.internal.NotesLookupResultBufferDecoder; import com.mindoo.domino.jna.internal.NotesSearchKeyEncoder; import com.mindoo.domino.jna.queries.condition.Selection; import com.mindoo.domino.jna.structs.NotesCollectionPosition; import com.mindoo.domino.jna.structs.NotesTimeDate; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; import lotus.domino.Database; import lotus.domino.View; import lotus.domino.ViewColumn; import lotus.notes.addins.changeman.functions.DominoConsoleCommand; /** * A collection represents a list of Notes, comparable to the {@link View} object * * @author Karsten Lehmann */ public class NotesCollection implements IRecyclableNotesObject { private int m_hDB32; private long m_hDB64; private int m_hCollection32; private long m_hCollection64; private String m_name; private NotesIDTable m_collapsedList; private NotesIDTable m_selectedList; private String m_viewUNID; private boolean m_noRecycle; private int m_viewNoteId; private IntByReference m_activeFTSearchHandle32; private LongByReference m_activeFTSearchHandle64; private NotesIDTable m_unreadTable; private String m_asUserCanonical; private NotesDatabase m_parentDb; private boolean m_autoUpdate; private CollationInfo m_collationInfo; private Map<String, Integer> m_columnIndices; private Map<Integer, String> m_columnNamesByIndex; private Map<Integer, Boolean> m_columnIsCategoryByIndex; /** * Creates a new instance, 32 bit mode * * @param parentDb parent database * @param hCollection collection handle * @param name collection name * @param viewNoteId view note id * @param viewUNID view UNID * @param collapsedList id table for the collapsed list * @param selectedList id table for the selected list * @param unreadTable id table for the unread list * @param asUserCanonical user used to read the collection data */ public NotesCollection(NotesDatabase parentDb, int hCollection, String name, int viewNoteId, String viewUNID, NotesIDTable collapsedList, NotesIDTable selectedList, NotesIDTable unreadTable, String asUserCanonical) { if (NotesJNAContext.is64Bit()) throw new IllegalStateException("Constructor is 32bit only"); m_asUserCanonical = asUserCanonical; m_parentDb = parentDb; m_hDB32 = parentDb.getHandle32(); m_hCollection32 = hCollection; m_name = name; m_viewNoteId = viewNoteId; m_viewUNID = viewUNID; m_collapsedList = collapsedList; m_selectedList = selectedList; m_unreadTable = unreadTable; m_autoUpdate = true; } /** * Creates a new instance, 64 bit mode * * @param parentDb parent database * @param hCollection collection handle * @param name collection name * @param viewNoteId view note id * @param viewUNID view UNID * @param collapsedList id table for the collapsed list * @param selectedList id table for the selected list * @param unreadTable id table for the unread list * @param asUserCanonical user used to read the collection data */ public NotesCollection(NotesDatabase parentDb, long hCollection, String name, int viewNoteId, String viewUNID, NotesIDTable collapsedList, NotesIDTable selectedList, NotesIDTable unreadTable, String asUserCanonical) { if (!NotesJNAContext.is64Bit()) throw new IllegalStateException("Constructor is 64bit only"); m_asUserCanonical = asUserCanonical; m_parentDb = parentDb; m_hDB64 = parentDb.getHandle64(); m_hCollection64 = hCollection; m_name = name; m_viewNoteId = viewNoteId; m_viewUNID = viewUNID; m_collapsedList = collapsedList; m_selectedList = selectedList; m_unreadTable = unreadTable; m_autoUpdate = true; } /** * Returns the name of the collection * * @return name */ public String getName() { return m_name; } /** * Returns the parent database of this collation * * @return database */ public NotesDatabase getParent() { return m_parentDb; } /** * Method to check whether a collection column contains a category * * @param columnName programmatic column name * @return true if category, false otherwise */ public boolean isCategoryColumn(String columnName) { if (m_columnIsCategoryByIndex==null) { scanColumns(); } int colValuesIndex = getColumnValuesIndex(columnName); Boolean isCategory = m_columnIsCategoryByIndex.get(colValuesIndex); return Boolean.TRUE.equals(isCategory); } /** * Returns the column values index for the specified programmatic column name * * @param columnName column name * @return index or -1 for unknown columns; returns 65535 for static column values that are not returned as column values */ public int getColumnValuesIndex(String columnName) { if (m_columnIndices==null) { scanColumns(); } Integer idx = m_columnIndices.get(columnName.toLowerCase()); return idx==null ? -1 : idx.intValue(); } /** * Returns whether the view automatically handles view index updates while reading from the view.<br> * <br> * This flag is used by the methods<br> * <br> * <ul> * <li>{@link #getAllEntries(String, int, EnumSet, int, EnumSet, ViewLookupCallback)}</li> * <li>{@link #getAllEntriesByKey(EnumSet, EnumSet, ViewLookupCallback, Object...)}</li> * <li>{@link #getAllIds(Navigate)}</li> * <li>{@link #getAllIdsByKey(EnumSet, Object...)}</li> * </ul> * @return true if auto update */ public boolean isAutoUpdate() { return m_autoUpdate; } /** * Changes the auto update flag, which indicates whether the view automatically handles view index * updates while reading from the view.<br> * <br> * This flag is used by the methods<br> * <br> * <ul> * <li>{@link #getAllEntries(String, int, EnumSet, int, EnumSet, ViewLookupCallback)}</li> * <li>{@link #getAllEntriesByKey(EnumSet, EnumSet, ViewLookupCallback, Object...)}</li> * <li>{@link #getAllIds(Navigate)}</li> * <li>{@link #getAllIdsByKey(EnumSet, Object...)}</li> * </ul> * @param update true to activate auto update */ public void setAutoUpdate(boolean update) { m_autoUpdate = update; } /** * Returns the index modified sequence number that can be used to track view changes. * The method calls {@link #getLastModifiedTime()} and returns part of the result (Innards[0]). * We found out by testing that this value is the same that NIFFindByKeyExtended2 returns. * * @return index modified sequence number */ public int getIndexModifiedSequenceNo() { NotesTimeDate ndtModified = getLastModifiedTime(); return ndtModified.Innards[0]; } /** * Each time the number of documents in a collection is modified, a sequence number * is incremented. This function will return the modification sequence number, which * may then be compared to a previous value (also obtained by calling * NIFGetLastModifiedTime()) to determine whether or not the number of documents in the * collection has been changed.<br> * <br>Note that the TIMEDATE value returned by this function is not an actual time. * * @return time date */ public NotesTimeDate getLastModifiedTime() { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); NotesTimeDate retLastModifiedTime = new NotesTimeDate(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NIFGetLastModifiedTime(m_hCollection64, retLastModifiedTime); } else { notesAPI.b32_NIFGetLastModifiedTime(m_hCollection32, retLastModifiedTime); } return retLastModifiedTime; } /** * This function adds the document(s) specified in an ID Table to a folder. * * @param idTable id table */ public void addToFolder(NotesIDTable idTable) { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_FolderDocAdd(m_hDB64, 0, m_viewNoteId, idTable.getHandle64(), 0); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_FolderDocAdd(m_hDB32, 0, m_viewNoteId, idTable.getHandle32(), 0); NotesErrorUtils.checkResult(result); } } /** * This function adds the document(s) specified as note id set to a folder * * @param noteIds ids of notes to add */ public void addToFolder(Set<Integer> noteIds) { NotesIDTable idTable = new NotesIDTable(); try { idTable.addNotes(noteIds); addToFolder(idTable); } finally { idTable.recycle(); } } /** * This function removes the document(s) specified in an ID Table from a folder. * * @param idTable id table */ public void removeFromFolder(NotesIDTable idTable) { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_FolderDocRemove(m_hDB64, 0, m_viewNoteId, idTable.getHandle64(), 0); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_FolderDocRemove(m_hDB32, 0, m_viewNoteId, idTable.getHandle32(), 0); NotesErrorUtils.checkResult(result); } } /** * This function removes the document(s) specified as note id set from a folder. * * @param noteIds ids of notes to remove */ public void removeFromFolder(Set<Integer> noteIds) { NotesIDTable idTable = new NotesIDTable(); try { idTable.addNotes(noteIds); removeFromFolder(idTable); } finally { idTable.recycle(); } } /** * This function removes all documents from a specified folder.<br> * <br> * Subfolders and documents within the subfolders are not removed. */ public void removeAllFromFolder() { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_FolderDocRemoveAll(m_hDB64, 0, m_viewNoteId, 0); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_FolderDocRemoveAll(m_hDB32, 0, m_viewNoteId, 0); NotesErrorUtils.checkResult(result); } } /** * This function moves the specified folder under a given parent folder.<br> * <br> * If the parent folder is a shared folder, then the child folder must be a shared folder.<br> * If the parent folder is a private folder, then the child folder must be a private folder. * * @param newParentFolder parent folder */ public void moveFolder(NotesCollection newParentFolder) { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_FolderMove(m_hDB64, 0, m_viewNoteId, 0, newParentFolder.getNoteId(), 0); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_FolderMove(m_hDB32, 0, m_viewNoteId, 0, newParentFolder.getNoteId(), 0); NotesErrorUtils.checkResult(result); } } /** * This function renames the specified folder and its subfolders. * * @param name new folder name */ public void renameFolder(String name) { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory pszName = NotesStringUtils.toLMBCS(name, false); if (pszName.size() > NotesCAPI.DESIGN_FOLDER_MAX_NAME) { throw new IllegalArgumentException("Folder name too long (max "+NotesCAPI.DESIGN_FOLDER_MAX_NAME+" bytes, found "+pszName.size()+" bytes)"); } if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_FolderRename(m_hDB64, 0, m_viewNoteId, pszName, (short) pszName.size(), 0); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_FolderRename(m_hDB32, 0, m_viewNoteId, pszName, (short) pszName.size(), 0); NotesErrorUtils.checkResult(result); } } /** * This function returns the number of entries in the specified folder's index.<br> * <br> * This is the number of documents plus the number of cateogories (if any) in the folder.<br> * <br> * Subfolders and documents in subfolders are not included in the count. * * @return count */ public long getFolderDocCount() { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { LongByReference pdwNumDocs = new LongByReference(); short result = notesAPI.b64_FolderDocCount(m_hDB64, 0, m_viewNoteId, 0, pdwNumDocs); NotesErrorUtils.checkResult(result); return pdwNumDocs.getValue(); } else { LongByReference pdwNumDocs = new LongByReference(); short result = notesAPI.b32_FolderDocCount(m_hDB32, 0, m_viewNoteId, 0, pdwNumDocs); NotesErrorUtils.checkResult(result); return pdwNumDocs.getValue(); } } /** * Returns an id table of the folder content * * @param validateIds If set, return only "validated" noteIDs * @return id table */ public NotesIDTable getIDTableForFolder(boolean validateIds) { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { LongByReference hTable = new LongByReference(); short result = notesAPI.b64_NSFFolderGetIDTable(m_hDB64, m_hDB64, m_viewNoteId, validateIds ? NotesCAPI.DB_GETIDTABLE_VALIDATE : 0, hTable); NotesErrorUtils.checkResult(result); return new NotesIDTable(hTable.getValue()); } else { IntByReference hTable = new IntByReference(); short result = notesAPI.b32_NSFFolderGetIDTable(m_hDB32, m_hDB32, m_viewNoteId, validateIds ? NotesCAPI.DB_GETIDTABLE_VALIDATE : 0, hTable); NotesErrorUtils.checkResult(result); return new NotesIDTable(hTable.getValue()); } } /** * Method to check whether a skip or return navigator returns view data from last to first entry * * @param nav navigator mode * @return true if descending */ public static boolean isDescendingNav(EnumSet<Navigate> nav) { boolean descending = nav.contains(Navigate.PREV) || nav.contains(Navigate.PREV_CATEGORY) || nav.contains(Navigate.PREV_EXP_NONCATEGORY) || nav.contains(Navigate.PREV_EXPANDED) || nav.contains(Navigate.PREV_EXPANDED_CATEGORY) || nav.contains(Navigate.PREV_EXPANDED_SELECTED) || nav.contains(Navigate.PREV_EXPANDED_UNREAD) || nav.contains(Navigate.PREV_HIT) || nav.contains(Navigate.PREV_MAIN) || nav.contains(Navigate.PREV_NONCATEGORY) || nav.contains(Navigate.PREV_PARENT) || nav.contains(Navigate.PREV_PEER) || nav.contains(Navigate.PREV_SELECTED) || nav.contains(Navigate.PREV_SELECTED_HIT) || nav.contains(Navigate.PREV_SELECTED_MAIN) || nav.contains(Navigate.PREV_UNREAD) || nav.contains(Navigate.PREV_UNREAD_HIT) || nav.contains(Navigate.PREV_UNREAD_MAIN) || nav.contains(Navigate.PARENT); return descending; } /** * Method to reverse the traversal order, e.g. from {@link Navigate#NEXT} to * {@link Navigate#PREV}. * * @param nav nav constant * @return reversed constant */ public static Navigate reverseNav(Navigate nav) { switch (nav) { case PARENT: return Navigate.CHILD; case CHILD: return Navigate.PARENT; case NEXT_PEER: return Navigate.PREV_PEER; case PREV_PEER: return Navigate.NEXT_PEER; case FIRST_PEER: return Navigate.LAST_PEER; case LAST_PEER: return Navigate.FIRST_PEER; case NEXT_MAIN: return Navigate.PREV_MAIN; case PREV_MAIN: return Navigate.NEXT_MAIN; case NEXT_PARENT: return Navigate.PREV_PARENT; case PREV_PARENT: return Navigate.NEXT_PARENT; case NEXT: return Navigate.PREV; case PREV: return Navigate.NEXT; case NEXT_UNREAD: return Navigate.PREV_UNREAD; case NEXT_UNREAD_MAIN: return Navigate.PREV_UNREAD_MAIN; case PREV_UNREAD_MAIN: return Navigate.NEXT_UNREAD_MAIN; case PREV_UNREAD: return Navigate.NEXT_UNREAD; case NEXT_SELECTED: return Navigate.PREV_SELECTED; case PREV_SELECTED: return Navigate.NEXT_SELECTED; case NEXT_SELECTED_MAIN: return Navigate.PREV_SELECTED_MAIN; case PREV_SELECTED_MAIN: return Navigate.NEXT_SELECTED_MAIN; case NEXT_EXPANDED: return Navigate.PREV_EXPANDED; case PREV_EXPANDED: return Navigate.NEXT_EXPANDED; case NEXT_EXPANDED_UNREAD: return Navigate.PREV_EXPANDED_UNREAD; case PREV_EXPANDED_UNREAD: return Navigate.NEXT_EXPANDED_UNREAD; case NEXT_EXPANDED_SELECTED: return Navigate.PREV_EXPANDED_SELECTED; case PREV_EXPANDED_SELECTED: return Navigate.NEXT_EXPANDED_SELECTED; case NEXT_EXPANDED_CATEGORY: return Navigate.PREV_EXPANDED_CATEGORY; case PREV_EXPANDED_CATEGORY: return Navigate.NEXT_EXPANDED_CATEGORY; case NEXT_EXP_NONCATEGORY: return Navigate.PREV_EXP_NONCATEGORY; case PREV_EXP_NONCATEGORY: return Navigate.NEXT_EXP_NONCATEGORY; case NEXT_HIT: return Navigate.PREV_HIT; case PREV_HIT: return Navigate.NEXT_HIT; case NEXT_SELECTED_HIT: return Navigate.PREV_SELECTED_HIT; case PREV_SELECTED_HIT: return Navigate.NEXT_SELECTED_HIT; case NEXT_UNREAD_HIT: return Navigate.PREV_UNREAD_HIT; case PREV_UNREAD_HIT: return Navigate.NEXT_UNREAD_HIT; case NEXT_CATEGORY: return Navigate.PREV_CATEGORY; case PREV_CATEGORY: return Navigate.NEXT_CATEGORY; case NEXT_NONCATEGORY: return Navigate.PREV_NONCATEGORY; case PREV_NONCATEGORY: return Navigate.NEXT_NONCATEGORY; default: return nav; } } public boolean isRecycled() { if (NotesJNAContext.is64Bit()) { return m_hCollection64==0; } else { return m_hCollection32==0; } } public void recycle() { if (!m_noRecycle) { boolean bHandleIsNull = false; if (NotesJNAContext.is64Bit()) { bHandleIsNull = m_hCollection64==0; } else { bHandleIsNull = m_hCollection32==0; } if (!bHandleIsNull) { clearSearch(); if (m_unreadTable!=null && !m_unreadTable.isRecycled()) { m_unreadTable.recycle(); } NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFCloseCollection(m_hCollection64); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(this); m_hCollection64=0; } else { result = notesAPI.b32_NIFCloseCollection(m_hCollection32); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(this); m_hCollection32=0; } } } } public void setNoRecycle() { m_noRecycle=true; } private void checkHandle() { if (NotesJNAContext.is64Bit()) { if (m_hCollection64==0) throw new NotesError(0, "Collection already recycled"); NotesGC.__b64_checkValidObjectHandle(getClass(), m_hCollection64); } else { if (m_hCollection32==0) throw new NotesError(0, "Collection already recycled"); NotesGC.__b32_checkValidObjectHandle(getClass(), m_hCollection32); } } public int getNoteId() { return m_viewNoteId; } public String getUNID() { return m_viewUNID; } public int getHandle32() { return m_hCollection32; } public long getHandle64() { return m_hCollection64; } /** * Returns the user for which the collation returns the data * * @return null for server */ public String getContextUser() { return m_asUserCanonical; } /** * Returns the unread table.<br>Adding note ids * to this table causes the notes to be found in view lookups using {@link Navigate#NEXT_UNREAD} * and similar flags.<br> * <br> * For remote databases, do not forget to call {@link #updateFilters(EnumSet)} * after you are done modifying the table to re-send the list to the server. * * @return unread table */ public NotesIDTable getUnreadTable() { return m_unreadTable; } /** * Returns the collapsed list. Can be used to tell Domino which categories are * expanded/collapsed.<br> Adding note ids * to this table causes the notes to be found in view lookups using {@link Navigate#NEXT_EXPANDED}, * {@link Navigate#NEXT_EXPANDED_CATEGORY}, {@link Navigate#NEXT_EXPANDED_SELECTED} or * {@link Navigate#NEXT_EXPANDED_UNREAD}.<br> * <br> * For remote databases, do not forget to call {@link #updateFilters(EnumSet)} * after you are done modifying the table to re-send the list to the server. * * @return collapsed list */ public NotesIDTable getCollapsedList() { return m_collapsedList; } /** * Returns an id table of "selected" note ids; adding note ids * to this table causes the notes to be found in view lookups using {@link Navigate#NEXT_SELECTED} * and similar flags.<br> * <br> * For remote databases, do not forget to call {@link #updateFilters(EnumSet)} * after you are done modifying the table to re-send the list to the server. * * @return selected list */ public NotesIDTable getSelectedList() { return m_selectedList; } /** * Performs a fulltext search in the collection * * @param query fulltext query * @param limit max entries to return or 0 to get all * @param options FTSearch flags * @param filterIDTable optional ID table to refine the search * @return search result */ public SearchResult ftSearch(String query, short limit, EnumSet<FTSearch> options, NotesIDTable filterIDTable) { clearSearch(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { LongByReference rethSearch = new LongByReference(); result = notesAPI.b64_FTOpenSearch(rethSearch); NotesErrorUtils.checkResult(result); m_activeFTSearchHandle64 = rethSearch; } else { IntByReference rethSearch = new IntByReference(); result = notesAPI.b32_FTOpenSearch(rethSearch); NotesErrorUtils.checkResult(result); m_activeFTSearchHandle32 = rethSearch; } Memory queryLMBCS = NotesStringUtils.toLMBCS(query, true); IntByReference retNumDocs = new IntByReference(); //always filter view data EnumSet<FTSearch> optionsWithView = options.clone(); optionsWithView.add(FTSearch.SET_COLL); int optionsWithViewBitMask = FTSearch.toBitMask(optionsWithView); if (NotesJNAContext.is64Bit()) { LongByReference rethResults = new LongByReference(); result = notesAPI.b64_FTSearch( m_hDB64, m_activeFTSearchHandle64, m_hCollection64, queryLMBCS, optionsWithViewBitMask, limit, filterIDTable==null ? 0 : filterIDTable.getHandle64(), retNumDocs, new Memory(Pointer.SIZE), // Reserved field rethResults); if (result == 3874) { //handle special error code: no documents found return new SearchResult(null, 0); } NotesErrorUtils.checkResult(result); return new SearchResult(rethResults.getValue()==0 ? null : new NotesIDTable(rethResults.getValue()), retNumDocs.getValue()); } else { IntByReference rethResults = new IntByReference(); result = notesAPI.b32_FTSearch( m_hDB32, m_activeFTSearchHandle32, m_hCollection32, queryLMBCS, optionsWithViewBitMask, limit, filterIDTable==null ? 0 : filterIDTable.getHandle32(), retNumDocs, new Memory(Pointer.SIZE), // Reserved field rethResults); if (result == 3874) { //handle special error code: no documents found return new SearchResult(null, 0); } NotesErrorUtils.checkResult(result); return new SearchResult(rethResults.getValue()==0 ? null : new NotesIDTable(rethResults.getValue()), retNumDocs.getValue()); } } /** * Container for a FT search result * * @author Karsten Lehmann */ public static class SearchResult { private NotesIDTable m_matchesIDTable; private int m_numDocs; public SearchResult(NotesIDTable matchesIDTable, int numDocs) { m_matchesIDTable = matchesIDTable; m_numDocs = numDocs; } public int getNumDocs() { return m_numDocs; } public NotesIDTable getMatches() { return m_matchesIDTable; } } /** * Resets an active filtering cause by a FT search */ public void clearSearch() { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { if (m_activeFTSearchHandle64!=null) { short result = notesAPI.b64_FTCloseSearch(m_activeFTSearchHandle64.getValue()); NotesErrorUtils.checkResult(result); m_activeFTSearchHandle64=null; } } else { if (m_activeFTSearchHandle32!=null) { short result = notesAPI.b32_FTCloseSearch(m_activeFTSearchHandle32.getValue()); NotesErrorUtils.checkResult(result); m_activeFTSearchHandle32=null; } } } /** * Locates a note in the collection * * @param noteId note id * @return collection position * @throws NotesError if not found */ public String locateNote(int noteId) { checkHandle(); NotesCollectionPosition foundPos = new NotesCollectionPosition(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFLocateNote(m_hCollection64, foundPos, noteId); } else { result = notesAPI.b32_NIFLocateNote(m_hCollection32, foundPos, noteId); } NotesErrorUtils.checkResult(result); return foundPos.toPosString(); } /** * Locates a note in the collection * * @param noteId note id as hex string * @return collection position * @throws NotesError if not found */ public String locateNote(String noteId) { return locateNote(Integer.parseInt(noteId, 16)); } /** * Convenience function that returns a sorted set of note ids of documents * matching the specified search key(s) in the collection * * @param findFlags find flags, see {@link Find} * @param keys lookup keys * @return note ids */ public LinkedHashSet<Integer> getAllIdsByKey(EnumSet<Find> findFlags, Object... keys) { LinkedHashSet<Integer> noteIds = getAllEntriesByKey(findFlags, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<LinkedHashSet<Integer>>() { @Override public LinkedHashSet<Integer> startingLookup() { return new LinkedHashSet<Integer>(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead( LinkedHashSet<Integer> result, NotesViewEntryData entryData) { result.add(entryData.getNoteId()); return Action.Continue; } @Override public LinkedHashSet<Integer> lookupDone(LinkedHashSet<Integer> result) { return result; } }, keys); return noteIds; } /** * Method to check whether an optimized view lookup method can be used for * a set of find/return flags and the current Domino version * * @param findFlags find flags * @param returnMask return flags * @param keys lookup keys * @return true if method can be used */ private boolean canUseOptimizedLookupForKeyLookup(EnumSet<Find> findFlags, EnumSet<ReadMask> returnMask, Object... keys) { if (findFlags.contains(Find.GREATER_THAN) || findFlags.contains(Find.LESS_THAN)) { //TODO check this with IBM dev; we had crashes like "[0A0F:0002-21A00] PANIC: LookupHandle: null handle" using NIFFindByKeyExtended2 return false; } { //we had "ERR 774: Unsupported return flag(s)" errors when using the optimized lookup //method wither return values other than note id boolean unsupportedValuesFound = false; for (ReadMask currReadMaskValues: returnMask) { if ((currReadMaskValues != ReadMask.NOTEID) && (currReadMaskValues != ReadMask.SUMMARY)) { unsupportedValuesFound = true; break; } } if (unsupportedValuesFound) { return false; } } { //check for R9 and flag compatibility short buildVersion = m_parentDb.getParentServerBuildVersion(); if (buildVersion < 400) { return false; } } return true; } /** * Callback base class used to process collection lookup results * * @author Karsten Lehmann */ public static abstract class ViewLookupCallback<T> { public enum Action {Continue, Stop}; private NotesTimeDate m_newDiffTime; /** * The method is called when the view lookup is (re-)started. If the view * index is modified while reading, the view read operation restarts from * the beginning. * * @return result object that is passed to {@link #entryRead(Object, NotesViewEntryData)} */ public abstract T startingLookup(); /** * Override this method to return the programmatic name of a collection column. If * a non-null value is returned, we use an optimized lookup method to read the data, * resulting in much better performance (working like the formula @DbColumn) * * @return programmatic column name or null */ public String getNameForSingleColumnRead() { return null; } /** * Implement this method to process a read entry directly or add it to a result object.<br> * Please note: If you process the entry directly, keep in mind that the lookup * may restart when a view index change is detected. * * @param result context * @param entryData entry data * @return action (whether the lookup should continue) */ public abstract Action entryRead(T result, NotesViewEntryData entryData); /** * Override this empty method to get notified about view index changes */ public void viewIndexChangeDetected() { } /** * The method is called when differential view reading is used to return the {@link NotesTimeDate} * to be used for the next lookups * * @param newDiffTime new diff time */ public void setNewDiffTime(NotesTimeDate newDiffTime) { m_newDiffTime = newDiffTime; } /** * Use this method to read the {@link NotesTimeDate} to be used for the next lookups when using differential view * reads * * @return diff time or null */ public NotesTimeDate getNewDiffTime() { return m_newDiffTime; } /** * Override this method to return an optional {@link CollectionDataCache} to speed up view reading. * The returned cache instance is shared for all calls done with this callback implementation.<br> * <br> * Please note that according to IBM dev, this optimized view reading (differential view reads) does * only work in views that are not permuted (where documents do not appear multiple times, because * "Show multiple values as separate entries" has been set on any view column). * * @return cache or null (default value) */ public CollectionDataCache createDataCache() { return null; } private CollectionDataCache m_cacheInstance; /** * Standard implementation of this method calls {@link #createDataCache()} once * and stores the object instance in a member variable for later reuse.<br> * Can be overridden in case you need to store the cache somewhere else, * e.g. to reuse it later on. * * @return cache */ public CollectionDataCache getDataCache() { if (m_cacheInstance==null) { m_cacheInstance = createDataCache(); } return m_cacheInstance; } /** * Method is called when the lookup process is done * * @param result result object * @return result or transformed result */ public abstract T lookupDone(T result); } /** * Subclass of {@link ViewLookupCallback} that wraps any methods and forwards all calls * the another {@link ViewLookupCallback}. * * @author Karsten Lehmann */ public static class ViewLookupCallbackWrapper<T> extends ViewLookupCallback<T> { private ViewLookupCallback<T> m_innerCallback; public ViewLookupCallbackWrapper(ViewLookupCallback<T> innerCallback) { m_innerCallback = innerCallback; } @Override public String getNameForSingleColumnRead() { return m_innerCallback.getNameForSingleColumnRead(); } @Override public T startingLookup() { return m_innerCallback.startingLookup(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(T result, NotesViewEntryData entryData) { return m_innerCallback.entryRead(result, entryData); } @Override public CollectionDataCache createDataCache() { return m_innerCallback.createDataCache(); } @Override public NotesTimeDate getNewDiffTime() { return m_innerCallback.getNewDiffTime(); } @Override public void setNewDiffTime(NotesTimeDate newDiffTime) { m_innerCallback.setNewDiffTime(newDiffTime); } @Override public T lookupDone(T result) { return m_innerCallback.lookupDone(result); } @Override public void viewIndexChangeDetected() { m_innerCallback.viewIndexChangeDetected(); } } /** * Subclass of {@link ViewLookupCallback} that uses an optimized view lookup to * only read the value of a single collection column. This results in much * better performance, because the 64K summary buffer is not polluted with irrelevant data.<br> * <br> * Please make sure to pass either {@link ReadMask#SUMMARYVALUES} or {@link ReadMask#SUMMARY}, * preferably {@link ReadMask#SUMMARYVALUES}. * * @author Karsten Lehmann */ public static class ReadSingleColumnValues extends ViewLookupCallback<Set<String>> { private String m_columnName; private Locale m_sortLocale; /** * Creates a new instance * * @param columnName programmatic column name * @param sortLocale optional sort locale used to sort the result */ public ReadSingleColumnValues(String columnName, Locale sortLocale) { m_columnName = columnName; m_sortLocale = sortLocale; } @Override public String getNameForSingleColumnRead() { return m_columnName; } @Override public Set<String> startingLookup() { Collator collator = Collator.getInstance(m_sortLocale==null ? Locale.getDefault() : m_sortLocale); return new TreeSet<String>(collator); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(Set<String> result, NotesViewEntryData entryData) { String colValue = entryData.getAsString(m_columnName, null); if (colValue!=null) { result.add(colValue); } return com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action.Continue; } @Override public Set<String> lookupDone(Set<String> result) { return result; } } /** * Subclass of {@link ViewLookupCallback} that stores the data of read collection entries * in a {@link List}. * * @author Karsten Lehmann */ public static class EntriesAsListCallback extends ViewLookupCallback<List<NotesViewEntryData>> { private int m_maxEntries; /** * Creates a new instance * * @param maxEntries maximum entries to return */ public EntriesAsListCallback(int maxEntries) { m_maxEntries = maxEntries; } @Override public List<NotesViewEntryData> startingLookup() { return new ArrayList<NotesViewEntryData>(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead( List<NotesViewEntryData> result, NotesViewEntryData entryData) { if (m_maxEntries==0) { return Action.Stop; } if (!isAccepted(entryData)) { //ignore this entry return Action.Continue; } //add entry to result list result.add(entryData); if (result.size() >= m_maxEntries) { //stop the lookup, we have enough data return Action.Stop; } else { //go on reading the view return Action.Continue; } } /** * Override this method to filter entries * * @param entryData current entry * @return true if entry should be added to the result */ protected boolean isAccepted(NotesViewEntryData entryData) { return true; } @Override public List<NotesViewEntryData> lookupDone(List<NotesViewEntryData> result) { return result; } } /** * Very fast scan function that populates a {@link NotesIDTable} with note ids in the * collection. Uses an undocumented C API call internally. Since the {@link NotesIDTable} * is sorted in ascending note id order, this method does not keep the original view order. * Use {@link NotesCollection#getAllIds(Navigate)} to get an ID list sorted in view order. * * @param navigator use {@link Navigate#NEXT} to read documents and categories, {@link Navigate#NEXT_CATEGORY} to only read categories and {@link Navigate#NEXT_NONCATEGORY} to only read documents * @param filterTable true to filter the ID table to entries visible for the current user * @param idTable table to populate with note ids */ public void getAllIds(Navigate navigator, boolean filterTable, NotesIDTable idTable) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_NIFGetIDTableExtended(m_hCollection64, Navigate.toBitMask(EnumSet.of(navigator)), (short) (filterTable ? 0 : 1), idTable.getHandle64()); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_NIFGetIDTableExtended(m_hCollection32, Navigate.toBitMask(EnumSet.of(navigator)), (short) (filterTable ? 0 : 1), idTable.getHandle32()); NotesErrorUtils.checkResult(result); } } /** * Convenience method that collects all note ids in the view, in the sort order of the current collation * * @param navigator use {@link Navigate#NEXT} to read documents and categories, {@link Navigate#NEXT_CATEGORY} to only read categories and {@link Navigate#NEXT_NONCATEGORY} to only read documents * @return set of note ids, sorted by occurence in the collection */ public LinkedHashSet<Integer> getAllIds(Navigate navigator) { LinkedHashSet<Integer> ids = getAllEntries("0", 1, EnumSet.of(navigator), Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<LinkedHashSet<Integer>>() { @Override public LinkedHashSet<Integer> startingLookup() { return new LinkedHashSet<Integer>(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead( LinkedHashSet<Integer> ctx, NotesViewEntryData entryData) { ctx.add(entryData.getNoteId()); return Action.Continue; } @Override public LinkedHashSet<Integer> lookupDone(LinkedHashSet<Integer> result) { return result; } }); return ids; } /** * Reads all values of a collection column * * @param columnName programmatic column name * @param sortLocale optional sort locale to sort the values; if null, we use the locale returned by {@link Locale#getDefault()} * @return column values */ public Set<String> getColumnValues(String columnName, Locale sortLocale) { boolean isCategory = isCategoryColumn(columnName); Navigate nav = isCategory ? Navigate.NEXT_CATEGORY : Navigate.NEXT_NONCATEGORY; return getAllEntries("0", 1, EnumSet.of(nav), Integer.MAX_VALUE, EnumSet.of(ReadMask.SUMMARYVALUES), new ReadSingleColumnValues(columnName, sortLocale)); } /** * The method reads a number of entries located under a specified category from the collection/view. * It internally takes care of view index changes while reading view data and restarts reading * if such a change has been detected. * * @param category category or catlevel1\catlevel2 structure * @param skipCount number of entries to skip * @param returnNav navigator to specify how to move in the collection * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result */ public <T> T getAllEntriesInCategory(String category, int skipCount, EnumSet<Navigate> returnNav, int preloadEntryCount, EnumSet<ReadMask> returnMask, final ViewLookupCallback<T> callback) { return getAllEntriesInCategory(category, skipCount, returnNav, null, null, preloadEntryCount, returnMask, callback); } /** * The method reads a number of entries located under a specified category from the collection/view. * It internally takes care of view index changes while reading view data and restarts reading * if such a change has been detected. * * @param category category or catlevel1\catlevel2 structure * @param skipCount number of entries to skip * @param returnNav navigator to specify how to move in the collection * @param diffTime If non-null, this is a "differential view read" meaning that the caller wants * us to optimize things by only returning full information for notes which have * changed (or are new) in the view, return just NoteIDs for notes which haven't * changed since this time and return a deleted ID table for notes which may be * known by the caller and have been deleted since DiffTime. * <b>Please note that "differential view reads" do only work in views without permutations (no columns with "show multiple values as separate entries" set) according to IBM. Otherwise, all the view data is always returned.</b> * @param diffIDTable If DiffTime is non-null and DiffIDTable is not null it provides a * list of notes which the caller has current information on. We use this to * know which notes we can return shortened information for (i.e., just the NoteID) * and what notes we might have to include in the returned DelNoteIDTable. * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result */ public <T> T getAllEntriesInCategory(String category, int skipCount, EnumSet<Navigate> returnNav, NotesTimeDate diffTime, NotesIDTable diffIDTable, int preloadEntryCount, EnumSet<ReadMask> returnMask, final ViewLookupCallback<T> callback) { final String[] categoryPos = new String[1]; final int[] expectedLkViewMod = new int[1]; while (true) { expectedLkViewMod[0] = getIndexModifiedSequenceNo(); //find category entry FindResult catFindResult = findByKey(EnumSet.of(Find.CASE_INSENSITIVE, Find.FIRST_EQUAL, Find.EQUAL), category); if (catFindResult.getEntriesFound()==0) { //category not found T result = callback.startingLookup(); result = callback.lookupDone(result); return result; } String firstDocInCategoryPos = catFindResult.getPosition(); if (!firstDocInCategoryPos.contains(".")) { //category not found T result = callback.startingLookup(); result = callback.lookupDone(result); return result; } categoryPos[0] = firstDocInCategoryPos.substring(0, firstDocInCategoryPos.indexOf('.')); System.out.println("categoryPos[0]: "+categoryPos[0]); NotesCollectionPosition pos = NotesCollectionPosition.toPosition(categoryPos[0]); pos.MinLevel = (byte) (pos.Level+1); pos.MaxLevel = 32; pos.write(); final boolean[] viewIndexModified = new boolean[1]; EnumSet<Navigate> useReturnNav = returnNav.clone(); useReturnNav.add(Navigate.MINLEVEL); EnumSet<ReadMask> useReturnMask = returnMask.clone(); useReturnMask.add(ReadMask.INDEXPOSITION); T result = getAllEntries(pos.toPosString(), skipCount, useReturnNav, preloadEntryCount, useReturnMask, new ViewLookupCallbackWrapper<T>(callback) { int cnt=0; @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(T result, NotesViewEntryData entryData) { cnt++; //check if this entry is still one of the descendants of the category entry String entryPos = entryData.getPositionStr(); if (entryPos.startsWith(categoryPos[0])) { return super.entryRead(result, entryData); } if ((cnt % 100)==0) { int currViewIndexMod = getIndexModifiedSequenceNo(); if (currViewIndexMod!=expectedLkViewMod[0]) { viewIndexModified[0] = true; return Action.Stop; } } return Action.Continue; } }); if (viewIndexModified[0]) { callback.viewIndexChangeDetected(); continue; } int currViewIndexMod = getIndexModifiedSequenceNo(); if (currViewIndexMod!=expectedLkViewMod[0]) { //view has changed, restart callback.viewIndexChangeDetected(); continue; } return result; } } /** * The method reads a number of entries from the collection/view. It internally takes care * of view index changes while reading view data and restarts reading if such a change has been * detected. * * @param startPosStr start position; use "0" or null to start before the first entry * @param skipCount number entries to skip before reading * @param returnNav navigator to specify how to move in the collection * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result * * @param <T> type of lookup result object */ public <T> T getAllEntries(String startPosStr, int skipCount, EnumSet<Navigate> returnNav, int preloadEntryCount, EnumSet<ReadMask> returnMask, ViewLookupCallback<T> callback) { NotesCollectionPosition pos = NotesCollectionPosition.toPosition(startPosStr==null ? "0" : startPosStr); //decide whether we need to use the undocumented NIFReadEntriesExt String readSingleColumnName = callback.getNameForSingleColumnRead(); if (readSingleColumnName!=null) { //make sure that we actually read any column values if (!returnMask.contains(ReadMask.SUMMARY) && !returnMask.contains(ReadMask.SUMMARYVALUES)) { returnMask = returnMask.clone(); returnMask.add(ReadMask.SUMMARYVALUES); } } CollectionDataCache dataCache = callback.getDataCache(); if (returnMask.equals(EnumSet.of(ReadMask.NOTEID))) { //disable cache if all we need to read is the note id dataCache = null; } Integer readSingleColumnIndex = readSingleColumnName==null ? null : getColumnValuesIndex(readSingleColumnName); if (readSingleColumnName!=null) { //TODO view row caching currently disabled for single column reads, needs more work dataCache = null; } if (dataCache!=null) { //if caching is used, make sure that we read the note id, because that's how we hash our data if (!returnMask.contains(ReadMask.NOTEID) && !returnMask.contains(ReadMask.NOTEID)) { returnMask = returnMask.clone(); returnMask.add(ReadMask.NOTEID); } } while (true) { T result = callback.startingLookup(); if (preloadEntryCount==0) { //nothing to do result = callback.lookupDone(result); return result; } boolean viewModified = false; boolean firstLoopRun = true; NotesTimeDate retDiffTime = null; NotesTimeDate diffTime = null; NotesIDTable diffIDTable = null; if (dataCache!=null) { CacheState cacheState = dataCache.getCacheState(); //only use cache content if read masks are compatible Map<Integer,CacheableViewEntryData> cacheEntries = cacheState.getCacheEntries(); if (cacheEntries!=null && !cacheEntries.isEmpty()) { EnumSet<ReadMask> cacheReadMask = cacheState.getReadMask(); if (returnMask.equals(cacheReadMask)) { diffTime = cacheState.getDiffTime(); diffIDTable = new NotesIDTable(); diffIDTable.addNotes(cacheEntries.keySet()); } } } List<NotesViewEntryData> entriesToUpdateCache = dataCache==null ? null : new ArrayList<NotesViewEntryData>(); while (true) { if (preloadEntryCount==0) { break; } NotesViewLookupResultData data; data = readEntriesExt(pos, returnNav, firstLoopRun ? skipCount : 1, returnNav, preloadEntryCount, returnMask, diffTime, diffIDTable, readSingleColumnIndex); retDiffTime = data.getReturnedDiffTime(); if (dataCache!=null) { //if data cache is used, we fill in missing gaps in cases where NIF skipped producing //the summary data, because the corresponding cache entry was already //up to date List<NotesViewEntryData> entries = data.getEntries(); dataCache.populateEntryStubsWithData(entries); entriesToUpdateCache.addAll(entries); } if (data.getReturnCount()==0) { //no more data found result = callback.lookupDone(result); if (dataCache!=null && retDiffTime!=null) { if (!entriesToUpdateCache.isEmpty()) { dataCache.addCacheValues(returnMask, retDiffTime, entriesToUpdateCache); } callback.setNewDiffTime(retDiffTime); } return result; } firstLoopRun = false; if (isAutoUpdate()) { if (data.hasAnyNonDataConflicts()) { //refresh the view and restart the lookup viewModified=true; break; } } List<NotesViewEntryData> entries = data.getEntries(); for (NotesViewEntryData currEntry : entries) { Action action = callback.entryRead(result, currEntry); if (action==Action.Stop) { result = callback.lookupDone(result); if (dataCache!=null && retDiffTime!=null) { if (!entriesToUpdateCache.isEmpty()) { dataCache.addCacheValues(returnMask, retDiffTime, entriesToUpdateCache); } callback.setNewDiffTime(retDiffTime); } return result; } } } if (dataCache!=null && retDiffTime!=null) { if (!entriesToUpdateCache.isEmpty()) { dataCache.addCacheValues(returnMask, retDiffTime, entriesToUpdateCache); } callback.setNewDiffTime(retDiffTime); } if (diffIDTable!=null) { diffIDTable.recycle(); } if (viewModified) { //view index was changed while reading; restart scan callback.viewIndexChangeDetected(); update(); continue; } return result; } } /** * Returns all view entries matching the specified search key(s) in the collection. * It internally takes care of view index changes while reading view data and restarts * reading if such a change has been detected. * * @param findFlags find flags, see {@link Find} * @param returnMask values to be returned * @param callback lookup callback * @param keys lookup keys * @return lookup result * * @param <T> type of lookup result object */ public <T> T getAllEntriesByKey(EnumSet<Find> findFlags, EnumSet<ReadMask> returnMask, ViewLookupCallback<T> callback, Object... keys) { //we are leaving the loop when there is no more data to be read; //while(true) is here to rerun the query in case of view index changes while reading while (true) { T result = callback.startingLookup(); NotesViewLookupResultData data; //position of first match String firstMatchPosStr; int remainingEntries; int entriesToSkipOnFirstLoopRun = 0; if (canUseOptimizedLookupForKeyLookup(findFlags, returnMask, keys)) { //do the first lookup and read operation atomically; uses a large buffer for local calls EnumSet<Find> findFlagsWithExtraBits = findFlags.clone(); findFlagsWithExtraBits.add(Find.AND_READ_MATCHES); findFlagsWithExtraBits.add(Find.RETURN_DWORD); data = findByKeyExtended2(findFlagsWithExtraBits, returnMask, keys); int numEntriesFound = data.getReturnCount(); if (numEntriesFound!=-1) { if (isAutoUpdate()) { //check for view index or design change if (data.hasAnyNonDataConflicts()) { //refresh the view and restart the lookup callback.viewIndexChangeDetected(); update(); continue; } } //copy the data we have read List<NotesViewEntryData> entries = data.getEntries(); for (NotesViewEntryData currEntryData : entries) { Action action = callback.entryRead(result, currEntryData); if (action==Action.Stop) { result = callback.lookupDone(result); return result; } } entriesToSkipOnFirstLoopRun = entries.size(); if (!data.hasMoreToDo()) { //we are done result = callback.lookupDone(result); return result; } //compute what we have left int entriesReadOnFirstLookup = entries.size(); remainingEntries = numEntriesFound - entriesReadOnFirstLookup; firstMatchPosStr = data.getPosition(); } else { //workaround for a bug where the method NIFFindByKeyExtended2 returns -1 as numEntriesFound //and no buffer data //fallback to classic lookup until this is fixed/commented by IBM dev: FindResult findResult = findByKey(findFlags, keys); remainingEntries = findResult.getEntriesFound(); if (remainingEntries==0) { return result; } firstMatchPosStr = findResult.getPosition(); } } else { //first find the start position to read data FindResult findResult = findByKey(findFlags, keys); remainingEntries = findResult.getEntriesFound(); if (remainingEntries==0) { return result; } firstMatchPosStr = findResult.getPosition(); } if (!canFindExactNumberOfMatches(findFlags)) { Direction currSortDirection = getCurrentSortDirection(); if (currSortDirection!=null) { //handle special case for inquality search where column sort order matches the find flag, //so we can read all view entries after findResult.getPosition() if (currSortDirection==Direction.Ascending && findFlags.contains(Find.GREATER_THAN)) { //read all entries after findResult.getPosition() remainingEntries = Integer.MAX_VALUE; } else if (currSortDirection==Direction.Descending && findFlags.contains(Find.LESS_THAN)) { //read all entries after findResult.getPosition() remainingEntries = Integer.MAX_VALUE; } } } if (firstMatchPosStr!=null) { //position of the first match; we skip (entries.size()) to read the remaining entries boolean isFirstLookup = true; NotesCollectionPosition lookupPos = NotesCollectionPosition.toPosition(firstMatchPosStr); boolean viewModified = false; while (remainingEntries>0) { //on first lookup, start at "posStr" and skip the amount of already read entries data = readEntries(lookupPos, EnumSet.of(Navigate.NEXT_NONCATEGORY), isFirstLookup ? entriesToSkipOnFirstLoopRun : 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), remainingEntries, returnMask); if (isFirstLookup || isAutoUpdate()) { //for the first lookup, make sure we start at the right position if (data.hasAnyNonDataConflicts()) { //set viewModified to true and leave the inner loop; we will refresh the view and restart the lookup viewModified=true; break; } } isFirstLookup=false; List<NotesViewEntryData> entries = data.getEntries(); if (entries.isEmpty()) { //looks like we don't have any more data in the view break; } for (NotesViewEntryData currEntryData : entries) { Action action = callback.entryRead(result, currEntryData); if (action==Action.Stop) { result = callback.lookupDone(result); return result; } } remainingEntries = remainingEntries - entries.size(); } if (viewModified) { //refresh view and redo the whole lookup callback.viewIndexChangeDetected(); update(); continue; } } result = callback.lookupDone(result); return result; } } /** * This method is in essense a combo NIFFindKey/NIFReadEntries API. It leverages * the C API method NIFFindByKeyExtended2 internally which was introduced in Domino R9<br> * <br> * The purpose of this method is to provide a mechanism to position into a * collection and read the associated entries in an atomic manner.<br> * <br> * More specifically, the key provided is positioned to and the entries from * the collection are read while the collection is read locked so that no other updates can occur.<br> * <br> * 1) This avoids the possibility of the initial collection position shifting * due to an insert/delete/update in and/or around the logical key value that * would result in an ordinal change to the position.<br> * <br> * This a classic problem when doing a NIFFindKey, getting the position returned, * and then doing a NIFReadEntries following.<br> * <br> * 2) The API improves the ability to read all the entries that are associated * with the key position atomically.<br> * <br> * This can be done depending on the size of the data being returned.<br> * <br> * If all the data fits into the limitation (64K) of the return buffer, then * it will be done atomically in 1 call.<br> * Otherwise subsequent NIFReadEntries will need to be called, which will be non-atomic.<br> * <br> * The 64K limit only changes behavior to NIFFindByKey/NIFReadEntries when the call is client/server. * Locally there is no limit. * <hr> * Original documentation of C API method NIFFindByKeyExtended2:<br> * <br> * NIFFindByKeyExtended2 - Lookup index entry by "key"<br> * <br> * Given a "key" buffer in the standard format of a summary buffer,<br> * locate the entry which matches the given key(s). Supply as many<br> * "key" summary items as required to correspond to the way the index<br> * collates, in order to uniquely find an entry.<br> * <br> * If multiple index entries match the specified key (especially if<br> * not enough key items were specified), then the index position of<br> * the FIRST matching entry is returned ("first" is defined by the<br> * entry which collates before all others in the collated index).<br> * <br> * Note that the more explicitly an entry can be specified (by<br> * specifying as many keys as possible), then the faster the lookup<br> * can be performed, since the "key" lookup is very fast, but a<br> * sequential search is performed to locate the "first" entry when<br> * multiple entries match.<br> * <br> * This routine can only be used when dealing with notes that do not<br> * have multiple permutations, and cannot be used to locate response<br> * notes. * * @param findFlags find flags ({@link Find}) * @param returnMask mask specifying what information is to be returned on each entry ({link ReadMask}) * @param keys lookup keys * @return lookup result */ public NotesViewLookupResultData findByKeyExtended2(EnumSet<Find> findFlags, EnumSet<ReadMask> returnMask, Object... keys) { checkHandle(); if (keys==null || keys.length==0) throw new IllegalArgumentException("No search keys specified"); if (!canUseOptimizedLookupForKeyLookup(findFlags, returnMask, keys)) { throw new UnsupportedOperationException("This method cannot be used for the specified arguments (only noteids) or the current platform (only R9 and above)"); } IntByReference retNumMatches = new IntByReference(); NotesCollectionPosition retIndexPos = new NotesCollectionPosition(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short findFlagsBitMask = Find.toBitMask(findFlags); short result; int returnMaskBitMask = ReadMask.toBitMask(returnMask); ShortByReference retSignalFlags = new ShortByReference(); if (NotesJNAContext.is64Bit()) { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b64_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } LongByReference retBuffer = new LongByReference(); IntByReference retSequence = new IntByReference(); result = notesAPI.b64_NIFFindByKeyExtended2(m_hCollection64, keyBuffer, findFlagsBitMask, returnMaskBitMask, retIndexPos, retNumMatches, retSignalFlags, retBuffer, retSequence); if (result == 1028 || result == 17412) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } NotesErrorUtils.checkResult(result); if (retNumMatches.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } else { if (retBuffer.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, retNumMatches.getValue(), retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null); } else { boolean convertStringsLazily = true; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b64_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), 0, retNumMatches.getValue(), returnMask, retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null, convertStringsLazily, null); return viewData; } } } else { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b32_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } IntByReference retBuffer = new IntByReference(); IntByReference retSequence = new IntByReference(); result = notesAPI.b32_NIFFindByKeyExtended2(m_hCollection32, keyBuffer, findFlagsBitMask, returnMaskBitMask, retIndexPos, retNumMatches, retSignalFlags, retBuffer, retSequence); if (result == 1028 || result == 17412) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } NotesErrorUtils.checkResult(result); if (retNumMatches.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } else { if (retBuffer.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, retNumMatches.getValue(), retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null); } else { boolean convertStringsLazily = true; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b32_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), 0, retNumMatches.getValue(), returnMask, retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null, convertStringsLazily, null); return viewData; } } } } /** * This function searches through a collection for the first note whose sort * column values match the given search keys.<br> * <br> * The search key consists of an array containing one or several values. * This function matches each value in the * search key against the corresponding sorted column of the view or folder.<br> * <br> * Only sorted columns are used. The values in the search key * must be specified in the same order as the sorted columns in the view * or folder, from left to right. Other unsorted columns may lie between * the sorted columns to be searched.<br> * <br> * For example, suppose view columns 1, 3, 4 and 5 are sorted.<br> * The key buffer may contain search keys for: just column 1; columns 1 * and 3; or for columns 1, 3, and 4.<br> * <br> * This function yields the {@link NotesCollectionPosition} of the first note in the * collection that matches the keys. It also yields a count of the number * of notes that match the keys. Since all notes that match the keys * appear contiguously in the view or folder, you may pass the resulting * {@link NotesCollectionPosition} and match count as inputs to * {@link NotesCollection#readEntries(NotesCollectionPosition, EnumSet, int, EnumSet, int, EnumSet)} * to read all the entries in the collection that match the keys.<br> * <br> * If multiple notes match the specified (partial) keys, and * {@link Find#FIRST_EQUAL} (the default flag) is specified, * hen the position * of the first matching note is returned ("first" is defined by the * note which collates before all the others in the view).<br> * <br> * The position of the last matching note is returned if {@link Find#LAST_EQUAL} * is specified. If {@link Find#LESS_THAN} is specified, * then the last note * with a key value less than the specified key is returned.<br> * <br> * If {@link Find#GREATER_THAN} is specified, then the first * note with a key * value greater than the specified key is returned.<br> * <br> * This routine cannot be used to locate notes that are categorized * under multiple categories (the resulting position is unpredictable), * and also cannot be used to locate responses.<br> * <br> * This routine is usually not appropriate for equality searches of key * values of {@link Calendar}.<br> * <br> * A match will only be found if the key value is * as precise as and is equal to the internally stored data.<br> * <br> * {@link Calendar} data is displayed with less precision than what is stored * internally. Use inequality searches, such as {@link Find#GREATER_THAN} or * {@link Find#LESS_THAN}, for {@link Calendar} key values * to avoid having to find * an exact match of the specified value. If the precise key value * is known, however, equality searches of {@link Calendar} values are supported.<br> * <br> * Returning the number of matches on an inequality search is not supported.<br> * <br> * In other words, if you specify any one of the following for the FindFlags argument:<br> * {@link Find#LESS_THAN}<br> * {@link Find#LESS_THAN} | {@link Find#EQUAL}<br> * {@link Find#GREATER_THAN}<br> * {@link Find#GREATER_THAN} | {@link Find#EQUAL}<br> * <br> * this function cannot determine the number of notes that match the search * condition (use {@link #canFindExactNumberOfMatches(EnumSet)} to check * whether a combination of find flags can return the exact number of matches).<br> * If we cannot determine the number of notes, the function will return 1 for the count * value returned by {@link FindResult#getEntriesFound()}. * @param findFlags {@link Find} * @param keys lookup keys, can be {@link String}, double / {@link Double}, int / {@link Integer}, {@link Date}, {@link Calendar}, {@link Date}[] or {@link Calendar}[] with two elements for date ranges * @return result */ public FindResult findByKey(EnumSet<Find> findFlags, Object... keys) { checkHandle(); if (keys==null || keys.length==0) throw new IllegalArgumentException("No search keys specified"); IntByReference retNumMatches = new IntByReference(); NotesCollectionPosition retIndexPos = new NotesCollectionPosition(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short findFlagsBitMask = Find.toBitMask(findFlags); short result; if (NotesJNAContext.is64Bit()) { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b64_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } result = notesAPI.b64_NIFFindByKey(m_hCollection64, keyBuffer, findFlagsBitMask, retIndexPos, retNumMatches); } else { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b32_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } result = notesAPI.b32_NIFFindByKey(m_hCollection32, keyBuffer, findFlagsBitMask, retIndexPos, retNumMatches); } if (result == 1028 || result == 17412) { return new FindResult("", 0, canFindExactNumberOfMatches(findFlags)); } NotesErrorUtils.checkResult(result); int nMatchesFound = retNumMatches.getValue(); int[] retTumbler = retIndexPos.Tumbler; short retLevel = retIndexPos.Level; StringBuilder sb = new StringBuilder(); for (int i=0; i<=retLevel; i++) { if (sb.length()>0) sb.append("."); sb.append(retTumbler[i]); } String firstMatchPos = sb.toString(); return new FindResult(firstMatchPos, nMatchesFound, canFindExactNumberOfMatches(findFlags)); } /** * This function searches through a collection for notes whose primary sort * key matches a given string. The primary sort key for a given note is the * value displayed for that note in the leftmost sorted column in the view * or folder. Use this function only when the leftmost sorted column of * the view or folder is a string.<br> * <br> * This function yields the {@link NotesCollectionPosition} of the first note in the * collection that matches the string. It also yields a count of the number * of notes that match the string.<br> * <br> * With views that are not categorized, all notes with primary sort keys that * match the string appear contiguously in the view or folder.<br> * <br> * This means you may pass the resulting {@link NotesCollectionPosition} and match count * as inputs to {@link #readEntries(NotesCollectionPosition, EnumSet, int, EnumSet, int, EnumSet)} * to read all the entries in the collection that match the string.<br> * <br> * This routine returns limited results if the view is categorized.<br> * <br> * Views that are categorized do not necessarily list all notes whose<br> * sort keys match the string contiguously; such as in the case where * the category note intervenes.<br> * Likewise, this routine cannot be used to locate notes that are * categorized under multiple categories (the resulting position is unpredictable), * and also cannot be used to locate responses.<br> * <br> * Use {@link #findByKey(EnumSet, Object...)} if the leftmost sorted column * is a number or a time/date.<br> * <br> * Returning the number of matches on an inequality search is not supported.<br> * <br> * In other words, if you specify any one of the following for the FindFlags argument:<br> * <br> * {@link Find#LESS_THAN}<br> * {@link Find#LESS_THAN} | {@link Find#EQUAL}<br> * {@link Find#GREATER_THAN}<br> * {@link Find#GREATER_THAN} | {@link Find#EQUAL}<br> * <br> * this function cannot determine the number of notes that match the search * condition (use {@link #canFindExactNumberOfMatches(EnumSet)} to check * whether a combination of find flags can return the exact number of matches).<br> * If we cannot determine the number of notes, the function will return 1 for the count * value returned by {@link FindResult#getEntriesFound()}. * * @param name name to look for * @param findFlags find flags, see {@link Find} * @return result */ public FindResult findByName(String name, EnumSet<Find> findFlags) { checkHandle(); Memory nameLMBCS = NotesStringUtils.toLMBCS(name, true); IntByReference retNumMatches = new IntByReference(); NotesCollectionPosition retIndexPos = new NotesCollectionPosition(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short findFlagsBitMask = Find.toBitMask(findFlags); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFFindByName(m_hCollection64, nameLMBCS, findFlagsBitMask, retIndexPos, retNumMatches); } else { result = notesAPI.b32_NIFFindByName(m_hCollection32, nameLMBCS, findFlagsBitMask, retIndexPos, retNumMatches); } if (result == 1028 || result == 17412) { return new FindResult("", 0, canFindExactNumberOfMatches(findFlags)); } NotesErrorUtils.checkResult(result); int nMatchesFound = retNumMatches.getValue(); int[] retTumbler = retIndexPos.Tumbler; short retLevel = retIndexPos.Level; StringBuilder sb = new StringBuilder(); for (int i=0; i<=retLevel; i++) { if (sb.length()>0) sb.append("."); sb.append(retTumbler[i]); } String firstMatchPos = sb.toString(); return new FindResult(firstMatchPos, nMatchesFound, canFindExactNumberOfMatches(findFlags)); } /** * If the specified find flag uses an inequality search like {@link Find#LESS_THAN} * or {@link Find#GREATER_THAN}, this method returns true, meaning that * the Notes API cannot return an exact number of matches. * * @param findFlags find flags * @return true if exact number of matches can be returned */ public boolean canFindExactNumberOfMatches(EnumSet<Find> findFlags) { if (findFlags.contains(Find.LESS_THAN)) { return false; } else if (findFlags.contains(Find.GREATER_THAN)) { return false; } else { return true; } } /** * Container object for a collection lookup result * * @author Karsten Lehmann */ public static class FindResult { private String m_position; private int m_entriesFound; private boolean m_hasExactNumberOfMatches; /** * Creates a new instance * * @param position position of the first match * @param entriesFound number of entries found or 1 if hasExactNumberOfMatches is <code>false</code> * @param hasExactNumberOfMatches true if Notes was able to count the number of matches (e.g. for string key lookups with full or partial matches) */ public FindResult(String position, int entriesFound, boolean hasExactNumberOfMatches) { m_position = position; m_entriesFound = entriesFound; m_hasExactNumberOfMatches = hasExactNumberOfMatches; } /** * Returns the number of entries found or 1 if hasExactNumberOfMatches is <code>false</code> * and any matches were found * * @return count */ public int getEntriesFound() { return m_entriesFound; } /** * Returns the position of the first match * * @return position */ public String getPosition() { return m_position; } /** * Use this method to check whether Notes was able to count the number of matches * (e.g. for string key lookups with full or partial matches) * * @return true if we have an exact match count */ public boolean hasExactNumberOfMatches() { return m_hasExactNumberOfMatches; } } public NotesViewLookupResultData readEntries(NotesCollectionPosition startPos, EnumSet<Navigate> skipNavigator, int skipCount, EnumSet<Navigate> returnNavigator, int returnCount, EnumSet<ReadMask> returnMask) { checkHandle(); IntByReference retNumEntriesSkipped = new IntByReference(); IntByReference retNumEntriesReturned = new IntByReference(); ShortByReference retSignalFlags = new ShortByReference(); ShortByReference retBufferLength = new ShortByReference(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short skipNavBitMask = Navigate.toBitMask(skipNavigator); short returnNavBitMask = Navigate.toBitMask(returnNavigator); int readMaskBitMask = ReadMask.toBitMask(returnMask); short result; if (NotesJNAContext.is64Bit()) { LongByReference retBuffer = new LongByReference(); result = notesAPI.b64_NIFReadEntries(m_hCollection64, // hCollection startPos, // IndexPos skipNavBitMask, // SkipNavigator skipCount, // SkipCount returnNavBitMask, // ReturnNavigator returnCount, // ReturnCount readMaskBitMask, // Return mask retBuffer, // rethBuffer retBufferLength, // retBufferLength retNumEntriesSkipped, // retNumEntriesSkipped retNumEntriesReturned, // retNumEntriesReturned retSignalFlags // retSignalFlags ); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = getIndexModifiedSequenceNo(); int iBufLength = (int) (retBufferLength.getValue() & 0xffff); if (iBufLength==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, null); } else { boolean convertStringsLazily = true; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b64_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, null, convertStringsLazily, null); return viewData; } } else { IntByReference retBuffer = new IntByReference(); result = notesAPI.b32_NIFReadEntries(m_hCollection32, // hCollection startPos, // IndexPos skipNavBitMask, // SkipNavigator skipCount, // SkipCount returnNavBitMask, // ReturnNavigator returnCount, // ReturnCount readMaskBitMask, // Return mask retBuffer, // rethBuffer retBufferLength, // retBufferLength retNumEntriesSkipped, // retNumEntriesSkipped retNumEntriesReturned, // retNumEntriesReturned retSignalFlags // retSignalFlags ); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = getIndexModifiedSequenceNo(); if (retBufferLength.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, null); } else { boolean convertStringsLazily = true; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b32_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, null, convertStringsLazily, null); return viewData; } } } public NotesViewLookupResultData readEntriesExt(NotesCollectionPosition startPos, EnumSet<Navigate> skipNavigator, int skipCount, EnumSet<Navigate> returnNavigator, int returnCount, EnumSet<ReadMask> returnMask, NotesTimeDate diffTime, NotesIDTable diffIDTable, Integer columnNumber) { checkHandle(); IntByReference retNumEntriesSkipped = new IntByReference(); IntByReference retNumEntriesReturned = new IntByReference(); ShortByReference retSignalFlags = new ShortByReference(); ShortByReference retBufferLength = new ShortByReference(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short skipNavBitMask = Navigate.toBitMask(skipNavigator); short returnNavBitMask = Navigate.toBitMask(returnNavigator); int readMaskBitMask = ReadMask.toBitMask(returnMask); int flags = 0; NotesTimeDate retDiffTime = new NotesTimeDate(); NotesTimeDate retModifiedTime = new NotesTimeDate(); IntByReference retSequence = new IntByReference(); String singleColumnLookupName = columnNumber == null ? null : getColumnName(columnNumber); short result; if (NotesJNAContext.is64Bit()) { LongByReference retBuffer = new LongByReference(); result = notesAPI.b64_NIFReadEntriesExt(m_hCollection64, startPos, skipNavBitMask, skipCount, returnNavBitMask, returnCount, readMaskBitMask, diffTime, diffIDTable==null ? 0 : diffIDTable.getHandle64(), columnNumber==null ? NotesCAPI.MAXDWORD : columnNumber, flags, retBuffer, retBufferLength, retNumEntriesSkipped, retNumEntriesReturned, retSignalFlags, retDiffTime, retModifiedTime, retSequence); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = retModifiedTime.Innards[0]; //getIndexModifiedSequenceNo(); int iBufLength = (int) (retBufferLength.getValue() & 0xffff); if (iBufLength==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, retDiffTime); } else { boolean convertStringsLazily = true; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b64_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, retDiffTime, convertStringsLazily, singleColumnLookupName); return viewData; } } else { IntByReference retBuffer = new IntByReference(); result = notesAPI.b32_NIFReadEntriesExt(m_hCollection32, startPos, skipNavBitMask, skipCount, returnNavBitMask, returnCount, readMaskBitMask, diffTime, diffIDTable==null ? 0 : diffIDTable.getHandle32(), columnNumber==null ? NotesCAPI.MAXDWORD : columnNumber, flags, retBuffer, retBufferLength, retNumEntriesSkipped, retNumEntriesReturned, retSignalFlags, retDiffTime, retModifiedTime, retSequence); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = retModifiedTime.Innards[0]; //getIndexModifiedSequenceNo(); if (retBufferLength.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, retDiffTime); } else { boolean convertStringsLazily = true; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b32_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, null, convertStringsLazily, singleColumnLookupName); return viewData; } } } /** * Updates the view to reflect the current database content (using NIFUpdateCollection method) */ public void update() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFUpdateCollection(m_hCollection64); } else { result = notesAPI.b32_NIFUpdateCollection(m_hCollection32); } NotesErrorUtils.checkResult(result); } /** * Returns the programmatic name of the column that has last been used to resort * the view * * @return column name or null if view has not been resorted */ public String getCurrentSortColumnName() { short collation = getCollation(); if (collation==0) return null; CollationInfo colInfo = getCollationsInfo(); return colInfo.getSortItem(collation); } /** * Returns the sort direction that has last been used to resort the view * * @return direction or null */ public Direction getCurrentSortDirection() { short collation = getCollation(); if (collation==0) return null; CollationInfo colInfo = getCollationsInfo(); return colInfo.getSortDirection(collation); } /** * Returns the currently active collation * * @return collation */ private short getCollation() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; ShortByReference retCollationNum = new ShortByReference(); if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFGetCollation(m_hCollection64, retCollationNum); } else { result = notesAPI.b32_NIFGetCollation(m_hCollection32, retCollationNum); } NotesErrorUtils.checkResult(result); return retCollationNum.getValue(); } /** * Changes the collation to sort the collection by the specified column and direction * * @param progColumnName programmatic column name * @param direction sort direction */ public void resortView(String progColumnName, Direction direction) { short collation = findCollation(progColumnName, direction); if (collation==-1) { throw new NotesError(0, "Column "+progColumnName+" does not exist or is not sortable in "+direction+" direction"); } setCollation(collation); } /** * Resets the view sorting to the default (collation=0). Only needs to be called if * view had been resorted via {@link #resortView(String, Direction)} */ public void resetViewSortingToDefault() { setCollation((short) 0); } /** * Sets the active collation (collection column sorting) * * @param collation collation */ private void setCollation(short collation) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFSetCollation(m_hCollection64, collation); } else { result = notesAPI.b32_NIFSetCollation(m_hCollection32, collation); } NotesErrorUtils.checkResult(result); } /** * Returns programmatic names and sorting of sortable columns * * @return info object with collation info */ private CollationInfo getCollationsInfo() { if (m_collationInfo==null) { scanColumns(); } return m_collationInfo; } /** * Returns an iterator of all available columns for which we can read column values * (e.g. does not return static column names) * * @return programmatic column names converted to lowercase in the order they appear in the view */ public Iterator<String> getColumnNames() { if (m_columnIndices==null) { scanColumns(); } return m_columnIndices.keySet().iterator(); } /** * Returns the programmatic column name for a column index * * @param index index * @return column name or null if index is unknown / invalid */ public String getColumnName(int index) { String colName = m_columnNamesByIndex.get(index); return colName; } /** * Returns the number of columns for which we can read column data (e.g. does not count columns * with static values) * * @return number of columns */ public int getNumberOfColumns() { if (m_columnIndices==null) { scanColumns(); } return m_columnIndices.size(); } /** * Returns programmatic names and sorting of sortable columns * * @return info object with collation info */ private void scanColumns() { m_columnIndices = new LinkedHashMap<String, Integer>(); m_columnNamesByIndex = new TreeMap<Integer, String>(); m_columnIsCategoryByIndex = new TreeMap<Integer, Boolean>(); try { //TODO implement this in pure JNA code Database db = m_parentDb.getSession().getDatabase(m_parentDb.getServer(), m_parentDb.getRelativeFilePath()); View view = db.getView(getName()); if (view==null) { throw new NotesError(0, "View "+getName()+" not found using legacy API"); } CollationInfo collationInfo = new CollationInfo(); Vector<?> columns = view.getColumns(); try { short collation = 1; for (int i=0; i<columns.size(); i++) { ViewColumn currCol = (ViewColumn) columns.get(i); String currItemName = currCol.getItemName(); String currItemNameLC = currItemName.toLowerCase(); int currColumnValuesIndex = currCol.getColumnValuesIndex(); m_columnIndices.put(currItemNameLC, currColumnValuesIndex); if (currColumnValuesIndex != ViewColumn.VC_NOT_PRESENT) { m_columnNamesByIndex.put(currColumnValuesIndex, currItemNameLC); boolean isCategory = currCol.isCategory(); m_columnIsCategoryByIndex.put(currColumnValuesIndex, isCategory); } boolean isResortAscending = currCol.isResortAscending(); boolean isResortDescending = currCol.isResortDescending(); if (isResortAscending || isResortDescending) { if (isResortAscending) { collationInfo.addCollation(collation, currItemName, Direction.Ascending); collation++; } if (isResortDescending) { collationInfo.addCollation(collation, currItemName, Direction.Descending); collation++; } } } m_collationInfo = collationInfo; } finally { view.recycle(columns); } } catch (Throwable t) { throw new NotesError(0, "Could not read collation information for view "+getName(), t); } } /** * Container class with view collation information (collation index vs. sort item name and sort direction) * * @author Karsten Lehmann */ private static class CollationInfo { private Map<String,Short> m_ascendingLookup; private Map<String,Short> m_descendingLookup; private Map<Short,String> m_collationSortItem; private Map<Short,Direction> m_collationSorting; private int m_nrOfCollations; /** * Creates a new instance */ public CollationInfo() { m_ascendingLookup = new HashMap<String,Short>(); m_descendingLookup = new HashMap<String,Short>(); m_collationSortItem = new HashMap<Short, String>(); m_collationSorting = new HashMap<Short, NotesCollection.Direction>(); } /** * Internal method to populate the maps * * @param collation collation index * @param itemName sort item name * @param direction sort direction */ void addCollation(short collation, String itemName, Direction direction) { String itemNameLC = itemName.toLowerCase(); if (direction == Direction.Ascending) { m_ascendingLookup.put(itemNameLC, Short.valueOf(collation)); } else if (direction == Direction.Descending) { m_descendingLookup.put(itemNameLC, Short.valueOf(collation)); } m_nrOfCollations = Math.max(m_nrOfCollations, collation); m_collationSorting.put(collation, direction); m_collationSortItem.put(collation, itemNameLC); } /** * Returns the total number of collations * * @return number */ public int getNumberOfCollations() { return m_nrOfCollations; } /** * Finds a collation index * * @param sortItem sort item name * @param direction sort direction * @return collation index or -1 if not found */ public short findCollation(String sortItem, Direction direction) { String itemNameLC = sortItem.toLowerCase(); if (direction==Direction.Ascending) { Short collation = m_ascendingLookup.get(itemNameLC); return collation==null ? -1 : collation.shortValue(); } else { Short collation = m_descendingLookup.get(itemNameLC); return collation==null ? -1 : collation.shortValue(); } } /** * Returns the sort item name of a collation * * @param collation collation index * @return sort item name */ public String getSortItem(int collation) { if (collation > m_nrOfCollations) throw new IndexOutOfBoundsException("Unknown collation index (max value: "+m_nrOfCollations+")"); String sortItem = m_collationSortItem.get(Short.valueOf((short)collation)); return sortItem; } /** * Returns the sort direction of a collation * * @param collation collation index * @return sort direction */ public Direction getSortDirection(int collation) { if (collation > m_nrOfCollations) throw new IndexOutOfBoundsException("Unknown collation index (max value: "+m_nrOfCollations+")"); Direction direction = m_collationSorting.get(Short.valueOf((short)collation)); return direction; } } /** Available column sort directions */ public static enum Direction {Ascending, Descending}; /** * Finds the matching collation nunber for the specified sort column and direction * Convenience method that calls {@link #hashCollations(View)} and {@link CollationInfo#findCollation(String, Direction)} * * @param view view view to search for the collation * @param columnName sort column name * @param direction sort direction * @return collation number or -1 if not found */ private short findCollation(String columnName, Direction direction) { return getCollationsInfo().findCollation(columnName, direction); } /** * Method to check if a note is visible in a view for the current user * * @param noteId note id * @return true if visible */ public boolean isNoteInView(int noteId) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; IntByReference retIsInView = new IntByReference(); if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFIsNoteInView(m_hCollection64, noteId, retIsInView); } else { result = notesAPI.b32_NIFIsNoteInView(m_hCollection32, noteId, retIsInView); } NotesErrorUtils.checkResult(result); boolean isInView = retIsInView.getValue()==1; return isInView; } /** * Method to check if the view index is up to date or if any note has changed in * the database since the last view index update. * * @return true if up to date */ public boolean isUpToDate() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { return notesAPI.b64_NIFCollectionUpToDate(m_hCollection64); } else { return notesAPI.b32_NIFCollectionUpToDate(m_hCollection32); } } /** * Check if the collection is currently being updated * * @return true if being updated */ public boolean isUpdateInProgress() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { return notesAPI.b64_NIFIsUpdateInProgress(m_hCollection64); } else { return notesAPI.b32_NIFIsUpdateInProgress(m_hCollection32); } } /** * Notify of modification to per-user index filters<br> * <br> * This routine must be called by application code when it makes changes * to any of the index filters (unread list, expand/collapse list, * selected list). No handles to the lists are necessary as input * to this function, since the collection context block remembers the * filter handles that were originally specified to the OpenCollection * call.<br> * If the collection is open on a remote server, then the newly * modified lists are re-sent over to the server. If the collection * is "local", then nothing is done. * * @param flags Flags indicating which filters were modified */ public void updateFilters(EnumSet<UpdateCollectionFilters> flags) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short flagsBitmask = UpdateCollectionFilters.toBitMask(flags); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NIFUpdateFilters(m_hCollection64, flagsBitmask); } else { result = notesAPI.b32_NIFUpdateFilters(m_hCollection32, flagsBitmask); } NotesErrorUtils.checkResult(result); } /** * Unfinished alternative lookup method * * @param column first column to return * @param columns other columns to return * @deprecated not ready for prime time * @return selection */ public Selection select(String column, String... columns) { List<String> columnsList = new ArrayList<String>(); columnsList.add(column); if (columns!=null) { for (String currCol : columns) { columnsList.add(currCol); } } String[] columnsArr = columnsList.toArray(new String[columnsList.size()]); return new Selection(columnsArr); } @Override public String toString() { if (isRecycled()) { return "NotesCollection [recycled]"; } else { return "NotesCollection [handle="+(NotesJNAContext.is64Bit() ? m_hCollection64 : m_hCollection32)+", noteid="+getNoteId()+"]"; } } }
package com.mindoo.domino.jna; import java.text.Collator; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import com.mindoo.domino.jna.CollectionDataCache.CacheState; import com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action; import com.mindoo.domino.jna.NotesSearch.ISearchMatch; import com.mindoo.domino.jna.NotesViewEntryData.CacheableViewEntryData; import com.mindoo.domino.jna.constants.FTSearch; import com.mindoo.domino.jna.constants.Find; import com.mindoo.domino.jna.constants.Navigate; import com.mindoo.domino.jna.constants.NoteClass; import com.mindoo.domino.jna.constants.ReadMask; import com.mindoo.domino.jna.constants.Search; import com.mindoo.domino.jna.constants.UpdateCollectionFilters; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.gc.IRecyclableNotesObject; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.internal.Mem32; import com.mindoo.domino.jna.internal.Mem64; import com.mindoo.domino.jna.internal.NotesConstants; import com.mindoo.domino.jna.internal.NotesLookupResultBufferDecoder; import com.mindoo.domino.jna.internal.NotesNativeAPI32; import com.mindoo.domino.jna.internal.NotesNativeAPI64; import com.mindoo.domino.jna.internal.NotesSearchKeyEncoder; import com.mindoo.domino.jna.internal.structs.NotesCollectionDataStruct; import com.mindoo.domino.jna.internal.structs.NotesCollectionPositionStruct; import com.mindoo.domino.jna.internal.structs.NotesTimeDateStruct; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.mindoo.domino.jna.utils.PlatformUtils; import com.mindoo.domino.jna.utils.StringTokenizerExt; import com.mindoo.domino.jna.utils.StringUtil; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; /** * A collection represents a list of notes, comparable to the View object in Notes.jar * * @author Karsten Lehmann */ public class NotesCollection implements IRecyclableNotesObject { private int m_hDB32; private long m_hDB64; private int m_hCollection32; private long m_hCollection64; private String m_name; private List<String> m_aliases; private NotesIDTable m_collapsedList; private NotesIDTable m_selectedList; private String m_viewUNID; private boolean m_noRecycle; private int m_viewNoteId; private IntByReference m_activeFTSearchHandle32; private LongByReference m_activeFTSearchHandle64; private NotesIDTable m_unreadTable; private String m_asUserCanonical; private NotesDatabase m_parentDb; private boolean m_autoUpdate; private CollationInfo m_collationInfo; private Map<String, Integer> m_columnIndicesByItemName; private Map<String, Integer> m_columnIndicesByTitle; private Map<Integer, String> m_columnNamesByIndex; private Map<Integer, Boolean> m_columnIsCategoryByIndex; private Map<Integer, String> m_columnTitlesLCByIndex; private Map<Integer, String> m_columnTitlesByIndex; private NotesNote m_viewNote; private NotesViewFormat m_viewFormat; /** * Creates a new instance, 32 bit mode * * @param parentDb parent database * @param hCollection collection handle * @param viewNoteId view note id * @param viewUNID view UNID * @param collapsedList id table for the collapsed list * @param selectedList id table for the selected list * @param unreadTable id table for the unread list * @param asUserCanonical user used to read the collection data */ public NotesCollection(NotesDatabase parentDb, int hCollection, int viewNoteId, String viewUNID, NotesIDTable collapsedList, NotesIDTable selectedList, NotesIDTable unreadTable, String asUserCanonical) { if (PlatformUtils.is64Bit()) throw new IllegalStateException("Constructor is 32bit only"); m_asUserCanonical = asUserCanonical; m_parentDb = parentDb; m_hDB32 = parentDb.getHandle32(); m_hCollection32 = hCollection; m_viewNoteId = viewNoteId; m_viewUNID = viewUNID; m_collapsedList = collapsedList; m_selectedList = selectedList; m_unreadTable = unreadTable; m_autoUpdate = true; } /** * Creates a new instance, 64 bit mode * * @param parentDb parent database * @param hCollection collection handle * @param viewNoteId view note id * @param viewUNID view UNID * @param collapsedList id table for the collapsed list * @param selectedList id table for the selected list * @param unreadTable id table for the unread list * @param asUserCanonical user used to read the collection data */ public NotesCollection(NotesDatabase parentDb, long hCollection, int viewNoteId, String viewUNID, NotesIDTable collapsedList, NotesIDTable selectedList, NotesIDTable unreadTable, String asUserCanonical) { if (!PlatformUtils.is64Bit()) throw new IllegalStateException("Constructor is 64bit only"); m_asUserCanonical = asUserCanonical; m_parentDb = parentDb; m_hDB64 = parentDb.getHandle64(); m_hCollection64 = hCollection; m_viewNoteId = viewNoteId; m_viewUNID = viewUNID; m_collapsedList = collapsedList; m_selectedList = selectedList; m_unreadTable = unreadTable; m_autoUpdate = true; } /** * Returns the name of the collection * * @return name */ public String getName() { if (m_name==null) { decodeNameAndAliases(); } return m_name; } /** * Returns the collection's selection formula * * @return formula */ public String getSelectionFormula() { NotesNote note = getViewNote(); List<Object> formulaObj = note.getItemValue("$FORMULA"); String formula = formulaObj!=null && !formulaObj.isEmpty() ? formulaObj.get(0).toString() : ""; return formula; } /** * Returns the alias names of the collection * * @return alias names or empty list */ public List<String> getAliases() { if (m_aliases==null) { decodeNameAndAliases(); } return m_aliases; } private void decodeNameAndAliases() { NotesNote viewNote = getViewNote(); List<String> aliases = new ArrayList<String>(); String name = ""; String title = viewNote.getItemValueString("$TITLE"); StringTokenizerExt st = new StringTokenizerExt(title, "|"); if (st.hasMoreTokens()) { name = st.nextToken(); while (st.hasMoreTokens()) { aliases.add(st.nextToken()); } } m_name = name; m_aliases = Collections.unmodifiableList(aliases); } /** * Returns the parent database of this collation * * @return database */ public NotesDatabase getParent() { return m_parentDb; } /** * Method to check whether a collection column contains a category * * @param columnName programmatic column name * @return true if category, false otherwise */ public boolean isCategoryColumn(String columnName) { if (m_columnIsCategoryByIndex==null) { scanColumns(); } int colValuesIndex = getColumnValuesIndex(columnName); Boolean isCategory = m_columnIsCategoryByIndex.get(colValuesIndex); return Boolean.TRUE.equals(isCategory); } /** * Returns the column values index for the specified programmatic column name * or column title * * @param columnNameOrTitle programmatic column name or title, case insensitive * @return index or -1 for unknown columns; returns 65535 for static column values that are not returned as column values */ public int getColumnValuesIndex(String columnNameOrTitle) { if (m_columnIndicesByItemName==null) { scanColumns(); } Integer idx = m_columnIndicesByItemName.get(columnNameOrTitle.toLowerCase()); if (idx==null) { idx = m_columnIndicesByTitle.get(columnNameOrTitle.toLowerCase()); } return idx==null ? -1 : idx.intValue(); } /** * Returns whether the view automatically handles view index updates while reading from the view.<br> * <br> * This flag is used by the methods<br> * <br> * <ul> * <li>{@link #getAllEntries(String, int, EnumSet, int, EnumSet, ViewLookupCallback)}</li> * <li>{@link #getAllEntriesByKey(EnumSet, EnumSet, ViewLookupCallback, Object...)}</li> * <li>{@link #getAllIds(Navigate)}</li> * <li>{@link #getAllIdsByKey(EnumSet, Object...)}</li> * </ul> * @return true if auto update */ public boolean isAutoUpdate() { return m_autoUpdate; } /** * Changes the auto update flag, which indicates whether the view automatically handles view index * updates while reading from the view.<br> * <br> * This flag is used by the methods<br> * <br> * <ul> * <li>{@link #getAllEntries(String, int, EnumSet, int, EnumSet, ViewLookupCallback)}</li> * <li>{@link #getAllEntriesByKey(EnumSet, EnumSet, ViewLookupCallback, Object...)}</li> * <li>{@link #getAllIds(Navigate)}</li> * <li>{@link #getAllIdsByKey(EnumSet, Object...)}</li> * </ul> * @param update true to activate auto update */ public void setAutoUpdate(boolean update) { m_autoUpdate = update; } /** * Returns the index modified sequence number that can be used to track view changes. * The method calls {@link #getLastModifiedTime()} and returns part of the result (Innards[0]). * We found out by testing that this value is the same that NIFFindByKeyExtended2 returns. * * @return index modified sequence number */ public int getIndexModifiedSequenceNo() { NotesTimeDate ndtModified = getLastModifiedTime(); return ndtModified.getInnardsNoClone()[0]; } /** * Each time the number of documents in a collection is modified, a sequence number * is incremented. This function will return the modification sequence number, which * may then be compared to a previous value (also obtained by calling * NIFGetLastModifiedTime()) to determine whether or not the number of documents in the * collection has been changed.<br> * <br>Note that the TIMEDATE value returned by this function is not an actual time. * * @return time date */ public NotesTimeDate getLastModifiedTime() { NotesTimeDateStruct retLastModifiedTime = NotesTimeDateStruct.newInstance(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NIFGetLastModifiedTime(m_hCollection64, retLastModifiedTime); } else { NotesNativeAPI32.get().NIFGetLastModifiedTime(m_hCollection32, retLastModifiedTime); } return new NotesTimeDate(retLastModifiedTime); } /** * Returns the {@link NotesTimeDate} when this view was last accessed * * @return last access date/time */ public NotesTimeDate getLastAccessedTime() { NotesTimeDateStruct retLastAccessedTime = NotesTimeDateStruct.newInstance(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NIFGetLastAccessedTime(m_hCollection64, retLastAccessedTime); } else { NotesNativeAPI32.get().NIFGetLastAccessedTime(m_hCollection32, retLastAccessedTime); } return new NotesTimeDate(retLastAccessedTime); } /** * Returns the {@link NotesTimeDate} when the view index will be discarded * * @return discard date/time */ public NotesTimeDate getNextDiscardTime() { NotesTimeDateStruct retNextDiscardTime = NotesTimeDateStruct.newInstance(); if (PlatformUtils.is64Bit()) { NotesNativeAPI64.get().NIFGetNextDiscardTime(m_hCollection64, retNextDiscardTime); } else { NotesNativeAPI32.get().NIFGetNextDiscardTime(m_hCollection32, retNextDiscardTime); } return new NotesTimeDate(retNextDiscardTime); } /** * This function adds the document(s) specified in an ID Table to this folder. * Throws an error if {@link #isFolder()} is <code>false</code>. * * @param idTable id table * @throws NotesError with id 947 (Attempt to perform folder operation on non-folder note) if not a folder */ public void addToThisFolder(NotesIDTable idTable) { if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().FolderDocAdd(m_hDB64, 0, m_viewNoteId, idTable.getHandle64(), 0); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().FolderDocAdd(m_hDB32, 0, m_viewNoteId, idTable.getHandle32(), 0); NotesErrorUtils.checkResult(result); } } /** * This function adds the document(s) specified as note id set to this folder. * Throws an error if {@link #isFolder()} is <code>false</code>. * * @param noteIds ids of notes to add * @throws NotesError with id 947 (Attempt to perform folder operation on non-folder note) if not a folder */ public void addToThisFolder(Collection<Integer> noteIds) { NotesIDTable idTable = new NotesIDTable(); try { idTable.addNotes(noteIds); addToThisFolder(idTable); } finally { idTable.recycle(); } } /** * This function removes the document(s) specified in an ID Table from a folder. * * @param idTable id table */ public void removeFromFolder(NotesIDTable idTable) { if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().FolderDocRemove(m_hDB64, 0, m_viewNoteId, idTable.getHandle64(), 0); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().FolderDocRemove(m_hDB32, 0, m_viewNoteId, idTable.getHandle32(), 0); NotesErrorUtils.checkResult(result); } } /** * This function removes the document(s) specified as note id set from a folder. * * @param noteIds ids of notes to remove */ public void removeFromFolder(Set<Integer> noteIds) { NotesIDTable idTable = new NotesIDTable(); try { idTable.addNotes(noteIds); removeFromFolder(idTable); } finally { idTable.recycle(); } } /** * This function removes all documents from a specified folder.<br> * <br> * Subfolders and documents within the subfolders are not removed. */ public void removeAllFromFolder() { if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().FolderDocRemoveAll(m_hDB64, 0, m_viewNoteId, 0); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().FolderDocRemoveAll(m_hDB32, 0, m_viewNoteId, 0); NotesErrorUtils.checkResult(result); } } /** * This function moves the specified folder under a given parent folder.<br> * <br> * If the parent folder is a shared folder, then the child folder must be a shared folder.<br> * If the parent folder is a private folder, then the child folder must be a private folder. * * @param newParentFolder parent folder */ public void moveFolder(NotesCollection newParentFolder) { if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().FolderMove(m_hDB64, 0, m_viewNoteId, 0, newParentFolder.getNoteId(), 0); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().FolderMove(m_hDB32, 0, m_viewNoteId, 0, newParentFolder.getNoteId(), 0); NotesErrorUtils.checkResult(result); } } /** * This function renames the specified folder and its subfolders. * * @param name new folder name */ public void renameFolder(String name) { Memory pszName = NotesStringUtils.toLMBCS(name, false); if (pszName.size() > NotesConstants.DESIGN_FOLDER_MAX_NAME) { throw new IllegalArgumentException("Folder name too long (max "+NotesConstants.DESIGN_FOLDER_MAX_NAME+" bytes, found "+pszName.size()+" bytes)"); } if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().FolderRename(m_hDB64, 0, m_viewNoteId, pszName, (short) pszName.size(), 0); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().FolderRename(m_hDB32, 0, m_viewNoteId, pszName, (short) pszName.size(), 0); NotesErrorUtils.checkResult(result); } } /** * This function returns the number of entries in the specified folder's index.<br> * <br> * This is the number of documents plus the number of cateogories (if any) in the folder.<br> * <br> * Subfolders and documents in subfolders are not included in the count. * * @return count */ public long getFolderDocCount() { if (PlatformUtils.is64Bit()) { LongByReference pdwNumDocs = new LongByReference(); short result = NotesNativeAPI64.get().FolderDocCount(m_hDB64, 0, m_viewNoteId, 0, pdwNumDocs); NotesErrorUtils.checkResult(result); return pdwNumDocs.getValue(); } else { LongByReference pdwNumDocs = new LongByReference(); short result = NotesNativeAPI32.get().FolderDocCount(m_hDB32, 0, m_viewNoteId, 0, pdwNumDocs); NotesErrorUtils.checkResult(result); return pdwNumDocs.getValue(); } } /** * Returns an id table of the folder content * * @param validateIds If set, return only "validated" noteIDs * @return id table */ public NotesIDTable getIDTableForFolder(boolean validateIds) { if (PlatformUtils.is64Bit()) { LongByReference hTable = new LongByReference(); short result = NotesNativeAPI64.get().NSFFolderGetIDTable(m_hDB64, m_hDB64, m_viewNoteId, validateIds ? NotesConstants.DB_GETIDTABLE_VALIDATE : 0, hTable); NotesErrorUtils.checkResult(result); //don't auto-gc the ID table, since there is no remark in the C API that we are responsible return new NotesIDTable(hTable.getValue(), true); } else { IntByReference hTable = new IntByReference(); short result = NotesNativeAPI32.get().NSFFolderGetIDTable(m_hDB32, m_hDB32, m_viewNoteId, validateIds ? NotesConstants.DB_GETIDTABLE_VALIDATE : 0, hTable); NotesErrorUtils.checkResult(result); //don't auto-gc the ID table, since there is no remark in the C API that we are responsible return new NotesIDTable(hTable.getValue(), true); } } /** * Method to check whether a skip or return navigator returns view data from last to first entry * * @param nav navigator mode * @return true if descending */ public static boolean isDescendingNav(EnumSet<Navigate> nav) { boolean descending = nav.contains(Navigate.PREV) || nav.contains(Navigate.PREV_CATEGORY) || nav.contains(Navigate.PREV_EXP_NONCATEGORY) || nav.contains(Navigate.PREV_EXPANDED) || nav.contains(Navigate.PREV_EXPANDED_CATEGORY) || nav.contains(Navigate.PREV_EXPANDED_SELECTED) || nav.contains(Navigate.PREV_EXPANDED_UNREAD) || nav.contains(Navigate.PREV_HIT) || nav.contains(Navigate.PREV_MAIN) || nav.contains(Navigate.PREV_NONCATEGORY) || nav.contains(Navigate.PREV_PARENT) || nav.contains(Navigate.PREV_PEER) || nav.contains(Navigate.PREV_SELECTED) || nav.contains(Navigate.PREV_SELECTED_HIT) || nav.contains(Navigate.PREV_SELECTED_MAIN) || nav.contains(Navigate.PREV_UNREAD) || nav.contains(Navigate.PREV_UNREAD_HIT) || nav.contains(Navigate.PREV_UNREAD_MAIN) || nav.contains(Navigate.PARENT); return descending; } /** * Method to reverse the traversal order, e.g. from {@link Navigate#NEXT} to * {@link Navigate#PREV}. * * @param nav nav constant * @return reversed constant */ public static Navigate reverseNav(Navigate nav) { switch (nav) { case PARENT: return Navigate.CHILD; case CHILD: return Navigate.PARENT; case NEXT_PEER: return Navigate.PREV_PEER; case PREV_PEER: return Navigate.NEXT_PEER; case FIRST_PEER: return Navigate.LAST_PEER; case LAST_PEER: return Navigate.FIRST_PEER; case NEXT_MAIN: return Navigate.PREV_MAIN; case PREV_MAIN: return Navigate.NEXT_MAIN; case NEXT_PARENT: return Navigate.PREV_PARENT; case PREV_PARENT: return Navigate.NEXT_PARENT; case NEXT: return Navigate.PREV; case PREV: return Navigate.NEXT; case NEXT_UNREAD: return Navigate.PREV_UNREAD; case NEXT_UNREAD_MAIN: return Navigate.PREV_UNREAD_MAIN; case PREV_UNREAD_MAIN: return Navigate.NEXT_UNREAD_MAIN; case PREV_UNREAD: return Navigate.NEXT_UNREAD; case NEXT_SELECTED: return Navigate.PREV_SELECTED; case PREV_SELECTED: return Navigate.NEXT_SELECTED; case NEXT_SELECTED_MAIN: return Navigate.PREV_SELECTED_MAIN; case PREV_SELECTED_MAIN: return Navigate.NEXT_SELECTED_MAIN; case NEXT_EXPANDED: return Navigate.PREV_EXPANDED; case PREV_EXPANDED: return Navigate.NEXT_EXPANDED; case NEXT_EXPANDED_UNREAD: return Navigate.PREV_EXPANDED_UNREAD; case PREV_EXPANDED_UNREAD: return Navigate.NEXT_EXPANDED_UNREAD; case NEXT_EXPANDED_SELECTED: return Navigate.PREV_EXPANDED_SELECTED; case PREV_EXPANDED_SELECTED: return Navigate.NEXT_EXPANDED_SELECTED; case NEXT_EXPANDED_CATEGORY: return Navigate.PREV_EXPANDED_CATEGORY; case PREV_EXPANDED_CATEGORY: return Navigate.NEXT_EXPANDED_CATEGORY; case NEXT_EXP_NONCATEGORY: return Navigate.PREV_EXP_NONCATEGORY; case PREV_EXP_NONCATEGORY: return Navigate.NEXT_EXP_NONCATEGORY; case NEXT_HIT: return Navigate.PREV_HIT; case PREV_HIT: return Navigate.NEXT_HIT; case NEXT_SELECTED_HIT: return Navigate.PREV_SELECTED_HIT; case PREV_SELECTED_HIT: return Navigate.NEXT_SELECTED_HIT; case NEXT_UNREAD_HIT: return Navigate.PREV_UNREAD_HIT; case PREV_UNREAD_HIT: return Navigate.NEXT_UNREAD_HIT; case NEXT_CATEGORY: return Navigate.PREV_CATEGORY; case PREV_CATEGORY: return Navigate.NEXT_CATEGORY; case NEXT_NONCATEGORY: return Navigate.PREV_NONCATEGORY; case PREV_NONCATEGORY: return Navigate.NEXT_NONCATEGORY; default: return nav; } } public boolean isRecycled() { if (PlatformUtils.is64Bit()) { return m_hCollection64==0; } else { return m_hCollection32==0; } } public void recycle() { if (!m_noRecycle) { boolean bHandleIsNull = false; if (PlatformUtils.is64Bit()) { bHandleIsNull = m_hCollection64==0; } else { bHandleIsNull = m_hCollection32==0; } if (!bHandleIsNull) { clearSearch(); if (m_unreadTable!=null && !m_unreadTable.isRecycled()) { m_unreadTable.recycle(); } short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFCloseCollection(m_hCollection64); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(NotesCollection.class, this); m_hCollection64=0; } else { result = NotesNativeAPI32.get().NIFCloseCollection(m_hCollection32); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(NotesCollection.class, this); m_hCollection32=0; } } } } public void setNoRecycle() { m_noRecycle=true; } @Override public boolean isNoRecycle() { return m_noRecycle; } private void checkHandle() { if (PlatformUtils.is64Bit()) { if (m_hCollection64==0) throw new NotesError(0, "Collection already recycled"); NotesGC.__b64_checkValidObjectHandle(NotesCollection.class, m_hCollection64); } else { if (m_hCollection32==0) throw new NotesError(0, "Collection already recycled"); NotesGC.__b32_checkValidObjectHandle(NotesCollection.class, m_hCollection32); } } public int getNoteId() { return m_viewNoteId; } public String getUNID() { return m_viewUNID; } public int getHandle32() { return m_hCollection32; } public long getHandle64() { return m_hCollection64; } /** * Returns the user for which the collation returns the data * * @return null for server */ public String getContextUser() { return m_asUserCanonical; } /** * Returns the unread table.<br>Adding note ids * to this table causes the notes to be found in view lookups using {@link Navigate#NEXT_UNREAD} * and similar flags.<br> * <br> * For remote databases, do not forget to call {@link #updateFilters(EnumSet)} * after you are done modifying the table to re-send the list to the server. * * @return unread table */ public NotesIDTable getUnreadTable() { return m_unreadTable; } /** * Returns the collapsed list. Can be used to tell Domino which categories are * expanded/collapsed.<br> Adding note ids * to this table causes the notes to be found in view lookups using {@link Navigate#NEXT_EXPANDED}, * {@link Navigate#NEXT_EXPANDED_CATEGORY}, {@link Navigate#NEXT_EXPANDED_SELECTED} or * {@link Navigate#NEXT_EXPANDED_UNREAD}.<br> * <br> * For remote databases, do not forget to call {@link #updateFilters(EnumSet)} * after you are done modifying the table to re-send the list to the server. * * @return collapsed list */ public NotesIDTable getCollapsedList() { return m_collapsedList; } /** * Returns an id table of "selected" note ids; adding note ids * to this table causes the notes to be found in view lookups using {@link Navigate#NEXT_SELECTED} * and similar flags.<br> * <br> * For remote databases, do not forget to call {@link #updateFilters(EnumSet)} * after you are done modifying the table to re-send the list to the server. * * @return selected list */ public NotesIDTable getSelectedList() { return m_selectedList; } /** * Performs a fulltext search in the collection, storing the search result in the collection, * which means that navigating via {@link Navigate#NEXT_HIT} jumps from one search hit to the next * (setting {@link FTSearch#SET_COLL} option manually is not required). * * @param query fulltext query * @param limit max entries to return or 0 to get all * @param options FTSearch flags * @return search result */ public SearchResult ftSearch(String query, int limit, EnumSet<FTSearch> options) { return ftSearch(query, limit, options, null); } /** * Performs a fulltext search in the collection, storing the search result in the collection, * which means that navigating via {@link Navigate#NEXT_HIT} jumps from one search hit to the next * (setting {@link FTSearch#SET_COLL} option manually is not required). * * @param query fulltext query * @param limit max entries to return or 0 to get all * @param options FTSearch flags * @param filterIDTable optional ID table to refine the search * @return search result */ public SearchResult ftSearch(String query, int limit, EnumSet<FTSearch> options, NotesIDTable filterIDTable) { clearSearch(); if (limit<0 || limit>65535) throw new IllegalArgumentException("Limit must be between 0 and 65535 (WORD datatype in C API)"); short result; if (PlatformUtils.is64Bit()) { m_activeFTSearchHandle64 = new LongByReference(); m_activeFTSearchHandle64.setValue(0); result = NotesNativeAPI64.get().FTOpenSearch(m_activeFTSearchHandle64); NotesErrorUtils.checkResult(result); } else { m_activeFTSearchHandle32 = new IntByReference(); m_activeFTSearchHandle32.setValue(0); result = NotesNativeAPI32.get().FTOpenSearch(m_activeFTSearchHandle32); NotesErrorUtils.checkResult(result); } Memory queryLMBCS = NotesStringUtils.toLMBCS(query, true); IntByReference retNumDocs = new IntByReference(); //always filter view data EnumSet<FTSearch> optionsWithView = options.clone(); optionsWithView.add(FTSearch.SET_COLL); if (filterIDTable!=null) { //automatically set refine option if id table is not null optionsWithView.add(FTSearch.REFINE); } int optionsWithViewBitMask = FTSearch.toBitMask(optionsWithView); short limitShort = (short) (limit & 0xffff); if (PlatformUtils.is64Bit()) { LongByReference rethResults = new LongByReference(); result = NotesNativeAPI64.get().FTSearch( m_hDB64, m_activeFTSearchHandle64, m_hCollection64, queryLMBCS, optionsWithViewBitMask, limitShort, filterIDTable==null ? 0 : filterIDTable.getHandle64(), retNumDocs, new Memory(Pointer.SIZE), // Reserved field rethResults); if (result == 3874) { //handle special error code: no documents found return new SearchResult(null, 0); } NotesErrorUtils.checkResult(result); NotesIDTable resultsIdTable = null; long hResults = rethResults.getValue(); if (hResults!=0) { resultsIdTable = new NotesIDTable(rethResults.getValue(), false); } if (options.contains(FTSearch.RET_IDTABLE) && resultsIdTable==null) { resultsIdTable = new NotesIDTable(); } return new SearchResult(resultsIdTable, retNumDocs.getValue()); } else { IntByReference rethResults = new IntByReference(); result = NotesNativeAPI32.get().FTSearch( m_hDB32, m_activeFTSearchHandle32, m_hCollection32, queryLMBCS, optionsWithViewBitMask, limitShort, filterIDTable==null ? 0 : filterIDTable.getHandle32(), retNumDocs, new Memory(Pointer.SIZE), // Reserved field rethResults); if (result == 3874) { //handle special error code: no documents found return new SearchResult(null, 0); } NotesErrorUtils.checkResult(result); NotesIDTable resultsIdTable = null; int hResults = rethResults.getValue(); if (hResults!=0) { resultsIdTable = new NotesIDTable(rethResults.getValue(), false); } if (options.contains(FTSearch.RET_IDTABLE) && resultsIdTable==null) { resultsIdTable = new NotesIDTable(); } return new SearchResult(resultsIdTable, retNumDocs.getValue()); } } /** * Container for a FT search result * * @author Karsten Lehmann */ public static class SearchResult { private NotesIDTable m_matchesIDTable; private int m_numDocs; public SearchResult(NotesIDTable matchesIDTable, int numDocs) { m_matchesIDTable = matchesIDTable; m_numDocs = numDocs; } public int getNumDocs() { return m_numDocs; } public NotesIDTable getMatches() { return m_matchesIDTable; } } /** * Resets an active filtering cause by a FT search */ public void clearSearch() { checkHandle(); if (PlatformUtils.is64Bit()) { if (m_activeFTSearchHandle64!=null) { long handle = m_activeFTSearchHandle64.getValue(); if (handle!=0) { short result = NotesNativeAPI64.get().FTCloseSearch(handle); NotesErrorUtils.checkResult(result); } m_activeFTSearchHandle64=null; } } else { if (m_activeFTSearchHandle32!=null) { int handle = m_activeFTSearchHandle32.getValue(); if (handle!=0) { short result = NotesNativeAPI32.get().FTCloseSearch(handle); NotesErrorUtils.checkResult(result); } m_activeFTSearchHandle32=null; } } } /** * Locates a note in the collection * * @param noteId note id * @return collection position * @throws NotesError if not found */ public String locateNote(int noteId) { checkHandle(); NotesCollectionPositionStruct foundPos = NotesCollectionPositionStruct.newInstance(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFLocateNote(m_hCollection64, foundPos, noteId); } else { result = NotesNativeAPI32.get().NIFLocateNote(m_hCollection32, foundPos, noteId); } NotesErrorUtils.checkResult(result); return foundPos.toPosString(); } /** * Locates a note in the collection * * @param noteId note id as hex string * @return collection position * @throws NotesError if not found */ public String locateNote(String noteId) { return locateNote(Integer.parseInt(noteId, 16)); } /** * Convenience function that returns a sorted set of note ids of documents * matching the specified search key(s) in the collection * * @param findFlags find flags, see {@link Find} * @param keys lookup keys * @return note ids */ public LinkedHashSet<Integer> getAllIdsByKey(EnumSet<Find> findFlags, Object... keys) { LinkedHashSet<Integer> noteIds = getAllEntriesByKey(findFlags, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<LinkedHashSet<Integer>>() { @Override public LinkedHashSet<Integer> startingLookup() { return new LinkedHashSet<Integer>(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead( LinkedHashSet<Integer> result, NotesViewEntryData entryData) { result.add(entryData.getNoteId()); return Action.Continue; } @Override public LinkedHashSet<Integer> lookupDone(LinkedHashSet<Integer> result) { return result; } }, keys); return noteIds; } /** * Method to check whether an optimized view lookup method can be used for * a set of find/return flags and the current Domino version * * @param findFlags find flags * @param returnMask return flags * @param keys lookup keys * @return true if method can be used */ private boolean canUseOptimizedLookupForKeyLookup(EnumSet<Find> findFlags, EnumSet<ReadMask> returnMask, Object... keys) { if (findFlags.contains(Find.GREATER_THAN) || findFlags.contains(Find.LESS_THAN)) { //TODO check this with IBM dev; we had crashes like "[0A0F:0002-21A00] PANIC: LookupHandle: null handle" using NIFFindByKeyExtended2 return false; } { //we had "ERR 774: Unsupported return flag(s)" errors when using the optimized lookup //method with other return values other than note id boolean unsupportedValuesFound = false; for (ReadMask currReadMaskValues: returnMask) { if ((currReadMaskValues != ReadMask.NOTEID) && (currReadMaskValues != ReadMask.SUMMARY)) { unsupportedValuesFound = true; break; } } if (unsupportedValuesFound) { return false; } } { //check for R9 and flag compatibility short buildVersion = m_parentDb.getParentServerBuildVersion(); if (buildVersion < 400) { return false; } } return true; } /** * Callback base class used to process collection lookup results * * @author Karsten Lehmann */ public static abstract class ViewLookupCallback<T> { public enum Action {Continue, Stop}; private NotesTimeDate m_newDiffTime; /** * The method is called when the view lookup is (re-)started. If the view * index is modified while reading, the view read operation restarts from * the beginning. * * @return result object that is passed to {@link #entryRead(Object, NotesViewEntryData)} */ public abstract T startingLookup(); /** * Override this method to return the programmatic name of a collection column. If * a non-null value is returned, we use an optimized lookup method to read the data, * resulting in much better performance (working like the formula @DbColumn) * * @return programmatic column name or null */ public String getNameForSingleColumnRead() { return null; } /** * Implement this method to process a read entry directly or add it to a result object.<br> * Please note: If you process the entry directly, keep in mind that the lookup * may restart when a view index change is detected. * * @param result context * @param entryData entry data * @return action (whether the lookup should continue) */ public abstract Action entryRead(T result, NotesViewEntryData entryData); /** * This method gets called when a view index change has been detected * during a view read operation which would cause the operation to be restarted. * Add your own code to log these retries or decide to stop reading when too * much time has passed * * @param nrOfRetries number of retries already made (0 = first retry is about to begin) * @param durationSinceStart number of milliseconds elapsed since starting the lookup * @return action, whether to continue (default) or stop the lookup; if stop, the lookup method returns null; as an alternative, throw a {@link RuntimeException} here to jump out of the lookup function without return value */ public Action retryingReadBecauseViewIndexChanged(int nrOfRetries, long durationSinceStart) { return Action.Continue; } /** * The method is called when differential view reading is used to return the {@link NotesTimeDate} * to be used for the next lookups * * @param newDiffTime new diff time */ public void setNewDiffTime(NotesTimeDate newDiffTime) { m_newDiffTime = newDiffTime; } /** * Use this method to read the {@link NotesTimeDate} to be used for the next lookups when using differential view * reads * * @return diff time or null */ public NotesTimeDate getNewDiffTime() { return m_newDiffTime; } /** * Override this method to return an optional {@link CollectionDataCache} to speed up view reading. * The returned cache instance is shared for all calls done with this callback implementation.<br> * <br> * Please note that according to IBM dev, this optimized view reading (differential view reads) does * only work in views that are not permuted (where documents do not appear multiple times, because * "Show multiple values as separate entries" has been set on any view column). * * @return cache or null (default value) */ public CollectionDataCache createDataCache() { return null; } private CollectionDataCache m_cacheInstance; /** * Standard implementation of this method calls {@link #createDataCache()} once * and stores the object instance in a member variable for later reuse.<br> * Can be overridden in case you need to store the cache somewhere else, * e.g. to reuse it later on. * * @return cache */ public CollectionDataCache getDataCache() { if (m_cacheInstance==null) { m_cacheInstance = createDataCache(); } return m_cacheInstance; } /** * Method is called when the lookup process is done * * @param result result object * @return result or transformed result */ public abstract T lookupDone(T result); } /** * Subclass of {@link ViewLookupCallback} that wraps any methods and forwards all calls * the another {@link ViewLookupCallback}. * * @author Karsten Lehmann */ public static class ViewLookupCallbackWrapper<T> extends ViewLookupCallback<T> { private ViewLookupCallback<T> m_innerCallback; public ViewLookupCallbackWrapper(ViewLookupCallback<T> innerCallback) { m_innerCallback = innerCallback; } @Override public String getNameForSingleColumnRead() { return m_innerCallback.getNameForSingleColumnRead(); } @Override public T startingLookup() { return m_innerCallback.startingLookup(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(T result, NotesViewEntryData entryData) { return m_innerCallback.entryRead(result, entryData); } @Override public CollectionDataCache createDataCache() { return m_innerCallback.createDataCache(); } @Override public NotesTimeDate getNewDiffTime() { return m_innerCallback.getNewDiffTime(); } @Override public void setNewDiffTime(NotesTimeDate newDiffTime) { m_innerCallback.setNewDiffTime(newDiffTime); } @Override public T lookupDone(T result) { return m_innerCallback.lookupDone(result); } @Override public Action retryingReadBecauseViewIndexChanged(int nrOfRetries, long durationSinceStart) { return m_innerCallback.retryingReadBecauseViewIndexChanged(nrOfRetries, durationSinceStart); } } /** * Subclass of {@link ViewLookupCallback} that uses an optimized view lookup to * only read the value of a single collection column. This results in much * better performance, because the 64K summary buffer is not polluted with irrelevant data.<br> * <br> * Please make sure to pass either {@link ReadMask#SUMMARYVALUES} or {@link ReadMask#SUMMARY}, * preferably {@link ReadMask#SUMMARYVALUES}. * * @author Karsten Lehmann */ public static class ReadSingleColumnValues extends ViewLookupCallback<Set<String>> { private String m_columnName; private Locale m_sortLocale; /** * Creates a new instance * * @param columnName programmatic column name * @param sortLocale optional sort locale used to sort the result */ public ReadSingleColumnValues(String columnName, Locale sortLocale) { m_columnName = columnName; m_sortLocale = sortLocale; } @Override public String getNameForSingleColumnRead() { return m_columnName; } @Override public Set<String> startingLookup() { Collator collator = Collator.getInstance(m_sortLocale==null ? Locale.getDefault() : m_sortLocale); return new TreeSet<String>(collator); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(Set<String> result, NotesViewEntryData entryData) { String colValue = entryData.getAsString(m_columnName, null); if (colValue!=null) { result.add(colValue); } return com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action.Continue; } @Override public Set<String> lookupDone(Set<String> result) { return result; } } /** * Subclass of {@link ViewLookupCallback} that stores the data of read collection entries * in a {@link List}. * * @author Karsten Lehmann */ public static class EntriesAsListCallback extends ViewLookupCallback<List<NotesViewEntryData>> { private int m_maxEntries; /** * Creates a new instance * * @param maxEntries maximum entries to return */ public EntriesAsListCallback(int maxEntries) { m_maxEntries = maxEntries; } @Override public List<NotesViewEntryData> startingLookup() { return new ArrayList<NotesViewEntryData>(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead( List<NotesViewEntryData> result, NotesViewEntryData entryData) { if (m_maxEntries==0) { return Action.Stop; } if (!isAccepted(entryData)) { //ignore this entry return Action.Continue; } //add entry to result list result.add(entryData); if (result.size() >= m_maxEntries) { //stop the lookup, we have enough data return Action.Stop; } else { //go on reading the view return Action.Continue; } } /** * Override this method to filter entries * * @param entryData current entry * @return true if entry should be added to the result */ protected boolean isAccepted(NotesViewEntryData entryData) { return true; } @Override public List<NotesViewEntryData> lookupDone(List<NotesViewEntryData> result) { return result; } } /** * Fast method to count view entries taking read access rights into account.<br> * <br> * Traverses the view index from start to end with the specified navigation strategy * counting the visited and readable rows. As navigation strategy, use * {@link Navigate#NEXT_NONCATEGORY} to move from one document to the next, * {@link Navigate#NEXT_CATEGORY} to move between categories only or * {@link Navigate#NEXT_SELECTED} to move between selected entries previously set via * {@link NotesCollection#select(Collection, boolean)}. * * @param navigator navigation strategory * @return number of entries visited */ public int getEntryCount(Navigate navigator) { EnumSet<Navigate> skipNavigator = EnumSet.of(Navigate.CONTINUE); skipNavigator.add(navigator); //start at position "0" (right before the first view entry), //and skip over the whole view counting entries and not reading any row data NotesViewLookupResultData skipResult = readEntries(new NotesCollectionPosition("0"), skipNavigator, Integer.MAX_VALUE, EnumSet.of(Navigate.CURRENT), 0, EnumSet.of(ReadMask.NOTEID)); return skipResult.getSkipCount(); } /** * Very fast scan function that populates a {@link NotesIDTable} with note ids in the * collection. Uses an undocumented C API call internally. Since the {@link NotesIDTable} * is sorted in ascending note id order, this method does not keep the original view order. * Use {@link NotesCollection#getAllIds(Navigate)} to get an ID list sorted in view order.<br> * <br> * Please note:<br> * With <code>filterTable</code> set to <code>false</code> and by using the navigator {@link Navigate#NEXT}, * it is more likely for the used C API function to reuse a cached ID table of all the note ids in * the view, resulting in much better performance. <b>It's important that the response hierarchy * flag is disable in the view design for this optimization to work.</b> * * @param navigator use {@link Navigate#NEXT} to read documents and categories, {@link Navigate#NEXT_CATEGORY} to only read categories and {@link Navigate#NEXT_NONCATEGORY} to only read documents * @param filterTable true to filter the ID table to entries visible for the current user * @param idTable table to populate with note ids */ public void getAllIds(Navigate navigator, boolean filterTable, NotesIDTable idTable) { checkHandle(); if (PlatformUtils.is64Bit()) { short result = NotesNativeAPI64.get().NIFGetIDTableExtended(m_hCollection64, Navigate.toBitMask(EnumSet.of(navigator)), (short) (filterTable ? 0 : 1), idTable.getHandle64()); NotesErrorUtils.checkResult(result); } else { short result = NotesNativeAPI32.get().NIFGetIDTableExtended(m_hCollection32, Navigate.toBitMask(EnumSet.of(navigator)), (short) (filterTable ? 0 : 1), idTable.getHandle32()); NotesErrorUtils.checkResult(result); } } /** * Convenience method that collects all note ids in the view, in the sort order of the current collation * * @param navigator use {@link Navigate#NEXT} to read documents and categories, {@link Navigate#NEXT_CATEGORY} to only read categories and {@link Navigate#NEXT_NONCATEGORY} to only read documents * @return set of note ids, sorted by occurence in the collection */ public LinkedHashSet<Integer> getAllIds(Navigate navigator) { LinkedHashSet<Integer> ids = getAllEntries("0", 1, EnumSet.of(navigator), Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<LinkedHashSet<Integer>>() { @Override public LinkedHashSet<Integer> startingLookup() { return new LinkedHashSet<Integer>(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead( LinkedHashSet<Integer> ctx, NotesViewEntryData entryData) { ctx.add(entryData.getNoteId()); return Action.Continue; } @Override public LinkedHashSet<Integer> lookupDone(LinkedHashSet<Integer> result) { return result; } }); return ids; } /** * Reads all values of a collection column * * @param columnName programmatic column name * @param sortLocale optional sort locale to sort the values; if null, we use the locale returned by {@link Locale#getDefault()} * @return column values */ public Set<String> getColumnValues(String columnName, Locale sortLocale) { boolean isCategory = isCategoryColumn(columnName); Navigate nav = isCategory ? Navigate.NEXT_CATEGORY : Navigate.NEXT_NONCATEGORY; return getAllEntries("0", 1, EnumSet.of(nav), Integer.MAX_VALUE, EnumSet.of(ReadMask.SUMMARYVALUES), new ReadSingleColumnValues(columnName, sortLocale)); } /** * The method reads a number of entries located under a specified category from the collection/view. * It internally takes care of view index changes while reading view data and restarts reading * if such a change has been detected. * * @param <T> result data type * * @param category category or catlevel1\catlevel2 structure * @param skipCount number of entries to skip * @param returnNav navigator to specify how to move in the collection * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result */ public <T> T getAllEntriesInCategory(String category, int skipCount, EnumSet<Navigate> returnNav, int preloadEntryCount, EnumSet<ReadMask> returnMask, final ViewLookupCallback<T> callback) { return getAllEntriesInCategory(category, skipCount, returnNav, null, null, preloadEntryCount, returnMask, callback); } /** * Convenience method that reads all note ids located under a category * * @param category category * @param returnNav navigator to be used to scan for collection entries * @return ids in view order */ public LinkedHashSet<Integer> getAllIdsInCategory(String category, EnumSet<Navigate> returnNav) { return getAllEntriesInCategory(category, 0, returnNav, Integer.MAX_VALUE, EnumSet.of(ReadMask.NOTEID), new ViewLookupCallback<LinkedHashSet<Integer>>() { @Override public LinkedHashSet<Integer> startingLookup() { return new LinkedHashSet<Integer>(); } @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead( LinkedHashSet<Integer> ctx, NotesViewEntryData entryData) { ctx.add(entryData.getNoteId()); return Action.Continue; } @Override public LinkedHashSet<Integer> lookupDone(LinkedHashSet<Integer> result) { return result; } }); } /** * The method reads a number of entries located under a specified category from the collection/view. * It internally takes care of view index changes while reading view data and restarts reading * if such a change has been detected. * * @param <T> result data type * * @param category category or catlevel1\catlevel2 structure * @param skipCount number of entries to skip * @param returnNav navigator to specify how to move in the collection * @param diffTime If non-null, this is a "differential view read" meaning that the caller wants * us to optimize things by only returning full information for notes which have * changed (or are new) in the view, return just NoteIDs for notes which haven't * changed since this time and return a deleted ID table for notes which may be * known by the caller and have been deleted since DiffTime. * <b>Please note that "differential view reads" do only work in views without permutations (no columns with "show multiple values as separate entries" set) according to IBM. Otherwise, all the view data is always returned.</b> * @param diffIDTable If DiffTime is non-null and DiffIDTable is not null it provides a * list of notes which the caller has current information on. We use this to * know which notes we can return shortened information for (i.e., just the NoteID) * and what notes we might have to include in the returned DelNoteIDTable. * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result */ public <T> T getAllEntriesInCategory(final String category, int skipCount, EnumSet<Navigate> returnNav, NotesTimeDate diffTime, NotesIDTable diffIDTable, int preloadEntryCount, EnumSet<ReadMask> returnMask, final ViewLookupCallback<T> callback) { final String[] categoryPos = new String[1]; IStartPositionRetriever catPosRetriever = new IStartPositionRetriever() { @Override public String getStartPosition() { //find category entry using NIFFindByKeyExtended2 with flag FIND_CATEGORY_MATCH NotesViewLookupResultData catLkResult = findByKeyExtended2(EnumSet.of(Find.MATCH_CATEGORYORLEAF, Find.REFRESH_FIRST, Find.RETURN_DWORD, Find.AND_READ_MATCHES), EnumSet.of(ReadMask.NOTEID, ReadMask.SUMMARY), category); if (catLkResult.getReturnCount()==0) { //category not found return null; } categoryPos[0] = catLkResult.getPosition(); if (StringUtil.isEmpty(categoryPos[0])) { //category not found return null; } else { return categoryPos[0]; } } }; EnumSet<ReadMask> useReturnMask = returnMask.clone(); //make sure that we get the entry position for the range check useReturnMask.add(ReadMask.INDEXPOSITION); return getAllEntries(catPosRetriever, skipCount, returnNav, preloadEntryCount, useReturnMask, new ViewLookupCallbackWrapper<T>(callback) { @Override public com.mindoo.domino.jna.NotesCollection.ViewLookupCallback.Action entryRead(T result, NotesViewEntryData entryData) { //check if this entry is still one of the descendants of the category entry String entryPos = entryData.getPositionStr(); if (entryPos.equals(categoryPos[0])) { //skip category entry return Action.Continue; } else if (entryPos.startsWith(categoryPos[0])) { return super.entryRead(result, entryData); } else { return Action.Stop; } } }); } /** * The method reads a number of entries from the collection/view, starting an a row * with the specified note id. The method internally takes care * of view index changes while reading view data and restarts reading if such a change has been * detected. * * @param noteId note id to start reading * @param skipCount number entries to skip before reading * @param returnNav navigator to specify how to move in the collection * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result * * @param <T> type of lookup result object */ public <T> T getAllEntriesStartingAtNoteId(int noteId, int skipCount, EnumSet<Navigate> returnNav, int preloadEntryCount, EnumSet<ReadMask> returnMask, ViewLookupCallback<T> callback) { String fakePos = Integer.toString(noteId); EnumSet<ReadMask> useReturnMask = returnMask.clone(); useReturnMask.add(ReadMask.INIT_POS_NOTEID); T entries = getAllEntries(fakePos, skipCount, returnNav, preloadEntryCount, useReturnMask, callback); return entries; } /** * The method reads a number of entries from the collection/view. It internally takes care * of view index changes while reading view data and restarts reading if such a change has been * detected. * * @param startPosStr start position; use "0" or null to start before the first entry; in that case set <code>skipCount</code> to 1 to start reading at the first view row * @param skipCount number entries to skip before reading * @param returnNav navigator to specify how to move in the collection * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result * * @param <T> type of lookup result object */ public <T> T getAllEntries(final String startPosStr, int skipCount, EnumSet<Navigate> returnNav, int preloadEntryCount, EnumSet<ReadMask> returnMask, ViewLookupCallback<T> callback) { return getAllEntries(new IStartPositionRetriever() { @Override public String getStartPosition() { return startPosStr; } }, skipCount, returnNav, preloadEntryCount, returnMask, callback); } /** * Callback to dynamically locate the start position of a collection scan, e.g. * the position of a category entry. We use a callback to be able to react on * view index updates. Since a lookup may be repeated when the view index changes, * this callback may be called multiple times to return a fresh starting position * for the lookup. * * @author Karsten Lehmann */ private static interface IStartPositionRetriever { /** * Implement this method to find the lookup start position * * @return start position or null if not found */ public String getStartPosition(); } /** * The method reads a number of entries from the collection/view. It internally takes care * of view index changes while reading view data and restarts reading if such a change has been * detected. * * @param startPosRetriever callback to find the start position to read * @param skipCount number entries to skip before reading * @param returnNav navigator to specify how to move in the collection * @param preloadEntryCount amount of entries that is read from the view; if a filter is specified, this should be higher than returnCount * @param returnMask values to extract * @param callback callback that is called for each entry read from the collection * @return lookup result * * @param <T> type of lookup result object */ private <T> T getAllEntries(IStartPositionRetriever startPosRetriever, int skipCount, EnumSet<Navigate> returnNav, int preloadEntryCount, EnumSet<ReadMask> returnMask, ViewLookupCallback<T> callback) { EnumSet<ReadMask> useReturnMask = returnMask; //decide whether we need to use the undocumented NIFReadEntriesExt String readSingleColumnName = callback.getNameForSingleColumnRead(); if (readSingleColumnName!=null) { //make sure that we actually read any column values if (!useReturnMask.contains(ReadMask.SUMMARY) && !useReturnMask.contains(ReadMask.SUMMARYVALUES)) { useReturnMask = useReturnMask.clone(); useReturnMask.add(ReadMask.SUMMARYVALUES); } } CollectionDataCache dataCache = callback.getDataCache(); if (useReturnMask.equals(EnumSet.of(ReadMask.NOTEID))) { //disable cache if all we need to read is the note id dataCache = null; } Integer readSingleColumnIndex = readSingleColumnName==null ? null : getColumnValuesIndex(readSingleColumnName); if (readSingleColumnName!=null) { //TODO view row caching currently disabled for single column reads, needs more work dataCache = null; } if (dataCache!=null) { //if caching is used, make sure that we read the note id, because that's how we hash our data if (!useReturnMask.contains(ReadMask.NOTEID) && !useReturnMask.contains(ReadMask.NOTEID)) { useReturnMask = useReturnMask.clone(); useReturnMask.add(ReadMask.NOTEID); } } long t0 = System.currentTimeMillis(); int runs = -1; while (true) { runs++; int indexModifiedBeforeGettingStartPos = getIndexModifiedSequenceNo(); String startPosStr = startPosRetriever.getStartPosition(); if (StringUtil.isEmpty(startPosStr)) { T result = callback.startingLookup(); result = callback.lookupDone(result); return result; } int indexModifiedAfterGettingStartPos = getIndexModifiedSequenceNo(); if (indexModifiedBeforeGettingStartPos != indexModifiedAfterGettingStartPos) { //view index was changed while reading; restart scan Action retryAction = callback.retryingReadBecauseViewIndexChanged(runs, System.currentTimeMillis() - t0); if (retryAction==Action.Stop) { return null; } update(); continue; } NotesCollectionPositionStruct pos = NotesCollectionPositionStruct.toPosition(("last".equalsIgnoreCase(startPosStr) || startPosStr==null) ? "0" : startPosStr); NotesCollectionPosition posWrap = new NotesCollectionPosition(pos); T result = callback.startingLookup(); if (preloadEntryCount==0) { //nothing to do result = callback.lookupDone(result); return result; } boolean viewModified = false; boolean firstLoopRun = true; NotesTimeDate retDiffTime = null; NotesTimeDate diffTime = null; NotesIDTable diffIDTable = null; if (dataCache!=null) { CacheState cacheState = dataCache.getCacheState(); //only use cache content if read masks are compatible Map<Integer,CacheableViewEntryData> cacheEntries = cacheState.getCacheEntries(); if (cacheEntries!=null && !cacheEntries.isEmpty()) { EnumSet<ReadMask> cacheReadMask = cacheState.getReadMask(); if (useReturnMask.equals(cacheReadMask)) { diffTime = cacheState.getDiffTime(); diffIDTable = new NotesIDTable(); diffIDTable.addNotes(cacheEntries.keySet()); } } } List<NotesViewEntryData> entriesToUpdateCache = dataCache==null ? null : new ArrayList<NotesViewEntryData>(); while (true) { if (preloadEntryCount==0) { break; } int useSkipCount; if (firstLoopRun) { if ("last".equalsIgnoreCase(startPosStr)) { //TODO make "last" work when called from getAllEntriesInCategory //first jump to the end of the view useSkipCount = Integer.MAX_VALUE; } else { useSkipCount = skipCount; } } else { //just skip the last entry that we returned on the last NIFReadEntries call useSkipCount = 1; } EnumSet<Navigate> skipNav = returnNav.clone(); if (firstLoopRun) { if ("last".equalsIgnoreCase(startPosStr)) { //compute the skipNav by reversing the returnNav; e.g. for startPos="last" //and returnNav=Navigate.PREV_SELECTED, we first jump to the end of the view //with skipCount=INTEGER.MAX_VALUE Navigate.NEXT_SELECTED. //Then we start reading n entries with Navigate.PREV_SELECTED, //effectively returning the last n selected entries of the view skipNav = EnumSet.noneOf(Navigate.class); for (Navigate currNav : returnNav) { skipNav.add(reverseNav(currNav)); } //set NAVIGATE_CONTINUE to stop skipping on the last view element and not return an error skipNav.add(Navigate.CONTINUE); } else { skipNav = returnNav; } } else { skipNav = returnNav; } NotesViewLookupResultData data; data = readEntriesExt(posWrap, skipNav, useSkipCount, returnNav, preloadEntryCount, useReturnMask, diffTime, diffIDTable, readSingleColumnIndex); int indexModifiedAfterDataLookup = getIndexModifiedSequenceNo(); if (indexModifiedAfterGettingStartPos != indexModifiedAfterDataLookup) { //view index was changed while reading; restart scan Action retryAction = callback.retryingReadBecauseViewIndexChanged(runs, System.currentTimeMillis() - t0); if (retryAction==Action.Stop) { return null; } update(); continue; } if (useReturnMask.contains(ReadMask.INIT_POS_NOTEID)) { //make sure to only use this flag on the first lookup call useReturnMask = useReturnMask.clone(); useReturnMask.remove(ReadMask.INIT_POS_NOTEID); } retDiffTime = data.getReturnedDiffTime(); if (dataCache!=null) { //if data cache is used, we fill in missing gaps in cases where NIF skipped producing //the summary data, because the corresponding cache entry was already //up to date List<NotesViewEntryData> entries = data.getEntries(); dataCache.populateEntryStubsWithData(entries); entriesToUpdateCache.addAll(entries); } if (data.getReturnCount()==0) { //no more data found result = callback.lookupDone(result); if (dataCache!=null && retDiffTime!=null) { if (!entriesToUpdateCache.isEmpty()) { dataCache.addCacheValues(useReturnMask, retDiffTime, entriesToUpdateCache); } callback.setNewDiffTime(retDiffTime); } return result; } firstLoopRun = false; if (isAutoUpdate()) { if (data.hasAnyNonDataConflicts()) { //refresh the view and restart the lookup viewModified=true; break; } } List<NotesViewEntryData> entries = data.getEntries(); for (NotesViewEntryData currEntry : entries) { Action action = callback.entryRead(result, currEntry); if (action==Action.Stop) { result = callback.lookupDone(result); if (dataCache!=null && retDiffTime!=null) { if (!entriesToUpdateCache.isEmpty()) { dataCache.addCacheValues(useReturnMask, retDiffTime, entriesToUpdateCache); } callback.setNewDiffTime(retDiffTime); } return result; } } } if (dataCache!=null && retDiffTime!=null) { if (!entriesToUpdateCache.isEmpty()) { dataCache.addCacheValues(useReturnMask, retDiffTime, entriesToUpdateCache); } callback.setNewDiffTime(retDiffTime); } if (diffIDTable!=null) { diffIDTable.recycle(); } if (viewModified) { //view index was changed while reading; restart scan Action retryAction = callback.retryingReadBecauseViewIndexChanged(runs, System.currentTimeMillis() - t0); if (retryAction==Action.Stop) { return null; } update(); continue; } return result; } } /** * Returns all view entries matching the specified search key(s) in the collection. * It internally takes care of view index changes while reading view data and restarts * reading if such a change has been detected. * * @param findFlags find flags, see {@link Find} * @param returnMask values to be returned * @param callback lookup callback * @param keys lookup keys * @return lookup result * * @param <T> type of lookup result object */ public <T> T getAllEntriesByKey(EnumSet<Find> findFlags, EnumSet<ReadMask> returnMask, ViewLookupCallback<T> callback, Object... keys) { //we are leaving the loop when there is no more data to be read; //while(true) is here to rerun the query in case of view index changes while reading long t0=System.currentTimeMillis(); int runs = -1; while (true) { runs++; T result = callback.startingLookup(); NotesViewLookupResultData data; //position of first match String firstMatchPosStr; int remainingEntries; int entriesToSkipOnFirstLoopRun = 0; if (canUseOptimizedLookupForKeyLookup(findFlags, returnMask, keys)) { //do the first lookup and read operation atomically; uses a large buffer for local calls EnumSet<Find> findFlagsWithExtraBits = findFlags.clone(); findFlagsWithExtraBits.add(Find.AND_READ_MATCHES); findFlagsWithExtraBits.add(Find.RETURN_DWORD); data = findByKeyExtended2(findFlagsWithExtraBits, returnMask, keys); int numEntriesFound = data.getReturnCount(); if (numEntriesFound!=-1) { if (isAutoUpdate()) { //check for view index or design change if (data.hasAnyNonDataConflicts()) { //refresh the view and restart the lookup Action retryAction = callback.retryingReadBecauseViewIndexChanged(runs, System.currentTimeMillis() - t0); if (retryAction==Action.Stop) { return null; } update(); continue; } } //copy the data we have read List<NotesViewEntryData> entries = data.getEntries(); for (NotesViewEntryData currEntryData : entries) { Action action = callback.entryRead(result, currEntryData); if (action==Action.Stop) { result = callback.lookupDone(result); return result; } } entriesToSkipOnFirstLoopRun = entries.size(); if (!data.hasMoreToDo()) { //we are done result = callback.lookupDone(result); return result; } //compute what we have left int entriesReadOnFirstLookup = entries.size(); remainingEntries = numEntriesFound - entriesReadOnFirstLookup; firstMatchPosStr = data.getPosition(); } else { //workaround for a bug where the method NIFFindByKeyExtended2 returns -1 as numEntriesFound //and no buffer data //fallback to classic lookup until this is fixed/commented by IBM dev: FindResult findResult = findByKey(findFlags, keys); remainingEntries = findResult.getEntriesFound(); if (remainingEntries==0) { return result; } firstMatchPosStr = findResult.getPosition(); } } else { //first find the start position to read data FindResult findResult = findByKey(findFlags, keys); remainingEntries = findResult.getEntriesFound(); if (remainingEntries==0) { return result; } firstMatchPosStr = findResult.getPosition(); } if (!canFindExactNumberOfMatches(findFlags)) { Direction currSortDirection = getCurrentSortDirection(); if (currSortDirection!=null) { //handle special case for inquality search where column sort order matches the find flag, //so we can read all view entries after findResult.getPosition() if (currSortDirection==Direction.Ascending && findFlags.contains(Find.GREATER_THAN)) { //read all entries after findResult.getPosition() remainingEntries = Integer.MAX_VALUE; } else if (currSortDirection==Direction.Descending && findFlags.contains(Find.LESS_THAN)) { //read all entries after findResult.getPosition() remainingEntries = Integer.MAX_VALUE; } } } if (firstMatchPosStr!=null) { //position of the first match; we skip (entries.size()) to read the remaining entries boolean isFirstLookup = true; NotesCollectionPositionStruct lookupPos = NotesCollectionPositionStruct.toPosition(firstMatchPosStr); NotesCollectionPosition lookupPosWrap = new NotesCollectionPosition(lookupPos); boolean viewModified = false; while (remainingEntries>0) { //on first lookup, start at "posStr" and skip the amount of already read entries data = readEntries(lookupPosWrap, EnumSet.of(Navigate.NEXT_NONCATEGORY), isFirstLookup ? entriesToSkipOnFirstLoopRun : 1, EnumSet.of(Navigate.NEXT_NONCATEGORY), remainingEntries, returnMask); if (isFirstLookup || isAutoUpdate()) { //for the first lookup, make sure we start at the right position if (data.hasAnyNonDataConflicts()) { //set viewModified to true and leave the inner loop; we will refresh the view and restart the lookup viewModified=true; break; } } isFirstLookup=false; List<NotesViewEntryData> entries = data.getEntries(); if (entries.isEmpty()) { //looks like we don't have any more data in the view break; } for (NotesViewEntryData currEntryData : entries) { Action action = callback.entryRead(result, currEntryData); if (action==Action.Stop) { result = callback.lookupDone(result); return result; } } remainingEntries = remainingEntries - entries.size(); } if (viewModified) { //refresh view and redo the whole lookup Action retryAction = callback.retryingReadBecauseViewIndexChanged(runs, System.currentTimeMillis() - t0); if (retryAction==Action.Stop) { return null; } update(); continue; } } result = callback.lookupDone(result); return result; } } /** * This method is in essense a combo NIFFindKey/NIFReadEntries API. It leverages * the C API method NIFFindByKeyExtended2 internally which was introduced in Domino R9<br> * <br> * The purpose of this method is to provide a mechanism to position into a * collection and read the associated entries in an atomic manner.<br> * <br> * More specifically, the key provided is positioned to and the entries from * the collection are read while the collection is read locked so that no other updates can occur.<br> * <br> * 1) This avoids the possibility of the initial collection position shifting * due to an insert/delete/update in and/or around the logical key value that * would result in an ordinal change to the position.<br> * <br> * This a classic problem when doing a NIFFindKey, getting the position returned, * and then doing a NIFReadEntries following.<br> * <br> * 2) The API improves the ability to read all the entries that are associated * with the key position atomically.<br> * <br> * This can be done depending on the size of the data being returned.<br> * <br> * If all the data fits into the limitation (64K) of the return buffer, then * it will be done atomically in 1 call.<br> * Otherwise subsequent NIFReadEntries will need to be called, which will be non-atomic.<br> * <br> * The 64K limit only changes behavior to NIFFindByKey/NIFReadEntries when the call is client/server. * Locally there is no limit. * <hr> * Original documentation of C API method NIFFindByKeyExtended2:<br> * <br> * NIFFindByKeyExtended2 - Lookup index entry by "key"<br> * <br> * Given a "key" buffer in the standard format of a summary buffer,<br> * locate the entry which matches the given key(s). Supply as many<br> * "key" summary items as required to correspond to the way the index<br> * collates, in order to uniquely find an entry.<br> * <br> * If multiple index entries match the specified key (especially if<br> * not enough key items were specified), then the index position of<br> * the FIRST matching entry is returned ("first" is defined by the<br> * entry which collates before all others in the collated index).<br> * <br> * Note that the more explicitly an entry can be specified (by<br> * specifying as many keys as possible), then the faster the lookup<br> * can be performed, since the "key" lookup is very fast, but a<br> * sequential search is performed to locate the "first" entry when<br> * multiple entries match.<br> * <br> * This routine can only be used when dealing with notes that do not<br> * have multiple permutations, and cannot be used to locate response<br> * notes. * * @param findFlags find flags ({@link Find}) * @param returnMask mask specifying what information is to be returned on each entry ({link ReadMask}) * @param keys lookup keys * @return lookup result */ public NotesViewLookupResultData findByKeyExtended2(EnumSet<Find> findFlags, EnumSet<ReadMask> returnMask, Object... keys) { checkHandle(); if (keys==null || keys.length==0) throw new IllegalArgumentException("No search keys specified"); IntByReference retNumMatches = new IntByReference(); NotesCollectionPositionStruct retIndexPos = NotesCollectionPositionStruct.newInstance(); int findFlagsBitMask = Find.toBitMaskInt(findFlags); short result; int returnMaskBitMask = ReadMask.toBitMask(returnMask); ShortByReference retSignalFlags = new ShortByReference(); if (PlatformUtils.is64Bit()) { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b64_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } LongByReference retBuffer = new LongByReference(); IntByReference retSequence = new IntByReference(); result = NotesNativeAPI64.get().NIFFindByKeyExtended2(m_hCollection64, keyBuffer, findFlagsBitMask, returnMaskBitMask, retIndexPos, retNumMatches, retSignalFlags, retBuffer, retSequence); if (result == 1028 || result == 17412) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } NotesErrorUtils.checkResult(result); if (retNumMatches.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } else { if (retBuffer.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, retNumMatches.getValue(), retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null); } else { boolean convertStringsLazily = true; boolean convertNotesTimeDateToCalendar = false; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b64_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), 0, retNumMatches.getValue(), returnMask, retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null, convertStringsLazily, convertNotesTimeDateToCalendar, null); return viewData; } } } else { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b32_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } IntByReference retBuffer = new IntByReference(); IntByReference retSequence = new IntByReference(); result = NotesNativeAPI32.get().NIFFindByKeyExtended2(m_hCollection32, keyBuffer, findFlagsBitMask, returnMaskBitMask, retIndexPos, retNumMatches, retSignalFlags, retBuffer, retSequence); if (result == 1028 || result == 17412) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } NotesErrorUtils.checkResult(result); if (retNumMatches.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, 0, retSignalFlags.getValue(), null, retSequence.getValue(), null); } else { if (retBuffer.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), 0, retNumMatches.getValue(), retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null); } else { boolean convertStringsLazily = true; boolean convertNotesTimeDateToCalendar = false; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b32_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), 0, retNumMatches.getValue(), returnMask, retSignalFlags.getValue(), retIndexPos.toPosString(), retSequence.getValue(), null, convertStringsLazily, convertNotesTimeDateToCalendar, null); return viewData; } } } } /** * This function searches through a collection for the first note whose sort * column values match the given search keys.<br> * <br> * The search key consists of an array containing one or several values. * This function matches each value in the * search key against the corresponding sorted column of the view or folder.<br> * <br> * Only sorted columns are used. The values in the search key * must be specified in the same order as the sorted columns in the view * or folder, from left to right. Other unsorted columns may lie between * the sorted columns to be searched.<br> * <br> * For example, suppose view columns 1, 3, 4 and 5 are sorted.<br> * The key buffer may contain search keys for: just column 1; columns 1 * and 3; or for columns 1, 3, and 4.<br> * <br> * This function yields the {@link NotesCollectionPosition} of the first note in the * collection that matches the keys. It also yields a count of the number * of notes that match the keys. Since all notes that match the keys * appear contiguously in the view or folder, you may pass the resulting * {@link NotesCollectionPosition} and match count as inputs to * {@link #readEntries(NotesCollectionPosition, EnumSet, int, EnumSet, int, EnumSet)} * to read all the entries in the collection that match the keys.<br> * <br> * If multiple notes match the specified (partial) keys, and * {@link Find#FIRST_EQUAL} (the default flag) is specified, * hen the position * of the first matching note is returned ("first" is defined by the * note which collates before all the others in the view).<br> * <br> * The position of the last matching note is returned if {@link Find#LAST_EQUAL} * is specified. If {@link Find#LESS_THAN} is specified, * then the last note * with a key value less than the specified key is returned.<br> * <br> * If {@link Find#GREATER_THAN} is specified, then the first * note with a key * value greater than the specified key is returned.<br> * <br> * This routine cannot be used to locate notes that are categorized * under multiple categories (the resulting position is unpredictable), * and also cannot be used to locate responses.<br> * <br> * This routine is usually not appropriate for equality searches of key * values of {@link Calendar}.<br> * <br> * A match will only be found if the key value is * as precise as and is equal to the internally stored data.<br> * <br> * {@link Calendar} data is displayed with less precision than what is stored * internally. Use inequality searches, such as {@link Find#GREATER_THAN} or * {@link Find#LESS_THAN}, for {@link Calendar} key values * to avoid having to find * an exact match of the specified value. If the precise key value * is known, however, equality searches of {@link Calendar} values are supported.<br> * <br> * Returning the number of matches on an inequality search is not supported.<br> * <br> * In other words, if you specify any one of the following for the FindFlags argument:<br> * {@link Find#LESS_THAN}<br> * {@link Find#LESS_THAN} | {@link Find#EQUAL}<br> * {@link Find#GREATER_THAN}<br> * {@link Find#GREATER_THAN} | {@link Find#EQUAL}<br> * <br> * this function cannot determine the number of notes that match the search * condition (use {@link #canFindExactNumberOfMatches(EnumSet)} to check * whether a combination of find flags can return the exact number of matches).<br> * If we cannot determine the number of notes, the function will return 1 for the count * value returned by {@link FindResult#getEntriesFound()}. * @param findFlags {@link Find} * @param keys lookup keys, can be {@link String}, double / {@link Double}, int / {@link Integer}, {@link Date}, {@link Calendar}, {@link Date}[] or {@link Calendar}[] with two elements for date ranges * @return result */ public FindResult findByKey(EnumSet<Find> findFlags, Object... keys) { checkHandle(); if (keys==null || keys.length==0) throw new IllegalArgumentException("No search keys specified"); IntByReference retNumMatches = new IntByReference(); NotesCollectionPositionStruct retIndexPos = NotesCollectionPositionStruct.newInstance(); short findFlagsBitMask = Find.toBitMask(findFlags); short result; if (PlatformUtils.is64Bit()) { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b64_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } result = NotesNativeAPI64.get().NIFFindByKey(m_hCollection64, keyBuffer, findFlagsBitMask, retIndexPos, retNumMatches); } else { Memory keyBuffer; try { keyBuffer = NotesSearchKeyEncoder.b32_encodeKeys(keys); } catch (Throwable e) { throw new NotesError(0, "Could not encode search keys", e); } result = NotesNativeAPI32.get().NIFFindByKey(m_hCollection32, keyBuffer, findFlagsBitMask, retIndexPos, retNumMatches); } if (result == 1028 || result == 17412) { return new FindResult("", 0, canFindExactNumberOfMatches(findFlags)); } NotesErrorUtils.checkResult(result); int nMatchesFound = retNumMatches.getValue(); int[] retTumbler = retIndexPos.Tumbler; short retLevel = retIndexPos.Level; StringBuilder sb = new StringBuilder(); for (int i=0; i<=retLevel; i++) { if (sb.length()>0) sb.append("."); sb.append(retTumbler[i]); } String firstMatchPos = sb.toString(); return new FindResult(firstMatchPos, nMatchesFound, canFindExactNumberOfMatches(findFlags)); } /** * This function searches through a collection for notes whose primary sort * key matches a given string. The primary sort key for a given note is the * value displayed for that note in the leftmost sorted column in the view * or folder. Use this function only when the leftmost sorted column of * the view or folder is a string.<br> * <br> * This function yields the {@link NotesCollectionPosition} of the first note in the * collection that matches the string. It also yields a count of the number * of notes that match the string.<br> * <br> * With views that are not categorized, all notes with primary sort keys that * match the string appear contiguously in the view or folder.<br> * <br> * This means you may pass the resulting {@link NotesCollectionPosition} and match count * as inputs to {@link #readEntries(NotesCollectionPosition, EnumSet, int, EnumSet, int, EnumSet)} * to read all the entries in the collection that match the string.<br> * <br> * This routine returns limited results if the view is categorized.<br> * <br> * Views that are categorized do not necessarily list all notes whose<br> * sort keys match the string contiguously; such as in the case where * the category note intervenes.<br> * Likewise, this routine cannot be used to locate notes that are * categorized under multiple categories (the resulting position is unpredictable), * and also cannot be used to locate responses.<br> * <br> * Use {@link #findByKey(EnumSet, Object...)} if the leftmost sorted column * is a number or a time/date.<br> * <br> * Returning the number of matches on an inequality search is not supported.<br> * <br> * In other words, if you specify any one of the following for the FindFlags argument:<br> * <br> * {@link Find#LESS_THAN}<br> * {@link Find#LESS_THAN} | {@link Find#EQUAL}<br> * {@link Find#GREATER_THAN}<br> * {@link Find#GREATER_THAN} | {@link Find#EQUAL}<br> * <br> * this function cannot determine the number of notes that match the search * condition (use {@link #canFindExactNumberOfMatches(EnumSet)} to check * whether a combination of find flags can return the exact number of matches).<br> * If we cannot determine the number of notes, the function will return 1 for the count * value returned by {@link FindResult#getEntriesFound()}. * * @param name name to look for * @param findFlags find flags, see {@link Find} * @return result */ public FindResult findByName(String name, EnumSet<Find> findFlags) { checkHandle(); Memory nameLMBCS = NotesStringUtils.toLMBCS(name, true); IntByReference retNumMatches = new IntByReference(); NotesCollectionPositionStruct retIndexPos = NotesCollectionPositionStruct.newInstance(); short findFlagsBitMask = Find.toBitMask(findFlags); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFFindByName(m_hCollection64, nameLMBCS, findFlagsBitMask, retIndexPos, retNumMatches); } else { result = NotesNativeAPI32.get().NIFFindByName(m_hCollection32, nameLMBCS, findFlagsBitMask, retIndexPos, retNumMatches); } if (result == 1028 || result == 17412) { return new FindResult("", 0, canFindExactNumberOfMatches(findFlags)); } NotesErrorUtils.checkResult(result); int nMatchesFound = retNumMatches.getValue(); int[] retTumbler = retIndexPos.Tumbler; short retLevel = retIndexPos.Level; StringBuilder sb = new StringBuilder(); for (int i=0; i<=retLevel; i++) { if (sb.length()>0) sb.append("."); sb.append(retTumbler[i]); } String firstMatchPos = sb.toString(); return new FindResult(firstMatchPos, nMatchesFound, canFindExactNumberOfMatches(findFlags)); } /** * If the specified find flag uses an inequality search like {@link Find#LESS_THAN} * or {@link Find#GREATER_THAN}, this method returns true, meaning that * the Notes API cannot return an exact number of matches. * * @param findFlags find flags * @return true if exact number of matches can be returned */ public boolean canFindExactNumberOfMatches(EnumSet<Find> findFlags) { if (findFlags.contains(Find.LESS_THAN)) { return false; } else if (findFlags.contains(Find.GREATER_THAN)) { return false; } else { return true; } } /** * Container object for a collection lookup result * * @author Karsten Lehmann */ public static class FindResult { private String m_position; private int m_entriesFound; private boolean m_hasExactNumberOfMatches; /** * Creates a new instance * * @param position position of the first match * @param entriesFound number of entries found or 1 if hasExactNumberOfMatches is <code>false</code> * @param hasExactNumberOfMatches true if Notes was able to count the number of matches (e.g. for string key lookups with full or partial matches) */ public FindResult(String position, int entriesFound, boolean hasExactNumberOfMatches) { m_position = position; m_entriesFound = entriesFound; m_hasExactNumberOfMatches = hasExactNumberOfMatches; } /** * Returns the number of entries found or 1 if hasExactNumberOfMatches is <code>false</code> * and any matches were found * * @return count */ public int getEntriesFound() { return m_entriesFound; } /** * Returns the position of the first match * * @return position */ public String getPosition() { return m_position; } /** * Use this method to check whether Notes was able to count the number of matches * (e.g. for string key lookups with full or partial matches) * * @return true if we have an exact match count */ public boolean hasExactNumberOfMatches() { return m_hasExactNumberOfMatches; } } /** * Returns the number of top level entries in the view * * @return top level entries */ public int getTopLevelEntries() { NotesViewLookupResultData lkData = readEntries(new NotesCollectionPosition("0"), EnumSet.of(Navigate.CURRENT), 0, EnumSet.of(Navigate.CURRENT), 0, EnumSet.of(ReadMask.COLLECTIONSTATS)); return lkData.getStats().getTopLevelEntries(); } public NotesViewLookupResultData readEntries(NotesCollectionPosition startPos, EnumSet<Navigate> skipNavigator, int skipCount, EnumSet<Navigate> returnNavigator, int returnCount, EnumSet<ReadMask> returnMask) { checkHandle(); IntByReference retNumEntriesSkipped = new IntByReference(); IntByReference retNumEntriesReturned = new IntByReference(); ShortByReference retSignalFlags = new ShortByReference(); ShortByReference retBufferLength = new ShortByReference(); short skipNavBitMask = Navigate.toBitMask(skipNavigator); short returnNavBitMask = Navigate.toBitMask(returnNavigator); int readMaskBitMask = ReadMask.toBitMask(returnMask); NotesCollectionPositionStruct startPosStruct = startPos==null ? null : startPos.getAdapter(NotesCollectionPositionStruct.class); short result; if (PlatformUtils.is64Bit()) { LongByReference retBuffer = new LongByReference(); result = NotesNativeAPI64.get().NIFReadEntries(m_hCollection64, // hCollection startPosStruct, // IndexPos skipNavBitMask, // SkipNavigator skipCount, // SkipCount returnNavBitMask, // ReturnNavigator returnCount, // ReturnCount readMaskBitMask, // Return mask retBuffer, // rethBuffer retBufferLength, // retBufferLength retNumEntriesSkipped, // retNumEntriesSkipped retNumEntriesReturned, // retNumEntriesReturned retSignalFlags // retSignalFlags ); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = getIndexModifiedSequenceNo(); int iBufLength = (int) (retBufferLength.getValue() & 0xffff); if (iBufLength==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, null); } else { boolean convertStringsLazily = true; boolean convertNotesTimeDateToCalendar = false; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b64_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, null, convertStringsLazily, convertNotesTimeDateToCalendar, null); return viewData; } } else { IntByReference retBuffer = new IntByReference(); result = NotesNativeAPI32.get().NIFReadEntries(m_hCollection32, // hCollection startPosStruct, // IndexPos skipNavBitMask, // SkipNavigator skipCount, // SkipCount returnNavBitMask, // ReturnNavigator returnCount, // ReturnCount readMaskBitMask, // Return mask retBuffer, // rethBuffer retBufferLength, // retBufferLength retNumEntriesSkipped, // retNumEntriesSkipped retNumEntriesReturned, // retNumEntriesReturned retSignalFlags // retSignalFlags ); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = getIndexModifiedSequenceNo(); int iBufLength = (int) (retBufferLength.getValue() & 0xffff); if (iBufLength==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, null); } else { boolean convertStringsLazily = true; boolean convertNotesTimeDateToCalendar = false; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b32_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, null, convertStringsLazily, convertNotesTimeDateToCalendar, null); return viewData; } } } public NotesViewLookupResultData readEntriesExt(NotesCollectionPosition startPos, EnumSet<Navigate> skipNavigator, int skipCount, EnumSet<Navigate> returnNavigator, int returnCount, EnumSet<ReadMask> returnMask, NotesTimeDate diffTime, NotesIDTable diffIDTable, Integer columnNumber) { checkHandle(); IntByReference retNumEntriesSkipped = new IntByReference(); IntByReference retNumEntriesReturned = new IntByReference(); ShortByReference retSignalFlags = new ShortByReference(); ShortByReference retBufferLength = new ShortByReference(); short skipNavBitMask = Navigate.toBitMask(skipNavigator); short returnNavBitMask = Navigate.toBitMask(returnNavigator); int readMaskBitMask = ReadMask.toBitMask(returnMask); NotesCollectionPositionStruct startPosStruct = startPos==null ? null : startPos.getAdapter(NotesCollectionPositionStruct.class); int flags = 0; NotesTimeDateStruct retDiffTimeStruct = NotesTimeDateStruct.newInstance(); NotesTimeDateStruct retModifiedTimeStruct = NotesTimeDateStruct.newInstance(); IntByReference retSequence = new IntByReference(); String singleColumnLookupName = columnNumber == null ? null : getColumnName(columnNumber); NotesTimeDateStruct diffTimeStruct = diffTime==null ? null : NotesTimeDateStruct.newInstance(diffTime.getInnards()); short result; if (PlatformUtils.is64Bit()) { LongByReference retBuffer = new LongByReference(); result = NotesNativeAPI64.get().NIFReadEntriesExt(m_hCollection64, startPosStruct, skipNavBitMask, skipCount, returnNavBitMask, returnCount, readMaskBitMask, diffTimeStruct, diffIDTable==null ? 0 : diffIDTable.getHandle64(), columnNumber==null ? NotesConstants.MAXDWORD : columnNumber, flags, retBuffer, retBufferLength, retNumEntriesSkipped, retNumEntriesReturned, retSignalFlags, retDiffTimeStruct, retModifiedTimeStruct, retSequence); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = retModifiedTimeStruct.Innards[0]; //getIndexModifiedSequenceNo(); NotesTimeDate retDiffTimeWrap = new NotesTimeDate(retDiffTimeStruct); int iBufLength = (int) (retBufferLength.getValue() & 0xffff); if (iBufLength==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, new NotesTimeDate(retDiffTimeStruct)); } else { boolean convertStringsLazily = true; boolean convertNotesTimeDateToCalendar = false; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b64_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, retDiffTimeWrap, convertStringsLazily, convertNotesTimeDateToCalendar, singleColumnLookupName); return viewData; } } else { IntByReference retBuffer = new IntByReference(); result = NotesNativeAPI32.get().NIFReadEntriesExt(m_hCollection32, startPosStruct, skipNavBitMask, skipCount, returnNavBitMask, returnCount, readMaskBitMask, diffTimeStruct, diffIDTable==null ? 0 : diffIDTable.getHandle32(), columnNumber==null ? NotesConstants.MAXDWORD : columnNumber, flags, retBuffer, retBufferLength, retNumEntriesSkipped, retNumEntriesReturned, retSignalFlags, retDiffTimeStruct, retModifiedTimeStruct, retSequence); NotesErrorUtils.checkResult(result); int indexModifiedSequenceNo = retModifiedTimeStruct.Innards[0]; //getIndexModifiedSequenceNo(); NotesTimeDate retDiffTimeWrap = new NotesTimeDate(retDiffTimeStruct); if (retBufferLength.getValue()==0) { return new NotesViewLookupResultData(null, new ArrayList<NotesViewEntryData>(0), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), retSignalFlags.getValue(), null, indexModifiedSequenceNo, retDiffTimeWrap); } else { boolean convertStringsLazily = true; boolean convertNotesTimeDateToCalendar = false; NotesViewLookupResultData viewData = NotesLookupResultBufferDecoder.b32_decodeCollectionLookupResultBuffer(this, retBuffer.getValue(), retNumEntriesSkipped.getValue(), retNumEntriesReturned.getValue(), returnMask, retSignalFlags.getValue(), null, indexModifiedSequenceNo, retDiffTimeWrap, convertStringsLazily, convertNotesTimeDateToCalendar, singleColumnLookupName); return viewData; } } } /** * Updates the view to reflect the current database content (using NIFUpdateCollection method) */ public void update() { checkHandle(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFUpdateCollection(m_hCollection64); } else { result = NotesNativeAPI32.get().NIFUpdateCollection(m_hCollection32); } NotesErrorUtils.checkResult(result); } /** * Returns the programmatic name of the column that has last been used to resort * the view * * @return column name or null if view has not been resorted */ public String getCurrentSortColumnName() { short collation = getCollation(); if (collation==0) return null; CollationInfo colInfo = getCollationsInfo(); return colInfo.getSortItem(collation); } /** * Returns the sort direction that has last been used to resort the view * * @return direction or null */ public Direction getCurrentSortDirection() { short collation = getCollation(); if (collation==0) return null; CollationInfo colInfo = getCollationsInfo(); return colInfo.getSortDirection(collation); } /** * Returns the currently active collation * * @return collation */ private short getCollation() { checkHandle(); short result; ShortByReference retCollationNum = new ShortByReference(); if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFGetCollation(m_hCollection64, retCollationNum); } else { result = NotesNativeAPI32.get().NIFGetCollation(m_hCollection32, retCollationNum); } NotesErrorUtils.checkResult(result); return retCollationNum.getValue(); } /** * Method to check whether a column in the view design can be programmatically * sorted in the specified direction * * @param progColumnName programmatic column name * @param direction sort direction * @return true if sortable */ public boolean isColumnResortable(String progColumnName, Direction direction) { short collation = findCollation(progColumnName, direction); return collation!=-1; } /** * Changes the collation to sort the collection by the specified column and direction * * @param progColumnName programmatic column name * @param direction sort direction */ public void resortView(String progColumnName, Direction direction) { short collation = findCollation(progColumnName, direction); if (collation==-1) { throw new NotesError(0, "Column "+progColumnName+" does not exist in view "+getName()+" or is not sortable in "+direction+" direction"); } setCollation(collation); } /** * Resets the view sorting to the default (collation=0). Only needs to be called if * view had been resorted via {@link #resortView(String, Direction)} */ public void resetViewSortingToDefault() { setCollation((short) 0); } /** * Sets the active collation (collection column sorting) * * @param collation collation */ private void setCollation(short collation) { checkHandle(); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFSetCollation(m_hCollection64, collation); } else { result = NotesNativeAPI32.get().NIFSetCollation(m_hCollection32, collation); } NotesErrorUtils.checkResult(result); } /** * Returns programmatic names and sorting of sortable columns * * @return info object with collation info */ private CollationInfo getCollationsInfo() { if (m_collationInfo==null) { scanColumns(); } return m_collationInfo; } /** * Returns an iterator of all available columns for which we can read column values * (e.g. does not return static column names) * * @return programmatic column names converted to lowercase in the order they appear in the view */ public Iterator<String> getColumnNames() { if (m_columnIndicesByItemName==null) { scanColumns(); } return m_columnIndicesByItemName.keySet().iterator(); } /** * Returns the programmatic column name for a column index * * @param index index starting with 0 * @return column name */ public String getColumnName(int index) { return getColumn(index).getItemName(); } /** * Returns the number of columns for which we can read column data (e.g. does not count columns * with static values) * * @return number of columns */ public int getNumberOfColumns() { if (m_viewFormat==null) { scanColumns(); } return m_viewFormat.getColumns().size(); } /** * Returns the column title for a column * * @param columnIndex column index * @return title */ public String getColumnTitle(int columnIndex) { return getColumn(columnIndex).getTitle(); } private NotesNote getViewNote() { if (m_viewNote==null) { m_viewNote = m_parentDb.openNoteByUnid(m_viewUNID); } return m_viewNote; } /** * New method to read information about view columns and sortings using C methods */ private void scanColumns() { m_columnIndicesByItemName = new LinkedHashMap<String, Integer>(); m_columnIndicesByTitle = new LinkedHashMap<String, Integer>(); m_columnNamesByIndex = new TreeMap<Integer, String>(); m_columnIsCategoryByIndex = new TreeMap<Integer, Boolean>(); m_columnTitlesLCByIndex = new TreeMap<Integer, String>(); m_columnTitlesByIndex = new TreeMap<Integer, String>(); NotesNote viewNote = getViewNote(); //read collations CollationInfo collationInfo = new CollationInfo(); int colNo = 0; boolean readCollations = false; while (viewNote.hasItem("$Collation"+(colNo==0 ? "" : colNo))) { List<Object> collationInfoList = viewNote.getItemValue("$Collation"+(colNo==0 ? "" : colNo)); if (collationInfoList!=null && !collationInfoList.isEmpty()) { readCollations = true; NotesCollationInfo colInfo = (NotesCollationInfo) collationInfoList.get(0); List<NotesCollateDescriptor> collateDescList = colInfo.getDescriptors(); if (!collateDescList.isEmpty()) { NotesCollateDescriptor firstCollateDesc = collateDescList.get(0); String currItemName = firstCollateDesc.getName(); Direction currDirection = firstCollateDesc.getDirection(); collationInfo.addCollation((short) colNo, currItemName, currDirection); } } colNo++; } m_collationInfo = collationInfo; if (!readCollations) { throw new AssertionError("View note with UNID "+m_viewUNID+" contains collations"); } //read view columns List<Object> viewFormatList = viewNote.getItemValue("$VIEWFORMAT"); if (!(viewFormatList!=null && !viewFormatList.isEmpty())) throw new AssertionError("View note with UNID "+m_viewUNID+" has item $VIEWFORMAT"); NotesViewFormat format = (NotesViewFormat) viewFormatList.get(0); m_viewFormat = format; List<NotesViewColumn> columns = format.getColumns(); for (int i=0; i<columns.size(); i++) { NotesViewColumn currCol = columns.get(i); String currItemName = currCol.getItemName(); String currItemNameLC = currItemName.toLowerCase(Locale.ENGLISH); String currTitle = currCol.getTitle(); String currTitleLC = currTitle.toLowerCase(Locale.ENGLISH); int currColumnValuesIndex = currCol.getColumnValuesIndex(); m_columnIndicesByItemName.put(currItemNameLC, currColumnValuesIndex); m_columnIndicesByTitle.put(currTitleLC, currColumnValuesIndex); m_columnNamesByIndex.put(currColumnValuesIndex, currItemNameLC); m_columnTitlesLCByIndex.put(currColumnValuesIndex, currTitleLC); m_columnTitlesByIndex.put(currColumnValuesIndex, currTitle); boolean isCategory = currCol.isCategory(); m_columnIsCategoryByIndex.put(currColumnValuesIndex, isCategory); } } /** * Returns the view column at the specified index * * @param columnIndex index starting with 0 * @return column */ public NotesViewColumn getColumn(int columnIndex) { if (m_viewFormat==null) { scanColumns(); } return m_viewFormat.getColumns().get(columnIndex); } /** * Returns design information about the view * * @return view columns */ public List<NotesViewColumn> getColumns() { if (m_viewFormat==null) { scanColumns(); } return Collections.unmodifiableList(m_viewFormat.getColumns()); } /** * Container class with view collation information (collation index vs. sort item name and sort direction) * * @author Karsten Lehmann */ private static class CollationInfo { private Map<String,Short> m_ascendingLookup; private Map<String,Short> m_descendingLookup; private Map<Short,String> m_collationSortItem; private Map<Short,Direction> m_collationSorting; private int m_nrOfCollations; /** * Creates a new instance */ public CollationInfo() { m_ascendingLookup = new HashMap<String,Short>(); m_descendingLookup = new HashMap<String,Short>(); m_collationSortItem = new HashMap<Short, String>(); m_collationSorting = new HashMap<Short, NotesCollection.Direction>(); } /** * Internal method to populate the maps * * @param collation collation index * @param itemName sort item name * @param direction sort direction */ void addCollation(short collation, String itemName, Direction direction) { String itemNameLC = itemName.toLowerCase(); if (direction == Direction.Ascending) { m_ascendingLookup.put(itemNameLC, Short.valueOf(collation)); } else if (direction == Direction.Descending) { m_descendingLookup.put(itemNameLC, Short.valueOf(collation)); } m_nrOfCollations = Math.max(m_nrOfCollations, collation); m_collationSorting.put(collation, direction); m_collationSortItem.put(collation, itemNameLC); } /** * Returns the total number of collations * * @return number */ public int getNumberOfCollations() { return m_nrOfCollations; } /** * Finds a collation index * * @param sortItem sort item name * @param direction sort direction * @return collation index or -1 if not found */ public short findCollation(String sortItem, Direction direction) { String itemNameLC = sortItem.toLowerCase(); if (direction==Direction.Ascending) { Short collation = m_ascendingLookup.get(itemNameLC); return collation==null ? -1 : collation.shortValue(); } else { Short collation = m_descendingLookup.get(itemNameLC); return collation==null ? -1 : collation.shortValue(); } } /** * Returns the sort item name of a collation * * @param collation collation index * @return sort item name */ public String getSortItem(int collation) { if (collation > m_nrOfCollations) throw new IndexOutOfBoundsException("Unknown collation index (max value: "+m_nrOfCollations+")"); String sortItem = m_collationSortItem.get(Short.valueOf((short)collation)); return sortItem; } /** * Returns the sort direction of a collation * * @param collation collation index * @return sort direction */ public Direction getSortDirection(int collation) { if (collation > m_nrOfCollations) throw new IndexOutOfBoundsException("Unknown collation index (max value: "+m_nrOfCollations+")"); Direction direction = m_collationSorting.get(Short.valueOf((short)collation)); return direction; } } /** Available column sort directions */ public static enum Direction {Ascending, Descending}; /** * Finds the matching collation number for the specified sort column and direction * Convenience method that calls {@link #getCollationsInfo()} and {@link CollationInfo#findCollation(String, Direction)} * * @param columnName sort column name * @param direction sort direction * @return collation number or -1 if not found */ private short findCollation(String columnName, Direction direction) { return getCollationsInfo().findCollation(columnName, direction); } /** * Method to check if a note is visible in a view for the current user * * @param noteId note id * @return true if visible */ public boolean isNoteInView(int noteId) { checkHandle(); short result; IntByReference retIsInView = new IntByReference(); if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFIsNoteInView(m_hCollection64, noteId, retIsInView); } else { result = NotesNativeAPI32.get().NIFIsNoteInView(m_hCollection32, noteId, retIsInView); } NotesErrorUtils.checkResult(result); boolean isInView = retIsInView.getValue()==1; return isInView; } /** * Method to check if a note is visible in a view for the current user * * @param note note * @return true if visible */ public boolean isNoteInView(NotesNote note) { return isNoteInView(note.getNoteId()); } /** * Method to check whether a view is time variant and has to be rebuilt on each db open * * @return true if time variant */ public boolean isTimeVariantView() { checkHandle(); if (PlatformUtils.is64Bit()) { return NotesNativeAPI64.get().NIFIsTimeVariantView(m_hCollection64); } else { return NotesNativeAPI32.get().NIFIsTimeVariantView(m_hCollection32); } } /** * Method to check if the view index is up to date or if any note has changed in * the database since the last view index update. * * @return true if up to date */ public boolean isUpToDate() { checkHandle(); if (PlatformUtils.is64Bit()) { return NotesNativeAPI64.get().NIFCollectionUpToDate(m_hCollection64); } else { return NotesNativeAPI32.get().NIFCollectionUpToDate(m_hCollection32); } } /** * Method to check whether this collection is a folder * * @return true if folder */ public boolean isFolder() { NotesNote viewNote = getViewNote(); String flags = viewNote.getItemValueString(NotesConstants.DESIGN_FLAGS); return flags.contains(NotesConstants.DESIGN_FLAG_FOLDER_VIEW); } /** * Check if the collection is currently being updated * * @return true if being updated */ public boolean isUpdateInProgress() { checkHandle(); if (PlatformUtils.is64Bit()) { return NotesNativeAPI64.get().NIFIsUpdateInProgress(m_hCollection64); } else { return NotesNativeAPI32.get().NIFIsUpdateInProgress(m_hCollection32); } } /** * Notify of modification to per-user index filters<br> * <br> * This routine must be called by application code when it makes changes * to any of the index filters (unread list, expand/collapse list, * selected list). No handles to the lists are necessary as input * to this function, since the collection context block remembers the * filter handles that were originally specified to the OpenCollection * call.<br> * If the collection is open on a remote server, then the newly * modified lists are re-sent over to the server. If the collection * is "local", then nothing is done. * * @param flags Flags indicating which filters were modified */ public void updateFilters(EnumSet<UpdateCollectionFilters> flags) { checkHandle(); short flagsBitmask = UpdateCollectionFilters.toBitMask(flags); short result; if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFUpdateFilters(m_hCollection64, flagsBitmask); } else { result = NotesNativeAPI32.get().NIFUpdateFilters(m_hCollection32, flagsBitmask); } NotesErrorUtils.checkResult(result); } @Override public String toString() { if (isRecycled()) { return "NotesCollection [recycled]"; } else { return "NotesCollection [handle="+(PlatformUtils.is64Bit() ? m_hCollection64 : m_hCollection32)+", noteid="+getNoteId()+"]"; } } /** * Resets the selected list ID table */ public void clearSelection() { m_selectedList.clear(); //push selection changes to remote servers updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED)); } /** * This method adds a list of note ids to the selected list * * @param noteIds note ids to add * @param clearPrevSelection true to clear the previous selection */ public void select(Collection<Integer> noteIds, boolean clearPrevSelection) { NotesIDTable selectedList = getSelectedList(); if (clearPrevSelection) { selectedList.clear(); } selectedList.addNotes(noteIds); //push selection changes to remote servers updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED)); } /** * This method adds a list of note ids stored in a {@link NotesIDTable} * to the selected list. Method is expected to run faster than * {@link #select(Collection, boolean)} because the C API handles copying * the note ids between IDTables. * * @param selectedNoteIds {@link NotesIDTable} with note ids * @param clearPrevSelection true to clear the previous selection */ public void select(NotesIDTable selectedNoteIds, boolean clearPrevSelection) { NotesIDTable selectedList = getSelectedList(); if (clearPrevSelection) { selectedList.clear(); } selectedList.addTable(selectedNoteIds); //push selection changes to remote servers updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED)); } /** * This function runs a selection formula on every document of this collection. * Documents matching the selection formula get added to the selected list.<br> * After calling this method, the selected documents can then be read via * {@link #getAllEntries(String, int, EnumSet, int, EnumSet, ViewLookupCallback)} * with the navigator {@link Navigate#NEXT_SELECTED}. * * @param formula selection formula, e.g. SELECT form="Person" * @param clearPrevSelection true to clear the previous selection */ public void select(String formula, boolean clearPrevSelection) { NotesIDTable idTable = new NotesIDTable(); try { //collect all ids of this collection getAllIds(Navigate.NEXT, false, idTable); final Set<Integer> retIds = new TreeSet<Integer>(); NotesSearch.search(m_parentDb, idTable, formula, "-", EnumSet.of(Search.SESSION_USERNAME), EnumSet.of(NoteClass.DOCUMENT), null, new NotesSearch.SearchCallback() { @Override public Action noteFound(NotesDatabase parentDb, ISearchMatch searchMatch, IItemTableData summaryBufferData) { retIds.add(searchMatch.getNoteId()); return Action.Continue; } }); NotesIDTable selectedList = getSelectedList(); if (clearPrevSelection) { selectedList.clear(); } if (!retIds.isEmpty()) selectedList.addNotes(retIds); //push selection changes to remote servers updateFilters(EnumSet.of(UpdateCollectionFilters.FILTER_SELECTED)); } finally { idTable.recycle(); } } /** * Returns the total number of documents in the view * * @return document count */ public int getDocumentCount() { checkHandle(); IntByReference retDocCount = new IntByReference(); short result; //use lightweight function that reads the count from the note id index (fast) if (PlatformUtils.is64Bit()) { result = NotesNativeAPI64.get().NIFGetCollectionDocCountLW(m_hCollection64, retDocCount); } else { result = NotesNativeAPI32.get().NIFGetCollectionDocCountLW(m_hCollection32, retDocCount); } NotesErrorUtils.checkResult(result); return retDocCount.getValue(); } /** * Retrieve detailed information about the collection itself, such as the number of documents * in the collection and the total size of the document entries in the collection.<br> * This function returns a {@link NotesCollectionData} object.<br> * * It is only useful for providing information about a collection which is not categorized.<br> * The index of a categorized collection is implemented using nested B-Trees, and it is not possible to provide * useful information about all of the B-Trees which make up the index.<br> * If this method is called for a categorized collection, the data that is returned pertains * only to the top-level category entries, and not to the main notes in the collection. * * @return collection data */ public NotesCollectionData getCollectionData() { checkHandle(); NotesCollectionDataStruct struct; IItemValueTableData[] itemValueTables = new IItemValueTableData[NotesConstants.PERCENTILE_COUNT]; short result; if (PlatformUtils.is64Bit()) { LongByReference rethCollData = new LongByReference(); result = NotesNativeAPI64.get().NIFGetCollectionData(m_hCollection64, rethCollData); NotesErrorUtils.checkResult(result); long hCollData = rethCollData.getValue(); Pointer ptrCollectionData = Mem64.OSLockObject(hCollData); try { struct = NotesCollectionDataStruct.newInstance(ptrCollectionData); struct.read(); final boolean convertStringsLazily = false; final boolean convertNotesTimeDateToCalendar = false; final boolean decodeAllValues = true; for (int i=0; i<NotesConstants.PERCENTILE_COUNT; i++) { Pointer ptrItemTable = ptrCollectionData.share(struct.keyOffset[i]); itemValueTables[i] = NotesLookupResultBufferDecoder.decodeItemValueTable(ptrItemTable, convertStringsLazily, convertNotesTimeDateToCalendar, decodeAllValues); } NotesCollectionData data = new NotesCollectionData(struct.docCount, struct.docTotalSize, struct.btreeLeafNodes, struct.btreeDepth, itemValueTables); return data; } finally { Mem64.OSUnlockObject(hCollData); result = Mem64.OSMemFree(hCollData); NotesErrorUtils.checkResult(result); } } else { IntByReference rethCollData = new IntByReference(); result = NotesNativeAPI32.get().NIFGetCollectionData(m_hCollection32, rethCollData); NotesErrorUtils.checkResult(result); int hCollData = rethCollData.getValue(); Pointer ptrCollectionData = Mem32.OSLockObject(hCollData); try { struct = NotesCollectionDataStruct.newInstance(ptrCollectionData); struct.read(); final boolean convertStringsLazily = false; final boolean convertNotesTimeDateToCalendar = false; final boolean decodeAllValues = true; for (int i=0; i<NotesConstants.PERCENTILE_COUNT; i++) { Pointer ptrItemTable = ptrCollectionData.share(struct.keyOffset[i]); itemValueTables[i] = NotesLookupResultBufferDecoder.decodeItemValueTable(ptrItemTable, convertStringsLazily, convertNotesTimeDateToCalendar, decodeAllValues); } NotesCollectionData data = new NotesCollectionData(struct.docCount, struct.docTotalSize, struct.btreeLeafNodes, struct.btreeDepth, itemValueTables); return data; } finally { Mem32.OSUnlockObject(hCollData); result = Mem32.OSMemFree(hCollData); NotesErrorUtils.checkResult(result); } } } }
package us.myles.ViaVersion.boss; import com.google.common.base.Preconditions; import us.myles.ViaVersion.api.PacketWrapper; import us.myles.ViaVersion.api.Via; import us.myles.ViaVersion.api.boss.BossBar; import us.myles.ViaVersion.api.boss.BossColor; import us.myles.ViaVersion.api.boss.BossFlag; import us.myles.ViaVersion.api.boss.BossStyle; import us.myles.ViaVersion.api.data.UserConnection; import us.myles.ViaVersion.api.protocol.ProtocolVersion; import us.myles.ViaVersion.api.type.Type; import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9To1_8; import java.util.*; public abstract class CommonBoss<T> extends BossBar<T> { private final UUID uuid; private String title; private float health; private BossColor color; private BossStyle style; private final Set<UUID> players; private final Set<UserConnection> connections; private boolean visible; private final Set<BossFlag> flags; public CommonBoss(String title, float health, BossColor color, BossStyle style) { Preconditions.checkNotNull(title, "Title cannot be null"); Preconditions.checkArgument((health >= 0 && health <= 1), "Health must be between 0 and 1"); this.uuid = UUID.randomUUID(); this.title = title; this.health = health; this.color = color == null ? BossColor.PURPLE : color; this.style = style == null ? BossStyle.SOLID : style; this.players = new HashSet<>(); this.connections = Collections.newSetFromMap(new WeakHashMap<>()); this.flags = new HashSet<>(); visible = true; } @Override public BossBar setTitle(String title) { Preconditions.checkNotNull(title); this.title = title; sendPacket(CommonBoss.UpdateAction.UPDATE_TITLE); return this; } @Override public BossBar setHealth(float health) { Preconditions.checkArgument((health >= 0 && health <= 1), "Health must be between 0 and 1"); this.health = health; sendPacket(CommonBoss.UpdateAction.UPDATE_HEALTH); return this; } @Override public BossColor getColor() { return color; } @Override public BossBar setColor(BossColor color) { Preconditions.checkNotNull(color); this.color = color; sendPacket(CommonBoss.UpdateAction.UPDATE_STYLE); return this; } @Override public BossBar setStyle(BossStyle style) { Preconditions.checkNotNull(style); this.style = style; sendPacket(CommonBoss.UpdateAction.UPDATE_STYLE); return this; } @Override public BossBar addPlayer(UUID player) { if (!players.contains(player)) { players.add(player); if (visible) { UserConnection user = Via.getManager().getConnection(player); sendPacket(player, getPacket(CommonBoss.UpdateAction.ADD, user)); } } return this; } @Override public BossBar addConnection(UserConnection conn) { if (!connections.contains(conn)) { connections.add(conn); if (visible) { sendPacketConnection(conn, getPacket(CommonBoss.UpdateAction.ADD, conn)); } } return this; } @Override public BossBar removePlayer(UUID uuid) { if (players.contains(uuid)) { players.remove(uuid); UserConnection user = Via.getManager().getConnection(uuid); sendPacket(uuid, getPacket(UpdateAction.REMOVE, user)); } return this; } @Override public BossBar removeConnection(UserConnection conn) { if (connections.contains(conn)) { connections.remove(conn); sendPacketConnection(conn, getPacket(UpdateAction.REMOVE, conn)); } return this; } @Override public BossBar addFlag(BossFlag flag) { Preconditions.checkNotNull(flag); if (!hasFlag(flag)) flags.add(flag); sendPacket(CommonBoss.UpdateAction.UPDATE_FLAGS); return this; } @Override public BossBar removeFlag(BossFlag flag) { Preconditions.checkNotNull(flag); if (hasFlag(flag)) flags.remove(flag); sendPacket(CommonBoss.UpdateAction.UPDATE_FLAGS); return this; } @Override public boolean hasFlag(BossFlag flag) { Preconditions.checkNotNull(flag); return flags.contains(flag); } @Override public Set<UUID> getPlayers() { return Collections.unmodifiableSet(players); } @Override public Set<UserConnection> getConnections() { return Collections.unmodifiableSet(connections); } @Override public BossBar show() { setVisible(true); return this; } @Override public BossBar hide() { setVisible(false); return this; } @Override public boolean isVisible() { return visible; } @Override public UUID getId() { return uuid; } public UUID getUuid() { return uuid; } @Override public String getTitle() { return title; } @Override public float getHealth() { return health; } @Override public BossStyle getStyle() { return style; } public Set<BossFlag> getFlags() { return flags; } private void setVisible(boolean value) { if (visible != value) { visible = value; sendPacket(value ? CommonBoss.UpdateAction.ADD : CommonBoss.UpdateAction.REMOVE); } } private void sendPacket(UpdateAction action) { for (UUID uuid : new ArrayList<>(players)) { UserConnection connection = Via.getManager().getConnection(uuid); PacketWrapper wrapper = getPacket(action, connection); sendPacket(uuid, wrapper); } for (UserConnection conn : new ArrayList<>(connections)) { PacketWrapper wrapper = getPacket(action, conn); sendPacketConnection(conn, wrapper); } } private void sendPacket(UUID uuid, PacketWrapper wrapper) { if (!Via.getAPI().isInjected(uuid) || !(Via.getAPI().getPlayerVersion(uuid) >= ProtocolVersion.v1_9.getId())) { players.remove(uuid); return; } try { wrapper.send(Protocol1_9To1_8.class); } catch (Exception e) { e.printStackTrace(); } } private void sendPacketConnection(UserConnection conn, PacketWrapper wrapper) { if (conn.getProtocolInfo() == null || conn.getProtocolInfo().getProtocolVersion() < ProtocolVersion.v1_9.getId()) { connections.remove(conn); return; } try { wrapper.send(Protocol1_9To1_8.class); } catch (Exception e) { e.printStackTrace(); } } private PacketWrapper getPacket(UpdateAction action, UserConnection connection) { try { PacketWrapper wrapper = new PacketWrapper(0x0C, null, connection); // TODO don't use fixed packet ids for future support wrapper.write(Type.UUID, uuid); wrapper.write(Type.VAR_INT, action.getId()); switch (action) { case ADD: Protocol1_9To1_8.FIX_JSON.write(wrapper, title); wrapper.write(Type.FLOAT, health); wrapper.write(Type.VAR_INT, color.getId()); wrapper.write(Type.VAR_INT, style.getId()); wrapper.write(Type.BYTE, (byte) flagToBytes()); break; case REMOVE: break; case UPDATE_HEALTH: wrapper.write(Type.FLOAT, health); break; case UPDATE_TITLE: Protocol1_9To1_8.FIX_JSON.write(wrapper, title); break; case UPDATE_STYLE: wrapper.write(Type.VAR_INT, color.getId()); wrapper.write(Type.VAR_INT, style.getId()); break; case UPDATE_FLAGS: wrapper.write(Type.BYTE, (byte) flagToBytes()); break; } return wrapper; } catch (Exception e) { e.printStackTrace(); } return null; } private int flagToBytes() { int bitmask = 0; for (BossFlag flag : flags) bitmask |= flag.getId(); return bitmask; } private enum UpdateAction { ADD(0), REMOVE(1), UPDATE_HEALTH(2), UPDATE_TITLE(3), UPDATE_STYLE(4), UPDATE_FLAGS(5); private final int id; UpdateAction(int id) { this.id = id; } public int getId() { return id; } } }
package com.adaptc.mws.plugins; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.HttpsURLConnection; import java.io.File; public interface ISslService { /** * Generates a socket factory that automatically trusts all server certificates.<br/> * <b>WARNING</b>: If this socket factory is used, it may present a large security risk. Use only * during development and only when the risks are understood. * @return An SSLSocketFactory instance that may be used in the communication library of choice * @throws Exception On error initializing the SSL context */ public SSLSocketFactory getLenientSocketFactory() throws Exception; /** * Exactly the same as {@link #getLenientSocketFactory}, except the socket factory returned is the * HttpClient version instead of the java built-in version. * Identical to calling getLenientHttpClientSocketFactory(false). * @see #getLenientHttpClientSocketFactory(boolean) */ public org.apache.http.conn.ssl.SSLSocketFactory getLenientHttpClientSocketFactory() throws Exception; /** * Exactly the same as {@link #getLenientHttpClientSocketFactory}, except the socket factory returned is the * HttpClient version instead of the java built-in version. * @param useLenientHostnameVerifier If true, uses the {@link #getLenientHttpClientHostnameVerifier()} method to set the hostname verifier on the socket factory */ public org.apache.http.conn.ssl.SSLSocketFactory getLenientHttpClientSocketFactory( boolean useLenientHostnameVerifier) throws Exception; /** * Generates a hostname verifier that automatically trusts all host names.<br/> * <b>WARNING</b>: If this hostname verifier is used, it may present a large security risk. Use only * during development and only when the risks are understood. * @return A HostnameVerifier instance that may be used in the communication library of choice */ public HostnameVerifier getLenientHostnameVerifier(); /** * Exactly the same as {@link #getLenientHostnameVerifier}, except the hostname verifier returned is the * HttpClient version instead of the java built-in version. */ public org.apache.http.conn.ssl.X509HostnameVerifier getLenientHttpClientHostnameVerifier() throws Exception; /** * Generates a socket factory for the specified options. * <p/> * If the certificate file is a relative path (no leading '/'), it will be loaded * from the MWS certificates directory as documented. * @param clientCertificate The client certificate file to use * @param clientCertAlias The alias of the client certificate to use for socket communication, may be null to use the given certificate's alias * @return An SSLSocketFactory instance that may be used in the communication library of choice * @throws Exception On error initializing the SSL context or if the certificate(s) are invalid */ public SSLSocketFactory getSocketFactory(String clientCertificate, String clientCertAlias) throws Exception; /** * Exactly the same as {@link #getLenientSocketFactory}, except the socket factory returned is the * HttpClient version instead of the java built-in version. */ public org.apache.http.conn.ssl.SSLSocketFactory getHttpClientSocketFactory(String clientCertificate, String clientCertAlias) throws Exception; /** * Generates a socket factory for the specified options. * <p/> * If the certificate file or private key is a relative path (no leading '/'), it will be loaded * from the MWS certificates directory as documented. * @param clientCertificate The client certificate file to use * @param clientCertAlias The alias of the client certificate to use for socket communication, may be null to use the given certificate's alias * @param clientPrivateKey The client private key file to use * @param clientKeyPassword The password to decrypt the client certificate private key, may be null to use an unencrypted certificate * @return An SSLSocketFactory instance that may be used in the communication library of choice * @throws Exception On error initializing the SSL context or if the certificate(s) are invalid */ public SSLSocketFactory getSocketFactory(String clientCertificate, String clientCertAlias, String clientPrivateKey, String clientKeyPassword) throws Exception; /** * Exactly the same as {@link #getLenientSocketFactory}, except the socket factory returned is the * HttpClient version instead of the java built-in version. */ public org.apache.http.conn.ssl.SSLSocketFactory getHttpClientSocketFactory(String clientCertificate, String clientCertAlias, String clientPrivateKey, String clientKeyPassword) throws Exception; /** * Generates a socket factory for the specified options. * <p/> * If the client, private key, or server certificate file is a relative path (no leading '/'), it will be loaded * from the MWS certificates directory as documented. * @param serverCertificate The server certificate(s) or chain certificate to use (multiple certificates may be present in this file) * @return An SSLSocketFactory instance that may be used in the communication library of choice * @throws Exception On error initializing the SSL context or if the certificate(s) are invalid */ public SSLSocketFactory getSocketFactory(String serverCertificate) throws Exception; /** * Exactly the same as {@link #getLenientSocketFactory}, except the socket factory returned is the * HttpClient version instead of the java built-in version. */ public org.apache.http.conn.ssl.SSLSocketFactory getHttpClientSocketFactory(String serverCertificate) throws Exception; /** * Generates a socket factory for the specified options. * <p/> * If the client or server certificate file is a relative path (no leading '/'), it will be loaded * from the MWS certificates directory as documented. * @param clientCertificate The client certificate file to use * @param clientCertAlias The alias of the client certificate to use for socket communication, may be null to use the given certificate's alias * @param serverCertificate The server certificate(s) or chain certificate to use (multiple certificates may be present in this file) * @return An SSLSocketFactory instance that may be used in the communication library of choice * @throws Exception On error initializing the SSL context or if the certificate(s) are invalid */ public SSLSocketFactory getSocketFactory(String clientCertificate, String clientCertAlias, String serverCertificate) throws Exception; /** * Exactly the same as {@link #getLenientSocketFactory}, except the socket factory returned is the * HttpClient version instead of the java built-in version. */ public org.apache.http.conn.ssl.SSLSocketFactory getHttpClientSocketFactory(String clientCertificate, String clientCertAlias, String serverCertificate) throws Exception; /** * Generates a socket factory for the specified options. * <p/> * If the client, private key, or server certificate file is a relative path (no leading '/'), it will be loaded * from the MWS certificates directory as documented. * @param clientCertificate The client certificate file to use * @param clientCertAlias The alias of the client certificate to use for socket communication, may be null to use the given certificate's alias * @param clientPrivateKey The client private key file to use * @param clientKeyPassword The password to decrypt the client certificate private key, may be null to use an unencrypted certificate * @param serverCertificate The server certificate(s) or chain certificate to use (multiple certificates may be present in this file) * @return An SSLSocketFactory instance that may be used in the communication library of choice * @throws Exception On error initializing the SSL context or if the certificate(s) are invalid */ public SSLSocketFactory getSocketFactory(String clientCertificate, String clientCertAlias, String clientPrivateKey, String clientKeyPassword, String serverCertificate) throws Exception; /** * Exactly the same as {@link #getLenientSocketFactory}, except the socket factory returned is the * HttpClient version instead of the java built-in version. */ public org.apache.http.conn.ssl.SSLSocketFactory getHttpClientSocketFactory(String clientCertificate, String clientCertAlias, String clientPrivateKey, String clientKeyPassword, String serverCertificate) throws Exception; /** * Returns the file representing the certificate for the given filename. This includes accounting for relative * and absolute file paths and handling of the MWS certificates location. * @param filename The filename of the certificate, either absolute or relative. * @return The resulting file or null if filename is null */ public File getCertificateFile(String filename); }
package com.github.pedrovgs; import android.annotation.TargetApi; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v4.widget.ViewDragHelper; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.RelativeLayout; import android.widget.Toast; import com.nineoldandroids.view.ViewHelper; class DraggableView extends RelativeLayout { /* * Constants */ private static final String LOGTAG = "DraggableView"; private static final int SCALE_FACTOR = 2; private static final int DRAG_VIEW_MARGIN_RIGHT = 30; private static final int DRAG_VIEW_MARGIN_BOTTOM = 30; private static final float SLIDE_TOP = 0f; private static final float SLIDE_BOTTOM = 1f; private static final int MINIMUM_DY_FOR_VERTICAL_DRAG = 10; private static final int MINIMUN_DX_FOR_HORIZONTAL_DRAG = 20; /* * Attributes */ private View dragView; private View secondView; private FragmentManager fragmentManager; private ViewDragHelper viewDragHelper; private int lastActionMotionEvent = -1; /* * Constructors */ public DraggableView(Context context) { super(context); initializeView(); } public DraggableView(Context context, AttributeSet attrs) { super(context, attrs); initializeView(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public DraggableView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initializeView(); } public void setFragmentManager(FragmentManager fragmentManager) { this.fragmentManager = fragmentManager; } public void attachTopFragment(Fragment topFragment) { addFragmentToView(R.id.dragView, topFragment); } public void attachBottomFragment(Fragment bottomFragment) { addFragmentToView(R.id.secondView, bottomFragment); } private void addFragmentToView(final int viewId, final Fragment fragment) { fragmentManager.beginTransaction().replace(viewId, fragment).commit(); } private void initializeView() { viewDragHelper = ViewDragHelper.create(this, 1f, new DragPanelCallback()); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (!isInEditMode()) { dragView = findViewById(R.id.dragView); secondView = findViewById(R.id.secondView); hookListeners(); } } @Override public void computeScroll() { if (!isInEditMode() && viewDragHelper.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private void hookListeners() { dragView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getContext(), "Drag View touched", Toast.LENGTH_SHORT).show(); } }); secondView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getContext(), "Second View touched", Toast.LENGTH_SHORT).show(); } }); } private void changeDragViewPosition() { ViewHelper.setPivotX(dragView, dragView.getWidth() - getDragViewMarginRight()); ViewHelper.setPivotY(dragView, dragView.getHeight() - getDragViewMarginBottom()); } private void changeSeondViewPosition() { ViewHelper.setY(secondView, dragView.getTop() + dragView.getHeight()); } private int getDragViewMarginRight() { return DRAG_VIEW_MARGIN_RIGHT; } private int getDragViewMarginBottom() { return DRAG_VIEW_MARGIN_BOTTOM; } private void changeDragViewScale() { ViewHelper.setScaleX(dragView, 1 - getVerticalDragOffset() / SCALE_FACTOR); ViewHelper.setScaleY(dragView, 1 - getVerticalDragOffset() / SCALE_FACTOR); } private void changeBackgroundAlpha() { Drawable background = getBackground(); if (background != null) { int newAlpha = (int) (100 * (1 - getVerticalDragOffset())); background.setAlpha(newAlpha); } } private void changeSecondViewAlpha() { ViewHelper.setAlpha(secondView, 1 - getVerticalDragOffset()); } private void changeDragViewViewAlpha() { ViewHelper.setAlpha(dragView, 1 - getHorizontalDragOffset()); } private float getHorizontalDragOffset() { return (float) Math.abs(dragView.getLeft()) / (float) getWidth(); } private float getVerticalDragOffset() { return dragView.getTop() / getVierticalDragRange(); } private float getVierticalDragRange() { return getHeight() - dragView.getHeight(); } private boolean isHeaderAboveTheMiddle() { Log.d(LOGTAG, "isHeaderAboveTheMiddle"); int viewHeight = getHeight(); float viewHeaderY = ViewHelper.getY(dragView) + (dragView.getHeight() / 2); return viewHeaderY < (viewHeight * 0.5f); } public void maximize() { Log.d(LOGTAG, "maximize"); smoothSlideTo(SLIDE_TOP); } public void minimize() { Log.d(LOGTAG, "minimize"); smoothSlideTo(SLIDE_BOTTOM); } private boolean smoothSlideTo(float slideOffset) { final int topBound = getPaddingTop(); int y = (int) (topBound + slideOffset * getVierticalDragRange()); if (viewDragHelper.smoothSlideViewTo(dragView, 0, y)) { ViewCompat.postInvalidateOnAnimation(this); return true; } return false; } private void closeToRight() { if (viewDragHelper.smoothSlideViewTo(dragView, dragView.getWidth(), getHeight() - dragView.getHeight())) { ViewCompat.postInvalidateOnAnimation(this); } } private void closeToLeft() { if (viewDragHelper.smoothSlideViewTo(dragView, -dragView.getWidth(), getHeight() - dragView.getHeight())) { ViewCompat.postInvalidateOnAnimation(this); } } private boolean isMinimized() { return isDragViewAtBottom() && isDragViewAtRight(); } private boolean isMaximized() { return isDragViewAtTop(); } private boolean isNextToLeftBound() { return (dragView.getRight() - getDragViewMarginRight()) < getWidth() / 2; } private boolean isNextToRightBound() { return (dragView.getLeft() - getDragViewMarginRight()) > getWidth() * 0.25; } private boolean isDragViewAtTop() { return dragView.getTop() == 0; } private boolean isDragViewAtRight() { return dragView.getRight() >= (getWidth() - MINIMUN_DX_FOR_HORIZONTAL_DRAG); } private boolean isDragViewAtBottom() { return dragView.getTop() == (getHeight() - dragView.getHeight()); } public void setTopViewHeight(final int topFragmentHeight) { LayoutParams layoutParams = (LayoutParams) dragView.getLayoutParams(); layoutParams.height = topFragmentHeight; dragView.setLayoutParams(layoutParams); } /* * DragPanelCallback */ private class DragPanelCallback extends ViewDragHelper.Callback { @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { if (isDragViewAtBottom()) { changeDragViewViewAlpha(); } else { changeDragViewScale(); changeDragViewPosition(); changeSecondViewAlpha(); changeSeondViewPosition(); changeBackgroundAlpha(); } invalidate(); } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { super.onViewReleased(releasedChild, xvel, yvel); if (!isDragViewAtBottom()) { if (isHeaderAboveTheMiddle()) { maximize(); } else { minimize(); } } else { if (isNextToLeftBound()) { closeToLeft(); } else if (isNextToRightBound()) { closeToRight(); } else { minimize(); } } } @Override public boolean tryCaptureView(View view, int pointerId) { return view == dragView; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { int newLeft = 0; if (((isMinimized() && (dx > MINIMUN_DX_FOR_HORIZONTAL_DRAG || dx < -MINIMUN_DX_FOR_HORIZONTAL_DRAG))) || (isDragViewAtBottom())) { newLeft = left; } return newLeft; } @Override public int clampViewPositionVertical(View child, int top, int dy) { int newTop; if (isMinimized() && (dy >= MINIMUM_DY_FOR_VERTICAL_DRAG || dy >= -MINIMUM_DY_FOR_VERTICAL_DRAG) || (!isMinimized() && !isDragViewAtBottom())) { final int topBound = getPaddingTop(); final int bottomBound = getHeight() - child.getHeight() - child.getPaddingBottom(); newTop = Math.min(Math.max(top, topBound), bottomBound); } else { newTop = getHeight() - dragView.getHeight(); } return newTop; } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { final int action = MotionEventCompat.getActionMasked(ev); Log.d(LOGTAG, "onInterceptTouchEvent " + action); if ((action != MotionEvent.ACTION_DOWN)) { Log.d(LOGTAG, "ACTION_DOWN"); viewDragHelper.cancel(); return super.onInterceptTouchEvent(ev); } if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { Log.d(LOGTAG, "ACTION_CANCEL || ACTION_UP"); viewDragHelper.cancel(); return false; } final float x = ev.getX(); final float y = ev.getY(); boolean interceptTap = false; switch (action) { case MotionEvent.ACTION_DOWN: interceptTap = viewDragHelper.isViewUnder(dragView, (int) x, (int) y); break; case MotionEvent.ACTION_MOVE: interceptTap = false; } return viewDragHelper.shouldInterceptTouchEvent(ev) || interceptTap; } @Override public boolean onTouchEvent(MotionEvent ev) { Log.d(LOGTAG, "onTouchEvent"); viewDragHelper.processTouchEvent(ev); boolean dragViewTouched = isViewHit(dragView, (int) ev.getX(), (int) ev.getY()) && ev.getAction() == MotionEvent.ACTION_UP && lastActionMotionEvent != MotionEvent.ACTION_MOVE; if (dragViewTouched) { dragView.performClick(); } boolean secondViewTouched = isViewHit(secondView, (int) ev.getX(), (int) ev.getY()) && ev.getAction() == MotionEvent.ACTION_UP && lastActionMotionEvent != MotionEvent.ACTION_MOVE; if (secondViewTouched && !dragViewTouched) { secondView.performClick(); } lastActionMotionEvent = ev.getAction(); return true; } private boolean isViewHit(View view, int x, int y) { Log.d(LOGTAG, "isViewHit"); int[] viewLocation = new int[2]; view.getLocationOnScreen(viewLocation); int[] parentLocation = new int[2]; this.getLocationOnScreen(parentLocation); int screenX = parentLocation[0] + x; int screenY = parentLocation[1] + y; return screenX >= viewLocation[0] && screenX < viewLocation[0] + view.getWidth() && screenY >= viewLocation[1] && screenY < viewLocation[1] + view.getHeight(); } }
package org.neo4j.kernel; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.transaction.TransactionManager; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.kernel.impl.core.KernelPanicEventGenerator; import org.neo4j.kernel.impl.core.LockReleaser; import org.neo4j.kernel.impl.core.TxEventSyncHookFactory; import org.neo4j.kernel.impl.nioneo.xa.NioNeoDbPersistenceSource; import org.neo4j.kernel.impl.transaction.LockManager; import org.neo4j.kernel.impl.transaction.TxModule; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; import org.neo4j.kernel.impl.util.FileUtils; class GraphDbInstance { private boolean started = false; private boolean create; private String storeDir; GraphDbInstance( String storeDir, boolean create ) { this.storeDir = storeDir; this.create = create; } private Config config = null; private NioNeoDbPersistenceSource persistenceSource = null; public Config getConfig() { return config; } private Map<Object, Object> getDefaultParams() { Map<Object, Object> params = new HashMap<Object, Object>(); params.put( "neostore.nodestore.db.mapped_memory", "20M" ); params.put( "neostore.propertystore.db.mapped_memory", "90M" ); params.put( "neostore.propertystore.db.index.mapped_memory", "1M" ); params.put( "neostore.propertystore.db.index.keys.mapped_memory", "1M" ); params.put( "neostore.propertystore.db.strings.mapped_memory", "130M" ); params.put( "neostore.propertystore.db.arrays.mapped_memory", "130M" ); params.put( "neostore.relationshipstore.db.mapped_memory", "100M" ); // if on windows, default no memory mapping String nameOs = System.getProperty( "os.name" ); if ( nameOs.startsWith( "Windows" ) ) { params.put( Config.USE_MEMORY_MAPPED_BUFFERS, "false" ); } return params; } /** * Starts Neo4j with default configuration * @param graphDb The graph database service. * * @param storeDir path to directory where Neo4j store is located * @param create if true a new Neo4j store will be created if no store exist * at <CODE>storeDir</CODE> * @param configuration parameters * @throws StartupFailedException if unable to start */ public synchronized Map<Object, Object> start( GraphDatabaseService graphDb, Map<String, String> stringParams, KernelPanicEventGenerator kpe, TxEventSyncHookFactory syncHookFactory ) { if ( started ) { throw new IllegalStateException( "Neo4j instance already started" ); } Map<Object, Object> params = getDefaultParams(); boolean useMemoryMapped = true; if ( stringParams.containsKey( Config.USE_MEMORY_MAPPED_BUFFERS ) ) { params.put( Config.USE_MEMORY_MAPPED_BUFFERS, stringParams.get( Config.USE_MEMORY_MAPPED_BUFFERS ) ); } if ( "false".equals( params.get( Config.USE_MEMORY_MAPPED_BUFFERS ) ) ) { useMemoryMapped = false; } boolean dump = false; if ( "true".equals( stringParams.get( Config.DUMP_CONFIGURATION ) ) ) { dump = true; } storeDir = FileUtils.fixSeparatorsInPath( storeDir ); new AutoConfigurator( storeDir, useMemoryMapped, dump ).configure( params ); for ( Map.Entry<String, String> entry : stringParams.entrySet() ) { params.put( entry.getKey(), entry.getValue() ); } config = new Config( graphDb, storeDir, params, kpe ); String separator = System.getProperty( "file.separator" ); String store = storeDir + separator + "neostore"; params.put( "store_dir", storeDir ); params.put( "neo_store", store ); params.put( "create", String.valueOf( create ) ); String logicalLog = storeDir + separator + "nioneo_logical.log"; params.put( "logical_log", logicalLog ); byte resourceId[] = "414141".getBytes(); params.put( LockManager.class, config.getLockManager() ); params.put( LockReleaser.class, config.getLockReleaser() ); config.getTxModule().registerDataSource( Config.DEFAULT_DATA_SOURCE_NAME, Config.NIO_NEO_DB_CLASS, resourceId, params ); // hack for lucene index recovery if in path if ( !config.isReadOnly() || config.isBackupSlave() ) { try { Class clazz = Class.forName( Config.LUCENE_DS_CLASS ); cleanWriteLocksInLuceneDirectory( storeDir + "/lucene" ); byte luceneId[] = "162373".getBytes(); registerLuceneDataSource( "lucene", clazz.getName(), config.getTxModule(), storeDir + "/lucene", config.getLockManager(), luceneId, params ); } catch ( ClassNotFoundException e ) { // ok index util not on class path } try { Class clazz = Class.forName( Config.LUCENE_FULLTEXT_DS_CLASS ); cleanWriteLocksInLuceneDirectory( storeDir + "/lucene-fulltext" ); byte[] luceneId = "262374".getBytes(); registerLuceneDataSource( "lucene-fulltext", clazz.getName(), config.getTxModule(), storeDir + "/lucene-fulltext", config.getLockManager(), luceneId, params ); } catch ( ClassNotFoundException e ) { // ok index util not on class path } } persistenceSource = new NioNeoDbPersistenceSource(); config.setPersistenceSource( Config.DEFAULT_DATA_SOURCE_NAME, create ); config.getIdGeneratorModule().setPersistenceSourceInstance( persistenceSource ); config.getTxModule().init(); config.getPersistenceModule().init(); persistenceSource.init(); config.getIdGeneratorModule().init(); config.getGraphDbModule().init(); config.getTxModule().start(); config.getPersistenceModule().start( config.getTxModule().getTxManager(), persistenceSource, syncHookFactory ); persistenceSource.start( config.getTxModule().getXaDataSourceManager() ); config.getIdGeneratorModule().start(); config.getGraphDbModule().start( config.getLockReleaser(), config.getPersistenceModule().getPersistenceManager(), params ); if ( "true".equals( params.get( Config.DUMP_CONFIGURATION ) ) ) { for ( Object key : params.keySet() ) { if ( key instanceof String ) { Object value = params.get( key ); if ( value instanceof String ) { System.out.println( key + "=" + value ); } } } } started = true; return Collections.unmodifiableMap( params ); } private void cleanWriteLocksInLuceneDirectory( String luceneDir ) { File dir = new File( luceneDir ); if ( !dir.isDirectory() ) { return; } for ( File file : dir.listFiles() ) { if ( file.isDirectory() ) { cleanWriteLocksInLuceneDirectory( file.getAbsolutePath() ); } else if ( file.getName().equals( "write.lock" ) ) { boolean success = file.delete(); assert success; } } } private XaDataSource registerLuceneDataSource( String name, String className, TxModule txModule, String luceneDirectory, LockManager lockManager, byte[] resourceId, Map<Object,Object> params ) { params.put( "dir", luceneDirectory ); params.put( LockManager.class, lockManager ); return txModule.registerDataSource( name, className, resourceId, params, true ); } /** * Returns true if Neo4j is started. * * @return True if Neo4j started */ public boolean started() { return started; } /** * Shut down Neo4j. */ public synchronized void shutdown() { if ( started ) { config.getGraphDbModule().stop(); config.getIdGeneratorModule().stop(); persistenceSource.stop(); config.getPersistenceModule().stop(); config.getTxModule().stop(); config.getGraphDbModule().destroy(); config.getIdGeneratorModule().destroy(); persistenceSource.destroy(); config.getPersistenceModule().destroy(); config.getTxModule().destroy(); } started = false; } public Iterable<RelationshipType> getRelationshipTypes() { return config.getGraphDbModule().getRelationshipTypes(); } public boolean transactionRunning() { try { return config.getTxModule().getTxManager().getTransaction() != null; } catch ( Exception e ) { throw new TransactionFailureException( "Unable to get transaction.", e ); } } public TransactionManager getTransactionManager() { return config.getTxModule().getTxManager(); } }
package org.dspace.storage.bitstore; import java.io.*; import java.math.BigInteger; import java.security.*; import java.sql.SQLException; import java.util.*; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.Utils; import org.dspace.storage.rdbms.*; import org.apache.log4j.Logger; /** * Stores, retrieves and deletes bitstreams. * * @author Peter Breton * @version $Revision$ */ public class BitstreamStorageManager { // These settings control the way an identifier is hashed into // directory and file names // With digitsPerLevel 2 and directoryLevels 3, an identifier // like 12345678901234567890 turns into the relative name // /12/34/56/12345678901234567890. // You should not change these settings if you have data in the // asset store, as the BitstreamStorageManager will be unable // to find your existing data. private static final int digitsPerLevel = 2; private static final int directoryLevels = 3; /** Root directory (as String) */ private static String root = ConfigurationManager.getProperty("assetstore.dir"); /** Root directory (as File) */ private static File rootDirectory; /** Initialization flag */ private static boolean initialized = false; /** Algorithm for the MessageDigest */ private static final String DIGEST_ALGORITHM = "MD5"; /** log4j log */ private static Logger log = Logger.getLogger(BitstreamStorageManager.class); /** Private Constructor */ private BitstreamStorageManager () {} /** * Store a stream of bits. * * <p>If this method returns successfully, the bits have been stored, * and RDBMS metadata entries are in place (the context still * needs to be completed to finalize the transaction).</p> * * <p>If this method returns successfully and the context is aborted, * then the bits will be stored in the asset store and the RDBMS * metadata entries will exist, but with the deleted flag set.</p> * * If this method throws an exception, then any of the following * may be true: * * <ul> * <li>Neither bits nor RDBMS metadata entries have been stored. * <li>RDBMS metadata entries with the deleted flag set have been * stored, but no bits. * <li>RDBMS metadata entries with the deleted flag set have been * stored, and some or all of the bits have also been stored. * </ul> * * @param context The current context * @param is The stream of bits to store * @exception IOException If a problem occurs while storing the bits * @exception SQLException If a problem occurs accessing the RDBMS * * @return The ID of the stored bitstream */ public static int store(Context context, InputStream is) throws SQLException, IOException { initialize(); String id = Utils.generateKey(); TableRow bitstream = createDeletedBitstream(id); File file = forId(id, true); String fullname = file.getAbsolutePath(); FileOutputStream fos = new FileOutputStream(file); NumberBytesInputStream nbis = new NumberBytesInputStream(is); DigestInputStream dis = null; try { dis = new DigestInputStream(nbis, MessageDigest.getInstance(DIGEST_ALGORITHM)); } // Should never happen catch (NoSuchAlgorithmException nsae) { if (log.isDebugEnabled()) log.debug("Caught NoSuchAlgorithmException", nsae); } Utils.bufferedCopy(dis, fos); fos.close(); is.close(); bitstream.setColumn("size", nbis.getNumberOfBytesRead()); bitstream.setColumn("checksum", Utils.toHex(dis.getMessageDigest().digest())); bitstream.setColumn("checksum_algorithm", DIGEST_ALGORITHM); bitstream.setColumn("deleted", false); DatabaseManager.update(context, bitstream); int bitstream_id = bitstream.getIntColumn("bitstream_id"); if (log.isDebugEnabled()) log.debug("Stored bitstream " + bitstream_id + " in file " + fullname); return bitstream_id; } /** * Retrieve the bits for the bitstream with ID. If the bitstream * does not exist, or is marked deleted, returns null. * * @param context The current context * @param id The ID of the bitstream to retrieve * @exception IOException If a problem occurs while retrieving the bits * @exception SQLException If a problem occurs accessing the RDBMS * * @return The stream of bits, or null */ public static InputStream retrieve(Context context, int id) throws SQLException, IOException { initialize(); File file = forId(context, id, false); return (file != null) ? new FileInputStream(file) : null; } /** * <p>Remove a bitstream from the asset store. This method does * not delete any bits, but simply marks the bitstreams as deleted * (the context still needs to be completed to finalize the transaction). * </p> * * <p>If the context is aborted, the bitstreams deletion status * remains unchanged.</p> * * @param context The current context * @param id The ID of the bitstream to delete * @exception IOException If a problem occurs while deleting the bits * @exception SQLException If a problem occurs accessing the RDBMS */ public static void delete(Context context, int id) throws SQLException, IOException { initialize(); DatabaseManager.updateQuery (context, "update Bitstream set deleted = 't' where bitstream_id = " + id); } /** * Clean up the bitstream storage area. * This method deletes any bitstreams which are more than 1 hour * old and marked deleted. The deletions cannot be undone. * * @exception IOException If a problem occurs while cleaning up * @exception SQLException If a problem occurs accessing the RDBMS */ public static void cleanup() throws SQLException, IOException { initialize(); Context context = new Context(); try { List storage = DatabaseManager.query (context, "Bitstream", "select * from Bitstream where deleted = 't'").toList(); for (Iterator iterator = storage.iterator(); iterator.hasNext(); ) { TableRow row = (TableRow) iterator.next(); int bid = row.getIntColumn("bitstream_id"); File file = forId(getInternalId(context, bid)); // Make sure entries which do not exist are removed if (file == null) { DatabaseManager.delete (context, "Bitstream", bid); continue; } // This is a small chance that this is a file which is // being stored -- get it next time. if (isRecent(file)) continue; DatabaseManager.delete (context, "Bitstream", bid); boolean success = file.delete(); if (log.isDebugEnabled()) log.debug("Deleted bitstream " + bid + " (file " + file.getAbsolutePath() + ") with result " + success); deleteParents(file); } context.complete(); } // Aborting will leave the DB objects around, even if the // bitstreams are deleted. This is OK; deleting them next // time around will be a no-op. catch (SQLException sqle) { context.abort(); throw sqle; } catch (IOException ioe) { context.abort(); throw ioe; } } // Internal methods /** * Set the assetstore root (for testing). * * @param dir The new asset store directory root * @return The previous assetstore root * @exception IOException If there is a problem with the asset store * directory */ protected static String setRoot(String dir) throws IOException { String previous = root; root = dir; initializeInternal(); return previous; } /** * Set the assetstore root to its default value (for testing). * * @return The previous assetstore root * @exception IOException If there is a problem with the asset store * directory */ protected static String setRoot() throws IOException { return setRoot(ConfigurationManager.getProperty("assetstore.dir")); } /** * Return true if this file is too recent to be deleted, * false otherwise. * * @param file The file to check * @return True if this file is too recent to be deleted */ private static boolean isRecent(File file) { long lastmod = file.lastModified(); long now = new java.util.Date().getTime(); if (lastmod >= now) return true; // Less than one hour old return now - lastmod < (1 * 60 * 1000); } /** * Delete empty parent directories. * * @param file The file with parent directories to delete */ private synchronized static void deleteParents(File file) { if (file == null) return; File tmp = file; for (int i = 0; i < directoryLevels; i++) { File directory = tmp.getParentFile(); File[] files = directory.listFiles(); // Only delete empty directories if (files.length != 0) break; directory.delete(); tmp = directory; } } /** * Initialize the storage area. Calling this method multiple times * only initializes once. * * @exception IOException If there is a problem with the asset store * directory */ private synchronized static void initialize() throws IOException { if (initialized) return; initializeInternal(); initialized = true; } /** * Initialize the storage area. * * @exception IOException If there is a problem with the asset store * directory */ private synchronized static void initializeInternal() throws IOException { File dir = new File(root); // Sanity checks if (!dir.exists()) throw new IOException("Asset store directory \"" + root + "\" does not exist"); if (!dir.isDirectory()) throw new IOException("\"" + root + "\" is not a directory"); if (!dir.canRead()) throw new IOException("Cannot read from \"" + root + "\""); if (!dir.canWrite()) throw new IOException("Cannot write to \"" + root + "\""); rootDirectory = dir; } /** * Return the file corresponding to ID, or null. * * @param context The current context * @param id The ID of the bitstream * @param includeDeleted If true, deleted bitstreams will be considered. * @return The file corresponding to ID, or null * @exception IOException If a problem occurs while determining the file * @exception SQLException If a problem occurs accessing the RDBMS */ protected static File forId(Context context, int id, boolean includeDeleted) throws IOException, SQLException { String sql = new StringBuffer() .append("select * from Bitstream where Bitstream.bitstream_id = ") .append(id) .append(includeDeleted ? "" : " and deleted = 'f'") .toString(); TableRow row = DatabaseManager.querySingle (context, "Bitstream", sql); return row == null ? null : forId(row.getStringColumn("internal_id"), false); } /** * Returns the file corresponding to ID, or null. * * @param id The internal storage ID * @return The file corresponding to ID, or null * @exception IOException If a problem occurs while determining the file */ protected static File forId(String id) throws IOException { return forId(id, false); } /** * Returns the file corresponding to ID. * If CREATE is true and the file does not exist, it is created. * Otherwise, null is returned. * * @param id The internal storage ID * @param create If true, and the file does not exist, it will be * created. * @return The file corresponding to ID, or null * @exception IOException If a problem occurs while determining the file */ private static File forId(String id, boolean create) throws IOException { File file = new File(id2Filename(id)); if (file.exists()) return file; if (!create) return null; File parent = file.getParentFile(); if (!parent.exists()) parent.mkdirs(); file.createNewFile(); return file; } /** * Maps ID to full filename. * * @param id The internal storage ID * @return The full filename * @exception IOException If a problem occurs while determining the * file name */ private static String id2Filename(String id) throws IOException { BigInteger bigint = new BigInteger(id); StringBuffer result = new StringBuffer().append(rootDirectory.getCanonicalPath()); // Split the id into groups for (int i = 0; i < directoryLevels; i++) { int digits = i * digitsPerLevel; result.append(File.separator).append(id.substring(digits, digits + digitsPerLevel)); } String theName = result.append(File.separator).append(id).toString(); if (log.isDebugEnabled()) log.debug("Filename for " + id + " is " + theName); return theName; } // RDBMS methods /** * Create and return a bitstream with ID which is marked deleted. */ private static TableRow createDeletedBitstream(String id) throws SQLException, IOException { Context context = new Context(); TableRow bitstream = DatabaseManager.create(context, "Bitstream"); bitstream.setColumn("deleted", true); bitstream.setColumn("internal_id", id); DatabaseManager.update(context, bitstream); context.complete(); return bitstream; } /** * Return the internal storage id for the bitstream with ID, * or null. */ private static String getInternalId(Context context, int id) throws SQLException { TableRow row = DatabaseManager.querySingle (context, "Bitstream", "select * from Bitstream where bitstream_id = " + id); return row == null ? null : row.getStringColumn("internal_id"); } } /** * Simple filter which counts the number of bytes read. */ class NumberBytesInputStream extends FilterInputStream { /** Number of bytes read */ private int count = 0; /** * Constructor * * @param is The stream to filter. */ public NumberBytesInputStream (InputStream is) { super(is); } // FilterInputStream methods public int read() throws java.io.IOException { int result = in.read(); if (result != -1) count++; return result; } public int read(byte[] data) throws java.io.IOException { int result = in.read(data); if (result != -1) count += result; return result; } public int read(byte[] data, int start, int length) throws java.io.IOException { int result = in.read(data, start, length); if (result != -1) count += result; return result; } public long skip(long length) throws java.io.IOException { long result = in.skip(length); count += (int) result; return result; } public boolean markSupported() { return false; } // non-interface methods /** * Return the number of bytes read from the stream. * * @return The number of bytes read from the stream. */ public int getNumberOfBytesRead() { return count; } }
package org.jeasy.jobs.server; import org.jeasy.jobs.ContextConfiguration; import org.jeasy.jobs.job.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import javax.sql.DataSource; import java.io.File; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; @EnableAutoConfiguration(exclude = HibernateJpaAutoConfiguration.class) @ComponentScan("org.jeasy.jobs.server") public class JobServer { private static final Logger LOGGER = LoggerFactory.getLogger(JobServer.class); private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor(); public static void main(String[] args) { JobDefinitions jobDefinitions = failFastLoadJobDefinitions(); ConfigurableApplicationContext applicationContext = SpringApplication.run(new Object[]{JobServer.class, ContextConfiguration.class}, args); JobServerConfiguration jobServerConfiguration = new JobServerConfiguration.Loader().loadServerConfiguration(); LOGGER.info("Using job server configuration: " + jobServerConfiguration); if (jobServerConfiguration.isDatabaseInit()) { DataSource dataSource = applicationContext.getBean(DataSource.class); LOGGER.info("Initializing database"); DatabaseInitializer databaseInitializer = applicationContext.getBean(DatabaseInitializer.class); databaseInitializer.init(dataSource, jobDefinitions); } JobService jobService = applicationContext.getBean(JobService.class); jobService.setExecutorService(executorService(jobServerConfiguration.getWorkersNumber())); jobService.setJobDefinitions(jobDefinitions.mapJobDefinitionsToJobIdentifiers()); JobRequestPoller jobRequestPoller = new JobRequestPoller(jobService); SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(jobRequestPoller, 0, jobServerConfiguration.getPollingInterval(), TimeUnit.SECONDS); LOGGER.info("Job server started"); registerShutdownHook(); } private static JobDefinitions failFastLoadJobDefinitions() { JobDefinitions jobDefinitions = null; String configurationPath = System.getProperty(JobDefinitions.JOBS_DEFINITIONS_CONFIGURATION_FILE_PARAMETER_NAME); if (configurationPath == null) { LOGGER.error("No jobs configuration file specified. Jobs configuration file is mandatory to load job definitions." + "Please provide a JVM property -D" + JobDefinitions.JOBS_DEFINITIONS_CONFIGURATION_FILE_PARAMETER_NAME + "=/path/to/jobs/configuration/file"); System.exit(1); } try { jobDefinitions = new JobDefinitions.Reader().read(new File(configurationPath)); } catch (Exception e) { LOGGER.error("Unable to load jobs configuration from file " + configurationPath, e); System.exit(1); } return jobDefinitions; } private static void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { SCHEDULED_EXECUTOR_SERVICE.shutdownNow(); LOGGER.info("Job manager stopped"); })); } private static ExecutorService executorService(int workersNumber) { final AtomicLong count = new AtomicLong(0); return Executors.newFixedThreadPool(workersNumber, r -> { Thread thread = new Thread(r); thread.setName("worker-thread-" + count.incrementAndGet()); // make this configurable: easy.jobs.server.config.workers.name.prefix return thread; }); } }
package sizzle.functions; import sizzle.types.Ast.Declaration; import sizzle.types.Ast.Method; import sizzle.types.Ast.Modifier; import sizzle.types.Ast.Modifier.ModifierKind; import sizzle.types.Ast.Modifier.Visibility; import sizzle.types.Ast.Namespace; import sizzle.types.Ast.Variable; /** * Boa domain-specific functions for working with the Modifier type. * * @author rdyer */ public class BoaModifierIntrinsics { /** * Returns a specific Annotation Modifier, if it exists otherwise returns null. * * @param m the Method to check * @param name the annotation to look for * @return the annotation Modifier or null */ @FunctionSpec(name = "get_annotation", returnType = "Modifier", formalParameters = { "Method", "string" }) public static Modifier getAnnotation(final Method m, final String name) { for (int i = 0; i < m.getModifiersCount(); i++) { Modifier mod = m.getModifiers(i); if (mod.getKind() == ModifierKind.ANNOTATION && mod.getAnnotationName().equals(name)) return mod; } return null; } /** * Returns if the Method has the specified modifier. * * @param m the Method to examine * @param kind the ModifierKind to test for * @return true if m contains a modifier kind */ @FunctionSpec(name = "has_modifier", returnType = "bool", formalParameters = { "Method", "int" }) public static boolean hasModifier(final Method m, final ModifierKind kind) { for (int i = 0; i < m.getModifiersCount(); i++) if (m.getModifiers(i).getKind() == kind) return true; return false; } /** * Returns if the Method has the specified visibility modifier. * * @param m the Method to examine * @param v the Visibility modifier to test for * @return true if m contains a visibility modifier v */ @FunctionSpec(name = "has_visibility", returnType = "bool", formalParameters = { "Method", "int" }) public static boolean hasVisibility(final Method m, final Visibility v) { for (int i = 0; i < m.getModifiersCount(); i++) if (m.getModifiers(i).getKind() == ModifierKind.VISIBILITY && (m.getModifiers(i).getVisibility() & v.getNumber()) == v.getNumber()) return true; return false; } /** * Returns if the Method has a FINAL modifier. * * @param m the Method to check * @return true if m has a FINAL modifier */ @FunctionSpec(name = "has_modifier_final", returnType = "bool", formalParameters = { "Method" }) public static boolean hasModifierFinal(final Method m) { return hasModifier(m, ModifierKind.FINAL); } /** * Returns if the Method has a STATIC modifier. * * @param m the Method to check * @return true if m has a STATIC modifier */ @FunctionSpec(name = "has_modifier_static", returnType = "bool", formalParameters = { "Method" }) public static boolean hasModifierStatic(final Method m) { return hasModifier(m, ModifierKind.STATIC); } /** * Returns if the Method has a SYNCHRONIZED modifier. * * @param m the Method to check * @return true if m has a SYNCHRONIZED modifier */ @FunctionSpec(name = "has_modifier_synchronized", returnType = "bool", formalParameters = { "Method" }) public static boolean hasModifierSynchronized(final Method m) { return hasModifier(m, ModifierKind.SYNCHRONIZED); } /** * Returns if the Method has an Annotation. * * @param m the Method to check * @return true if m has an annotation */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Method" }) public static boolean hasAnnotation(final Method m) { return hasModifier(m, ModifierKind.ANNOTATION); } /** * Returns if the Method has an Annotation with the given name. * * @param m the Method to check * @param name the annotation name to look for * @return true if m has an annotation with the given name */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Method", "string" }) public static boolean hasAnnotation(final Method m, final String name) { return getAnnotation(m, name) != null; } /** * Returns if the Method has a PUBLIC visibility modifier. * * @param m the Method to check * @return true if m has a PUBLIC visibility modifier */ @FunctionSpec(name = "has_modifier_public", returnType = "bool", formalParameters = { "Method" }) public static boolean hasModifierPublic(final Method m) { return hasVisibility(m, Visibility.PUBLIC); } /** * Returns if the Method has a PRIVATE visibility modifier. * * @param m the Method to check * @return true if m has a PRIVATE visibility modifier */ @FunctionSpec(name = "has_modifier_private", returnType = "bool", formalParameters = { "Method" }) public static boolean hasModifierPrivate(final Method m) { return hasVisibility(m, Visibility.PRIVATE); } /** * Returns if the Method has a PROTECTED visibility modifier. * * @param m the Method to check * @return true if m has a PROTECTED visibility modifier */ @FunctionSpec(name = "has_modifier_protected", returnType = "bool", formalParameters = { "Method" }) public static boolean hasModifierProtected(final Method m) { return hasVisibility(m, Visibility.PROTECTED); } /** * Returns if the Method has a NAMESPACE visibility modifier. * * @param m the Method to check * @return true if m has a NAMESPACE visibility modifier */ @FunctionSpec(name = "has_modifier_namespace", returnType = "bool", formalParameters = { "Method" }) public static boolean hasModifierNamespace(final Method m) { return hasVisibility(m, Visibility.NAMESPACE); } /** * Returns a specific Annotation Modifier, if it exists otherwise returns null. * * @param v the Variable to check * @param name the annotation to look for * @return the annotation Modifier or null */ @FunctionSpec(name = "get_annotation", returnType = "Modifier", formalParameters = { "Variable", "string" }) public static Modifier getAnnotation(final Variable v, final String name) { for (int i = 0; i < v.getModifiersCount(); i++) { Modifier mod = v.getModifiers(i); if (mod.getKind() == ModifierKind.ANNOTATION && mod.getAnnotationName().equals(name)) return mod; } return null; } /** * Returns if the Variable has the specified modifier. * * @param v the Variable to examine * @param kind the ModifierKind to test for * @return true if v contains a modifier kind */ @FunctionSpec(name = "has_modifier", returnType = "bool", formalParameters = { "Variable", "int" }) public static boolean hasModifier(final Variable v, final ModifierKind kind) { for (int i = 0; i < v.getModifiersCount(); i++) if (v.getModifiers(i).getKind() == kind) return true; return false; } /** * Returns if the Variable has the specified visibility modifier. * * @param var the Variable to examine * @param v the Visibility modifier to test for * @return true if v contains a visibility modifier v */ @FunctionSpec(name = "has_visibility", returnType = "bool", formalParameters = { "Variable", "int" }) public static boolean hasVisibility(final Variable var, final Visibility v) { for (int i = 0; i < var.getModifiersCount(); i++) if (var.getModifiers(i).getKind() == ModifierKind.VISIBILITY && (var.getModifiers(i).getVisibility() & v.getNumber()) == v.getNumber()) return true; return false; } /** * Returns if the Variable has a FINAL modifier. * * @param v the Variable to check * @return true if v has a FINAL modifier */ @FunctionSpec(name = "has_modifier_final", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasModifierFinal(final Variable v) { return hasModifier(v, ModifierKind.FINAL); } /** * Returns if the Variable has a STATIC modifier. * * @param v the Variable to check * @return true if v has a STATIC modifier */ @FunctionSpec(name = "has_modifier_static", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasModifierStatic(final Variable v) { return hasModifier(v, ModifierKind.STATIC); } /** * Returns if the Variable has a SYNCHRONIZED modifier. * * @param v the Variable to check * @return true if v has a SYNCHRONIZED modifier */ @FunctionSpec(name = "has_modifier_synchronized", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasModifierSynchronized(final Variable v) { return hasModifier(v, ModifierKind.SYNCHRONIZED); } /** * Returns if the Variable has an Annotation. * * @param v the Variable to check * @return true if v has an annotation */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasAnnotation(final Variable v) { return hasModifier(v, ModifierKind.ANNOTATION); } /** * Returns if the Variable has an Annotation with the given name. * * @param v the Variable to check * @param name the annotation name to look for * @return true if v has an annotation with the given name */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Variable", "string" }) public static boolean hasAnnotation(final Variable v, final String name) { return getAnnotation(v, name) != null; } /** * Returns if the Variable has a PUBLIC visibility modifier. * * @param v the Variable to check * @return true if v has a PUBLIC visibility modifier */ @FunctionSpec(name = "has_modifier_public", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasModifierPublic(final Variable v) { return hasVisibility(v, Visibility.PUBLIC); } /** * Returns if the Variable has a PRIVATE visibility modifier. * * @param v the Variable to check * @return true if v has a PRIVATE visibility modifier */ @FunctionSpec(name = "has_modifier_private", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasModifierPrivate(final Variable v) { return hasVisibility(v, Visibility.PRIVATE); } /** * Returns if the Variable has a PROTECTED visibility modifier. * * @param v the Variable to check * @return true if v has a PROTECTED visibility modifier */ @FunctionSpec(name = "has_modifier_protected", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasModifierProtected(final Variable v) { return hasVisibility(v, Visibility.PROTECTED); } /** * Returns if the Variable has a NAMESPACE visibility modifier. * * @param v the Variable to check * @return true if v has a NAMESPACE visibility modifier */ @FunctionSpec(name = "has_modifier_namespace", returnType = "bool", formalParameters = { "Variable" }) public static boolean hasModifierNamespace(final Variable v) { return hasVisibility(v, Visibility.NAMESPACE); } /** * Returns a specific Annotation Modifier, if it exists otherwise returns null. * * @param d the Declaration to check * @param name the annotation to look for * @return the annotation Modifier or null */ @FunctionSpec(name = "get_annotation", returnType = "Modifier", formalParameters = { "Declaration", "string" }) public static Modifier getAnnotation(final Declaration d, final String name) { for (int i = 0; i < d.getModifiersCount(); i++) { Modifier mod = d.getModifiers(i); if (mod.getKind() == ModifierKind.ANNOTATION && mod.getAnnotationName().equals(name)) return mod; } return null; } /** * Returns if the Declaration has the specified modifier. * * @param d the Declaration to examine * @param kind the ModifierKind to test for * @return true if d contains a modifier kind */ @FunctionSpec(name = "has_modifier", returnType = "bool", formalParameters = { "Declaration", "int" }) public static boolean hasModifier(final Declaration d, final ModifierKind kind) { for (int i = 0; i < d.getModifiersCount(); i++) if (d.getModifiers(i).getKind() == kind) return true; return false; } /** * Returns if the Declaration has the specified visibility modifier. * * @param d the Declaration to examine * @param v the Visibility modifier to test for * @return true if d contains a visibility modifier v */ @FunctionSpec(name = "has_visibility", returnType = "bool", formalParameters = { "Declaration", "int" }) public static boolean hasVisibility(final Declaration d, final Visibility v) { for (int i = 0; i < d.getModifiersCount(); i++) if (d.getModifiers(i).getKind() == ModifierKind.VISIBILITY && (d.getModifiers(i).getVisibility() & v.getNumber()) == v.getNumber()) return true; return false; } /** * Returns if the Declaration has a FINAL modifier. * * @param d the Declaration to check * @return true if d has a FINAL modifier */ @FunctionSpec(name = "has_modifier_final", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasModifierFinal(final Declaration d) { return hasModifier(d, ModifierKind.FINAL); } /** * Returns if the Declaration has a STATIC modifier. * * @param d the Declaration to check * @return true if d has a STATIC modifier */ @FunctionSpec(name = "has_modifier_static", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasModifierStatic(final Declaration d) { return hasModifier(d, ModifierKind.STATIC); } /** * Returns if the Declaration has a SYNCHRONIZED modifier. * * @param d the Declaration to check * @return true if d has a SYNCHRONIZED modifier */ @FunctionSpec(name = "has_modifier_synchronized", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasModifierSynchronized(final Declaration d) { return hasModifier(d, ModifierKind.SYNCHRONIZED); } /** * Returns if the Declaration has an Annotation. * * @param d the Declaration to check * @return true if d has an annotation */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasAnnotation(final Declaration d) { return hasModifier(d, ModifierKind.ANNOTATION); } /** * Returns if the Declaration has an Annotation with the given name. * * @param d the Declaration to check * @param name the annotation name to look for * @return true if d has an annotation with the given name */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Declaration", "string" }) public static boolean hasAnnotation(final Declaration d, final String name) { return getAnnotation(d, name) != null; } /** * Returns if the Declaration has a PUBLIC visibility modifier. * * @param d the Declaration to check * @return true if d has a PUBLIC visibility modifier */ @FunctionSpec(name = "has_modifier_public", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasModifierPublic(final Declaration d) { return hasVisibility(d, Visibility.PUBLIC); } /** * Returns if the Declaration has a PRIVATE visibility modifier. * * @param d the Declaration to check * @return true if d has a PRIVATE visibility modifier */ @FunctionSpec(name = "has_modifier_private", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasModifierPrivate(final Declaration d) { return hasVisibility(d, Visibility.PRIVATE); } /** * Returns if the Declaration has a PROTECTED visibility modifier. * * @param d the Declaration to check * @return true if d has a PROTECTED visibility modifier */ @FunctionSpec(name = "has_modifier_protected", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasModifierProtected(final Declaration d) { return hasVisibility(d, Visibility.PROTECTED); } /** * Returns if the Declaration has a NAMESPACE visibility modifier. * * @param d the Declaration to check * @return true if d has a NAMESPACE visibility modifier */ @FunctionSpec(name = "has_modifier_namespace", returnType = "bool", formalParameters = { "Declaration" }) public static boolean hasModifierNamespace(final Declaration d) { return hasVisibility(d, Visibility.NAMESPACE); } /** * Returns a specific Annotation Modifier, if it exists otherwise returns null. * * @param d the Namespace to check * @param name the annotation to look for * @return the annotation Modifier or null */ @FunctionSpec(name = "get_annotation", returnType = "Modifier", formalParameters = { "Namespace", "string" }) public static Modifier getAnnotation(final Namespace n, final String name) { for (int i = 0; i < n.getModifiersCount(); i++) { Modifier mod = n.getModifiers(i); if (mod.getKind() == ModifierKind.ANNOTATION && mod.getAnnotationName().equals(name)) return mod; } return null; } /** * Returns if the Namespace has the specified modifier. * * @param d the Namespace to examine * @param kind the ModifierKind to test for * @return true if d contains a modifier kind */ @FunctionSpec(name = "has_modifier", returnType = "bool", formalParameters = { "Namespace", "int" }) public static boolean hasModifier(final Namespace n, final ModifierKind kind) { for (int i = 0; i < n.getModifiersCount(); i++) if (n.getModifiers(i).getKind() == kind) return true; return false; } /** * Returns if the Namespace has the specified visibility modifier. * * @param d the Namespace to examine * @param v the Visibility modifier to test for * @return true if d contains a visibility modifier v */ @FunctionSpec(name = "has_visibility", returnType = "bool", formalParameters = { "Namespace", "int" }) public static boolean hasVisibility(final Namespace n, final Visibility v) { for (int i = 0; i < n.getModifiersCount(); i++) if (n.getModifiers(i).getKind() == ModifierKind.VISIBILITY && (n.getModifiers(i).getVisibility() & v.getNumber()) == v.getNumber()) return true; return false; } /** * Returns if the Namespace has a FINAL modifier. * * @param d the Namespace to check * @return true if d has a FINAL modifier */ @FunctionSpec(name = "has_modifier_final", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasModifierFinal(final Namespace n) { return hasModifier(n, ModifierKind.FINAL); } /** * Returns if the Namespace has a STATIC modifier. * * @param d the Namespace to check * @return true if d has a STATIC modifier */ @FunctionSpec(name = "has_modifier_static", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasModifierStatic(final Namespace n) { return hasModifier(n, ModifierKind.STATIC); } /** * Returns if the Namespace has a SYNCHRONIZED modifier. * * @param d the Namespace to check * @return true if d has a SYNCHRONIZED modifier */ @FunctionSpec(name = "has_modifier_synchronized", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasModifierSynchronized(final Namespace n) { return hasModifier(n, ModifierKind.SYNCHRONIZED); } /** * Returns if the Namespace has an Annotation. * * @param d the Namespace to check * @return true if d has an annotation */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasAnnotation(final Namespace n) { return hasModifier(n, ModifierKind.ANNOTATION); } /** * Returns if the Namespace has an Annotation with the given name. * * @param d the Namespace to check * @param name the annotation name to look for * @return true if d has an annotation with the given name */ @FunctionSpec(name = "has_annotation", returnType = "bool", formalParameters = { "Namespace", "string" }) public static boolean hasAnnotation(final Namespace n, final String name) { return getAnnotation(n, name) != null; } /** * Returns if the Namespace has a PUBLIC visibility modifier. * * @param d the Namespace to check * @return true if d has a PUBLIC visibility modifier */ @FunctionSpec(name = "has_modifier_public", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasModifierPublic(final Namespace n) { return hasVisibility(n, Visibility.PUBLIC); } /** * Returns if the Namespace has a PRIVATE visibility modifier. * * @param d the Namespace to check * @return true if d has a PRIVATE visibility modifier */ @FunctionSpec(name = "has_modifier_private", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasModifierPrivate(final Namespace n) { return hasVisibility(n, Visibility.PRIVATE); } /** * Returns if the Namespace has a PROTECTED visibility modifier. * * @param d the Namespace to check * @return true if d has a PROTECTED visibility modifier */ @FunctionSpec(name = "has_modifier_protected", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasModifierProtected(final Namespace n) { return hasVisibility(n, Visibility.PROTECTED); } /** * Returns if the Namespace has a NAMESPACE visibility modifier. * * @param d the Namespace to check * @return true if d has a NAMESPACE visibility modifier */ @FunctionSpec(name = "has_modifier_namespace", returnType = "bool", formalParameters = { "Namespace" }) public static boolean hasModifierNamespace(final Namespace n) { return hasVisibility(n, Visibility.NAMESPACE); } }
// OMETiffReader.java package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveInteger; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.IFormatReader; import loci.formats.MissingLibraryException; import loci.formats.ome.OMEXMLMetadata; import loci.formats.services.OMEXMLService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffParser; public class OMETiffReader extends FormatReader { // -- Constants -- public static final String NO_OME_XML_MSG = "ome-xml.jar is required to read OME-TIFF files. " + "Please download it from " + FormatTools.URL_BIO_FORMATS_LIBRARIES; // -- Fields -- /** Mapping from series and plane numbers to files and IFD entries. */ protected OMETiffPlane[][] info; // dimensioned [numSeries][numPlanes] /** List of used files. */ protected String[] used; private int lastPlane; private boolean hasSPW; // -- Constructor -- /** Constructs a new OME-TIFF reader. */ public OMETiffReader() { super("OME-TIFF", new String[] {"ome.tif", "ome.tiff"}); suffixNecessary = false; suffixSufficient = false; domains = FormatTools.NON_GRAPHICS_DOMAINS; hasCompanionFiles = true; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFD ifd = tp.getFirstIFD(); long[] ifdOffsets = tp.getIFDOffsets(); ras.close(); String xml = ifd.getComment(); OMEXMLMetadata meta; try { ServiceFactory factory = new ServiceFactory(); OMEXMLService service = factory.getInstance(OMEXMLService.class); meta = service.createOMEXMLMetadata(xml); } catch (DependencyException de) { throw new MissingLibraryException(NO_OME_XML_MSG, de); } catch (ServiceException se) { throw new FormatException(se); } if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } int nImages = 0; for (int i=0; i<meta.getImageCount(); i++) { int nChannels = meta.getChannelCount(i); if (nChannels == 0) nChannels = 1; int z = meta.getPixelsSizeZ(i).getValue().intValue(); int t = meta.getPixelsSizeT(i).getValue().intValue(); nImages += z * t * nChannels; } return nImages <= ifdOffsets.length; } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); boolean validHeader = tp.isValidHeader(); if (!validHeader) return false; // look for OME-XML in first IFD's comment IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; String comment = ifd.getComment(); if (comment == null || comment.trim().length() == 0) return false; try { ServiceFactory factory = new ServiceFactory(); OMEXMLService service = factory.getInstance(OMEXMLService.class); service.createOMEXMLMetadata(comment.trim()); return true; } catch (DependencyException de) { } catch (ServiceException se) { } catch (NullPointerException e) { } return false; } /* @see loci.formats.IFormatReader#getDomains() */ public String[] getDomains() { FormatTools.assertId(currentId, true, 1); return hasSPW ? new String[] {FormatTools.HCS_DOMAIN} : FormatTools.NON_SPECIAL_DOMAINS; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { if (info[series][lastPlane] == null || info[series][lastPlane].reader == null || info[series][lastPlane].id == null) { return null; } info[series][lastPlane].reader.setId(info[series][lastPlane].id); return info[series][lastPlane].reader.get8BitLookupTable(); } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { if (info[series][lastPlane] == null || info[series][lastPlane].reader == null || info[series][lastPlane].id == null) { return null; } info[series][lastPlane].reader.setId(info[series][lastPlane].id); return info[series][lastPlane].reader.get16BitLookupTable(); } /* * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); lastPlane = no; int i = info[series][no].ifd; MinimalTiffReader r = (MinimalTiffReader) info[series][no].reader; if (r.getCurrentFile() == null) { r.setId(info[series][no].id); } IFDList ifdList = r.getIFDs(); if (i >= ifdList.size()) { LOGGER.warn("Error untangling IFDs; the OME-TIFF file may be malformed."); return buf; } IFD ifd = ifdList.get(i); RandomAccessInputStream s = new RandomAccessInputStream(info[series][no].id); TiffParser p = new TiffParser(s); p.getSamples(ifd, buf, x, y, w, h); s.close(); return buf; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (noPixels) return null; Vector<String> usedFiles = new Vector<String>(); for (int i=0; i<info[series].length; i++) { if (!usedFiles.contains(info[series][i].id)) { usedFiles.add(info[series][i].id); } } return usedFiles.toArray(new String[usedFiles.size()]); } /* @see loci.formats.IFormatReader#fileGroupOption() */ public int fileGroupOption(String id) { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { info = null; used = null; lastPlane = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { // normalize file name super.initFile(normalizeFilename(null, id)); id = currentId; String dir = new File(id).getParent(); // parse and populate OME-XML metadata String fileName = new Location(id).getAbsoluteFile().getAbsolutePath(); RandomAccessInputStream ras = new RandomAccessInputStream(fileName); TiffParser tp = new TiffParser(ras); IFD firstIFD = tp.getFirstIFD(); ras.close(); String xml = firstIFD.getComment(); OMEXMLMetadata meta; OMEXMLService service; try { ServiceFactory factory = new ServiceFactory(); service = factory.getInstance(OMEXMLService.class); meta = service.createOMEXMLMetadata(xml); } catch (DependencyException de) { throw new MissingLibraryException(NO_OME_XML_MSG, de); } catch (ServiceException se) { throw new FormatException(se); } hasSPW = meta.getPlateCount() > 0; // TODO //Hashtable originalMetadata = meta.getOriginalMetadata(); //if (originalMetadata != null) metadata = originalMetadata; LOGGER.trace(xml); if (meta.getRoot() == null) { throw new FormatException("Could not parse OME-XML from TIFF comment"); } String currentUUID = meta.getUUID(); service.convertMetadata(meta, metadataStore); // determine series count from Image and Pixels elements int seriesCount = meta.getImageCount(); core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = new CoreMetadata(); } info = new OMETiffPlane[seriesCount][]; // compile list of file/UUID mappings Hashtable<String, String> files = new Hashtable<String, String>(); boolean needSearch = false; for (int i=0; i<seriesCount; i++) { int tiffDataCount = meta.getTiffDataCount(i); for (int td=0; td<tiffDataCount; td++) { String uuid = null; try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { } String filename = null; if (uuid == null) { // no UUID means that TiffData element refers to this file uuid = ""; filename = id; } else { filename = meta.getUUIDFileName(i, td); if (!new Location(dir, filename).exists()) filename = null; if (filename == null) { if (uuid.equals(currentUUID) || currentUUID == null) { // UUID references this file filename = id; } else { // will need to search for this UUID filename = ""; needSearch = true; } } else filename = normalizeFilename(dir, filename); } String existing = files.get(uuid); if (existing == null) files.put(uuid, filename); else if (!existing.equals(filename)) { throw new FormatException("Inconsistent UUID filenames"); } } } // search for missing filenames if (needSearch) { Enumeration en = files.keys(); while (en.hasMoreElements()) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); if (filename.equals("")) { // TODO search... // should scan only other .ome.tif files // to make this work with OME server may be a little tricky? throw new FormatException("Unmatched UUID: " + uuid); } } } // build list of used files Enumeration en = files.keys(); int numUUIDs = files.size(); HashSet fileSet = new HashSet(); // ensure no duplicate filenames for (int i=0; i<numUUIDs; i++) { String uuid = (String) en.nextElement(); String filename = files.get(uuid); fileSet.add(filename); } used = new String[fileSet.size()]; Iterator iter = fileSet.iterator(); for (int i=0; i<used.length; i++) used[i] = (String) iter.next(); // process TiffData elements Hashtable<String, IFormatReader> readers = new Hashtable<String, IFormatReader>(); for (int i=0; i<seriesCount; i++) { int s = i; LOGGER.debug("Image[{}] {", i); LOGGER.debug(" id = {}", meta.getImageID(i)); String order = meta.getPixelsDimensionOrder(i).toString(); PositiveInteger samplesPerPixel = null; if (meta.getChannelCount(i) > 0) { samplesPerPixel = meta.getChannelSamplesPerPixel(i, 0); } int samples = samplesPerPixel == null ? -1 : samplesPerPixel.getValue(); int tiffSamples = firstIFD.getSamplesPerPixel(); if (samples != tiffSamples) { LOGGER.warn("SamplesPerPixel mismatch: OME={}, TIFF={}", samples, tiffSamples); samples = tiffSamples; } int effSizeC = meta.getPixelsSizeC(i).getValue().intValue() / samples; if (effSizeC == 0) effSizeC = 1; if (effSizeC * samples != meta.getPixelsSizeC(i).getValue().intValue()) { effSizeC = meta.getPixelsSizeC(i).getValue().intValue(); } int sizeT = meta.getPixelsSizeT(i).getValue().intValue(); int sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); int num = effSizeC * sizeT * sizeZ; OMETiffPlane[] planes = new OMETiffPlane[num]; for (int no=0; no<num; no++) planes[no] = new OMETiffPlane(); int tiffDataCount = meta.getTiffDataCount(i); for (int td=0; td<tiffDataCount; td++) { LOGGER.debug(" TiffData[{}] {", td); // extract TiffData parameters String filename = null; String uuid = null; try { filename = meta.getUUIDFileName(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving filename."); } try { uuid = meta.getUUIDValue(i, td); } catch (NullPointerException e) { LOGGER.debug("Ignoring null UUID object when retrieving value."); } NonNegativeInteger tdIFD = meta.getTiffDataIFD(i, td); int ifd = tdIFD == null ? 0 : tdIFD.getValue(); NonNegativeInteger numPlanes = meta.getTiffDataPlaneCount(i, td); NonNegativeInteger firstC = meta.getTiffDataFirstC(i, td); NonNegativeInteger firstT = meta.getTiffDataFirstT(i, td); NonNegativeInteger firstZ = meta.getTiffDataFirstZ(i, td); int c = firstC == null ? 0 : firstC.getValue(); int t = firstT == null ? 0 : firstT.getValue(); int z = firstZ == null ? 0 : firstZ.getValue(); // NB: some writers index FirstC, FirstZ and FirstT from 1 if (c >= effSizeC) c if (z >= sizeZ) z if (t >= sizeT) t int index = FormatTools.getIndex(order, sizeZ, effSizeC, sizeT, num, z, c, t); int count = numPlanes == null ? 1 : numPlanes.getValue(); if (count == 0) { core[s] = null; break; } // get reader object for this filename if (filename == null) { if (uuid == null) filename = id; else filename = files.get(uuid); } else filename = normalizeFilename(dir, filename); IFormatReader r = readers.get(filename); if (r == null) { r = new MinimalTiffReader(); readers.put(filename, r); } Location file = new Location(filename); if (!file.exists()) { // if this is an absolute file name, try using a relative name // old versions of OMETiffWriter wrote an absolute path to // UUID.FileName, which causes problems if the file is moved to // a different directory filename = filename.substring(filename.lastIndexOf(File.separator) + 1); filename = dir + File.separator + filename; if (!new Location(filename).exists()) { filename = currentId; } } // populate plane index -> IFD mapping for (int q=0; q<count; q++) { int no = index + q; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = ifd + q; planes[no].certain = true; LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); } if (numPlanes == null) { // unknown number of planes; fill down for (int no=index+1; no<num; no++) { if (planes[no].certain) break; planes[no].reader = r; planes[no].id = filename; planes[no].ifd = planes[no - 1].ifd + 1; LOGGER.debug(" Plane[{}]: FILLED", no); } } else { // known number of planes; clear anything subsequently filled for (int no=index+count; no<num; no++) { if (planes[no].certain) break; planes[no].reader = null; planes[no].id = null; planes[no].ifd = -1; LOGGER.debug(" Plane[{}]: CLEARED", no); } } LOGGER.debug(" }"); } if (core[s] == null) continue; // verify that all planes are available LOGGER.debug(" for (int no=0; no<num; no++) { LOGGER.debug(" Plane[{}]: file={}, IFD={}", new Object[] {no, planes[no].id, planes[no].ifd}); if (planes[no].reader == null) { LOGGER.warn("Image ID '{}': missing plane "Using TiffReader to determine the number of planes.", meta.getImageID(i), no); TiffReader r = new TiffReader(); r.setId(currentId); planes = new OMETiffPlane[r.getImageCount()]; for (int plane=0; plane<planes.length; plane++) { planes[plane] = new OMETiffPlane(); planes[plane].id = currentId; planes[plane].reader = r; planes[plane].ifd = plane; } num = planes.length; r.close(); } } LOGGER.debug(" }"); // populate core metadata info[s] = planes; try { core[s].sizeX = meta.getPixelsSizeX(i).getValue().intValue(); int tiffWidth = (int) firstIFD.getImageWidth(); if (core[s].sizeX != tiffWidth) { LOGGER.warn("SizeX mismatch: OME={}, TIFF={}", core[s].sizeX, tiffWidth); } core[s].sizeY = meta.getPixelsSizeY(i).getValue().intValue(); int tiffHeight = (int) firstIFD.getImageLength(); if (core[s].sizeY != tiffHeight) { LOGGER.warn("SizeY mismatch: OME={}, TIFF={}", core[s].sizeY, tiffHeight); } core[s].sizeZ = meta.getPixelsSizeZ(i).getValue().intValue(); core[s].sizeC = meta.getPixelsSizeC(i).getValue().intValue(); core[s].sizeT = meta.getPixelsSizeT(i).getValue().intValue(); core[s].pixelType = FormatTools.pixelTypeFromString( meta.getPixelsType(i).toString()); int tiffPixelType = firstIFD.getPixelType(); if (core[s].pixelType != tiffPixelType) { LOGGER.warn("PixelType mismatch: OME={}, TIFF={}", core[s].pixelType, tiffPixelType); core[s].pixelType = tiffPixelType; } core[s].imageCount = num; core[s].dimensionOrder = meta.getPixelsDimensionOrder(i).toString(); core[s].orderCertain = true; PhotoInterp photo = firstIFD.getPhotometricInterpretation(); core[s].rgb = samples > 1 || photo == PhotoInterp.RGB; if ((samples != core[s].sizeC && (samples % core[s].sizeC) != 0 && (core[s].sizeC % samples) != 0) || core[s].sizeC == 1) { core[s].sizeC *= samples; } if (core[s].sizeZ * core[s].sizeT * core[s].sizeC > core[s].imageCount && !core[s].rgb) { if (core[s].sizeZ == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeC = 1; } else if (core[s].sizeT == core[s].imageCount) { core[s].sizeZ = 1; core[s].sizeC = 1; } else if (core[s].sizeC == core[s].imageCount) { core[s].sizeT = 1; core[s].sizeZ = 1; } } if (meta.getPixelsBinDataCount(i) > 1) { LOGGER.warn("OME-TIFF Pixels element contains BinData elements! " + "Ignoring."); } core[s].littleEndian = firstIFD.isLittleEndian(); core[s].interleaved = false; core[s].indexed = photo == PhotoInterp.RGB_PALETTE && firstIFD.getIFDValue(IFD.COLOR_MAP) != null; if (core[s].indexed) { core[s].rgb = false; } core[s].falseColor = false; core[s].metadataComplete = true; } catch (NullPointerException exc) { throw new FormatException("Incomplete Pixels metadata", exc); } } // remove null CoreMetadata entries Vector<CoreMetadata> series = new Vector<CoreMetadata>(); Vector<OMETiffPlane[]> planeInfo = new Vector<OMETiffPlane[]>(); for (int i=0; i<core.length; i++) { if (core[i] != null) { series.add(core[i]); planeInfo.add(info[i]); } } core = series.toArray(new CoreMetadata[series.size()]); info = planeInfo.toArray(new OMETiffPlane[0][0]); } // -- Helper methods -- private String normalizeFilename(String dir, String name) { File file = new File(dir, name); if (file.exists()) return file.getAbsolutePath(); return new Location(name).getAbsolutePath(); } // -- Helper classes -- /** Structure containing details on where to find a particular image plane. */ private class OMETiffPlane { /** Reader to use for accessing this plane. */ public IFormatReader reader; /** File containing this plane. */ public String id; /** IFD number of this plane. */ public int ifd = -1; /** Certainty flag, for dealing with unspecified NumPlanes. */ public boolean certain = false; } }
package org.ethereum.db; import org.ethereum.core.Block; import org.ethereum.datasource.KeyValueDataSource; import org.hibernate.SessionFactory; import org.mapdb.DB; import org.mapdb.DataIO; import org.mapdb.Serializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import static java.math.BigInteger.ZERO; import static org.ethereum.crypto.HashUtil.shortHash; import static org.spongycastle.util.Arrays.areEqual; public class IndexedBlockStore extends AbstractBlockstore{ private static final Logger logger = LoggerFactory.getLogger("general"); IndexedBlockStore cache; Map<Long, List<BlockInfo>> index; KeyValueDataSource blocks; DB indexDB; public IndexedBlockStore(){ } public void init(Map<Long, List<BlockInfo>> index, KeyValueDataSource blocks, IndexedBlockStore cache, DB indexDB) { this.cache = cache; this.index = index; this.blocks = blocks; this.indexDB = indexDB; } public Block getBestBlock(){ Long maxLevel = getMaxNumber(); if (maxLevel < 0) return null; Block bestBlock = getChainBlockByNumber(maxLevel); if (bestBlock != null) return bestBlock; // That scenario can happen // if there is a fork branch that is // higher than main branch but has // less TD than the main branch TD while (bestBlock == null){ --maxLevel; bestBlock = getChainBlockByNumber(maxLevel); } return bestBlock; } public byte[] getBlockHashByNumber(long blockNumber){ return getChainBlockByNumber(blockNumber).getHash(); // FIXME: can be improved by accessing the hash directly in the index } @Override public void flush(){ if (cache == null) return; long t1 = System.nanoTime(); for (byte[] hash : cache.blocks.keys()){ blocks.put(hash, cache.blocks.get(hash)); } for (Map.Entry<Long, List<BlockInfo>> e : cache.index.entrySet()) { Long number = e.getKey(); List<BlockInfo> infos = e.getValue(); if (index.containsKey(number)) infos.addAll(index.get(number)); index.put(number, infos); } cache.blocks.close(); cache.index.clear(); long t2 = System.nanoTime(); if (indexDB != null) indexDB.commit(); logger.info("Flush block store in: {} ms", ((float)(t2 - t1) / 1_000_000)); } @Override public void saveBlock(Block block, BigInteger cummDifficulty, boolean mainChain){ if (cache == null) addInternalBlock(block, cummDifficulty, mainChain); else cache.saveBlock(block, cummDifficulty, mainChain); } private void addInternalBlock(Block block, BigInteger cummDifficulty, boolean mainChain){ List<BlockInfo> blockInfos = index.get(block.getNumber()); if (blockInfos == null){ blockInfos = new ArrayList<>(); } BlockInfo blockInfo = new BlockInfo(); blockInfo.setCummDifficulty(cummDifficulty); blockInfo.setHash(block.getHash()); blockInfo.setMainChain(mainChain); // FIXME:maybe here I should force reset main chain for all uncles on that level blockInfos.add(blockInfo); index.put(block.getNumber(), blockInfos); blocks.put(block.getHash(), block.getEncoded()); } public List<Block> getBlocksByNumber(long number){ List<Block> result = new ArrayList<>(); if (cache != null) result = cache.getBlocksByNumber(number); List<BlockInfo> blockInfos = index.get(number); if (blockInfos == null){ return result; } for (BlockInfo blockInfo : blockInfos){ byte[] hash = blockInfo.getHash(); byte[] blockRlp = blocks.get(hash); result.add(new Block(blockRlp)); } return result; } @Override public Block getChainBlockByNumber(long number){ if (cache != null) { Block block = cache.getChainBlockByNumber(number); if (block != null) return block; } List<BlockInfo> blockInfos = index.get(number); if (blockInfos == null){ return null; } for (BlockInfo blockInfo : blockInfos){ if (blockInfo.isMainChain()){ byte[] hash = blockInfo.getHash(); byte[] blockRlp = blocks.get(hash); return new Block(blockRlp); } } return null; } @Override public Block getBlockByHash(byte[] hash) { if (cache != null) { Block cachedBlock = cache.getBlockByHash(hash); if (cachedBlock != null) return cachedBlock; } byte[] blockRlp = blocks.get(hash); if (blockRlp == null) return null; return new Block(blockRlp); } @Override public boolean isBlockExist(byte[] hash) { if (cache != null) { Block cachedBlock = cache.getBlockByHash(hash); if (cachedBlock != null) return true; } byte[] blockRlp = blocks.get(hash); return blockRlp != null; } @Override public BigInteger getTotalDifficultyForHash(byte[] hash){ if (cache != null && cache.getBlockByHash(hash) != null) { return cache.getTotalDifficultyForHash(hash); } Block block = this.getBlockByHash(hash); if (block == null) return ZERO; Long level = block.getNumber(); List<BlockInfo> blockInfos = index.get(level); for (BlockInfo blockInfo : blockInfos) if (areEqual(blockInfo.getHash(), hash)) { return blockInfo.cummDifficulty; } return ZERO; } @Override public BigInteger getTotalDifficulty(){ BigInteger cacheTotalDifficulty = ZERO; long maxNumber = getMaxNumber(); if (cache != null) { List<BlockInfo> infos = getBlockInfoForLevel(maxNumber); if (infos != null){ for (BlockInfo blockInfo : infos){ if (blockInfo.isMainChain()){ return blockInfo.getCummDifficulty(); } } // todo: need better testing for that place // here is the place when you know // for sure that the potential fork // branch is higher than main branch // in that case the correct td is the // first level when you have [mainchain = true] Blockinfo boolean found = false; Map<Long, List<BlockInfo>> searching = cache.index; while (!found){ --maxNumber; infos = getBlockInfoForLevel(maxNumber); for (BlockInfo blockInfo : infos) { if (blockInfo.isMainChain()) { found = true; return blockInfo.getCummDifficulty(); } } } } } List<BlockInfo> blockInfos = index.get(maxNumber); for (BlockInfo blockInfo : blockInfos){ if (blockInfo.isMainChain()){ return blockInfo.getCummDifficulty(); } } return cacheTotalDifficulty; } @Override public long getMaxNumber(){ Long bestIndex = 0L; if (index.size() > 0){ bestIndex = (long) index.size(); } if (cache != null){ return bestIndex + cache.index.size() - 1L; } else return bestIndex - 1L; } @Override public List<byte[]> getListHashesEndWith(byte[] hash, long number){ List<byte[]> cachedHashes = new ArrayList<>(); if (cache != null) cachedHashes = cache.getListHashesEndWith(hash, number); byte[] rlp = blocks.get(hash); if (rlp == null) return cachedHashes; for (int i = 0; i < number; ++i){ Block block = new Block(rlp); cachedHashes.add(block.getHash()); rlp = blocks.get(block.getParentHash()); if (rlp == null) break; } return cachedHashes; } @Override public void reBranch(Block forkBlock){ Block bestBlock = getBestBlock(); long maxLevel = Math.max(bestBlock.getNumber(), forkBlock.getNumber()); // 1. First ensure that you are one the save level long currentLevel = maxLevel; Block forkLine = forkBlock; if (forkBlock.getNumber() > bestBlock.getNumber()){ while(currentLevel > bestBlock.getNumber()){ List<BlockInfo> blocks = getBlockInfoForLevel(currentLevel); BlockInfo blockInfo = getBlockInfoForHash(blocks, forkLine.getHash()); if (blockInfo != null) blockInfo.setMainChain(true); forkLine = getBlockByHash(forkLine.getParentHash()); --currentLevel; } } Block bestLine = bestBlock; if (bestBlock.getNumber() > forkBlock.getNumber()){ while(currentLevel > forkBlock.getNumber()){ List<BlockInfo> blocks = getBlockInfoForLevel(currentLevel); BlockInfo blockInfo = getBlockInfoForHash(blocks, bestLine.getHash()); if (blockInfo != null) blockInfo.setMainChain(false); bestLine = getBlockByHash(bestLine.getParentHash()); --currentLevel; } } // 2. Loop back on each level until common block while( !bestLine.isEqual(forkLine) ) { List<BlockInfo> levelBlocks = getBlockInfoForLevel(currentLevel); BlockInfo bestInfo = getBlockInfoForHash(levelBlocks, bestLine.getHash()); if (bestInfo != null) bestInfo.setMainChain(false); BlockInfo forkInfo = getBlockInfoForHash(levelBlocks, forkLine.getHash()); if (forkInfo != null) forkInfo.setMainChain(true); bestLine = getBlockByHash(bestLine.getParentHash()); forkLine = getBlockByHash(forkLine.getParentHash()); --currentLevel; } } public List<byte[]> getListHashesStartWith(long number, long maxBlocks){ List<byte[]> result = new ArrayList<>(); int i; for ( i = 0; i < maxBlocks; ++i){ List<BlockInfo> blockInfos = index.get(number); if (blockInfos == null) break; for (BlockInfo blockInfo : blockInfos) if (blockInfo.isMainChain()){ result.add(blockInfo.getHash()); break; } ++number; } maxBlocks -= i; if (cache != null) result.addAll( cache.getListHashesStartWith(number, maxBlocks) ); return result; } public static class BlockInfo implements Serializable { byte[] hash; BigInteger cummDifficulty; boolean mainChain; public byte[] getHash() { return hash; } public void setHash(byte[] hash) { this.hash = hash; } public BigInteger getCummDifficulty() { return cummDifficulty; } public void setCummDifficulty(BigInteger cummDifficulty) { this.cummDifficulty = cummDifficulty; } public boolean isMainChain() { return mainChain; } public void setMainChain(boolean mainChain) { this.mainChain = mainChain; } } public static final Serializer<List<BlockInfo>> BLOCK_INFO_SERIALIZER = new Serializer<List<BlockInfo>>(){ @Override public void serialize(DataOutput out, List<BlockInfo> value) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(value); byte[] data = bos.toByteArray(); DataIO.packInt(out, data.length); out.write(data); } @Override public List<BlockInfo> deserialize(DataInput in, int available) throws IOException { List<BlockInfo> value = null; try { int size = DataIO.unpackInt(in); byte[] data = new byte[size]; in.readFully(data); ByteArrayInputStream bis = new ByteArrayInputStream(data, 0, data.length); ObjectInputStream ois = new ObjectInputStream(bis); value = (List<BlockInfo>)ois.readObject(); } catch (ClassNotFoundException e) {e.printStackTrace();} return value; } }; public void printChain(){ Long number = getMaxNumber(); for (long i = 0; i < number; ++i){ List<BlockInfo> levelInfos = index.get(i); if (levelInfos != null) { System.out.print(i); for (BlockInfo blockInfo : levelInfos){ if (blockInfo.isMainChain()) System.out.print(" [" + shortHash(blockInfo.getHash()) + "] "); else System.out.print(" " + shortHash(blockInfo.getHash()) + " "); } System.out.println(); } } if (cache != null) cache.printChain(); } private List<BlockInfo> getBlockInfoForLevel(Long level){ if (cache != null){ List<BlockInfo> infos = cache.index.get(level); if (infos != null) return infos; } return index.get(level); } private static BlockInfo getBlockInfoForHash(List<BlockInfo> blocks, byte[] hash){ for (BlockInfo blockInfo : blocks) if (areEqual(hash, blockInfo.getHash())) return blockInfo; return null; } @Override public void load() { } public void setSessionFactory(SessionFactory sessionFactory){ throw new UnsupportedOperationException(); } }
package loci.common; import java.io.IOException; import java.net.URL; public class ReflectedUniverse { // -- Constants -- // -- Fields -- private ome.scifio.common.ReflectedUniverse unv; // -- Constructors -- /** Constructs a new reflected universe. */ public ReflectedUniverse() { unv = new ome.scifio.common.ReflectedUniverse(); } /** * Constructs a new reflected universe, with the given URLs * representing additional search paths for imported classes * (in addition to the CLASSPATH). */ public ReflectedUniverse(URL[] urls) { unv = new ome.scifio.common.ReflectedUniverse (urls); } /** Constructs a new reflected universe that uses the given class loader. */ public ReflectedUniverse(ClassLoader loader) { unv = new ome.scifio.common.ReflectedUniverse (loader); } // -- Utility methods -- /** * Returns whether the given object is compatible with the * specified class for the purposes of reflection. */ public static boolean isInstance(Class<?> c, Object o) { return ome.scifio.common.ReflectedUniverse .isInstance(c, o); } // -- ReflectedUniverse API methods -- /** * Executes a command in the universe. The following syntaxes are valid: * <ul> * <li>import fully.qualified.package.ClassName</li> * <li>var = new ClassName(param1, ..., paramN)</li> * <li>var.method(param1, ..., paramN)</li> * <li>var2 = var.method(param1, ..., paramN)</li> * <li>ClassName.method(param1, ..., paramN)</li> * <li>var2 = ClassName.method(param1, ..., paramN)</li> * <li>var2 = var</li> * </ul> * Important guidelines: * <ul> * <li>Any referenced class must be imported first using "import".</li> * <li>Variables can be exported from the universe with getVar().</li> * <li>Variables can be imported to the universe with setVar().</li> * <li>Each parameter must be either: * <ol> * <li>a variable in the universe</li> * <li>a static or instance field (i.e., no nested methods)</li> * <li>a string literal (remember to escape the double quotes)</li> * <li>an integer literal</li> * <li>a long literal (ending in L)</li> * <li>a double literal (containing a decimal point)</li> * <li>a boolean literal (true or false)</li> * <li>the null keyword</li> * </ol> * </li> * </ul> */ public Object exec(String command) throws ReflectException { try { return unv.exec(command); } catch (ome.scifio.common.ReflectException e) { throw new ReflectException(e.getCause()); } } /** Registers a variable in the universe. */ public void setVar(String varName, Object obj) { unv.setVar(varName, obj); } /** Registers a variable of primitive type boolean in the universe. */ public void setVar(String varName, boolean b) { unv.setVar(varName, b); } /** Registers a variable of primitive type byte in the universe. */ public void setVar(String varName, byte b) { unv.setVar(varName, b); } /** Registers a variable of primitive type char in the universe. */ public void setVar(String varName, char c) { unv.setVar(varName, c); } /** Registers a variable of primitive type double in the universe. */ public void setVar(String varName, double d) { unv.setVar(varName, d); } /** Registers a variable of primitive type float in the universe. */ public void setVar(String varName, float f) { unv.setVar(varName, f); } /** Registers a variable of primitive type int in the universe. */ public void setVar(String varName, int i) { unv.setVar(varName, i); } /** Registers a variable of primitive type long in the universe. */ public void setVar(String varName, long l) { unv.setVar(varName, l); } /** Registers a variable of primitive type short in the universe. */ public void setVar(String varName, short s) { unv.setVar(varName, s); } /** * Returns the value of a variable or field in the universe. * Primitive types will be wrapped in their Java Object wrapper classes. */ public Object getVar(String varName) throws ReflectException { try { return unv.getVar(varName); } catch (ome.scifio.common.ReflectException e) { throw (ReflectException)e; } } /** Sets whether access modifiers (protected, private, etc.) are ignored. */ public void setAccessibilityIgnored(boolean ignore) { unv.setAccessibilityIgnored(ignore); } /** Gets whether access modifiers (protected, private, etc.) are ignored. */ public boolean isAccessibilityIgnored() { return unv.isAccessibilityIgnored(); } // -- Main method -- /** * Allows exploration of a reflected universe in an interactive environment. */ public static void main(String[] args) throws IOException { ome.scifio.common.ReflectedUniverse.main(args); } // -- Object delegators -- @Override public boolean equals(Object obj) { return unv.equals(obj); } @Override public int hashCode() { return unv.hashCode(); } @Override public String toString() { return unv.toString(); } }
/* @java.file.header */ package org.gridgain.examples; import org.gridgain.grid.*; import java.util.concurrent.*; /** * Example that demonstrates how to exchange messages between nodes. Use such * functionality for cases when you need to communicate to other nodes outside * of grid task. * <p> * To run this example you must have at least one remote node started. * <p> * Remote nodes should always be started with special configuration file which * enables P2P class loading: {@code 'ggstart.{sh|bat} examples/config/example-compute.xml'}. * <p> * Alternatively you can run {@link ComputeNodeStartup} in another JVM which will start GridGain node * with {@code examples/config/example-compute.xml} configuration. */ public final class MessagingExample { /** Number of messages. */ private static final int MESSAGES_NUM = 10; /** Message topics. */ private enum TOPIC { ORDERED, UNORDERED } /** * Executes example. * * @param args Command line arguments, none required. * @throws GridException If example execution failed. */ public static void main(String[] args) throws Exception { try (Grid g = GridGain.start("examples/config/example-compute.xml")) { if (!ExamplesUtils.checkMinTopologySize(g, 2)) return; System.out.println(); System.out.println(">>> Messaging example started."); // Projection for remote nodes. GridProjection rmtPrj = g.forRemotes(); // Listen for messages from remote nodes to make sure that they received all the messages. int msgCnt = rmtPrj.nodes().size() * MESSAGES_NUM; CountDownLatch orderedLatch = new CountDownLatch(msgCnt); CountDownLatch unorderedLatch = new CountDownLatch(msgCnt); localListen(g.forLocal(), orderedLatch, unorderedLatch); // Register listeners on all grid nodes. startListening(rmtPrj); // Send unordered messages to all remote nodes. for (int i = 0; i < MESSAGES_NUM; i++) rmtPrj.message().send(TOPIC.UNORDERED, Integer.toString(i)); System.out.println(">>> Finished sending unordered messages."); // Send ordered messages to all remote nodes. for (int i = 0; i < MESSAGES_NUM; i++) rmtPrj.message().sendOrdered(TOPIC.ORDERED, Integer.toString(i), 0); System.out.println(">>> Finished sending ordered messages."); System.out.println(">>> Check output on all nodes for message printouts."); System.out.println(">>> Will wait for messages acknowledgements from all remote nodes."); orderedLatch.await(); unorderedLatch.await(); System.out.println(">>> Messaging example finished."); } } /** * Start listening to messages on all grid nodes within passed in projection. * * @param prj Grid projection. * @throws GridException If failed. */ private static void startListening(GridProjection prj) throws GridException { // Add ordered message listener. prj.message().remoteListen(TOPIC.ORDERED, (nodeId, msg) -> { System.out.println("Received ordered message [msg=" + msg + ", fromNodeId=" + nodeId + ']'); try { prj.forNodeId(nodeId).message().send(TOPIC.ORDERED, msg); } catch (GridException e) { e.printStackTrace(); } return true; // Return true to continue listening. }).get(); // Add unordered message listener. prj.message().remoteListen(TOPIC.UNORDERED, (nodeId, msg) -> { System.out.println("Received unordered message [msg=" + msg + ", fromNodeId=" + nodeId + ']'); try { prj.forNodeId(nodeId).message().send(TOPIC.UNORDERED, msg); } catch (GridException e) { e.printStackTrace(); } return true; // Return true to continue listening. }).get(); } /** * Listen for messages from remote nodes. * * @param prj Grid projection. * @param orderedLatch Latch for ordered messages acks. * @param unorderedLatch Latch for unordered messages acks. */ private static void localListen( GridProjection prj, final CountDownLatch orderedLatch, final CountDownLatch unorderedLatch ) { prj.message().localListen(TOPIC.ORDERED, (nodeId, msg) -> { orderedLatch.countDown(); // Return true to continue listening, false to stop. return orderedLatch.getCount() > 0; }); prj.message().localListen(TOPIC.UNORDERED, (nodeId, msg) -> { unorderedLatch.countDown(); // Return true to continue listening, false to stop. return unorderedLatch.getCount() > 0; }); } }
package org.cinchapi.concourse; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.cinchapi.concourse.annotate.CompoundOperation; import org.cinchapi.concourse.config.ConcourseConfiguration; import org.cinchapi.concourse.lang.BuildableState; import org.cinchapi.concourse.lang.Criteria; import org.cinchapi.concourse.lang.Translate; import org.cinchapi.concourse.security.ClientSecurity; import org.cinchapi.concourse.thrift.AccessToken; import org.cinchapi.concourse.thrift.ConcourseService; import org.cinchapi.concourse.thrift.Operator; import org.cinchapi.concourse.thrift.TObject; import org.cinchapi.concourse.thrift.TTransactionException; import org.cinchapi.concourse.thrift.TransactionToken; import org.cinchapi.concourse.time.Time; import org.cinchapi.concourse.util.Convert; import org.cinchapi.concourse.util.TLinkedTableMap; import org.cinchapi.concourse.util.Timestamps; import org.cinchapi.concourse.util.Transformers; import org.cinchapi.concourse.util.TLinkedHashMap; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * <p> * Concourse is a schemaless and distributed version control database with * automatic indexing, acid transactions and full-text search. Concourse * provides a more intuitive approach to data management that is easy to deploy, * access and scale with minimal tuning while also maintaining the referential * integrity and ACID characteristics of traditional database systems. * </p> * <h2>Data Model</h2> * <p> * The Concourse data model is lightweight and flexible. Unlike other databases, * Concourse is completely schemaless and does not hold data in tables or * collections. Instead, Concourse is simply a distributed graph of records. * Each record has multiple keys. And each key has one or more distinct values. * Like any graph, you can link records to one another. And the structure of one * record does not affect the structure of another. * </p> * <p> * <ul> * <li><strong>Record</strong> &mdash; A logical grouping of data about a single * person, place, or thing (i.e. an object). Each {@code record} is a collection * of key/value pairs that are together identified by a unique primary key. * <li><strong>Key</strong> &mdash; An attribute that maps to a set of * <em>one or more</em> distinct {@code values}. A {@code record} can have many * different {@code keys}, and the {@code keys} in one {@code record} do not * affect those in another {@code record}. * <li><strong>Value</strong> &mdash; A dynamically typed quantity that is * associated with a {@code key} in a {@code record}. * </ul> * </p> * <h4>Data Types</h4> * <p> * Concourse natively stores most of the Java primitives: boolean, double, * float, integer, long, and string (UTF-8). Otherwise, the value of the * {@link #toString()} method for the Object is stored. * </p> * <h4>Links</h4> * <p> * Concourse supports linking a {@code key} in one {@code record} to another * {@code record}. Links are one-directional, but it is possible to add two * links that are the inverse of each other to simulate bi-directionality (i.e. * link "friend" in Record 1 to Record 2 and link "friend" in Record 2 to Record * 1). * </p> * <h2>Transactions</h2> * <p> * By default, Concourse conducts every operation in {@code autocommit} mode * where every change is immediately written. Concourse also supports the * ability to stage a group of operations in transactions that are atomic, * consistent, isolated, and durable using the {@link #stage()}, * {@link #commit()} and {@link #abort()} methods. * * </p> * <h2>Thread Safety</h2> * <p> * You should <strong>not</strong> use the same client connection in multiple * threads. If you need to interact with Concourse using multiple threads, you * should create a separate connection for each thread or use a * {@link ConnectionPool}. * </p> * * @author jnelson */ public abstract class Concourse implements AutoCloseable { /** * Create a new Client connection to the environment of the Concourse * Server described in {@code concourse_client.prefs} (or the default * environment and server if the prefs file does not exist) and return a * handler to facilitate database interaction. * * @return the database handler */ public static Concourse connect() { return new Client(); } * /** * Create a new Client connection to the specified {@code environment} of * the Concourse Server described in {@code concourse_client.prefs} (or * the default server if the prefs file does not exist) and return a * handler to facilitate database interaction. * * @param environment * @return */ public static Concourse connect(String environment) { return new Client(environment); } /** * Create a new Client connection to the default environment of the * specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password * @return the database handler */ public static Concourse connect(String host, int port, String username, String password) { return new Client(host, port, username, password); } /** * Create a new Client connection to the specified {@code environment} of * the specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password * @param environment * @return the database handler */ public static Concourse connect(String host, int port, String username, String password, String environment) { return new Client(host, port, username, password, environment); } /** * Discard any changes that are currently staged for commit. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be committed immediately. * </p> */ public abstract void abort(); /** * Add {@code key} as {@code value} in each of the {@code records} if it is * not already contained. * * @param key * @param value * @param records * @return a mapping from each record to a boolean indicating if * {@code value} is added */ @CompoundOperation public abstract Map<Long, Boolean> add(String key, Object value, Collection<Long> records); /** * Add {@code key} as {@code value} to {@code record} if it is not already * contained. * * @param key * @param value * @param record * @return {@code true} if {@code value} is added */ public abstract <T> boolean add(String key, T value, long record); /** * Audit {@code record} and return a log of revisions. * * @param record * @return a mapping from timestamp to a description of a revision */ public abstract Map<Timestamp, String> audit(long record); /** * Audit {@code key} in {@code record} and return a log of revisions. * * @param key * @param record * @return a mapping from timestamp to a description of a revision */ public abstract Map<Timestamp, String> audit(String key, long record); /** * Browse the {@code records} and return a mapping from each record to all * the data that is contained as a mapping from key name to value set. * * @param records * @return a mapping of all the contained keys and their mapped values in * each record */ public abstract Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records); /** * Browse the {@code records} at {@code timestamp} and return a mapping from * each record to all the data that was contained as a mapping from key name * to value set. * * @param records * @param timestamp * @return a mapping of all the contained keys and their mapped values in * each record */ public abstract Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records, Timestamp timestamp); /** * Browse {@code record} and return all the data that is presently contained * as a mapping from key name to value set. * <p> * <em>This method is the atomic equivalent of calling * {@code fetch(describe(record), record)}</em> * </p> * * @param record * @return a mapping of all the presently contained keys and their mapped * values */ public abstract Map<String, Set<Object>> browse(long record); /** * Browse {@code record} at {@code timestamp} and return all the data that * was contained as a mapping from key name to value set. * <p> * <em>This method is the atomic equivalent of calling * {@code fetch(describe(record, timestamp), record, timestamp)}</em> * </p> * * @param record * @param timestamp * @return a mapping of all the contained keys and their mapped * values */ public abstract Map<String, Set<Object>> browse(long record, Timestamp timestamp); /** * Browse {@code key} and return all the data that is indexed as a mapping * from value to the set of records containing the value for {@code key}. * * @param key * @return a mapping of all the indexed values and their associated records. */ public abstract Map<Object, Set<Long>> browse(String key); /** * Browse {@code key} at {@code timestamp} and return all the data that was * indexed as a mapping from value to the set of records that contained the * value for {@code key} . * * @param key * @param timestamp * @return a mapping of all the indexed values and their associated records. */ public abstract Map<Object, Set<Long>> browse(String key, Timestamp timestamp); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * and return a mapping from each timestamp to the non-empty set of values. * * @param key * @param record * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record */ public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * from {@code start} timestamp inclusively to present and return a mapping * from each timestamp to the non-emtpy set of values. * * @param key * @param record * @param start * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record from specified start * timestamp to present */ @CompoundOperation public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * from {@code start} timestamp inclusively to {@code end} timestamp * exclusively and return a mapping from each timestamp to the non-empty * set of values. * * @param key * @param record * @param start * @param end * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record from specified start * timestamp to specified end timestamp */ @CompoundOperation public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start, Timestamp end); /** * Clear every {@code key} and contained value in each of * the {@code records} by removing every value for each {@code key} in each * record. * * @param records */ @CompoundOperation public abstract void clear(Collection<Long> records); /** * Clear each of the {@code keys} in each of the {@code records} by removing * every value for each key in each record. * * @param keys * @param records */ @CompoundOperation public abstract void clear(Collection<String> keys, Collection<Long> records); /** * Clear each of the {@code keys} in {@code record} by removing every value * for each key. * * @param keys * @param record */ @CompoundOperation public abstract void clear(Collection<String> keys, long record); /** * Atomically clear {@code record} by removing each contained * key and their values. * * @param record */ public abstract void clear(long record); /** * Clear {@code key} in each of the {@code records} by removing every value * for {@code key} in each record. * * @param key * @param records */ @CompoundOperation public abstract void clear(String key, Collection<Long> records); /** * Atomically clear {@code key} in {@code record} by removing each contained * value. * * @param record */ public abstract void clear(String key, long record); @Override public final void close() throws Exception { exit(); } /** * Attempt to permanently commit all the currently staged changes. This * function returns {@code true} if and only if all the changes can be * successfully applied. Otherwise, this function returns {@code false} and * all the changes are aborted. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be written immediately. * </p> * * @return {@code true} if all staged changes are successfully committed */ public abstract boolean commit(); /** * Create a new Record and return its Primary Key. * * @return the Primary Key of the new Record */ public abstract long create(); /** * Describe each of the {@code records} and return a mapping from each * record to the keys that currently have at least one value. * * @param records * @return the populated keys in each record */ @CompoundOperation public abstract Map<Long, Set<String>> describe(Collection<Long> records); /** * Describe each of the {@code records} at {@code timestamp} and return a * mapping from each record to the keys that had at least one value. * * @param records * @param timestamp * @return the populated keys in each record at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp); /** * Describe {@code record} and return the keys that currently have at least * one value. * * @param record * @return the populated keys in {@code record} */ public abstract Set<String> describe(long record); /** * Describe {@code record} at {@code timestamp} and return the keys that had * at least one value. * * @param record * @param timestamp * @return the populated keys in {@code record} at {@code timestamp} */ public abstract Set<String> describe(long record, Timestamp timestamp); /** * Close the Client connection. */ public abstract void exit(); /** * Fetch each of the {@code keys} from each of the {@code records} and * return a mapping from each record to a mapping from each key to the * contained values. * * @param keys * @param records * @return the contained values for each of the {@code keys} in each of the * {@code records} */ @CompoundOperation public abstract Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records); /** * Fetch each of the {@code keys} from each of the {@code records} at * {@code timestamp} and return a mapping from each record to a mapping from * each key to the contained values. * * @param keys * @param records * @param timestamp * @return the contained values for each of the {@code keys} in each * of the {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Fetch each of the {@code keys} from {@code record} and return a mapping * from each key to the contained values. * * @param keys * @param record * @return the contained values for each of the {@code keys} in * {@code record} */ @CompoundOperation public abstract Map<String, Set<Object>> fetch(Collection<String> keys, long record); /** * Fetch each of the {@code keys} from {@code record} at {@code timestamp} * and return a mapping from each key to the contained values. * * @param keys * @param record * @param timestamp * @return the contained values for each of the {@code keys} in * {@code record} at {@code timestamp} */ @CompoundOperation public abstract Map<String, Set<Object>> fetch(Collection<String> keys, long record, Timestamp timestamp); /** * Fetch {@code key} from each of the {@code records} and return a mapping * from each record to contained values. * * @param key * @param records * @return the contained values for {@code key} in each {@code record} */ @CompoundOperation public abstract Map<Long, Set<Object>> fetch(String key, Collection<Long> records); /** * Fetch {@code key} from} each of the {@code records} at {@code timestamp} * and return a mapping from each record to the contained values. * * @param key * @param records * @param timestamp * @return the contained values for {@code key} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Set<Object>> fetch(String key, Collection<Long> records, Timestamp timestamp); /** * Fetch {@code key} from {@code record} and return all the contained * values. * * @param key * @param record * @return the contained values */ public abstract Set<Object> fetch(String key, long record); /** * Fetch {@code key} from {@code record} at {@code timestamp} and return the * set of values that were mapped. * * @param key * @param record * @param timestamp * @return the contained values */ public abstract Set<Object> fetch(String key, long record, Timestamp timestamp); /** * Find and return the set of records that satisfy the {@code criteria}. * This is analogous to the SELECT action in SQL. * * @param criteria * @return the records that match the {@code criteria} */ public abstract Set<Long> find(Criteria criteria); /** * Find and return the set of records that satisfy the {@code criteria}. * This is analogous to the SELECT action in SQL. * * @param criteria * @return the records that match the {@code criteria} */ public abstract Set<Long> find(Object criteria); // this method exists in // case the caller forgets // to called #build() on // the CriteriaBuilder /** * Find {@code key} {@code operator} {@code value} and return the set of * records that satisfy the criteria. This is analogous to the SELECT action * in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value); /** * Find {@code key} {@code operator} {@code value} and {@code value2} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Object value2); /** * Find {@code key} {@code operator} {@code value} and {@code value2} at * {@code timestamp} and return the set of records that satisfy the * criteria. This is analogous to the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @param timestamp * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Object value2, Timestamp timestamp); /** * Find {@code key} {@code operator} {@code value} at {@code timestamp} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Timestamp timestamp); /** * Get each of the {@code keys} from each of the {@code records} and return * a mapping from each record to a mapping of each key to the first * contained value. * * @param keys * @param records * @return the first contained value for each of the {@code keys} in each of * the {@code records} */ @CompoundOperation public abstract Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records); /** * Get each of the {@code keys} from each of the {@code records} at * {@code timestamp} and return a mapping from each record to a mapping of * each key to the first contained value. * * @param keys * @param records * @param timestamp * @return the first contained value for each of the {@code keys} in each of * the {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Get each of the {@code keys} from {@code record} and return a mapping * from each key to the first contained value. * * @param keys * @param record * @return the first contained value for each of the {@code keys} in * {@code record} */ @CompoundOperation public abstract Map<String, Object> get(Collection<String> keys, long record); /** * Get each of the {@code keys} from {@code record} at {@code timestamp} and * return a mapping from each key to the first contained value. * * @param keys * @param record * @param timestamp * @return the first contained value for each of the {@code keys} in * {@code record} at {@code timestamp} */ @CompoundOperation public abstract Map<String, Object> get(Collection<String> keys, long record, Timestamp timestamp); /** * Get {@code key} from each of the {@code records} and return a mapping * from each record to the first contained value. * * @param key * @param records * @return the first contained value for {@code key} in each of the * {@code records} */ @CompoundOperation public abstract Map<Long, Object> get(String key, Collection<Long> records); /** * Get {@code key} from each of the {@code records} at {@code timestamp} and * return a mapping from each record to the first contained value. * * @param key * @param records * @param timestamp * @return the first contained value for {@code key} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Object> get(String key, Collection<Long> records, Timestamp timestamp); /** * Get {@code key} from {@code record} and return the first contained value * or {@code null} if there is none. Compared to * {@link #fetch(String, long)}, this method is suited for cases when the * caller is certain that {@code key} in {@code record} maps to a single * value of type {@code T}. * * @param key * @param record * @return the first contained value */ public abstract <T> T get(String key, long record); /** * Get {@code key} from {@code record} at {@code timestamp} and return the * first contained value or {@code null} if there was none. Compared to * {@link #fetch(String, long, Timestamp)}, this method is suited for cases * when the caller is certain that {@code key} in {@code record} mapped to a * single value of type {@code T} at {@code timestamp}. * * @param key * @param record * @param timestamp * @return the first contained value */ public abstract <T> T get(String key, long record, Timestamp timestamp); /** * Return the environment of the server that is currently in use by this * client. * * @return the server environment */ public abstract String getServerEnvironment(); /** * Return the version of the server to which this client is currently * connected. * * @return the server version */ public abstract String getServerVersion(); /** * Atomically insert the key/value mappings described in the {@code json} * formatted string into a new record. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @return the primary key of the new record or {@code null} if the insert * is unsuccessful */ public abstract long insert(String json); /** * Insert the key/value mappings described in the {@code json} formated * string into each of the {@code records}. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @param records * @return a mapping from each primary key to a boolean describing if the * data was successfully inserted into that record */ @CompoundOperation public abstract Map<Long, Boolean> insert(String json, Collection<Long> records); /** * Atomically insert the key/value mappings described in the {@code json} * formatted string into {@code record}. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @param record * @return {@code true} if the data is inserted into {@code record} */ public abstract boolean insert(String json, long record); /** * Link {@code key} in {@code source} to each of the {@code destinations}. * * @param key * @param source * @param destinations * @return a mapping from each destination to a boolean indicating if the * link was added */ public abstract Map<Long, Boolean> link(String key, long source, Collection<Long> destinations); /** * Link {@code key} in {@code source} to {@code destination}. * * @param key * @param source * @param destination * @return {@code true} if the link is added */ public abstract boolean link(String key, long source, long destination); /** * Ping each of the {@code records}. * * @param records * @return a mapping from each record to a boolean indicating if the record * currently has at least one populated key */ @CompoundOperation public abstract Map<Long, Boolean> ping(Collection<Long> records); /** * Ping {@code record}. * * @param record * @return {@code true} if {@code record} currently has at least one * populated key */ public abstract boolean ping(long record); /** * Remove {@code key} as {@code value} in each of the {@code records} if it * is contained. * * @param key * @param value * @param records * @return a mapping from each record to a boolean indicating if * {@code value} is removed */ @CompoundOperation public abstract Map<Long, Boolean> remove(String key, Object value, Collection<Long> records); /** * Remove {@code key} as {@code value} to {@code record} if it is contained. * * @param key * @param value * @param record * @return {@code true} if {@code value} is removed */ public abstract <T> boolean remove(String key, T value, long record); /** * Revert each of the {@code keys} in each of the {@code records} to * {@code timestamp} by creating new revisions that the relevant changes * that have occurred since {@code timestamp}. * * @param keys * @param records * @param timestamp */ @CompoundOperation public abstract void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Revert each of the {@code keys} in {@code record} to {@code timestamp} by * creating new revisions that the relevant changes * that have occurred since {@code timestamp}. * * @param keys * @param record * @param timestamp */ @CompoundOperation public abstract void revert(Collection<String> keys, long record, Timestamp timestamp); /** * Revert {@code key} in each of the {@code records} to {@code timestamp} by * creating new revisions that the relevant changes that have occurred * since {@code timestamp}. * * @param key * @param records * @param timestamp */ @CompoundOperation public abstract void revert(String key, Collection<Long> records, Timestamp timestamp); /** * Atomically revert {@code key} in {@code record} to {@code timestamp} by * creating new revisions that undo the relevant changes that have * occurred since {@code timestamp}. * * @param key * @param record * @param timestamp */ public abstract void revert(String key, long record, Timestamp timestamp); /** * Search {@code key} for {@code query} and return the set of records that * match. * * @param key * @param query * @return the records that match the query */ public abstract Set<Long> search(String key, String query); /** * Set {@code key} as {@code value} in each of the {@code records}. * * @param key * @param value * @param records */ @CompoundOperation public abstract void set(String key, Object value, Collection<Long> records); /** * Atomically set {@code key} as {@code value} in {@code record}. This is a * convenience method that clears the values for {@code key} and adds * {@code value}. * * @param key * @param value * @param record */ public abstract <T> void set(String key, T value, long record); /** * Turn on {@code staging} mode so that all subsequent changes are * collected in a staging area before possibly being committed. Staged * operations are guaranteed to be reliable, all or nothing * units of work that allow correct recovery from failures and provide * isolation between clients so that Concourse is always in a consistent * state (e.g. a transaction). * <p> * After this method returns, all subsequent operations will be done in * {@code staging} mode until either {@link #abort()} or {@link #commit()} * is invoked. * </p> * <p> * All operations that occur within a transaction should be wrapped in a * try-catch block so that transaction exceptions can be caught and the * transaction can be properly aborted. * * <pre> * try { * concourse.stage(); * concourse.get(&quot;foo&quot;, 1); * concourse.add(&quot;foo&quot;, &quot;bar&quot;, 1); * concourse.commit(); * } * catch (TransactionException e) { * concourse.abort(); * } * </pre> * * </p> */ public abstract void stage() throws TransactionException; /** * Remove link from {@code key} in {@code source} to {@code destination}. * * @param key * @param source * @param destination * @return {@code true} if the link is removed */ public abstract boolean unlink(String key, long source, long destination); /** * Verify {@code key} equals {@code value} in {@code record} and return * {@code true} if {@code value} is currently mapped from {@code key} in * {@code record}. * * @param key * @param value * @param record * @return {@code true} if {@code key} equals {@code value} in * {@code record} */ public abstract boolean verify(String key, Object value, long record); /** * Verify {@code key} equaled {@code value} in {@code record} at * {@code timestamp} and return {@code true} if {@code value} was mapped * from {@code key} in {@code record}. * * @param key * @param value * @param record * @param timestamp * @return {@code true} if {@code key} equaled {@code value} in * {@code record} at {@code timestamp} */ public abstract boolean verify(String key, Object value, long record, Timestamp timestamp); /** * Atomically verify {@code key} equals {@code expected} in {@code record} * and swap with {@code replacement}. * * @param key * @param expected * @param record * @param replacement * @return {@code true} if the swap is successful */ public abstract boolean verifyAndSwap(String key, Object expected, long record, Object replacement); /** * The implementation of the {@link Concourse} interface that establishes a * connection with the remote server and handles communication. This class * is a more user friendly wrapper around a Thrift * {@link ConcourseService.Client}. * * @author jnelson */ private final static class Client extends Concourse { // NOTE: The configuration variables are static because we want to // guarantee that they are set before the client connection is // constructed. Even though these variables are static, it is still the // case that any changes to the configuration will be picked up // immediately for new client connections. private static String SERVER_HOST; private static int SERVER_PORT; private static String USERNAME; private static String PASSWORD; private static String ENVIRONMENT; static { ConcourseConfiguration config; try { config = ConcourseConfiguration .loadConfig("concourse_client.prefs"); } catch (Exception e) { config = null; } SERVER_HOST = "localhost"; SERVER_PORT = 1717; USERNAME = "admin"; PASSWORD = "admin"; ENVIRONMENT = ""; if(config != null) { SERVER_HOST = config.getString("host", SERVER_HOST); SERVER_PORT = config.getInt("port", SERVER_PORT); USERNAME = config.getString("username", USERNAME); PASSWORD = config.getString("password", PASSWORD); ENVIRONMENT = config.getString("environment", ENVIRONMENT); } } /** * Represents a request to respond to a query using the current state as * opposed to the history. */ private static Timestamp now = Timestamp.fromMicros(0); /** * An encrypted copy of the username passed to the constructor. */ private final ByteBuffer username; /** * An encrypted copy of the password passed to the constructor. */ private final ByteBuffer password; /** * The host of the connection. */ private final String host; /** * The port of the connection. */ private final int port; /** * The environment to which the client is connected. */ private final String environment; /** * The Thrift client that actually handles all RPC communication. */ private final ConcourseService.Client client; /** * The client keeps a copy of its {@link AccessToken} and passes it to * the * server for each remote procedure call. The client will * re-authenticate * when necessary using the username/password read from the prefs file. */ private AccessToken creds = null; /** * Whenever the client starts a Transaction, it keeps a * {@link TransactionToken} so that the server can stage the changes in * the * appropriate place. */ private TransactionToken transaction = null; /** * Create a new Client connection to the environment of the Concourse * Server described in {@code concourse_client.prefs} (or the default * environment and server if the prefs file does not exist) and return a * handler to facilitate database interaction. */ public Client() { this(ENVIRONMENT); } /** * Create a new Client connection to the specified {@code environment} * of * the Concourse Server described in {@code concourse_client.prefs} (or * the default server if the prefs file does not exist) and return a * handler to facilitate database interaction. * * @param environment */ public Client(String environment) { this(SERVER_HOST, SERVER_PORT, USERNAME, PASSWORD, environment); } /** * Create a new Client connection to the default environment of the * specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password */ public Client(String host, int port, String username, String password) { this(host, port, username, password, ""); } /** * Create a new Client connection to the specified {@code environment} * of * the specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password * @param environment */ public Client(String host, int port, String username, String password, String environment) { this.host = host; this.port = port; this.username = ClientSecurity.encrypt(username); this.password = ClientSecurity.encrypt(password); this.environment = environment; final TTransport transport = new TSocket(host, port); try { transport.open(); TProtocol protocol = new TBinaryProtocol(transport); client = new ConcourseService.Client(protocol); authenticate(); Runtime.getRuntime().addShutdownHook(new Thread("shutdown") { @Override public void run() { if(transaction != null && transport.isOpen()) { abort(); } } }); } catch (TTransportException e) { throw new RuntimeException( "Could not connect to the Concourse Server at " + host + ":" + port); } } @Override public void abort() { execute(new Callable<Void>() { @Override public Void call() throws Exception { if(transaction != null) { final TransactionToken token = transaction; transaction = null; client.abort(creds, token, environment); } return null; } }); } @Override public Map<Long, Boolean> add(String key, Object value, Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, add(key, value, record)); } return result; } @Override public <T> boolean add(final String key, final T value, final long record) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.add(key, Convert.javaToThrift(value), record, creds, transaction, environment); } }); } return false; } @Override public Map<Timestamp, String> audit(final long record) { return execute(new Callable<Map<Timestamp, String>>() { @Override public Map<Timestamp, String> call() throws Exception { Map<Long, String> audit = client.audit(record, null, creds, transaction, environment); return ((TLinkedHashMap<Timestamp, String>) Transformers .transformMap(audit, new Function<Long, Timestamp>() { @Override public Timestamp apply(Long input) { return Timestamp.fromMicros(input); } })).setKeyName("DateTime").setValueName( "Revision"); } }); } @Override public Map<Timestamp, String> audit(final String key, final long record) { return execute(new Callable<Map<Timestamp, String>>() { @Override public Map<Timestamp, String> call() throws Exception { Map<Long, String> audit = client.audit(record, key, creds, transaction, environment); return ((TLinkedHashMap<Timestamp, String>) Transformers .transformMap(audit, new Function<Long, Timestamp>() { @Override public Timestamp apply(Long input) { return Timestamp.fromMicros(input); } })).setKeyName("DateTime").setValueName( "Revision"); } }); } @CompoundOperation @Override public Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records) { Map<Long, Map<String, Set<Object>>> data = TLinkedTableMap .newTLinkedTableMap("Record"); for (long record : records) { data.put(record, browse(record, now)); } return data; } @CompoundOperation @Override public Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records, Timestamp timestamp) { Map<Long, Map<String, Set<Object>>> data = TLinkedTableMap .newTLinkedTableMap("Record"); for (long record : records) { data.put(record, browse(record, timestamp)); } return data; } @Override public Map<String, Set<Object>> browse(long record) { return browse(record, now); } @Override public Map<String, Set<Object>> browse(final long record, final Timestamp timestamp) { return execute(new Callable<Map<String, Set<Object>>>() { @Override public Map<String, Set<Object>> call() throws Exception { Map<String, Set<Object>> data = TLinkedHashMap .newTLinkedHashMap("Key", "Values"); for (Entry<String, Set<TObject>> entry : client.browse0( record, timestamp.getMicros(), creds, transaction, environment).entrySet()) { data.put(entry.getKey(), Transformers.transformSet( entry.getValue(), new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert.thriftToJava(input); } })); } return data; } }); } @Override public Map<Object, Set<Long>> browse(String key) { return browse(key, now); } @Override public Map<Object, Set<Long>> browse(final String key, final Timestamp timestamp) { return execute(new Callable<Map<Object, Set<Long>>>() { @Override public Map<Object, Set<Long>> call() throws Exception { Map<Object, Set<Long>> data = TLinkedHashMap .newTLinkedHashMap(key, "Records"); for (Entry<TObject, Set<Long>> entry : client.browse1(key, timestamp.getMicros(), creds, transaction, environment).entrySet()) { data.put(Convert.thriftToJava(entry.getKey()), entry.getValue()); } return data; } }); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record) { return execute(new Callable<Map<Timestamp, Set<Object>>>() { @Override public Map<Timestamp, Set<Object>> call() throws Exception { Map<Long, Set<TObject>> chronologize = client.chronologize( record, key, creds, transaction, environment); Map<Timestamp, Set<Object>> result = TLinkedHashMap .newTLinkedHashMap("DateTime", "Values"); for (Entry<Long, Set<TObject>> entry : chronologize .entrySet()) { result.put(Timestamp.fromMicros(entry.getKey()), Transformers.transformSet(entry.getValue(), new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert .thriftToJava(input); } })); } return result; } }); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record, final Timestamp start) { return chronologize(key, record, start, Timestamp.now()); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record, final Timestamp start, final Timestamp end) { Preconditions.checkArgument(start.getMicros() <= end.getMicros(), "Start of range cannot be greater than the end"); Map<Timestamp, Set<Object>> result = TLinkedHashMap .newTLinkedHashMap("DateTime", "Values"); Map<Timestamp, Set<Object>> chronology = chronologize(key, record); int index = Timestamps.findNearestSuccessorForTimestamp( chronology.keySet(), start); Entry<Timestamp, Set<Object>> entry = null; if(index > 0) { entry = Iterables.get(chronology.entrySet(), index - 1); result.put(entry.getKey(), entry.getValue()); } for (int i = index; i < chronology.size(); i++) { entry = Iterables.get(chronology.entrySet(), i); if(entry.getKey().getMicros() >= end.getMicros()) { break; } result.put(entry.getKey(), entry.getValue()); } return result; } @Override public void clear(final Collection<Long> records) { for (Long record : records) { clear(record); } } @Override public void clear(Collection<String> keys, Collection<Long> records) { for (long record : records) { for (String key : keys) { clear(key, record); } } } @Override public void clear(Collection<String> keys, long record) { for (String key : keys) { clear(key, record); } } @Override public void clear(final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.clear1(record, creds, transaction, environment); return null; } }); } @Override public void clear(String key, Collection<Long> records) { for (long record : records) { clear(key, record); } } @Override public void clear(final String key, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.clear(key, record, creds, transaction, environment); return null; } }); } @Override public boolean commit() { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final TransactionToken token = transaction; transaction = null; return client.commit(creds, token, environment); } }); } @Override public long create() { return Time.now(); // TODO get a primary key using a plugin } @Override public Map<Long, Set<String>> describe(Collection<Long> records) { Map<Long, Set<String>> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Keys"); for (long record : records) { result.put(record, describe(record)); } return result; } @Override public Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp) { Map<Long, Set<String>> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Keys"); for (long record : records) { result.put(record, describe(record, timestamp)); } return result; } @Override public Set<String> describe(long record) { return describe(record, now); } @Override public Set<String> describe(final long record, final Timestamp timestamp) { return execute(new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { return client.describe(record, timestamp.getMicros(), creds, transaction, environment); } }); } @Override public void exit() { client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); } @Override public Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records) { TLinkedTableMap<Long, String, Set<Object>> result = TLinkedTableMap .<Long, String, Set<Object>> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { result.put(record, key, fetch(key, record)); } } return result; } @Override public Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records, Timestamp timestamp) { TLinkedTableMap<Long, String, Set<Object>> result = TLinkedTableMap .<Long, String, Set<Object>> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { result.put(record, key, fetch(key, record, timestamp)); } } return result; } @Override public Map<String, Set<Object>> fetch(Collection<String> keys, long record) { Map<String, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Values"); for (String key : keys) { result.put(key, fetch(key, record)); } return result; } @Override public Map<String, Set<Object>> fetch(Collection<String> keys, long record, Timestamp timestamp) { Map<String, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Values"); for (String key : keys) { result.put(key, fetch(key, record, timestamp)); } return result; } @Override public Map<Long, Set<Object>> fetch(String key, Collection<Long> records) { Map<Long, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { result.put(record, fetch(key, record)); } return result; } @Override public Map<Long, Set<Object>> fetch(String key, Collection<Long> records, Timestamp timestamp) { Map<Long, Set<Object>> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { result.put(record, fetch(key, record, timestamp)); } return result; } @Override public Set<Object> fetch(String key, long record) { return fetch(key, record, now); } @Override public Set<Object> fetch(final String key, final long record, final Timestamp timestamp) { return execute(new Callable<Set<Object>>() { @Override public Set<Object> call() throws Exception { Set<TObject> values = client.fetch(key, record, timestamp.getMicros(), creds, transaction, environment); return Transformers.transformSet(values, new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert.thriftToJava(input); } }); } }); } @Override public Set<Long> find(final Criteria criteria) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find1(Translate.toThrift(criteria), creds, transaction, environment); } }); } @Override public Set<Long> find(Object object) { if(object instanceof BuildableState) { return find(((BuildableState) object).build()); } else { throw new IllegalArgumentException(object + " is not a valid argument for the find method"); } } @Override public Set<Long> find(String key, Operator operator, Object value) { return find(key, operator, value, now); } @Override public Set<Long> find(String key, Operator operator, Object value, Object value2) { return find(key, operator, value, value2, now); } @Override public Set<Long> find(final String key, final Operator operator, final Object value, final Object value2, final Timestamp timestamp) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find(key, operator, Lists.transform( Lists.newArrayList(value, value2), new Function<Object, TObject>() { @Override public TObject apply(Object input) { return Convert.javaToThrift(input); } }), timestamp.getMicros(), creds, transaction, environment); } }); } @Override public Set<Long> find(final String key, final Operator operator, final Object value, final Timestamp timestamp) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find(key, operator, Lists.transform( Lists.newArrayList(value), new Function<Object, TObject>() { @Override public TObject apply(Object input) { return Convert.javaToThrift(input); } }), timestamp.getMicros(), creds, transaction, environment); } }); } @Override public Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records) { TLinkedTableMap<Long, String, Object> result = TLinkedTableMap .<Long, String, Object> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { Object value = get(key, record); if(value != null) { result.put(record, key, value); } } } return result; } @Override public Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { TLinkedTableMap<Long, String, Object> result = TLinkedTableMap .<Long, String, Object> newTLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { Object value = get(key, record, timestamp); if(value != null) { result.put(record, key, value); } } } return result; } @Override public Map<String, Object> get(Collection<String> keys, long record) { Map<String, Object> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Value"); for (String key : keys) { Object value = get(key, record); if(value != null) { result.put(key, value); } } return result; } @Override public Map<String, Object> get(Collection<String> keys, long record, Timestamp timestamp) { Map<String, Object> result = TLinkedHashMap.newTLinkedHashMap( "Key", "Value"); for (String key : keys) { Object value = get(key, record, timestamp); if(value != null) { result.put(key, value); } } return result; } @Override public Map<Long, Object> get(String key, Collection<Long> records) { Map<Long, Object> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { Object value = get(key, record); if(value != null) { result.put(record, value); } } return result; } @Override public Map<Long, Object> get(String key, Collection<Long> records, Timestamp timestamp) { Map<Long, Object> result = TLinkedHashMap.newTLinkedHashMap( "Record", key); for (long record : records) { Object value = get(key, record, timestamp); if(value != null) { result.put(record, value); } } return result; } @Override @Nullable public <T> T get(String key, long record) { return get(key, record, now); } @SuppressWarnings("unchecked") @Override @Nullable public <T> T get(String key, long record, Timestamp timestamp) { Set<Object> values = fetch(key, record, timestamp); if(!values.isEmpty()) { return (T) values.iterator().next(); } return null; } @Override public String getServerEnvironment() { return execute(new Callable<String>() { @Override public String call() throws Exception { return client.getServerEnvironment(creds, transaction, environment); } }); } @Override public String getServerVersion() { return execute(new Callable<String>() { @Override public String call() throws Exception { return client.getServerVersion(); } }); } @Override public long insert(final String json) { return execute(new Callable<Long>() { @Override public Long call() throws Exception { return client .insert1(json, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> insert(String json, Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, insert(json, record)); } return result; } @Override public boolean insert(final String json, final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.insert(json, record, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> link(String key, long source, Collection<Long> destinations) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long destination : destinations) { result.put(destination, link(key, source, destination)); } return result; } @Override public boolean link(String key, long source, long destination) { return add(key, Link.to(destination), source); } @Override public Map<Long, Boolean> ping(Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, ping(record)); } return result; } @Override public boolean ping(final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.ping(record, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> remove(String key, Object value, Collection<Long> records) { Map<Long, Boolean> result = TLinkedHashMap.newTLinkedHashMap( "Record", "Result"); for (long record : records) { result.put(record, remove(key, value, record)); } return result; } @Override public <T> boolean remove(final String key, final T value, final long record) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.remove(key, Convert.javaToThrift(value), record, creds, transaction, environment); } }); } return false; } @Override public void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { for (long record : records) { for (String key : keys) { revert(key, record, timestamp); } } } @Override public void revert(Collection<String> keys, long record, Timestamp timestamp) { for (String key : keys) { revert(key, record, timestamp); } } @Override public void revert(String key, Collection<Long> records, Timestamp timestamp) { for (long record : records) { revert(key, record, timestamp); } } @Override public void revert(final String key, final long record, final Timestamp timestamp) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.revert(key, record, timestamp.getMicros(), creds, transaction, environment); return null; } }); } @Override public Set<Long> search(final String key, final String query) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.search(key, query, creds, transaction, environment); } }); } @Override public void set(String key, Object value, Collection<Long> records) { for (long record : records) { set(key, value, record); } } @Override public <T> void set(final String key, final T value, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.set0(key, Convert.javaToThrift(value), record, creds, transaction, environment); return null; } }); } @Override public void stage() throws TransactionException { execute(new Callable<Void>() { @Override public Void call() throws Exception { transaction = client.stage(creds, environment); return null; } }); } @Override public String toString() { return "Connected to " + host + ":" + port + " as " + new String(ClientSecurity.decrypt(username).array()); } @Override public boolean unlink(String key, long source, long destination) { return remove(key, Link.to(destination), source); } @Override public boolean verify(String key, Object value, long record) { return verify(key, value, record, now); } @Override public boolean verify(final String key, final Object value, final long record, final Timestamp timestamp) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.verify(key, Convert.javaToThrift(value), record, timestamp.getMicros(), creds, transaction, environment); } }); } @Override public boolean verifyAndSwap(final String key, final Object expected, final long record, final Object replacement) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.verifyAndSwap(key, Convert.javaToThrift(expected), record, Convert.javaToThrift(replacement), creds, transaction, environment); } }); } /** * Authenticate the {@link #username} and {@link #password} and populate * {@link #creds} with the appropriate AccessToken. */ private void authenticate() { try { creds = client.login(ClientSecurity.decrypt(username), ClientSecurity.decrypt(password), environment); } catch (TException e) { throw Throwables.propagate(e); } } /** * Execute the task defined in {@code callable}. This method contains * retry logic to handle cases when {@code creds} expires and must be * updated. * * @param callable * @return the task result */ private <T> T execute(Callable<T> callable) { try { return callable.call(); } catch (SecurityException e) { authenticate(); return execute(callable); } catch (TTransactionException e) { throw new TransactionException(); } catch (Exception e) { throw Throwables.propagate(e); } } } }
package org.cinchapi.concourse; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.cinchapi.concourse.annotate.CompoundOperation; import org.cinchapi.concourse.config.ConcourseConfiguration; import org.cinchapi.concourse.lang.BuildableState; import org.cinchapi.concourse.lang.Criteria; import org.cinchapi.concourse.lang.Translate; import org.cinchapi.concourse.security.ClientSecurity; import org.cinchapi.concourse.thrift.AccessToken; import org.cinchapi.concourse.thrift.ConcourseService; import org.cinchapi.concourse.thrift.Operator; import org.cinchapi.concourse.thrift.TObject; import org.cinchapi.concourse.thrift.TSecurityException; import org.cinchapi.concourse.thrift.TTransactionException; import org.cinchapi.concourse.thrift.TransactionToken; import org.cinchapi.concourse.time.Time; import org.cinchapi.concourse.util.Convert; import org.cinchapi.concourse.util.PrettyLinkedTableMap; import org.cinchapi.concourse.util.Timestamps; import org.cinchapi.concourse.util.Transformers; import org.cinchapi.concourse.util.PrettyLinkedHashMap; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * <p> * Concourse is a distributed self-tuning database with automatic indexing, * version control, and ACID transactions. Concourse provides a more intuitive * approach to data management that is easy to deploy, access and scale while * maintaining the strong consistency of traditional database systems. * </p> * <h2>Data Model</h2> * <p> * The Concourse data model is lightweight and flexible. Unlike other databases, * Concourse is completely schemaless and does not hold data in tables or * collections. Instead, Concourse is simply a distributed graph of records. * Each record has multiple keys. And each key has one or more distinct values. * Like any graph, you can link records to one another. And the structure of one * record does not affect the structure of another. * </p> * <p> * <ul> * <li><strong>Record</strong> &mdash; A logical grouping of data about a single * person, place, or thing (i.e. an object). Each {@code record} is a collection * of key/value pairs that are together identified by a unique primary key. * <li><strong>Key</strong> &mdash; An attribute that maps to a set of * <em>one or more</em> distinct {@code values}. A {@code record} can have many * different {@code keys}, and the {@code keys} in one {@code record} do not * affect those in another {@code record}. * <li><strong>Value</strong> &mdash; A dynamically typed quantity that is * associated with a {@code key} in a {@code record}. * </ul> * </p> * <h4>Data Types</h4> * <p> * Concourse natively stores most of the Java primitives: boolean, double, * float, integer, long, and string (UTF-8). Otherwise, the value of the * {@link #toString()} method for the Object is stored. * </p> * <h4>Links</h4> * <p> * Concourse supports linking a {@code key} in one {@code record} to another * {@code record}. Links are one-directional, but it is possible to add two * links that are the inverse of each other to simulate bi-directionality (i.e. * link "friend" in Record 1 to Record 2 and link "friend" in Record 2 to Record * 1). * </p> * <h2>Transactions</h2> * <p> * By default, Concourse conducts every operation in {@code autocommit} mode * where every change is immediately written. Concourse also supports the * ability to stage a group of operations in transactions that are atomic, * consistent, isolated, and durable using the {@link #stage()}, * {@link #commit()} and {@link #abort()} methods. * * </p> * <h2>Thread Safety</h2> * <p> * You should <strong>not</strong> use the same client connection in multiple * threads. If you need to interact with Concourse using multiple threads, you * should create a separate connection for each thread or use a * {@link ConnectionPool}. * </p> * * @author jnelson */ public abstract class Concourse implements AutoCloseable { /** * Create a new Client connection to the environment of the Concourse Server * described in {@code concourse_client.prefs} (or the default environment * and server if the prefs file does not exist) and return a handler to * facilitate database interaction. * * @return the database handler */ public static Concourse connect() { return new Client(); } * /** Create a new Client connection to the specified {@code environment} * of the Concourse Server described in {@code concourse_client.prefs} (or * the default server if the prefs file does not exist) and return a handler * to facilitate database interaction. * * @param environment * @return */ public static Concourse connect(String environment) { return new Client(environment); } /** * Create a new Client connection to the default environment of the * specified Concourse Server and return a handler to facilitate database * interaction. * * @param host * @param port * @param username * @param password * @return the database handler */ public static Concourse connect(String host, int port, String username, String password) { return new Client(host, port, username, password); } /** * Create a new Client connection to the specified {@code environment} of * the specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password * @param environment * @return the database handler */ public static Concourse connect(String host, int port, String username, String password, String environment) { return new Client(host, port, username, password, environment); } /** * Discard any changes that are currently staged for commit. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be committed immediately. * </p> */ public abstract void abort(); /** * Add {@code key} as {@code value} in each of the {@code records} if it is * not already contained. * * @param key * @param value * @param records * @return a mapping from each record to a boolean indicating if * {@code value} is added */ @CompoundOperation public abstract Map<Long, Boolean> add(String key, Object value, Collection<Long> records); /** * Add {@code key} as {@code value} in a new record and return the primary * key. * * @param key * @param value * @return the primary key of the record in which the data was added */ public abstract <T> long add(String key, T value); /** * Add {@code key} as {@code value} to {@code record} if it is not already * contained. * * @param key * @param value * @param record * @return {@code true} if {@code value} is added */ public abstract <T> boolean add(String key, T value, long record); /** * Audit {@code record} and return a log of revisions. * * @param record * @return a mapping from timestamp to a description of a revision */ public abstract Map<Timestamp, String> audit(long record); /** * Audit {@code key} in {@code record} and return a log of revisions. * * @param key * @param record * @return a mapping from timestamp to a description of a revision */ public abstract Map<Timestamp, String> audit(String key, long record); /** * Browse the {@code records} and return a mapping from each record to all * the data that is contained as a mapping from key name to value set. * * @param records * @return a mapping of all the contained keys and their mapped values in * each record */ public abstract Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records); /** * Browse the {@code records} at {@code timestamp} and return a mapping from * each record to all the data that was contained as a mapping from key name * to value set. * * @param records * @param timestamp * @return a mapping of all the contained keys and their mapped values in * each record */ public abstract Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records, Timestamp timestamp); /** * Browse {@code record} and return all the data that is presently contained * as a mapping from key name to value set. * <p> * <em>This method is the atomic equivalent of calling * {@code fetch(describe(record), record)}</em> * </p> * * @param record * @return a mapping of all the presently contained keys and their mapped * values */ public abstract Map<String, Set<Object>> browse(long record); /** * Browse {@code record} at {@code timestamp} and return all the data that * was contained as a mapping from key name to value set. * <p> * <em>This method is the atomic equivalent of calling * {@code fetch(describe(record, timestamp), record, timestamp)}</em> * </p> * * @param record * @param timestamp * @return a mapping of all the contained keys and their mapped values */ public abstract Map<String, Set<Object>> browse(long record, Timestamp timestamp); /** * Browse {@code key} and return all the data that is indexed as a mapping * from value to the set of records containing the value for {@code key}. * * @param key * @return a mapping of all the indexed values and their associated records. */ public abstract Map<Object, Set<Long>> browse(String key); /** * Browse {@code key} at {@code timestamp} and return all the data that was * indexed as a mapping from value to the set of records that contained the * value for {@code key} . * * @param key * @param timestamp * @return a mapping of all the indexed values and their associated records. */ public abstract Map<Object, Set<Long>> browse(String key, Timestamp timestamp); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * and return a mapping from each timestamp to the non-empty set of values. * * @param key * @param record * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record */ public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * from {@code start} timestamp inclusively to present and return a mapping * from each timestamp to the non-emtpy set of values. * * @param key * @param record * @param start * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record from specified start * timestamp to present */ @CompoundOperation public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start); /** * Chronologize non-empty sets of values in {@code key} from {@code record} * from {@code start} timestamp inclusively to {@code end} timestamp * exclusively and return a mapping from each timestamp to the non-empty set * of values. * * @param key * @param record * @param start * @param end * @return a chronological mapping from each timestamp to the set of values * that were contained for the key in record from specified start * timestamp to specified end timestamp */ @CompoundOperation public abstract Map<Timestamp, Set<Object>> chronologize(String key, long record, Timestamp start, Timestamp end); /** * Clear every {@code key} and contained value in each of the * {@code records} by removing every value for each {@code key} in each * record. * * @param records */ @CompoundOperation public abstract void clear(Collection<Long> records); /** * Clear each of the {@code keys} in each of the {@code records} by removing * every value for each key in each record. * * @param keys * @param records */ @CompoundOperation public abstract void clear(Collection<String> keys, Collection<Long> records); /** * Clear each of the {@code keys} in {@code record} by removing every value * for each key. * * @param keys * @param record */ @CompoundOperation public abstract void clear(Collection<String> keys, long record); /** * Atomically clear {@code record} by removing each contained key and their * values. * * @param record */ public abstract void clear(long record); /** * Clear {@code key} in each of the {@code records} by removing every value * for {@code key} in each record. * * @param key * @param records */ @CompoundOperation public abstract void clear(String key, Collection<Long> records); /** * Atomically clear {@code key} in {@code record} by removing each contained * value. * * @param record */ public abstract void clear(String key, long record); @Override public final void close() { exit(); } /** * Attempt to permanently commit all the currently staged changes. This * function returns {@code true} if and only if all the changes can be * successfully applied. Otherwise, this function returns {@code false} and * all the changes are aborted. * <p> * After this function returns, Concourse will return to {@code autocommit} * mode and all subsequent changes will be written immediately. * </p> * * @return {@code true} if all staged changes are successfully committed */ public abstract boolean commit(); /** * Create a new Record and return its Primary Key. * * @return the Primary Key of the new Record */ public abstract long create(); /** * Describe each of the {@code records} and return a mapping from each * record to the keys that currently have at least one value. * * @param records * @return the populated keys in each record */ @CompoundOperation public abstract Map<Long, Set<String>> describe(Collection<Long> records); /** * Describe each of the {@code records} at {@code timestamp} and return a * mapping from each record to the keys that had at least one value. * * @param records * @param timestamp * @return the populated keys in each record at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp); /** * Describe {@code record} and return the keys that currently have at least * one value. * * @param record * @return the populated keys in {@code record} */ public abstract Set<String> describe(long record); /** * Describe {@code record} at {@code timestamp} and return the keys that had * at least one value. * * @param record * @param timestamp * @return the populated keys in {@code record} at {@code timestamp} */ public abstract Set<String> describe(long record, Timestamp timestamp); /** * Close the Client connection. */ public abstract void exit(); /** * Fetch each of the {@code keys} from each of the {@code records} and * return a mapping from each record to a mapping from each key to the * contained values. * * @param keys * @param records * @return the contained values for each of the {@code keys} in each of the * {@code records} */ @CompoundOperation public abstract Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records); /** * Fetch each of the {@code keys} from each of the {@code records} at * {@code timestamp} and return a mapping from each record to a mapping from * each key to the contained values. * * @param keys * @param records * @param timestamp * @return the contained values for each of the {@code keys} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Fetch each of the {@code keys} from {@code record} and return a mapping * from each key to the contained values. * * @param keys * @param record * @return the contained values for each of the {@code keys} in * {@code record} */ @CompoundOperation public abstract Map<String, Set<Object>> fetch(Collection<String> keys, long record); /** * Fetch each of the {@code keys} from {@code record} at {@code timestamp} * and return a mapping from each key to the contained values. * * @param keys * @param record * @param timestamp * @return the contained values for each of the {@code keys} in * {@code record} at {@code timestamp} */ @CompoundOperation public abstract Map<String, Set<Object>> fetch(Collection<String> keys, long record, Timestamp timestamp); /** * Fetch {@code key} from each of the {@code records} and return a mapping * from each record to contained values. * * @param key * @param records * @return the contained values for {@code key} in each {@code record} */ @CompoundOperation public abstract Map<Long, Set<Object>> fetch(String key, Collection<Long> records); /** * Fetch {@code key} from} each of the {@code records} at {@code timestamp} * and return a mapping from each record to the contained values. * * @param key * @param records * @param timestamp * @return the contained values for {@code key} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Set<Object>> fetch(String key, Collection<Long> records, Timestamp timestamp); /** * Fetch {@code key} from {@code record} and return all the contained * values. * * @param key * @param record * @return the contained values */ public abstract Set<Object> fetch(String key, long record); /** * Fetch {@code key} from {@code record} at {@code timestamp} and return the * set of values that were mapped. * * @param key * @param record * @param timestamp * @return the contained values */ public abstract Set<Object> fetch(String key, long record, Timestamp timestamp); /** * Find and return the set of records that satisfy the {@code criteria}. * This is analogous to the SELECT action in SQL. * * @param criteria * @return the records that match the {@code criteria} */ public abstract Set<Long> find(Criteria criteria); /** * Find and return the set of records that satisfy the {@code criteria}. * This is analogous to the SELECT action in SQL. * * @param criteria * @return the records that match the {@code criteria} */ public abstract Set<Long> find(Object criteria); // this method exists in // case the caller // forgets // to called #build() on // the CriteriaBuilder /** * Find and return the set of records where {@code key} is equal to * {@code value}. This method is a shortcut for calling * {@link #find(String, Operator, Object)} with {@link Operator#EQUALS}. * * @param key * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, Object value); /** * Find {@code key} {@code operator} {@code value} and return the set of * records that satisfy the criteria. This is analogous to the SELECT action * in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value); /** * Find {@code key} {@code operator} {@code value} and {@code value2} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Object value2); /** * Find {@code key} {@code operator} {@code value} and {@code value2} at * {@code timestamp} and return the set of records that satisfy the * criteria. This is analogous to the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @param timestamp * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Object value2, Timestamp timestamp); /** * Find {@code key} {@code operator} {@code value} at {@code timestamp} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, Operator operator, Object value, Timestamp timestamp); /** * Find {@code key} {@code operator} {@code value} and return the set of * records that satisfy the criteria. This is analogous to the SELECT action * in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, String operator, Object value); /** * Find {@code key} {@code operator} {@code value} and {@code value2} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @return the records that match the criteria */ public abstract Set<Long> find(String key, String operator, Object value, Object value2); /** * Find {@code key} {@code operator} {@code value} and {@code value2} at * {@code timestamp} and return the set of records that satisfy the * criteria. This is analogous to the SELECT action in SQL. * * @param key * @param operator * @param value * @param value2 * @param timestamp * @return the records that match the criteria */ public abstract Set<Long> find(String key, String operator, Object value, Object value2, Timestamp timestamp); /** * Find {@code key} {@code operator} {@code value} at {@code timestamp} and * return the set of records that satisfy the criteria. This is analogous to * the SELECT action in SQL. * * @param key * @param operator * @param value * @return the records that match the criteria */ public abstract Set<Long> find(String key, String operator, Object value, Timestamp timestamp); /** * Get each of the {@code keys} from each of the {@code records} and return * a mapping from each record to a mapping of each key to the first * contained value. * * @param keys * @param records * @return the first contained value for each of the {@code keys} in each of * the {@code records} */ @CompoundOperation public abstract Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records); /** * Get each of the {@code keys} from each of the {@code records} at * {@code timestamp} and return a mapping from each record to a mapping of * each key to the first contained value. * * @param keys * @param records * @param timestamp * @return the first contained value for each of the {@code keys} in each of * the {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Get each of the {@code keys} from {@code record} and return a mapping * from each key to the first contained value. * * @param keys * @param record * @return the first contained value for each of the {@code keys} in * {@code record} */ @CompoundOperation public abstract Map<String, Object> get(Collection<String> keys, long record); /** * Get each of the {@code keys} from {@code record} at {@code timestamp} and * return a mapping from each key to the first contained value. * * @param keys * @param record * @param timestamp * @return the first contained value for each of the {@code keys} in * {@code record} at {@code timestamp} */ @CompoundOperation public abstract Map<String, Object> get(Collection<String> keys, long record, Timestamp timestamp); /** * Get {@code key} from each of the {@code records} and return a mapping * from each record to the first contained value. * * @param key * @param records * @return the first contained value for {@code key} in each of the * {@code records} */ @CompoundOperation public abstract Map<Long, Object> get(String key, Collection<Long> records); /** * Get {@code key} from each of the {@code records} at {@code timestamp} and * return a mapping from each record to the first contained value. * * @param key * @param records * @param timestamp * @return the first contained value for {@code key} in each of the * {@code records} at {@code timestamp} */ @CompoundOperation public abstract Map<Long, Object> get(String key, Collection<Long> records, Timestamp timestamp); /** * Get {@code key} from {@code record} and return the first contained value * or {@code null} if there is none. Compared to * {@link #fetch(String, long)}, this method is suited for cases when the * caller is certain that {@code key} in {@code record} maps to a single * value of type {@code T}. * * @param key * @param record * @return the first contained value */ public abstract <T> T get(String key, long record); /** * Get {@code key} from {@code record} at {@code timestamp} and return the * first contained value or {@code null} if there was none. Compared to * {@link #fetch(String, long, Timestamp)}, this method is suited for cases * when the caller is certain that {@code key} in {@code record} mapped to a * single value of type {@code T} at {@code timestamp}. * * @param key * @param record * @param timestamp * @return the first contained value */ public abstract <T> T get(String key, long record, Timestamp timestamp); /** * Return the environment of the server that is currently in use by this * client. * * @return the server environment */ public abstract String getServerEnvironment(); /** * Return the version of the server to which this client is currently * connected. * * @return the server version */ public abstract String getServerVersion(); /** * Atomically insert the key/value mappings described in the {@code json} * formatted string into a new record. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @return the primary key of the new record or {@code null} if the insert * is unsuccessful */ public abstract long insert(String json); /** * Insert the key/value mappings described in the {@code json} formated * string into each of the {@code records}. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @param records * @return a mapping from each primary key to a boolean describing if the * data was successfully inserted into that record */ @CompoundOperation public abstract Map<Long, Boolean> insert(String json, Collection<Long> records); /** * Atomically insert the key/value mappings described in the {@code json} * formatted string into {@code record}. * <p> * The {@code json} formatted string must describe an JSON object that * contains one or more keys, each of which maps to a JSON primitive or an * array of JSON primitives. * </p> * * @param json * @param record * @return {@code true} if the data is inserted into {@code record} */ public abstract boolean insert(String json, long record); /** * Link {@code key} in {@code source} to each of the {@code destinations}. * * @param key * @param source * @param destinations * @return a mapping from each destination to a boolean indicating if the * link was added */ public abstract Map<Long, Boolean> link(String key, long source, Collection<Long> destinations); /** * Link {@code key} in {@code source} to {@code destination}. * * @param key * @param source * @param destination * @return {@code true} if the link is added */ public abstract boolean link(String key, long source, long destination); /** * Ping each of the {@code records}. * * @param records * @return a mapping from each record to a boolean indicating if the record * currently has at least one populated key */ @CompoundOperation public abstract Map<Long, Boolean> ping(Collection<Long> records); /** * Ping {@code record}. * * @param record * @return {@code true} if {@code record} currently has at least one * populated key */ public abstract boolean ping(long record); /** * Remove {@code key} as {@code value} in each of the {@code records} if it * is contained. * * @param key * @param value * @param records * @return a mapping from each record to a boolean indicating if * {@code value} is removed */ @CompoundOperation public abstract Map<Long, Boolean> remove(String key, Object value, Collection<Long> records); /** * Remove {@code key} as {@code value} to {@code record} if it is contained. * * @param key * @param value * @param record * @return {@code true} if {@code value} is removed */ public abstract <T> boolean remove(String key, T value, long record); /** * Revert each of the {@code keys} in each of the {@code records} to * {@code timestamp} by creating new revisions that the relevant changes * that have occurred since {@code timestamp}. * * @param keys * @param records * @param timestamp */ @CompoundOperation public abstract void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp); /** * Revert each of the {@code keys} in {@code record} to {@code timestamp} by * creating new revisions that the relevant changes that have occurred since * {@code timestamp}. * * @param keys * @param record * @param timestamp */ @CompoundOperation public abstract void revert(Collection<String> keys, long record, Timestamp timestamp); /** * Revert {@code key} in each of the {@code records} to {@code timestamp} by * creating new revisions that the relevant changes that have occurred since * {@code timestamp}. * * @param key * @param records * @param timestamp */ @CompoundOperation public abstract void revert(String key, Collection<Long> records, Timestamp timestamp); /** * Atomically revert {@code key} in {@code record} to {@code timestamp} by * creating new revisions that undo the relevant changes that have occurred * since {@code timestamp}. * * @param key * @param record * @param timestamp */ public abstract void revert(String key, long record, Timestamp timestamp); /** * Search {@code key} for {@code query} and return the set of records that * match. * * @param key * @param query * @return the records that match the query */ public abstract Set<Long> search(String key, String query); /** * Set {@code key} as {@code value} in each of the {@code records}. * * @param key * @param value * @param records */ @CompoundOperation public abstract void set(String key, Object value, Collection<Long> records); /** * Atomically set {@code key} as {@code value} in {@code record}. This is a * convenience method that clears the values for {@code key} and adds * {@code value}. * * @param key * @param value * @param record */ public abstract <T> void set(String key, T value, long record); /** * Turn on {@code staging} mode so that all subsequent changes are collected * in a staging area before possibly being committed. Staged operations are * guaranteed to be reliable, all or nothing units of work that allow * correct recovery from failures and provide isolation between clients so * that Concourse is always in a consistent state (e.g. a transaction). * <p> * After this method returns, all subsequent operations will be done in * {@code staging} mode until either {@link #abort()} or {@link #commit()} * is invoked. * </p> * <p> * All operations that occur within a transaction should be wrapped in a * try-catch block so that transaction exceptions can be caught and the * transaction can be properly aborted. * * <pre> * try { * concourse.stage(); * concourse.get(&quot;foo&quot;, 1); * concourse.add(&quot;foo&quot;, &quot;bar&quot;, 1); * concourse.commit(); * } * catch (TransactionException e) { * concourse.abort(); * } * </pre> * * </p> */ public abstract void stage() throws TransactionException; /** * Remove link from {@code key} in {@code source} to {@code destination}. * * @param key * @param source * @param destination * @return {@code true} if the link is removed */ public abstract boolean unlink(String key, long source, long destination); /** * Verify {@code key} equals {@code value} in {@code record} and return * {@code true} if {@code value} is currently mapped from {@code key} in * {@code record}. * * @param key * @param value * @param record * @return {@code true} if {@code key} equals {@code value} in * {@code record} */ public abstract boolean verify(String key, Object value, long record); /** * Verify {@code key} equaled {@code value} in {@code record} at * {@code timestamp} and return {@code true} if {@code value} was mapped * from {@code key} in {@code record}. * * @param key * @param value * @param record * @param timestamp * @return {@code true} if {@code key} equaled {@code value} in * {@code record} at {@code timestamp} */ public abstract boolean verify(String key, Object value, long record, Timestamp timestamp); /** * Atomically verify {@code key} equals {@code expected} in {@code record} * and swap with {@code replacement}. * * @param key * @param expected * @param record * @param replacement * @return {@code true} if the swap is successful */ public abstract boolean verifyAndSwap(String key, Object expected, long record, Object replacement); /** * Atomically verify that {@code key} equals {@code expected} in * {@code record} or set it as such. * <p> * Please note that after returning, this method guarantees that {@code key} * in {@code record} will only contain {@code value}, even if {@code value} * already existed alongside other values [e.g. calling verifyOrSet("foo", * "bar", 1) will mean that "foo" in 1 only has "bar" as a value after * returning, even if "foo" in 1 already had "bar", "baz", and "apple" as * values]. * </p> * <p> * <em>So, basically, this function has the same guarantee as the * {@link #set(String, Object, long)} method, except it will not create any * new revisions unless it is necessary to do so.</em> The {@code set} * method, on the other hand, would indiscriminately clear all the values * for {@code key} in {@code record} before adding {@code value}, even if * {@code value} already existed. * </p> * <p> * If you want to add a new value if it does not exist while also preserving * other values, you should use the {@link #add(String, Object, long)} * method instead. * </p> * * @param key * @param value * @param record */ public abstract void verifyOrSet(String key, Object value, long record); /** * The implementation of the {@link Concourse} interface that establishes a * connection with the remote server and handles communication. This class * is a more user friendly wrapper around a Thrift * {@link ConcourseService.Client}. * * @author jnelson */ private final static class Client extends Concourse { // NOTE: The configuration variables are static because we want to // guarantee that they are set before the client connection is // constructed. Even though these variables are static, it is still the // case that any changes to the configuration will be picked up // immediately for new client connections. private static String SERVER_HOST; private static int SERVER_PORT; private static String USERNAME; private static String PASSWORD; private static String ENVIRONMENT; static { ConcourseConfiguration config; try { config = ConcourseConfiguration .loadConfig("concourse_client.prefs"); } catch (Exception e) { config = null; } SERVER_HOST = "localhost"; SERVER_PORT = 1717; USERNAME = "admin"; PASSWORD = "admin"; ENVIRONMENT = ""; if(config != null) { SERVER_HOST = config.getString("host", SERVER_HOST); SERVER_PORT = config.getInt("port", SERVER_PORT); USERNAME = config.getString("username", USERNAME); PASSWORD = config.getString("password", PASSWORD); ENVIRONMENT = config.getString("environment", ENVIRONMENT); } } /** * Represents a request to respond to a query using the current state as * opposed to the history. */ private static Timestamp now = Timestamp.fromMicros(0); /** * An encrypted copy of the username passed to the constructor. */ private final ByteBuffer username; /** * An encrypted copy of the password passed to the constructor. */ private final ByteBuffer password; /** * The host of the connection. */ private final String host; /** * The port of the connection. */ private final int port; /** * The environment to which the client is connected. */ private final String environment; /** * The Thrift client that actually handles all RPC communication. */ private final ConcourseService.Client client; /** * The client keeps a copy of its {@link AccessToken} and passes it to * the server for each remote procedure call. The client will * re-authenticate when necessary using the username/password read from * the prefs file. */ private AccessToken creds = null; /** * Whenever the client starts a Transaction, it keeps a * {@link TransactionToken} so that the server can stage the changes in * the appropriate place. */ private TransactionToken transaction = null; /** * Create a new Client connection to the environment of the Concourse * Server described in {@code concourse_client.prefs} (or the default * environment and server if the prefs file does not exist) and return a * handler to facilitate database interaction. */ public Client() { this(ENVIRONMENT); } /** * Create a new Client connection to the specified {@code environment} * of the Concourse Server described in {@code concourse_client.prefs} * (or the default server if the prefs file does not exist) and return a * handler to facilitate database interaction. * * @param environment */ public Client(String environment) { this(SERVER_HOST, SERVER_PORT, USERNAME, PASSWORD, environment); } /** * Create a new Client connection to the default environment of the * specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password */ public Client(String host, int port, String username, String password) { this(host, port, username, password, ""); } /** * Create a new Client connection to the specified {@code environment} * of the specified Concourse Server and return a handler to facilitate * database interaction. * * @param host * @param port * @param username * @param password * @param environment */ public Client(String host, int port, String username, String password, String environment) { this.host = host; this.port = port; this.username = ClientSecurity.encrypt(username); this.password = ClientSecurity.encrypt(password); this.environment = environment; final TTransport transport = new TSocket(host, port); try { transport.open(); TProtocol protocol = new TBinaryProtocol(transport); client = new ConcourseService.Client(protocol); authenticate(); Runtime.getRuntime().addShutdownHook(new Thread("shutdown") { @Override public void run() { if(transaction != null && transport.isOpen()) { abort(); } } }); } catch (TTransportException e) { throw new RuntimeException( "Could not connect to the Concourse Server at " + host + ":" + port); } } @Override public void abort() { execute(new Callable<Void>() { @Override public Void call() throws Exception { if(transaction != null) { final TransactionToken token = transaction; transaction = null; client.abort(creds, token, environment); } return null; } }); } @Override public Map<Long, Boolean> add(String key, Object value, Collection<Long> records) { Map<Long, Boolean> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", "Result"); for (long record : records) { result.put(record, add(key, value, record)); } return result; } public <T> long add(final String key, final T value) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Long>() { @Override public Long call() throws Exception { return client.add1(key, Convert.javaToThrift(value), creds, transaction, environment); } }); } else { throw new IllegalArgumentException( "Either your key is blank or value"); } } @Override public <T> boolean add(final String key, final T value, final long record) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.add(key, Convert.javaToThrift(value), record, creds, transaction, environment); } }); } return false; } @Override public Map<Timestamp, String> audit(final long record) { return execute(new Callable<Map<Timestamp, String>>() { @Override public Map<Timestamp, String> call() throws Exception { Map<Long, String> audit = client.audit(record, null, creds, transaction, environment); return ((PrettyLinkedHashMap<Timestamp, String>) Transformers .transformMap(audit, new Function<Long, Timestamp>() { @Override public Timestamp apply(Long input) { return Timestamp.fromMicros(input); } })).setKeyName("DateTime").setValueName( "Revision"); } }); } @Override public Map<Timestamp, String> audit(final String key, final long record) { return execute(new Callable<Map<Timestamp, String>>() { @Override public Map<Timestamp, String> call() throws Exception { Map<Long, String> audit = client.audit(record, key, creds, transaction, environment); return ((PrettyLinkedHashMap<Timestamp, String>) Transformers .transformMap(audit, new Function<Long, Timestamp>() { @Override public Timestamp apply(Long input) { return Timestamp.fromMicros(input); } })).setKeyName("DateTime").setValueName( "Revision"); } }); } @CompoundOperation @Override public Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records) { Map<Long, Map<String, Set<Object>>> data = PrettyLinkedTableMap .newPrettyLinkedTableMap("Record"); for (long record : records) { data.put(record, browse(record, now)); } return data; } @CompoundOperation @Override public Map<Long, Map<String, Set<Object>>> browse( Collection<Long> records, Timestamp timestamp) { Map<Long, Map<String, Set<Object>>> data = PrettyLinkedTableMap .newPrettyLinkedTableMap("Record"); for (long record : records) { data.put(record, browse(record, timestamp)); } return data; } @Override public Map<String, Set<Object>> browse(long record) { return browse(record, now); } @Override public Map<String, Set<Object>> browse(final long record, final Timestamp timestamp) { return execute(new Callable<Map<String, Set<Object>>>() { @Override public Map<String, Set<Object>> call() throws Exception { Map<String, Set<Object>> data = PrettyLinkedHashMap .newPrettyLinkedHashMap("Key", "Values"); for (Entry<String, Set<TObject>> entry : client.browse0( record, timestamp.getMicros(), creds, transaction, environment).entrySet()) { data.put(entry.getKey(), Transformers.transformSet( entry.getValue(), new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert.thriftToJava(input); } })); } return data; } }); } @Override public Map<Object, Set<Long>> browse(String key) { return browse(key, now); } @Override public Map<Object, Set<Long>> browse(final String key, final Timestamp timestamp) { return execute(new Callable<Map<Object, Set<Long>>>() { @Override public Map<Object, Set<Long>> call() throws Exception { Map<Object, Set<Long>> data = PrettyLinkedHashMap .newPrettyLinkedHashMap(key, "Records"); for (Entry<TObject, Set<Long>> entry : client.browse1(key, timestamp.getMicros(), creds, transaction, environment).entrySet()) { data.put(Convert.thriftToJava(entry.getKey()), entry.getValue()); } return data; } }); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record) { return execute(new Callable<Map<Timestamp, Set<Object>>>() { @Override public Map<Timestamp, Set<Object>> call() throws Exception { Map<Long, Set<TObject>> chronologize = client.chronologize( record, key, creds, transaction, environment); Map<Timestamp, Set<Object>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("DateTime", "Values"); for (Entry<Long, Set<TObject>> entry : chronologize .entrySet()) { result.put(Timestamp.fromMicros(entry.getKey()), Transformers.transformSet(entry.getValue(), new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert .thriftToJava(input); } })); } return result; } }); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record, final Timestamp start) { return chronologize(key, record, start, Timestamp.now()); } @Override public Map<Timestamp, Set<Object>> chronologize(final String key, final long record, final Timestamp start, final Timestamp end) { Preconditions.checkArgument(start.getMicros() <= end.getMicros(), "Start of range cannot be greater than the end"); Map<Timestamp, Set<Object>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("DateTime", "Values"); Map<Timestamp, Set<Object>> chronology = chronologize(key, record); int index = Timestamps.findNearestSuccessorForTimestamp( chronology.keySet(), start); Entry<Timestamp, Set<Object>> entry = null; if(index > 0) { entry = Iterables.get(chronology.entrySet(), index - 1); result.put(entry.getKey(), entry.getValue()); } for (int i = index; i < chronology.size(); ++i) { entry = Iterables.get(chronology.entrySet(), i); if(entry.getKey().getMicros() >= end.getMicros()) { break; } result.put(entry.getKey(), entry.getValue()); } return result; } @Override public void clear(final Collection<Long> records) { for (Long record : records) { clear(record); } } @Override public void clear(Collection<String> keys, Collection<Long> records) { for (long record : records) { for (String key : keys) { clear(key, record); } } } @Override public void clear(Collection<String> keys, long record) { for (String key : keys) { clear(key, record); } } @Override public void clear(final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.clear1(record, creds, transaction, environment); return null; } }); } @Override public void clear(String key, Collection<Long> records) { for (long record : records) { clear(key, record); } } @Override public void clear(final String key, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.clear(key, record, creds, transaction, environment); return null; } }); } @Override public boolean commit() { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final TransactionToken token = transaction; transaction = null; return client.commit(creds, token, environment); } }); } @Override public long create() { return Time.now(); // TODO get a primary key using a plugin } @Override public Map<Long, Set<String>> describe(Collection<Long> records) { Map<Long, Set<String>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", "Keys"); for (long record : records) { result.put(record, describe(record)); } return result; } @Override public Map<Long, Set<String>> describe(Collection<Long> records, Timestamp timestamp) { Map<Long, Set<String>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", "Keys"); for (long record : records) { result.put(record, describe(record, timestamp)); } return result; } @Override public Set<String> describe(long record) { return describe(record, now); } @Override public Set<String> describe(final long record, final Timestamp timestamp) { return execute(new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { return client.describe(record, timestamp.getMicros(), creds, transaction, environment); } }); } @Override public void exit() { try { client.logout(creds, environment); client.getInputProtocol().getTransport().close(); client.getOutputProtocol().getTransport().close(); } catch (TSecurityException | TTransportException e) { // Handle corner case where the client is existing because of // (or after the occurence of) a password change, which means it // can't perform a traditional logout. Its worth nothing that // we're okay with this scenario because a password change will // delete all previously issued tokens. } catch (Exception e) { throw Throwables.propagate(e); } } @Override public Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records) { PrettyLinkedTableMap<Long, String, Set<Object>> result = PrettyLinkedTableMap .<Long, String, Set<Object>> newPrettyLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { result.put(record, key, fetch(key, record)); } } return result; } @Override public Map<Long, Map<String, Set<Object>>> fetch( Collection<String> keys, Collection<Long> records, Timestamp timestamp) { PrettyLinkedTableMap<Long, String, Set<Object>> result = PrettyLinkedTableMap .<Long, String, Set<Object>> newPrettyLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { result.put(record, key, fetch(key, record, timestamp)); } } return result; } @Override public Map<String, Set<Object>> fetch(Collection<String> keys, long record) { Map<String, Set<Object>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Key", "Values"); for (String key : keys) { result.put(key, fetch(key, record)); } return result; } @Override public Map<String, Set<Object>> fetch(Collection<String> keys, long record, Timestamp timestamp) { Map<String, Set<Object>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Key", "Values"); for (String key : keys) { result.put(key, fetch(key, record, timestamp)); } return result; } @Override public Map<Long, Set<Object>> fetch(String key, Collection<Long> records) { Map<Long, Set<Object>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", key); for (long record : records) { result.put(record, fetch(key, record)); } return result; } @Override public Map<Long, Set<Object>> fetch(String key, Collection<Long> records, Timestamp timestamp) { Map<Long, Set<Object>> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", key); for (long record : records) { result.put(record, fetch(key, record, timestamp)); } return result; } @Override public Set<Object> fetch(String key, long record) { return fetch(key, record, now); } @Override public Set<Object> fetch(final String key, final long record, final Timestamp timestamp) { return execute(new Callable<Set<Object>>() { @Override public Set<Object> call() throws Exception { Set<TObject> values = client.fetch(key, record, timestamp.getMicros(), creds, transaction, environment); return Transformers.transformSet(values, new Function<TObject, Object>() { @Override public Object apply(TObject input) { return Convert.thriftToJava(input); } }); } }); } @Override public Set<Long> find(final Criteria criteria) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find1(Translate.toThrift(criteria), creds, transaction, environment); } }); } @Override public Set<Long> find(Object object) { if(object instanceof BuildableState) { return find(((BuildableState) object).build()); } else { throw new IllegalArgumentException(object + " is not a valid argument for the find method"); } } @Override public Set<Long> find(String key, Object value) { return find(key, Operator.EQUALS, value); } @Override public Set<Long> find(String key, Operator operator, Object value) { return find(key, operator, value, now); } @Override public Set<Long> find(String key, Operator operator, Object value, Object value2) { return find(key, operator, value, value2, now); } @Override public Set<Long> find(final String key, final Operator operator, final Object value, final Object value2, final Timestamp timestamp) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find(key, operator, Lists.transform( Lists.newArrayList(value, value2), new Function<Object, TObject>() { @Override public TObject apply(Object input) { return Convert.javaToThrift(input); } }), timestamp.getMicros(), creds, transaction, environment); } }); } @Override public Set<Long> find(final String key, final Operator operator, final Object value, final Timestamp timestamp) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.find(key, operator, Lists.transform( Lists.newArrayList(value), new Function<Object, TObject>() { @Override public TObject apply(Object input) { return Convert.javaToThrift(input); } }), timestamp.getMicros(), creds, transaction, environment); } }); } @Override public Set<Long> find(final String key, final String operator, final Object value) { Operator parsedOp = Convert.stringToOperator(operator); return find(key, parsedOp, value); } @Override public Set<Long> find(final String key, final String operator, final Object value, final Object value2) { Operator parsedOp = Convert.stringToOperator(operator); return find(key, parsedOp, value, value2); } @Override public Set<Long> find(final String key, final String operator, final Object value, final Object value2, Timestamp timestamp) { Operator parsedOp = Convert.stringToOperator(operator); return find(key, parsedOp, value, value2, timestamp); } @Override public Set<Long> find(final String key, final String operator, final Object value, Timestamp timestamp) { Operator parsedOp = Convert.stringToOperator(operator); return find(key, parsedOp, value, timestamp); } @Override public Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records) { PrettyLinkedTableMap<Long, String, Object> result = PrettyLinkedTableMap .<Long, String, Object> newPrettyLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { Object value = get(key, record); if(value != null) { result.put(record, key, value); } } } return result; } @Override public Map<Long, Map<String, Object>> get(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { PrettyLinkedTableMap<Long, String, Object> result = PrettyLinkedTableMap .<Long, String, Object> newPrettyLinkedTableMap("Record"); for (long record : records) { for (String key : keys) { Object value = get(key, record, timestamp); if(value != null) { result.put(record, key, value); } } } return result; } @Override public Map<String, Object> get(Collection<String> keys, long record) { Map<String, Object> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Key", "Value"); for (String key : keys) { Object value = get(key, record); if(value != null) { result.put(key, value); } } return result; } @Override public Map<String, Object> get(Collection<String> keys, long record, Timestamp timestamp) { Map<String, Object> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Key", "Value"); for (String key : keys) { Object value = get(key, record, timestamp); if(value != null) { result.put(key, value); } } return result; } @Override public Map<Long, Object> get(String key, Collection<Long> records) { Map<Long, Object> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", key); for (long record : records) { Object value = get(key, record); if(value != null) { result.put(record, value); } } return result; } @Override public Map<Long, Object> get(String key, Collection<Long> records, Timestamp timestamp) { Map<Long, Object> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", key); for (long record : records) { Object value = get(key, record, timestamp); if(value != null) { result.put(record, value); } } return result; } @Override @Nullable public <T> T get(String key, long record) { return get(key, record, now); } @SuppressWarnings("unchecked") @Override @Nullable public <T> T get(String key, long record, Timestamp timestamp) { Set<Object> values = fetch(key, record, timestamp); if(!values.isEmpty()) { return (T) values.iterator().next(); } return null; } @Override public String getServerEnvironment() { return execute(new Callable<String>() { @Override public String call() throws Exception { return client.getServerEnvironment(creds, transaction, environment); } }); } @Override public String getServerVersion() { return execute(new Callable<String>() { @Override public String call() throws Exception { return client.getServerVersion(); } }); } @Override public long insert(final String json) { return execute(new Callable<Long>() { @Override public Long call() throws Exception { return client .insert1(json, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> insert(String json, Collection<Long> records) { Map<Long, Boolean> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", "Result"); for (long record : records) { result.put(record, insert(json, record)); } return result; } @Override public boolean insert(final String json, final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.insert(json, record, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> link(String key, long source, Collection<Long> destinations) { Map<Long, Boolean> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", "Result"); for (long destination : destinations) { result.put(destination, link(key, source, destination)); } return result; } @Override public boolean link(String key, long source, long destination) { return add(key, Link.to(destination), source); } @Override public Map<Long, Boolean> ping(Collection<Long> records) { Map<Long, Boolean> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", "Result"); for (long record : records) { result.put(record, ping(record)); } return result; } @Override public boolean ping(final long record) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.ping(record, creds, transaction, environment); } }); } @Override public Map<Long, Boolean> remove(String key, Object value, Collection<Long> records) { Map<Long, Boolean> result = PrettyLinkedHashMap .newPrettyLinkedHashMap("Record", "Result"); for (long record : records) { result.put(record, remove(key, value, record)); } return result; } @Override public <T> boolean remove(final String key, final T value, final long record) { if(!StringUtils.isBlank(key) && (!(value instanceof String) || (value instanceof String && !StringUtils .isBlank((String) value)))) { // CON-21 return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.remove(key, Convert.javaToThrift(value), record, creds, transaction, environment); } }); } return false; } @Override public void revert(Collection<String> keys, Collection<Long> records, Timestamp timestamp) { for (long record : records) { for (String key : keys) { revert(key, record, timestamp); } } } @Override public void revert(Collection<String> keys, long record, Timestamp timestamp) { for (String key : keys) { revert(key, record, timestamp); } } @Override public void revert(String key, Collection<Long> records, Timestamp timestamp) { for (long record : records) { revert(key, record, timestamp); } } @Override public void revert(final String key, final long record, final Timestamp timestamp) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.revert(key, record, timestamp.getMicros(), creds, transaction, environment); return null; } }); } @Override public Set<Long> search(final String key, final String query) { return execute(new Callable<Set<Long>>() { @Override public Set<Long> call() throws Exception { return client.search(key, query, creds, transaction, environment); } }); } @Override public void set(String key, Object value, Collection<Long> records) { for (long record : records) { set(key, value, record); } } @Override public <T> void set(final String key, final T value, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.set0(key, Convert.javaToThrift(value), record, creds, transaction, environment); return null; } }); } @Override public void stage() throws TransactionException { execute(new Callable<Void>() { @Override public Void call() throws Exception { transaction = client.stage(creds, environment); return null; } }); } @Override public String toString() { return "Connected to " + host + ":" + port + " as " + new String(ClientSecurity.decrypt(username).array()); } @Override public boolean unlink(String key, long source, long destination) { return remove(key, Link.to(destination), source); } @Override public boolean verify(String key, Object value, long record) { return verify(key, value, record, now); } @Override public boolean verify(final String key, final Object value, final long record, final Timestamp timestamp) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.verify(key, Convert.javaToThrift(value), record, timestamp.getMicros(), creds, transaction, environment); } }); } @Override public boolean verifyAndSwap(final String key, final Object expected, final long record, final Object replacement) { return execute(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return client.verifyAndSwap(key, Convert.javaToThrift(expected), record, Convert.javaToThrift(replacement), creds, transaction, environment); } }); } @Override public void verifyOrSet(final String key, final Object value, final long record) { execute(new Callable<Void>() { @Override public Void call() throws Exception { client.verifyOrSet(key, Convert.javaToThrift(value), record, creds, transaction, environment); return null; } }); } /** * Authenticate the {@link #username} and {@link #password} and populate * {@link #creds} with the appropriate AccessToken. */ private void authenticate() { try { creds = client.login(ClientSecurity.decrypt(username), ClientSecurity.decrypt(password), environment); } catch (TException e) { throw Throwables.propagate(e); } } /** * Execute the task defined in {@code callable}. This method contains * retry logic to handle cases when {@code creds} expires and must be * updated. * * @param callable * @return the task result */ private <T> T execute(Callable<T> callable) { try { return callable.call(); } catch (SecurityException e) { authenticate(); return execute(callable); } catch (TTransactionException e) { throw new TransactionException(); } catch (Exception e) { throw Throwables.propagate(e); } } } }
package com.google.refine.jython; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.python.core.Py; import org.python.core.PyException; import org.python.core.PyFloat; import org.python.core.PyFunction; import org.python.core.PyInteger; import org.python.core.PyLong; import org.python.core.PyNone; import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; import com.google.refine.expr.EvalError; import com.google.refine.expr.Evaluable; import com.google.refine.expr.HasFields; import com.google.refine.expr.LanguageSpecificParser; import com.google.refine.expr.ParsingException; public class JythonEvaluable implements Evaluable { static public LanguageSpecificParser createParser() { return new LanguageSpecificParser() { @Override public Evaluable parse(String s) throws ParsingException { return new JythonEvaluable(s); } }; } private static final String s_functionName = "___temp___"; private static PythonInterpreter _engine; // FIXME(SM): this initialization logic depends on the fact that the JVM's // current working directory is the root of the OpenRefine distributions // or the development checkouts. While this works in practice, it would // be preferable to have a more reliable address space, but since we // don't have access to the servlet context from this class this is // the best we can do for now. static { File libPath = new File("webapp/WEB-INF/lib/jython"); if (!libPath.exists() && !libPath.canRead()) { libPath = new File("main/webapp/WEB-INF/lib/jython"); if (!libPath.exists() && !libPath.canRead()) { libPath = null; } } if (libPath != null) { Properties props = new Properties(); props.setProperty("python.path", libPath.getAbsolutePath()); PythonInterpreter.initialize(System.getProperties(), props, new String[] { "" }); } _engine = new PythonInterpreter(); } public JythonEvaluable(String s) { // indent and create a function out of the code String[] lines = s.split("\r\n|\r|\n"); StringBuffer sb = new StringBuffer(1024); sb.append("def "); sb.append(s_functionName); sb.append("(value, cell, cells, row, rowIndex):"); for (String line : lines) { sb.append("\n "); sb.append(line); } _engine.exec(sb.toString()); } @Override public Object evaluate(Properties bindings) { try { // call the temporary PyFunction directly Object result = ((PyFunction)_engine.get(s_functionName)).__call__( new PyObject[] { Py.java2py( bindings.get("value") ), new JythonHasFieldsWrapper((HasFields) bindings.get("cell"), bindings), new JythonHasFieldsWrapper((HasFields) bindings.get("cells"), bindings), new JythonHasFieldsWrapper((HasFields) bindings.get("row"), bindings), Py.java2py( bindings.get("rowIndex") ) } ); return unwrap(result); } catch (PyException e) { return new EvalError(e.toString()); } } protected Object unwrap(Object result) { if (result != null) { if (result instanceof JythonObjectWrapper) { return ((JythonObjectWrapper) result)._obj; } else if (result instanceof JythonHasFieldsWrapper) { return ((JythonHasFieldsWrapper) result)._obj; } else if (result instanceof PyString) { return ((PyString) result).asString(); } else if (result instanceof PyInteger) { return (long) ((PyInteger) result).asInt(); } else if (result instanceof PyLong) { return ((PyLong) result).getLong(Long.MIN_VALUE, Long.MAX_VALUE); } else if (result instanceof PyFloat) { return ((PyFloat) result).asDouble(); } else if (result instanceof PyObject) { return unwrap((PyObject) result); } } return result; } protected Object unwrap(PyObject po) { if (po instanceof PyNone) { return null; } else if (po.isNumberType()) { return po.asDouble(); } else if (po.isSequenceType()) { Iterator<PyObject> i = po.asIterable().iterator(); List<Object> list = new ArrayList<Object>(); while (i.hasNext()) { list.add(unwrap((Object) i.next())); } return list.toArray(); } else { return po; } } }
package Examples; // This file is part of Aspose.Words. The source code in this file // is only intended as a supplement to the documentation, and is provided import com.aspose.words.*; import com.aspose.words.net.System.Data.*; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.ArrayList; public class ExMailMerge extends ApiExampleBase { @Test public void executeArray() throws Exception { //ExStart //ExFor:MailMerge.Execute(String[], Object[]) //ExFor:ContentDisposition //ExFor:Document.Save(HttpResponse,String,ContentDisposition,SaveOptions) //ExId:MailMergeArray //ExSummary:Performs a simple insertion of data into merge fields. // Open an existing document. Document doc = new Document(getMyDir() + "MailMerge.ExecuteArray.doc"); // Fill the fields in the document with user data. doc.getMailMerge().execute(new String[]{"FullName", "Company", "Address", "Address2", "City"}, new Object[]{"James Bond", "MI5 Headquarters", "Milbank", "", "London"}); doc.save(getArtifactsDir() + "MailMerge.ExecuteArray.doc"); //ExEnd } @Test public void executeDataTable() throws Exception { //ExStart //ExFor:Document //ExFor:MailMerge //ExFor:MailMerge.Execute(DataTable) //ExFor:MailMerge.Execute(DataRow) //ExFor:Document.MailMerge //ExSummary:Executes mail merge from data stored in a ResultSet. Document doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc"); // This example creates a table, but you would normally load table from a database. DataTable table = new DataTable("Test"); table.getColumns().add("CustomerName"); table.getColumns().add("Address"); table.getRows().add(new Object[]{"Thomas Hardy", "120 Hanover Sq., London"}); table.getRows().add(new Object[]{"Paolo Accorti", "Via Monte Bianco 34, Torino"}); // Field values from the table are inserted into the mail merge fields found in the document. doc.getMailMerge().execute(table); doc.save(getArtifactsDir() + "MailMerge.ExecuteDataTable.doc"); // Open a fresh copy of our document to perform another mail merge. doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc"); // We can also source values for a mail merge from a single row in the table doc.getMailMerge().execute(table.getRows().get(1)); doc.save(getArtifactsDir() + "MailMerge.ExecuteDataTable.OneRow.doc"); //ExEnd } @Test public void executeDataReader() throws Exception { //ExStart //ExFor:MailMerge.Execute(IDataReader) //ExSummary:Shows how to run a mail merge using data from a data reader. // Open the template document Document doc = new Document(getMyDir() + "MailingLabelsDemo.doc"); // Open the data reader. java.sql.ResultSet resultSet = executeDataTable("SELECT TOP 50 * FROM Customers ORDER BY Country, CompanyName"); DataTable dataTable = new DataTable(resultSet, "OrderDetails"); IDataReader dataReader = new DataTableReader(dataTable); // Perform the mail merge doc.getMailMerge().execute(dataReader); doc.save(getArtifactsDir() + "MailMerge.ExecuteDataReader.doc"); //ExEnd } @Test public void executeWithRegionsDataSet() throws Exception { //ExStart //ExFor:MailMerge.ExecuteWithRegions(DataSet) //ExSummary:Executes a mail merge with repeatable regions from an ADO.NET DataSet. // Open the document. // For a mail merge with repeatable regions, the document should have mail merge regions // in the document designated with MERGEFIELD TableStart:MyTableName and TableEnd:MyTableName. Document doc = new Document(getMyDir() + "MailMerge.ExecuteWithRegions.doc"); final int orderId = 10444; // Populate tables and add them to the dataset. // For a mail merge with repeatable regions, DataTable.TableName should be // set to match the name of the region defined in the document. DataSet dataSet = new DataSet(); DataTable orderTable = getTestOrder(orderId); dataSet.getTables().add(orderTable); DataTable orderDetailsTable = getTestOrderDetails(orderId, "ProductID"); dataSet.getTables().add(orderDetailsTable); // This looks through all mail merge regions inside the document and for each // region tries to find a DataTable with a matching name inside the DataSet. // If a table is found, its content is merged into the mail merge region in the document. doc.getMailMerge().executeWithRegions(dataSet); doc.save(getArtifactsDir() + "MailMerge.ExecuteWithRegionsDataSet.doc"); //ExEnd } //ExStart //ExFor:Document.MailMerge //ExFor:MailMerge.ExecuteWithRegions(DataTable) //ExId:MailMergeRegions //ExSummary:Executes a mail merge with repeatable regions. @Test //ExSkip public void executeWithRegionsDataTable() throws Exception { Document doc = new Document(getMyDir() + "MailMerge.ExecuteWithRegions.doc"); final int orderId = 10444; // Perform several mail merge operations populating only part of the document each time. // Use DataTable as a data source. // The table name property should be set to match the name of the region defined in the document. DataTable orderTable = getTestOrder(orderId); doc.getMailMerge().executeWithRegions(orderTable); DataTable orderDetailsTable = getTestOrderDetails(orderId, "ExtendedPrice DESC"); doc.getMailMerge().executeWithRegions(orderDetailsTable); doc.save(getArtifactsDir() + "MailMerge.ExecuteWithRegionsDataTable.doc"); } private static DataTable getTestOrder(final int orderId) throws Exception { java.sql.ResultSet resultSet = executeDataTable(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", Integer.toString(orderId))); return new DataTable(resultSet, "Orders"); } private static DataTable getTestOrderDetails(final int orderId, final String orderBy) throws Exception { StringBuilder builder = new StringBuilder(); builder.append(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0}", Integer.toString(orderId))); if ((orderBy != null) && (orderBy.length() > 0)) { builder.append(" ORDER BY "); builder.append(orderBy); } java.sql.ResultSet resultSet = executeDataTable(builder.toString()); return new DataTable(resultSet, "OrderDetails"); } /** * Utility function that creates a connection, command, * executes the command and return the result in a DataTable. */ private static java.sql.ResultSet executeDataTable(final String commandText) throws Exception { // Loads the driver Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); // Open the database connection. String connString = "jdbc:ucanaccess://" + getDatabaseDir() + "Northwind.mdb"; // From Wikipedia: The Sun driver has a known issue with character encoding and Microsoft Access databases. // Microsoft Access may use an encoding that is not correctly translated by the driver, leading to the replacement // in strings of, for example, accented characters by question marks. // In this case I have to set CP1252 for the european characters to come through in the data values. java.util.Properties props = new java.util.Properties(); props.put("charSet", "Cp1252"); props.put("UID", "Admin"); // DSN-less DB connection. java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, props); // Create and execute a command. java.sql.Statement statement = conn.createStatement(); return statement.executeQuery(commandText); } //ExEnd @Test public void mappedDataFields() throws Exception { Document doc = new Document(); //ExStart //ExFor:MailMerge.MappedDataFields //ExFor:MappedDataFieldCollection //ExFor:MappedDataFieldCollection.Add //ExId:MailMergeMappedDataFields //ExSummary:Shows how to add a mapping when a merge field in a document and a data field in a data source have different names. doc.getMailMerge().getMappedDataFields().add("MyFieldName_InDocument", "MyFieldName_InDataSource"); //ExEnd } @Test public void trimWhiteSpaces() throws Exception { //ExStart //ExFor:MailMerge.TrimWhitespaces //ExSummary:Shows how to trimmed whitespaces from mail merge values. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.insertField("MERGEFIELD field", null); doc.getMailMerge().setTrimWhitespaces(true); doc.getMailMerge().execute(new String[]{"field"}, new Object[]{" first line\rsecond line\rthird line "}); Assert.assertEquals(doc.getText(), "first line\rsecond line\rthird line\f"); //ExEnd } @Test public void mailMergeGetFieldNames() throws Exception { Document doc = new Document(); //ExStart //ExFor:MailMerge.GetFieldNames //ExId:MailMergeGetFieldNames //ExSummary:Shows how to get names of all merge fields in a document. String[] fieldNames = doc.getMailMerge().getFieldNames(); //ExEnd } @Test public void deleteFields() throws Exception { Document doc = new Document(); //ExStart //ExFor:MailMerge.DeleteFields //ExId:MailMergeDeleteFields //ExSummary:Shows how to delete all merge fields from a document without executing mail merge. doc.getMailMerge().deleteFields(); //ExEnd } @Test public void removeContainingFields() throws Exception { Document doc = new Document(); //ExStart //ExFor:MailMerge.CleanupOptions //ExFor:MailMergeCleanupOptions //ExId:MailMergeRemoveContainingFields //ExSummary:Shows how to instruct the mail merge engine to remove any containing fields from around a merge field during mail merge. doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS); //ExEnd } @Test public void removeUnusedFields() throws Exception { Document doc = new Document(); //ExStart //ExFor:MailMerge.CleanupOptions //ExFor:MailMergeCleanupOptions //ExId:MailMergeRemoveUnusedFields //ExSummary:Shows how to automatically remove unmerged merge fields during mail merge. doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS); //ExEnd } @Test public void removeEmptyParagraphs() throws Exception { Document doc = new Document(); //ExStart //ExFor:MailMerge.CleanupOptions //ExFor:MailMergeCleanupOptions //ExId:MailMergeRemoveEmptyParagraphs //ExSummary:Shows how to make sure empty paragraphs that result from merging fields with no data are removed from the document. doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_PARAGRAPHS); //ExEnd } @Test(enabled = false, description = "WORDSNET-17733", dataProvider = "removeColonBetweenEmptyMergeFieldsDataProvider") public void removeColonBetweenEmptyMergeFields(final String punctuationMark, final boolean isCleanupParagraphsWithPunctuationMarks, final String resultText) throws Exception { //ExStart //ExFor:MailMerge.CleanupParagraphsWithPunctuationMarks //ExSummary:Shows how to remove paragraphs with punctuation marks after mail merge operation. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); FieldMergeField mergeFieldOption1 = (FieldMergeField) builder.insertField("MERGEFIELD", "Option_1"); mergeFieldOption1.setFieldName("Option_1"); // Here is the complete list of cleanable punctuation marks: builder.write(punctuationMark); FieldMergeField mergeFieldOption2 = (FieldMergeField) builder.insertField("MERGEFIELD", "Option_2"); mergeFieldOption2.setFieldName("Option_2"); doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_PARAGRAPHS); // The default value of the option is true which means that the behaviour was changed to mimic MS Word // If you rely on the old behavior are able to revert it by setting the option to false doc.getMailMerge().setCleanupParagraphsWithPunctuationMarks(isCleanupParagraphsWithPunctuationMarks); doc.getMailMerge().execute(new String[]{"Option_1", "Option_2"}, new Object[]{null, null}); doc.save(getArtifactsDir() + "RemoveColonBetweenEmptyMergeFields.docx"); //ExEnd Assert.assertEquals(doc.getText(), resultText); } //JAVA-added data provider for test method @DataProvider(name = "removeColonBetweenEmptyMergeFieldsDataProvider") public static Object[][] removeColonBetweenEmptyMergeFieldsDataProvider() { return new Object[][] { {"!", false, ""}, {", ", false, ""}, {" . ", false, ""}, {" :", false, ""}, {" ; ", false, ""}, {" ? ", false, ""}, {" ¡ ", false, ""}, {" ¿ ", false, ""}, {"!", true, "!\f"}, {", ", true, ", \f"}, {" . ", true, " . \f"}, {" :", true, " :\f"}, {" ; ", true, " ; \f"}, {" ? ", true, " ? \f"}, {" ¡ ", true, " ¡ \f"}, {" ¿ ", true, " ¿ \f"}, }; } @Test public void getFieldNames() throws Exception { //ExStart //ExFor:FieldAddressBlock //ExFor:FieldAddressBlock.GetFieldNames //ExSummary:Shows how to get mail merge field names used by the field Document doc = new Document(getMyDir() + "MailMerge.GetFieldNames.docx"); String[] addressFieldsExpect = {"Company", "First Name", "Middle Name", "Last Name", "Suffix", "Address 1", "City", "State", "Country or Region", "Postal Code"}; FieldAddressBlock addressBlockField = (FieldAddressBlock) doc.getRange().getFields().get(0); String[] addressBlockFieldNames = addressBlockField.getFieldNames(); //ExEnd Assert.assertEquals(addressBlockFieldNames, addressFieldsExpect); String[] greetingFieldsExpect = {"Courtesy Title", "Last Name"}; FieldGreetingLine greetingLineField = (FieldGreetingLine) doc.getRange().getFields().get(1); String[] greetingLineFieldNames = greetingLineField.getFieldNames(); Assert.assertEquals(greetingLineFieldNames, greetingFieldsExpect); } @Test public void useNonMergeFields() throws Exception { Document doc = new Document(); //ExStart //ExFor:MailMerge.UseNonMergeFields //ExSummary:Shows how to perform mail merge into merge fields and into additional fields types. doc.getMailMerge().setUseNonMergeFields(true); //ExEnd } @Test(dataProvider = "mustasheTemplateSyntaxDataProvider") public void mustasheTemplateSyntax(final boolean restoreTags, final String sectionText) throws Exception { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.write("{{ testfield1 }}"); builder.write("{{ testfield2 }}"); builder.write("{{ testfield3 }}"); doc.getMailMerge().setUseNonMergeFields(true); doc.getMailMerge().setPreserveUnusedTags(restoreTags); DataTable table = new DataTable("Test"); table.getColumns().add("testfield2"); table.getRows().add("value 1"); doc.getMailMerge().execute(table); String paraText = DocumentHelper.getParagraphText(doc, 0); Assert.assertEquals(sectionText, paraText); } //JAVA-added data provider for test method @DataProvider(name = "mustasheTemplateSyntaxDataProvider") public static Object[][] mustasheTemplateSyntaxDataProvider() { return new Object[][] { {true, "{{ testfield1 }}value 1{{ testfield3 }}\f"}, {false, "\u0013MERGEFIELD \"testfield1\"\u0014«testfield1»\u0015value 1\u0013MERGEFIELD \"testfield3\"\u0014«testfield3»\u0015\f"}, }; } @Test public void testMailMergeGetRegionsHierarchy() throws Exception { //ExStart //ExFor:MailMergeRegionInfo //ExFor:MailMerge.GetRegionsHierarchy //ExFor:MailMergeRegionInfo.Regions //ExFor:MailMergeRegionInfo.Name //ExFor:MailMergeRegionInfo.Fields //ExFor:MailMergeRegionInfo.StartField //ExFor:MailMergeRegionInfo.EndField //ExFor:MailMergeRegionInfo.Level //ExSummary:Shows how to get MailMergeRegionInfo and work with it Document doc = new Document(getMyDir() + "MailMerge.TestRegionsHierarchy.doc"); //Returns a full hierarchy of regions (with fields) available in the document. MailMergeRegionInfo regionInfo = doc.getMailMerge().getRegionsHierarchy(); //Get top regions in the document ArrayList topRegions = regionInfo.getRegions(); Assert.assertEquals(topRegions.size(), 2); Assert.assertEquals(((MailMergeRegionInfo) topRegions.get(0)).getName(), "Region1"); Assert.assertEquals(((MailMergeRegionInfo) topRegions.get(1)).getName(), "Region2"); Assert.assertEquals(((MailMergeRegionInfo) topRegions.get(0)).getLevel(), 1); Assert.assertEquals(((MailMergeRegionInfo) topRegions.get(1)).getLevel(), 1); //Get nested region in first top region ArrayList nestedRegions = ((MailMergeRegionInfo) topRegions.get(0)).getRegions(); Assert.assertEquals(nestedRegions.size(), 2); Assert.assertEquals(((MailMergeRegionInfo) nestedRegions.get(0)).getName(), "NestedRegion1"); Assert.assertEquals(((MailMergeRegionInfo) nestedRegions.get(1)).getName(), "NestedRegion2"); Assert.assertEquals(((MailMergeRegionInfo) nestedRegions.get(0)).getLevel(), 2); Assert.assertEquals(((MailMergeRegionInfo) nestedRegions.get(1)).getLevel(), 2); //Get field list in first top region ArrayList fieldList = ((MailMergeRegionInfo) topRegions.get(0)).getFields(); Assert.assertEquals(fieldList.size(), 4); FieldMergeField startFieldMergeField = ((MailMergeRegionInfo) nestedRegions.get(0)).getStartField(); Assert.assertEquals(startFieldMergeField.getFieldName(), "TableStart:NestedRegion1"); FieldMergeField endFieldMergeField = ((MailMergeRegionInfo) nestedRegions.get(0)).getEndField(); Assert.assertEquals(endFieldMergeField.getFieldName(), "TableEnd:NestedRegion1"); //ExEnd } @Test public void testTagsReplacedEventShouldRisedWithUseNonMergeFieldsOption() throws Exception { //ExStart //ExFor:MailMerge.MailMergeCallback //ExFor:IMailMergeCallback //ExFor:IMailMergeCallback.TagsReplaced //ExSummary:Shows how to define custom logic for handling events during mail merge. Document document = new Document(); document.getMailMerge().setUseNonMergeFields(true); MailMergeCallbackStub mailMergeCallbackStub = new MailMergeCallbackStub(); document.getMailMerge().setMailMergeCallback(mailMergeCallbackStub); document.getMailMerge().execute(new String[0], new Object[0]); Assert.assertEquals(mailMergeCallbackStub.getTagsReplacedCounter(), 1); } private static class MailMergeCallbackStub implements IMailMergeCallback { public void tagsReplaced() { mTagsReplacedCounter++; } public int getTagsReplacedCounter() { return mTagsReplacedCounter; } private int mTagsReplacedCounter; } //ExEnd @Test(dataProvider = "getRegionsByNameDataProvider") public void getRegionsByName(final String regionName) throws Exception { Document doc = new Document(getMyDir() + "MailMerge.RegionsByName.doc"); ArrayList<MailMergeRegionInfo> regions = doc.getMailMerge().getRegionsByName(regionName); Assert.assertEquals(regions.size(), 2); for (MailMergeRegionInfo region : regions) { Assert.assertEquals(region.getName(), regionName); } } //JAVA-added data provider for test method @DataProvider(name = "getRegionsByNameDataProvider") public static Object[][] getRegionsByNameDataProvider() { return new Object[][]{{"Region1"}, {"NestedRegion1"},}; } @Test public void cleanupOptions() throws Exception { Document doc = new Document(getMyDir() + "MailMerge.CleanUp.docx"); DataTable data = getDataTable(); doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS); doc.getMailMerge().executeWithRegions(data); doc.save(getArtifactsDir() + "MailMerge.CleanUp.docx"); Assert.assertTrue(DocumentHelper.compareDocs(getArtifactsDir() + "MailMerge.CleanUp.docx", getGoldsDir() + "MailMerge.CleanUp Gold.docx")); } /** * Create DataTable and fill it with data. * In real life this DataTable should be filled from a database. */ private static DataTable getDataTable() { DataTable dataTable = new DataTable("StudentCourse"); dataTable.getColumns().add("CourseName"); DataRow dataRowEmpty = dataTable.newRow(); dataTable.getRows().add(dataRowEmpty); dataRowEmpty.set(0, ""); for (int i = 0; i < 10; i++) { DataRow datarow = dataTable.newRow(); dataTable.getRows().add(datarow); datarow.set(0, "Course " + Integer.toString(i)); } return dataTable; } @Test public void unconditionalMergeFieldsAndRegions() throws Exception { //ExStart //ExFor:MailMerge.UnconditionalMergeFieldsAndRegions //ExSummary:Shows how to merge fields or regions regardless of the parent IF field's condition. Document doc = new Document(getMyDir() + "MailMerge.UnconditionalMergeFieldsAndRegions.docx"); // Merge fields and merge regions are merged regardless of the parent IF field's condition. doc.getMailMerge().setUnconditionalMergeFieldsAndRegions(true); // Fill the fields in the document with user data. doc.getMailMerge().execute( new String[]{"FullName"}, new Object[]{"James Bond"}); doc.save(getArtifactsDir() + "MailMerge.UnconditionalMergeFieldsAndRegions.docx"); //ExEnd } }
package org.exist.xquery.modules.mail; import org.exist.dom.QName; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Variable; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.Type; import org.exist.xquery.functions.util.ExistVersion; //send-email specific imports import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.Socket; import java.util.Collection; import java.util.Date; import java.util.Properties; import java.util.Vector; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import org.w3c.dom.Node; /** * @author Adam Retter (adam.retter@devon.gov.uk) */ public class SendEmail extends BasicFunction { //TODO: Feature - Add an option to execute the function Asynchronously as Socket operations for SMTP can be slow (Sendmail seems fast enough). Will require placing the SMTP code in a thread. //TODO: Feature - Add a facility for the user to add their own message headers. //TODO: Feature - Add attachment support, will need base64 encoding etc... //TODO: Read the location of sendmail from the configuration file. Can vary from system to system public final static FunctionSignature signature = new FunctionSignature( new QName("send-email", MailModule.NAMESPACE_URI, MailModule.PREFIX), "Sends an email $a through the SMTP Server $b, or if $b is () tries to use the local sendmail program. $a is the email in the following format <mail><from/><to/><cc/><bcc/><subject/><message><text/><xhtml/></message></mail>. $c defines the charset value used in the \"Content-Type\" message header (Defaults to UTF-8)", new SequenceType[] { new SequenceType(Type.NODE, Cardinality.EXACTLY_ONE), new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE), new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE) }, new SequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE)); /** * @param context * @param signature */ public SendEmail(XQueryContext context) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try { //Parse the XML <mail> into a mail Object mail theMail = ParseMailXML( ((NodeValue)args[0].itemAt(0)).getNode() ); //Send email with Sendmail or SMTP? if(args[1].getLength() > 0) { //SMTP if(SendSMTP(theMail, args[1].getStringValue(), args[2].getStringValue())) { return(BooleanValue.TRUE); } } else { //Sendmail if(SendSendmail(theMail, args[2].getStringValue())) { return(BooleanValue.TRUE); } } //Failed to send email return(BooleanValue.FALSE); } catch(TransformerException e) { throw new XPathException("Could not Transform XHTML Message Body: " + e.getMessage(), e); } } //Sends an email using the system's sendmail binary private boolean SendSendmail(mail aMail, String ContentType_Charset) { try { //Create a vector of all Recipients, should include to, cc and bcc recipient Vector allrecipients = new Vector(); allrecipients.addAll(aMail.getTo()); allrecipients.addAll(aMail.getCC()); allrecipients.addAll(aMail.getBCC()); //Get a string of all recipients email addresses String recipients = ""; for(int x = 0; x < allrecipients.size(); x++) { //Check format of to address does it include a name as well as the email address? if(((String)allrecipients.elementAt(x)).indexOf("<") != -1) { //yes, just add the email address recipients += " " + ((String)allrecipients.elementAt(x)).substring(((String)allrecipients.elementAt(x)).indexOf("<") + 1, ((String)allrecipients.elementAt(x)).indexOf(">")); } else { //add the email address recipients += " " + ((String)allrecipients.elementAt(x)); } } //Create a sendmail Process Process p = Runtime.getRuntime().exec("/usr/sbin/sendmail" + recipients); //Get a Buffered Print Writer to the Processes stdOut PrintWriter out = new PrintWriter(p.getOutputStream()); //Send the Message WriteMessage(out, aMail, ContentType_Charset); //Close the stdOut out.close(); } catch(IOException e) { return(false); } //Message Sent Succesfully LOG.info("send-email() message sent using Sendmail " + new Date()); return(true); } //Sends an email using an SMTP Server private boolean SendSMTP(mail aMail, String SMTPServer, String ContentType_Charset) { final int TCP_PROTOCOL_SMTP = 25; //SMTP Protocol String SMTPResult = ""; //Holds the server Result code when an SMTP Command is executed try { //Create a Socket and connect to the SMTP Server Socket smtpSock = new Socket(SMTPServer, TCP_PROTOCOL_SMTP); //Create a Buffered Reader for the Socket BufferedReader in = new BufferedReader(new InputStreamReader(smtpSock.getInputStream())); //Create an Output Writer for the Socket PrintWriter out = new PrintWriter(new OutputStreamWriter(smtpSock.getOutputStream())); //First line sent to us from the SMTP server should be "220 blah blah", 220 indicates okay SMTPResult = in.readLine(); if(!SMTPResult.substring(0, 3).toString().equals("220")) { LOG.error("Error - SMTP Server not ready!"); return(false); } //Say "HELO" out.println("HELO " + InetAddress.getLocalHost().getHostName()); out.flush(); //get "HELLO" response, should be "250 blah blah" SMTPResult = in.readLine(); if(!SMTPResult.substring(0, 3).toString().equals("250")) { LOG.error("Error - SMTP HELO Failed: " + SMTPResult); return(false); } //Send "MAIL FROM:" //Check format of from address does it include a name as well as the email address? if(aMail.getFrom().indexOf("<") != -1) { //yes, just send the email address out.println("MAIL FROM: " + aMail.getFrom().substring(aMail.getFrom().indexOf("<") + 1, aMail.getFrom().indexOf(">"))); } else { //no, doesnt include a name so send the email address out.println("MAIL FROM: " + aMail.getFrom()); } out.flush(); //Get "MAIL FROM:" response SMTPResult = in.readLine(); if(!SMTPResult.substring(0, 3).toString().equals("250")) { LOG.error("Error - SMTP MAIL FROM failed: " + SMTPResult); return(false); } //RCPT TO should be issued for each to, cc and bcc recipient Vector allrecipients = new Vector(); allrecipients.addAll(aMail.getTo()); allrecipients.addAll(aMail.getCC()); allrecipients.addAll(aMail.getBCC()); for(int x = 0; x < allrecipients.size(); x++) { //Send "RCPT TO:" //Check format of to address does it include a name as well as the email address? if(((String)allrecipients.elementAt(x)).indexOf("<") != -1) { //yes, just send the email address out.println("RCPT TO: " + ((String)allrecipients.elementAt(x)).substring(((String)allrecipients.elementAt(x)).indexOf("<") + 1, ((String)allrecipients.elementAt(x)).indexOf(">"))); } else { out.println("RCPT TO: " + ((String)allrecipients.elementAt(x))); } out.flush(); //Get "RCPT TO:" response SMTPResult = in.readLine(); if(!SMTPResult.substring(0, 3).toString().equals("250")) { LOG.error("Error - SMTP RCPT TO failed: " + SMTPResult); } } //SEND "DATA" out.println("DATA"); out.flush(); //Get "DATA" response, should be "354 blah blah" SMTPResult = in.readLine(); if(!SMTPResult.substring(0, 3).toString().equals("354")) { LOG.error("Error - SMTP DATA failed: " + SMTPResult); return(false); } //Send the Message WriteMessage(out, aMail, ContentType_Charset); //Get end message response, should be "250 blah blah" SMTPResult = in.readLine(); if(!SMTPResult.substring(0, 3).toString().equals("250")) { LOG.error("Error - Message not accepted: " + SMTPResult); return(false); } } catch(IOException e) { return(false); } //Message Sent Succesfully LOG.info("send-email() message sent using SMTP " + new Date()); return(true); } //Writes an email payload (Headers + Body) from a mail object private void WriteMessage(PrintWriter out, mail aMail, String ContentType_Charset) throws IOException { String Version = eXistVersion(); //Version of eXist String MultipartBoundary = "eXist.multipart." + Version; //Multipart Boundary //write the message headers out.println("From: " + aMail.getFrom()); for(int x = 0; x < aMail.countTo(); x++) { out.println("To: " + aMail.getTo(x)); } for(int x = 0; x < aMail.countCC(); x++) { out.println("CC: " + aMail.getCC(x)); } for(int x = 0; x < aMail.countBCC(); x++) { out.println("BCC: " + aMail.getBCC(x)); } out.println("Date: " + new Date()); out.println("Subject: " + aMail.getSubject()); out.println("X-Mailer: eXist " + Version + " util:send-email()"); out.println("MIME-Version: 1.0"); //Is this a multipart message i.e. text and html? if((!aMail.getText().toString().equals("")) && (!aMail.getXHTML().toString().equals(""))) { //Yes, start multipart message out.println("Content-Type: multipart/alternative; boundary=\"" + MultipartBoundary + "\";"); //Mime warning out.println("Error your mail client is not MIME Compatible"); //send the text part first out.println("--" + MultipartBoundary); if(ContentType_Charset == "") { out.println("Content-Type: text/plain; charset=UTF-8"); } else { out.println("Content-Type: text/plain; charset=" + ContentType_Charset); } out.println("Content-Transfer-Encoding: quoted-printable"); out.println(aMail.getText()); //send the html part next out.println("--" + MultipartBoundary); if(ContentType_Charset == "") { out.println("Content-Type: text/plain; charset=UTF-8"); } else { out.println("Content-Type: text/plain; charset=" + ContentType_Charset); } out.println("Content-Transfer-Encoding: quoted-printable"); out.println(aMail.getXHTML()); //Emd multipart message out.println("--" + MultipartBoundary + "--"); } else { //No, is it a text email if(!aMail.getText().toString().equals("")) { //Yes, text email if(ContentType_Charset == "") { out.println("Content-Type: text/plain; charset=UTF-8"); } else { out.println("Content-Type: text/plain; charset=" + ContentType_Charset); } out.println("Content-Transfer-Encoding: quoted-printable"); //now send the trxt message out.println(); out.println(aMail.getText()); } else { //No, HTML email if(ContentType_Charset == "") { out.println("Content-Type: text/plain; charset=UTF-8"); } else { out.println("Content-Type: text/plain; charset=" + ContentType_Charset); } out.println("Content-Transfer-Encoding: quoted-printable"); //now send the html message out.println(); out.println(aMail.getXHTML()); } } //end the message, <cr><lf>.<cr><lf> out.println(); out.println("."); out.println(); out.flush(); } //Gets the eXist Version Number private String eXistVersion() throws IOException { Properties sysProperties = new Properties(); sysProperties.load(ExistVersion.class.getClassLoader().getResourceAsStream("org/exist/system.properties")); return((String)sysProperties.getProperty("product-version", "unknown version")); } //Constructs a mail object from an XML representation private mail ParseMailXML(Node message) throws TransformerException { //Expects message to be in the format - /* * <mail> * <from></from> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text></text> * <xhtml></xhtml> * </message> * </mail> * */ //New mail Object mail theMail = new mail(); //Make sure that message has a Mail node if(message.getNodeType() == Node.ELEMENT_NODE && message.getLocalName().equals("mail")) { //Get the First Child Node child = message.getFirstChild(); while(child != null) { //Parse each of the child nodes if(child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { if(child.getLocalName().equals("from")) { theMail.setFrom(child.getFirstChild().getNodeValue()); } else if(child.getLocalName().equals("to")) { theMail.addTo(child.getFirstChild().getNodeValue()); } else if(child.getLocalName().equals("cc")) { theMail.addCC(child.getFirstChild().getNodeValue()); } else if(child.getLocalName().equals("bcc")) { theMail.addBCC(child.getFirstChild().getNodeValue()); } else if(child.getLocalName().equals("subject")) { theMail.setSubject(child.getFirstChild().getNodeValue()); } else if(child.getLocalName().equals("message")) { //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while(bodyPart != null) { if(bodyPart.getLocalName().equals("text")) { theMail.setText(bodyPart.getFirstChild().getNodeValue()); } else if(bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); theMail.setXHTML(strWriter.toString()); } //next body part bodyPart = bodyPart.getNextSibling(); } } } //next node child = child.getNextSibling(); } } //Return the mail object return(theMail); } //Class that Represents an email private class mail { private String from = ""; //Who is the mail from private Vector to = new Vector(); //Who is the mail going to private Vector cc = new Vector(); //Carbon Copy to private Vector bcc = new Vector(); //Blind Carbon Copy to private String subject = ""; //Subject of the mail private String text = ""; //Body text of the mail private String xhtml = ""; //Body XHTML of the mail //From public void setFrom(String from) { this.from = from; } public String getFrom() { return(this.from); } public void addTo(String to) { this.to.addElement(to); } public int countTo() { return(to.size()); } public String getTo(int index) { return((String)to.elementAt(index)); } public Collection getTo() { return(to); } public void addCC(String cc) { this.cc.addElement(cc); } public int countCC() { return(cc.size()); } public String getCC(int index) { return((String)cc.elementAt(index)); } public Collection getCC() { return(cc); } //BCC public void addBCC(String bcc) { this.bcc.addElement(bcc); } public int countBCC() { return(bcc.size()); } public String getBCC(int index) { return((String)bcc.elementAt(index)); } public Collection getBCC() { return(bcc); } //Subject public void setSubject(String subject) { this.subject = subject; } public String getSubject() { return(subject); } //text public void setText(String text) { this.text = text; } public String getText() { return(text); } //xhtml public void setXHTML(String xhtml) { this.xhtml = xhtml; } public String getXHTML() { return(xhtml); } } }
package be.ibridge.kettle.job.entry.trans; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.cluster.SlaveServer; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleJobException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.logging.Log4jFileAppender; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.vfs.KettleVFS; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.JobEntryBase; import be.ibridge.kettle.job.entry.JobEntryDialogInterface; import be.ibridge.kettle.job.entry.JobEntryInterface; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.repository.RepositoryDirectory; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransExecutionConfiguration; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.cluster.TransSplitter; import be.ibridge.kettle.www.SlaveServerTransStatus; import be.ibridge.kettle.www.WebResult; /** * This is the job entry that defines a transformation to be run. * * @author Matt * @since 1-10-2003, rewritten on 18-06-2004 * */ public class JobEntryTrans extends JobEntryBase implements Cloneable, JobEntryInterface { private String transname; private String filename; private RepositoryDirectory directory; public String arguments[]; public boolean argFromPrevious; public boolean execPerRow; public boolean clearResultRows; public boolean clearResultFiles; public boolean setLogfile; public String logfile, logext; public boolean addDate, addTime; public int loglevel; private String directoryPath; private boolean clustering; public JobEntryTrans(String name) { super(name, ""); setType(JobEntryInterface.TYPE_JOBENTRY_TRANSFORMATION); } public JobEntryTrans() { this(""); clear(); } public Object clone() { JobEntryTrans je = (JobEntryTrans) super.clone(); return je; } public JobEntryTrans(JobEntryBase jeb) { super(jeb); } public void setFileName(String n) { filename=n; } /** * @deprecated use getFilename() instead * @return the filename */ public String getFileName() { return filename; } public String getFilename() { return filename; } public String getRealFilename() { return StringUtil.environmentSubstitute(getFilename()); } public void setTransname(String transname) { this.transname=transname; } public String getTransname() { return transname; } public RepositoryDirectory getDirectory() { return directory; } public void setDirectory(RepositoryDirectory directory) { this.directory = directory; } public String getLogFilename() { String retval=""; if (setLogfile) { retval+=logfile; Calendar cal = Calendar.getInstance(); if (addDate) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); retval+="_"+sdf.format(cal.getTime()); } if (addTime) { SimpleDateFormat sdf = new SimpleDateFormat("HHmmss"); retval+="_"+sdf.format(cal.getTime()); } if (logext!=null && logext.length()>0) { retval+="."+logext; } } return retval; } public String getXML() { StringBuffer retval = new StringBuffer(300); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("filename", filename)); retval.append(" ").append(XMLHandler.addTagValue("transname", transname)); if (directory!=null) { retval.append(" ").append(XMLHandler.addTagValue("directory", directory.getPath())); } else if (directoryPath!=null) { retval.append(" ").append(XMLHandler.addTagValue("directory", directoryPath)); // don't loose this info (backup/recovery) } retval.append(" ").append(XMLHandler.addTagValue("arg_from_previous", argFromPrevious)); retval.append(" ").append(XMLHandler.addTagValue("exec_per_row", execPerRow)); retval.append(" ").append(XMLHandler.addTagValue("clear_rows", clearResultRows)); retval.append(" ").append(XMLHandler.addTagValue("clear_files", clearResultFiles)); retval.append(" ").append(XMLHandler.addTagValue("set_logfile", setLogfile)); retval.append(" ").append(XMLHandler.addTagValue("logfile", logfile)); retval.append(" ").append(XMLHandler.addTagValue("logext", logext)); retval.append(" ").append(XMLHandler.addTagValue("add_date", addDate)); retval.append(" ").append(XMLHandler.addTagValue("add_time", addTime)); retval.append(" ").append(XMLHandler.addTagValue("loglevel", LogWriter.getLogLevelDesc(loglevel))); retval.append(" ").append(XMLHandler.addTagValue("cluster", clustering)); if (arguments!=null) for (int i=0;i<arguments.length;i++) { retval.append(" ").append(XMLHandler.addTagValue("argument"+i, arguments[i])); } return retval.toString(); } public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases); filename = XMLHandler.getTagValue(entrynode, "filename") ; transname = XMLHandler.getTagValue(entrynode, "transname") ; directoryPath = XMLHandler.getTagValue(entrynode, "directory"); if (rep!=null) // import from XML into a repository for example... (or copy/paste) { directory = rep.getDirectoryTree().findDirectory(directoryPath); } argFromPrevious = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "arg_from_previous") ); execPerRow = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "exec_per_row") ); clearResultRows = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "clear_rows") ); clearResultFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "clear_files") ); setLogfile = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "set_logfile") ); addDate = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_date") ); addTime = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "add_time") ); logfile = XMLHandler.getTagValue(entrynode, "logfile"); logext = XMLHandler.getTagValue(entrynode, "logext"); loglevel = LogWriter.getLogLevel( XMLHandler.getTagValue(entrynode, "loglevel")); clustering = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "cluster") ); // How many arguments? int argnr = 0; while ( XMLHandler.getTagValue(entrynode, "argument"+argnr)!=null) argnr++; arguments = new String[argnr]; // Read them all... for (int a=0;a<argnr;a++) arguments[a]=XMLHandler.getTagValue(entrynode, "argument"+a); } catch(KettleException e) { throw new KettleXMLException("Unable to load job entry of type 'trans' from XML node", e); } } // Load the jobentry from repository public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException { try { super.loadRep(rep, id_jobentry, databases); transname = rep.getJobEntryAttributeString(id_jobentry, "name"); String dirPath = rep.getJobEntryAttributeString(id_jobentry, "dir_path"); directory = rep.getDirectoryTree().findDirectory(dirPath); filename = rep.getJobEntryAttributeString(id_jobentry, "file_name"); argFromPrevious = rep.getJobEntryAttributeBoolean(id_jobentry, "arg_from_previous"); execPerRow = rep.getJobEntryAttributeBoolean(id_jobentry, "exec_per_row"); clearResultRows = rep.getJobEntryAttributeBoolean(id_jobentry, "clear_rows", true); clearResultFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "clear_files", true); setLogfile = rep.getJobEntryAttributeBoolean(id_jobentry, "set_logfile"); addDate = rep.getJobEntryAttributeBoolean(id_jobentry, "add_date"); addTime = rep.getJobEntryAttributeBoolean(id_jobentry, "add_time"); logfile = rep.getJobEntryAttributeString(id_jobentry, "logfile"); logext = rep.getJobEntryAttributeString(id_jobentry, "logext"); loglevel = LogWriter.getLogLevel( rep.getJobEntryAttributeString(id_jobentry, "loglevel") ); clustering = rep.getJobEntryAttributeBoolean(id_jobentry, "cluster"); // How many arguments? int argnr = rep.countNrJobEntryAttributes(id_jobentry, "argument"); arguments = new String[argnr]; // Read them all... for (int a=0;a<argnr;a++) { arguments[a]= rep.getJobEntryAttributeString(id_jobentry, a, "argument"); } } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to load job entry of type 'trans' from the repository for id_jobentry="+id_jobentry, dbe); } } // Save the attributes of this job entry public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); long id_transformation = rep.getTransformationID(transname, directory.getID()); rep.saveJobEntryAttribute(id_job, getID(), "id_transformation", id_transformation); rep.saveJobEntryAttribute(id_job, getID(), "name", getTransname()); rep.saveJobEntryAttribute(id_job, getID(), "dir_path", getDirectory()!=null?getDirectory().getPath():""); rep.saveJobEntryAttribute(id_job, getID(), "file_name", filename); rep.saveJobEntryAttribute(id_job, getID(), "arg_from_previous", argFromPrevious); rep.saveJobEntryAttribute(id_job, getID(), "exec_per_row", execPerRow); rep.saveJobEntryAttribute(id_job, getID(), "clear_rows", clearResultRows); rep.saveJobEntryAttribute(id_job, getID(), "clear_files", clearResultFiles); rep.saveJobEntryAttribute(id_job, getID(), "set_logfile", setLogfile); rep.saveJobEntryAttribute(id_job, getID(), "add_date", addDate); rep.saveJobEntryAttribute(id_job, getID(), "add_time", addTime); rep.saveJobEntryAttribute(id_job, getID(), "logfile", logfile); rep.saveJobEntryAttribute(id_job, getID(), "logext", logext); rep.saveJobEntryAttribute(id_job, getID(), "loglevel", LogWriter.getLogLevelDesc(loglevel)); rep.saveJobEntryAttribute(id_job, getID(), "cluster", clustering); // save the arguments... if (arguments!=null) { for (int i=0;i<arguments.length;i++) { rep.saveJobEntryAttribute(id_job, getID(), i, "argument", arguments[i]); } } } catch(KettleDatabaseException dbe) { throw new KettleException("Unable to save job entry of type 'trans' to the repository for id_job="+id_job, dbe); } } public void clear() { super.clear(); transname=null; filename=null; directory = new RepositoryDirectory(); arguments=null; argFromPrevious=false; execPerRow=false; addDate=false; addTime=false; logfile=null; logext=null; setLogfile=false; clearResultRows=true; clearResultFiles=true; } /** * Execute this job entry and return the result. * In this case it means, just set the result boolean in the Result class. * @param result The result of the previous execution * @param nr the job entry number * @param rep the repository connection to use * @param parentJob the parent job * @return The Result of the execution. */ public Result execute(Result result, int nr, Repository rep, Job parentJob) throws KettleException { LogWriter log = LogWriter.getInstance(); result.setEntryNr( nr ); LogWriter logwriter = log; Log4jFileAppender appender = null; int backupLogLevel = log.getLogLevel(); if (setLogfile) { try { appender = LogWriter.createFileAppender(StringUtil.environmentSubstitute(getLogFilename()), true); } catch(KettleException e) { log.logError(toString(), "Unable to open file appender for file ["+getLogFilename()+"] : "+e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); result.setResult(false); return result; } log.addAppender(appender); log.setLogLevel(loglevel); } // Open the transformation... // Default directory for now... log.logBasic(toString(), "Opening filename : ["+StringUtil.environmentSubstitute(getFilename())+"]"); if (!Const.isEmpty(getFilename())) { log.logBasic(toString(), "Opening transformation: ["+StringUtil.environmentSubstitute(getFilename())+"]"); } else { log.logBasic(toString(), "Opening transformation: ["+StringUtil.environmentSubstitute(getTransname())+"] in directory ["+directory.getPath()+"]"); } // Load the transformation only once for the complete loop! TransMeta transMeta = getTransMeta(rep); int iteration = 0; String args[] = arguments; if (args==null || args.length==0) // No arguments set, look at the parent job. { args = parentJob.getJobMeta().getArguments(); } Row resultRow = null; boolean first = true; List rows = result.getRows(); while( ( first && !execPerRow ) || ( execPerRow && rows!=null && iteration<rows.size() && result.getNrErrors()==0 ) && !parentJob.isStopped() ) { first=false; if (rows!=null && execPerRow) { resultRow = (Row) rows.get(iteration); } else { resultRow = null; } try { log.logDetailed(toString(), "Starting transformation...(file="+getFilename()+", name="+getName()+"), repinfo="+getDescription()); // Set the result rows for the next one... transMeta.setPreviousResult(result); if (clearResultRows) { transMeta.getPreviousResult().setRows(new ArrayList()); } if (clearResultFiles) { transMeta.getPreviousResult().getResultFiles().clear(); } /* * Set one or more "result" rows on the transformation... */ if (execPerRow) // Execute for each input row { if (argFromPrevious) // Copy the input row to the (command line) arguments { args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).getString(); } } } else { // Just pass a single row ArrayList newList = new ArrayList(); newList.add(resultRow); // This previous result rows list can be either empty or not. // Depending on the checkbox "clear result rows" // In this case, it would execute the transformation with one extra row each time // Can't figure out a real use-case for it, but hey, who am I to decide that, right? transMeta.getPreviousResult().getRows().addAll(newList); } } else { if (argFromPrevious) { // Only put the first Row on the arguments args = null; if (resultRow!=null) { args = new String[resultRow.size()]; for (int i=0;i<resultRow.size();i++) { args[i] = resultRow.getValue(i).toString(); } } } else { args = parentJob.getJobMeta().getArguments(); } } if (clustering) { TransExecutionConfiguration executionConfiguration = new TransExecutionConfiguration(); executionConfiguration.setClusterPosting(true); executionConfiguration.setClusterPreparing(true); executionConfiguration.setClusterStarting(true); executionConfiguration.setClusterShowingTransformation(false); executionConfiguration.setSafeModeEnabled(false); TransSplitter transSplitter = Trans.executeClustered(transMeta, executionConfiguration ); // See if the remote transformations have finished. // We could just look at the master, but I doubt that that is enough in all situations. SlaveServer[] slaveServers = transSplitter.getSlaveTargets(); // <-- ask these guys TransMeta[] slaves = transSplitter.getSlaves(); SlaveServer masterServer = transSplitter.getMasterServer(); // <-- AND this one TransMeta master = transSplitter.getMaster(); boolean allFinished = false; long errors = 0L; while (!allFinished && !parentJob.isStopped() && errors==0) { allFinished = true; errors=0L; // Slaves first... for (int s=0;s<slaveServers.length && allFinished && errors==0;s++) { try { SlaveServerTransStatus transStatus = slaveServers[s].getTransStatus(slaves[s].getName()); if (transStatus.isRunning()) allFinished = false; errors+=transStatus.getNrStepErrors(); } catch(Exception e) { errors+=1; log.logError(toString(), "Unable to contact slave server '"+slaveServers[s].getName()+"' to check slave transformation : "+e.toString()); } } // Check the master too if (allFinished && errors==0) { try { SlaveServerTransStatus transStatus = masterServer.getTransStatus(master.getName()); if (transStatus.isRunning()) allFinished = false; errors+=transStatus.getNrStepErrors(); } catch(Exception e) { errors+=1; log.logError(toString(), "Unable to contact slave server '"+masterServer.getName()+"' to check master transformation : "+e.toString()); } } if (parentJob.isStopped() || errors != 0) { // Stop all slaves and the master on the slave servers for (int s=0;s<slaveServers.length && allFinished && errors==0;s++) { try { WebResult webResult = slaveServers[s].stopTransformation(slaves[s].getName()); if (!WebResult.STRING_OK.equals(webResult.getResult())) { log.logError(toString(), "Unable to stop slave transformation '"+slaves[s].getName()+"' : "+webResult.getMessage()); } } catch(Exception e) { errors+=1; log.logError(toString(), "Unable to contact slave server '"+slaveServers[s].getName()+"' to stop transformation : "+e.toString()); } } try { WebResult webResult = masterServer.stopTransformation(master.getName()); if (!WebResult.STRING_OK.equals(webResult.getResult())) { log.logError(toString(), "Unable to stop master transformation '"+masterServer.getName()+"' : "+webResult.getMessage()); } } catch(Exception e) { errors+=1; log.logError(toString(), "Unable to contact master server '"+masterServer.getName()+"' to stop the master : "+e.toString()); } } // Keep waiting until all transformations have finished // If needed, we stop them again and again until they yield. if (!allFinished) { // Not finished or error: wait a bit longer log.logDetailed(toString(), "Clustered transformation is still running, waiting 10 seconds..."); try { Thread.sleep(10000); } catch(Exception e) {} // Check all slaves every 10 seconds. TODO: add 10s as parameter } } result.setNrErrors(errors); } else // Local execution... { // Create the transformation from meta-data Trans trans = new Trans(logwriter, transMeta); if (parentJob.getJobMeta().isBatchIdPassed()) { trans.setPassedBatchId(parentJob.getPassedBatchId()); } // set the parent job on the transformation, variables are taken from here... trans.setParentJob(parentJob); // Execute! if (!trans.execute(args)) { log.logError(toString(), "Unable to prepare for execution of the transformation"); result.setNrErrors(1); } else { while (!trans.isFinished() && !parentJob.isStopped() && trans.getErrors() == 0) { try { Thread.sleep(100);} catch(InterruptedException e) { } } if (parentJob.isStopped() || trans.getErrors() != 0) { trans.stopAll(); trans.waitUntilFinished(); trans.endProcessing("stop"); result.setNrErrors(1); } else { trans.endProcessing("end"); } Result newResult = trans.getResult(); result.clear(); // clear only the numbers, NOT the files or rows. result.add(newResult); // Set the result rows too... result.setRows(newResult.getRows()); if (setLogfile) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, KettleVFS.getFileObject(getLogFilename()), parentJob.getName(), toString()); result.getResultFiles().put(resultFile.getFile().toString(), resultFile); } } } } catch(Exception e) { log.logError(toString(), "Unable to open transformation: "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } iteration++; } if (setLogfile) { if (appender!=null) { log.removeAppender(appender); appender.close(); } log.setLogLevel(backupLogLevel); } if (result.getNrErrors()==0) { result.setResult( true ); } else { result.setResult( false ); } return result; } private TransMeta getTransMeta(Repository rep) throws KettleException { LogWriter log = LogWriter.getInstance(); TransMeta transMeta = null; if (!Const.isEmpty(getFilename())) // Load from an XML file { log.logBasic(toString(), "Loading transformation from XML file ["+StringUtil.environmentSubstitute(getFilename())+"]"); transMeta = new TransMeta(StringUtil.environmentSubstitute(getFilename())); } else if (!Const.isEmpty(getTransname()) && getDirectory() != null) // Load from the repository { log.logBasic(toString(), "Loading transformation from repository ["+StringUtil.environmentSubstitute(getTransname())+"] in directory ["+getDirectory()+"]"); if ( rep != null ) { // It only makes sense to try to load from the repository when the repository is also filled in. transMeta = new TransMeta(rep, StringUtil.environmentSubstitute(getTransname()), getDirectory()); } else { throw new KettleException("No repository defined!"); } } else { throw new KettleJobException("The transformation to execute is not specified!"); } // Set the arguments... transMeta.setArguments(arguments); return transMeta; } public boolean evaluates() { return true; } public boolean isUnconditional() { return true; } public ArrayList getSQLStatements(Repository repository) throws KettleException { TransMeta transMeta = getTransMeta(repository); return transMeta.getSQLStatements(); } /** * @return Returns the directoryPath. */ public String getDirectoryPath() { return directoryPath; } /** * @param directoryPath The directoryPath to set. */ public void setDirectoryPath(String directoryPath) { this.directoryPath = directoryPath; } public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) { return new JobEntryTransDialog(shell,this,rep); } /** * @return the clustering */ public boolean isClustering() { return clustering; } /** * @param clustering the clustering to set */ public void setClustering(boolean clustering) { this.clustering = clustering; } }
package be.ugent.oomo.groep12.studgent.view; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.location.Location; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import be.ugent.oomo.groep12.studgent.activity.POIDetailActivity; import be.ugent.oomo.groep12.studgent.common.PointOfInterest; import be.ugent.oomo.groep12.studgent.utilities.LocationUtil; import com.google.android.gms.maps.model.LatLng; public class OverlayView extends FrameLayout implements OnClickListener { private int screenWidth; private int screenHeight; private static int fov = 80; private Location devLoc; private ArrayList<POIView> pois; public OverlayView(Context context) { super(context); init(context); } public OverlayView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public OverlayView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { screenWidth = context.getResources().getDisplayMetrics().widthPixels; screenHeight = context.getResources().getDisplayMetrics().heightPixels; // Set device location as static, for now devLoc = LocationUtil.getLocationFromLatLng(new LatLng(50.848602, 3.175140)); // Add some dummy data pois = new ArrayList<POIView>(); POIView t = new POIView(context, new PointOfInterest(10, "Noorden", "", new LatLng(179, 0))); pois.add(t); t = new POIView(context, new PointOfInterest(10, "Delta Lights", "", new LatLng(50.844924, 3.176591))); pois.add(t); for (POIView v : pois) { this.addView(v); // Make view clickable v.setOnClickListener(this); v.setClickable(true); } } public void updateOverlay(int az) { for (POIView v : pois) { float bearing = devLoc.bearingTo(LocationUtil .getLocationFromLatLng(v.getPoi().getLocation())); float t = ((az - bearing) + 180) % 360 - 180; if (t > fov) { // Do not draw, because poi is outside fov v.setVisibility(View.INVISIBLE); } else { float offset = ((az - bearing) + 180) % 360 - 180; offset = (offset / fov) * screenWidth; v.setTranslationX(-offset); // Hackish way to force visibility with a SurfaceView beneath // this view v.setVisibility(View.VISIBLE); v.requestLayout(); } } } @Override public void onClick(View v) { if (((POIView) v).getPoi() != null) { Intent intent = new Intent(getContext(), POIDetailActivity.class); intent.putExtra("poi", ((POIView) v).getPoi()); getContext().startActivity(intent); } } }
package businesslogic.promotionbl; import java.rmi.RemoteException; import java.util.ArrayList; import po.CategoryPO; import po.CommodityLineItemPO; import po.SpecialOfferPO; import util.ResultMessage; import vo.CategoryVO; import vo.CommodityLineItemVO; import vo.CommodityVO; import vo.SaleVO; import vo.SpecialOfferVO; import businesslogic.commoditybl.Category; import businesslogic.commoditybl.Commodity; import businesslogic.utilitybl.Utility; import dataservice.datafactoryservice.DataFactoryImpl; public class SpecialOfferPromotion { public String createId() { ArrayList<SpecialOfferVO> voList = show(); if (voList.size() == 0) { return "SPO-00000"; } else { String max = voList.get(voList.size() - 1).id; String oldMax = max.substring(max.length() - 5); int maxInt = Integer.parseInt(oldMax); String pattern = "00000"; java.text.DecimalFormat df = new java.text.DecimalFormat(pattern); String maxStr = df.format(maxInt + 1); return "SPO-" + maxStr; } } public ResultMessage add(SpecialOfferVO vo) { SpecialOfferPO po = voToPO(vo); String commodityId = vo.id; String commodityName = null; for (CommodityLineItemVO vo1 : vo.commodityList) { commodityName += vo1.name + "x" + vo1.number + " "; } if (!Utility.checkTime(vo.startTime, vo.endTime)) { return ResultMessage.TIME_ERROR; } try { DataFactoryImpl.getInstance().getSpecialOfferData().insert(po); } catch (RemoteException e) { e.printStackTrace(); } Category cat = new Category(); CategoryPO pocheck=cat.getById("99999"); if(pocheck==null){ CategoryVO catvo=new CategoryVO("99999", "", 0, null); cat.add(catvo); } CategoryVO catvo = cat.CategoryPOToCategoryVO(cat.getById("99999")); CommodityVO commodityvo = new CommodityVO("99999-" + commodityId, commodityName, "nothing", 0, 0, vo.total, 0, 0, 0, false, catvo); new Commodity().add(commodityvo); return ResultMessage.SUCCESS; } public ResultMessage update(SpecialOfferVO vo) { SpecialOfferPO po = voToPO(vo); if (!Utility.checkTime(vo.startTime, vo.endTime)) { return ResultMessage.TIME_ERROR; } try { DataFactoryImpl.getInstance().getSpecialOfferData().update(po); } catch (RemoteException e) { e.printStackTrace(); } return ResultMessage.SUCCESS; } public ArrayList<SpecialOfferVO> show() { ArrayList<SpecialOfferPO> poList = null; try { poList = DataFactoryImpl.getInstance().getSpecialOfferData().show(); } catch (RemoteException e) { e.printStackTrace(); } ArrayList<SpecialOfferVO> voList = new ArrayList<SpecialOfferVO>(); for (SpecialOfferPO po : poList) { if (!po.isValid()) { continue; } if (Utility.inTime(po.getStartTime(), po.getEndTime())) { continue; } SpecialOfferVO vo = poToVo(po); voList.add(vo); } return voList; } public ArrayList<SpecialOfferVO> showAll() { ArrayList<SpecialOfferPO> poList = null; try { poList = DataFactoryImpl.getInstance().getSpecialOfferData().show(); } catch (RemoteException e) { e.printStackTrace(); } ArrayList<SpecialOfferVO> voList = new ArrayList<SpecialOfferVO>(); for (SpecialOfferPO po : poList) { SpecialOfferVO vo = poToVo(po); voList.add(vo); } return voList; } public SpecialOfferVO getById(String id){ ArrayList<SpecialOfferVO> voList=showAll(); for(SpecialOfferVO vo:voList){ if(vo.id.equals(id)){ return vo; } } return null; } public SaleVO calBonus(SaleVO saleVO, SpecialOfferVO specialOfferVO) { int validnumber = 0; for (CommodityLineItemVO voCheck : specialOfferVO.commodityList) { for (CommodityLineItemVO voBuy : saleVO.saleList) { if (voBuy.id.equals(voCheck.id) && voBuy.number >= voCheck.number) { validnumber++; } } } if (validnumber != specialOfferVO.commodityList.size()) { saleVO.remark += ""; } // TODO return saleVO; } private SpecialOfferPO voToPO(SpecialOfferVO vo) { String id=vo.id; ArrayList<CommodityLineItemPO> giftInfo = Utility .voListToPOList(vo.commodityList); double total = vo.total; String startTime = vo.startTime; String endTime = vo.endTime; boolean valid = vo.valid; SpecialOfferPO po = new SpecialOfferPO(id, giftInfo, total, startTime, endTime, valid); return po; } private SpecialOfferVO poToVo(SpecialOfferPO po) { String id = po.getId(); ArrayList<CommodityLineItemVO> giftInfo = Utility.poListToVOList(po .getCommodityList()); double total = po.getTotal(); String startTime = po.getStartTime(); String endTime = po.getEndTime(); boolean valid = po.isValid(); SpecialOfferVO vo = new SpecialOfferVO(id, giftInfo, total, startTime, endTime, valid); return vo; } }
package com.foundationdb.blob; import com.foundationdb.*; import com.foundationdb.async.*; import com.foundationdb.subspace.Subspace; import com.foundationdb.tuple.Tuple2; public class SQLBlob extends BlobAsync { public SQLBlob(Subspace subspace){ super (subspace); } public Future<Void> setLinkedTable(TransactionContext tcx, final int tableId) { return tcx.runAsync(new Function<Transaction, Future<Void>>() { @Override public Future<Void> apply(Transaction tr) { tr.set(attributeKey(), Tuple2.from((long)tableId).pack()); return new ReadyFuture<>((Void) null); } }); } public Future<Integer> getLinkedTable(TransactionContext tcx) { return tcx.runAsync(new Function<Transaction, Future<Integer>>() { @Override public Future<Integer> apply(Transaction tr) { return tr.get(attributeKey()).map(new Function<byte[], Integer>() { @Override public Integer apply(byte[] tableIdBytes) { if(tableIdBytes == null) { return null; } int tableId = (int)Tuple2.fromBytes(tableIdBytes).getLong(0); return Integer.valueOf(tableId); } }); } }); } public Future<Boolean> isLinked(TransactionContext tcx) { return tcx.runAsync(new Function<Transaction, Future<Boolean>>() { @Override public Future<Boolean> apply(Transaction tr) { return tr.get(attributeKey()).map(new Function<byte[], Boolean>() { @Override public Boolean apply(byte[] tableIdBytes) { if(tableIdBytes == null) { return false; } return true; } }); } }); } }
package edu.umd.cs.findbugs.props; import java.util.HashMap; import java.util.Map; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.FindBugsAnalysisFeatures; /** * A Set of WarningProperty objects, each with an optional attribute Object. A * WarningPropertySet is useful for collecting heuristics to use in the * determination of whether or not a warning is a false positive, or what the * warning's priority should be. * * @author David Hovemeyer */ public class WarningPropertySet<T extends WarningProperty> implements Cloneable { private Map<T, Object> map; @Override public String toString() { StringBuffer buf = new StringBuffer("{ "); for (Map.Entry<T, Object> entry : map.entrySet()) { WarningProperty prop = entry.getKey(); Object attribute = entry.getValue(); buf.append(" "); buf.append(prop.getPriorityAdjustment()); buf.append("\t"); buf.append(prop.getName()); buf.append("\t"); buf.append(attribute); buf.append("\n"); } buf.append("}\n"); return buf.toString(); } /** * Constructor Creates empty object. */ public WarningPropertySet() { this.map = new HashMap<T, Object>(); } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } /** * Add a warning property to the set. The warning implicitly has the boolean * value "true" as its attribute. * * @param prop * the WarningProperty * @return this object */ public WarningPropertySet<T> addProperty(T prop) { map.put(prop, Boolean.TRUE); return this; } /** * Remove a warning property from the set. * * @param prop * the WarningProperty * @return this object */ public WarningPropertySet<T> removeProperty(T prop) { map.remove(prop); return this; } /** * Add a warning property and its attribute value. * * @param prop * the WarningProperty * @param value * the attribute value * @return this object */ public WarningPropertySet<T> setProperty(T prop, String value) { map.put(prop, value); return this; } /** * Add a warning property and its attribute value. * * @param prop * the WarningProperty * @param value * the attribute value */ public void setProperty(T prop, Boolean value) { map.put(prop, value); } /** * Return whether or not the set contains the given WarningProperty. * * @param prop * the WarningProperty * @return true if the set contains the WarningProperty, false if not */ public boolean containsProperty(T prop) { return map.keySet().contains(prop); } /** * Check whether or not the given WarningProperty has the given attribute * value. * * @param prop * the WarningProperty * @param value * the attribute value * @return true if the set contains the WarningProperty and has an attribute * equal to the one given, false otherwise */ public boolean checkProperty(T prop, Object value) { Object attribute = getProperty(prop); return (attribute != null && attribute.equals(value)); } /** * Get the value of the attribute for the given WarningProperty. Returns * null if the set does not contain the WarningProperty. * * @param prop * the WarningProperty * @return the WarningProperty's attribute value, or null if the set does * not contain the WarningProperty */ public Object getProperty(T prop) { return map.get(prop); } /** * Use the PriorityAdjustments specified by the set's WarningProperty * elements to compute a warning priority from the given base priority. * * @param basePriority * the base priority * @return the computed warning priority */ public int computePriority(int basePriority) { boolean relaxedReporting = FindBugsAnalysisFeatures.isRelaxedMode(); boolean atLeastMedium = false; boolean falsePositive = false; boolean atMostLow = false; boolean atMostMedium = false; int aLittleBitLower = 0; int priority = basePriority; if (!relaxedReporting) { for (T warningProperty : map.keySet()) { PriorityAdjustment adj = warningProperty.getPriorityAdjustment(); if (adj == PriorityAdjustment.FALSE_POSITIVE) { falsePositive = true; atMostLow = true; } else if (adj == PriorityAdjustment.A_LITTLE_BIT_LOWER_PRIORITY) aLittleBitLower++; else if (adj == PriorityAdjustment.A_LITTLE_BIT_HIGHER_PRIORITY) aLittleBitLower else if (adj == PriorityAdjustment.RAISE_PRIORITY) --priority; else if (adj == PriorityAdjustment.RAISE_PRIORITY_TO_AT_LEAST_NORMAL) { --priority; atLeastMedium = true; } else if (adj == PriorityAdjustment.RAISE_PRIORITY_TO_HIGH) { return Detector.HIGH_PRIORITY; } else if (adj == PriorityAdjustment.LOWER_PRIORITY) { ++priority; } else if (adj == PriorityAdjustment.AT_MOST_LOW) { priority++; atMostLow = true; } else if (adj == PriorityAdjustment.AT_MOST_MEDIUM) { atMostMedium = true; } else if (adj == PriorityAdjustment.NO_ADJUSTMENT) { assert true; // do nothing } else throw new IllegalStateException("Unknown priority " + adj); } if (aLittleBitLower >= 3 || priority == 1 && aLittleBitLower == 2) priority++; else if (aLittleBitLower <= -2) priority if (atMostMedium) priority = Math.max(Detector.NORMAL_PRIORITY, priority); if (falsePositive && !atLeastMedium) return Detector.EXP_PRIORITY + 1; else if (atMostLow) return Math.min(Math.max(Detector.LOW_PRIORITY, priority), Detector.EXP_PRIORITY); if (atLeastMedium && priority > Detector.NORMAL_PRIORITY) priority = Detector.NORMAL_PRIORITY; if (priority < Detector.HIGH_PRIORITY) priority = Detector.HIGH_PRIORITY; else if (priority > Detector.EXP_PRIORITY) priority = Detector.EXP_PRIORITY; } return priority; } /** * Determine whether or not a warning with given priority is expected to be * a false positive. * * @param priority * the priority * @return true if the warning is expected to be a false positive, false if * not */ public boolean isFalsePositive(int priority) { return priority > Detector.EXP_PRIORITY; } /** * Decorate given BugInstance with properties. * * @param bugInstance * the BugInstance */ public void decorateBugInstance(BugInstance bugInstance) { for (Map.Entry<T, Object> entry : map.entrySet()) { WarningProperty prop = entry.getKey(); Object attribute = entry.getValue(); if (attribute == null) attribute = ""; bugInstance.setProperty(prop.getName(), attribute.toString()); } } }
package com.linxiao.framework.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import com.linxiao.framework.R; /** * * <p>,,8dp * 8dp, * ,>5,,99,99+, * setTargetView(),javaView</p> * <p> * <br> * badge_color: <br> * badge_default_size: <br> * badge_hideOnZero: 0 <br> * badge_ellipsisDigit: <br> * badge_numberEllipsis: 99+ <br> * </p> * * Create on 2015-11-03 * @author linxiao * @version 1.0 */ public class BadgeView extends TextView { private static final String TAG = BadgeView.class.getSimpleName(); private int minPaddingHorizontal = dip2Px(4); private int minPaddingVertical = dip2Px(1); private int badgeColor = Color.RED; private float radius; private int defaultSize = dip2Px(8); private boolean hideOnZero = false; private String ellipsis = "99+"; private int ellipsisDigit = 2; private int extraPaddingHorizontal; private int extraPaddingVertical; private FrameLayout badgeContainer; //padding private int cachePaddingLeft; private int cachePaddingTop; private int cachePaddingRight; private int cachePaddingBottom; private int strokeWidth = 0; private int strokeColor = 0; public BadgeView(Context context) { super(context); init(context, null); setLayoutParams(new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) ); setTextSize(12); } public BadgeView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public BadgeView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { if (attrs != null) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BadgeView); badgeColor = typedArray.getColor(R.styleable.BadgeView_badge_color, badgeColor); defaultSize = typedArray.getDimensionPixelSize(R.styleable.BadgeView_badge_defaultSize, dip2Px(8)); hideOnZero = typedArray.getBoolean(R.styleable.BadgeView_badge_hideOnZero, false); ellipsis = typedArray.getString(R.styleable.BadgeView_badge_numberEllipsis); ellipsisDigit = typedArray.getInt(R.styleable.BadgeView_badge_ellipsisDigit, 2); typedArray.recycle(); } if (TextUtils.isEmpty(ellipsis)) { countEllipsisString(); } //setText if (!TextUtils.isEmpty(getText())) { setText(getText()); } setTextColor(Color.WHITE); setGravity(Gravity.CENTER); } private void countEllipsisString() { ellipsis = ""; for (int i = 0; i < ellipsisDigit; i++) { ellipsis += "9"; } ellipsis += "+"; } /** * 0 * * @param hideOnZero * */ public void setHideOnZero(boolean hideOnZero) { this.hideOnZero = hideOnZero; setText(getText()); } public void setDefaultBadgeSize(int defaultSize) { this.defaultSize = defaultSize; requestLayout(); } public void setNumber(int i) { setText(String.valueOf(i)); } /** * , 99"99+",5 */ @Override public void setText(CharSequence text, BufferType type) { if (ellipsisDigit == 0) { // TextViewsetText super.setText(text, type); return; } if (text == null) { return; } if (text.toString().matches("^\\d+$")) { int number = Integer.parseInt(text.toString()); if (number == 0 && hideOnZero) { hide(); } else { show(); } if (text.length() > ellipsisDigit) { text = ellipsis; } } else if (text.length() > 5) { text = text.subSequence(0, 4) + "..."; } super.setText(text, type); requestLayout(); } public void setBadgeStroke(int width, int color) { strokeWidth = width; strokeColor = color; setBadgeBackground(); } private void setBadgeBackground() { GradientDrawable defaultBgDrawable = new GradientDrawable(); defaultBgDrawable.setCornerRadius(radius); defaultBgDrawable.setColor(badgeColor); if (strokeWidth != 0 && strokeColor != 0) { defaultBgDrawable.setStroke(strokeWidth, strokeColor); } super.setBackgroundDrawable(defaultBgDrawable); } public void show() { this.setVisibility(View.VISIBLE); } public void hide() { this.setVisibility(View.GONE); } /** * * @param target * @param badgeGravity * @param marginLeft * @param marginTop * @param marginRight * @param marginBottom * */ public void setTargetView(View target, int badgeGravity, int marginLeft, int marginRight, int marginTop, int marginBottom) { if (getParent() != null) { ((ViewGroup) getParent()).removeView(this); } if (target == null) { return; } if (target.getParent() instanceof ViewGroup) { ViewGroup parentContainer = (ViewGroup) target.getParent(); if (parentContainer.equals(badgeContainer)) { //setTargetView; FrameLayout.LayoutParams badgeLayoutParam = (FrameLayout.LayoutParams) this.getLayoutParams(); badgeLayoutParam.gravity = badgeGravity; badgeLayoutParam.setMargins(marginLeft, marginTop, marginRight, marginBottom); return; } // ViewsetTargetView, FrameLayout if (badgeContainer != null && badgeContainer.getChildCount() > 0) { View lastTarget = badgeContainer.getChildAt(0); if (lastTarget != null) { ViewGroup lastParent = (ViewGroup) badgeContainer.getParent(); ViewGroup.LayoutParams lastLayoutParams = badgeContainer.getLayoutParams(); badgeContainer.removeView(lastTarget); lastParent.removeView(badgeContainer); lastTarget.setLayoutParams(lastLayoutParams); lastParent.addView(lastTarget); } } int groupIndex = parentContainer.indexOfChild(target); parentContainer.removeView(target); badgeContainer = new FrameLayout(getContext()); ViewGroup.LayoutParams parentLayoutParams = target.getLayoutParams(); badgeContainer.setLayoutParams(parentLayoutParams); target.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); parentContainer.addView(badgeContainer, groupIndex, parentLayoutParams); badgeContainer.addView(target); badgeContainer.addView(this); FrameLayout.LayoutParams badgeLayoutParam = (FrameLayout.LayoutParams) this.getLayoutParams(); badgeLayoutParam.gravity = badgeGravity; badgeLayoutParam.setMargins(marginLeft, marginTop, marginRight, marginBottom); } else if (target.getParent() == null) { Log.e(getClass().getSimpleName(), "ParentView is needed"); } } /** * margin 0 * * @param target * */ public void setTargetView(View target) { setTargetView(target, Gravity.END, 0, 0, 0, 0); } /** * margin 0 * * @param target * @param badgeGravity * */ public void setTargetView(View target, int badgeGravity) { setTargetView(target, badgeGravity, 0, 0, 0, 0); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int textLength = this.getText().length(); if (textLength <= 0) { setMeasuredDimension(defaultSize, defaultSize); return; } int mode = MeasureSpec.getMode(widthMeasureSpec); if (mode != MeasureSpec.EXACTLY) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); execSetPadding(); if (textLength == 1) { int textWidth = (int)getPaint().measureText(getText().toString()); int pLeft = getPaddingLeft(); int pRight = getPaddingRight(); int horSize = textWidth + pLeft + pRight + extraPaddingHorizontal * 2; Log.d(TAG, "onMeasure: textWidth = " + textWidth); Log.d(TAG, "onMeasure: pLeft = " + pLeft); Log.d(TAG, "onMeasure: pRight = " + pRight); Log.d(TAG, "onMeasure: extraHor = " + extraPaddingHorizontal); setMeasuredDimension(horSize, horSize); return; } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); radius = bottom - top; setBadgeBackground(); } @Override public void setPadding(int left, int top, int right, int bottom) { cachePaddingLeft = left; cachePaddingTop = top; cachePaddingRight = right; cachePaddingBottom = bottom; execSetPadding(); } private void execSetPadding() { if (ellipsisDigit == 0) { // TextViewsetText super.setPadding(cachePaddingLeft, cachePaddingTop, cachePaddingRight, cachePaddingBottom); return; } int textLength = 0; if (this.getText() != null) { textLength = this.getText().length(); } if (textLength == 0) { super.setPadding(cachePaddingLeft, cachePaddingTop, cachePaddingRight, cachePaddingBottom); return; } int padding = Math.max( Math.max(cachePaddingLeft, cachePaddingRight), Math.max(cachePaddingTop, cachePaddingBottom)); if (textLength == 1) { // , /padding, extraPaddingHorizontal = getExtraPaddingHorizontal(); extraPaddingVertical = getExtraPaddingVertical(); super.setPadding( padding + extraPaddingHorizontal, padding + extraPaddingVertical, padding + extraPaddingHorizontal, padding + extraPaddingVertical ); return; } super.setPadding( minPaddingHorizontal + padding, minPaddingVertical + padding, minPaddingHorizontal + padding, minPaddingVertical + padding ); } @Override public int getPaddingLeft() { if (super.getPaddingLeft() == 0) { return 0; } int textLength = this.getText().length(); if (textLength == 0) { return 0; } if (textLength == 1) { return super.getPaddingLeft() - extraPaddingHorizontal; } if (textLength > 1) { return super.getPaddingLeft() - minPaddingHorizontal; } return super.getPaddingLeft(); } @Override public int getPaddingRight() { if (super.getPaddingRight() == 0) { return 0; } int textLength = this.getText().length(); if (textLength == 0) { return 0; } if (textLength == 1) { return super.getPaddingRight() - extraPaddingHorizontal; } if (textLength > 1) { return super.getPaddingRight() - minPaddingHorizontal; } return super.getPaddingRight(); } @Override public int getPaddingTop() { if (super.getPaddingTop() == 0) { return 0; } int textLength = this.getText().length(); if (textLength == 0) { return 0; } if (textLength == 1) { return super.getPaddingTop() - extraPaddingVertical; } if (textLength > 1) { return super.getPaddingTop() - minPaddingVertical; } return super.getPaddingTop(); } @Override public int getPaddingBottom() { if (super.getPaddingBottom() == 0) { return 0; } int textLength = this.getText().length(); if (textLength == 0) { return 0; } if (textLength == 1) { return super.getPaddingBottom() - extraPaddingVertical; } if (textLength > 1) { return super.getPaddingBottom() - minPaddingVertical; } return super.getPaddingBottom(); } private int getExtraPaddingHorizontal() { if (this.getText().length() != 1) { return 0 ; } int textWidth = (int) (getPaint().measureText(getText().toString())); Paint.FontMetrics fm = getPaint().getFontMetrics(); int textHeight = (int) (Math.ceil(fm.descent - fm.top) + 2); if (textHeight <= textWidth) { return 0; } return (textHeight + getCompoundPaddingBottom() + getCompoundPaddingTop() - textWidth) / 2; } private int getExtraPaddingVertical() { if (this.getText().length() != 1) { return 0 ; } int textWidth = (int) (getPaint().measureText(getText().toString())); Paint.FontMetrics fm = getPaint().getFontMetrics(); int textHeight = (int) (Math.ceil(fm.descent - fm.top) + 2); if (textWidth <= textHeight) { return 0; } return (textWidth + getCompoundPaddingLeft() + getCompoundPaddingRight() - textHeight) / 2; } @Override public void setBackground(Drawable background) { setBadgeBackground(); } @Override public void setBackgroundColor(int color) { badgeColor = color; setBadgeBackground(); } @Override public void setBackgroundDrawable(Drawable background) { setBadgeBackground(); } @Override public void setBackgroundResource(int resid) { setBadgeBackground(); } private int dip2Px(float dip) { return (int) (dip * getResources().getDisplayMetrics().density + 0.5f); } }
package continuum.slab; import continuum.Continuum; import continuum.atom.AtomID; import continuum.atom.Particles; import continuum.core.slab.RockSlab; import continuum.core.io.file.FileSystemReference; import continuum.core.slab.AtomTranslator; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static continuum.Continuum.particles; import static org.junit.Assert.assertEquals; public class IteratorTest { FileSystemReference reference = new FileSystemReference("/tmp/continuum/test.IteratorTest"); @Test public void testIterate() throws Exception { reference.delete(); Slab slab = new RockSlab("testIterate.0.slab", reference); slab.open(); String name = "testIterate"; Map<String, String> map = new HashMap<>(); map.put("foo", "bar"); map.put("baz", "bat"); Map<String, String> map2 = new HashMap<>(); map2.put("zack", "bar"); map2.put("fuz", "da'vinci"); reference.child(name).delete(); AtomTranslator translator = new AtomTranslator(Continuum.Dimension.SPACE, slab); long ts1 = System.currentTimeMillis(); long ts2 = ts1 + 100; translator.write( Continuum.satom().name("testiterate") .particles(particles(map)) .value(123456.3D) .timestamp(ts1) .build() ); translator.write( Continuum.satom().name("testiterate") .particles(particles(map2)) .value(12341.01234D) .timestamp(ts2) .build() ); Iterator itr = translator.iterator(); int i = 0; itr.seekToFirst(); do { AtomID id = itr.ID(); if (i == 0) { assertEquals("testiterate", id.name()); assertEquals("bar", id.particles().get("foo")); assertEquals("bat", id.particles().get("baz")); assertEquals(123456.3D, itr.values().value(), 0.0001); } else if (i == 1) { assertEquals("testiterate", id.name()); Particles particles = id.particles(); assertEquals("da'vinci", particles.get("fuz")); assertEquals("bar", particles.get("zack")); assertEquals(12341.01234, itr.values().value(), 0.0001); } i++; } while (itr.next()); itr.close(); slab.close(); slab.reference().delete(); assertEquals(2, i); } }
package codeOrchestra.colt.as.compiler.fcsh; import codeOrchestra.colt.as.compiler.fcsh.console.command.CommandCallback; import codeOrchestra.colt.as.compiler.fcsh.console.command.FCSHCommandExecuteThread; import codeOrchestra.colt.as.compiler.fcsh.console.command.FCSHCommandRunnable; import codeOrchestra.colt.as.compiler.fcsh.console.command.impl.*; import codeOrchestra.colt.as.compiler.fcsh.make.CompilationResult; import codeOrchestra.colt.as.compiler.fcsh.target.CompilerTarget; import codeOrchestra.colt.core.license.DemoHelper; import codeOrchestra.colt.core.logging.Logger; import codeOrchestra.lcs.license.COLTRunningKey; import codeOrchestra.util.StringUtils; import codeOrchestra.util.SystemInfo; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Alexander Eliseyev */ public class FCSHManager { private static FCSHManager instance = new FCSHManager(); public static FCSHManager instance() { return instance; } public static final Logger LOG = Logger.getLogger("fcsh"); private static final int FCSH_INIT_CHECK_INTERVAL = 100; public static final long FCSH_INIT_TIMEOUT = 3000; private FCSHProcessHandler fcshProcessHandler; private final Map<List<String>, CompilerTarget> compilerTargets = Collections.synchronizedMap(new HashMap<List<String>, CompilerTarget>()); public void restart() throws FCSHException, MaximumCompilationsCountReachedException { if (DemoHelper.get().maxCompilationsCountReached()) { COLTRunningKey.setRunning(false); throw new MaximumCompilationsCountReachedException(); } else { COLTRunningKey.setRunning(true); } destroyProcess(); assureFCSHIsActive(); } public void destroyProcess() { try { if (fcshProcessHandler != null && !fcshProcessHandler.isProcessTerminated()) { fcshProcessHandler.destroyProcess(); } } catch (Throwable t) { // ignore } } public CompilerTarget registerCompileTarget(List<String> arguments, int id) { synchronized (compilerTargets) { CompilerTarget compilerTarget = compilerTargets.get(arguments); if (compilerTarget == null) { compilerTarget = new CompilerTarget(id); compilerTargets.put(arguments, compilerTarget); } return compilerTarget; } } public CompilationResult compile(CompilerTarget target) throws FCSHException, MaximumCompilationsCountReachedException { incrementCompilationCount(); assureFCSHIsActive(); CompileTargetCommand compileCommand = new CompileTargetCommand(this, target); LOG.info("Compiling the target #" + target.getId()); submitCommand(compileCommand); return compileCommand.getCompileResult(); } private void assureFCSHIsActive() throws FCSHException { if (fcshProcessHandler != null && !fcshProcessHandler.isProcessTerminated()) { // No need to reactivate, the process is still running return; } clearTargets(); IFCSHLauncher fcshLauncher; ProcessBuilder processBuilder; if (FCSHLauncher.NATIVE_FCSH && SystemInfo.isWindows) { fcshLauncher = new FCSHNativeLauncher(); } else { fcshLauncher = new FCSHLauncher(); } processBuilder = fcshLauncher.createProcessBuilder(); Process fcshProcess; try { fcshLauncher.runBeforeStart(); fcshProcess = processBuilder.start(); } catch (IOException e) { throw new FCSHException("Error while trying to start the fcsh process", e); } String commandString = StringUtils.join(processBuilder.command(), ", "); LOG.info(commandString); fcshProcessHandler = new FCSHProcessHandler(fcshProcess, commandString); fcshProcessHandler.startNotify(); // Give fcsh some time to start up long timeout = FCSH_INIT_TIMEOUT; while (!fcshProcessHandler.isInitialized()) { if (timeout < 0) { return; } try { Thread.sleep(FCSH_INIT_CHECK_INTERVAL); timeout -= FCSH_INIT_CHECK_INTERVAL; } catch (InterruptedException e) { // ignore } } } public void submitCommand(CommandCallback commandCallback) throws FCSHException { assureFCSHIsActive(); FCSHCommandRunnable fcshCommandRunnable = new FCSHCommandRunnable(this, commandCallback); if (commandCallback.isSynchronous()) { fcshCommandRunnable.run(); } else { new FCSHCommandExecuteThread(fcshCommandRunnable).start(); } } public void clear() throws FCSHException { assureFCSHIsActive(); submitCommand(new ClearCommand()); } public CompilationResult baseMXMLC(List<String> arguments) throws FCSHException, MaximumCompilationsCountReachedException { incrementCompilationCount(); assureFCSHIsActive(); LivecodingBaseMXMLCCommand mxmlcCommand = new LivecodingBaseMXMLCCommand(arguments); LOG.info("Compiling: " + mxmlcCommand.getCommand()); submitCommand(mxmlcCommand); return mxmlcCommand.getCompileResult(); } public CompilationResult baseCOMPC(List<String> arguments) throws FCSHException { assureFCSHIsActive(); LivecodingBaseCOMPCCommand compcCommand = new LivecodingBaseCOMPCCommand(arguments); LOG.info("Compiling: " + compcCommand.getCommand()); submitCommand(compcCommand); return compcCommand.getCompileResult(); } public CompilationResult incrementalCOMPC(List<String> arguments) throws FCSHException, MaximumCompilationsCountReachedException { incrementCompilationCount(); assureFCSHIsActive(); LivecodingIncrementalCOMPCCommand compcCommand = new LivecodingIncrementalCOMPCCommand(arguments); LOG.info("Compiling: " + compcCommand.getCommand()); submitCommand(compcCommand); return compcCommand.getCompileResult(); } public CompilationResult compc(List<String> commandArguments) throws FCSHException, MaximumCompilationsCountReachedException { incrementCompilationCount(); assureFCSHIsActive(); synchronized (compilerTargets) { CompilerTarget compilerTarget = compilerTargets.get(commandArguments); if (compilerTarget != null) { return compile(compilerTarget); } } COMPCCommand compcCommand = new COMPCCommand(commandArguments); LOG.info("Compiling: " + compcCommand.getCommand()); submitCommand(compcCommand); return compcCommand.getCompileResult(); } public CompilationResult mxmlc(List<String> commandArguments) throws FCSHException, MaximumCompilationsCountReachedException { incrementCompilationCount(); assureFCSHIsActive(); synchronized (compilerTargets) { CompilerTarget compilerTarget = compilerTargets.get(commandArguments); if (compilerTarget != null) { return compile(compilerTarget); } } MXMLCCommand mxmlcCommand = new MXMLCCommand(commandArguments); LOG.info("Compiling: " + mxmlcCommand.getCommand()); submitCommand(mxmlcCommand); return mxmlcCommand.getCompileResult(); } private void incrementCompilationCount() throws MaximumCompilationsCountReachedException { if (DemoHelper.get().maxCompilationsCountReached()) { COLTRunningKey.setRunning(false); throw new MaximumCompilationsCountReachedException(); } else { COLTRunningKey.setRunning(true); } DemoHelper.get().incrementCompilationsCount(); } public void deleteLivecodingCaches() throws FCSHException { assureFCSHIsActive(); LivecodingCachesDeleteCommand deleteCachesCommand = new LivecodingCachesDeleteCommand(); submitCommand(deleteCachesCommand); } public void startCPUProfiling() throws FCSHException { if (!FCSHLauncher.PROFILING_ON) { return; } assureFCSHIsActive(); submitCommand(new CPUProfilingStartCommand()); } public void stopCPUProfiling() throws FCSHException { if (!FCSHLauncher.PROFILING_ON) { return; } assureFCSHIsActive(); submitCommand(new CPUProfilingStopCommand()); } public void clearTargets() { this.compilerTargets.clear(); } public FCSHProcessHandler getProcessHandler() { return fcshProcessHandler; } }
package org.spine3.test; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.reflect.Invokable; import com.google.common.reflect.Parameter; import com.google.common.reflect.TypeToken; import com.google.protobuf.Any; import com.google.protobuf.Message; import org.spine3.util.Exceptions; import javax.annotation.Nullable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.Set; import static com.google.common.base.Defaults.defaultValue; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.primitives.Primitives.allPrimitiveTypes; import static com.google.common.primitives.Primitives.isWrapperType; import static com.google.common.primitives.Primitives.unwrap; import static java.util.Collections.unmodifiableMap; import static java.util.Collections.unmodifiableSet; import static javax.lang.model.SourceVersion.isName; /** * Serves as a helper to ensure that none of the methods of the target utility * class accept {@code null}s as argument values. * * <p>The helper checks the methods with access modifiers: * <ul> * <li>the {@code public}; * <li>the {@code protected}; * <li>the {@code default}. * </ul> * * <p>The helper does not check the methods: * <ul> * <li>with the {@code private} modifier; * <li>without the {@code static} modifier; * <li>with only the primitive parameters; * <li>if all the parameters are marked as {@code Nullable}. * </ul> * * <p>The examples of the methods which will be checked: * <ul> * <li>public static void method(Object obj); * <li>protected static void method(Object first, long second); * <li>public static void method(@Nullable Object first, Object second); * <li>static void method(Object first, Object second). * </ul> * * <p>The examples of the methods which will be ignored: * <ul> * <li>public void method(Object obj); * <li>private static void method(Object obj); * <li>public static void method(@Nullable Object obj); * <li>protected static void method(int first, float second). * </ul> * * @author Illia Shepilov */ public class NullToleranceTest { private final Class targetClass; private final Set<String> excludedMethods; private final Map<Class<?>, ?> defaultValues; private NullToleranceTest(Builder builder) { this.targetClass = builder.targetClass; this.excludedMethods = builder.excludedMethods; this.defaultValues = builder.defaultValues; } /** * Checks the all non-private methods in the {@code targetClass}. * * <p>The check is successful if each of the non-primitive method parameters is ensured to be non-null. * * @return {@code true} if the check is successful, {@code false} otherwise */ public boolean check() { final DefaultValueProvider valuesProvider = new DefaultValueProvider(defaultValues); final Iterable<Method> accessibleMethods = getAccessibleMethods(targetClass); final String targetClassName = targetClass.getName(); for (Method method : accessibleMethods) { final Class[] parameterTypes = method.getParameterTypes(); final String methodName = method.getName(); final boolean excluded = excludedMethods.contains(methodName); final boolean primitivesOnly = allPrimitiveTypes().containsAll(Arrays.asList(parameterTypes)); final boolean skipMethod = excluded || parameterTypes.length == 0 || primitivesOnly; if (skipMethod) { continue; } final MethodChecker methodChecker = new MethodChecker(method, targetClassName, valuesProvider); final boolean passed = methodChecker.check(); if (!passed) { return false; } } return true; } /** * Returns the {@code Iterable} over all the declared {@code Method}s * in the {@code Class} which are static and non-private. * * @param targetClass the target class * @return the array of the {@code Method} */ private static Iterable<Method> getAccessibleMethods(Class targetClass) { final Method[] declaredMethods = targetClass.getDeclaredMethods(); final ImmutableList.Builder<Method> listBuilder = ImmutableList.builder(); for (Method method : declaredMethods) { final Invokable<?, Object> invokable = Invokable.from(method); final boolean privateMethod = invokable.isPrivate(); final boolean staticMethod = invokable.isStatic(); if (!privateMethod && staticMethod) { listBuilder.add(method); } } final ImmutableList<Method> result = listBuilder.build(); return result; } /** * Creates a new builder for the {@code NullToleranceTest}. * * @return the {@code Builder} */ public static Builder newBuilder() { return new Builder(); } @VisibleForTesting Class getTargetClass() { return targetClass; } @VisibleForTesting Set<String> getExcludedMethods() { return unmodifiableSet(excludedMethods); } @VisibleForTesting Map<?, ?> getDefaultValues() { return unmodifiableMap(defaultValues); } /** * Serves as a helper to ensure that the method does not accept {@code null}s as argument values. */ private static class MethodChecker { /** * The method to test. */ private final Method method; /** * The name of the {@code Class} instance, which the tested method belongs to. */ private final String targetClassName; /** * The pre-configured provider of the default values per type. */ private final DefaultValueProvider valuesProvider; private MethodChecker(Method method, String targetClassName, DefaultValueProvider valuesProvider) { this.method = method; this.targetClassName = targetClassName; this.valuesProvider = valuesProvider; } private boolean check() { final boolean nullableOnly = hasOnlyNullableArgs(); if (nullableOnly) { return true; } final Class[] parameterTypes = method.getParameterTypes(); final Object[] parameterValues = getParameterValues(parameterTypes); final ImmutableList<Parameter> parameters = Invokable.from(method) .getParameters(); for (int i = 0; i < parameterValues.length; i++) { Object[] copiedParametersArray = Arrays.copyOf(parameterValues, parameterValues.length); final boolean primitive = TypeToken.of(parameterTypes[i]) .isPrimitive(); final boolean nullableParameter = parameters.get(i) .isAnnotationPresent(Nullable.class); if (primitive || nullableParameter) { continue; } copiedParametersArray[i] = null; final boolean correct = invokeAndCheck(copiedParametersArray); if (!correct) { return false; } } return true; } private boolean hasOnlyNullableArgs() { final ImmutableList<Parameter> parameters = Invokable.from(method) .getParameters(); for (Parameter parameter : parameters) { final boolean present = parameter.isAnnotationPresent(Nullable.class); if (!present) { return false; } } return true; } private Object[] getParameterValues(Class[] parameterTypes) { final Object[] parameterValues = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { final Class type = parameterTypes[i]; final Object defaultValue = valuesProvider.getDefaultValue(type); parameterValues[i] = defaultValue; } return parameterValues; } private boolean invokeAndCheck(Object[] params) { try { method.setAccessible(true); method.invoke(null, params); } catch (InvocationTargetException ex) { boolean valid = validateException(ex); return valid; } catch (IllegalAccessException e) { throw Exceptions.wrappedCause(e); } return false; } private boolean validateException(InvocationTargetException ex) { final Throwable cause = ex.getCause(); checkException(cause); final boolean result = hasExpectedStackTrace(cause); return result; } private static void checkException(Throwable cause) { final boolean correctException = cause instanceof NullPointerException; if (!correctException) { throw Exceptions.wrappedCause(cause); } } /** * Checks the stack trace elements. * * <p>It is expected that each of the tested utility methods invokes * {@link Preconditions#checkNotNull(Object)} as a first step of the execution. * * <p>Therefore the stack trace is analysed to ensure its first element references * the {@code Preconditions#checkNotNull(Object)} and the second one references the tested method. * * @param cause the {@code Throwable} * @return {@code true} if the {@code StackTraceElement}s matches the expected, {@code false} otherwise */ private boolean hasExpectedStackTrace(Throwable cause) { final StackTraceElement[] stackTraceElements = cause.getStackTrace(); final StackTraceElement preconditionsElement = stackTraceElements[0]; final boolean preconditionClass = Preconditions.class.getName() .equals(preconditionsElement.getClassName()); if (!preconditionClass) { return false; } final StackTraceElement targetClassElement = stackTraceElements[1]; final String targetMethodName = targetClassElement.getMethodName(); final boolean correct = method.getName() .equals(targetMethodName); if (!correct) { return false; } final boolean correctClass = targetClassName.equals(targetClassElement.getClassName()); return correctClass; } } /** * Provides the default values for the method arguments based on the argument type. */ private static class DefaultValueProvider { private static final Class[] EMPTY_PARAMETER_TYPES = {}; private static final Object[] EMPTY_ARGUMENTS = {}; private static final String METHOD_NAME = "getDefaultInstance"; private final Map<Class<?>, ?> defaultValues; private DefaultValueProvider(Map<Class<?>, ?> defaultValues) { this.defaultValues = defaultValues; } private Object getDefaultValue(Class<?> type) { Object result = defaultValues.get(type); if (result != null) { return result; } result = findDerivedTypeValue(type); final boolean primitive = allPrimitiveTypes().contains(type); if (result == null && primitive) { result = defaultValue(type); } final boolean wrapper = isWrapperType(type); if (result == null && wrapper) { final Class<?> unwrappedPrimitive = unwrap(type); result = defaultValue(unwrappedPrimitive); } if (result == null) { final Class<Message> messageClass = Message.class; final boolean assignableFromMessage = messageClass.isAssignableFrom(type); if (assignableFromMessage) { @SuppressWarnings("unchecked") //It's fine since we checked for the type. final Class<? extends Message> messageType = (Class<? extends Message>) type; result = getDefaultMessageInstance(messageType); } } checkState(result != null); return result; } /** * Returns the default value, if its type is derived from the given {@code type}. * * <p><b>Example:</b> * * <pre> * {@code public class Person {...} * * public class User extends Person {...} * // ... * * builder.addDefaultValue(new User()); * // ... * findDerivedTypeValue(Person); // will return an instance of User. * } * </pre> * * <p>In case there are several suitable value, the first one is used. * * @param type the parent type to look the default value for * @return the default value, or {@code null} if no such value can be found */ @Nullable private <T> T findDerivedTypeValue(Class<T> type) { for (Class clazz : defaultValues.keySet()) { final boolean passedToMap = type.isAssignableFrom(clazz); if (passedToMap) { @SuppressWarnings("unchecked") // It's OK, since we check for the type compliance above. final T result = (T) defaultValues.get(clazz); return result; } } return null; } private static Message getDefaultMessageInstance(Class<? extends Message> type) { // using the default instance of {@code Any} if the parameter type is {@code Message} if (type.equals(Message.class)) { return Any.getDefaultInstance(); } try { final Method method = type.getMethod(METHOD_NAME, EMPTY_PARAMETER_TYPES); final Message defaultInstance = (Message) method.invoke(null, EMPTY_ARGUMENTS); return defaultInstance; } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw Exceptions.wrappedCause(e); } } } /** * A builder for {@link NullToleranceTest}. */ public static class Builder { private static final String STRING_DEFAULT_VALUE = ""; private final Set<String> excludedMethods; private final Map<Class<?>, ? super Object> defaultValues; private Class<?> targetClass; private Builder() { defaultValues = newHashMap(); excludedMethods = newHashSet(); } /** * Sets the target class. * * @param utilClass the utility {@link Class} * @return the {@code Builder} */ public Builder setClass(Class utilClass) { this.targetClass = checkNotNull(utilClass); return this; } /** * Adds the method name which will be excluded from the check. * * @param methodName the name of the method to exclude * @return the {@code Builder} */ @SuppressWarnings("WeakerAccess") // it is a public API. public Builder excludeMethod(String methodName) { checkNotNull(methodName); final boolean validName = isName(methodName); checkArgument(validName); excludedMethods.add(methodName); return this; } @SuppressWarnings("WeakerAccess") // it is a public API. public <I> Builder addDefaultValue(I value) { checkNotNull(value); defaultValues.put(value.getClass(), value); return this; } @VisibleForTesting Class<?> getTargetClass() { return targetClass; } @VisibleForTesting Set<String> getExcludedMethods() { return unmodifiableSet(excludedMethods); } @VisibleForTesting Map<?, ?> getDefaultValues() { return unmodifiableMap(defaultValues); } /** * Initializes the {@link NullToleranceTest} instance. * * @return the {@code nullToleranceTest} instance. */ public NullToleranceTest build() { checkNotNull(targetClass); addDefaultTypeValues(); final NullToleranceTest result = new NullToleranceTest(this); return result; } private void addDefaultTypeValues() { // If no default value has been set for {@code String}, // add an empty string literal as one. for (Object clazz : defaultValues.keySet()) { final boolean stringClass = String.class.isAssignableFrom((Class) clazz); if (stringClass) { return; } } defaultValues.put(String.class, STRING_DEFAULT_VALUE); } } }
package jlibs.xml; import jlibs.core.lang.ImpossibleException; import jlibs.xml.sax.MyNamespaceSupport; import java.lang.reflect.Field; /** * Interface containing commonly used namespaces and their common prefixes. * * NOTE: The naming convention that should be followed for an uri is: * String URI_<suggestedPrefixInUppercase> = "<namespaceURI> * @author Santhosh Kumar T */ public interface Namespaces{ String URI_XML = "http: String URI_XMLNS = "http: /** Schema namespace as defined by XSD **/ String URI_XSD = "http: /** Instance namespace as defined by XSD **/ String URI_XSI = "http: String URI_XSL = "http: String URI_BPWS = "http://schemas.xmlsoap.org/ws/2003/03/business-process/"; //NOI18N String URI_FESB = "http: String URI_XHTML = "http: String URI_XPATH = "http: String URI_PLINK = "http://schemas.xmlsoap.org/ws/2003/05/partner-link/"; //NOI18N /** WSDL namespace for WSDL framework **/ String URI_WSDL = "http://schemas.xmlsoap.org/wsdl/"; //NOI18N /** WSDL namespace for WSDL HTTP GET & POST binding **/ String URI_HTTP = "http://schemas.xmlsoap.org/wsdl/http/"; //NOI18N /** WSDL namespace for WSDL MIME binding **/ String URI_MIME = "http://schemas.xmlsoap.org/wsdl/mime/"; //NOI18N /** WSDL namespace for WSDL SOAP binding **/ String URI_SOAP = "http://schemas.xmlsoap.org/wsdl/soap/"; //NOI18N /** Encoding namespace as defined by SOAP 1.1 **/ String URI_SOAPENC = "http://schemas.xmlsoap.org/soap/encoding/"; //NOI18N /** Envelope namespace as defined by SOAP 1.1 **/ String URI_SOAPENV = "http://schemas.xmlsoap.org/soap/envelope/"; //NOI18N MyNamespaceSupport SUGGESTED = new MyNamespaceSupport(){ { for(Field field: Namespaces.class.getFields()){ if(field.getName().startsWith("URI_")) //NOI18N try{ String prefix = field.getName().substring("URI_".length()).toLowerCase(); //NOI18N String uri = (String)field.get(null); declarePrefix(prefix, uri); } catch(IllegalAccessException ex){ throw new ImpossibleException(ex); } } } }; }
package com.adam.aslfms.receiver; /** * A BroadcastReceiver for intents sent by the myTouch 4G Music Player. * * @see BuiltInMusicAppReceiver * * @author tgwizard * @since 1.3.2 */ public class MyTouch4GMusicReceiver extends BuiltInMusicAppReceiver { // these first two are untested public static final String ACTION_MYTOUCH4G_PLAYSTATECHANGED = "com.real.IMP.playstatechanged"; public static final String ACTION_MYTOUCH4G_STOP = "com.real.IMP.playbackcomplete"; // should work public static final String ACTION_MYTOUCH4G_METACHANGED = "com.real.IMP.metachanged"; public MyTouch4GMusicReceiver() { super(ACTION_MYTOUCH4G_STOP, "com.real.IMP", "myTouch 4G Music Player"); } }
package com.mortennobel.imagescaling; import javax.imageio.ImageIO; import java.io.IOException; import java.io.File; import java.awt.image.BufferedImage; import java.awt.*; public class CreateSharpenMaskTest { private BufferedImage image; private DimensionConstrain dimensionConstrain = DimensionConstrain.createMaxDimension(100,100); public CreateSharpenMaskTest() { setUp(); Dimension dim = dimensionConstrain.getDimension(new Dimension(image.getWidth(),image.getHeight())); BufferedImage res = new BufferedImage(dim.width*5,dim.height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = res.createGraphics(); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); for (ResampleOp.UnsharpenMask unsharpenMask : ResampleOp.UnsharpenMask.values()){ saveSubImageType(scale(unsharpenMask),g,unsharpenMask); } g.dispose(); saveImage(res, "SharpenMask.png"); } private void saveSubImageType(BufferedImage source, Graphics2D dest, ResampleOp.UnsharpenMask unsharpenMash){ int x = source.getWidth()*unsharpenMash.ordinal(); int height = dest.getFontMetrics().getHeight(); int margin = 5; dest.drawImage(source, x ,0,null); dest.setColor(new Color(1,1,1,0.5f)); dest.fillRect(x,0,source.getWidth(), height+2*margin); dest.setColor(Color.black); dest.drawString(unsharpenMash.name(),x+2,height+margin); } private void saveImage(BufferedImage bufferedImage, String s) { File file = new File(System.getProperty("user.dir"),s); try{ ImageIO.write(bufferedImage, "png", file); } catch (Exception e){ e.printStackTrace(); } } private BufferedImage scale(ResampleOp.UnsharpenMask mask) { ResampleOp op = new ResampleOp(dimensionConstrain); op.setUnsharpenMask(mask); return op.filter(image, null); } protected void setUp() { try { image = ImageIO.read(getClass().getResource("/com/mortennobel/imagescaling/flower.jpg")); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new CreateSharpenMaskTest(); } }
package com.android.buscaminas; import java.util.ArrayList; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Picture; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; @SuppressLint({ "DrawAllocation", "NewApi" }) public class Buscaminas extends Activity implements OnTouchListener { private Tablero fondo; Button boton_reinicio; private Celda[][] casillas; private boolean activo = true; private final int filas=8; private final int col=8; boolean firstEvent=false; int cantidadBomba = 40; int condicionganar; TextView cronometro; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.buscaminas); LinearLayout layout2 = (LinearLayout) findViewById(R.id.layout2); fondo = new Tablero(this); fondo.setOnTouchListener(this); //creacion de los botones del panel superior //estos id no estan implementados en el xml por problemas con el frame this.boton_reinicio = (Button) findViewById(R.id.boton_reinicio); this.cronometro = (TextView)findViewById(R.id.cronometro); boton_reinicio.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub reiniciarActividad(Buscaminas.this); } }); layout2.addView(fondo); casillas = new Celda[filas][filas]; for (int f = 0; f <filas; f++) { for (int c = 0; c < filas; c++) { casillas[f][c] = new Celda(); } } } @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); return true; } @Override public boolean onTouch(View v, MotionEvent event) { if (activo) for (int f = 0; f < filas; f++) { for (int c = 0; c < filas; c++) { //comprobacion de la casilla hacia si misma if (casillas[f][c].dentro((int) event.getX(), (int) event.getY())) { //validamos el primer click evento if(!this.firstEvent){ this.firstEvent=true; this.disponerBombas(f,c); //<-- funcion update this.contarBombasPerimetro(); } //destapamos de todas formas casillas[f][c].destapado = true; if (casillas[f][c].contenido == 80) { Toast.makeText(this, "Booooooooommmmmmmmmmmm", Toast.LENGTH_LONG).show(); //desactivamos el perder partida para pruebas //activo = false; } if (casillas[f][c].contenido == 0){ recorrer(f, c); } //para que no de mas de un click a la vez fondo.invalidate(); } } } if (gano() && activo) { Toast.makeText(this, "Ganaste", Toast.LENGTH_LONG).show(); activo = false; } return true; } //funcion del boton reinicio public static void reiniciarActividad(Activity actividad){ Intent intent=new Intent(); intent.setClass(actividad, actividad.getClass()); //llamamos a la actividad actividad.startActivity(intent); //finalizamos la actividad actual actividad.finish(); } class Tablero extends View { public Tablero(Context context) { super(context); } protected void onDraw(Canvas canvas) { canvas.drawRGB(0, 0, 0); int ancho = 0; if (canvas.getWidth() < canvas.getHeight()) ancho = fondo.getWidth(); else ancho = fondo.getHeight(); int anchocua = ancho / filas; Paint paint = new Paint(20); Paint paint2 = new Paint(); paint2.setTextSize(20); paint2.setTypeface(Typeface.DEFAULT_BOLD); paint2.setARGB(255, 0, 0, 255); Paint paintlinea1 = new Paint(); //paintlinea1.setARGB(0, 255, 255, 255); int filaact = 0; for (int f = 0; f < filas; f++) { for (int c = 0; c < filas; c++) { casillas[f][c].fijarxy(c * anchocua, filaact, anchocua); if (casillas[f][c].destapado == false) //Visible paint.setARGB(255,230,230,250 ); //100,245,245,220 else //BackGround //this.findViewById(R.id.button1); //Background square paint.setARGB(255,245,222,179); //200,227,168,87 canvas.drawRect(c * anchocua, filaact, c * anchocua + anchocua - 2, filaact + anchocua - 2, paint); // linea blanca /*canvas.drawLine(c * anchocua, filaact, c * anchocua + anchocua, filaact, paintlinea1); canvas.drawLine(c * anchocua + anchocua - 1, filaact, c * anchocua + anchocua - 1, filaact + anchocua, paintlinea1);*/ if (casillas[f][c].contenido >= 1 && casillas[f][c].contenido <= filas && casillas[f][c].destapado) canvas.drawText( String.valueOf(casillas[f][c].contenido), c * anchocua + (anchocua / 2) - filas, filaact + anchocua / 2, paint2); //Aqui esta la bomba if (casillas[f][c].contenido == 80 && casillas[f][c].destapado) { Paint bomba = new Paint(); bomba.setARGB(255, 255, 0, 0); canvas.drawCircle(c * anchocua + (anchocua / 2), filaact + (anchocua / 2), filas, bomba); Picture p = new Picture(); canvas.drawPicture(new Picture()); } } filaact = filaact + anchocua; } } } //disponer bombas actualizado para el primer click private void disponerBombas(int fil , int co) { do { int fila = (int) (Math.random() * filas); int columna = (int) (Math.random() * filas); //le agrego posicion actual para primer click if(fila!= fil || columna !=co){ if (casillas[fila][columna].contenido == 0) { //80 significa que tiene bomba casillas[fila][columna].contenido = 80; cantidadBomba } } } while (cantidadBomba != 0); } private boolean gano() { for (int f = 0; f < filas; f++) for (int c = 0; c < filas; c++) if (casillas[f][c].destapado) condicionganar++; if (condicionganar == 56) return true; else return false; } private void contarBombasPerimetro() { for (int f = 0; f < filas; f++) { for (int c = 0; c < filas; c++) { if (casillas[f][c].contenido == 0) { int cant = contarCoordenada(f, c); casillas[f][c].contenido = cant; } } } } int contarCoordenada(int fila, int columna) { int total = 0; if (fila - 1 >= 0 && columna - 1 >= 0) { if (casillas[fila - 1][columna - 1].contenido == 80) total++; } if (fila - 1 >= 0) { if (casillas[fila - 1][columna].contenido == 80) total++; } if (fila - 1 >= 0 && columna + 1 < filas) { if (casillas[fila - 1][columna + 1].contenido == 80) total++; } if (columna + 1 < filas) { if (casillas[fila][columna + 1].contenido == 80) total++; } if (fila + 1 <filas && columna + 1 <filas) { if (casillas[fila + 1][columna + 1].contenido == 80) total++; } if (fila + 1 < filas) { if (casillas[fila + 1][columna].contenido == 80) total++; } if (fila + 1 < filas && columna - 1 >= 0) { if (casillas[fila + 1][columna - 1].contenido == 80) total++; } if (columna - 1 >= 0) { if (casillas[fila][columna - 1].contenido == 80) total++; } return total; } private void recorrer(int fil, int col) { if (fil >= 0 && fil < filas && col >= 0 && col < filas) { if (casillas[fil][col].contenido == 0) { casillas[fil][col].destapado = true; //significa que ia estan visitadas casillas[fil][col].contenido = 50; recorrer(fil, col + 1); recorrer(fil, col - 1); recorrer(fil + 1, col); recorrer(fil - 1, col); recorrer(fil - 1, col - 1); recorrer(fil - 1, col + 1); recorrer(fil + 1, col + 1); recorrer(fil + 1, col - 1); //si tienen numeros solo los destapa } else if (casillas[fil][col].contenido >= 1 && casillas[fil][col].contenido <= filas) { casillas[fil][col].destapado = true; } } } }
package org.spine3.server.storage.datastore; import com.google.cloud.datastore.Blob; import com.google.cloud.datastore.BlobValue; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.Key; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.Message; import org.spine3.protobuf.AnyPacker; import org.spine3.server.entity.LifecycleFlags; import org.spine3.server.storage.EntityField; import org.spine3.type.TypeUrl; import javax.annotation.Nullable; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.spine3.server.storage.datastore.DsProperties.isArchived; import static org.spine3.server.storage.datastore.DsProperties.isDeleted; /** * Utility class for converting {@link Message proto messages} into {@link Entity Entities} and * vise versa. * * @author Dmytro Dashenkov */ @SuppressWarnings("UtilityClass") class Entities { private static final Predicate<Entity> NOT_ARCHIVED_OR_DELETED = new Predicate<Entity>() { @Override public boolean apply(@Nullable Entity input) { if (input == null) { return false; } final boolean isNotArchived = !isArchived(input); final boolean isNotDeleted = !isDeleted(input); return isNotArchived && isNotDeleted; } }; private static final String DEFAULT_MESSAGE_FACTORY_METHOD_NAME = "getDefaultInstance"; private Entities() { } /** * Retrieves a message of given type, assignable from {@code Message}, from an {@link Entity}. * * <p>If passed {@link Entity} is {@code null}, a default instance for the given type * is returned. * * @param entity source {@link Entity} to get message form * @param type {@link TypeUrl} of required message * @param <M> required message type * @return message contained in the {@link Entity} */ static <M extends Message> M entityToMessage(@Nullable Entity entity, TypeUrl type) { if (entity == null) { return defaultMessage(type); } final Blob value = entity.getBlob(EntityField.bytes.toString()); final ByteString valueBytes = ByteString.copyFrom(value.toByteArray()); final Any wrapped = Any.newBuilder() .setValue(valueBytes) .setTypeUrl(type.value()) .build(); final M result = AnyPacker.unpack(wrapped); return result; } /** * Retrieves a {@link List} of messages of given type, assignable from {@code Message}, * from a collection of {@link Entity Entities}. * * <p>If passed {@link Entity} is {@code null}, a default instance for given type is returned. * * @param entities a collection of the source {@link Entity Entities} to get message form * @param type {@link TypeUrl} of required message * @param <M> required message type * @return message contained in the {@link Entity} */ static <M extends Message> List<M> entitiesToMessages(Collection<Entity> entities, TypeUrl type) { if (entities.isEmpty()) { return Collections.emptyList(); } final String typeName = type.value(); final ImmutableList.Builder<M> messages = new ImmutableList.Builder<>(); for (Entity entity : entities) { if (entity == null) { final M defaultMessage = defaultMessage(type); messages.add(defaultMessage); continue; } final Blob value = entity.getBlob(EntityField.bytes.toString()); final ByteString valueBytes = ByteString.copyFrom(value.toByteArray()); final Any wrapped = Any.newBuilder() .setValue(valueBytes) .setTypeUrl(typeName) .build(); final M message = AnyPacker.unpack(wrapped); messages.add(message); } return messages.build(); } /** * Generates an {@link Entity} with given {@link Key} and from given proto {@code Message} * * @param message source of data to be put into the {@link Entity} * @param key instance of {@link Key} to be assigned to the {@link Entity} * @return new instance of {@link Entity} containing serialized proto message */ static Entity messageToEntity(Message message, Key key) { checkNotNull(message); checkNotNull(key); final byte[] messageBytes = message.toByteArray(); final Blob valueBlob = Blob.copyFrom(messageBytes); final BlobValue blobValue = BlobValue.newBuilder(valueBlob) .setExcludeFromIndexes(true) .build(); final Entity entity = Entity.newBuilder(key) .set(EntityField.bytes.toString(), blobValue) .build(); return entity; } static LifecycleFlags getEntityStatus(Entity entity) { checkNotNull(entity); final boolean archived = isArchived(entity); final boolean deleted = isDeleted(entity); final LifecycleFlags result = LifecycleFlags.newBuilder() .setArchived(archived) .setDeleted(deleted) .build(); return result; } static Predicate<Entity> activeEntity() { return NOT_ARCHIVED_OR_DELETED; } @SuppressWarnings("unchecked") static <M extends Message> M defaultMessage(TypeUrl type) { final Class<M> messageClass = type.getJavaClass(); checkState(messageClass != null, String.format( "Not found class for type url \"%s\". Try to rebuild the project", type.getTypeName())); final M message; try { final Method factoryMethod = messageClass.getDeclaredMethod(DEFAULT_MESSAGE_FACTORY_METHOD_NAME); message = (M) factoryMethod.invoke(null); return message; } catch (@SuppressWarnings("OverlyBroadCatchBlock") ReflectiveOperationException e) { throw new IllegalStateException("Couldn't invoke static method " + DEFAULT_MESSAGE_FACTORY_METHOD_NAME + " from class " + messageClass.getCanonicalName(), e); } } }
package enosphorous.chateau_romani.handlers; import enosphorous.chateau_romani.common.Items; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.EntityWitch; import net.minecraft.item.Item; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.living.LivingDropsEvent; public class WitchDropHandler { public static double rand; @ForgeSubscribe public void onEntityDrop1(LivingDropsEvent event) { if (event.source.getDamageType().equals("player")) { rand = Math.random(); if (event.entityLiving instanceof EntityWitch) { if (rand < 0.3D) { event.entityLiving.dropItem(Items.fermented_grain.itemID, 2); } } } } @ForgeSubscribe public void onEntityDrop2(LivingDropsEvent event) { if (event.source.getDamageType().equals("player")) { rand = Math.random(); if (event.entityLiving instanceof EntityWitch) { if (rand < 0.3D) { event.entityLiving.dropItem(Items.milk_bottle.itemID, 1); } } } } @ForgeSubscribe public void onEntityDrop3(LivingDropsEvent event) { if (event.source.getDamageType().equals("player")) { rand = Math.random(); if (event.entityLiving instanceof EntityWitch) { if (rand < 0.1D) { event.entityLiving.dropItem(Items.bottled_fire.itemID, 1); } } } } @ForgeSubscribe public void onEntityDrop4(LivingDropsEvent event) { if (event.source.getDamageType().equals("player")) { rand = Math.random(); if (event.entityLiving instanceof EntityWitch) { if (rand < 0.03D) { event.entityLiving.dropItem(Items.bottled_ghast.itemID, 1); } } } } @ForgeSubscribe public void onEntityDrop5(LivingDropsEvent event) { if (event.source.getDamageType().equals("player")) { rand = Math.random(); if (event.entityLiving instanceof EntityWitch) { if (rand < 0.05D) { event.entityLiving.dropItem(Items.potion_red.itemID, 1); } } } } @ForgeSubscribe public void onEntityDrop6(LivingDropsEvent event) { if (event.source.getDamageType().equals("player")) { rand = Math.random(); if (event.entityLiving instanceof EntityWitch) { if (rand < 0.05D) { event.entityLiving.dropItem(Items.potion_green.itemID, 1); } } } } @ForgeSubscribe public void onEntityDrop7(LivingDropsEvent event) { if (event.source.getDamageType().equals("player")) { rand = Math.random(); if (event.entityLiving instanceof EntityWitch) { if (rand < 0.02D) { event.entityLiving.dropItem(Items.potion_blue.itemID, 1); } } } } }
package com.example.ccweibo; import java.util.Arrays; 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.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TableLayout; import android.widget.TableRow; public class FavouriteTwitterAct extends Activity { // like a map private SharedPreferences savedSearches; // populating the layout programatically private TableLayout queryTableLayout; private EditText queryEditText; private EditText tagEditText; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_favtwitter); // should have a file names 'searches' savedSearches = getSharedPreferences("searches", MODE_PRIVATE); // all ui components are inherited from View queryTableLayout = (TableLayout) findViewById(R.id.queryTableLayout); queryEditText = (EditText) findViewById(R.id.queryEditText); tagEditText = (EditText) findViewById(R.id.tagEditText); Button saveButton = (Button) findViewById(R.id.saveButton); saveButton.setOnClickListener(saveButtonListener); Button clearTagsButton = (Button) findViewById(R.id.clearTagsButton); clearTagsButton.setOnClickListener(clearTagsButtonListener); refreshButtons(null); } // recreate tag and search pairs based on the result from file private void refreshButtons(String newTag) { String[] tags = savedSearches.getAll().keySet().toArray(new String[0]); Arrays.sort(tags, String.CASE_INSENSITIVE_ORDER); if (newTag != null) { makeTagGUI(newTag, Arrays.binarySearch(tags, newTag)); } else { for (int i = 0; i < tags.length; i++) { makeTagGUI(tags[i], i); } } } // add a new tag-query pair or modify existing ones // SharedPreferences will store the entries in this file: // /data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml // note: makeTag will only add data to file, to build it to GUI, need to // invoke makeTagGUI private void makeTag(String query, String tag) { String originalQuery = savedSearches.getString(tag, null); SharedPreferences.Editor preferencesEditor = savedSearches.edit(); preferencesEditor.putString(tag, query); preferencesEditor.apply(); if (originalQuery == null) { refreshButtons(tag); } } // add new tag and editbutton to GUI dynamically private void makeTagGUI(String tag, int index) { // the inflater is a systemService // also available to get Alarm_service or power_service LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // inflate a created view View newTagView = inflater.inflate(R.layout.new_tag_view, null); Button newTagButton = (Button) newTagView .findViewById(R.id.newTagButton); newTagButton.setText(tag); newTagButton.setOnClickListener(queryButtonListener); Button newEditButton = (Button) newTagView .findViewById(R.id.newEditButton); newEditButton.setOnClickListener(editButtonListener); queryTableLayout.addView(newTagView, index); } private void clearButtons() { queryTableLayout.removeAllViews(); } // save a query text and update the queryTableLayout public OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { String qTx = queryEditText.getText().toString(); String tTx = tagEditText.getText().toString(); if (qTx.length() > 0 && tTx.length() > 0) { makeTag(qTx, tTx); queryEditText.setText(""); tagEditText.setText(""); } // spawn a warning dialog else { AlertDialog.Builder builder = new AlertDialog.Builder( FavouriteTwitterAct.this); builder.setTitle(R.string.missingTitle); builder.setPositiveButton(R.string.OK, null); builder.setMessage(R.string.missingMessage); builder.create().show(); } } }; // remove all tags from GUI and SharedPreferences // should always do SharedPreferences.edit() to return the Editor public OnClickListener clearTagsButtonListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub AlertDialog.Builder builder = new AlertDialog.Builder( FavouriteTwitterAct.this); builder.setTitle(R.string.confirmTitle); builder.setPositiveButton(R.string.erase, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { clearButtons(); SharedPreferences.Editor preferencesEditor = savedSearches .edit(); preferencesEditor.clear(); preferencesEditor.apply(); } }); // you can cancel, of course builder.setCancelable(false); builder.setNegativeButton(R.string.cancel, null); builder.setMessage(R.string.confirmMessage); builder.create().show(); } }; // clicking this button will open a browser and take you to the address public OnClickListener queryButtonListener = new OnClickListener() { @Override public void onClick(View v) { // can use v to access the button String key = ((Button) v).getText().toString(); String query = savedSearches.getString(key, null); String urlString = getString(R.string.searchURL) + query; // create an Intent to launch a web browser startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlString))); } }; // when clicking edit, will set the tagEditText and queryEditText to what // was in the tag, and click save will overwite the data public OnClickListener editButtonListener = new OnClickListener() { @Override public void onClick(View v) { // because the edit button and the tag belong to the same TableRow // parent, we get its parent and then get the tag // there're duplicate ids in the scroll view, so we need this way to // get the corresponding tag String tag = ((Button) (((TableRow) v.getParent()) .findViewById(R.id.newTagButton))).getText().toString(); // we set these two fields to be the current value, user can modify // and udpate by clicking save tagEditText.setText(tag); queryEditText.setText(savedSearches.getString(tag, null)); } }; }
package de.eightbitboy.ecorealms.world.meta; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import java.util.Arrays; import java.util.List; import de.eightbitboy.ecorealms.control.Control; import de.eightbitboy.ecorealms.control.ControlActionMapping; import de.eightbitboy.ecorealms.util.Logger; public class Highlighter implements ControlActionMapping.ActionListener { private static final float CLICK_HEIGHT = 0.01f; private static final float HOVER_HEIGHT = CLICK_HEIGHT + 0.005f; private Control control; private ModelInstance[] instances = new ModelInstance[2]; private ModelInstance clickModel; private ModelInstance hoverModel; public Highlighter(Control control) { this.control = control; createModels(); ControlActionMapping.subscribe(ControlActionMapping.Action.LMB, this); } private void createModels() { ModelBuilder modelBuilder = new ModelBuilder(); Material material = new Material(ColorAttribute.createDiffuse(Color.RED)); Model model = modelBuilder.createRect( 0, 0, CLICK_HEIGHT, 1, 0, CLICK_HEIGHT, 1, 1, CLICK_HEIGHT, 0, 1, CLICK_HEIGHT, 0, 0, 1, material, VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); clickModel = new ModelInstance(model); material = new Material(ColorAttribute.createDiffuse(Color.LIME)); model = modelBuilder.createRect( 0, 0, HOVER_HEIGHT, 1, 0, HOVER_HEIGHT, 1, 1, HOVER_HEIGHT, 0, 1, HOVER_HEIGHT, 0, 0, 1, material, VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal); hoverModel = new ModelInstance(model); instances[0] = clickModel; instances[1] = hoverModel; } public void update() { hoverModel.transform.setToTranslation( control.getHoverOverMap().x, control.getHoverOverMap().y, HOVER_HEIGHT); } public List<ModelInstance> getModelInstances() { return Arrays.asList(instances); } @Override public void action(ControlActionMapping.Action action) { clickModel.transform.setToTranslation( action.info().mousePositionOnMap.x, action.info().mousePositionOnMap.y, CLICK_HEIGHT); } }
package com.intellij.lexer; import com.intellij.html.embedding.HtmlEmbedment; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.XmlTokenType; import org.jetbrains.annotations.NotNull; import java.util.Objects; /** * @author Maxim.Mossienko */ public class HtmlLexer extends BaseHtmlLexer { private IElementType myTokenType; private int myTokenStart; private int myTokenEnd; public HtmlLexer() { this(new MergingLexerAdapter(new FlexAdapter(new _HtmlLexer()), TOKENS_TO_MERGE), true); } protected HtmlLexer(@NotNull Lexer baseLexer, boolean caseInsensitive) { super(baseLexer, caseInsensitive); } @Override public void start(@NotNull CharSequence buffer, int startOffset, int endOffset, int initialState) { myTokenType = null; super.start(buffer, startOffset, endOffset, initialState); } @Override public void advance() { myTokenType = null; super.advance(); } @Override public IElementType getTokenType() { if (myTokenType != null) return myTokenType; IElementType tokenType = super.getTokenType(); myTokenStart = super.getTokenStart(); myTokenEnd = super.getTokenEnd(); HtmlEmbedment embedment = acquireHtmlEmbedmentInfo(); if (embedment != null) { skipEmbedment(embedment); myTokenEnd = embedment.getRange().getEndOffset(); myTokenType = Objects.requireNonNullElse(embedment.getElementType(), XmlTokenType.XML_DATA_CHARACTERS); } else { myTokenType = tokenType; } return myTokenType; } @Override public int getTokenStart() { if (myTokenType != null) { return myTokenStart; } return super.getTokenStart(); } @Override public int getTokenEnd() { if (myTokenType != null) { return myTokenEnd; } return super.getTokenEnd(); } }
package org.basex.core; import org.basex.core.jobs.*; import org.basex.core.locks.*; import org.basex.core.users.*; import org.basex.data.*; import org.basex.io.random.*; import org.basex.query.util.pkg.*; import org.basex.query.value.seq.*; import org.basex.server.*; import org.basex.util.*; import org.basex.util.list.*; public final class Context { /** Blocked clients. */ public final ClientBlocker blocker; /** Job pool. */ public final JobPool jobs; /** Options. */ public final MainOptions options; /** Static options. */ public final StaticOptions soptions; /** Client sessions. */ public final Sessions sessions; /** Opened databases. */ public final Datas datas; /** Users. */ public final Users users; /** EXPath package repository. */ public final EXPathRepo repo; /** Databases list. */ public final Databases databases; /** Log. */ public final Log log; /** Locking. */ public final Locking locking; /** Client info. Set to {@code null} in standalone/server mode. */ private final ClientInfo client; /** Current node context. {@code null} if all documents of the current database are referenced. */ private DBNodes current; /** User reference. */ private User user; /** Currently opened database. */ private Data data; /** Indicates if the class has been closed/finalized. */ private boolean closed; // GUI references /** Marked nodes. {@code null} if database is closed. */ public DBNodes marked; /** Copied nodes {@code null} if database is closed.. */ public DBNodes copied; /** Focused node. */ public int focused = -1; /** * Default constructor, which is usually called once in the lifetime of a project. */ public Context() { this(true); } /** * Default constructor, which is usually called once in the lifetime of a project. * @param file retrieve options from disk */ public Context(final boolean file) { this(new StaticOptions(file)); } /** * Constructor, called by clients, and adopting the variables of the specified context. * The {@link #user} must be set after calling this method. * @param ctx main context */ public Context(final Context ctx) { this(ctx, null); } /** * Constructor, called by clients, and adopting the variables of the main context. * The {@link #user} must be set after calling this method. * @param ctx main context * @param client client info (can be {@code null}) */ public Context(final Context ctx, final ClientInfo client) { this.client = client; soptions = ctx.soptions; options = new MainOptions(ctx.options); datas = ctx.datas; sessions = ctx.sessions; databases = ctx.databases; blocker = ctx.blocker; locking = ctx.locking; users = ctx.users; repo = ctx.repo; log = ctx.log; jobs = ctx.jobs; } /** * Private constructor. * @param soptions static options */ private Context(final StaticOptions soptions) { this.soptions = soptions; options = new MainOptions(); datas = new Datas(); sessions = new Sessions(); blocker = new ClientBlocker(); databases = new Databases(soptions); locking = new Locking(soptions); users = new Users(soptions); repo = new EXPathRepo(soptions); log = new Log(soptions); user = users.get(UserText.ADMIN); jobs = new JobPool(soptions); client = null; } /** * Returns the user of this context. * @return user (can be {@code null} if it has not yet been assigned */ public User user() { return user; } /** * Sets the user of this context. This method can only be called once. * @param us user */ public void user(final User us) { if(user != null) throw Util.notExpected("User has already been assigned."); user = us; } /** * Closes the database context. Must only be called on the global database context, * and not on client instances. */ public synchronized void close() { if(closed) return; closed = true; jobs.close(); sessions.close(); datas.close(); log.close(); closeDB(); } /** * Returns {@code true} if a data reference exists and if the current node set contains * all documents. * @return result of check */ public boolean root() { return data != null && current == null; } /** * Returns the current data reference. * @return data reference */ public Data data() { return data; } /** * Returns the current node context. * @return node set, or {@code null} if no database is opened */ public DBNodes current() { if(data == null) return null; if(current != null) return current; return new DBNodes(data, true, data.resources.docs().toArray()); } /** * Sets the current node context. Discards the input if it contains all document * nodes of the currently opened database. * @param curr node set */ public void current(final DBNodes curr) { current = curr.discardDocs(); } /** * Sets the specified data instance as current database. * @param dt data reference */ public void openDB(final Data dt) { data = dt; copied = null; set(null, new DBNodes(dt)); } /** * Closes the current database context. */ public void closeDB() { data = null; copied = null; set(null, null); } /** * Sets the current context and marked node set and resets the focus. * @param curr context set * @param mark marked nodes */ public void set(final DBNodes curr, final DBNodes mark) { current = curr; marked = mark; focused = -1; } public void invalidate() { current = null; } /** * Checks if the specified database is pinned. * @param db name of database * @return result of check */ public boolean pinned(final String db) { return datas.pinned(db) || TableDiskAccess.locked(db, this); } public boolean perm(final Perm perm, final String db) { return user.has(perm, db); } /** * Returns the host and port of a client. * @return address (or {@code null}) */ public String clientAddress() { return client != null ? client.clientAddress() : null; } /** * Returns the name of the current client or user. * @return user name (or {@code null}) */ public String clientName() { return client != null ? client.clientName() : user != null ? user.name() : null; } /** * Returns all databases for which the current user has read access. * @return resulting list */ public StringList listDBs() { return listDBs(null); } /** * Returns all databases for which the current user has read access. * @param name database pattern (can be {@code null}) * @return resulting list */ public StringList listDBs(final String name) { final StringList dbs = databases.listDBs(name); final StringList sl = new StringList(dbs.size()); for(final String db : dbs) { if(perm(Perm.READ, db)) sl.add(db); } return sl; } }
package com.google.mu.util.stream; import static java.util.Objects.requireNonNull; import java.util.AbstractMap; import java.util.Map; import com.google.mu.util.stream.Iteration.Continuation; /** * Similar to {@link Iteration}, but is used to iteratively {@link #yeild yield()} pairs into a * lazy {@link BiStream}. */ public class BiIteration<L, R> { private final Iteration<Map.Entry<L, R>> iteration = new Iteration<>(); /** Yields the pair of {@code left} and {@code right} to the result {@code BiStream}. */ public final BiIteration<L, R> yield(L left, R right) { iteration.yield( new AbstractMap.SimpleImmutableEntry<>(requireNonNull(left), requireNonNull(right))); return this; } /** * Yields to the result {@code BiStream} a recursive iteration or lazy side-effect wrapped in * {@code continuation}. */ public final BiIteration<L, R> yield(Continuation continuation) { iteration.yield(continuation); return this; } /** Returns the {@code BiStreram} that iterates through the {@link #yield yielded} pairs. */ public final BiStream<L, R> stream() { return BiStream.from(iteration.stream()); } }
package com.thoughtworks.xstream; import com.thoughtworks.xstream.alias.ClassMapper; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.basic.*; import com.thoughtworks.xstream.converters.collections.*; import com.thoughtworks.xstream.converters.extended.*; import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.converters.reflection.SerializableConverter; import com.thoughtworks.xstream.core.*; import com.thoughtworks.xstream.core.util.ClassLoaderReference; import com.thoughtworks.xstream.core.util.CompositeClassLoader; import com.thoughtworks.xstream.core.util.CustomObjectInputStream; import com.thoughtworks.xstream.core.util.CustomObjectOutputStream; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.mapper.*; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.sql.Time; import java.sql.Timestamp; import java.util.*; /** * Simple facade to XStream library, a Java-XML serialization tool. * <p/> * <p><hr><b>Example</b><blockquote><pre> * XStream xstream = new XStream(); * String xml = xstream.toXML(myObject); // serialize to XML * Object myObject2 = xstream.fromXML(xml); // deserialize from XML * </pre></blockquote><hr> * <p/> * <h3>Aliasing classes</h3> * <p/> * <p>To create shorter XML, you can specify aliases for classes using * the <code>alias()</code> method. * For example, you can shorten all occurences of element * <code>&lt;com.blah.MyThing&gt;</code> to * <code>&lt;my-thing&gt;</code> by registering an alias for the class. * <p><hr><blockquote><pre> * xstream.alias("my-thing", MyThing.class); * </pre></blockquote><hr> * <p/> * <h3>Converters</h3> * <p/> * <p>XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} * instances, each of which acts as a strategy for converting a particular type * of class to XML and back again. Out of the box, XStream contains converters * for most basic types (String, Date, int, boolean, etc) and collections (Map, List, * Set, Properties, etc). For other objects reflection is used to serialize * each field recursively.</p> * <p/> * <p>Extra converters can be registered using the <code>registerConverter()</code> * method. Some non-standard converters are supplied in the * {@link com.thoughtworks.xstream.converters.extended} package and you can create * your own by implementing the {@link com.thoughtworks.xstream.converters.Converter} * interface.</p> * <p/> * <p><hr><b>Example</b><blockquote><pre> * xstream.registerConverter(new SqlTimestampConverter()); * xstream.registerConverter(new DynamicProxyConverter()); * </pre></blockquote><hr> * <p>The default converter, ie the converter which will be used if no other registered * converter is suitable, can be configured by either one of the constructors * or can be changed using the <code>changeDefaultConverter()</code> method. * If not set, XStream uses {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} * as the initial default converter. * </p> * <p/> * <p><hr><b>Example</b><blockquote><pre> * xstream.changeDefaultConverter(new ACustomDefaultConverter()); * </pre></blockquote><hr> * <p/> * <h3>Object graphs</h3> * <p/> * <p>XStream has support for object graphs; a deserialized object graph * will keep references intact, including circular references.</p> * <p/> * <p>XStream can signify references in XML using either XPath or IDs. The * mode can be changed using <code>setMode()</code>:</p> * <p/> * <table border="1"> * <tr> * <td><code>xstream.setMode(XStream.XPATH_REFERENCES);</code></td> * <td><i>(Default)</i> Uses XPath references to signify duplicate * references. This produces XML with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td> * <td>Uses ID references to signify duplicate references. In some * scenarios, such as when using hand-written XML, this is * easier to work with.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td> * <td>This disables object graph support and treats the object * structure like a tree. Duplicate references are treated * as two seperate objects and circular references cause an * exception. This is slightly faster and uses less memory * than the other two modes.</td> * </tr> * </table> * * <h3>Thread safety</h3> * * <p>The XStream instance is thread-safe. That is, once the XStream instance * has been created and configured, it may be shared across multiple threads * allowing objects to be serialized/deserialized concurrently. * * <h3>Implicit collections</h3> * <p/> * <p>To avoid the need for special tags for collections, you can define implicit collections using one of the * <code>addImplicitCollection</code> methods.</p> * * @author Joe Walnes * @author Mauro Talevi */ public class XStream { private ClassAliasingMapper classAliasingMapper; private FieldAliasingMapper fieldAliasingMapper; private DefaultImplementationsMapper defaultImplementationsMapper; private ImmutableTypesMapper immutableTypesMapper; private ImplicitCollectionMapper implicitCollectionMapper; private ReflectionProvider reflectionProvider; private HierarchicalStreamDriver hierarchicalStreamDriver; private MarshallingStrategy marshallingStrategy; private ClassLoaderReference classLoaderReference; // TODO: Should be changeable private ClassMapper classMapper; private DefaultConverterLookup converterLookup; private JVM jvm = new JVM(); public static final int NO_REFERENCES = 1001; public static final int ID_REFERENCES = 1002; public static final int XPATH_REFERENCES = 1003; private static final int PRIORITY_NORMAL = 0; private static final int PRIORITY_LOW = -10; private static final int PRIORITY_VERY_LOW = -20; public XStream() { this(null, null, new XppDriver()); } /** * @deprecated As of XStream 1.1.1, a default Converter is unnecessary as you can register a Converter with an * associated priority. Use an alternate constructor. */ public XStream(Converter defaultConverter) { this(null, null, new XppDriver(), null); registerConverter(defaultConverter, PRIORITY_VERY_LOW); } public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, null, hierarchicalStreamDriver); } public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, null, new XppDriver()); } public XStream(ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, null, hierarchicalStreamDriver); } public XStream(ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver) { this(reflectionProvider, classMapper, driver, null); } public XStream(ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver, String classAttributeIdentifier) { jvm = new JVM(); if (reflectionProvider == null) { reflectionProvider = jvm.bestReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader()); this.classMapper = classMapper == null ? buildMapper(classAttributeIdentifier) : classMapper; converterLookup = new DefaultConverterLookup(this.classMapper); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_REFERENCES); } /** * @deprecated As of XStream 1.1.1, a default Converter is unnecessary as you can register a Converter with an * associated priority. Use an alternate constructor. */ public XStream(ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver, String classAttributeIdentifier, Converter defaultConverter) { this(reflectionProvider, classMapper, driver, classAttributeIdentifier); registerConverter(defaultConverter, PRIORITY_VERY_LOW); } private ClassMapper buildMapper(String classAttributeIdentifier) { MapperWrapper mapper = new DefaultMapper(classLoaderReference, classAttributeIdentifier); mapper = new XmlFriendlyMapper(mapper); mapper = new ClassAliasingMapper(mapper); classAliasingMapper = (ClassAliasingMapper) mapper; // need a reference to that one mapper = new FieldAliasingMapper(mapper); fieldAliasingMapper = (FieldAliasingMapper) mapper; // need a reference to that one mapper = new ImplicitCollectionMapper(mapper); implicitCollectionMapper = (ImplicitCollectionMapper)mapper; // need a reference to this one mapper = new DynamicProxyMapper(mapper); if (JVM.is15()) { mapper = new EnumMapper(mapper); } mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); defaultImplementationsMapper = (DefaultImplementationsMapper) mapper; // and that one mapper = new ImmutableTypesMapper(mapper); immutableTypesMapper = (ImmutableTypesMapper)mapper; // that one too mapper = wrapMapper(mapper); mapper = new CachingMapper(mapper); return mapper; } protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } protected void setupAliases() { alias("null", ClassMapper.Null.class); alias("int", Integer.class); alias("float", Float.class); alias("double", Double.class); alias("long", Long.class); alias("short", Short.class); alias("char", Character.class); alias("byte", Byte.class); alias("boolean", Boolean.class); alias("number", Number.class); alias("object", Object.class); alias("big-int", BigInteger.class); alias("big-decimal", BigDecimal.class); alias("string-buffer", StringBuffer.class); alias("string", String.class); alias("java-class", Class.class); alias("method", Method.class); alias("constructor", Constructor.class); alias("date", Date.class); alias("url", URL.class); alias("bit-set", BitSet.class); alias("map", Map.class); alias("entry", Map.Entry.class); alias("properties", Properties.class); alias("list", List.class); alias("set", Set.class); alias("linked-list", LinkedList.class); alias("vector", Vector.class); alias("tree-map", TreeMap.class); alias("tree-set", TreeSet.class); alias("hashtable", Hashtable.class); // Instantiating these two classes starts the AWT system, which is undesirable. Calling loadClass ensures // a reference to the class is found but they are not instantiated. alias("awt-color", jvm.loadClass("java.awt.Color")); alias("awt-font", jvm.loadClass("java.awt.Font")); alias("sql-timestamp", Timestamp.class); alias("sql-time", Time.class); alias("sql-date", java.sql.Date.class); alias("file", File.class); alias("locale", Locale.class); alias("gregorian-calendar", Calendar.class); if (JVM.is14()) { alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap")); alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet")); alias("trace", jvm.loadClass("java.lang.StackTraceElement")); alias("currency", jvm.loadClass("java.util.Currency")); } if (JVM.is15()) { alias("enum-set", jvm.loadClass("java.util.EnumSet")); alias("enum-map", jvm.loadClass("java.util.EnumMap")); } } protected void setupDefaultImplementations() { addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } protected void setupConverters() { ReflectionConverter reflectionConverter = new ReflectionConverter(classMapper, reflectionProvider); registerConverter(reflectionConverter, PRIORITY_VERY_LOW); registerConverter(new SerializableConverter(classMapper, reflectionProvider), PRIORITY_LOW); registerConverter(new ExternalizableConverter(classMapper), PRIORITY_LOW); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter(new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(classMapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(classMapper), PRIORITY_NORMAL); registerConverter(new MapConverter(classMapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(classMapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(classMapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); registerConverter(new DynamicProxyConverter(classMapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(), PRIORITY_NORMAL); registerConverter(new FontConverter(), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); if (JVM.is14()) { // late bound converters - allows XStream to be compiled on earlier JDKs dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.ThrowableConverter", PRIORITY_NORMAL, new Class[] {Converter.class} , new Object[] { reflectionConverter} ); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL, new Class[] {Converter.class} , new Object[] { reflectionConverter} ); } if (JVM.is15()) { // late bound converters - allows XStream to be compiled on earlier JDKs dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL, new Class[] {Mapper.class}, new Object[] {classMapper}); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL, new Class[] {Mapper.class}, new Object[] {classMapper}); } } private void dynamicallyRegisterConverter(String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Converter converter = (Converter) constructor.newInstance(constructorParamValues); registerConverter(converter, priority); } catch (Exception e) { throw new InitializationException("Could not instatiate converter : " + className, e); } } protected void setupImmutableTypes() { // primitives are always immutable addImmutableType(boolean.class); addImmutableType(Boolean.class); addImmutableType(byte.class); addImmutableType(Byte.class); addImmutableType(char.class); addImmutableType(Character.class); addImmutableType(double.class); addImmutableType(Double.class); addImmutableType(float.class); addImmutableType(Float.class); addImmutableType(int.class); addImmutableType(Integer.class); addImmutableType(long.class); addImmutableType(Long.class); addImmutableType(short.class); addImmutableType(Short.class); // additional types addImmutableType(ClassMapper.Null.class); addImmutableType(BigDecimal.class); addImmutableType(BigInteger.class); addImmutableType(String.class); addImmutableType(URL.class); addImmutableType(File.class); addImmutableType(Class.class); } public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } /** * Serialize an object to a pretty-printed XML String. */ public String toXML(Object obj) { Writer stringWriter = new StringWriter(); HierarchicalStreamWriter writer = new PrettyPrintWriter(stringWriter); marshal(obj, writer); return stringWriter.toString(); } /** * Serialize an object to the given Writer as pretty-printed XML. */ public void toXML(Object obj, Writer writer) { marshal(obj, new PrettyPrintWriter(writer)); } /** * Serialize and object to a hierarchical data structure (such as XML). */ public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } /** * Serialize and object to a hierarchical data structure (such as XML). * * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, XStream * shall create one lazily as needed. */ public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, classMapper, dataHolder); } /** * Deserialize an object from an XML String. */ public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } /** * Deserialize an object from an XML Reader. */ public Object fromXML(Reader xml) { return unmarshal(hierarchicalStreamDriver.createReader(xml), null); } /** * Deserialize an object from an XML String, * populating the fields of the given root object instead of instantiating * a new one. */ public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } /** * Deserialize an object from an XML Reader, * populating the fields of the given root object instead of instantiating * a new one. */ public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from a hierarchical data structure (such as XML). */ public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } /** * Deserialize an object from a hierarchical data structure (such as XML), * populating the fields of the given root object instead of instantiating * a new one. */ public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @param root If present, the passed in object will have its fields populated, as opposed to XStream creating a * new instance. * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, XStream * shall create one lazily as needed. */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, classMapper); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased */ public void alias(String name, Class type) { classAliasingMapper.addClassAlias(name, type); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @param defaultImplementation Default implementation of type to use if no other specified. */ public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } public void aliasField(String alias, Class type, String fieldName) { fieldAliasingMapper.addFieldAlias(alias, type, fieldName); } /** * Associate a default implementation of a class with an object. Whenever XStream encounters an instance of this * type, it will use the default implementation instead. * * For example, java.util.ArrayList is the default implementation of java.util.List. * @param defaultImplementation * @param ofType */ public void addDefaultImplementation(Class defaultImplementation, Class ofType) { defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } public void addImmutableType(Class type) { immutableTypesMapper.addImmutableType(type); } /** * @deprecated As of 1.1.1 you should register a converter with the appropriate priority. */ public void changeDefaultConverter(Converter defaultConverter) { registerConverter(defaultConverter, PRIORITY_VERY_LOW); } public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(Converter converter, int priority) { converterLookup.registerConverter(converter, priority); } public ClassMapper getClassMapper() { return classMapper; } public ConverterLookup getConverterLookup() { return converterLookup; } /** * Change mode for dealing with duplicate references. * Valid valuse are <code>XStream.XPATH_REFERENCES</code>, * <code>XStream.ID_REFERENCES</code> and <code>XStream.NO_REFERENCES</code>. * * @see #XPATH_REFERENCES * @see #ID_REFERENCES * @see #NO_REFERENCES */ public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy()); break; default: throw new IllegalArgumentException("Unknown mode : " + mode); } } /** * @deprecated Use addImplicitCollection() instead. */ public void addDefaultCollection(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName); } /** * Adds a default implicit collection which is used for any unmapped xml tag. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This filed must be an <code>java.util.ArrayList</code>. */ public void addImplicitCollection(Class ownerType, String fieldName) { implicitCollectionMapper.add(ownerType, fieldName, null, Object.class); } /** * Adds implicit collection which is used for all items of the given itemType. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This filed must be an <code>java.util.ArrayList</code>. * @param itemType type of the items to be part of this collection. */ public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { implicitCollectionMapper.add(ownerType, fieldName, null, itemType); } /** * Adds implicit collection which is used for all items of the given element name defined by itemFieldName. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This filed must be an <code>java.util.ArrayList</code>. * @param itemFieldName element name of the implicit collection * @param itemType item type to be aliases be the itemFieldName */ public void addImplicitCollection(Class ownerType, String fieldName, String itemFieldName, Class itemType) { implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType); } public DataHolder newDataHolder() { return new MapBackedDataHolder(); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * <p>To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}.</p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * <p>To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}.</p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream. * * <p>Because an ObjectOutputStream can contain multiple items and XML only allows a single root node, the stream * must be written inside an enclosing node.</p> * * <p>It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be incomplete.</p> * * <h3>Example</h3> * <pre>ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things"); * out.writeInt(123); * out.writeObject("Hello"); * out.writeObject(someObject) * out.close();</pre> * * @param writer The writer to serialize the objects to. * @param rootNodeName The name of the root node enclosing the stream of objects. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, String rootNodeName) throws IOException { writer.startNode(rootNodeName); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(Object object) { marshal(object, writer); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void flush() { writer.flush(); } public void close() { writer.endNode(); writer.close(); } }); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream. * * <h3>Example</h3> * <pre>ObjectInputStream in = xstream.createObjectOutputStream(aReader); * int a = out.readInt(); * Object b = out.readObject(); * Object c = out.readObject();</pre> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); Object result = unmarshal(reader); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException("not in call to readObject"); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException("not in call to readObject"); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException("stream inactive"); } public void close() { reader.close(); } }); } /** * Change the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } /** * Change the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } public static class InitializationException extends BaseException { public InitializationException(String message, Throwable cause) { super(message, cause); } } }
package net.domesdaybook.parser.tree.node; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import net.domesdaybook.parser.ParseException; import net.domesdaybook.parser.tree.ParseTree; import org.junit.Test; import net.domesdaybook.parser.tree.ParseTreeType; import net.domesdaybook.parser.tree.node.ChildrenNode.ListStrategy; /** * @author Matt Palmer * */ public class ChildrenNodeTest { @Test public final void testDifferentNumbersOfChildren() { for (int numChildren = 0; numChildren < 10; numChildren++) { runNumChildrenTests(numChildren); } } private void runNumChildrenTests(int numChildren) { List<ParseTree> children = new ArrayList<ParseTree>(); for (int i = 0; i < numChildren; i++) { children.add(new BaseNode(ParseTreeType.ANY)); } runTests(children, numChildren); } private void runTests(List<ParseTree> children, int numChildren) { for (ParseTreeType type : ParseTreeType.values()) { testConstructors(type, children, numChildren); testChangingChildren(type, children, numChildren); } } private void testConstructors(ParseTreeType type, List<ParseTree> children, int numChildren) { ChildrenNode node = new ChildrenNode(type, children); testNode("Default false inversion: ", node, type, numChildren, false); node = new ChildrenNode(type, children, false); testNode("Specified false inversion: ", node, type, numChildren, false); node = new ChildrenNode(type, children, true); testNode("Specified true inversion: ", node, type, numChildren, true); } private void testChangingChildren(ParseTreeType type, List<ParseTree> children, int numChildren) { List<ParseTree> childrenToTest = new ArrayList<ParseTree>(children); ChildrenNode defaultNode = new ChildrenNode(type, childrenToTest); ChildrenNode copyNode = new ChildrenNode(type, childrenToTest, ListStrategy.COPY_LIST); ChildrenNode givenNode = new ChildrenNode(type, childrenToTest, ListStrategy.USE_GIVEN_LIST); assertEquals("Before change: Default behaviour is to copy the child list.", numChildren, defaultNode.getChildren().size()); assertEquals("Before change: Specified copy behaviour also copies the list.", numChildren, copyNode.getChildren().size()); assertEquals("Before change: Specified use given behaviour has same children now.", numChildren, givenNode.getChildren().size()); ParseTree nodeToAdd = new StringNode("Node to add"); childrenToTest.add(nodeToAdd); assertEquals("Add to test list: Default behaviour is to copy the child list.", numChildren, defaultNode.getChildren().size()); assertEquals("Add to test list: Specified copy behaviour also copies the list.", numChildren, copyNode.getChildren().size()); assertEquals("Add to test list: Specified use given behaviour has more children now.", numChildren + 1, givenNode.getChildren().size()); ParseTree nodeToAdd2 = new StringNode("Second node to add"); defaultNode.addChild(nodeToAdd2); copyNode.addChild(nodeToAdd2); givenNode.addChild(nodeToAdd2); assertEquals("Add to default node: Default behaviour is to copy the child list.", numChildren + 1, defaultNode.getChildren().size()); assertEquals("Add to copy node: Specified copy behaviour also copies the list.", numChildren + 1, copyNode.getChildren().size()); assertEquals("Add to given node: Specified use given behaviour has more children now.", numChildren + 2, givenNode.getChildren().size()); assertEquals("Add to given node: test list is also increased", numChildren + 2, childrenToTest.size()); childrenToTest.remove(nodeToAdd); assertEquals("Remove node from test list: Default behaviour is to copy the child list.", numChildren + 1, defaultNode.getChildren().size()); assertEquals("Remove node from test list: Specified copy behaviour also copies the list.", numChildren + 1, copyNode.getChildren().size()); assertEquals("Remove node from test list: Specified use given behaviour has less children now.", numChildren + 1, givenNode.getChildren().size()); defaultNode.removeChild(nodeToAdd2); copyNode.removeChild(nodeToAdd2); givenNode.removeChild(nodeToAdd2); assertEquals("Remove from default node: Default behaviour is is back to start", numChildren, defaultNode.getChildren().size()); assertEquals("Remove from copy node: Specified copy behaviour is back to start.", numChildren, copyNode.getChildren().size()); assertEquals("Remove from given node: Specified use given behaviour is back to start.", numChildren, givenNode.getChildren().size()); assertEquals("Remove from given node: test list is back to start", numChildren, childrenToTest.size()); } private void testNode(String description, ChildrenNode node, ParseTreeType type, int numChildren, boolean isInverted) { assertEquals(description + "ChildrenNode has correct type: " + type, node.getParseTreeType(), type); try { assertEquals(description + "ChildrenNode value is correct inversion: " + isInverted, isInverted, node.isValueInverted()); } catch (ParseException e) { fail(description + "ChildrenNode should not throw a ParseException if asked if the value is inverted."); } try { node.getByteValue(); fail(description + "Expected a ParseException if asked for the byte value"); } catch (ParseException allIsFine) {}; try { node.getIntValue(); fail(description + "Expected a ParseException if asked for the int value"); } catch (ParseException allIsFine) {}; try { node.getTextValue(); fail(description + "Expected a ParseException if asked for the text value"); } catch (ParseException allIsFine) {}; assertNotNull(description + "Child list is not null", node.getChildren()); assertEquals(description + "Child list has correct number of children " + numChildren, numChildren, node.getChildren().size()); } }
package edu.neu.ccs.pyramid.application; import com.fasterxml.jackson.databind.ObjectMapper; import edu.neu.ccs.pyramid.classification.logistic_regression.LogisticRegression; import edu.neu.ccs.pyramid.classification.logistic_regression.LogisticRegressionInspector; import edu.neu.ccs.pyramid.configuration.Config; import edu.neu.ccs.pyramid.dataset.*; import edu.neu.ccs.pyramid.eval.MAP; import edu.neu.ccs.pyramid.eval.MLMeasures; import edu.neu.ccs.pyramid.feature.Feature; import edu.neu.ccs.pyramid.feature.FeatureList; import edu.neu.ccs.pyramid.feature.TopFeatures; import edu.neu.ccs.pyramid.multilabel_classification.MultiLabelClassifier; import edu.neu.ccs.pyramid.multilabel_classification.cbm.*; import edu.neu.ccs.pyramid.optimization.EarlyStopper; import edu.neu.ccs.pyramid.util.ListUtil; import edu.neu.ccs.pyramid.util.Pair; import edu.neu.ccs.pyramid.util.PrintUtil; import edu.neu.ccs.pyramid.util.Serialization; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.time.StopWatch; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class CBMEN { private static boolean VERBOSE = false; public static void main(String[] args) throws Exception { if (args.length != 1) { throw new IllegalArgumentException("Please specify a properties file."); } Config config = new Config(args[0]); System.out.println(config); VERBOSE = config.getBoolean("output.verbose"); new File(config.getString("output.dir")).mkdirs(); if (config.getBoolean("tune")){ System.out.println("============================================================"); System.out.println("Start hyper parameter tuning"); StopWatch stopWatch = new StopWatch(); stopWatch.start(); List<TuneResult> tuneResults = new ArrayList<>(); List<MultiLabelClfDataSet> dataSets = loadTrainValidData(config); List<Double> penalties = config.getDoubles("tune.penalty.candidates"); List<Double> l1Ratioes = config.getDoubles("tune.l1Ratio.candidates"); List<Integer> components = config.getIntegers("tune.numComponents.candidates"); for (double penalty: penalties){ for (double l1Ratio : l1Ratioes) { for (int component: components){ StopWatch stopWatch1 = new StopWatch(); stopWatch1.start(); HyperParameters hyperParameters = new HyperParameters(); hyperParameters.numComponents = component; hyperParameters.l1Ratio = l1Ratio; hyperParameters.penalty = penalty; System.out.println(" System.out.println("Trying hyper parameters:"); System.out.println("train.numComponents = "+hyperParameters.numComponents); System.out.println("train.penalty = "+hyperParameters.penalty); System.out.println("train.l1Ratio = "+hyperParameters.l1Ratio); TuneResult tuneResult = tune(config, hyperParameters, dataSets.get(0), dataSets.get(1)); System.out.println("Found optimal train.iterations = "+tuneResult.hyperParameters.iterations); System.out.println("Validation performance = "+tuneResult.performance); tuneResults.add(tuneResult); System.out.println("Time spent on trying this set of hyper parameters = "+stopWatch1); } } } Comparator<TuneResult> comparator = Comparator.comparing(res->res.performance); TuneResult best; String predictTarget = config.getString("tune.targetMetric"); switch (predictTarget){ case "instance_set_accuracy": best = tuneResults.stream().max(comparator).get(); break; case "instance_f1": best = tuneResults.stream().max(comparator).get(); break; case "instance_hamming_loss": best = tuneResults.stream().min(comparator).get(); break; case "label_map": best = tuneResults.stream().max(comparator).get(); break; default: throw new IllegalArgumentException("tune.targetMetric should be instance_set_accuracy, instance_f1 or instance_hamming_loss"); } System.out.println(" System.out.println("Hyper parameter tuning done."); System.out.println("Time spent on entire hyper parameter tuning = "+stopWatch); System.out.println("Best validation performance = "+best.performance); System.out.println("Best hyper parameters:"); System.out.println("train.numComponents = "+best.hyperParameters.numComponents); System.out.println("train.penalty = "+best.hyperParameters.penalty); System.out.println("train.l1Ratio = "+best.hyperParameters.l1Ratio); System.out.println("train.iterations = "+best.hyperParameters.iterations); Config tunedHypers = best.hyperParameters.asConfig(); tunedHypers.store(new File(config.getString("output.dir"), "tuned_hyper_parameters.properties")); System.out.println("Tuned hyper parameters saved to "+new File(config.getString("output.dir"), "tuned_hyper_parameters.properties").getAbsolutePath()); System.out.println("============================================================"); } if (config.getBoolean("train")){ System.out.println("============================================================"); if (config.getBoolean("train.useTunedHyperParameters")){ File hyperFile = new File(config.getString("output.dir"), "tuned_hyper_parameters.properties"); if (!hyperFile.exists()){ System.out.println("train.useTunedHyperParameters is set to true. But no tuned hyper parameters can be found in the output directory."); System.out.println("Please either run hyper parameter tuning, or provide hyper parameters manually and set train.useTunedHyperParameters=false."); System.exit(1); } Config tunedHypers = new Config(hyperFile); HyperParameters hyperParameters = new HyperParameters(tunedHypers); System.out.println("Start training with tuned hyper parameters:"); System.out.println("train.numComponents = "+hyperParameters.numComponents); System.out.println("train.penalty = "+hyperParameters.penalty); System.out.println("train.l1Ratio = "+hyperParameters.l1Ratio); System.out.println("train.iterations = "+hyperParameters.iterations); MultiLabelClfDataSet trainSet = loadTrainData(config); train(config, hyperParameters, trainSet); } else { HyperParameters hyperParameters = new HyperParameters(config); System.out.println("Start training with given hyper parameters:"); System.out.println("train.numComponents = "+hyperParameters.numComponents); System.out.println("train.penalty = "+hyperParameters.penalty); System.out.println("train.l1Ratio = "+hyperParameters.l1Ratio); System.out.println("train.iterations = "+hyperParameters.iterations); MultiLabelClfDataSet trainSet = loadTrainData(config); train(config, hyperParameters, trainSet); } System.out.println("============================================================"); } if (config.getBoolean("test")){ System.out.println("============================================================"); test(config); System.out.println("============================================================"); } } private static TuneResult tune(Config config, HyperParameters hyperParameters, MultiLabelClfDataSet trainSet, MultiLabelClfDataSet validSet) throws Exception{ CBM cbm = newCBM(config, trainSet, hyperParameters); EarlyStopper earlyStopper = loadNewEarlyStopper(config); ENCBMOptimizer optimizer = getOptimizer(config, hyperParameters, cbm, trainSet); if (config.getBoolean("train.randomInitialize")) { optimizer.randInitialize(); } else { optimizer.initialize(); } MultiLabelClassifier classifier; String predictTarget = config.getString("tune.targetMetric"); switch (predictTarget){ case "instance_set_accuracy": AccPredictor accPredictor = new AccPredictor(cbm); accPredictor.setComponentContributionThreshold(config.getDouble("predict.piThreshold")); classifier = accPredictor; break; case "instance_f1": PluginF1 pluginF1 = new PluginF1(cbm); List<MultiLabel> support = DataSetUtil.gatherMultiLabels(trainSet); pluginF1.setSupport(support); pluginF1.setPiThreshold(config.getDouble("predict.piThreshold")); classifier = pluginF1; break; case "instance_hamming_loss": MarginalPredictor marginalPredictor = new MarginalPredictor(cbm); marginalPredictor.setPiThreshold(config.getDouble("predict.piThreshold")); classifier = marginalPredictor; break; case "label_map": AccPredictor accPredictor2 = new AccPredictor(cbm); accPredictor2.setComponentContributionThreshold(config.getDouble("predict.piThreshold")); classifier = accPredictor2; break; default: throw new IllegalArgumentException("predictTarget should be instance_set_accuracy, instance_f1 or instance_hamming_loss"); } int interval = config.getInt("tune.monitorInterval"); for (int iter = 1; true; iter++){ if (VERBOSE){ System.out.println("iteration "+iter ); } optimizer.iterate(); if (iter%interval==0){ MLMeasures validMeasures = new MLMeasures(classifier,validSet); if (VERBOSE){ System.out.println("validation performance with "+predictTarget+" optimal predictor:"); System.out.println(validMeasures); } switch (predictTarget){ case "instance_set_accuracy": earlyStopper.add(iter,validMeasures.getInstanceAverage().getAccuracy()); break; case "instance_f1": earlyStopper.add(iter,validMeasures.getInstanceAverage().getF1()); break; case "instance_hamming_loss": earlyStopper.add(iter,validMeasures.getInstanceAverage().getHammingLoss()); break; case "label_map": List<MultiLabel> support = DataSetUtil.gatherMultiLabels(trainSet); double map = MAP.mapBySupport(cbm, validSet,support); earlyStopper.add(iter,map); break; default: throw new IllegalArgumentException("predictTarget should be instance_set_accuracy or instance_f1"); } if (earlyStopper.shouldStop()){ if (VERBOSE){ System.out.println("Early Stopper: the training should stop now!"); } break; } } } if (VERBOSE){ System.out.println("done!"); } hyperParameters.iterations = earlyStopper.getBestIteration(); TuneResult tuneResult = new TuneResult(); tuneResult.hyperParameters = hyperParameters; tuneResult.performance = earlyStopper.getBestValue(); return tuneResult; } private static void train(Config config, HyperParameters hyperParameters, MultiLabelClfDataSet trainSet) throws Exception{ List<Integer> unobservedLabels = DataSetUtil.unobservedLabels(trainSet); if (!unobservedLabels.isEmpty()){ System.out.println("The following labels do not actually appear in the training set and therefore cannot be learned:"); System.out.println(ListUtil.toSimpleString(unobservedLabels)); } String output = config.getString("output.dir"); FileUtils.writeStringToFile(new File(output,"unobserved_labels.txt"), ListUtil.toSimpleString(unobservedLabels)); StopWatch stopWatch = new StopWatch(); stopWatch.start(); CBM cbm = newCBM(config,trainSet, hyperParameters); ENCBMOptimizer optimizer = getOptimizer(config, hyperParameters, cbm, trainSet); System.out.println("Initializing the model"); if (config.getBoolean("train.randomInitialize")) { optimizer.randInitialize(); } else { optimizer.initialize(); } System.out.println("Initialization done"); for (int iter=1;iter<=hyperParameters.iterations;iter++){ System.out.println("Training progress: iteration "+iter ); optimizer.iterate(); } System.out.println("training done!"); System.out.println("time spent on training = "+stopWatch); Serialization.serialize(cbm, new File(output,"model")); List<MultiLabel> support = DataSetUtil.gatherMultiLabels(trainSet); Serialization.serialize(support, new File(output,"support")); // System.out.println("Making predictions on train set with 3 different predictors designed for different metrics:"); // reportAccPrediction(config, cbm, trainSet, "train"); // reportF1Prediction(config, cbm, trainSet, "train"); // reportHammingPrediction(config, cbm, trainSet, "train"); // reportGeneral(config, cbm, trainSet, "train"); } private static void test(Config config) throws Exception{ MultiLabelClfDataSet testSet = TRECFormat.loadMultiLabelClfDataSetAutoSparseSequential(config.getString("input.testData")); String output = config.getString("output.dir"); CBM cbm = (CBM) Serialization.deserialize(new File(output, "model")); System.out.println(); System.out.println("Making predictions on test set with 3 different predictors designed for different metrics:"); reportAccPrediction(config, cbm, testSet, "test"); reportF1Prediction(config, cbm, testSet, "test"); reportHammingPrediction(config, cbm, testSet, "test"); reportGeneral(config, cbm, testSet, "test"); System.out.println(); } private static void reportAccPrediction(Config config, CBM cbm, MultiLabelClfDataSet dataSet, String name) throws Exception{ System.out.println("============================================================"); System.out.println("Making predictions on "+name +" set with the instance set accuracy optimal predictor"); String output = config.getString("output.dir"); AccPredictor accPredictor = new AccPredictor(cbm); accPredictor.setComponentContributionThreshold(config.getDouble("predict.piThreshold")); StopWatch stopWatch = new StopWatch(); stopWatch.start(); MultiLabel[] predictions = accPredictor.predict(dataSet); System.out.println("time spent on prediction = "+stopWatch); MLMeasures mlMeasures = new MLMeasures(dataSet.getNumClasses(),dataSet.getMultiLabels(),predictions); System.out.println(name+" performance with the instance set accuracy optimal predictor"); System.out.println(mlMeasures); File performanceFile = Paths.get(output,name+"_predictions", "instance_accuracy_optimal","performance.txt").toFile(); FileUtils.writeStringToFile(performanceFile, mlMeasures.toString()); System.out.println(name+" performance is saved to "+performanceFile.toString()); // Here we do not use approximation double[] setProbs = IntStream.range(0, predictions.length).parallel(). mapToDouble(i->cbm.predictAssignmentProb(dataSet.getRow(i),predictions[i])).toArray(); File predictionFile = Paths.get(output,name+"_predictions", "instance_accuracy_optimal","predictions.txt").toFile(); try (BufferedWriter br = new BufferedWriter(new FileWriter(predictionFile))){ for (int i=0;i<dataSet.getNumDataPoints();i++){ br.write(predictions[i].toString()); br.write(":"); br.write(""+setProbs[i]); br.newLine(); } } System.out.println("predicted sets and their probabilities are saved to "+predictionFile.getAbsolutePath()); boolean individualPerformance = true; if (individualPerformance){ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(Paths.get(output,name+"_predictions", "instance_accuracy_optimal","individual_performance.json").toFile(),mlMeasures.getMacroAverage()); } System.out.println("============================================================"); } private static void reportF1Prediction(Config config, CBM cbm, MultiLabelClfDataSet dataSet, String name) throws Exception{ System.out.println("============================================================"); System.out.println("Making predictions on "+name+" set with the instance F1 optimal predictor"); String output = config.getString("output.dir"); PluginF1 pluginF1 = new PluginF1(cbm); List<MultiLabel> support = (List<MultiLabel>) Serialization.deserialize(new File(output, "support")); pluginF1.setSupport(support); pluginF1.setPiThreshold(config.getDouble("predict.piThreshold")); StopWatch stopWatch = new StopWatch(); stopWatch.start(); MultiLabel[] predictions = pluginF1.predict(dataSet); System.out.println("time spent on prediction = "+stopWatch); MLMeasures mlMeasures = new MLMeasures(dataSet.getNumClasses(),dataSet.getMultiLabels(),predictions); System.out.println(name+" performance with the instance F1 optimal predictor"); System.out.println(mlMeasures); File performanceFile = Paths.get(output,name+"_predictions", "instance_f1_optimal","performance.txt").toFile(); FileUtils.writeStringToFile(performanceFile, mlMeasures.toString()); System.out.println(name+" performance is saved to "+performanceFile.toString()); // Here we do not use approximation double[] setProbs = IntStream.range(0, predictions.length).parallel(). mapToDouble(i->cbm.predictAssignmentProb(dataSet.getRow(i),predictions[i])).toArray(); File predictionFile = Paths.get(output,name+"_predictions", "instance_f1_optimal","predictions.txt").toFile(); try (BufferedWriter br = new BufferedWriter(new FileWriter(predictionFile))){ for (int i=0;i<dataSet.getNumDataPoints();i++){ br.write(predictions[i].toString()); br.write(":"); br.write(""+setProbs[i]); br.newLine(); } } System.out.println("predicted sets and their probabilities are saved to "+predictionFile.getAbsolutePath()); boolean individualPerformance = true; if (individualPerformance){ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(Paths.get(output,name+"_predictions", "instance_f1_optimal","individual_performance.json").toFile(),mlMeasures.getMacroAverage()); } System.out.println("============================================================"); } private static void reportHammingPrediction(Config config, CBM cbm, MultiLabelClfDataSet dataSet, String name) throws Exception{ System.out.println("============================================================"); System.out.println("Making predictions on "+name+" set with the instance Hamming loss optimal predictor"); String output = config.getString("output.dir"); MarginalPredictor marginalPredictor = new MarginalPredictor(cbm); marginalPredictor.setPiThreshold(config.getDouble("predict.piThreshold")); StopWatch stopWatch = new StopWatch(); stopWatch.start(); MultiLabel[] predictions = marginalPredictor.predict(dataSet); System.out.println("time spent on prediction = "+stopWatch); MLMeasures mlMeasures = new MLMeasures(dataSet.getNumClasses(),dataSet.getMultiLabels(),predictions); System.out.println(name+" performance with the instance Hamming loss optimal predictor"); System.out.println(mlMeasures); File performanceFile = Paths.get(output,name+"_predictions", "instance_hamming_loss_optimal","performance.txt").toFile(); FileUtils.writeStringToFile(performanceFile, mlMeasures.toString()); System.out.println(name+" performance is saved to "+performanceFile.toString()); // Here we do not use approximation double[] setProbs = IntStream.range(0, predictions.length).parallel(). mapToDouble(i->cbm.predictAssignmentProb(dataSet.getRow(i),predictions[i])).toArray(); File predictionFile = Paths.get(output,name+"_predictions", "instance_hamming_loss_optimal","predictions.txt").toFile(); try (BufferedWriter br = new BufferedWriter(new FileWriter(predictionFile))){ for (int i=0;i<dataSet.getNumDataPoints();i++){ br.write(predictions[i].toString()); br.write(":"); br.write(""+setProbs[i]); br.newLine(); } } System.out.println("predicted sets and their probabilities are saved to "+predictionFile.getAbsolutePath()); boolean individualPerformance = true; if (individualPerformance){ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(Paths.get(output,name+"_predictions", "instance_hamming_loss_optimal","individual_performance.json").toFile(),mlMeasures.getMacroAverage()); } System.out.println("============================================================"); } private static void reportGeneral(Config config, CBM cbm, MultiLabelClfDataSet dataSet, String name) throws Exception{ System.out.println("============================================================"); System.out.println("computing other predictor-independent metrics"); System.out.println("label averaged MAP"); System.out.println(MAP.map(cbm, dataSet)); //todo // System.out.println("instance averaged MAP"); // System.out.println(MAP.instanceMAP(cbm, dataSet)); // System.out.println("global AP truncated at 30"); // System.out.println(AveragePrecision.globalAveragePrecisionTruncated(cbm, dataSet, 30)); String output = config.getString("output.dir"); File labelProbFile = Paths.get(output, name+"_predictions", "label_probabilities.txt").toFile(); double labelProbThreshold = config.getDouble("report.labelProbThreshold"); try (BufferedWriter br = new BufferedWriter(new FileWriter(labelProbFile))){ for (int i=0;i<dataSet.getNumDataPoints();i++){ br.write(CBMInspector.topLabels(cbm, dataSet.getRow(i), labelProbThreshold)); br.newLine(); } } System.out.println("individual label probabilities are saved to "+labelProbFile.getAbsolutePath()); List<Integer> unobservedLabels = Arrays.stream(FileUtils.readFileToString(new File(output,"unobserved_labels.txt")) .split(",")).map(s->s.trim()).filter(s->!s.isEmpty()).map(s->Integer.parseInt(s)).collect(Collectors.toList()); // Here we do not use approximation double[] logLikelihoods = IntStream.range(0, dataSet.getNumDataPoints()).parallel() .mapToDouble(i->cbm.predictLogAssignmentProb(dataSet.getRow(i),dataSet.getMultiLabels()[i])) .toArray(); double average = IntStream.range(0, dataSet.getNumDataPoints()).filter(i->!containsNovelClass(dataSet.getMultiLabels()[i],unobservedLabels)) .mapToDouble(i->logLikelihoods[i]).average().getAsDouble(); File logLikelihoodFile = Paths.get(output, name+"_predictions", "ground_truth_log_likelihood.txt").toFile(); FileUtils.writeStringToFile(logLikelihoodFile, PrintUtil.toMutipleLines(logLikelihoods)); System.out.println("individual log likelihood of the "+name +" ground truth label set is written to "+logLikelihoodFile.getAbsolutePath()); System.out.println("average log likelihood of the "+name+" ground truth label sets = "+average); if (!unobservedLabels.isEmpty()&&name.equals("test")){ System.out.println("This is computed by ignoring test instances with new labels unobserved during training"); System.out.println("The following labels do not actually appear in the training set and therefore cannot be learned:"); System.out.println(ListUtil.toSimpleString(unobservedLabels)); } } private static ENCBMOptimizer getOptimizer(Config config, HyperParameters hyperParameters, CBM cbm, MultiLabelClfDataSet trainSet){ ENCBMOptimizer optimizer = new ENCBMOptimizer(cbm, trainSet); optimizer.setLineSearch(config.getBoolean("train.elasticnet.lineSearch")); optimizer.setRegularizationBinary(hyperParameters.penalty); optimizer.setRegularizationMultiClass(hyperParameters.penalty); optimizer.setL1RatioBinary(hyperParameters.l1Ratio); optimizer.setL1RatioMultiClass(hyperParameters.l1Ratio); optimizer.setActiveSet(config.getBoolean("train.elasticnet.activeSet")); optimizer.setBinaryUpdatesPerIter(config.getInt("train.updatesPerIteration")); optimizer.setMulticlassUpdatesPerIter(config.getInt("train.updatesPerIteration")); optimizer.setSkipDataThreshold(config.getDouble("train.skipDataThreshold")); optimizer.setSkipLabelThreshold(config.getDouble("train.skipLabelThreshold")); return optimizer; } private static CBM newCBM(Config config, MultiLabelClfDataSet trainSet, HyperParameters hyperParameters){ CBM cbm; cbm = CBM.getBuilder() .setNumClasses(trainSet.getNumClasses()) .setNumFeatures(trainSet.getNumFeatures()) .setNumComponents(hyperParameters.numComponents) .setMultiClassClassifierType("elasticnet") .setBinaryClassifierType("elasticnet") .build(); cbm.setLabelTranslator(trainSet.getLabelTranslator()); String allowEmpty = config.getString("predict.allowEmpty"); switch (allowEmpty){ case "true": cbm.setAllowEmpty(true); break; case "false": cbm.setAllowEmpty(false); break; case "auto": Set<MultiLabel> seen = DataSetUtil.gatherMultiLabels(trainSet).stream().collect(Collectors.toSet()); MultiLabel empty = new MultiLabel(); if (seen.contains(empty)){ cbm.setAllowEmpty(true); if (VERBOSE){ System.out.println("training set contains empty labels, automatically set predict.allowEmpty = true"); } } else { cbm.setAllowEmpty(false); if (VERBOSE){ System.out.println("training set does not contain empty labels, automatically set predict.allowEmpty = false"); } } break; default: throw new IllegalArgumentException("unknown value for predict.allowEmpty"); } return cbm; } private static EarlyStopper loadNewEarlyStopper(Config config){ String earlyStopMetric = config.getString("tune.targetMetric"); int patience = config.getInt("tune.earlyStop.patience"); EarlyStopper.Goal earlyStopGoal = null; switch (earlyStopMetric){ case "instance_set_accuracy": earlyStopGoal = EarlyStopper.Goal.MAXIMIZE; break; case "instance_f1": earlyStopGoal = EarlyStopper.Goal.MAXIMIZE; break; case "instance_hamming_loss": earlyStopGoal = EarlyStopper.Goal.MINIMIZE; break; case "label_map": earlyStopGoal = EarlyStopper.Goal.MAXIMIZE; break; default: throw new IllegalArgumentException("unsupported tune.targetMetric "+earlyStopMetric); } EarlyStopper earlyStopper = new EarlyStopper(earlyStopGoal,patience); earlyStopper.setMinimumIterations(config.getInt("tune.earlyStop.minIterations")); return earlyStopper; } private static List<MultiLabelClfDataSet> loadTrainValidData(Config config) throws Exception{ String validPath = config.getString("input.validData"); List<MultiLabelClfDataSet> datasets = new ArrayList<>(); MultiLabelClfDataSet trainSet = TRECFormat.loadMultiLabelClfDataSetAutoSparseSequential(config.getString("input.trainData")); if (validPath.isEmpty()){ System.out.println("No external validation data is provided. Use random 20% of the training data for validation."); Pair<MultiLabelClfDataSet, MultiLabelClfDataSet> dataSetPair = DataSetUtil.splitToTrainValidation(trainSet,0.8); MultiLabelClfDataSet subTrain = dataSetPair.getFirst(); MultiLabelClfDataSet validSet = dataSetPair.getSecond(); datasets.add(subTrain); datasets.add(validSet); } else { MultiLabelClfDataSet validSet = TRECFormat.loadMultiLabelClfDataSetAutoSparseSequential(config.getString("input.validData")); datasets.add(trainSet); datasets.add(validSet); } return datasets; } private static MultiLabelClfDataSet loadTrainData(Config config) throws Exception{ String validPath = config.getString("input.validData"); MultiLabelClfDataSet trainSet = TRECFormat.loadMultiLabelClfDataSetAutoSparseSequential(config.getString("input.trainData")); if (validPath.isEmpty()||!config.getBoolean("train.useValidData")){ return trainSet; } else { MultiLabelClfDataSet validSet = TRECFormat.loadMultiLabelClfDataSetAutoSparseSequential(config.getString("input.validData")); return DataSetUtil.concatenateByRow(trainSet, validSet); } } private static class HyperParameters{ double penalty; double l1Ratio; int iterations; int numComponents; HyperParameters() { } HyperParameters(Config config) { penalty = config.getDouble("train.penalty"); l1Ratio = config.getDouble("train.l1Ratio"); iterations = config.getInt("train.iterations"); numComponents = config.getInt("train.numComponents"); } Config asConfig(){ Config config = new Config(); config.setDouble("train.penalty", penalty); config.setDouble("train.l1Ratio", l1Ratio); config.setInt("train.iterations", iterations); config.setInt("train.numComponents", numComponents); return config; } } private static class TuneResult{ HyperParameters hyperParameters; double performance; } private static boolean containsNovelClass(MultiLabel multiLabel, List<Integer> novelLabels){ for (int l:novelLabels){ if (multiLabel.matchClass(l)){ return true; } } return false; } }
package com.thoughtworks.xstream; import java.awt.font.TextAttribute; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.NotActiveException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.BitSet; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import com.thoughtworks.xstream.alias.ClassMapper; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.converters.DataHolder; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.basic.BigDecimalConverter; import com.thoughtworks.xstream.converters.basic.BigIntegerConverter; import com.thoughtworks.xstream.converters.basic.BooleanConverter; import com.thoughtworks.xstream.converters.basic.ByteConverter; import com.thoughtworks.xstream.converters.basic.CharConverter; import com.thoughtworks.xstream.converters.basic.DateConverter; import com.thoughtworks.xstream.converters.basic.DoubleConverter; import com.thoughtworks.xstream.converters.basic.FloatConverter; import com.thoughtworks.xstream.converters.basic.IntConverter; import com.thoughtworks.xstream.converters.basic.LongConverter; import com.thoughtworks.xstream.converters.basic.NullConverter; import com.thoughtworks.xstream.converters.basic.ShortConverter; import com.thoughtworks.xstream.converters.basic.StringBufferConverter; import com.thoughtworks.xstream.converters.basic.StringConverter; import com.thoughtworks.xstream.converters.basic.URLConverter; import com.thoughtworks.xstream.converters.collections.ArrayConverter; import com.thoughtworks.xstream.converters.collections.BitSetConverter; import com.thoughtworks.xstream.converters.collections.CharArrayConverter; import com.thoughtworks.xstream.converters.collections.CollectionConverter; import com.thoughtworks.xstream.converters.collections.MapConverter; import com.thoughtworks.xstream.converters.collections.PropertiesConverter; import com.thoughtworks.xstream.converters.collections.TreeMapConverter; import com.thoughtworks.xstream.converters.collections.TreeSetConverter; import com.thoughtworks.xstream.converters.extended.ColorConverter; import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter; import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; import com.thoughtworks.xstream.converters.extended.FileConverter; import com.thoughtworks.xstream.converters.extended.FontConverter; import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter; import com.thoughtworks.xstream.converters.extended.JavaClassConverter; import com.thoughtworks.xstream.converters.extended.JavaMethodConverter; import com.thoughtworks.xstream.converters.extended.LocaleConverter; import com.thoughtworks.xstream.converters.extended.SqlDateConverter; import com.thoughtworks.xstream.converters.extended.SqlTimeConverter; import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter; import com.thoughtworks.xstream.converters.extended.TextAttributeConverter; import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker; import com.thoughtworks.xstream.converters.reflection.SerializableConverter; import com.thoughtworks.xstream.core.BaseException; import com.thoughtworks.xstream.core.DefaultConverterLookup; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.MapBackedDataHolder; import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy; import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy; import com.thoughtworks.xstream.core.TreeMarshallingStrategy; import com.thoughtworks.xstream.core.util.ClassLoaderReference; import com.thoughtworks.xstream.core.util.CompositeClassLoader; import com.thoughtworks.xstream.core.util.CustomObjectInputStream; import com.thoughtworks.xstream.core.util.CustomObjectOutputStream; import com.thoughtworks.xstream.io.HierarchicalStreamDriver; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.StatefulWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.mapper.ArrayMapper; import com.thoughtworks.xstream.mapper.AttributeAliasingMapper; import com.thoughtworks.xstream.mapper.AttributeMapper; import com.thoughtworks.xstream.mapper.CachingMapper; import com.thoughtworks.xstream.mapper.ClassAliasingMapper; import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper; import com.thoughtworks.xstream.mapper.DefaultMapper; import com.thoughtworks.xstream.mapper.DynamicProxyMapper; import com.thoughtworks.xstream.mapper.EnumMapper; import com.thoughtworks.xstream.mapper.FieldAliasingMapper; import com.thoughtworks.xstream.mapper.ImmutableTypesMapper; import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.thoughtworks.xstream.mapper.OuterClassMapper; import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper; /** * Simple facade to XStream library, a Java-XML serialization tool. <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * XStream xstream = new XStream(); * String xml = xstream.toXML(myObject); // serialize to XML * Object myObject2 = xstream.fromXML(xml); // deserialize from XML * </pre> * * </blockquote> * <hr> * <p/> * <h3>Aliasing classes</h3> * <p/> * <p> * To create shorter XML, you can specify aliases for classes using the <code>alias()</code> * method. For example, you can shorten all occurences of element * <code>&lt;com.blah.MyThing&gt;</code> to <code>&lt;my-thing&gt;</code> by registering an * alias for the class. * <p> * <hr> * <blockquote> * * <pre> * xstream.alias(&quot;my-thing&quot;, MyThing.class); * </pre> * * </blockquote> * <hr> * <p/> * <h3>Converters</h3> * <p/> * <p> * XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each * of which acts as a strategy for converting a particular type of class to XML and back again. Out * of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc) * and collections (Map, List, Set, Properties, etc). For other objects reflection is used to * serialize each field recursively. * </p> * <p/> * <p> * Extra converters can be registered using the <code>registerConverter()</code> method. Some * non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended} * package and you can create your own by implementing the * {@link com.thoughtworks.xstream.converters.Converter} interface. * </p> * <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.registerConverter(new SqlTimestampConverter()); * xstream.registerConverter(new DynamicProxyConverter()); * </pre> * * </blockquote> * <hr> * <p> * The default converter, ie the converter which will be used if no other registered converter is * suitable, can be configured by either one of the constructors or can be changed using the * <code>changeDefaultConverter()</code> method. If not set, XStream uses * {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the initial default * converter. * </p> * <p/> * <p> * <hr> * <b>Example</b><blockquote> * * <pre> * xstream.changeDefaultConverter(new ACustomDefaultConverter()); * </pre> * * </blockquote> * <hr> * <p/> * <h3>Object graphs</h3> * <p/> * <p> * XStream has support for object graphs; a deserialized object graph will keep references intact, * including circular references. * </p> * <p/> * <p> * XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using * <code>setMode()</code>: * </p> * <p/> <table border="1"> * <tr> * <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td> * <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML * with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td> * <td>Uses XPath absolute references to signify duplicate * references. This produces XML with the least clutter.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td> * <td>Uses ID references to signify duplicate references. In some scenarios, such as when using * hand-written XML, this is easier to work with.</td> * </tr> * <tr> * <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td> * <td>This disables object graph support and treats the object structure like a tree. Duplicate * references are treated as two seperate objects and circular references cause an exception. This * is slightly faster and uses less memory than the other two modes.</td> * </tr> * </table> * <h3>Thread safety</h3> * <p> * The XStream instance is thread-safe. That is, once the XStream instance has been created and * configured, it may be shared across multiple threads allowing objects to be * serialized/deserialized concurrently. * <h3>Implicit collections</h3> * <p/> * <p> * To avoid the need for special tags for collections, you can define implicit collections using one * of the <code>addImplicitCollection</code> methods. * </p> * * @author Joe Walnes * @author J&ouml;rg Schaible * @author Mauro Talevi * @author Guilherme Silveira */ public class XStream { // CAUTION: The sequence of the fields is intentional for an optimal XML output of a // self-serializaion! private ReflectionProvider reflectionProvider; private HierarchicalStreamDriver hierarchicalStreamDriver; private ClassLoaderReference classLoaderReference; private MarshallingStrategy marshallingStrategy; private Mapper mapper; private DefaultConverterLookup converterLookup; private ClassAliasingMapper classAliasingMapper; private FieldAliasingMapper fieldAliasingMapper; private AttributeAliasingMapper attributeAliasingMapper; private AttributeMapper attributeMapper; private DefaultImplementationsMapper defaultImplementationsMapper; private ImmutableTypesMapper immutableTypesMapper; private ImplicitCollectionMapper implicitCollectionMapper; private transient JVM jvm = new JVM(); public static final int NO_REFERENCES = 1001; public static final int ID_REFERENCES = 1002; public static final int XPATH_RELATIVE_REFERENCES = 1003; public static final int XPATH_ABSOLUTE_REFERENCES = 1004; /** * @deprecated since 1.2, use {@link #XPATH_RELATIVE_REFERENCES} or * {@link #XPATH_ABSOLUTE_REFERENCES} instead. */ public static final int XPATH_REFERENCES = XPATH_RELATIVE_REFERENCES; public static final int PRIORITY_VERY_HIGH = 10000; public static final int PRIORITY_NORMAL = 0; public static final int PRIORITY_LOW = -10; public static final int PRIORITY_VERY_LOW = -20; /** * Constructs a default XStream. The instance will use the {@link XppDriver} as default and tries to determin the best * match for the {@link ReflectionProvider} on its own. * * @throws InitializationException in case of an initialization problem */ public XStream() { this(null, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link ReflectionProvider}. The instance will use the {@link XppDriver} as default. * * @throws InitializationException in case of an initialization problem */ public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, (Mapper)null, new XppDriver()); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will tries to determin the best * match for the {@link ReflectionProvider} on its own. * * @throws InitializationException in case of an initialization problem */ public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, (Mapper)null, hierarchicalStreamDriver); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}. * * @throws InitializationException in case of an initialization problem */ public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver); } /** * @deprecated As of 1.2, use * {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} */ public XStream( ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver) { this(reflectionProvider, (Mapper)classMapper, driver); } /** * @deprecated As of 1.2, use * {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} and * register classAttributeIdentifier as alias */ public XStream( ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver, String classAttributeIdentifier) { this(reflectionProvider, (Mapper)classMapper, driver); aliasAttribute(classAttributeIdentifier, "class"); } /** * Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}. * * @throws InitializationException in case of an initialization problem */ public XStream( ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { jvm = new JVM(); if (reflectionProvider == null) { reflectionProvider = jvm.bestReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader()); this.mapper = mapper == null ? buildMapper() : mapper; this.converterLookup = new DefaultConverterLookup(this.mapper); setupMappers(); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_RELATIVE_REFERENCES); } private Mapper buildMapper() { Mapper mapper = new DefaultMapper(classLoaderReference); if ( useXStream11XmlFriendlyMapper() ){ mapper = new XStream11XmlFriendlyMapper(mapper); } mapper = new ClassAliasingMapper(mapper); mapper = new FieldAliasingMapper(mapper); mapper = new AttributeAliasingMapper(mapper); mapper = new AttributeMapper(mapper); mapper = new ImplicitCollectionMapper(mapper); if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) { mapper = buildMapperDynamically( "com.thoughtworks.xstream.mapper.CGLIBMapper", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new DynamicProxyMapper(mapper); if (JVM.is15()) { mapper = new EnumMapper(mapper); } mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); mapper = new ImmutableTypesMapper(mapper); mapper = wrapMapper((MapperWrapper)mapper); mapper = new CachingMapper(mapper); return mapper; } private Mapper buildMapperDynamically( String className, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); return (Mapper)constructor.newInstance(constructorParamValues); } catch (Exception e) { throw new InitializationException("Could not instatiate mapper : " + className, e); } } protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } protected boolean useXStream11XmlFriendlyMapper() { return false; } private void setupMappers() { classAliasingMapper = (ClassAliasingMapper)this.mapper .lookupMapperOfType(ClassAliasingMapper.class); fieldAliasingMapper = (FieldAliasingMapper)this.mapper .lookupMapperOfType(FieldAliasingMapper.class); attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class); attributeAliasingMapper = (AttributeAliasingMapper)this.mapper .lookupMapperOfType(AttributeAliasingMapper.class); implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper .lookupMapperOfType(ImplicitCollectionMapper.class); defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper .lookupMapperOfType(DefaultImplementationsMapper.class); immutableTypesMapper = (ImmutableTypesMapper)this.mapper .lookupMapperOfType(ImmutableTypesMapper.class); // should use ctor, but converterLookup is not yet initialized instantiating this mapper if (attributeMapper != null) { attributeMapper.setConverterLookup(converterLookup); } } protected void setupAliases() { if (classAliasingMapper == null) { return; } alias("null", Mapper.Null.class); alias("int", Integer.class); alias("float", Float.class); alias("double", Double.class); alias("long", Long.class); alias("short", Short.class); alias("char", Character.class); alias("byte", Byte.class); alias("boolean", Boolean.class); alias("number", Number.class); alias("object", Object.class); alias("big-int", BigInteger.class); alias("big-decimal", BigDecimal.class); alias("string-buffer", StringBuffer.class); alias("string", String.class); alias("java-class", Class.class); alias("method", Method.class); alias("constructor", Constructor.class); alias("date", Date.class); alias("url", URL.class); alias("bit-set", BitSet.class); alias("map", Map.class); alias("entry", Map.Entry.class); alias("properties", Properties.class); alias("list", List.class); alias("set", Set.class); alias("linked-list", LinkedList.class); alias("vector", Vector.class); alias("tree-map", TreeMap.class); alias("tree-set", TreeSet.class); alias("hashtable", Hashtable.class); if(jvm.supportsAWT()) { // Instantiating these two classes starts the AWT system, which is undesirable. Calling // loadClass ensures a reference to the class is found but they are not instantiated. alias("awt-color", jvm.loadClass("java.awt.Color")); alias("awt-font", jvm.loadClass("java.awt.Font")); alias("awt-text-attribute", TextAttribute.class); } if(jvm.supportsSQL()) { alias("sql-timestamp", Timestamp.class); alias("sql-time", Time.class); alias("sql-date", java.sql.Date.class); } alias("file", File.class); alias("locale", Locale.class); alias("gregorian-calendar", Calendar.class); // since jdk 1.4 included, but previously available as separate package ... Class type = jvm.loadClass("javax.security.auth.Subject"); if (type != null) { alias("auth-subject", type); } if (JVM.is14()) { alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap")); alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet")); alias("trace", jvm.loadClass("java.lang.StackTraceElement")); alias("currency", jvm.loadClass("java.util.Currency")); aliasType("charset", jvm.loadClass("java.nio.charset.Charset")); } if (JVM.is15()) { alias("enum-set", jvm.loadClass("java.util.EnumSet")); alias("enum-map", jvm.loadClass("java.util.EnumMap")); } } protected void setupDefaultImplementations() { if (defaultImplementationsMapper == null) { return; } addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } protected void setupConverters() { // use different ReflectionProvider depending on JDK final ReflectionConverter reflectionConverter; if (JVM.is15()) { Class annotationProvider = jvm .loadClass("com.thoughtworks.xstream.annotations.AnnotationProvider"); dynamicallyRegisterConverter( "com.thoughtworks.xstream.annotations.AnnotationReflectionConverter", PRIORITY_VERY_LOW, new Class[]{ Mapper.class, ReflectionProvider.class, annotationProvider}, new Object[]{ mapper, reflectionProvider, reflectionProvider.newInstance(annotationProvider)}); reflectionConverter = (ReflectionConverter)converterLookup .lookupConverterForType(Object.class); } else { reflectionConverter = new ReflectionConverter(mapper, reflectionProvider); registerConverter(reflectionConverter, PRIORITY_VERY_LOW); } registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW); registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW); registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter(new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new MapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); if(jvm.supportsSQL()) { registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); } registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL); if(jvm.supportsAWT()) { registerConverter(new FontConverter(), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); // since jdk 1.4 included, but previously available as separate package ... if (jvm.loadClass("javax.security.auth.Subject") != null) { dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.SubjectConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); } if (JVM.is14()) { // late bound converters - allows XStream to be compiled on earlier JDKs dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.ThrowableConverter", PRIORITY_NORMAL, new Class[]{Converter.class}, new Object[]{reflectionConverter}); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL, new Class[]{Converter.class}, new Object[]{reflectionConverter}); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.extended.CharsetConverter", PRIORITY_NORMAL, null, null); } if (JVM.is15()) { // late bound converters - allows XStream to be compiled on earlier JDKs dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL, null, null); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); } if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) { dynamicallyRegisterConverter( "com.thoughtworks.xstream.converters.reflection.CGLIBEnhancedConverter", PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class}, new Object[]{mapper, reflectionProvider}); } registerConverter(new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL); } private void dynamicallyRegisterConverter( String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Object instance = constructor.newInstance(constructorParamValues); if (instance instanceof Converter) { registerConverter((Converter)instance, priority); } else if (instance instanceof SingleValueConverter) { registerConverter((SingleValueConverter)instance, priority); } } catch (Exception e) { throw new InitializationException("Could not instatiate converter : " + className, e); } } protected void setupImmutableTypes() { if (immutableTypesMapper == null) { return; } // primitives are always immutable addImmutableType(boolean.class); addImmutableType(Boolean.class); addImmutableType(byte.class); addImmutableType(Byte.class); addImmutableType(char.class); addImmutableType(Character.class); addImmutableType(double.class); addImmutableType(Double.class); addImmutableType(float.class); addImmutableType(Float.class); addImmutableType(int.class); addImmutableType(Integer.class); addImmutableType(long.class); addImmutableType(Long.class); addImmutableType(short.class); addImmutableType(Short.class); // additional types addImmutableType(Mapper.Null.class); addImmutableType(BigDecimal.class); addImmutableType(BigInteger.class); addImmutableType(String.class); addImmutableType(URL.class); addImmutableType(File.class); addImmutableType(Class.class); if(jvm.supportsAWT()) { addImmutableType(TextAttribute.class); } if (JVM.is14()) { // late bound types - allows XStream to be compiled on earlier JDKs Class type = jvm.loadClass("com.thoughtworks.xstream.converters.extended.CharsetConverter"); addImmutableType(type); } } public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } /** * Serialize an object to a pretty-printed XML String. * @throws BaseException if the object cannot be serialized */ public String toXML(Object obj) { Writer writer = new StringWriter(); toXML(obj, writer); return writer.toString(); } /** * Serialize an object to the given Writer as pretty-printed XML. * @throws BaseException if the object cannot be serialized */ public void toXML(Object obj, Writer out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); marshal(obj, writer); writer.flush(); } /** * Serialize an object to the given OutputStream as pretty-printed XML. * @throws BaseException if the object cannot be serialized */ public void toXML(Object obj, OutputStream out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); marshal(obj, writer); writer.flush(); } /** * Serialize and object to a hierarchical data structure (such as XML). * @throws BaseException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } /** * Serialize and object to a hierarchical data structure (such as XML). * * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If * not present, XStream shall create one lazily as needed. * @throws BaseException if the object cannot be serialized */ public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder); } /** * Deserialize an object from an XML String. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } /** * Deserialize an object from an XML Reader. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(Reader xml) { return unmarshal(hierarchicalStreamDriver.createReader(xml), null); } /** * Deserialize an object from an XML InputStream. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(InputStream input) { return unmarshal(hierarchicalStreamDriver.createReader(input), null); } /** * Deserialize an object from an XML String, populating the fields of the given root object * instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } /** * Deserialize an object from an XML Reader, populating the fields of the given root object * instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from an XML InputStream, populating the fields of the given root object * instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object fromXML(InputStream xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } /** * Deserialize an object from a hierarchical data structure (such as XML). * @throws BaseException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } /** * Deserialize an object from a hierarchical data structure (such as XML), populating the fields * of the given root object instead of instantiating a new one. * @throws BaseException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } /** * Deserialize an object from a hierarchical data structure (such as XML). * * @param root If present, the passed in object will have its fields populated, as opposed to * XStream creating a new instance. * @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If * not present, XStream shall create one lazily as needed. * @throws BaseException if the object cannot be deserialized */ public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type) { if (classAliasingMapper == null) { throw new InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addClassAlias(name, type); } /** * Alias a type to a shorter name to be used in XML elements. * Any class that is assignable to this type will be aliased to the same name. * * @param name Short name * @param type Type to be aliased * @since 1.2 * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void aliasType(String name, Class type) { if (classAliasingMapper == null) { throw new InitializationException("No " + ClassAliasingMapper.class.getName() + " available"); } classAliasingMapper.addTypeAlias(name, type); } /** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @param defaultImplementation Default implementation of type to use if no other specified. * @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } /** * Create an alias for a field name. * * @param alias the alias itself * @param type the type that declares the field * @param fieldName the name of the field * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void aliasField(String alias, Class type, String fieldName) { if (fieldAliasingMapper == null) { throw new InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.addFieldAlias(alias, type, fieldName); } /** * Create an alias for an attribute * * @param alias the alias itself * @param attributeName the name of the attribute * @throws InitializationException if no {@link AttributeAliasingMapper} is available */ public void aliasAttribute(String alias, String attributeName) { if (attributeAliasingMapper == null) { throw new InitializationException("No " + AttributeAliasingMapper.class.getName() + " available"); } attributeAliasingMapper.addAliasFor(attributeName, alias); } /** * Create an alias for an attribute. * * @param configurableClass the type where the attribute is defined * @param attributeName the name of the attribute * @param alias the alias itself * @throws InitializationException if no {@link AttributeAliasingMapper} is available */ public void aliasAttribute(Class configurableClass, String attributeName, String alias) { if (attributeAliasingMapper == null) { throw new InitializationException("No " + AttributeAliasingMapper.class.getName() + " available"); } attributeAliasingMapper.addAliasFor(configurableClass, attributeName, alias); } /** * Use an XML attribute for a field or a specific type. * * @param fieldName the name of the field * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(String fieldName, Class type) { if (attributeMapper == null) { throw new InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(fieldName, type); } /** * Use an XML attribute for a field of a specific type. * * @param fieldName the name of the field * @param definedIn the Class containing such field * @throws InitializationException if no {@link AttributeMapper} is available * @since upcoming */ public void useAttributeFor(Class definedIn, String fieldName) { if (attributeMapper == null) { throw new InitializationException("No " + AttributeMapper.class.getName() + " available"); } try { final Field field = definedIn.getDeclaredField(fieldName); attributeMapper.addAttributeFor(field); } catch (SecurityException e) { throw new InitializationException("Unable to access field " + fieldName + "@" + definedIn.getName()); } catch (NoSuchFieldException e) { throw new InitializationException("Unable to find field " + fieldName + "@" + definedIn.getName()); } } /** * Use an XML attribute for an arbitrary type. * * @param type the Class of the type to be rendered as XML attribute * @throws InitializationException if no {@link AttributeMapper} is available * @since 1.2 */ public void useAttributeFor(Class type) { if (attributeMapper == null) { throw new InitializationException("No " + AttributeMapper.class.getName() + " available"); } attributeMapper.addAttributeFor(type); } /** * Associate a default implementation of a class with an object. Whenever XStream encounters an * instance of this type, it will use the default implementation instead. For example, * java.util.ArrayList is the default implementation of java.util.List. * * @param defaultImplementation * @param ofType * @throws InitializationException if no {@link DefaultImplementationsMapper} is available */ public void addDefaultImplementation(Class defaultImplementation, Class ofType) { if (defaultImplementationsMapper == null) { throw new InitializationException("No " + DefaultImplementationsMapper.class.getName() + " available"); } defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } /** * Add immutable types. The value of the instances of these types will always be written into * the stream even if they appear multiple times. * @throws InitializationException if no {@link ImmutableTypesMapper} is available */ public void addImmutableType(Class type) { if (immutableTypesMapper == null) { throw new InitializationException("No " + ImmutableTypesMapper.class.getName() + " available"); } immutableTypesMapper.addImmutableType(type); } public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(Converter converter, int priority) { converterLookup.registerConverter(converter, priority); } public void registerConverter(SingleValueConverter converter) { registerConverter(converter, PRIORITY_NORMAL); } public void registerConverter(SingleValueConverter converter, int priority) { converterLookup.registerConverter(new SingleValueConverterWrapper(converter), priority); } /** * @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance * @deprecated As of 1.2, use {@link #getMapper} */ public ClassMapper getClassMapper() { if (mapper instanceof ClassMapper) { return (ClassMapper)mapper; } else { return (ClassMapper)Proxy.newProxyInstance(getClassLoader(), new Class[]{ClassMapper.class}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(mapper, args); } }); } } /** * Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}. * * @return the mapper * @since 1.2 */ public Mapper getMapper() { return mapper; } /** * Retrieve the {@link ReflectionProvider} in use. * * @return the mapper * @since 1.2.1 */ public ReflectionProvider getReflectionProvider() { return reflectionProvider; } public ConverterLookup getConverterLookup() { return converterLookup; } public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE)); break; case XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE)); break; default: throw new IllegalArgumentException("Unknown mode : " + mode); } } /** * Adds a default implicit collection which is used for any unmapped xml tag. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be an * <code>java.util.ArrayList</code>. */ public void addImplicitCollection(Class ownerType, String fieldName) { if (implicitCollectionMapper == null) { throw new InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, null, Object.class); } /** * Adds implicit collection which is used for all items of the given itemType. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be an * <code>java.util.ArrayList</code>. * @param itemType type of the items to be part of this collection. * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { if (implicitCollectionMapper == null) { throw new InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, null, itemType); } /** * Adds implicit collection which is used for all items of the given element name defined by * itemFieldName. * * @param ownerType class owning the implicit collection * @param fieldName name of the field in the ownerType. This field must be an * <code>java.util.ArrayList</code>. * @param itemFieldName element name of the implicit collection * @param itemType item type to be aliases be the itemFieldName * @throws InitializationException if no {@link ImplicitCollectionMapper} is available */ public void addImplicitCollection( Class ownerType, String fieldName, String itemFieldName, Class itemType) { if (implicitCollectionMapper == null) { throw new InitializationException("No " + ImplicitCollectionMapper.class.getName() + " available"); } implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType); } public DataHolder newDataHolder() { return new MapBackedDataHolder(); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * To change the name of the root element (from &lt;object-stream&gt;), use * {@link #createObjectOutputStream(java.io.Writer, String)}. * </p> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, "object-stream"); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName); } /** * Creates an ObjectOutputStream that serializes a stream of objects to the writer using * XStream. * <p> * Because an ObjectOutputStream can contain multiple items and XML only allows a single root * node, the stream must be written inside an enclosing node. * </p> * <p> * It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be * incomplete. * </p> * <h3>Example</h3> * * <pre> * ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, &quot;things&quot;); * out.writeInt(123); * out.writeObject(&quot;Hello&quot;); * out.writeObject(someObject) * out.close(); * </pre> * * @param writer The writer to serialize the objects to. * @param rootNodeName The name of the root node enclosing the stream of objects. * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @since 1.0.3 */ public ObjectOutputStream createObjectOutputStream( final HierarchicalStreamWriter writer, String rootNodeName) throws IOException { final StatefulWriter statefulWriter = new StatefulWriter(writer); statefulWriter.startNode(rootNodeName, null); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(Object object) { marshal(object, statefulWriter); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException("not in call to writeObject"); } public void flush() { statefulWriter.flush(); } public void close() { if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) { statefulWriter.endNode(); statefulWriter.close(); } } }); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using * XStream. * * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader) * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } /** * Creates an ObjectInputStream that deserializes a stream of objects from a reader using * XStream. * <h3>Example</h3> * * <pre> * ObjectInputStream in = xstream.createObjectOutputStream(aReader); * int a = out.readInt(); * Object b = out.readObject(); * Object c = out.readObject(); * </pre> * * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String) * @since 1.0.3 */ public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); Object result = unmarshal(reader); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException("not in call to readObject"); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException("not in call to readObject"); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException("stream inactive"); } public void close() { reader.close(); } }); } /** * Change the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } /** * Change the ClassLoader XStream uses to load classes. * * @since 1.1.1 */ public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } /** * Prevents a field from being serialized. To omit a field you must always provide the declaring * type and not necessarily the type that is converted. * * @since 1.1.3 * @throws InitializationException if no {@link FieldAliasingMapper} is available */ public void omitField(Class type, String fieldName) { if (fieldAliasingMapper == null) { throw new InitializationException("No " + FieldAliasingMapper.class.getName() + " available"); } fieldAliasingMapper.omitField(type, fieldName); } public static class InitializationException extends BaseException { public InitializationException(String message, Throwable cause) { super(message, cause); } public InitializationException(String message) { super(message); } } private Object readResolve() { jvm = new JVM(); return this; } }
package com.dmdirc.addons.parser_twitter.api; import java.io.BufferedReader; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import oauth.signpost.OAuth; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.basic.DefaultOAuthConsumer; import oauth.signpost.basic.DefaultOAuthProvider; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.signature.SignatureMethod; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.NoRouteToHostException; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.LinkedList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Implementation of the twitter API for DMDirc. * * @author shane */ public class TwitterAPI { /** OAuth Consumer */ private OAuthConsumer consumer; /** OAuth Provider */ private OAuthProvider provider; /** Have we signed anything yet? */ private boolean hasSigned = false; /** Login Username for this twitter API. */ private final String myLoginUsername; /** * Display Username for this twitter API. * (The same as myLoginUsername unless autoAt is enabled) */ private final String myDisplayUsername; /** Password for this twitter API if oauth isn't available. */ private String myPassword; /** Cache of users. */ final Map<String, TwitterUser> userCache = new HashMap<String, TwitterUser>(); /** Cache of user IDs to screen names. */ final Map<Long, String> userIDMap = new HashMap<Long, String>(); /** Cache of statuses. */ final Map<Long, TwitterStatus> statusCache = new HashMap<Long, TwitterStatus>(); /** API Allowed status */ private APIAllowed allowed = APIAllowed.UNKNOWN; /** How many API calls have we made since the last reset? */ private int usedCalls = 0; /** API reset time. */ private long resetTime = 0; /** Twitter Token */ private String token = ""; /** Twitter Token Secret */ private String tokenSecret = ""; /** Last input to the API. */ private String apiInput = ""; /** Last output from the API. */ private String apiOutput = ""; /** List of TwitterErrorHandlers */ private final List<TwitterErrorHandler> errorHandlers = new LinkedList<TwitterErrorHandler>(); /** List of TwitterRawHandlers */ private final List<TwitterRawHandler> rawHandlers = new LinkedList<TwitterRawHandler>(); /** What address should API calls be made to? */ private final String apiAddress; /** Should we use OAuth? */ private boolean useOAuth = true; /** Should we use ssl? */ private boolean useSSL = false; /** Should we enable debug? */ private boolean debug = false; /** Should we use the versioned API? */ private boolean useAPIVersion = false; /** * What version of the API should we try to use? * If useAPIVersion is false this is irrelevent, otherwise method calls will * try to use this version of the API, otherwise falling back to any lower * version they know how to use. */ private int apiVersion = 1; /** Source to try and use for non-oauth status updates. */ private String mySource = "web"; /** Should we prepend an @ to all user names? */ private boolean autoAt; /** * Create a non-OAuth using TwitterAPI. * * @param username Username to use. * @param password Password to use. * @param apiAddress * @param useAPIVersion * @param apiVersion */ public TwitterAPI(final String username, final String password, final String apiAddress, final boolean useAPIVersion, final int apiVersion, final boolean autoAt) { this(username, password, apiAddress, "", "", "", "", "", useAPIVersion, apiVersion, autoAt); useOAuth = false; } /** * Create a new Twitter API for the given user. * * @param username Username to use. * @param password Password to use. (if using OAuth then "" is sufficient, if specified then it will be used as a fallback if OAuth is unavailable) * @param apiAddress Address to send API Requests to. (No protocol, eg "api.twitter.com") * @param oauthAddress Path to OAuth. (default: apiAddress+"/oauth"); * @param consumerKey If using OAuth, the consumerKey to use. * @param consumerSecret If using OAuth, the consumerSecret to use. * @param token If using OAuth, the token to use. * @param tokenSecret If using OAuth, the tokenSecret to use. * @param useAPIVersion Should we use the versioned api? * @param apiVersion What version of the api should we use? (0 == Unversioned, -1 == maximum version known) * @param autoAt Should '@' signs be prepended to user names? */ public TwitterAPI(final String username, final String password, final String apiAddress, final String oauthAddress, final String consumerKey, final String consumerSecret, final String token, final String tokenSecret, final boolean useAPIVersion, final int apiVersion, final boolean autoAt) { this.myLoginUsername = username; this.apiAddress = apiAddress.replaceAll("/+$", ""); this.myPassword = password; this.autoAt = autoAt; this.myDisplayUsername = (autoAt ? "@" : "") + myLoginUsername; if (this.apiAddress.isEmpty() && myLoginUsername.isEmpty()) { return; } if (!consumerKey.isEmpty() && !consumerSecret.isEmpty()) { consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1); final String thisOauthAddress = ((useSSL) ? "https" : "http") + "://" + ((oauthAddress == null || oauthAddress.isEmpty()) ? apiAddress.replaceAll("/+$", "") + "/oauth" : oauthAddress.replaceAll("/+$", "")); provider = new DefaultOAuthProvider(consumer, thisOauthAddress+"/request_token", thisOauthAddress+"/access_token", thisOauthAddress+"/authorize"); this.token = token; this.tokenSecret = tokenSecret; try { useOAuth = !(getOAuthURL().isEmpty()); } catch (TwitterRuntimeException tre) { useOAuth = false; } } else { useOAuth = false; } this.useAPIVersion = useAPIVersion && (apiVersion != 0); if (apiVersion > 0) { this.apiVersion = apiVersion; } // if we are allowed, isAllowed will automatically call getUser() to // update the cache with our own user object. if (!isAllowed(true)) { // If not, add a temporary one. // It will be replaced as soon as the allowed status is changed to // true by isAlowed(). updateUser(new TwitterUser(this, myLoginUsername)); } } /** * Get the source used in status updates when not using OAuth. * * @return The source used in status updates when not using OAuth. */ public String getSource() { return mySource; } /** * Set the source used in status updates when using OAuth. * * @param source The source to use in status updates when not using OAuth. */ public void setSource(final String source) { this.mySource = source; } /** * Get the address to send API Calls to, assuming version 1 of the API. * * @param apiCall call we want to make * @return URL To use! */ private String getURL(final String apiCall) { return getURL(apiCall, 1); } /** * Get the address to send API Calls to. * * @param apiCall call we want to make * @param version API Version to use. (or 0 to make an unversioned call) * @return URL To use! */ private String getURL(final String apiCall, final int version) { if (!useAPIVersion || version == 0) { return (useSSL ? "https" : "http") + "://" + apiAddress + "/" + apiCall + ".xml"; } else { return (useSSL ? "https" : "http") + "://" + apiAddress + "/" + version + "/" + apiCall + ".xml"; } } /** * Add a new error handler. * * @param handler handler to add. */ public void addErrorHandler(final TwitterErrorHandler handler) { synchronized (errorHandlers) { errorHandlers.add(handler); } } /** * Remove an error handler. * * @param handler handler to remove. */ public void delErrorHandler(final TwitterErrorHandler handler) { synchronized (errorHandlers) { errorHandlers.remove(handler); } } /** * Clear error handlers. */ public void clearErrorHandlers() { synchronized (errorHandlers) { errorHandlers.clear(); } } /** * Handle an error from twitter. * * @param t The throwable that caused the error. * @param source Source of exception. * @param twitterInput The input to the API that caused this error. * @param twitterOutput The output from the API that caused this error. */ private void handleError(final Throwable t, final String source, final String twitterInput, final String twitterOutput) { handleError(t, source, twitterInput, twitterOutput, ""); } /** * Handle an error from twitter. * * @param t The throwable that caused the error. * @param source Source of exception. * @param twitterInput The input to the API that caused this error. * @param twitterOutput The output from the API that caused this error. * @param message If more information should be relayed to the user, it comes here */ private void handleError(final Throwable t, final String source, final String twitterInput, final String twitterOutput, final String message) { synchronized (errorHandlers) { for (TwitterErrorHandler eh : errorHandlers) { eh.handleTwitterError(this, t, source, twitterInput, twitterOutput, message); } } } /** * Add a new raw handler. * * @param handler handler to add. */ public void addRawHandler(final TwitterRawHandler handler) { synchronized (rawHandlers) { rawHandlers.add(handler); } } /** * Remove a raw handler. * * @param handler handler to remove. */ public void delRawHandler(final TwitterRawHandler handler) { synchronized (rawHandlers) { rawHandlers.remove(handler); } } /** * Clear raw handlers. */ public void clearRawHandlers() { synchronized (rawHandlers) { rawHandlers.clear(); } } /** * Handle input from twitter. * * @param raw The raw input from twitter. */ private void handleRawInput(final String raw) { synchronized (rawHandlers) { for (TwitterRawHandler rh : rawHandlers) { rh.handleRawTwitterInput(this, raw); } } } /** * Handle output to twitter. * * @param raw The raw output to twitter */ private void handleRawOutput(final String raw) { synchronized (rawHandlers) { for (TwitterRawHandler rh : rawHandlers) { rh.handleRawTwitterOutput(this, raw); } } } /** * Are we using autoAt? * * @return are we using autoAt? */ public boolean autoAt() { return autoAt; } /** * Set if we should use autoAt or not. * * @param autoAt Should we use autoAt? */ /* public void setAutoAt(final boolean autoAt) { this.autoAt = autoAt; } */ /** * Is debugging enabled? * * @return Is debugging enabled? */ public boolean isDebug() { return debug; } /** * Set if debugging is enabled. * * @param debug if debugging is enabled. */ public void setDebug(final boolean debug) { this.debug = debug; } /** * Are we using oauth? * * @return are we usin oauth? */ public boolean useOAuth() { return useOAuth; } /** * Set if we should use oauth or not. * * @param useOAuth Should we use oauth? */ public void setUseOAuth(final boolean useOAuth) { this.useOAuth = useOAuth; } /** * Are we using the versioned API? * * @return are we using the versioned API? */ public boolean useAPIVersion() { return useAPIVersion; } /** * Set if we should use the versioned API or not. * * This should be called after setApiVersion * * @param useAPIVersion Should we use the versioned API or not? */ public void setUseAPIVersion(final boolean useAPIVersion) { this.useAPIVersion = useAPIVersion; setApiVersion(apiVersion()); // Reset the API Version } /** * What version of the API are we using? * * @return The version of the API we are using (0 for none) */ public int apiVersion() { return apiVersion; } /** * Set the api version to try and use. * Methods will use the given api if support has been added, or the latest * version below that they know. * If this method is not called, then the latest version is assumed * * Changing this causes us to force a check to isAllowed() if apiversioning * is enabled * * @param apiVersion What API Version to use. */ public void setApiVersion(final int apiVersion) { this.apiVersion = apiVersion; if (useAPIVersion) { // if we are allowed, isAllowed will automatically call getUser() to // update the cache with our own user object. if (!isAllowed(true)) { // If not, add a temporary one. // It will be replaced as soon as the allowed status is changed to // true by isAlowed(). updateUser(new TwitterUser(this, myLoginUsername)); } } } /** * Set the account password. * * @param password new account password */ public void setPassword(final String password) { this.myPassword = password; } /** * Gets the twitter access token if known. * * @return Access Token */ public String getToken() { return token; } /** * Gets the twitter access token secret if known. * * @return Access Token Secret */ public String getTokenSecret() { return tokenSecret; } /** * Attempt to sign the given connection. * If not using OAuth, we just authenticate the connection instead. * * @param connection Connection to sign. */ private void signURL(final HttpURLConnection connection) { if (useOAuth) { if (!hasSigned) { if (getToken().isEmpty() || getTokenSecret().isEmpty()) { return; } consumer.setTokenWithSecret(getToken(), getTokenSecret()); hasSigned = true; } try { consumer.sign(connection); } catch (OAuthMessageSignerException ex) { handleError(ex, "(1) signURL", apiInput, apiOutput, "Unable to sign URL, are we authorised to use this account?"); } catch (OAuthExpectationFailedException ex) { handleError(ex, "(2) signURL", apiInput, apiOutput, "Unable to sign URL, are we authorised to use this account?"); } } else { // final String userpassword = myUsername + ":" + myPassword; // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); // String encodedAuthorization = enc.encode(userpassword.getBytes()); final String encodedAuthorization = b64encode(myLoginUsername + ":" + myPassword); connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization); } } private String b64encode(final String string) { final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; final StringBuilder encoded = new StringBuilder(); byte[] stringArray; try { stringArray = string.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { stringArray = string.getBytes(); } // determine how many padding bytes to add to the output final int paddingCount = (3 - (stringArray.length % 3)) % 3; // add any necessary padding to the input final byte[] padded = new byte[stringArray.length + paddingCount]; System.arraycopy(stringArray, 0, padded, 0, stringArray.length); // process 3 bytes at a time, churning out 4 output bytes for (int i = 0; i < padded.length; i += 3) { int j = (padded[i] << 16) + (padded[i + 1] << 8) + padded[i + 2]; encoded.append(base64code.charAt((j >> 18) & 0x3f)); encoded.append(base64code.charAt((j >> 12) & 0x3f)); encoded.append(base64code.charAt((j >> 6) & 0x3f)); encoded.append(base64code.charAt(j & 0x3f)); } // replace encoded padding nulls with "=" return encoded.substring(0, encoded.length() - paddingCount) + "==".substring(0, paddingCount); } /** * Parse the given string to a long without throwing an exception. * If an exception was raised, default will be used. * * @param string String to parse. * @param fallback Default on failure. * @return Long from string */ public static Long parseLong(final String string, final long fallback) { try { return Long.parseLong(string); } catch (NumberFormatException nfe) { return fallback; } } /** * Parse the given string as a twitter time to a long. * If parsing fails, then the fallback will be used. * * @param string String to parse. * @param fallback Default on failure. * @return Long from string */ public static Long timeStringToLong(final String string, final long fallback) { try { return (new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy").parse(string)).getTime(); } catch (ParseException ex) { return fallback; } } /** * Parse the given string to a boolean, returns true for "true", "yes" or "1" * * @param string String to parse. * @return Boolean from string */ public static boolean parseBoolean(final String string) { return string.equalsIgnoreCase("true") || string.equalsIgnoreCase("yes") || string.equalsIgnoreCase("1"); } /** * Get the contents of the given node from an element. * If node doesn't exist, fallbcak will be returned. * * @param element Element to look at * @param string Node to get content from. * @param fallback Default on failure. * @return Long from string */ public static String getElementContents(final Element element, final String string, final String fallback) { if (element != null) { final NodeList nl = element.getElementsByTagName(string); if (nl != null && nl.getLength() > 0) { return nl.item(0).getTextContent(); } } return fallback; } /** * Get the XML for the given address. * * @param address Address to get XML for. * @return Document object for this xml. */ private XMLResponse getXML(final String address) { try { final URL url = new URL(address); return getXML((HttpURLConnection) url.openConnection()); } catch (MalformedURLException ex) { if (isDebug()) { handleError(ex, "* (1) getXML: "+address, apiInput, apiOutput); } } catch (IOException ex) { if (isDebug()) { handleError(ex, "* (2) getXML: "+address, apiInput, apiOutput); } } return new XMLResponse(null, null); } /** * Get the XML for the given address, using a POST request. * * @param address Address to get XML for. * @return Document object for this xml. */ private XMLResponse postXML(final String address) { return postXML(address, ""); } /** * Get the XML for the given address, using a POST request. * * @param address Address to get XML for. * @param params Params to post. * @return Document object for this xml. */ private XMLResponse postXML(final String address, final String params) { try { final URL url = new URL(address + (params.isEmpty() ? "" : "?" + params)); return postXML((HttpURLConnection) url.openConnection()); } catch (MalformedURLException ex) { if (isDebug()) { handleError(ex, "* (1) postXML: "+address+" | "+params, apiInput, apiOutput); } } catch (IOException ex) { if (isDebug()) { handleError(ex, "* (2) postXML: "+address+" | "+params, apiInput, apiOutput); } } return new XMLResponse(null, null); } /** * Get the XML for the given UNSIGNED HttpURLConnection object, using a * POST request. * * @param request HttpURLConnection to get XML for. * @return Document object for this xml. */ private XMLResponse postXML(final HttpURLConnection request) { try { request.setRequestMethod("POST"); request.setRequestProperty("Content-Length", "0"); request.setUseCaches(false); } catch (ProtocolException ex) { if (isDebug()) { handleError(ex, "* (3) postXML: "+request.getURL(), apiInput, apiOutput); } } return getXML(request); } /** * Check if a connection can be made to the api. * * MalformedURLException or NoRouteToHostException cause this to return * false, otherwise true is sent. * * If any other IOException is thrown this is consided a success and true is * returned. * * If an IOException is thrown this will be sent via handleError when * debugigng is enabled. * * @return True if connecting to the api works, else false. */ public boolean checkConnection() { try { final URL url = new URL(getURL("account/verify_credentials")); final HttpURLConnection request = (HttpURLConnection) url.openConnection(); signURL(request); request.connect(); return true; } catch (MalformedURLException ex) { return false; } catch (NoRouteToHostException ex) { return false; } catch (IOException ex) { if (isDebug()) { handleError(ex, "* (1) checkConnection", "", ""); } return true; } } /** * Get the XML for the given UNSIGNED HttpURLConnection object. * * @param request HttpURLConnection to get XML for. * @return Document object for this xml. */ private XMLResponse getXML(final HttpURLConnection request) { if (request.getURL().getHost().isEmpty()) { return new XMLResponse(request, null); } if (resetTime > 0 && resetTime <= System.currentTimeMillis()) { usedCalls = 0; resetTime = System.currentTimeMillis() + 3600000; } usedCalls++; apiInput = request.getURL().toString(); handleRawOutput(apiInput); BufferedReader in = null; try { signURL(request); request.setConnectTimeout(5000); request.setReadTimeout(5000); request.connect(); in = new BufferedReader(new InputStreamReader(request.getInputStream())); } catch (IOException ex) { if (isDebug()) { handleError(ex, "* (4) getXML: "+request.getURL(), apiInput, apiOutput); } if (request.getErrorStream() != null) { in = new BufferedReader(new InputStreamReader(request.getErrorStream())); } else { return new XMLResponse(request, null); } } final StringBuilder xml = new StringBuilder(); boolean incomplete = false; String line; synchronized (this) { try { do { line = in.readLine(); if (line != null) { xml.append("\n"); xml.append(line); } } while (line != null); apiOutput = xml.toString().trim(); } catch (IOException ex) { apiOutput = xml.toString().trim() + "\n ... Incomplete!"; incomplete = true; if (isDebug()) { handleError(ex, "* (5) getXML", apiInput, apiOutput); } } finally { try { in.close(); } catch (IOException ex) { } } } handleRawInput(xml.toString() + (incomplete ? "\n ... Incomplete!" : "")); int responseCode; try { responseCode = request.getResponseCode(); if (responseCode != 200) { if (isDebug()) { handleError(null, "* (6) getXML", apiInput, apiOutput, "("+request.getResponseCode()+") "+request.getResponseMessage()); } else if (responseCode >= 500 && responseCode < 600) { handleError(null, "(6) getXML", apiInput, apiOutput, "("+request.getResponseCode()+") "+request.getResponseMessage()); } } } catch (IOException ioe) { responseCode = 0; if (isDebug()) { handleError(ioe, "* (7) getXML", apiInput, apiOutput, "Unable to get response code."); } } try { final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final Document doc = db.parse(new ByteArrayInputStream(apiOutput.getBytes())); final XMLResponse response = new XMLResponse(request, doc); if (response.isError()) { handleError(null, "(8) getXML", apiInput, apiOutput, response.getError()); } return response; } catch (SAXException ex) { if (isDebug()) { handleError(ex, "* (9) getXML", apiInput, apiOutput); } } catch (ParserConfigurationException ex) { if (isDebug()) { handleError(ex, "* (10) getXML", apiInput, apiOutput); } } catch (IOException ex) { if (isDebug()) { handleError(ex, "* (11) getXML", apiInput, apiOutput); } } return new XMLResponse(request, null); } /** * Remove the cache of the status object for the given status. * * @param status */ protected void uncacheStatus(final TwitterStatus status) { if (status == null) { return; } synchronized (statusCache) { statusCache.remove(status.getID()); } } /** * Remove the cache of the user object for the given user. * * @param user */ protected void uncacheUser(final TwitterUser user) { if (user == null) { return; } synchronized (userCache) { userCache.remove(user.getScreenName().toLowerCase()); userIDMap.remove(user.getID()); } } /** * Update the user object for the given user, if the user ins't know already * this will add them to the cache. * * @param user */ protected void updateUser(final TwitterUser user) { updateUser(user.getScreenName(), user); } /** * Update the user object for the given user, if the user ins't know already * this will add them to the cache. * * If the username doesn't match the screen name for the user, then the * cached object for "username" will be deleted and a new cached object * will be added from the users screen name. * * @param username * @param user */ protected void updateUser(final String username, final TwitterUser user) { if (user == null) { return; } synchronized (userCache) { if (!username.equalsIgnoreCase(user.getScreenName())) { userCache.remove(username.toLowerCase()); } userCache.put(user.getScreenName().toLowerCase(), user); userIDMap.put(user.getID(), user.getScreenName().toLowerCase()); } // TODO: TwitterStatus and TwitterMessage objects should be informed // about updates. } /** * Get a user object for the given user. * * @param username * @return User object for the requested user. */ public TwitterUser getUser(final String username) { return getUser(username, false); } /** * Get a cached user object for the given user. * * @param username * @return User object for the requested user. */ public TwitterUser getCachedUser(final String username) { synchronized (userCache) { if (userCache.containsKey(username.toLowerCase())) { return userCache.get(username.toLowerCase()); } else { return null; } } } /** * Get a user object for the given user. * * @param username * @param force Force an update of the cache? * @return User object for the requested user. */ public TwitterUser getUser(final String username, final boolean force) { TwitterUser user = getCachedUser(username); if (user == null || force) { if (username.equalsIgnoreCase(myDisplayUsername) && !isAllowed()) { user = new TwitterUser(this, myLoginUsername, -1, "", true); } else { final XMLResponse doc = getXML(getURL("users/show")+"?screen_name="+username); if (doc.isGood()) { user = new TwitterUser(this, doc.getDocumentElement()); } else { user = null; } } if (user != null) { updateUser(user); } } return user; } /** * Update the status object for the given status, if the status isn't known * already this will add them to the cache. * * @param status */ protected void updateStatus(final TwitterStatus status) { if (status == null) { return; } synchronized (statusCache) { statusCache.put(status.getID(), status); } } /** * Get a status object for the given id. * * @param id * @return Status object for the requested id. */ public TwitterStatus getStatus(final long id) { return getStatus(id, false); } /** * Get a cached status object for the given id. * * @param id * @return status object for the requested id. */ public TwitterStatus getCachedStatus(final long id) { synchronized (statusCache) { if (statusCache.containsKey(id)) { return statusCache.get(id); } else { return null; } } } /** * Get a status object for the given id. * * @param id * @param force Force an update of the cache? * @return status object for the requested id. */ public TwitterStatus getStatus(final long id, final boolean force) { TwitterStatus status = getCachedStatus(id); if (status == null || force) { final XMLResponse doc = getXML(getURL("statuses/show/"+id)); if (doc.isGood()) { status = new TwitterStatus(this, doc.getDocumentElement()); } else { status = null; } updateStatus(status); } return status; } /** * Prune the status cache of statuses older than the given time. * This should be done periodically depending on how many statuses you see. * * @param time */ public void pruneStatusCache(final long time) { synchronized (statusCache) { final Map<Long, TwitterStatus> current = new HashMap<Long, TwitterStatus>(statusCache); for (Long item : current.keySet()) { if (current.get(item).getTime() < time) { statusCache.remove(item); } } } } /** * Send a direct message to the given user * * @param target Target user. * @param message Message to send. * @return true if the message was sent, else false. */ public boolean newDirectMessage(final String target, final String message) { try { final XMLResponse doc = postXML(getURL("direct_messages/new"), "screen_name=" + target + "&text=" + URLEncoder.encode(message, "utf-8")); if (doc.isGood()) { new TwitterMessage(this, doc.getDocumentElement()); return true; } } catch (UnsupportedEncodingException ex) { if (isDebug()) { handleError(ex, "* (1) newDirectMessage: "+target+" | "+message, apiInput, apiOutput); } } return false; } /** * What port are we using? * * @return port for api connections. */ public int getPort() { return 80; } /** * Get a List of TwitterStatus Objects for this user. * * @param lastUserTimelineId * @return a List of TwitterStatus Objects for this user. */ public List<TwitterStatus> getUserTimeline(final long lastUserTimelineId) { final List<TwitterStatus> result = new ArrayList<TwitterStatus>(); final XMLResponse doc = getXML(getURL("statuses/user_timeline")+"?since_id="+lastUserTimelineId+"&count=20"); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("status"); for (int i = 0; i < nodes.getLength(); i++) { result.add(new TwitterStatus(this, nodes.item(i))); } } return result; } /** * Get a list of TwitterUsers who we are following. * * @return A list of TwitterUsers who we are following. */ public List<TwitterUser> getFriends() { final List<TwitterUser> result = new ArrayList<TwitterUser>(); long cursor = -1; int count = 0; while (cursor != 0) { final XMLResponse doc = getXML(getURL("statuses/friends") + "?cursor=" + cursor); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("user"); for (int i = 0; i < nodes.getLength(); i++) { final TwitterUser user = new TwitterUser(this, nodes.item(i)); updateUser(user); result.add(user); } cursor = parseLong(getElementContents(doc.getDocumentElement(), "next_cursor", "0"), 0); count = 0; } else if (count++ > 1) { break; // If we get an error twice in a row, abort. } } return result; } /** * Get a list of people we have blocked.. * * @return A list of people we have blocked. */ public List<TwitterUser> getBlocked() { final List<TwitterUser> result = new ArrayList<TwitterUser>(); final XMLResponse doc = getXML(getURL("blocks/blocking")); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("user"); for (int i = 0; i < nodes.getLength(); i++) { final TwitterUser user = new TwitterUser(this, nodes.item(i)); uncacheUser(user); result.add(user); } } return result; } /** * Get a list of IDs of people who are following us. * * @return A list of IDs of people who are following us. */ public List<Long> getFollowers() { final List<Long> result = new ArrayList<Long>(); long cursor = -1; int count = 0; while (cursor != 0) { final XMLResponse doc = getXML(getURL("followers/ids") + "?cursor=" + cursor); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("id"); for (int i = 0; i < nodes.getLength(); i++) { final Element element = (Element)nodes.item(i); final Long id = parseLong(element.getTextContent(), -1); result.add(id); if (userIDMap.containsKey(id)) { final TwitterUser user = getCachedUser(userIDMap.get(id)); user.setFollowingUs(true); } } cursor = parseLong(getElementContents(doc.getDocumentElement(), "next_cursor", "0"), 0); count = 0; } else if (count++ > 1) { break; // If we get an error twice in a row, abort. } } return result; } /** * Get the messages sent for us that are later than the given ID. * * @param lastReplyId Last reply we know of. * @return The messages sent for us that are later than the given ID. */ public List<TwitterStatus> getReplies(final long lastReplyId) { return getReplies(lastReplyId, 20); } /** * Get the messages sent for us that are later than the given ID. * * @param lastReplyId Last reply we know of. * @param count How many replies to get * @return The messages sent for us that are later than the given ID. */ public List<TwitterStatus> getReplies(final long lastReplyId, final int count) { final List<TwitterStatus> result = new ArrayList<TwitterStatus>(); final XMLResponse doc = getXML(getURL("statuses/mentions")+"?since_id="+lastReplyId+"&count="+count); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("status"); for (int i = 0; i < nodes.getLength(); i++) { result.add(new TwitterStatus(this, nodes.item(i))); } } return result; } /** * Get the messages sent by friends that are later than the given ID. * * @param lastTimelineId Last reply we know of. * @return The messages sent by friends that are later than the given ID. */ public List<TwitterStatus> getFriendsTimeline(final long lastTimelineId) { return getFriendsTimeline(lastTimelineId, 20); } /** * Get the messages sent by friends that are later than the given ID. * * @param lastTimelineId Last reply we know of. * @param count How many statuses to get * @return The messages sent by friends that are later than the given ID. */ public List<TwitterStatus> getFriendsTimeline(final long lastTimelineId, final int count) { final List<TwitterStatus> result = new ArrayList<TwitterStatus>(); final XMLResponse doc = getXML(getURL("statuses/home_timeline")+"?since_id="+lastTimelineId+"&count="+count); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("status"); for (int i = 0; i < nodes.getLength(); i++) { result.add(new TwitterStatus(this, nodes.item(i))); } } return result; } /** * Get the direct messages sent to us that are later than the given ID. * * @param lastDirectMessageId Last reply we know of. * @return The direct messages sent to us that are later than the given ID. */ public List<TwitterMessage> getDirectMessages(final long lastDirectMessageId) { return getDirectMessages(lastDirectMessageId, 20); } /** * Get the direct messages sent to us that are later than the given ID. * * @param lastDirectMessageId Last reply we know of. * @param count How many messages to request at a time * @return The direct messages sent to us that are later than the given ID. */ public List<TwitterMessage> getDirectMessages(final long lastDirectMessageId, final int count) { final List<TwitterMessage> result = new ArrayList<TwitterMessage>(); final XMLResponse doc = getXML(getURL("direct_messages")+"?since_id="+lastDirectMessageId+"&count="+count); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("direct_message"); for (int i = 0; i < nodes.getLength(); i++) { result.add(new TwitterMessage(this, nodes.item(i))); } } return result; } /** * Get the direct messages sent by us that are later than the given ID. * * @param lastDirectMessageId Last reply we know of. * @return The direct messages sent by us that are later than the given ID. */ public List<TwitterMessage> getSentDirectMessages(final long lastDirectMessageId) { return getSentDirectMessages(lastDirectMessageId, 20); } /** * Get the direct messages sent by us that are later than the given ID. * * @param lastDirectMessageId Last reply we know of. * @param count How many messages to request at a time * @return The direct messages sent by us that are later than the given ID. */ public List<TwitterMessage> getSentDirectMessages(final long lastDirectMessageId, final int count) { final List<TwitterMessage> result = new ArrayList<TwitterMessage>(); final XMLResponse doc = getXML(getURL("direct_messages/sent")+"?since_id="+lastDirectMessageId+"&count="+count); if (doc.isGood()) { final NodeList nodes = doc.getElementsByTagName("direct_message"); for (int i = 0; i < nodes.getLength(); i++) { result.add(new TwitterMessage(this, nodes.item(i))); } } return result; } /** * Set your status to the given TwitterStatus * * @param status Status to send * @param id id to reply to or -1 * @return True if status was updated ok. */ public boolean setStatus(final String status, final Long id) { try { final StringBuilder params = new StringBuilder("status="); params.append(URLEncoder.encode(status, "utf-8")); if (id >= 0) { params.append("&in_reply_to_status_id="+Long.toString(id)); } if (!useOAuth) { params.append("&source="+URLEncoder.encode(mySource, "utf-8")); } final XMLResponse doc = postXML(getURL("statuses/update"), params.toString()); if (doc.getResponseCode() == 200) { if (doc.isGood()) { new TwitterStatus(this, doc.getDocumentElement()); } return true; } } catch (UnsupportedEncodingException ex) { if (isDebug()) { handleError(ex, "* (1) setStatus: "+status+" | "+id, apiInput, apiOutput); } } catch (IOException ex) { if (isDebug()) { handleError(ex, "* (2) setStatus: "+status+" | "+id, apiInput, apiOutput); } } return false; } /** * Retweet the given status * * @param status Status to retweet * @return True if status was retweeted ok. */ public boolean retweetStatus(final TwitterStatus status) { final XMLResponse doc = postXML(getURL("statuses/retweet/"+status.getID())); if (doc.getResponseCode() == 200) { if (doc.isGood()) { new TwitterStatus(this, doc.getDocumentElement()); } return true; } return false; } /** * Delete the given status * * @param status Status to delete * @return True if status was deleted ok. */ public boolean deleteStatus(final TwitterStatus status) { final XMLResponse doc = postXML(getURL("statuses/destroy/"+status.getID())); if (doc.getResponseCode() == 200) { if (doc.isGood()) { final TwitterStatus deletedStatus = new TwitterStatus(this, doc.getDocumentElement()); uncacheStatus(deletedStatus); // Get our previous tweet. getUser(myDisplayUsername, true); } return true; } return false; } /** * Get the number of api calls remaining. * * @return Long[4] containting API calls limit information. * - 0 is remaning calls * - 1 is total calls per hour * - 2 is the time (in milliseconds) that the limit is reset. * - 3 is the estimated number of api calls we have made since * the last reset. */ public Long[] getRemainingApiCalls() { final XMLResponse doc = getXML(getURL("account/rate_limit_status")); // The call we just made doesn't count, so remove it from the count. usedCalls if (doc.isGood()) { final Element element = doc.getDocumentElement(); final long remaining = parseLong(getElementContents(element, "remaining-hits", ""), -1); final long total = parseLong(getElementContents(element, "hourly-limit", ""), -1); // laconica does this wrong :( so support both. final String resetTimeString = getElementContents(element, "reset-time-in-seconds", getElementContents(element, "reset_time_in_seconds", "0")); resetTime = 1000 * parseLong(resetTimeString, -1); return new Long[]{remaining, total, resetTime, (long)usedCalls}; } else { return new Long[]{0L, 0L, System.currentTimeMillis(), (long)usedCalls}; } } /** * How many calls have we used since reset? * * @return calls used since reset. */ public int getUsedCalls() { return usedCalls; } /** * Get the URL the user must visit in order to authorize DMDirc. * * @return the URL the user must visit in order to authorize DMDirc. * @throws TwitterRuntimeException if there is a problem with OAuth.* */ public String getOAuthURL() throws TwitterRuntimeException { try { return provider.retrieveRequestToken(OAuth.OUT_OF_BAND); } catch (OAuthMessageSignerException ex) { if (myPassword.isEmpty()) { if (isDebug()) { handleError(ex, "* (1) getOAuthURL", apiInput, apiOutput); } throw new TwitterRuntimeException(ex.getMessage(), ex); } } catch (OAuthNotAuthorizedException ex) { if (myPassword.isEmpty()) { if (isDebug()) { handleError(ex, "* (2) getOAuthURL", apiInput, apiOutput); } throw new TwitterRuntimeException(ex.getMessage(), ex); } } catch (OAuthExpectationFailedException ex) { if (myPassword.isEmpty()) { if (isDebug()) { handleError(ex, "* (3) getOAuthURL", apiInput, apiOutput); } throw new TwitterRuntimeException(ex.getMessage(), ex); } } catch (OAuthCommunicationException ex) { if (myPassword.isEmpty()) { if (isDebug()) { handleError(ex, "* (4) getOAuthURL", apiInput, apiOutput); } throw new TwitterRuntimeException(ex.getMessage(), ex); } } useOAuth = false; return ""; } /** * Get the URL the user must visit in order to authorize DMDirc. * * @param pin Pin for OAuth * @throws TwitterException if there is a problem with OAuth. */ public void setAccessPin(final String pin) throws TwitterException { if (!useOAuth) { return; } try { provider.retrieveAccessToken(pin); token = consumer.getToken(); tokenSecret = consumer.getTokenSecret(); } catch (OAuthMessageSignerException ex) { if (isDebug()) { handleError(ex, "* (1) setAccessPin: "+pin, apiInput, apiOutput); } throw new TwitterException(ex.getMessage(), ex); } catch (OAuthNotAuthorizedException ex) { if (isDebug()) { handleError(ex, "* (2) setAccessPin: "+pin, apiInput, apiOutput); } throw new TwitterException(ex.getMessage(), ex); } catch (OAuthExpectationFailedException ex) { if (isDebug()) { handleError(ex, "* (3) setAccessPin: "+pin, apiInput, apiOutput); } throw new TwitterException(ex.getMessage(), ex); } catch (OAuthCommunicationException ex) { if (isDebug()) { handleError(ex, "* (4) setAccessPin: "+pin, apiInput, apiOutput); } throw new TwitterException(ex.getMessage(), ex); } } /** * Get the login username for this Twitter API * * @return login Username for this twitter API */ public String getLoginUsername() { return myLoginUsername; } /** * Get the display username for this Twitter API * * @return display Username for this twitter API */ public String getDisplayUsername() { return myDisplayUsername; } /** * Have we been authorised to use this account? * * @return true if we have been authorised, else false. */ public boolean isAllowed() { return isAllowed(false); } /** * Have we been authorised to use this account? * Forcing a recheck may use up an API call. * * @param forceRecheck force a recheck to see if we are allowed. * @return true if we have been authorised, else false. */ public boolean isAllowed(final boolean forceRecheck) { if (myLoginUsername.isEmpty()) { return false; } if ((useOAuth && (getToken().isEmpty() || getTokenSecret().isEmpty())) || (!useOAuth && myPassword.isEmpty())) { return false; } if (allowed == allowed.UNKNOWN || forceRecheck) { try { final URL url = new URL(getURL("account/verify_credentials")); final HttpURLConnection request = (HttpURLConnection) url.openConnection(); final XMLResponse doc = getXML(request); allowed = (request.getResponseCode() == 200) ? allowed.TRUE : allowed.FALSE; if (doc.isGood() && allowed.getBooleanValue()) { final TwitterUser user = new TwitterUser(this, doc.getDocumentElement()); updateUser(user); getRemainingApiCalls(); } } catch (IOException ex) { if (isDebug()) { handleError(ex, "* (1) isAllowed", apiInput, apiOutput); } allowed = allowed.FALSE; } } return allowed.getBooleanValue(); } /** * Add the user with the given screen name as a friend. * * @param name name to add * @return The user just added */ public TwitterUser addFriend(final String name) { try { final XMLResponse doc = postXML(getURL("friendships/create"), "screen_name=" + URLEncoder.encode(name, "utf-8")); if (doc.isGood()) { final TwitterUser user = new TwitterUser(this, doc.getDocumentElement()); updateUser(user); return user; } } catch (UnsupportedEncodingException ex) { if (isDebug()) { handleError(ex, "* (1) addFriend: "+name, apiInput, apiOutput); } } return null; } /** * Remove the user with the given screen name as a friend. * * @param name name to remove * @return The user just deleted */ public TwitterUser delFriend(final String name) { try { final XMLResponse doc = postXML(getURL("friendships/destroy"), "screen_name=" + URLEncoder.encode(name, "utf-8")); if (doc.isGood()) { final TwitterUser user = new TwitterUser(this, doc.getDocumentElement()); uncacheUser(user); return user; } } catch (UnsupportedEncodingException ex) { if (isDebug()) { handleError(ex, "* (1) delFriend: "+name, apiInput, apiOutput); } } return null; } /** * Block a user on twitter. * * @param name Username to block. * @return The user just blocked. */ public TwitterUser blockUser(final String name) { try { final XMLResponse doc = postXML(getURL("blocks/create"), "screen_name=" + URLEncoder.encode(name, "utf-8")); if (doc.isGood()) { final TwitterUser user = new TwitterUser(this, doc.getDocumentElement()); uncacheUser(user); return user; } } catch (UnsupportedEncodingException ex) { if (isDebug()) { handleError(ex, "*(1) blockUser: "+name, apiInput, apiOutput); } } return null; } /** * Unblock a user on twitter. * * @param name Username to unblock. * @return The user just unblocked. */ public TwitterUser unblockUser(final String name) { try { final XMLResponse doc = postXML(getURL("blocks/destroy"), "screen_name=" + URLEncoder.encode(name, "utf-8")); if (doc.isGood()) { final TwitterUser user = new TwitterUser(this, doc.getDocumentElement()); uncacheUser(user); return user; } } catch (UnsupportedEncodingException ex) { if (isDebug()) { handleError(ex, "* (1) unblockUser: "+name, apiInput, apiOutput); } } return null; } }
package io.bootique; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.multibindings.MapBinder; import com.google.inject.multibindings.Multibinder; import io.bootique.annotation.Args; import io.bootique.annotation.DefaultCommand; import io.bootique.annotation.EnvironmentProperties; import io.bootique.annotation.EnvironmentVariables; import io.bootique.cli.Cli; import io.bootique.command.Command; import io.bootique.command.CommandManager; import io.bootique.command.DefaultCommandManager; import io.bootique.config.CliConfigurationSource; import io.bootique.config.ConfigurationFactory; import io.bootique.config.ConfigurationSource; import io.bootique.config.PolymorphicConfiguration; import io.bootique.config.TypesFactory; import io.bootique.env.DeclaredVariable; import io.bootique.env.DefaultEnvironment; import io.bootique.env.Environment; import io.bootique.help.DefaultHelpGenerator; import io.bootique.help.HelpCommand; import io.bootique.help.HelpGenerator; import io.bootique.help.config.ConfigHelpGenerator; import io.bootique.help.config.DefaultConfigHelpGenerator; import io.bootique.help.config.HelpConfigCommand; import io.bootique.jackson.DefaultJacksonService; import io.bootique.jackson.JacksonService; import io.bootique.jopt.JoptCliProvider; import io.bootique.log.BootLogger; import io.bootique.meta.application.ApplicationMetadata; import io.bootique.meta.application.OptionMetadata; import io.bootique.meta.config.ConfigHierarchyResolver; import io.bootique.meta.config.ConfigMetadataCompiler; import io.bootique.meta.module.ModulesMetadata; import io.bootique.meta.module.ModulesMetadataCompiler; import io.bootique.run.DefaultRunner; import io.bootique.run.Runner; import io.bootique.shutdown.DefaultShutdownManager; import io.bootique.shutdown.ShutdownManager; import io.bootique.shutdown.ShutdownTimeout; import io.bootique.terminal.FixedWidthTerminal; import io.bootique.terminal.SttyTerminal; import io.bootique.terminal.Terminal; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import java.util.logging.Level; /** * The main {@link Module} of Bootique DI runtime. Declares a minimal set of * services needed for a Bootique app to start: services for parsing command * line, reading configuration, selectign and running a Command. */ public class BQCoreModule implements Module { // TODO: duplicate of FormattedAppender.MIN_LINE_WIDTH private static final int TTY_MIN_COLUMNS = 40; private static final int TTY_DEFAULT_COLUMNS = 80; private String[] args; private BootLogger bootLogger; private Duration shutdownTimeout; private Supplier<Collection<BQModule>> modulesSource; private BQCoreModule() { this.shutdownTimeout = Duration.ofMillis(10000L); } /** * @return a Builder instance to configure the module before using it to * initialize DI container. * @since 0.12 */ public static Builder builder() { return new Builder(); } /** * Returns an instance of {@link BQCoreModuleExtender} used by downstream modules to load custom extensions to the * Bootique core module. Should be invoked from a downstream Module's "configure" method. * * @param binder DI binder passed to the Module that invokes this method. * @return an instance of {@link BQCoreModuleExtender} that can be used to load custom extensions to the Bootique * core. * @since 0.22 */ public static BQCoreModuleExtender extend(Binder binder) { return new BQCoreModuleExtender(binder); } /** * @param binder DI binder passed to the Module that invokes this method. * @return {@link Multibinder} for Bootique commands. * @since 0.12 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#addCommand(Class)}. */ @Deprecated public static Multibinder<Command> contributeCommands(Binder binder) { return extend(binder).getOrCreateCommandsBinder(); } /** * @param binder DI binder passed to the Module that invokes this method. * @return {@link Multibinder} for Bootique options. * @since 0.12 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#addOption(OptionMetadata)}. */ @Deprecated public static Multibinder<OptionMetadata> contributeOptions(Binder binder) { return extend(binder).getOrCreateOptionsBinder(); } /** * @param binder DI binder passed to the Module that invokes this method. * @return {@link MapBinder} for Bootique properties. * @see EnvironmentProperties * @since 0.12 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#setProperty(String, String)}. */ @Deprecated public static MapBinder<String, String> contributeProperties(Binder binder) { return extend(binder).getOrCreatePropertiesBinder(); } /** * @param binder DI binder passed to the Module that invokes this method. * @return {@link MapBinder} for values emulating environment variables. * @see EnvironmentVariables * @since 0.17 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#setVar(String, String)}. */ @Deprecated public static MapBinder<String, String> contributeVariables(Binder binder) { return extend(binder).getOrCreateVariablesBinder(); } /** * Provides a way to set default log levels for specific loggers. These settings can be overridden via Bootique * configuration of whatever logging module you might use, like bootique-logback. This feature may be handy to * suppress chatty third-party loggers, but still allow users to turn them on via configuration. * * @param binder DI binder passed to the Module that invokes this method. * @return {@link MapBinder} for Bootique properties. * @since 0.19 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#setLogLevel(String, Level)}. */ @Deprecated public static MapBinder<String, Level> contributeLogLevels(Binder binder) { return extend(binder).getOrCreateLogLevelsBinder(); } /** * Binds an optional application description used in help messages, etc. * * @param description optional application description used in help messages, etc. * @param binder DI binder passed to the Module that invokes this method. * @since 0.20 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#setApplicationDescription(String)}. */ @Deprecated public static void setApplicationDescription(Binder binder, String description) { extend(binder).setApplicationDescription(description); } /** * Initializes optional default command that will be executed if no explicit command is matched. * * @param binder DI binder passed to the Module that invokes this method. * @param commandType a class of the default command. * @since 0.20 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#setDefaultCommand(Class)}. */ @Deprecated public static void setDefaultCommand(Binder binder, Class<? extends Command> commandType) { extend(binder).setDefaultCommand(commandType); } /** * Initializes optional default command that will be executed if no explicit command is matched. * * @param binder DI binder passed to the Module that invokes this method. * @param command an instance of the default command. * @since 0.20 * @deprecated since 0.22 use {@link #extend(Binder)} to get an extender object, and * then call {@link BQCoreModuleExtender#setDefaultCommand(Command)}. */ @Deprecated public static void setDefaultCommand(Binder binder, Command command) { extend(binder).setDefaultCommand(command); } private static Optional<Command> defaultCommand(Injector injector) { Binding<Command> binding = injector.getExistingBinding(Key.get(Command.class, DefaultCommand.class)); return binding != null ? Optional.of(binding.getProvider().get()) : Optional.empty(); } @Override public void configure(Binder binder) { // trigger extension points creation and add default contributions BQCoreModule.extend(binder) .initAllExtensions() .addOption(createConfigOption()); // bind instances binder.bind(BootLogger.class).toInstance(Objects.requireNonNull(bootLogger)); binder.bind(String[].class).annotatedWith(Args.class).toInstance(Objects.requireNonNull(args)); binder.bind(Duration.class).annotatedWith(ShutdownTimeout.class) .toInstance(Objects.requireNonNull(shutdownTimeout)); // too much code to create config factory.. extracting it in a provider // class... binder.bind(ConfigurationFactory.class).toProvider(JsonNodeConfigurationFactoryProvider.class).in(Singleton.class); // we can't bind Provider with @Provides, so declaring it here... binder.bind(Cli.class).toProvider(JoptCliProvider.class).in(Singleton.class); // while "help" is a special command, we still store it in the common list of commands, // so that "--help" is exposed as an explicit option BQCoreModule.extend(binder).addCommand(HelpCommand.class); BQCoreModule.extend(binder).addCommand(HelpConfigCommand.class); } OptionMetadata createConfigOption() { return OptionMetadata .builder(CliConfigurationSource.CONFIG_OPTION, "Specifies YAML config location, which can be a file path or a URL.") .valueRequired("yaml_location").build(); } @Provides @Singleton JacksonService provideJacksonService(TypesFactory<PolymorphicConfiguration> typesFactory) { return new DefaultJacksonService(typesFactory.getTypes()); } @Provides @Singleton TypesFactory<PolymorphicConfiguration> provideConfigTypesFactory(BootLogger logger) { return new TypesFactory<>(getClass().getClassLoader(), PolymorphicConfiguration.class, logger); } @Provides @Singleton Runner provideRunner(Cli cli, CommandManager commandManager) { return new DefaultRunner(cli, commandManager); } @Provides @Singleton ShutdownManager provideShutdownManager(@ShutdownTimeout Duration timeout) { return new DefaultShutdownManager(timeout); } @Provides @Singleton ConfigurationSource provideConfigurationSource(Cli cli, BootLogger bootLogger) { return new CliConfigurationSource(cli, bootLogger); } @Provides @Singleton HelpCommand provideHelpCommand(BootLogger bootLogger, Provider<HelpGenerator> helpGeneratorProvider) { return new HelpCommand(bootLogger, helpGeneratorProvider); } @Provides @Singleton HelpConfigCommand provideHelpConfigCommand(BootLogger bootLogger, Provider<ConfigHelpGenerator> helpGeneratorProvider) { return new HelpConfigCommand(bootLogger, helpGeneratorProvider); } @Provides @Singleton CommandManager provideCommandManager(Set<Command> commands, HelpCommand helpCommand, Injector injector) { // help command is bound, but default is optional, so check via injector... Optional<Command> defaultCommand = defaultCommand(injector); Map<String, Command> commandMap = new HashMap<>(); commands.forEach(c -> { String name = c.getMetadata().getName(); // if command's name matches default command, exclude it from command map (it is implicit) if (!defaultCommand.isPresent() || !defaultCommand.get().getMetadata().getName().equals(name)) { Command existing = commandMap.put(name, c); // complain on dupes if (existing != null && existing != c) { String c1 = existing.getClass().getName(); String c2 = c.getClass().getName(); throw new RuntimeException( String.format("Duplicate command for name %s (provided by: %s and %s) ", name, c1, c2)); } } }); return new DefaultCommandManager(commandMap, defaultCommand, Optional.of(helpCommand)); } @Provides @Singleton HelpGenerator provideHelpGenerator(ApplicationMetadata application, Terminal terminal) { int maxColumns = terminal.getColumns(); if (maxColumns < TTY_MIN_COLUMNS) { maxColumns = TTY_DEFAULT_COLUMNS; } return new DefaultHelpGenerator(application, maxColumns); } @Provides @Singleton ConfigHelpGenerator provideConfigHelpGenerator(ModulesMetadata modulesMetadata, Terminal terminal) { int maxColumns = terminal.getColumns(); if (maxColumns < TTY_MIN_COLUMNS) { maxColumns = TTY_DEFAULT_COLUMNS; } return new DefaultConfigHelpGenerator(modulesMetadata, maxColumns); } @Provides @Singleton ConfigHierarchyResolver provideConfigHierarchyResolver(TypesFactory<PolymorphicConfiguration> typesFactory) { return ConfigHierarchyResolver.create(typesFactory.getTypes()); } @Provides @Singleton ModulesMetadata provideModulesMetadata(ConfigHierarchyResolver hierarchyResolver) { return new ModulesMetadataCompiler(new ConfigMetadataCompiler(hierarchyResolver::directSubclasses)) .compile(this.modulesSource != null ? modulesSource.get() : Collections.emptyList()); } @Provides @Singleton ApplicationMetadata provideApplicationMetadata(ApplicationDescription descriptionHolder, CommandManager commandManager, Set<OptionMetadata> options, Set<DeclaredVariable> declaredVariables, ModulesMetadata modulesMetadata) { ApplicationMetadata.Builder builder = ApplicationMetadata .builder() .description(descriptionHolder.getDescription()) .addOptions(options); commandManager.getCommands().values().forEach(c -> builder.addCommand(c.getMetadata())); // merge default command options with top-level app options commandManager.getDefaultCommand().ifPresent(c -> builder.addOptions(c.getMetadata().getOptions())); new DeclaredVariableMetaResolver(modulesMetadata).resolve(declaredVariables).forEach(builder::addVariable); return builder.build(); } @Provides @Singleton Environment provideEnvironment(@EnvironmentProperties Map<String, String> diProperties, @EnvironmentVariables Map<String, String> diVars, Set<DeclaredVariable> declaredVariables) { return DefaultEnvironment.withSystemPropertiesAndVariables() .properties(diProperties) .variables(diVars) .declaredVariables(declaredVariables) .build(); } @Provides @Singleton Terminal provideTerminal(BootLogger bootLogger) { // very simple OS test... boolean isUnix = "/".equals(System.getProperty("file.separator")); return isUnix ? new SttyTerminal(bootLogger) : new FixedWidthTerminal(TTY_DEFAULT_COLUMNS); } public static class Builder { private BQCoreModule module; private Builder() { this.module = new BQCoreModule(); } public BQCoreModule build() { return module; } public Builder bootLogger(BootLogger bootLogger) { module.bootLogger = bootLogger; return this; } /** * Sets a supplier of the app modules collection. It has to be provided externally by Bootique code that * assembles the stack. We have no way of discovering this information when inside the DI container. * * @param modulesSource a supplier of module collection. * @return this builder instance. * @since 0.21 */ public Builder moduleSource(Supplier<Collection<BQModule>> modulesSource) { module.modulesSource = modulesSource; return this; } public Builder args(String[] args) { module.args = args; return this; } public Builder shutdownTimeout(Duration timeout) { module.shutdownTimeout = timeout; return this; } } }
package com.badlogic.gdx.tests; import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputListener; import com.badlogic.gdx.RenderListener; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.TextureAtlas; import com.badlogic.gdx.graphics.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Delay; import com.badlogic.gdx.scenes.scene2d.actions.FadeIn; import com.badlogic.gdx.scenes.scene2d.actions.FadeOut; import com.badlogic.gdx.scenes.scene2d.actions.Forever; import com.badlogic.gdx.scenes.scene2d.actions.MoveBy; import com.badlogic.gdx.scenes.scene2d.actions.MoveTo; import com.badlogic.gdx.scenes.scene2d.actions.Parallel; import com.badlogic.gdx.scenes.scene2d.actions.Repeat; import com.badlogic.gdx.scenes.scene2d.actions.RotateBy; import com.badlogic.gdx.scenes.scene2d.actions.RotateTo; import com.badlogic.gdx.scenes.scene2d.actions.ScaleTo; import com.badlogic.gdx.scenes.scene2d.actions.Sequence; import com.badlogic.gdx.scenes.scene2d.actors.Button; import com.badlogic.gdx.scenes.scene2d.actors.Image; import com.badlogic.gdx.scenes.scene2d.actors.LinearGroup; import com.badlogic.gdx.scenes.scene2d.actors.LinearGroup.LinearGroupLayout; public class UITest implements RenderListener, InputListener { Texture uiTexture; Texture badlogic; TextureAtlas atlas; Stage ui; @Override public void surfaceCreated () { if (uiTexture == null) { Gdx.input.addInputListener(this); uiTexture = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/ui.png", FileType.Internal), TextureFilter.Linear, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); badlogic = Gdx.graphics.newTexture(Gdx.files.getFileHandle("data/badlogic.jpg", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); ui = new Stage(480, 320, false); atlas = new TextureAtlas(uiTexture); atlas.addRegion("blend", 0, 0, 64, 32); atlas.addRegion("blendDown", -1, -1, 64, 32); atlas.addRegion("rotate", 64, 0, 64, 32); atlas.addRegion("rotateDown", 63, -1, 64, 32); atlas.addRegion("scale", 64, 32, 64, 32); atlas.addRegion("scaleDown", 63, 31, 64, 32); atlas.addRegion("button", 0, 64, 64, 32); atlas.addRegion("buttonDown", -1, 63, 64, 32); Image img1 = new Image("image1", new TextureRegion(badlogic, 0, 0, 256, 256)); img1.width = img1.height = 64; img1.originX = img1.originY = 32; img1.action(Sequence.$(FadeOut.$(1), FadeIn.$(1), Delay.$(MoveTo.$(100, 100, 1), 2), ScaleTo.$(0.5f, 0.5f, 1), FadeOut.$(0.5f), Delay.$(Parallel.$(RotateTo.$(360, 1), FadeIn.$(1), ScaleTo.$(1, 1, 1)), 1))); ui.addActor(img1); Image img2 = new Image("image2", new TextureRegion(badlogic, 0, 0, 256, 256)); img2.width = img2.height = 64; img2.originX = img2.originY = 32; img2.action(Repeat.$(Sequence.$(MoveBy.$(50, 0, 1), MoveBy.$(0, 50, 1), MoveBy.$(-50, 0, 1), MoveBy.$(0, -50, 1)), 3)); ui.addActor(img2); Button button = new Button("button", atlas.getRegion("button"), atlas.getRegion("buttonDown")); button.action(Forever.$(RotateBy.$(360, 4))); ui.addActor(button); LinearGroup linear = new LinearGroup("linear", 64, 32 * 3, LinearGroupLayout.Vertical); linear.x = 200; linear.y = 150; linear.scaleX = linear.scaleY = 0; linear.addActor(new Button("blend", atlas.getRegion("blend"), atlas.getRegion("blendDown"))); linear.addActor(new Button("scale", atlas.getRegion("scale"), atlas.getRegion("scaleDown"))); linear.addActor(new Button("rotate", atlas.getRegion("rotate"), atlas.getRegion("rotateDown"))); linear.action(Parallel.$(ScaleTo.$(1, 1, 2), RotateTo.$(720, 2))); ui.addActor(linear); LinearGroup linearh = new LinearGroup("linearh", 64 * 3, 32, LinearGroupLayout.Horizontal); linearh.x = 500; linearh.y = 10; linearh.addActor(new Button("blendh", atlas.getRegion("blend"), atlas.getRegion("blendDown"))); linearh.addActor(new Button("scaleh", atlas.getRegion("scale"), atlas.getRegion("scaleDown"))); linearh.addActor(new Button("rotateh", atlas.getRegion("rotate"), atlas.getRegion("rotateDown"))); linearh.action(MoveTo.$(100, 10, 1.5f)); ui.addActor(linearh); // Group.enableDebugging( "data/debug.png" ); } } @Override public void surfaceChanged (int width, int height) { } @Override public void render () { GL10 gl = Gdx.graphics.getGL10(); gl.glClear(GL10.GL_COLOR_BUFFER_BIT); ui.act(Gdx.graphics.getDeltaTime()); ui.render(); } @Override public void dispose () { } @Override public boolean keyDown (int keycode) { // TODO Auto-generated method stub return false; } @Override public boolean keyUp (int keycode) { // TODO Auto-generated method stub return false; } @Override public boolean keyTyped (char character) { // TODO Auto-generated method stub return false; } @Override public boolean touchDown (int x, int y, int pointer) { ui.touchDown(x, y, pointer); return false; } Vector2 point = new Vector2(); @Override public boolean touchUp (int x, int y, int pointer) { if (!ui.touchUp(x, y, pointer)) { Actor actor = ui.findActor("image1"); if (actor != null) { ui.toStageCoordinates(x, y, point); actor.clearActions(); actor.action(MoveTo.$(point.x, point.y, 2)); actor.action(RotateBy.$(90, 2)); if (actor.scaleX == 1.0f) actor.action(ScaleTo.$(0.5f, 0.5f, 2)); else actor.action(ScaleTo.$(1f, 1f, 2)); } } return false; } @Override public boolean touchDragged (int x, int y, int pointer) { ui.touchDragged(x, y, pointer); return false; } }
package com.lyrch.openbrew.test; import com.lyrch.openbrew.IngredientActivity; import com.lyrch.openbrew.RecipeActivity; import android.content.Intent; import android.content.res.Resources; import android.test.ActivityInstrumentationTestCase2; import android.view.KeyEvent; import android.widget.Spinner; import android.widget.SpinnerAdapter; public class IngredientActivityTest extends ActivityInstrumentationTestCase2<IngredientActivity> { public static final int INGREDIENT_TYPE_COUNT = 8; public static final int TEST_POSITION = 3; public static final int INITIAL_POSITION = 0; private IngredientActivity mActivity; private Spinner mSpinner; private SpinnerAdapter mIngredientTypes; private String mSelection; private int mPos; public IngredientActivityTest() { super(IngredientActivity.class); } protected void setUp() throws Exception { super.setUp(); setActivityInitialTouchMode(false); System.out.println("Setting up."); mActivity = getActivity(); mSpinner = (Spinner) mActivity.findViewById(com.lyrch.openbrew.R.id.ingredient_type_spinner); mIngredientTypes = mSpinner.getAdapter(); } public void testPreConditions() { System.out.println(mSpinner.toString()); assertTrue(mSpinner.getOnItemSelectedListener() != null); assertTrue(mIngredientTypes != null); assertEquals(mIngredientTypes.getCount(), INGREDIENT_TYPE_COUNT); } public void testIngredientSelectionUI() { mActivity.runOnUiThread( new Runnable() { public void run() { mSpinner.requestFocus(); mSpinner.setSelection(INITIAL_POSITION); } } ); this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); for (int i = 1; i <= TEST_POSITION; i++) { this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN); } this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); mPos = mSpinner.getSelectedItemPosition(); mSelection = (String)mSpinner.getItemAtPosition(mPos); Resources res = mActivity.getResources(); String[] ingredients = res.getStringArray(com.lyrch.openbrew.R.array.ingredient_types); assertEquals(ingredients[TEST_POSITION],mSelection); } }
package com.worizon.junit.rpc; import java.io.IOException; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import com.worizon.net.HttpRequester; import com.worizon.net.HttpRequesterBuilder; import com.worizon.net.HttpRequester.TransformerContext; import com.worizon.test.TestServer; public class HttpRequesterBuilderTest { private TestServer server; private HttpRequester http; private HttpRequesterBuilder builder; @Before public void setUp() throws Exception{ server = new TestServer(4444); http = (HttpRequester)server.createTestRequester(new HttpRequester(), "request"); builder = new HttpRequesterBuilder(http); } //finish server in case any test fails and server is not stopped implicitly @After public void tearDown() throws Exception{ server.finish(); } @Test public void testEndpoint() throws Exception{ http = builder.endpoint("http://localhost:4444/rpc").build(); server.finish(); assertEquals("http://localhost:4444/rpc", http.getEndpoint()); } @Test public void testRequest() throws Exception{ http = builder.endpoint("http://localhost:4444/rpc").build(); http.request("test"); assertEquals("test", server.getBody()); assertEquals("application/json", server.getHeaders().get("Content-Type")); assertEquals("application/json", server.getHeaders().get("Accept")); assertEquals("no-cache", server.getHeaders().get("Cache-Control")); assertEquals("no-cache", server.getHeaders().get("Pragma")); assertEquals("localhost:4444", server.getHeaders().get("Host")); assertEquals("close", server.getHeaders().get("Connection")); assertEquals("5", server.getHeaders().get("Content-Length")); } @Test public void testAddTransformer() throws Exception{ http = builder .endpoint("http://localhost:4444/rpc") .addTransformer(new HttpRequester.ITransformer() { @Override public void transform(TransformerContext ctx) throws Exception { ctx.setBody("foo\n"); } }).build(); http.request("bar"); assertEquals("foo", server.getBody()); } @Test public void testConcatTransformers() throws Exception{ http = builder .endpoint("http://localhost:4444/rpc") .addTransformer(new HttpRequester.ITransformer() { @Override public void transform(TransformerContext ctx) throws Exception { ctx.setBody("foo\n"); } }) .addTransformer(new HttpRequester.ITransformer() { @Override public void transform(TransformerContext ctx) throws Exception { assertEquals("foo\n",ctx.getBody()); ctx.putHeader("Content-type", "text/xml"); } }) .build(); http.request("bar"); assertEquals("foo", server.getBody()); assertEquals("text/xml", server.getHeaders().get("Content-Type")); } @Test public void testSkipNextIfTrueTransformer() throws Exception{ http = builder .endpoint("http://localhost:4444/rpc") .skipNextIfTrue(true) .addTransformer(new HttpRequester.ITransformer() { @Override public void transform(TransformerContext ctx) throws Exception { throw new RuntimeException(); } }).build(); http.request("bar"); assertEquals("bar", server.getBody()); assertEquals("application/json", server.getHeaders().get("Content-Type")); } @Test public void testContinueIfTrueTransformer() throws Exception{ http = builder .endpoint("http://localhost:4444/rpc") .continueIfTrue(false) .addTransformer(new HttpRequester.ITransformer() { @Override public void transform(TransformerContext ctx) throws Exception { assertTrue(false); } }).build(); http.request("bar"); assertEquals("bar", server.getBody()); } @Test public void testBodyConcatTransformer() throws Exception{ http = builder .endpoint("http://localhost:4444/rpc") .addTransformer(new HttpRequester.ITransformer() { @Override public void transform(TransformerContext ctx) throws Exception { ctx.setBody( ctx.getBody().trim() ); } }) .bodyConcat("test2\n") .build(); http.request("bar"); assertEquals("bartest2", server.getBody()); } @Test public void testBodyPreprendTransformer() throws Exception{ http = builder .endpoint("http://localhost:4444/rpc") .bodyPrepend("test2") .build(); http.request("bar"); assertEquals("test2bar", server.getBody()); } @Test public void testBodyURLEncodeTransformer() throws Exception{ http = builder .endpoint("http://localhost:4444/rpc") .bodyTrim() .bodyURLEncode() .bodyConcat("\n") .build(); http.request("{test:1}"); assertArrayEquals(new char[]{'%','7','B','t','e','s','t','%','3','A','1','%','7','D'}, server.getBody().toCharArray()); } }
package net.coobird.thumbnailator.tasks.io; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.spi.IIORegistry; import javax.imageio.spi.ImageWriterSpi; import net.coobird.thumbnailator.TestUtils; import net.coobird.thumbnailator.ThumbnailParameter; import net.coobird.thumbnailator.builders.BufferedImageBuilder; import net.coobird.thumbnailator.tasks.UnsupportedFormatException; import net.coobird.thumbnailator.test.BufferedImageComparer; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.mockito.Mockito.*; import static org.junit.Assert.*; public class FileImageSinkTest { /** * The temporary directory to use when creating files to use for this test. */ private static final String TMPDIR = "test-resources/tmp/FileImageSinkTest"; @BeforeClass public static void makeTemporaryDirectory() { TestUtils.makeTemporaryDirectory(TMPDIR); } @AfterClass public static void deleteTemporaryDirectory() { TestUtils.deleteTemporaryDirectory(TMPDIR); } @Test public void validFilename_File() { // given File f = new File(TMPDIR, "test.png"); // when FileImageSink sink = new FileImageSink(f); // then assertEquals(f, sink.getSink()); } @Test public void validFilename_String() { // given String f = TMPDIR + "/test.png"; // when FileImageSink sink = new FileImageSink(f); // then assertEquals(new File(f), sink.getSink()); } @Test(expected=NullPointerException.class) public void nullFilename_File() { // given File f = null; try { // when new FileImageSink(f); } catch (NullPointerException e) { // then assertEquals("File cannot be null.", e.getMessage()); throw e; } } @Test(expected=NullPointerException.class) public void nullFilename_String() { // given String f = null; try { // when new FileImageSink(f); } catch (NullPointerException e) { // then assertEquals("File cannot be null.", e.getMessage()); throw e; } } @Test(expected=NullPointerException.class) public void write_NullImage() throws IOException { // given File f = new File(TMPDIR, "test.png"); f.deleteOnExit(); BufferedImage img = null; FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("png"); try { // when sink.write(img); } catch (NullPointerException e) { // then assertEquals("Cannot write a null image.", e.getMessage()); throw e; } } @Test public void write_ValidImage() throws IOException { // given File outputFile = new File(TMPDIR, "test.png"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("png", formatName); } @Test public void write_ValidImage_SetOutputFormatWithSameAsExtension() throws IOException { // given File outputFile = new File(TMPDIR, "test.png"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName("png"); sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("png", formatName); } @Test public void write_ValidImage_SetOutputFormatWithDifferentExtension() throws IOException { // given File outputFile = new File(TMPDIR, "test.png"); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName("JPEG"); sink.write(imgToWrite); // then outputFile = new File(TMPDIR, "test.png.JPEG"); outputFile.deleteOnExit(); assertEquals(outputFile.getAbsoluteFile(), sink.getSink().getAbsoluteFile()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("JPEG", formatName); } @Test public void write_ValidImage_SetOutputFormat_OutputFileHasNoExtension() throws IOException { // given File outputFile = new File(TMPDIR, "test"); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName("JPEG"); sink.write(imgToWrite); // then outputFile = new File(TMPDIR, "test.JPEG"); outputFile.deleteOnExit(); assertEquals(outputFile.getAbsoluteFile(), sink.getSink().getAbsoluteFile()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("JPEG", formatName); } @Test public void write_ValidImage_InvalidFileExtension() throws IOException { // given File outputFile = new File(TMPDIR, "test.foo"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when try { sink.write(imgToWrite); fail(); } catch (UnsupportedFormatException e) { // then } } @Test public void write_ValidImage_InvalidFileExtension_OutputFormatSetToValidFormat() throws IOException { // given File outputFile = new File(TMPDIR, "test.foo"); File actualOutputFile = new File(TMPDIR, "test.foo.png"); actualOutputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); sink.setOutputFormatName("png"); // when sink.write(imgToWrite); // then assertEquals(actualOutputFile.getCanonicalFile(), sink.getSink().getCanonicalFile()); BufferedImage writtenImg = ImageIO.read(actualOutputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(actualOutputFile)); assertEquals("png", formatName); } @Test public void write_ValidImage_WriterCantCompress() throws IOException { // given ImageWriteParam iwParam = mock(ImageWriteParam.class); ImageWriter writer = mock(ImageWriter.class); ImageWriterSpi spi = mock(ImageWriterSpi.class); when(iwParam.canWriteCompressed()).thenReturn(false); when(writer.getDefaultWriteParam()).thenReturn(iwParam); when(writer.getOriginatingProvider()).thenReturn(spi); when(spi.getFormatNames()).thenReturn(new String[] {"foo", "FOO"}); when(spi.getFileSuffixes()).thenReturn(new String[] {"foo", "FOO"}); when(spi.createWriterInstance()).thenReturn(writer); when(spi.createWriterInstance(anyObject())).thenReturn(writer); IIORegistry.getDefaultInstance().registerServiceProvider(spi); File outputFile = new File(TMPDIR, "test.foo"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); ThumbnailParameter param = mock(ThumbnailParameter.class); when(param.getOutputQuality()).thenReturn(0.8f); when(param.getOutputFormatType()).thenReturn(ThumbnailParameter.DEFAULT_FORMAT_TYPE); FileImageSink sink = new FileImageSink(outputFile); sink.setThumbnailParameter(param); // when sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); verify(iwParam, never()).setCompressionMode(ImageWriteParam.MODE_EXPLICIT); verify(iwParam, never()).setCompressionType(anyString()); verify(iwParam, never()).setCompressionQuality(anyFloat()); // - check to see that parameters were not read, as this format doesn't // support compression. verify(param, never()).getOutputQuality(); verify(param, never()).getOutputFormatType(); // clean up IIORegistry.getDefaultInstance().deregisterServiceProvider(spi); } @Test public void write_ValidImage_WriterCanCompress_NoCompressionTypeFromWriter() throws IOException { // given ImageWriteParam iwParam = mock(ImageWriteParam.class); ImageWriter writer = mock(ImageWriter.class); ImageWriterSpi spi = mock(ImageWriterSpi.class); when(iwParam.canWriteCompressed()).thenReturn(true); when(iwParam.getCompressionTypes()).thenReturn(null); when(writer.getDefaultWriteParam()).thenReturn(iwParam); when(writer.getOriginatingProvider()).thenReturn(spi); when(spi.getFormatNames()).thenReturn(new String[] {"foo", "FOO"}); when(spi.getFileSuffixes()).thenReturn(new String[] {"foo", "FOO"}); when(spi.createWriterInstance()).thenReturn(writer); when(spi.createWriterInstance(anyObject())).thenReturn(writer); IIORegistry.getDefaultInstance().registerServiceProvider(spi); File outputFile = new File(TMPDIR, "test.foo"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); ThumbnailParameter param = mock(ThumbnailParameter.class); when(param.getOutputQuality()).thenReturn(0.8f); when(param.getOutputFormatType()).thenReturn(ThumbnailParameter.DEFAULT_FORMAT_TYPE); FileImageSink sink = new FileImageSink(outputFile); sink.setThumbnailParameter(param); // when sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); verify(iwParam, atLeastOnce()).setCompressionMode(ImageWriteParam.MODE_EXPLICIT); verify(iwParam, never()).setCompressionType(anyString()); verify(iwParam, atLeastOnce()).setCompressionQuality(0.8f); // - check to see that parameters was read verify(param, atLeastOnce()).getOutputQuality(); verify(param, atLeastOnce()).getOutputFormatType(); // clean up IIORegistry.getDefaultInstance().deregisterServiceProvider(spi); } @Test public void write_ValidImage_WriterCanCompress_HasCompressionTypeFromWriter() throws IOException { // given ImageWriteParam iwParam = mock(ImageWriteParam.class); ImageWriter writer = mock(ImageWriter.class); ImageWriterSpi spi = mock(ImageWriterSpi.class); when(iwParam.canWriteCompressed()).thenReturn(true); when(iwParam.getCompressionTypes()).thenReturn(new String[] {"FOOBAR"}); when(writer.getDefaultWriteParam()).thenReturn(iwParam); when(writer.getOriginatingProvider()).thenReturn(spi); when(spi.getFormatNames()).thenReturn(new String[] {"foo", "FOO"}); when(spi.getFileSuffixes()).thenReturn(new String[] {"foo", "FOO"}); when(spi.createWriterInstance()).thenReturn(writer); when(spi.createWriterInstance(anyObject())).thenReturn(writer); IIORegistry.getDefaultInstance().registerServiceProvider(spi); File outputFile = new File(TMPDIR, "test.foo"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); ThumbnailParameter param = mock(ThumbnailParameter.class); when(param.getOutputQuality()).thenReturn(0.8f); when(param.getOutputFormatType()).thenReturn(ThumbnailParameter.DEFAULT_FORMAT_TYPE); FileImageSink sink = new FileImageSink(outputFile); sink.setThumbnailParameter(param); // when sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); verify(iwParam, atLeastOnce()).setCompressionMode(ImageWriteParam.MODE_EXPLICIT); verify(iwParam, atLeastOnce()).setCompressionType("FOOBAR"); verify(iwParam, atLeastOnce()).setCompressionQuality(0.8f); // - check to see that parameters was read verify(param, atLeastOnce()).getOutputQuality(); verify(param, atLeastOnce()).getOutputFormatType(); // clean up IIORegistry.getDefaultInstance().deregisterServiceProvider(spi); } @Test public void write_ValidImage_SetThumbnailParameter_BMP_QualityAndOutputFormatType_BothDefault() throws IOException { // given File outputFile = new File(TMPDIR, "test.bmp"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); ThumbnailParameter param = mock(ThumbnailParameter.class); when(param.getOutputQuality()).thenReturn(ThumbnailParameter.DEFAULT_QUALITY); when(param.getOutputFormatType()).thenReturn(ThumbnailParameter.DEFAULT_FORMAT_TYPE); FileImageSink sink = new FileImageSink(outputFile); sink.setThumbnailParameter(param); // when sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("bmp", formatName); verify(param, atLeastOnce()).getOutputQuality(); verify(param, atLeastOnce()).getOutputFormatType(); } @Test public void write_ValidImage_SetThumbnailParameter_BMP_QualityAndOutputFormatType_BothNonDefault() throws IOException { // given File outputFile = new File(TMPDIR, "test.bmp"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); ThumbnailParameter param = mock(ThumbnailParameter.class); when(param.getOutputQuality()).thenReturn(0.5f); when(param.getOutputFormatType()).thenReturn("BI_BITFIELDS"); FileImageSink sink = new FileImageSink(outputFile); sink.setThumbnailParameter(param); // when sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("bmp", formatName); verify(param, atLeastOnce()).getOutputQuality(); verify(param, atLeastOnce()).getOutputFormatType(); } @Test public void write_ValidImage_SetThumbnailParameter_BMP_OutputFormatType() throws IOException { // given File outputFile = new File(TMPDIR, "test.bmp"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); ThumbnailParameter param = mock(ThumbnailParameter.class); when(param.getOutputQuality()).thenReturn(ThumbnailParameter.DEFAULT_QUALITY); when(param.getOutputFormatType()).thenReturn("BI_BITFIELDS"); FileImageSink sink = new FileImageSink(outputFile); sink.setThumbnailParameter(param); // when sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("bmp", formatName); verify(param, atLeastOnce()).getOutputFormatType(); } @Test public void write_ValidImage_SetOutputFormatWithOriginalFormatConstant_FileExtension_png() throws IOException { // given File outputFile = new File(TMPDIR, "test.png"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName(ThumbnailParameter.ORIGINAL_FORMAT); sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("png", formatName); } @Test public void write_ValidImage_SetOutputFormatWithOriginalFormatConstant_FileExtension_bmp() throws IOException { // given File outputFile = new File(TMPDIR, "test.bmp"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName(ThumbnailParameter.ORIGINAL_FORMAT); sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("bmp", formatName); } @Test public void write_ValidImage_SetOutputFormatWithOriginalFormatConstant_FileExtension_jpg() throws IOException { // given File outputFile = new File(TMPDIR, "test.jpg"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName(ThumbnailParameter.ORIGINAL_FORMAT); sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("JPEG", formatName); } @Test public void write_ValidImage_SetOutputFormatWithOriginalFormatConstant_FileExtension_jpeg() throws IOException { // given File outputFile = new File(TMPDIR, "test.jpeg"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName(ThumbnailParameter.ORIGINAL_FORMAT); sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("JPEG", formatName); } @Test public void write_ValidImage_SetOutputFormatWithOriginalFormatConstant_FileExtension_Jpeg() throws IOException { // given File outputFile = new File(TMPDIR, "test.Jpeg"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); // when sink.setOutputFormatName(ThumbnailParameter.ORIGINAL_FORMAT); sink.write(imgToWrite); // then assertEquals(outputFile, sink.getSink()); BufferedImage writtenImg = ImageIO.read(outputFile); assertTrue(BufferedImageComparer.isRGBSimilar(imgToWrite, writtenImg)); String formatName = TestUtils.getFormatName(new FileInputStream(outputFile)); assertEquals("JPEG", formatName); } @Test(expected=UnsupportedFormatException.class) public void write_ValidImage_SetOutputFormatWithOriginalFormatConstant_NoFileExtension() throws IOException { // given File outputFile = new File(TMPDIR, "test"); outputFile.deleteOnExit(); BufferedImage imgToWrite = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); FileImageSink sink = new FileImageSink(outputFile); try { // when sink.setOutputFormatName(ThumbnailParameter.ORIGINAL_FORMAT); sink.write(imgToWrite); } catch (UnsupportedFormatException e) { // then assertEquals("Could not determine output format.", e.getMessage()); throw e; } } @Test public void write_NoExtentionSpecified() throws IOException { // set up File f = new File(TMPDIR, "tmp-" + Math.abs(new Random().nextLong())); // given FileImageSink sink = new FileImageSink(f); // when try { sink.write(new BufferedImageBuilder(100, 100).build()); fail(); } catch (UnsupportedFormatException e) { // then } } @Test public void write_SpecifiedExtensionIsPNG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIspng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIspng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("png"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIspng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("png"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIspng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("png"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsPNG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("PNG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsPNG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("PNG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsPNG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("PNG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsPng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Png"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsPng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Png"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsPng() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Png"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("png", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); File expectedFile = new File(f.getAbsolutePath() + ".jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); File expectedFile = new File(f.getAbsolutePath() + ".jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); File expectedFile = new File(f.getAbsolutePath() + ".jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); File expectedFile = new File(f.getAbsolutePath() + ".jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); File expectedFile = new File(f.getAbsolutePath() + ".jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); File expectedFile = new File(f.getAbsolutePath() + ".jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); File expectedFile = new File(f.getAbsolutePath() + ".JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); File expectedFile = new File(f.getAbsolutePath() + ".JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); File expectedFile = new File(f.getAbsolutePath() + ".JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); File expectedFile = new File(f.getAbsolutePath() + ".JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); File expectedFile = new File(f.getAbsolutePath() + ".JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); File expectedFile = new File(f.getAbsolutePath() + ".JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); File expectedFile = new File(f.getAbsolutePath() + ".Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); File expectedFile = new File(f.getAbsolutePath() + ".Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); File expectedFile = new File(f.getAbsolutePath() + ".Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPNG_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "PNG"); File expectedFile = new File(f.getAbsolutePath() + ".Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIspng_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "png"); File expectedFile = new File(f.getAbsolutePath() + ".Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsPng_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Png"); File expectedFile = new File(f.getAbsolutePath() + ".Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(expectedFile, sink.getSink()); assertTrue(expectedFile.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(expectedFile))); } @Test public void write_SpecifiedExtensionIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPG"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPEG"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpg"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpeg"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpg"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpeg"); // given FileImageSink sink = new FileImageSink(f); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPG_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPEG_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpg_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpeg_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpg_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpeg_SpecifiedOutputFormatIsjpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPG_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPEG_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpg_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpeg_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpg_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpeg_SpecifiedOutputFormatIsjpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPG_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPEG_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpg_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpeg_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpg_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpeg_SpecifiedOutputFormatIsJPG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPG_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPEG_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpg_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpeg_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpg_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpeg_SpecifiedOutputFormatIsJPEG() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("JPEG"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPG_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPEG_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpg_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpeg_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpg_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpeg_SpecifiedOutputFormatIsJpg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPG_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJPEG_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "JPEG"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpg_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsjpeg_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpg_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void write_SpecifiedExtensionIsJpeg_SpecifiedOutputFormatIsJpeg() throws IOException { // set up File f = TestUtils.createTempFile(TMPDIR, "Jpeg"); // given FileImageSink sink = new FileImageSink(f); sink.setOutputFormatName("Jpeg"); // when sink.write(new BufferedImageBuilder(100, 100).build()); // then assertEquals(f, sink.getSink()); assertTrue(f.exists()); assertEquals("JPEG", TestUtils.getFormatName(new FileInputStream(f))); } @Test public void constructorFile_write_allowOverwriteTrue() throws IOException { // set up File sourceFile = new File("test-resources/Thumbnailator/grid.png"); File f = new File(TMPDIR, "tmp-grid.png"); // copy the image to a temporary file. TestUtils.copyFile(sourceFile, f); // given FileImageSink sink = new FileImageSink(f, true); // when sink.write(ImageIO.read(f)); // then assertTrue(f.exists()); // clean ups f.delete(); } @Test(expected=IllegalArgumentException.class) public void constructorFile_write_allowOverwriteFalse() throws IOException { // set up File sourceFile = new File("test-resources/Thumbnailator/grid.png"); File f = new File(TMPDIR, "tmp-grid.png"); // copy the image to a temporary file. TestUtils.copyFile(sourceFile, f); // given FileImageSink sink = new FileImageSink(f, false); // when try { sink.write(ImageIO.read(f)); } catch (IllegalArgumentException e) { assertEquals("The destination file exists.", e.getMessage()); throw e; } // clean ups f.delete(); } @Test public void constructorString_write_allowOverwriteTrue() throws IOException { // set up File sourceFile = new File("test-resources/Thumbnailator/grid.png"); File f = new File(TMPDIR, "tmp-grid.png"); // copy the image to a temporary file. TestUtils.copyFile(sourceFile, f); // given FileImageSink sink = new FileImageSink(f.getAbsolutePath(), true); // when sink.write(ImageIO.read(f)); // then assertTrue(f.exists()); // clean ups f.delete(); } @Test(expected=IllegalArgumentException.class) public void constructorString_write_allowOverwriteFalse() throws IOException { // set up File sourceFile = new File("test-resources/Thumbnailator/grid.png"); File f = new File(TMPDIR, "tmp-grid.png"); // copy the image to a temporary file. TestUtils.copyFile(sourceFile, f); // given FileImageSink sink = new FileImageSink(f.getAbsolutePath(), false); // when try { sink.write(ImageIO.read(f)); } catch (IllegalArgumentException e) { assertEquals("The destination file exists.", e.getMessage()); throw e; } // clean ups f.delete(); } }
import jvmgo.exception.JvmExTest; import jvmgo.file.FileIoTest; import jvmgo.reflection.ArrayClassTest; import jvmgo.reflection.PrimitiveClassTest; import jvmgo.cl.ClassLoaderTest; import jvmgo.reflection.MethodTest; import jvmgo.thread.MainThreadTest; import jvmgo.StringTest; import jvmgo.UnitTestRunner; import jvmgo.cl.GetClassLoaderTest; import org.junit.Test; import static org.junit.Assert.*; public class UnitTests { @Test public void test() { assertEquals(2, 1 + 1); } public static void main(String[] args) { UnitTestRunner.run(new Class<?>[] { ArrayClassTest.class, ClassLoaderTest.class, FileIoTest.class, GetClassLoaderTest.class, JvmExTest.class, MainThreadTest.class, MethodTest.class, PrimitiveClassTest.class, StringTest.class, UnitTests.class, }); } }
package io.fundrequest.core.config; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.web3j.protocol.Web3j; import org.web3j.protocol.Web3jService; import org.web3j.protocol.http.HttpService; @Configuration public class Web3Config { @Bean @Primary public Web3j provideWeb3J(final Web3jService web3jService) { return Web3j.build(web3jService); } @Bean @Qualifier("local") public Web3j provideInfuraWeb3j(@Qualifier("local") final Web3jService web3jService) { return Web3j.build(web3jService); } @Bean @Primary public Web3jService provideWeb3JService(@Value("${io.fundrequest.ethereum.endpoint.url}") final String endpoint) { return new HttpService(endpoint); } @Bean @Qualifier("local") public Web3jService provideInfuraEndpoint(@Value("${io.fundrequest.ethereum.endpoint.local-url}") final String endpoint) { return new HttpService(endpoint); } }
package ragnardb.runtime; import gw.lang.reflect.IType; import gw.util.GosuExceptionUtil; import ragnardb.plugin.ISQLQueryResultType; import ragnardb.plugin.ISQLTableType; import java.sql.SQLException; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class ExecutableQuery<T> extends SQLQuery<T>{ private String statement; private IType returnType; private ISQLTableType returnTable; public ExecutableQuery(ITypeToSQLMetadata md, IType rootType, String s, IType ret, ISQLTableType rT){ super(md, rootType); statement = s; returnType = ret; returnTable = rT; } public ExecutableQuery<T> setup(){ ExecutableQuery<T> query = new ExecutableQuery<T>(_metadata, _rootType, this.statement, returnType, returnTable); return query; } @Override public Iterator<T> iterator(){ List<T> results = new LinkedList<>(); Iterable<SQLRecord> records = () -> { try { return SQLRecord.select( statement, Collections.emptyList(), _rootType ); } catch( SQLException e ) { throw GosuExceptionUtil.forceThrow( e ); } }; if(returnType instanceof ISQLTableType){ for(SQLRecord record: records){ results.add((T) record); } } else if(returnType instanceof ISQLQueryResultType){ for(SQLRecord record: records){ results.add((T) record); } } return results.iterator(); } }
package org.cleartk.token.pos.impl; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.uima.UIMAException; import org.apache.uima.analysis_component.AnalysisComponent; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.analysis_engine.metadata.SofaMapping; import org.apache.uima.collection.CollectionReader; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.metadata.TypePriorities; import org.apache.uima.resource.metadata.TypeSystemDescription; import org.cleartk.ViewNames; import org.cleartk.classifier.BuildJar; import org.cleartk.classifier.SequentialClassifierAnnotator; import org.cleartk.classifier.SequentialDataWriterAnnotator; import org.cleartk.classifier.Train; import org.cleartk.classifier.mallet.DefaultMalletCRFDataWriterFactory; import org.cleartk.classifier.opennlp.DefaultMaxentDataWriterFactory; import org.cleartk.classifier.viterbi.ViterbiDataWriter; import org.cleartk.classifier.viterbi.ViterbiDataWriterFactory; import org.cleartk.syntax.treebank.TreebankGoldAnnotator; import org.cleartk.token.pos.POSHandler; import org.cleartk.type.Sentence; import org.cleartk.type.Token; import org.cleartk.util.AnnotationRetrieval; import org.cleartk.util.FilesCollectionReader; import org.cleartk.util.TestsUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.uutuc.factory.AnalysisEngineFactory; import org.uutuc.factory.CollectionReaderFactory; import org.uutuc.factory.SofaMappingFactory; import org.uutuc.factory.TokenFactory; import org.uutuc.util.HideOutput; import org.uutuc.util.JCasIterable; import org.uutuc.util.TearDownUtil; public class DefaultPOSHandlerTest { private File outputDirectory = new File("test/data/token/poshandler"); @Before public void setUp() { outputDirectory.mkdirs(); } @After public void tearDown() { TearDownUtil.removeDirectory(outputDirectory); } @Test public void testCraft() throws Exception { TypeSystemDescription defaultTypeSystemDescription = TestsUtil.getTypeSystemDescription(); CollectionReader reader = CollectionReaderFactory.createCollectionReader(FilesCollectionReader.class, defaultTypeSystemDescription, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, "test/data/docs/treebank", FilesCollectionReader.PARAM_SUFFIXES, new String[] {".tree"}, FilesCollectionReader.PARAM_VIEW_NAME, ViewNames.TREEBANK); SofaMapping[] sofaMappings = new SofaMapping[] { SofaMappingFactory.createSofaMapping(ViewNames.TREEBANK, TreebankGoldAnnotator.class, ViewNames.TREEBANK), SofaMappingFactory.createSofaMapping(ViewNames.TREEBANK_ANNOTATIONS, TreebankGoldAnnotator.class, ViewNames.TREEBANK_ANNOTATIONS), SofaMappingFactory.createSofaMapping(ViewNames.TREEBANK_ANNOTATIONS, SequentialDataWriterAnnotator.class, ViewNames.DEFAULT) }; List<Class<? extends AnalysisComponent>> aggregatedClasses = new ArrayList<Class<? extends AnalysisComponent>>(); aggregatedClasses.add(TreebankGoldAnnotator.class); aggregatedClasses.add(SequentialDataWriterAnnotator.class); AnalysisEngine aggregateEngine = AnalysisEngineFactory.createAggregateAnalysisEngine(aggregatedClasses, defaultTypeSystemDescription, (TypePriorities)null, sofaMappings, TreebankGoldAnnotator.PARAM_POST_TREES, false, SequentialDataWriterAnnotator.PARAM_DATAWRITER_FACTORY_CLASS, ViterbiDataWriterFactory.class.getName(), ViterbiDataWriter.PARAM_DELEGATED_DATAWRITER_FACTORY_CLASS, DefaultMaxentDataWriterFactory.class.getName(), SequentialDataWriterAnnotator.PARAM_ANNOTATION_HANDLER, DefaultPOSHandler.class.getName(), SequentialDataWriterAnnotator.PARAM_OUTPUT_DIRECTORY, outputDirectory.getPath(), POSHandler.PARAM_FEATURE_EXTRACTOR_CLASS, DefaultFeatureExtractor.class.getName(), POSHandler.PARAM_TAGGER_CLASS, DefaultTagger.class.getName()); for(@SuppressWarnings("unused") JCas jCas : new JCasIterable(reader, aggregateEngine)); aggregateEngine.collectionProcessComplete(); HideOutput hider = new HideOutput(); Train.main(new String[] {outputDirectory.getPath(), "20", "5"}); hider.restoreOutput(); AnalysisEngine tagger = AnalysisEngineFactory.createAnalysisEngine("org.cleartk.token.pos.impl.DefaultPOSAnnotator", SequentialClassifierAnnotator.PARAM_CLASSIFIER_JAR, new File(outputDirectory, BuildJar.MODEL_FILE_NAME).getPath()); JCas jCas = TestsUtil.getJCas(); TokenFactory.createTokens(jCas, "What kitchen utensil is like a vampire ? Spatula", Token.class, Sentence.class ); tagger.process(jCas); assertEquals("WP", AnnotationRetrieval.get(jCas, Token.class, 0).getPos()); assertEquals("NN", AnnotationRetrieval.get(jCas, Token.class, 1).getPos()); assertEquals("NN", AnnotationRetrieval.get(jCas, Token.class, 2).getPos()); } @Test public void testWriterDescriptor() throws UIMAException, IOException { try { AnalysisEngineFactory.createAnalysisEngine("org.cleartk.token.pos.impl.DefaultPOSAnnotatorDataWriter"); Assert.fail("an exception should be thrown here."); } catch(Exception e) {} AnalysisEngine engine = AnalysisEngineFactory.createAnalysisEngine("org.cleartk.token.pos.impl.DefaultPOSAnnotatorDataWriter", SequentialDataWriterAnnotator.PARAM_OUTPUT_DIRECTORY, outputDirectory.getPath(), SequentialDataWriterAnnotator.PARAM_DATAWRITER_FACTORY_CLASS, DefaultMalletCRFDataWriterFactory.class.getName()); String expected = DefaultPOSHandler.class.getName(); Object actual = engine.getConfigParameterValue( SequentialDataWriterAnnotator.PARAM_ANNOTATION_HANDLER); Assert.assertEquals(expected, actual); expected= DefaultFeatureExtractor.class.getName(); actual= engine.getConfigParameterValue( POSHandler.PARAM_FEATURE_EXTRACTOR_CLASS); Assert.assertEquals(expected, actual); expected= DefaultTagger.class.getName(); actual= engine.getConfigParameterValue( POSHandler.PARAM_TAGGER_CLASS); Assert.assertEquals(expected, actual); } }
package org.jgroups.tests; import org.jgroups.Global; import org.jgroups.Header; import org.jgroups.util.Headers; import org.testng.annotations.Test; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * Tests the functionality of the Headers class * @author Bela Ban * @version $Id: HeadersTest.java,v 1.2 2008/07/30 09:50:22 belaban Exp $ */ @Test(groups=Global.FUNCTIONAL,sequential=false) public class HeadersTest { private static final String UDP="UDP", FRAG="FRAG", NAKACK="NAKACK"; private static final MyHeader h1=new MyHeader(), h2=new MyHeader(), h3=new MyHeader(); public static void testConstructor() { Headers hdrs=new Headers(5); System.out.println("hdrs = " + hdrs); assert hdrs.capacity() == 5 : "capacity must be 5 but was " + hdrs.capacity(); Object[] data=hdrs.getRawData(); assert data.length == hdrs.capacity() * 2; assert hdrs.size() == 0; } public static void testContructor2() { Headers old=createHeaders(3); Headers hdrs=new Headers(old); System.out.println("hdrs = " + hdrs); assert hdrs.capacity() == 3 : "capacity must be 3 but was " + hdrs.capacity(); Object[] data=hdrs.getRawData(); assert data.length == hdrs.capacity() * 2; assert hdrs.size() == 3; // make sure 'hdrs' is not changed when 'old' is modified, as 'hdrs' is a copy old.putHeader("BLA", new MyHeader()); assert hdrs.capacity() == 3 : "capacity must be 3 but was " + hdrs.capacity(); data=hdrs.getRawData(); assert data.length == hdrs.capacity() * 2; assert hdrs.size() == 3; } public static void testGetRawData() { Headers hdrs=createHeaders(3); Object[] data=hdrs.getRawData(); assert data.length == 6; assert data[0].equals(NAKACK); assert data[1].equals(h1); assert data[2].equals(FRAG); assert data[3].equals(h2); assert data[4].equals(UDP); assert data[5].equals(h3); assert data.length == hdrs.capacity() / 2; assert hdrs.size() == 3; } private static Headers createHeaders(int initial_capacity) { Headers hdrs=new Headers(initial_capacity); hdrs.putHeader(NAKACK, h1); hdrs.putHeader(FRAG, h2); hdrs.putHeader(UDP, h3); return hdrs; } public static class MyHeader extends Header { private static final long serialVersionUID=-7164974484154022976L; public MyHeader() { } public String toString() { return "MyHeader"; } public void writeExternal(ObjectOutput out) throws IOException { } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } } }
package com.gdrivefs.simplecache; import java.io.IOException; import java.lang.ref.SoftReference; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Collection; import java.util.ListIterator; import java.util.UUID; class DuplicateRejectingList implements List<File> { List<FileReference> delegate = new ArrayList<FileReference>(); public DuplicateRejectingList() { } public DuplicateRejectingList(Collection<File> seeds) { addAll(seeds); } @Override public boolean add(File element) { if(contains(element)) throw new Error("Duplicate added: "+element); return delegate.add(new FileReference(element)); } @Override public void add(int index, File element) { delegate.add(index, new FileReference(element)); } @Override public boolean addAll(Collection<? extends File> c) { for(File f : c) add(f); return c.size() > 0; } @Override public boolean addAll(int index, Collection<? extends File> c) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public void clear() { delegate.clear(); } @Override public boolean contains(Object o) { if(!(o instanceof File)) return false; return delegate.contains(new FileReference((File)o)); } @Override public boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public File get(int index) { try { return delegate.get(index).get(); } catch(IOException e) { throw new RuntimeException(e); } } @Override public int indexOf(Object o) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public Iterator<File> iterator() { final Iterator<FileReference> iterator = delegate.iterator(); return new Iterator<File>() { @Override public void remove() { iterator.remove(); } @Override public File next() { try { return iterator.next().get(); } catch(IOException e) { throw new RuntimeException(e); } } @Override public boolean hasNext() { return iterator.hasNext(); } }; } @Override public int lastIndexOf(Object o) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public ListIterator<File> listIterator() { throw new UnsupportedOperationException("Not yet implemented"); } @Override public ListIterator<File> listIterator(int index) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean remove(Object o) { if(!(o instanceof File)) return false; return delegate.remove(new FileReference((File)o)); } @Override public File remove(int index) { try { return delegate.remove(index).get(); } catch(IOException e) { throw new RuntimeException(e); } } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public File set(int index, File element) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int size() { return delegate.size(); } @Override public List<File> subList(int fromIndex, int toIndex) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public Object[] toArray() { Object[] array = new Object[delegate.size()]; for(int i = 0; i < delegate.size(); i++) try { array[i] = delegate.get(i).get(); } catch(IOException e) { throw new RuntimeException(e); } return array; } @Override public <T> T[] toArray(T[] a) { return (T[])toArray(); } } class FileReference { Drive drive; String googleId; UUID internalId; SoftReference<File> reference; public FileReference(Drive drive, String googleId, UUID internalId) { this.drive = drive; this.googleId = googleId; this.internalId = internalId; } public FileReference(File file) { this(file.drive, file.googleFileId, file.localFileId); reference = new SoftReference<File>(file); } public File get() throws IOException { File reference = this.reference.get(); if(reference != null) return reference; if(reference == null) reference = drive.getCachedFile(googleId); if(reference == null) reference = drive.getFile(internalId); if(reference == null) throw new Error("Assert not reached"); this.reference = new SoftReference<File>(reference); return reference; } public boolean equals(Object obj) { if(!(obj instanceof FileReference)) return false; FileReference other = (FileReference)obj; if(this.googleId != null && other.googleId != null) if(this.googleId.equals(other.googleId)) return true; else return false; if(this.internalId != null && other.internalId != null) if(this.internalId.equals(other.internalId)) return true; else return false; try { return this.get().equals(other.get()); } catch(IOException e) { throw new RuntimeException(e); } } }
package org.jvnet.hudson.test; import com.gargoylesoftware.htmlunit.AjaxController; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebRequestSettings; import com.gargoylesoftware.htmlunit.html.HtmlButton; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine; import com.gargoylesoftware.htmlunit.javascript.host.Stylesheet; import com.gargoylesoftware.htmlunit.javascript.host.XMLHttpRequest; import hudson.CloseProofOutputStream; import hudson.FilePath; import hudson.Functions; import hudson.Launcher.LocalLauncher; import hudson.WebAppMain; import hudson.matrix.MatrixProject; import hudson.maven.MavenModuleSet; import hudson.maven.MavenReporters; import hudson.model.Descriptor; import hudson.model.FreeStyleProject; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.JDK; import hudson.model.Label; import hudson.model.Node.Mode; import hudson.model.Result; import hudson.model.Run; import hudson.model.Saveable; import hudson.model.TaskListener; import hudson.model.UpdateCenter; import hudson.slaves.CommandLauncher; import hudson.slaves.DumbSlave; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildStep; import hudson.tasks.Mailer; import hudson.tasks.Maven; import hudson.tasks.Maven.MavenInstallation; import hudson.util.ProcessTreeKiller; import hudson.util.StreamTaskListener; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.apache.commons.io.FileUtils; import org.jvnet.hudson.test.HudsonHomeLoader.CopyExisting; import org.jvnet.hudson.test.recipes.Recipe; import org.jvnet.hudson.test.recipes.Recipe.Runner; import org.jvnet.hudson.test.rhino.JavaScriptDebugger; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.security.HashUserRealm; import org.mortbay.jetty.security.UserRealm; import org.mortbay.jetty.webapp.Configuration; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.jetty.webapp.WebXmlConfiguration; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.w3c.css.sac.CSSException; import org.w3c.css.sac.CSSParseException; import org.w3c.css.sac.ErrorHandler; import org.xml.sax.SAXException; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.jar.Manifest; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public abstract class HudsonTestCase extends TestCase { public Hudson hudson; protected final TestEnvironment env = new TestEnvironment(); protected HudsonHomeLoader homeLoader = HudsonHomeLoader.NEW; /** * TCP/IP port that the server is listening on. */ protected int localPort; protected Server server; /** * Where in the {@link Server} is Hudson deploed? */ protected String contextPath = "/"; /** * {@link Runnable}s to be invoked at {@link #tearDown()}. */ protected List<LenientRunnable> tearDowns = new ArrayList<LenientRunnable>(); protected List<Runner> recipes = new ArrayList<Runner>(); /** * Remember {@link WebClient}s that are created, to release them properly. */ private List<WeakReference<WebClient>> clients = new ArrayList<WeakReference<WebClient>>(); /** * JavaScript "debugger" that provides you information about the JavaScript call stack * and the current values of the local variables in those stack frame. * * <p> * Unlike Java debugger, which you as a human interfaces directly and interactively, * this JavaScript debugger is to be interfaced by your program (or through the * expression evaluation capability of your Java debugger.) */ protected JavaScriptDebugger jsDebugger = new JavaScriptDebugger(); protected HudsonTestCase(String name) { super(name); } protected HudsonTestCase() { } protected void setUp() throws Exception { env.pin(); recipe(); hudson = newHudson(); hudson.setNoUsageStatistics(true); // collecting usage stats from tests are pointless. hudson.servletContext.setAttribute("app",hudson); hudson.servletContext.setAttribute("version","?"); WebAppMain.installExpressionFactory(new ServletContextEvent(hudson.servletContext)); // set a default JDK to be the one that the harness is using. hudson.getJDKs().add(new JDK("default",System.getProperty("java.home"))); // cause all the descriptors to reload. // ideally we'd like to reset them to properly emulate the behavior, but that's not possible. Mailer.DESCRIPTOR.setHudsonUrl(null); for( Descriptor d : Descriptor.ALL ) d.load(); } protected void tearDown() throws Exception { // cancel pending asynchronous operations, although this doesn't really seem to be working for (WeakReference<WebClient> client : clients) { WebClient c = client.get(); if(c==null) continue; // unload the page to cancel asynchronous operations c.getPage("about:blank"); } clients.clear(); server.stop(); for (LenientRunnable r : tearDowns) r.run(); // TODO: avoid relying on singletons and switch to some DI container. // In the mean time, discard descriptors created during this exercise. // without this, plugins loaded in the tests will be left and interferes with the later tests. cleanUpDescriptors(Descriptor.ALL); cleanUpDescriptors(BuildStep.PUBLISHERS); cleanUpDescriptors(MavenReporters.LIST); hudson.cleanUp(); env.dispose(); } private void cleanUpDescriptors(Iterable<? extends Descriptor> cont) { ClassLoader base = getClass().getClassLoader(); for (Iterator<? extends Descriptor> itr = cont.iterator(); itr.hasNext();) { Descriptor d = itr.next(); ClassLoader cl = d.getClass().getClassLoader(); if(cl==base) continue; while(cl!=null) { cl = cl.getParent(); if(cl==base) { itr.remove(); break; } } } } protected void runTest() throws Throwable { System.out.println("=== Starting "+getName()); new JavaScriptEngine(null); // ensure that ContextFactory is initialized Context cx= ContextFactory.getGlobal().enterContext(); try { cx.setOptimizationLevel(-1); cx.setDebugger(jsDebugger,null); super.runTest(); } finally { Context.exit(); } } /** * Creates a new instance of {@link Hudson}. If the derived class wants to create it in a different way, * you can override it. */ protected Hudson newHudson() throws Exception { File home = homeLoader.allocate(); for (Runner r : recipes) r.decorateHome(this,home); return new Hudson(home, createWebServer()); } /** * Prepares a webapp hosting environment to get {@link ServletContext} implementation * that we need for testing. */ protected ServletContext createWebServer() throws Exception { server = new Server(); WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath); context.setClassLoader(getClass().getClassLoader()); context.setConfigurations(new Configuration[]{new WebXmlConfiguration(),new NoListenerConfiguration()}); server.setHandler(context); SocketConnector connector = new SocketConnector(); server.addConnector(connector); server.addUserRealm(configureUserRealm()); server.start(); localPort = connector.getLocalPort(); return context.getServletContext(); } /** * Configures a security realm for a test. */ protected UserRealm configureUserRealm() { HashUserRealm realm = new HashUserRealm(); realm.setName("default"); // this is the magic realm name to make it effective on everywhere realm.put("alice","alice"); realm.put("bob","bob"); realm.put("charlie","charlie"); realm.addUserToRole("alice","female"); realm.addUserToRole("bob","male"); realm.addUserToRole("charlie","male"); return realm; } /** * Locates Maven2 and configure that as the only Maven in the system. */ protected void configureDefaultMaven() throws Exception { // first if we are running inside Maven, pick that Maven. String home = System.getProperty("maven.home"); if(home!=null) { Maven.DESCRIPTOR.setInstallations(new MavenInstallation("default",home)); return; } // otherwise extract the copy we have. // this happens when a test is invoked from an IDE, for example. LOGGER.warning("Extracting a copy of Maven bundled in the test harness. " + "To avoid a performance hit, set the system property 'maven.home' to point to a Maven2 installation."); FilePath mvn = hudson.getRootPath().createTempFile("maven", "zip"); OutputStream os = mvn.write(); try { IOUtils.copy(HudsonTestCase.class.getClassLoader().getResourceAsStream("maven-2.0.7-bin.zip"), os); } finally { os.close(); } File mvnHome = createTmpDir(); mvn.unzip(new FilePath(mvnHome)); Maven.DESCRIPTOR.setInstallations(new MavenInstallation("default", new File(mvnHome,"maven-2.0.7").getAbsolutePath())); } // Convenience methods protected FreeStyleProject createFreeStyleProject() throws IOException { return createFreeStyleProject(createUniqueProjectName()); } protected FreeStyleProject createFreeStyleProject(String name) throws IOException { return (FreeStyleProject)hudson.createProject(FreeStyleProject.DESCRIPTOR,name); } protected MatrixProject createMatrixProject() throws IOException { return createMatrixProject(createUniqueProjectName()); } protected MatrixProject createMatrixProject(String name) throws IOException { return (MatrixProject)hudson.createProject(MatrixProject.DESCRIPTOR,name); } /** * Creates a empty Maven project with an unique name. * * @see #configureDefaultMaven() */ protected MavenModuleSet createMavenProject() throws IOException { return createMavenProject(createUniqueProjectName()); } /** * Creates a empty Maven project with the given name. * * @see #configureDefaultMaven() */ protected MavenModuleSet createMavenProject(String name) throws IOException { return (MavenModuleSet)hudson.createProject(MavenModuleSet.DESCRIPTOR,name); } private String createUniqueProjectName() { return "test"+hudson.getItems().size(); } /** * Creates {@link LocalLauncher}. Useful for launching processes. */ protected LocalLauncher createLocalLauncher() { return new LocalLauncher(new StreamTaskListener(System.out)); } /** * Allocates a new temporary directory for the duration of this test. */ public File createTmpDir() throws IOException { return env.temporaryDirectoryAllocator.allocate(); } public DumbSlave createSlave() throws Exception { return createSlave(null); } /** * Creates and launches a new slave on the local host. */ public DumbSlave createSlave(Label l) throws Exception { CommandLauncher launcher = new CommandLauncher( System.getProperty("java.home") + "/bin/java -jar " + hudson.getJnlpJars("slave.jar").getURL().getPath()); // this synchronization block is so that we don't end up adding the same slave name more than once. synchronized (hudson) { DumbSlave slave = new DumbSlave("slave" + hudson.getNodes().size(), "dummy", createTmpDir().getPath(), "1", Mode.NORMAL, l==null?"":l.getName(), launcher, RetentionStrategy.NOOP); hudson.addNode(slave); return slave; } } /** * Returns the last item in the list. */ protected <T> T last(List<T> items) { return items.get(items.size()-1); } /** * Pauses the execution until ENTER is hit in the console. * <p> * This is often very useful so that you can interact with Hudson * from an browser, while developing a test case. */ protected void pause() throws IOException { new BufferedReader(new InputStreamReader(System.in)).readLine(); } /** * Performs a search from the search box. */ protected Page search(String q) throws Exception { HtmlPage top = new WebClient().goTo(""); HtmlForm search = top.getFormByName("search"); search.getInputByName("q").setValueAttribute(q); return search.submit(null); } /** * Asserts that the outcome of the build is a specific outcome. */ public <R extends Run> R assertBuildStatus(Result status, R r) throws Exception { if(status==r.getResult()) return r; // dump the build output System.out.println(r.getLog()); assertEquals(status,r.getResult()); return r; } public <R extends Run> R assertBuildStatusSuccess(R r) throws Exception { assertBuildStatus(Result.SUCCESS,r); return r; } /** * Asserts that the console output of the build contains the given substring. */ public void assertLogContains(String substring, Run run) throws Exception { String log = run.getLog(); if(log.contains(substring)) return; // good! System.out.println(log); fail("Console output of "+run+" didn't contain "+substring); } /** * Asserts that the XPath matches. */ public void assertXPath(HtmlPage page, String xpath) { assertNotNull("There should be an object that matches XPath:"+xpath, page.getDocumentElement().selectSingleNode(xpath)); } /** * Submits the form. */ public HtmlPage submit(HtmlForm form) throws Exception { return (HtmlPage)form.submit((HtmlButton)last(form.getHtmlElementsByTagName("button"))); } /** * Creates a {@link TaskListener} connected to stdout. */ public TaskListener createTaskListener() { return new StreamTaskListener(new CloseProofOutputStream(System.out)); } // recipe methods. Control the test environments. /** * Called during the {@link #setUp()} to give a test case an opportunity to * control the test environment in which Hudson is run. * * <p> * One could override this method and call a series of {@code withXXX} methods, * or you can use the annotations with {@link Recipe} meta-annotation. */ protected void recipe() throws Exception { recipeLoadCurrentPlugin(); // look for recipe meta-annotation Method runMethod= getClass().getMethod(getName()); for( final Annotation a : runMethod.getAnnotations() ) { Recipe r = a.annotationType().getAnnotation(Recipe.class); if(r==null) continue; final Runner runner = r.value().newInstance(); recipes.add(runner); tearDowns.add(new LenientRunnable() { public void run() throws Exception { runner.tearDown(HudsonTestCase.this,a); } }); runner.setup(this,a); } } protected void recipeLoadCurrentPlugin() throws Exception { Enumeration<URL> e = getClass().getClassLoader().getResources("the.hpl"); if(!e.hasMoreElements()) return; // nope final URL hpl = e.nextElement(); if(e.hasMoreElements()) { // this happens if one plugin produces a test jar and another plugin depends on it. // I can't think of a good way to make this work, so for now, just detect that and report an error. URL hpl2 = e.nextElement(); throw new Error("We have both "+hpl+" and "+hpl2); } recipes.add(new Runner() { @Override public void decorateHome(HudsonTestCase testCase, File home) throws Exception { Manifest m = new Manifest(hpl.openStream()); String shortName = m.getMainAttributes().getValue("Short-Name"); if(shortName==null) throw new Error(hpl+" doesn't have the Short-Name attribute"); FileUtils.copyURLToFile(hpl,new File(home,"plugins/"+shortName+".hpl")); } }); } public HudsonTestCase withNewHome() { return with(HudsonHomeLoader.NEW); } public HudsonTestCase withExistingHome(File source) throws Exception { return with(new CopyExisting(source)); } public HudsonTestCase withPresetData(String name) { name = "/" + name + ".zip"; URL res = getClass().getResource(name); if(res==null) throw new IllegalArgumentException("No such data set found: "+name); return with(new CopyExisting(res)); } public HudsonTestCase with(HudsonHomeLoader homeLoader) { this.homeLoader = homeLoader; return this; } /** * Sometimes a part of a test case may ends up creeping into the serialization tree of {@link Saveable#save()}, * so detect that and flag that as an error. */ private Object writeReplace() { throw new AssertionError("HudsonTestCase "+getName()+" is not supposed to be serialized"); } /** * Extends {@link com.gargoylesoftware.htmlunit.WebClient} and provide convenience methods * for accessing Hudson. */ public class WebClient extends com.gargoylesoftware.htmlunit.WebClient { public WebClient() { // default is IE6, but this causes 'n.doScroll('left')' to fail in event-debug.js:1907 as HtmlUnit doesn't implement such a method, // so trying something else, until we discover another problem. super(BrowserVersion.FIREFOX_2); // setJavaScriptEnabled(false); setPageCreator(HudsonPageCreator.INSTANCE); clients.add(new WeakReference<WebClient>(this)); // make ajax calls synchronous for predictable behaviors that simplify debugging setAjaxController(new AjaxController() { public boolean processSynchron(HtmlPage page, WebRequestSettings settings, boolean async) { return true; } }); } /** * Logs in to Hudson. */ public WebClient login(String username, String password) throws Exception { HtmlPage page = goTo("login"); // page = (HtmlPage) page.getFirstAnchorByText("Login").click(); HtmlForm form = page.getFormByName("login"); form.getInputByName("j_username").setValueAttribute(username); form.getInputByName("j_password").setValueAttribute(password); form.submit(null); return this; } /** * Logs in to Hudson, by using the user name as the password. * * <p> * See {@link HudsonTestCase#configureUserRealm()} for how the container is set up with the user names * and passwords. All the test accounts have the same user name and password. */ public WebClient login(String username) throws Exception { login(username,username); return this; } /** * Short for {@code getPage(r,"")}, to access the top page of a build. */ public HtmlPage getPage(Run r) throws IOException, SAXException { return getPage(r,""); } /** * Accesses a page inside {@link Run}. * * @param relative * Relative URL within the build URL, like "changes". Doesn't start with '/'. Can be empty. */ public HtmlPage getPage(Run r, String relative) throws IOException, SAXException { return goTo(r.getUrl()+relative); } public HtmlPage getPage(Item item) throws IOException, SAXException { return getPage(item,""); } public HtmlPage getPage(Item item, String relative) throws IOException, SAXException { return goTo(item.getUrl()+relative); } /** * @deprecated * This method expects a full URL. This method is marked as deprecated to warn you * that you probably should be using {@link #goTo(String)} method, which accepts * a relative path within the Hudson being tested. (IOW, if you really need to hit * a website on the internet, there's nothing wrong with using this method.) */ public Page getPage(String url) throws IOException, FailingHttpStatusCodeException { return super.getPage(url); } /** * Requests a page within Hudson. * * @param relative * Relative path within Hudson. Starts without '/'. * For example, "job/test/" to go to a job top page. */ public HtmlPage goTo(String relative) throws IOException, SAXException { Page p = goTo(relative, "text/html"); if (p instanceof HtmlPage) { return (HtmlPage) p; } else { throw new AssertionError("Expected text/html but instead the content type was "+p.getWebResponse().getContentType()); } } public Page goTo(String relative, String expectedContentType) throws IOException, SAXException { return super.getPage(getContextPath() +relative); } /** * Returns the URL of the webapp top page. * URL ends with '/'. */ public String getContextPath() { return "http://localhost:"+localPort+contextPath; } } // needs to keep reference, or it gets GC-ed. private static final Logger XML_HTTP_REQUEST_LOGGER = Logger.getLogger(XMLHttpRequest.class.getName()); static { // screen scraping relies on locale being fixed. Locale.setDefault(Locale.ENGLISH); // don't waste bandwidth talking to the update center UpdateCenter.neverUpdate = true; // enable debug assistance System.setProperty("stapler.trace","true"); // we don't care CSS errors in YUI final ErrorHandler defaultHandler = Stylesheet.CSS_ERROR_HANDLER; Stylesheet.CSS_ERROR_HANDLER = new ErrorHandler() { public void warning(CSSParseException exception) throws CSSException { if(!ignore(exception)) defaultHandler.warning(exception); } public void error(CSSParseException exception) throws CSSException { if(!ignore(exception)) defaultHandler.error(exception); } public void fatalError(CSSParseException exception) throws CSSException { if(!ignore(exception)) defaultHandler.fatalError(exception); } private boolean ignore(CSSParseException e) { return e.getURI().contains("/yui/"); } }; // clean up run-away processes extra hard ProcessTreeKiller.enabled = true; // suppress INFO output from Spring, which is verbose Logger.getLogger("org.springframework").setLevel(Level.WARNING); // hudson-behavior.js relies on this to decide whether it's running unit tests. Functions.isUnitTest = true; // prototype.js calls this method all the time, so ignore this warning. XML_HTTP_REQUEST_LOGGER.setFilter(new Filter() { public boolean isLoggable(LogRecord record) { return !record.getMessage().contains("XMLHttpRequest.getResponseHeader() was called before the response was available."); } }); } private static final Logger LOGGER = Logger.getLogger(HudsonTestCase.class.getName()); }
package railo.runtime; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import java.util.TimeZone; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTag; import javax.servlet.jsp.tagext.Tag; import javax.servlet.jsp.tagext.TryCatchFinally; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcherInput; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import railo.commons.io.BodyContentStack; import railo.commons.io.IOUtil; import railo.commons.io.res.Resource; import railo.commons.io.res.util.ResourceClassLoader; import railo.commons.io.res.util.ResourceUtil; import railo.commons.lang.PhysicalClassLoader; import railo.commons.lang.SizeOf; import railo.commons.lang.StringUtil; import railo.commons.lang.SystemOut; import railo.commons.lang.mimetype.MimeType; import railo.commons.lang.types.RefBoolean; import railo.commons.lang.types.RefBooleanImpl; import railo.commons.lock.KeyLock; import railo.commons.lock.Lock; import railo.commons.net.HTTPUtil; import railo.intergral.fusiondebug.server.FDSignal; import railo.runtime.component.ComponentLoader; import railo.runtime.config.Config; import railo.runtime.config.ConfigImpl; import railo.runtime.config.ConfigWeb; import railo.runtime.config.ConfigWebImpl; import railo.runtime.config.Constants; import railo.runtime.config.NullSupportHelper; import railo.runtime.db.DataSource; import railo.runtime.db.DataSourceManager; import railo.runtime.db.DatasourceConnection; import railo.runtime.db.DatasourceConnectionPool; import railo.runtime.db.DatasourceManagerImpl; import railo.runtime.debug.ActiveLock; import railo.runtime.debug.ActiveQuery; import railo.runtime.debug.DebugCFMLWriter; import railo.runtime.debug.DebugEntryTemplate; import railo.runtime.debug.Debugger; import railo.runtime.debug.DebuggerImpl; import railo.runtime.debug.DebuggerPro; import railo.runtime.dump.DumpUtil; import railo.runtime.dump.DumpWriter; import railo.runtime.engine.ExecutionLog; import railo.runtime.engine.ThreadLocalPageContext; import railo.runtime.err.ErrorPage; import railo.runtime.err.ErrorPageImpl; import railo.runtime.err.ErrorPagePool; import railo.runtime.exp.Abort; import railo.runtime.exp.ApplicationException; import railo.runtime.exp.CasterException; import railo.runtime.exp.ExceptionHandler; import railo.runtime.exp.ExpressionException; import railo.runtime.exp.MissingIncludeException; import railo.runtime.exp.PageException; import railo.runtime.exp.PageExceptionBox; import railo.runtime.exp.PageServletException; import railo.runtime.functions.dynamicEvaluation.Serialize; import railo.runtime.interpreter.CFMLExpressionInterpreter; import railo.runtime.interpreter.VariableInterpreter; import railo.runtime.listener.ApplicationContext; import railo.runtime.listener.ApplicationContextPro; import railo.runtime.listener.ApplicationListener; import railo.runtime.listener.ClassicApplicationContext; import railo.runtime.listener.JavaSettingsImpl; import railo.runtime.listener.ModernAppListenerException; import railo.runtime.monitor.RequestMonitor; import railo.runtime.net.ftp.FTPPool; import railo.runtime.net.ftp.FTPPoolImpl; import railo.runtime.net.http.HTTPServletRequestWrap; import railo.runtime.net.http.ReqRspUtil; import railo.runtime.op.Caster; import railo.runtime.op.Decision; import railo.runtime.orm.ORMConfiguration; import railo.runtime.orm.ORMEngine; import railo.runtime.orm.ORMSession; import railo.runtime.query.QueryCache; import railo.runtime.rest.RestRequestListener; import railo.runtime.rest.RestUtil; import railo.runtime.security.Credential; import railo.runtime.security.CredentialImpl; import railo.runtime.tag.Login; import railo.runtime.tag.TagHandlerPool; import railo.runtime.type.Array; import railo.runtime.type.Collection; import railo.runtime.type.Collection.Key; import railo.runtime.type.Iterator; import railo.runtime.type.KeyImpl; import railo.runtime.type.Query; import railo.runtime.type.SVArray; import railo.runtime.type.Sizeable; import railo.runtime.type.Struct; import railo.runtime.type.StructImpl; import railo.runtime.type.UDF; import railo.runtime.type.UDFPlus; import railo.runtime.type.it.ItAsEnum; import railo.runtime.type.ref.Reference; import railo.runtime.type.ref.VariableReference; import railo.runtime.type.scope.Application; import railo.runtime.type.scope.Argument; import railo.runtime.type.scope.ArgumentImpl; import railo.runtime.type.scope.CGI; import railo.runtime.type.scope.CGIImpl; import railo.runtime.type.scope.Client; import railo.runtime.type.scope.Cluster; import railo.runtime.type.scope.Cookie; import railo.runtime.type.scope.CookieImpl; import railo.runtime.type.scope.Form; import railo.runtime.type.scope.FormImpl; import railo.runtime.type.scope.Local; import railo.runtime.type.scope.LocalNotSupportedScope; import railo.runtime.type.scope.Request; import railo.runtime.type.scope.RequestImpl; import railo.runtime.type.scope.Scope; import railo.runtime.type.scope.ScopeContext; import railo.runtime.type.scope.ScopeFactory; import railo.runtime.type.scope.ScopeSupport; import railo.runtime.type.scope.Server; import railo.runtime.type.scope.Session; import railo.runtime.type.scope.Threads; import railo.runtime.type.scope.URL; import railo.runtime.type.scope.URLForm; import railo.runtime.type.scope.URLImpl; import railo.runtime.type.scope.Undefined; import railo.runtime.type.scope.UndefinedImpl; import railo.runtime.type.scope.UrlFormImpl; import railo.runtime.type.scope.Variables; import railo.runtime.type.scope.VariablesImpl; import railo.runtime.type.util.CollectionUtil; import railo.runtime.type.util.KeyConstants; import railo.runtime.type.util.ListUtil; import railo.runtime.util.VariableUtil; import railo.runtime.util.VariableUtilImpl; import railo.runtime.writer.CFMLWriter; import railo.runtime.writer.DevNullBodyContent; /** * page context for every page object. * the PageContext is a jsp page context expanded by CFML functionality. * for example you have the method getSession to get jsp combatible session object (HTTPSession) * and with sessionScope() you get CFML combatible session object (Struct,Scope). */ public final class PageContextImpl extends PageContext implements Sizeable { private static final RefBoolean DUMMY_BOOL = new RefBooleanImpl(false); private static int counter=0; /** * Field <code>pathList</code> */ private LinkedList<UDF> udfs=new LinkedList<UDF>(); private LinkedList<PageSource> pathList=new LinkedList<PageSource>(); private LinkedList<PageSource> includePathList=new LinkedList<PageSource>(); private Set<PageSource> includeOnce=new HashSet<PageSource>(); /** * Field <code>executionTime</code> */ protected long executionTime=0; private HTTPServletRequestWrap req; private HttpServletResponse rsp; private HttpServlet servlet; private JspWriter writer; private JspWriter forceWriter; private BodyContentStack bodyContentStack; private DevNullBodyContent devNull; private ConfigWebImpl config; //private DataSourceManager manager; //private CFMLCompilerImpl compiler; // Scopes private ScopeContext scopeContext; private Variables variablesRoot=new VariablesImpl();//ScopeSupport(false,"variables",Scope.SCOPE_VARIABLES); private Variables variables=variablesRoot;//new ScopeSupport("variables",Scope.SCOPE_VARIABLES); private Undefined undefined; private URLImpl _url=new URLImpl(); private FormImpl _form=new FormImpl(); private URLForm urlForm=new UrlFormImpl(_form,_url); private URL url; private Form form; private RequestImpl request=new RequestImpl(); private CGIImpl cgi=new CGIImpl(); private Argument argument=new ArgumentImpl(); private static LocalNotSupportedScope localUnsupportedScope=LocalNotSupportedScope.getInstance(); private Local local=localUnsupportedScope; private Session session; private Server server; private Cluster cluster; private CookieImpl cookie=new CookieImpl(); private Client client; private Application application; private DebuggerPro debugger=new DebuggerImpl(); private long requestTimeout=-1; private short enablecfoutputonly=0; private int outputState; private String cfid; private String cftoken; private int id; private int requestId; private boolean psq; private Locale locale; private TimeZone timeZone; // Pools private ErrorPagePool errorPagePool=new ErrorPagePool(); private TagHandlerPool tagHandlerPool; private FTPPool ftpPool=new FTPPoolImpl(); private final QueryCache queryCache; private Component activeComponent; private UDF activeUDF; private Collection.Key activeUDFCalledName; //private ComponentScope componentScope=new ComponentScope(this); private Credential remoteUser; protected VariableUtilImpl variableUtil=new VariableUtilImpl(); private PageException exception; private PageSource base; ApplicationContext applicationContext; ApplicationContext defaultApplicationContext; private ScopeFactory scopeFactory=new ScopeFactory(); private Tag parentTag=null; private Tag currentTag=null; private Thread thread; private long startTime; private boolean isCFCRequest; private DatasourceManagerImpl manager; private Struct threads; private boolean hasFamily=false; //private CFMLFactoryImpl factory; private PageContextImpl parent; private Map<String,DatasourceConnection> conns=new HashMap<String,DatasourceConnection>(); private boolean fdEnabled; private ExecutionLog execLog; private boolean useSpecialMappings; private ORMSession ormSession; private boolean isChild; private boolean gatewayContext; private String serverPassword; private PageException pe; public long sizeOf() { return SizeOf.size(pathList)+ SizeOf.size(includePathList)+ SizeOf.size(executionTime)+ SizeOf.size(writer)+ SizeOf.size(forceWriter)+ SizeOf.size(bodyContentStack)+ SizeOf.size(variables)+ SizeOf.size(url)+ SizeOf.size(form)+ SizeOf.size(_url)+ SizeOf.size(_form)+ SizeOf.size(request)+ SizeOf.size(argument)+ SizeOf.size(local)+ SizeOf.size(cookie)+ SizeOf.size(debugger)+ SizeOf.size(requestTimeout)+ SizeOf.size(enablecfoutputonly)+ SizeOf.size(outputState)+ SizeOf.size(cfid)+ SizeOf.size(cftoken)+ SizeOf.size(id)+ SizeOf.size(psq)+ SizeOf.size(locale)+ SizeOf.size(errorPagePool)+ SizeOf.size(tagHandlerPool)+ SizeOf.size(ftpPool)+ SizeOf.size(activeComponent)+ SizeOf.size(activeUDF)+ SizeOf.size(remoteUser)+ SizeOf.size(exception)+ SizeOf.size(base)+ SizeOf.size(applicationContext)+ SizeOf.size(defaultApplicationContext)+ SizeOf.size(parentTag)+ SizeOf.size(currentTag)+ SizeOf.size(startTime)+ SizeOf.size(isCFCRequest)+ SizeOf.size(conns)+ SizeOf.size(serverPassword)+ SizeOf.size(ormSession); } /** * default Constructor * @param scopeContext * @param config Configuration of the CFML Container * @param queryCache Query Cache Object * @param id identity of the pageContext * @param servlet */ public PageContextImpl(ScopeContext scopeContext, ConfigWebImpl config, QueryCache queryCache,int id,HttpServlet servlet) { // must be first because is used after tagHandlerPool=config.getTagHandlerPool(); this.servlet=servlet; this.id=id; //this.factory=factory; bodyContentStack=new BodyContentStack(); devNull=bodyContentStack.getDevNullBodyContent(); this.config=config; manager=new DatasourceManagerImpl(config); this.scopeContext=scopeContext; undefined= new UndefinedImpl(this,config.getScopeCascadingType()); //this.compiler=compiler; //tagHandlerPool=config.getTagHandlerPool(); this.queryCache=queryCache; server=ScopeContext.getServerScope(this); defaultApplicationContext=new ClassicApplicationContext(config,"",true,null); } @Override public void initialize( Servlet servlet, ServletRequest req, ServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { initialize( (HttpServlet)servlet, (HttpServletRequest)req, (HttpServletResponse)rsp, errorPageURL, needsSession, bufferSize, autoFlush,false); } /** * initialize a existing page context * @param servlet * @param req * @param rsp * @param errorPageURL * @param needsSession * @param bufferSize * @param autoFlush */ public PageContextImpl initialize( HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush, boolean isChild) { requestId=counter++; rsp.setContentType("text/html; charset=UTF-8"); this.isChild=isChild; //rsp.setHeader("Connection", "close"); applicationContext=defaultApplicationContext; startTime=System.currentTimeMillis(); thread=Thread.currentThread(); isCFCRequest = StringUtil.endsWithIgnoreCase(req.getServletPath(),"."+config.getCFCExtension()); this.req=new HTTPServletRequestWrap(req); this.rsp=rsp; this.servlet=servlet; // Writers if(config.debugLogOutput()) { CFMLWriter w = config.getCFMLWriter(req,rsp); w.setAllowCompression(false); DebugCFMLWriter dcw = new DebugCFMLWriter(w); bodyContentStack.init(dcw); debugger.setOutputLog(dcw); } else { bodyContentStack.init(config.getCFMLWriter(req,rsp)); } writer=bodyContentStack.getWriter(); forceWriter=writer; // Scopes server=ScopeContext.getServerScope(this); if(hasFamily) { variablesRoot=new VariablesImpl(); variables=variablesRoot; request=new RequestImpl(); _url=new URLImpl(); _form=new FormImpl(); urlForm=new UrlFormImpl(_form,_url); undefined= new UndefinedImpl(this,config.getScopeCascadingType()); hasFamily=false; } else if(variables==null) { variablesRoot=new VariablesImpl(); variables=variablesRoot; } request.initialize(this); if(config.mergeFormAndURL()) { url=urlForm; form=urlForm; } else { url=_url; form=_form; } //url.initialize(this); //form.initialize(this); //undefined.initialize(this); psq=config.getPSQL(); fdEnabled=!config.allowRequestTimeout(); if(config.getExecutionLogEnabled()) this.execLog=config.getExecutionLogFactory().getInstance(this); if(config.debug()) debugger.init(config); return this; } @Override public void release() { if(config.getExecutionLogEnabled()){ execLog.release(); execLog=null; } if(config.debug()) { if(!gatewayContext)config.getDebuggerPool().store(this, debugger); debugger.reset(); } else ((DebuggerImpl)debugger).resetTraces(); // traces can alo be used when debugging is off this.serverPassword=null; boolean isChild=parent!=null; parent=null; // Attention have to be before close if(client!=null){ client.touchAfterRequest(this); client=null; } if(session!=null){ session.touchAfterRequest(this); session=null; } // ORM if(ormSession!=null){ // flush orm session try { ORMEngine engine=ormSession.getEngine(); ORMConfiguration config=engine.getConfiguration(this); if(config==null || (config.flushAtRequestEnd() && config.autoManageSession())){ ormSession.flush(this); //ormSession.close(this); //print.err("2orm flush:"+Thread.currentThread().getId()); } ormSession.close(this); } catch (Throwable t) { //print.printST(t); } ormSession=null; } close(); thread=null; base=null; //RequestImpl r = request; // Scopes if(hasFamily) { if(!isChild){ req.disconnect(); } request=null; _url=null; _form=null; urlForm=null; undefined=null; variables=null; variablesRoot=null; if(threads!=null && threads.size()>0) threads.clear(); } else { if(variables.isBind()) { variables=null; variablesRoot=null; } else { variables=variablesRoot; variables.release(this); } undefined.release(this); urlForm.release(this); request.release(); } cgi.release(); argument.release(this); local=localUnsupportedScope; cookie.release(); //if(cluster!=null)cluster.release(); //client=null; //session=null; application=null;// not needed at the moment -> application.releaseAfterRequest(); applicationContext=null; // Properties requestTimeout=-1; outputState=0; cfid=null; cftoken=null; locale=null; timeZone=null; url=null; form=null; // Pools errorPagePool.clear(); // transaction connection if(!conns.isEmpty()){ java.util.Iterator<Entry<String, DatasourceConnection>> it = conns.entrySet().iterator(); DatasourceConnectionPool pool = config.getDatasourceConnectionPool(); while(it.hasNext()) { pool.releaseDatasourceConnection((it.next().getValue())); } conns.clear(); } pathList.clear(); includePathList.clear(); executionTime=0; bodyContentStack.release(); //activeComponent=null; remoteUser=null; exception=null; ftpPool.clear(); parentTag=null; currentTag=null; // Req/Rsp //if(req!=null) req.clear(); req=null; rsp=null; servlet=null; // Writer writer=null; forceWriter=null; if(pagesUsed.size()>0)pagesUsed.clear(); activeComponent=null; activeUDF=null; gatewayContext=false; manager.release(); includeOnce.clear(); pe=null; } @Override public void write(String str) throws IOException { writer.write(str); } @Override public void forceWrite(String str) throws IOException { forceWriter.write(str); } @Override public void writePSQ(Object o) throws IOException, PageException { if(o instanceof Date || Decision.isDate(o, false)) { writer.write(Caster.toString(o)); } else { writer.write(psq?Caster.toString(o):StringUtil.replace(Caster.toString(o),"'","''",false)); } } @Override public void flush() { try { getOut().flush(); } catch (IOException e) {} } @Override public void close() { IOUtil.closeEL(getOut()); } public PageSource getRelativePageSource(String realPath) { SystemOut.print(config.getOutWriter(),"method getRelativePageSource is deprecated"); if(StringUtil.startsWith(realPath,'/')) return PageSourceImpl.best(getPageSources(realPath)); if(pathList.size()==0) return null; return pathList.getLast().getRealPage(realPath); } public PageSource getRelativePageSourceExisting(String realPath) { if(StringUtil.startsWith(realPath,'/')) return getPageSourceExisting(realPath); if(pathList.size()==0) return null; PageSource ps = pathList.getLast().getRealPage(realPath); if(PageSourceImpl.pageExist(ps)) return ps; return null; } /** * * @param realPath * @param previous relative not to the caller, relative to the callers caller * @return */ public PageSource getRelativePageSourceExisting(String realPath, boolean previous ) { if(StringUtil.startsWith(realPath,'/')) return getPageSourceExisting(realPath); if(pathList.size()==0) return null; PageSource ps=null,tmp=null; if(previous) { boolean valid=false; ps=pathList.getLast(); for(int i=pathList.size()-2;i>=0;i tmp=pathList.get(i); if(tmp!=ps) { ps=tmp; valid=true; break; } } if(!valid) return null; } else ps=pathList.getLast(); ps = ps.getRealPage(realPath); if(PageSourceImpl.pageExist(ps)) return ps; return null; } public PageSource[] getRelativePageSources(String realPath) { if(StringUtil.startsWith(realPath,'/')) return getPageSources(realPath); if(pathList.size()==0) return null; return new PageSource[]{ pathList.getLast().getRealPage(realPath)}; } public PageSource getPageSource(String realPath) { SystemOut.print(config.getOutWriter(),"method getPageSource is deprecated"); return PageSourceImpl.best(config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true)); } public PageSource[] getPageSources(String realPath) { return config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true); } public PageSource getPageSourceExisting(String realPath) { return config.getPageSourceExisting(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true,false); } public boolean useSpecialMappings(boolean useTagMappings) { boolean b=this.useSpecialMappings; this.useSpecialMappings=useTagMappings; return b; } public boolean useSpecialMappings() { return useSpecialMappings; } public Resource getPhysical(String realPath, boolean alsoDefaultMapping){ return config.getPhysical(applicationContext.getMappings(),realPath, alsoDefaultMapping); } public PageSource toPageSource(Resource res, PageSource defaultValue){ return config.toPageSource(applicationContext.getMappings(),res, defaultValue); } @Override public void doInclude(String realPath) throws PageException { doInclude(getRelativePageSources(realPath),false); } @Override public void doInclude(String realPath, boolean runOnce) throws PageException { doInclude(getRelativePageSources(realPath),runOnce); } @Override public void doInclude(PageSource source) throws PageException { doInclude(new PageSource[]{source},false); } @Override public void doInclude(PageSource[] sources, boolean runOnce) throws PageException { // debug if(!gatewayContext && config.debug()) { long currTime=executionTime; long exeTime=0; long time=System.nanoTime(); Page currentPage = PageSourceImpl.loadPage(this, sources); if(runOnce && includeOnce.contains(currentPage.getPageSource())) return; DebugEntryTemplate debugEntry=debugger.getEntry(this,currentPage.getPageSource()); try { addPageSource(currentPage.getPageSource(),true); debugEntry.updateFileLoadTime((System.nanoTime()-time)); exeTime=System.nanoTime(); currentPage.call(this); } catch(Throwable t){ PageException pe = Caster.toPageException(t); if(Abort.isAbort(pe)) { if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe; } else { if(fdEnabled){ FDSignal.signal(pe, false); } pe.addContext(currentPage.getPageSource(),-187,-187, null);// TODO was soll das 187 throw pe; } } finally { includeOnce.add(currentPage.getPageSource()); long diff= ((System.nanoTime()-exeTime)-(executionTime-currTime)); executionTime+=(System.nanoTime()-time); debugEntry.updateExeTime(diff); removeLastPageSource(true); } } // no debug else { Page currentPage = PageSourceImpl.loadPage(this, sources); if(runOnce && includeOnce.contains(currentPage.getPageSource())) return; try { addPageSource(currentPage.getPageSource(),true); currentPage.call(this); } catch(Throwable t){ PageException pe = Caster.toPageException(t); if(Abort.isAbort(pe)) { if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe; } else { pe.addContext(currentPage.getPageSource(),-187,-187, null); throw pe; } } finally { includeOnce.add(currentPage.getPageSource()); removeLastPageSource(true); } } } @Override public Array getTemplatePath() throws PageException { int len=includePathList.size(); SVArray sva = new SVArray(); PageSource ps; for(int i=0;i<len;i++) { ps=includePathList.get(i); if(i==0) { if(!ps.equals(getBasePageSource())) sva.append(ResourceUtil.getResource(this,getBasePageSource()).getAbsolutePath()); } sva.append(ResourceUtil.getResource(this, ps).getAbsolutePath()); } //sva.setPosition(sva.size()); return sva; } public List<PageSource> getPageSourceList() { return (List<PageSource>) pathList.clone(); } protected PageSource getPageSource(int index) { return includePathList.get(index-1); } public synchronized void copyStateTo(PageContextImpl other) { // private Debugger debugger=new DebuggerImpl(); other.requestTimeout=requestTimeout; other.locale=locale; other.timeZone=timeZone; other.fdEnabled=fdEnabled; other.useSpecialMappings=useSpecialMappings; other.serverPassword=serverPassword; hasFamily=true; other.hasFamily=true; other.parent=this; other.applicationContext=applicationContext; other.thread=Thread.currentThread(); other.startTime=System.currentTimeMillis(); other.isCFCRequest = isCFCRequest; // path other.base=base; java.util.Iterator<PageSource> it = includePathList.iterator(); while(it.hasNext()) { other.includePathList.add(it.next()); } it = pathList.iterator(); while(it.hasNext()) { other.pathList.add(it.next()); } // scopes //other.req.setAttributes(request); /*HttpServletRequest org = other.req.getOriginalRequest(); if(org instanceof HttpServletRequestDummy) { ((HttpServletRequestDummy)org).setAttributes(request); }*/ other.req=req; other.request=request; other.form=form; other.url=url; other.urlForm=urlForm; other._url=_url; other._form=_form; other.variables=variables; other.undefined=new UndefinedImpl(other,(short)other.undefined.getType()); // writers other.bodyContentStack.init(config.getCFMLWriter(other.req,other.rsp)); //other.bodyContentStack.init(other.req,other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(), other.config.isShowVersion(),config.contentLength(),config.allowCompression()); other.writer=other.bodyContentStack.getWriter(); other.forceWriter=other.writer; other.psq=psq; other.gatewayContext=gatewayContext; // thread if(threads!=null){ synchronized (threads) { java.util.Iterator<Entry<Key, Object>> it2 = threads.entryIterator(); Entry<Key, Object> entry; while(it2.hasNext()) { entry = it2.next(); other.setThreadScope(entry.getKey(), (Threads)entry.getValue()); } } } } /*public static void setState(PageContextImpl other,ApplicationContext applicationContext, boolean isCFCRequest) { other.hasFamily=true; other.applicationContext=applicationContext; other.thread=Thread.currentThread(); other.startTime=System.currentTimeMillis(); other.isCFCRequest = isCFCRequest; // path other.base=base; java.util.Iterator it = includePathList.iterator(); while(it.hasNext()) { other.includePathList.add(it.next()); } // scopes other.request=request; other.form=form; other.url=url; other.urlForm=urlForm; other._url=_url; other._form=_form; other.variables=variables; other.undefined=new UndefinedImpl(other,(short)other.undefined.getType()); // writers other.bodyContentStack.init(other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(),other.config.isShowVersion()); other.writer=other.bodyContentStack.getWriter(); other.forceWriter=other.writer; other.psq=psq; }*/ public int getCurrentLevel() { return includePathList.size()+1; } /** * @return the current template SourceFile */ public PageSource getCurrentPageSource() { return pathList.getLast(); } public PageSource getCurrentPageSource(PageSource defaultvalue) { try{ return pathList.getLast(); } catch(Throwable t){ return defaultvalue; } } /** * @return the current template SourceFile */ public PageSource getCurrentTemplatePageSource() { return includePathList.getLast(); } /** * @return base template file */ public PageSource getBasePageSource() { return base; } @Override public Resource getRootTemplateDirectory() { return config.getResource(ReqRspUtil.getRootPath(servlet.getServletContext())); } @Override public Scope scope(int type) throws PageException { switch(type) { case Scope.SCOPE_UNDEFINED: return undefinedScope(); case Scope.SCOPE_URL: return urlScope(); case Scope.SCOPE_FORM: return formScope(); case Scope.SCOPE_VARIABLES: return variablesScope(); case Scope.SCOPE_REQUEST: return requestScope(); case Scope.SCOPE_CGI: return cgiScope(); case Scope.SCOPE_APPLICATION: return applicationScope(); case Scope.SCOPE_ARGUMENTS: return argumentsScope(); case Scope.SCOPE_SESSION: return sessionScope(); case Scope.SCOPE_SERVER: return serverScope(); case Scope.SCOPE_COOKIE: return cookieScope(); case Scope.SCOPE_CLIENT: return clientScope(); case Scope.SCOPE_LOCAL: case ScopeSupport.SCOPE_VAR: return localScope(); case Scope.SCOPE_CLUSTER:return clusterScope(); } return variables; } public Scope scope(String strScope,Scope defaultValue) throws PageException { if(strScope==null)return defaultValue; strScope=strScope.toLowerCase().trim(); if("variables".equals(strScope)) return variablesScope(); if("url".equals(strScope)) return urlScope(); if("form".equals(strScope)) return formScope(); if("request".equals(strScope)) return requestScope(); if("cgi".equals(strScope)) return cgiScope(); if("application".equals(strScope)) return applicationScope(); if("arguments".equals(strScope)) return argumentsScope(); if("session".equals(strScope)) return sessionScope(); if("server".equals(strScope)) return serverScope(); if("cookie".equals(strScope)) return cookieScope(); if("client".equals(strScope)) return clientScope(); if("local".equals(strScope)) return localScope(); if("cluster".equals(strScope)) return clusterScope(); return defaultValue; } @Override public Undefined undefinedScope() { if(!undefined.isInitalized()) undefined.initialize(this); return undefined; } /** * @return undefined scope, undefined scope is a placeholder for the scopecascading */ public Undefined us() { if(!undefined.isInitalized()) undefined.initialize(this); return undefined; } @Override public Variables variablesScope() { return variables; } @Override public URL urlScope() { if(!url.isInitalized())url.initialize(this); return url; } @Override public Form formScope() { if(!form.isInitalized())form.initialize(this); return form; } @Override public URLForm urlFormScope() { if(!urlForm.isInitalized())urlForm.initialize(this); return urlForm; } @Override public Request requestScope() { return request; } @Override public CGI cgiScope() { if(!cgi.isInitalized())cgi.initialize(this); return cgi; } @Override public Application applicationScope() throws PageException { if(application==null) { if(!applicationContext.hasName()) throw new ExpressionException("there is no application context defined for this application","you can define a application context with the tag "+railo.runtime.config.Constants.CFAPP_NAME+"/"+railo.runtime.config.Constants.APP_CFC); application=scopeContext.getApplicationScope(this,DUMMY_BOOL); } return application; } @Override public Argument argumentsScope() { return argument; } @Override public Argument argumentsScope(boolean bind) { //Argument a=argumentsScope(); if(bind)argument.setBind(true); return argument; } @Override public Local localScope() { //if(local==localUnsupportedScope) // throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope")); return local; } @Override public Local localScope(boolean bind) { if(bind)local.setBind(true); //if(local==localUnsupportedScope) // throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope")); return local; } public Object localGet() throws PageException { return localGet(false); } public Object localGet(boolean bind, Object defaultValue) { if(undefined.getCheckArguments()){ return localScope(bind); } return undefinedScope().get(KeyConstants._local,defaultValue); } public Object localGet(boolean bind) throws PageException { // inside a local supported block if(undefined.getCheckArguments()){ return localScope(bind); } return undefinedScope().get(KeyConstants._local); } public Object localTouch() throws PageException { return localTouch(false); } public Object localTouch(boolean bind) throws PageException { // inside a local supported block if(undefined.getCheckArguments()){ return localScope(bind); } return touch(undefinedScope(), KeyConstants._local); //return undefinedScope().get(LOCAL); } public Object thisGet() throws PageException { return thisTouch(); } public Object thisTouch() throws PageException { // inside a component if(undefined.variablesScope() instanceof ComponentScope){ return ((ComponentScope)undefined.variablesScope()).getComponent(); } return undefinedScope().get(KeyConstants._THIS); } public Object thisGet(Object defaultValue) { return thisTouch(defaultValue); } public Object thisTouch(Object defaultValue) { // inside a component if(undefined.variablesScope() instanceof ComponentScope){ return ((ComponentScope)undefined.variablesScope()).getComponent(); } return undefinedScope().get(KeyConstants._THIS,defaultValue); } /** * @param local sets the current local scope * @param argument sets the current argument scope */ public void setFunctionScopes(Local local,Argument argument) { this.argument=argument; this.local=local; undefined.setFunctionScopes(local,argument); } @Override public Session sessionScope() throws PageException { return sessionScope(true); } public Session sessionScope(boolean checkExpires) throws PageException { if(session==null) { checkSessionContext(); session=scopeContext.getSessionScope(this,DUMMY_BOOL); } return session; } public void invalidateUserScopes(boolean migrateSessionData,boolean migrateClientData) throws PageException { checkSessionContext(); scopeContext.invalidateUserScope(this, migrateSessionData, migrateClientData); } private void checkSessionContext() throws ExpressionException { if(!applicationContext.hasName()) throw new ExpressionException("there is no session context defined for this application","you can define a session context with the tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); if(!applicationContext.isSetSessionManagement()) throw new ExpressionException("session scope is not enabled","you can enable session scope with tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); } @Override public Server serverScope() { //if(!server.isInitalized()) server.initialize(this); return server; } public void reset() { server=ScopeContext.getServerScope(this); } @Override public Cluster clusterScope() throws PageException { return clusterScope(true); } public Cluster clusterScope(boolean create) throws PageException { if(cluster==null && create) { cluster=ScopeContext.getClusterScope(config,create); //cluster.initialize(this); } //else if(!cluster.isInitalized()) cluster.initialize(this); return cluster; } @Override public Cookie cookieScope() { if(!cookie.isInitalized()) cookie.initialize(this); return cookie; } @Override public Client clientScope() throws PageException { if(client==null) { if(!applicationContext.hasName()) throw new ExpressionException("there is no client context defined for this application", "you can define a client context with the tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); if(!applicationContext.isSetClientManagement()) throw new ExpressionException("client scope is not enabled", "you can enable client scope with tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); client= scopeContext.getClientScope(this); } return client; } public Client clientScopeEL() { if(client==null) { if(applicationContext==null || !applicationContext.hasName()) return null; if(!applicationContext.isSetClientManagement()) return null; client= scopeContext.getClientScopeEL(this); } return client; } @Override public Object set(Object coll, String key, Object value) throws PageException { return variableUtil.set(this,coll,key,value); } public Object set(Object coll, Collection.Key key, Object value) throws PageException { return variableUtil.set(this,coll,key,value); } @Override public Object touch(Object coll, String key) throws PageException { Object o=getCollection(coll,key,null); if(o!=null) return o; return set(coll,key,new StructImpl()); } @Override public Object touch(Object coll, Collection.Key key) throws PageException { Object o=getCollection(coll,key,null); if(o!=null) return o; return set(coll,key,new StructImpl()); } /*private Object _touch(Scope scope, String key) throws PageException { Object o=scope.get(key,null); if(o!=null) return o; return scope.set(key, new StructImpl()); }*/ @Override public Object getCollection(Object coll, String key) throws PageException { return variableUtil.getCollection(this,coll,key); } @Override public Object getCollection(Object coll, Collection.Key key) throws PageException { return variableUtil.getCollection(this,coll,key); } @Override public Object getCollection(Object coll, String key, Object defaultValue) { return variableUtil.getCollection(this,coll,key,defaultValue); } @Override public Object getCollection(Object coll, Collection.Key key, Object defaultValue) { return variableUtil.getCollection(this,coll,key,defaultValue); } @Override public Object get(Object coll, String key) throws PageException { return variableUtil.get(this,coll,key); } @Override public Object get(Object coll, Collection.Key key) throws PageException { return variableUtil.get(this,coll,key); } @Override public Reference getReference(Object coll, String key) throws PageException { return new VariableReference(coll,key); } public Reference getReference(Object coll, Collection.Key key) throws PageException { return new VariableReference(coll,key); } @Override public Object get(Object coll, String key, Object defaultValue) { return variableUtil.get(this,coll,key, defaultValue); } @Override public Object get(Object coll, Collection.Key key, Object defaultValue) { return variableUtil.get(this,coll,key, defaultValue); } @Override public Object setVariable(String var, Object value) throws PageException { //return new CFMLExprInterpreter().interpretReference(this,new ParserString(var)).set(value); return VariableInterpreter.setVariable(this,var,value); } @Override public Object getVariable(String var) throws PageException { return VariableInterpreter.getVariable(this,var); } public void param(String type, String name, Object defaultValue,String regex) throws PageException { param(type, name, defaultValue,Double.NaN,Double.NaN,regex,-1); } public void param(String type, String name, Object defaultValue,double min, double max) throws PageException { param(type, name, defaultValue,min,max,null,-1); } public void param(String type, String name, Object defaultValue,int maxLength) throws PageException { param(type, name, defaultValue,Double.NaN,Double.NaN,null,maxLength); } public void param(String type, String name, Object defaultValue) throws PageException { param(type, name, defaultValue,Double.NaN,Double.NaN,null,-1); } private void param(String type, String name, Object defaultValue, double min,double max, String strPattern, int maxLength) throws PageException { // check attributes type if(type==null)type="any"; else type=type.trim().toLowerCase(); // check attributes name if(StringUtil.isEmpty(name)) throw new ExpressionException("The attribute name is required"); Object value=null; boolean isNew=false; // get value value=VariableInterpreter.getVariableEL(this,name,NullSupportHelper.NULL()); if(NullSupportHelper.NULL()==value) { if(defaultValue==null) throw new ExpressionException("The required parameter ["+name+"] was not provided."); value=defaultValue; isNew=true; } // cast and set value if(!"any".equals(type)) { // range if("range".equals(type)) { double number = Caster.toDoubleValue(value); if(!Decision.isValid(min)) throw new ExpressionException("Missing attribute [min]"); if(!Decision.isValid(max)) throw new ExpressionException("Missing attribute [max]"); if(number<min || number>max) throw new ExpressionException("The number ["+Caster.toString(number)+"] is out of range [min:"+Caster.toString(min)+";max:"+Caster.toString(max)+"]"); setVariable(name,Caster.toDouble(number)); } // regex else if("regex".equals(type) || "regular_expression".equals(type)) { String str=Caster.toString(value); if(strPattern==null) throw new ExpressionException("Missing attribute [pattern]"); try { Pattern pattern = new Perl5Compiler().compile(strPattern, Perl5Compiler.DEFAULT_MASK); PatternMatcherInput input = new PatternMatcherInput(str); if( !new Perl5Matcher().matches(input, pattern)) throw new ExpressionException("The value ["+str+"] doesn't match the provided pattern ["+strPattern+"]"); } catch (MalformedPatternException e) { throw new ExpressionException("The provided pattern ["+strPattern+"] is invalid",e.getMessage()); } setVariable(name,str); } else if ( type.equals( "int" ) || type.equals( "integer" ) ) { if ( !Decision.isInteger( value ) ) throw new ExpressionException( "The value [" + value + "] is not a valid integer" ); setVariable( name, value ); } else { if(!Decision.isCastableTo(type,value,true,true,maxLength)) { if(maxLength>-1 && ("email".equalsIgnoreCase(type) || "url".equalsIgnoreCase(type) || "string".equalsIgnoreCase(type))) { StringBuilder msg=new StringBuilder(CasterException.createMessage(value, type)); msg.append(" with a maximum length of "+maxLength+" characters"); throw new CasterException(msg.toString()); } throw new CasterException(value,type); } setVariable(name,value); //REALCAST setVariable(name,Caster.castTo(this,type,value,true)); } } else if(isNew) setVariable(name,value); } @Override public Object removeVariable(String var) throws PageException { return VariableInterpreter.removeVariable(this,var); } /** * a variable reference, references to variable, to modifed it, with global effect. * @param var variable name to get * @return return a variable reference by string syntax ("scopename.key.key" -> "url.name") * @throws PageException */ public VariableReference getVariableReference(String var) throws PageException { return VariableInterpreter.getVariableReference(this,var); } @Override public Object getFunction(Object coll, String key, Object[] args) throws PageException { return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args); } @Override public Object getFunction(Object coll, Key key, Object[] args) throws PageException { return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args); } @Override public Object getFunctionWithNamedValues(Object coll, String key, Object[] args) throws PageException { return variableUtil.callFunctionWithNamedValues(this,coll,key,args); } @Override public Object getFunctionWithNamedValues(Object coll, Key key, Object[] args) throws PageException { return variableUtil.callFunctionWithNamedValues(this,coll,key,args); } @Override public ConfigWeb getConfig() { return config; } @Override public Iterator getIterator(String key) throws PageException { Object o=VariableInterpreter.getVariable(this,key); if(o instanceof Iterator) return (Iterator) o; throw new ExpressionException("["+key+"] is not a iterator object"); } @Override public Query getQuery(String key) throws PageException { Object value=VariableInterpreter.getVariable(this,key); if(Decision.isQuery(value)) return Caster.toQuery(value); throw new CasterException(value,Query.class);///("["+key+"] is not a query object, object is from type "); } @Override public Query getQuery(Object value) throws PageException { if(Decision.isQuery(value)) return Caster.toQuery(value); value=VariableInterpreter.getVariable(this,Caster.toString(value)); if(Decision.isQuery(value)) return Caster.toQuery(value); throw new CasterException(value,Query.class); } @Override public void setAttribute(String name, Object value) { try { if(value==null)removeVariable(name); else setVariable(name,value); } catch (PageException e) {} } @Override public void setAttribute(String name, Object value, int scope) { switch(scope){ case javax.servlet.jsp.PageContext.APPLICATION_SCOPE: if(value==null) getServletContext().removeAttribute(name); else getServletContext().setAttribute(name, value); break; case javax.servlet.jsp.PageContext.PAGE_SCOPE: setAttribute(name, value); break; case javax.servlet.jsp.PageContext.REQUEST_SCOPE: if(value==null) req.removeAttribute(name); else setAttribute(name, value); break; case javax.servlet.jsp.PageContext.SESSION_SCOPE: HttpSession s = req.getSession(true); if(value==null)s.removeAttribute(name); else s.setAttribute(name, value); break; } } @Override public Object getAttribute(String name) { try { return getVariable(name); } catch (PageException e) { return null; } } @Override public Object getAttribute(String name, int scope) { switch(scope){ case javax.servlet.jsp.PageContext.APPLICATION_SCOPE: return getServletContext().getAttribute(name); case javax.servlet.jsp.PageContext.PAGE_SCOPE: return getAttribute(name); case javax.servlet.jsp.PageContext.REQUEST_SCOPE: return req.getAttribute(name); case javax.servlet.jsp.PageContext.SESSION_SCOPE: HttpSession s = req.getSession(); if(s!=null)return s.getAttribute(name); break; } return null; } @Override public Object findAttribute(String name) { // page Object value=getAttribute(name); if(value!=null) return value; // request value=req.getAttribute(name); if(value!=null) return value; // session HttpSession s = req.getSession(); value=s!=null?s.getAttribute(name):null; if(value!=null) return value; // application value=getServletContext().getAttribute(name); if(value!=null) return value; return null; } @Override public void removeAttribute(String name) { setAttribute(name, null); } @Override public void removeAttribute(String name, int scope) { setAttribute(name, null,scope); } @Override public int getAttributesScope(String name) { // page if(getAttribute(name)!=null) return PageContext.PAGE_SCOPE; // request if(req.getAttribute(name) != null) return PageContext.REQUEST_SCOPE; // session HttpSession s = req.getSession(); if(s!=null && s.getAttribute(name) != null) return PageContext.SESSION_SCOPE; // application if(getServletContext().getAttribute(name)!=null) return PageContext.APPLICATION_SCOPE; return 0; } @Override public Enumeration getAttributeNamesInScope(int scope) { switch(scope){ case javax.servlet.jsp.PageContext.APPLICATION_SCOPE: return getServletContext().getAttributeNames(); case javax.servlet.jsp.PageContext.PAGE_SCOPE: return ItAsEnum.toStringEnumeration(variablesScope().keyIterator()); case javax.servlet.jsp.PageContext.REQUEST_SCOPE: return req.getAttributeNames(); case javax.servlet.jsp.PageContext.SESSION_SCOPE: return req.getSession(true).getAttributeNames(); } return null; } @Override public JspWriter getOut() { return forceWriter; } @Override public HttpSession getSession() { return getHttpServletRequest().getSession(); } @Override public Object getPage() { return variablesScope(); } @Override public ServletRequest getRequest() { return getHttpServletRequest(); } @Override public HttpServletRequest getHttpServletRequest() { return req; } @Override public ServletResponse getResponse() { return rsp; } @Override public HttpServletResponse getHttpServletResponse() { return rsp; } public OutputStream getResponseStream() throws IOException { return getRootOut().getResponseStream(); } @Override public Exception getException() { // TODO impl return exception; } @Override public ServletConfig getServletConfig() { return config; } @Override public ServletContext getServletContext() { return servlet.getServletContext(); } /*public static void main(String[] args) { repl(" susi #error.susi# sorglos","susi", "Susanne"); repl(" susi #error.Susi# sorglos","susi", "Susanne"); }*/ private static String repl(String haystack, String needle, String replacement) { //print.o(haystack); //print.o(needle); StringBuilder regex=new StringBuilder("#[\\s]*error[\\s]*\\.[\\s]*"); char[] carr = needle.toCharArray(); for(int i=0;i<carr.length;i++){ regex.append("["); regex.append(Character.toLowerCase(carr[i])); regex.append(Character.toUpperCase(carr[i])); regex.append("]"); } regex.append("[\\s]* //print.o(regex); haystack=haystack.replaceAll(regex.toString(), replacement); //print.o(haystack); return haystack; } @Override public void handlePageException(PageException pe) { if(!Abort.isSilentAbort(pe)) { String charEnc = rsp.getCharacterEncoding(); if(StringUtil.isEmpty(charEnc,true)) { rsp.setContentType("text/html"); } else { rsp.setContentType("text/html; charset=" + charEnc); } rsp.setHeader("exception-message", pe.getMessage()); //rsp.setHeader("exception-detail", pe.getDetail()); int statusCode=getStatusCode(pe); if(getConfig().getErrorStatusCode())rsp.setStatus(statusCode); ErrorPage ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_EXCEPTION); ExceptionHandler.printStackTrace(this,pe); ExceptionHandler.log(getConfig(),pe); // error page exception if(ep!=null) { try { Struct sct=pe.getErrorBlock(this,ep); variablesScope().setEL(KeyConstants._error,sct); variablesScope().setEL(KeyConstants._cferror,sct); doInclude(ep.getTemplate()); return; } catch (Throwable t) { if(Abort.isSilentAbort(t)) return; pe=Caster.toPageException(t); } } // error page request ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_REQUEST); if(ep!=null) { PageSource ps = ep.getTemplate(); if(ps.physcalExists()){ Resource res = ps.getResource(); try { String content = IOUtil.toString(res, getConfig().getTemplateCharset()); Struct sct=pe.getErrorBlock(this,ep); java.util.Iterator<Entry<Key, Object>> it = sct.entryIterator(); Entry<Key, Object> e; String v; while(it.hasNext()){ e = it.next(); v=Caster.toString(e.getValue(),null); if(v!=null)content=repl(content, e.getKey().getString(), v); } write(content); return; } catch (Throwable t) { pe=Caster.toPageException(t); } } else pe=new ApplicationException("The error page template for type request only works if the actual source file also exists. If the exception file is in an Railo archive (.rc/.rcs), you need to use type exception instead."); } try { String template=getConfig().getErrorTemplate(statusCode); if(!StringUtil.isEmpty(template)) { try { Struct catchBlock=pe.getCatchBlock(getConfig()); variablesScope().setEL(KeyConstants._cfcatch,catchBlock); variablesScope().setEL(KeyConstants._catch,catchBlock); doInclude(template); return; } catch (PageException e) { pe=e; } } if(!Abort.isSilentAbort(pe))forceWrite(getConfig().getDefaultDumpWriter(DumpWriter.DEFAULT_RICH).toString(this,pe.toDumpData(this, 9999,DumpUtil.toDumpProperties()),true)); } catch (Exception e) {} } } private int getStatusCode(PageException pe) { int statusCode=500; int maxDeepFor404=0; if(pe instanceof ModernAppListenerException){ pe=((ModernAppListenerException)pe).getPageException(); maxDeepFor404=1; } else if(pe instanceof PageExceptionBox) pe=((PageExceptionBox)pe).getPageException(); if(pe instanceof MissingIncludeException) { MissingIncludeException mie=(MissingIncludeException) pe; if(mie.getPageDeep()<=maxDeepFor404) statusCode=404; } // TODO Auto-generated method stub return statusCode; } @Override public void handlePageException(Exception e) { handlePageException(Caster.toPageException(e)); } @Override public void handlePageException(Throwable t) { handlePageException(Caster.toPageException(t)); } @Override public void setHeader(String name, String value) { rsp.setHeader(name,value); } @Override public BodyContent pushBody() { forceWriter=bodyContentStack.push(); if(enablecfoutputonly>0 && outputState==0) { writer=devNull; } else writer=forceWriter; return (BodyContent)forceWriter; } @Override public JspWriter popBody() { forceWriter=bodyContentStack.pop(); if(enablecfoutputonly>0 && outputState==0) { writer=devNull; } else writer=forceWriter; return forceWriter; } @Override public void outputStart() { outputState++; if(enablecfoutputonly>0 && outputState==1)writer=forceWriter; //if(enablecfoutputonly && outputState>0) unsetDevNull(); } @Override public void outputEnd() { outputState if(enablecfoutputonly>0 && outputState==0)writer=devNull; } @Override public void setCFOutputOnly(boolean boolEnablecfoutputonly) { if(boolEnablecfoutputonly)this.enablecfoutputonly++; else if(this.enablecfoutputonly>0)this.enablecfoutputonly setCFOutputOnly(enablecfoutputonly); //if(!boolEnablecfoutputonly)setCFOutputOnly(enablecfoutputonly=0); } @Override public void setCFOutputOnly(short enablecfoutputonly) { this.enablecfoutputonly=enablecfoutputonly; if(enablecfoutputonly>0) { if(outputState==0) writer=devNull; } else { writer=forceWriter; } } @Override public boolean setSilent() { boolean before=bodyContentStack.getDevNull(); bodyContentStack.setDevNull(true); forceWriter = bodyContentStack.getWriter(); writer=forceWriter; return before; } @Override public boolean unsetSilent() { boolean before=bodyContentStack.getDevNull(); bodyContentStack.setDevNull(false); forceWriter = bodyContentStack.getWriter(); if(enablecfoutputonly>0 && outputState==0) { writer=devNull; } else writer=forceWriter; return before; } @Override public Debugger getDebugger() { return debugger; } @Override public void executeRest(String realPath, boolean throwExcpetion) throws PageException { ApplicationListener listener=null;//config.get ApplicationListener(); try{ String pathInfo = req.getPathInfo(); // charset try{ String charset=HTTPUtil.splitMimeTypeAndCharset(req.getContentType(),new String[]{"",""})[1]; if(StringUtil.isEmpty(charset))charset=ThreadLocalPageContext.getConfig().getWebCharset(); java.net.URL reqURL = new java.net.URL(req.getRequestURL().toString()); String path=ReqRspUtil.decode(reqURL.getPath(),charset,true); String srvPath=req.getServletPath(); if(path.startsWith(srvPath)) { pathInfo=path.substring(srvPath.length()); } } catch (Exception e){} // Service mapping if(StringUtil.isEmpty(pathInfo) || pathInfo.equals("/")) {// ToDo // list available services (if enabled in admin) if(config.getRestList()) { try { HttpServletRequest _req = getHttpServletRequest(); write("Available sevice mappings are:<ul>"); railo.runtime.rest.Mapping[] mappings = config.getRestMappings(); railo.runtime.rest.Mapping _mapping; String path; for(int i=0;i<mappings.length;i++){ _mapping=mappings[i]; Resource p = _mapping.getPhysical(); path=_req.getContextPath()+ReqRspUtil.getScriptName(_req)+_mapping.getVirtual(); write("<li "+(p==null || !p.isDirectory()?" style=\"color:red\"":"")+">"+path+"</li>"); } write("</ul>"); } catch (IOException e) { throw Caster.toPageException(e); } } else RestUtil.setStatus(this, 404, null); return; } // check for matrix int index; String entry; Struct matrix=new StructImpl(); while((index=pathInfo.lastIndexOf(';'))!=-1){ entry=pathInfo.substring(index+1); pathInfo=pathInfo.substring(0,index); if(StringUtil.isEmpty(entry,true)) continue; index=entry.indexOf('='); if(index!=-1)matrix.setEL(entry.substring(0,index).trim(), entry.substring(index+1).trim()); else matrix.setEL(entry.trim(), ""); } // get accept List<MimeType> accept = ReqRspUtil.getAccept(this); MimeType contentType = ReqRspUtil.getContentType(this); // check for format extension //int format = getApplicationContext().getRestSettings().getReturnFormat(); int format; boolean hasFormatExtension=false; if(StringUtil.endsWithIgnoreCase(pathInfo, ".json")) { pathInfo=pathInfo.substring(0,pathInfo.length()-5); format = UDF.RETURN_FORMAT_JSON; accept.clear(); accept.add(MimeType.APPLICATION_JSON); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".wddx")) { pathInfo=pathInfo.substring(0,pathInfo.length()-5); format = UDF.RETURN_FORMAT_WDDX; accept.clear(); accept.add(MimeType.APPLICATION_WDDX); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".cfml")) { pathInfo=pathInfo.substring(0,pathInfo.length()-5); format = UDF.RETURN_FORMAT_SERIALIZE; accept.clear(); accept.add(MimeType.APPLICATION_CFML); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".serialize")) { pathInfo=pathInfo.substring(0,pathInfo.length()-10); format = UDF.RETURN_FORMAT_SERIALIZE; accept.clear(); accept.add(MimeType.APPLICATION_CFML); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".xml")) { pathInfo=pathInfo.substring(0,pathInfo.length()-4); format = UDF.RETURN_FORMAT_XML; accept.clear(); accept.add(MimeType.APPLICATION_XML); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".java")) { pathInfo=pathInfo.substring(0,pathInfo.length()-5); format = UDFPlus.RETURN_FORMAT_JAVA; accept.clear(); accept.add(MimeType.APPLICATION_JAVA); hasFormatExtension=true; } else { format = getApplicationContext().getRestSettings().getReturnFormat(); //MimeType mt=MimeType.toMimetype(format); //if(mt!=null)accept.add(mt); } if(accept.size()==0) accept.add(MimeType.ALL); // loop all mappings //railo.runtime.rest.Result result = null;//config.getRestSource(pathInfo, null); RestRequestListener rl=null; railo.runtime.rest.Mapping[] restMappings = config.getRestMappings(); railo.runtime.rest.Mapping m,mapping=null,defaultMapping=null; //String callerPath=null; if(restMappings!=null)for(int i=0;i<restMappings.length;i++) { m = restMappings[i]; if(m.isDefault())defaultMapping=m; if(pathInfo.startsWith(m.getVirtualWithSlash(),0) && m.getPhysical()!=null) { mapping=m; //result = m.getResult(this,callerPath=pathInfo.substring(m.getVirtual().length()),format,matrix,null); rl=new RestRequestListener(m,pathInfo.substring(m.getVirtual().length()),matrix,format,hasFormatExtension,accept,contentType,null); break; } } // default mapping if(mapping==null && defaultMapping!=null && defaultMapping.getPhysical()!=null) { mapping=defaultMapping; //result = mapping.getResult(this,callerPath=pathInfo,format,matrix,null); rl=new RestRequestListener(mapping,pathInfo,matrix,format,hasFormatExtension,accept,contentType,null); } //base = PageSourceImpl.best(config.getPageSources(this,null,realPath,true,false,true)); if(mapping==null || mapping.getPhysical()==null){ RestUtil.setStatus(this,404,"no rest service for ["+pathInfo+"] found"); } else { base=config.toPageSource(null, mapping.getPhysical(), null); listener=((MappingImpl)base.getMapping()).getApplicationListener(); listener.onRequest(this, base,rl); } } catch(Throwable t) { PageException pe = Caster.toPageException(t); if(!Abort.isSilentAbort(pe)){ log(true); if(fdEnabled){ FDSignal.signal(pe, false); } if(listener==null) { if(base==null)listener=config.getApplicationListener(); else listener=((MappingImpl)base.getMapping()).getApplicationListener(); } listener.onError(this,pe); } else log(false); if(throwExcpetion) throw pe; } finally { if(enablecfoutputonly>0){ setCFOutputOnly((short)0); } base=null; } } @Override public void execute(String realPath, boolean throwExcpetion) throws PageException { execute(realPath, throwExcpetion, true); } public void execute(String realPath, boolean throwExcpetion, boolean onlyTopLevel) throws PageException { //SystemOut.printDate(config.getOutWriter(),"Call:"+realPath+" (id:"+getId()+";running-requests:"+config.getThreadQueue().size()+";)"); if(realPath.startsWith("/mapping-")){ base=null; int index = realPath.indexOf('/',9); if(index>-1){ String type = realPath.substring(9,index); if(type.equalsIgnoreCase("tag")){ base=getPageSource( new Mapping[]{config.getTagMapping(),config.getServerTagMapping()}, realPath.substring(index) ); } else if(type.equalsIgnoreCase("customtag")){ base=getPageSource( config.getCustomTagMappings(), realPath.substring(index) ); } /*else if(type.equalsIgnoreCase("gateway")){ base=config.getGatewayEngine().getMapping().getPageSource(realPath.substring(index)); if(!base.exists())base=getPageSource(realPath.substring(index)); }*/ } if(base==null) base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true)); } else base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true)); ApplicationListener listener=gatewayContext?config.getApplicationListener():((MappingImpl)base.getMapping()).getApplicationListener(); try { listener.onRequest(this,base,null); log(false); } catch(Throwable t) { PageException pe = Caster.toPageException(t); if(!Abort.isSilentAbort(pe)){ this.pe=pe; log(true); if(fdEnabled){ FDSignal.signal(pe, false); } listener.onError(this,pe); } else log(false); if(throwExcpetion) throw pe; } finally { if(enablecfoutputonly>0){ setCFOutputOnly((short)0); } if(!gatewayContext && getConfig().debug()) { try { listener.onDebug(this); } catch (PageException pe) { if(!Abort.isSilentAbort(pe))listener.onError(this,pe); } } base=null; } } private void log(boolean error) { if(!isGatewayContext() && config.isMonitoringEnabled()) { RequestMonitor[] monitors = config.getRequestMonitors(); if(monitors!=null)for(int i=0;i<monitors.length;i++){ if(monitors[i].isLogEnabled()){ try { monitors[i].log(this,error); } catch (Throwable e) {} } } } } private PageSource getPageSource(Mapping[] mappings, String realPath) { PageSource ps; //print.err(mappings.length); for(int i=0;i<mappings.length;i++) { ps = mappings[i].getPageSource(realPath); //print.err(ps.getDisplayPath()); if(ps.exists()) return ps; } return null; } @Override public void include(String realPath) throws ServletException,IOException { HTTPUtil.include(this, realPath); } @Override public void forward(String realPath) throws ServletException, IOException { HTTPUtil.forward(this, realPath); } public void include(PageSource ps) throws ServletException { try { doInclude(ps); } catch (PageException pe) { throw new PageServletException(pe); } } @Override public void clear() { try { //print.o(getOut().getClass().getName()); getOut().clear(); } catch (IOException e) {} } @Override public long getRequestTimeout() { if(requestTimeout==-1) requestTimeout=config.getRequestTimeout().getMillis(); return requestTimeout; } @Override public void setRequestTimeout(long requestTimeout) { this.requestTimeout = requestTimeout; } @Override public String getCFID() { if(cfid==null) initIdAndToken(); return cfid; } @Override public String getCFToken() { if(cftoken==null) initIdAndToken(); return cftoken; } @Override public String getURLToken() { if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) { HttpSession s = getSession(); return "CFID="+getCFID()+"&CFTOKEN="+getCFToken()+"&jsessionid="+(s!=null?getSession().getId():""); } return "CFID="+getCFID()+"&CFTOKEN="+getCFToken(); } @Override public String getJSessionId() { if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) { return getSession().getId(); } return null; } private String getCookieDomain() { String result = (String) cgiScope().get(KeyConstants._server_name, null); if ( result != null && applicationContext.isSetDomainCookies()) { String listLast = ListUtil.last( result, '.' ); if ( !Decision.isNumeric( listLast ) ) { // if it's numeric then must be IP address int numparts = 2; int listLen = ListUtil.len( result, '.', true ); if ( listLen > 2 ) { if ( listLast.length() == 2 || !StringUtil.isAscii( listLast ) ) { // country TLD int tldMinus1 = ListUtil.getAt( result, '.', listLen - 1, true, "" ).length(); if ( tldMinus1 == 2 || tldMinus1 == 3 ) // domain is in country like, example.co.uk or example.org.il numparts++; } } if ( listLen > numparts ) result = result.substring( result.indexOf( '.' ) ); else if ( listLen == numparts ) result = "." + result; } } return result; } /** * initialize the cfid and the cftoken */ private void initIdAndToken() { boolean setCookie=true; // From URL Object oCfid = urlScope().get(KeyConstants._cfid,null); Object oCftoken = urlScope().get(KeyConstants._cftoken,null); // Cookie if((oCfid==null || !Decision.isGUIdSimple(oCfid)) || oCftoken==null) { setCookie=false; oCfid = cookieScope().get(KeyConstants._cfid,null); oCftoken = cookieScope().get(KeyConstants._cftoken,null); } if(oCfid!=null && !Decision.isGUIdSimple(oCfid) ) { oCfid=null; } // New One if(oCfid==null || oCftoken==null) { setCookie=true; cfid=ScopeContext.getNewCFId(); cftoken=ScopeContext.getNewCFToken(); } else { cfid=Caster.toString(oCfid,null); cftoken=Caster.toString(oCftoken,null); } if(setCookie && applicationContext.isSetClientCookies()) { String domain = this.getCookieDomain(); cookieScope().setCookieEL(KeyConstants._cfid,cfid,CookieImpl.NEVER,false,"/", domain ); cookieScope().setCookieEL(KeyConstants._cftoken,cftoken,CookieImpl.NEVER,false,"/", domain ); } } public void resetIdAndToken() { cfid=ScopeContext.getNewCFId(); cftoken=ScopeContext.getNewCFToken(); if(applicationContext.isSetClientCookies()) { String domain = this.getCookieDomain(); cookieScope().setCookieEL(KeyConstants._cfid,cfid,CookieImpl.NEVER,false,"/", domain); cookieScope().setCookieEL(KeyConstants._cftoken,cftoken,CookieImpl.NEVER,false,"/", domain); } } @Override public int getId() { return id; } /** * @return returns the root JSP Writer * */ public CFMLWriter getRootOut() { return bodyContentStack.getBase(); } public JspWriter getRootWriter() { return bodyContentStack.getBase(); } @Override public void setPsq(boolean psq) { this.psq=psq; } @Override public boolean getPsq() { return psq; } @Override public Locale getLocale() { Locale l = ((ApplicationContextPro)getApplicationContext()).getLocale(); if(l!=null) return l; if(locale!=null) return locale; return config.getLocale(); } @Override public void setLocale(Locale locale) { ((ApplicationContextPro)getApplicationContext()).setLocale(locale); this.locale=locale; HttpServletResponse rsp = getHttpServletResponse(); String charEnc = rsp.getCharacterEncoding(); rsp.setLocale(locale); if(charEnc.equalsIgnoreCase("UTF-8")) { rsp.setContentType("text/html; charset=UTF-8"); } else if(!charEnc.equalsIgnoreCase(rsp.getCharacterEncoding())) { rsp.setContentType("text/html; charset=" + charEnc); } } @Override public void setLocale(String strLocale) throws ExpressionException { setLocale(Caster.toLocale(strLocale)); } @Override public void setErrorPage(ErrorPage ep) { errorPagePool.setErrorPage(ep); } @Override public Tag use(String tagClassName) throws PageException { parentTag=currentTag; currentTag= tagHandlerPool.use(tagClassName); if(currentTag==parentTag) throw new ApplicationException(""); currentTag.setPageContext(this); currentTag.setParent(parentTag); return currentTag; } @Override public Tag use(Class clazz) throws PageException { return use(clazz.getName()); } @Override public void reuse(Tag tag) throws PageException { currentTag=tag.getParent(); tagHandlerPool.reuse(tag); } @Override public QueryCache getQueryCache() { return queryCache; } @Override public void initBody(BodyTag bodyTag, int state) throws JspException { if (state != Tag.EVAL_BODY_INCLUDE) { bodyTag.setBodyContent(pushBody()); bodyTag.doInitBody(); } } @Override public void releaseBody(BodyTag bodyTag, int state) { if(bodyTag instanceof TryCatchFinally) { ((TryCatchFinally)bodyTag).doFinally(); } if (state != Tag.EVAL_BODY_INCLUDE)popBody(); } /* * * @return returns the cfml compiler * / public CFMLCompiler getCompiler() { return compiler; }*/ @Override public void setVariablesScope(Variables variables) { this.variables=variables; undefinedScope().setVariableScope(variables); if(variables instanceof ComponentScope) { activeComponent=((ComponentScope)variables).getComponent(); /*if(activeComponent.getAbsName().equals("jm.pixeltex.supersuperApp")){ print.dumpStack(); }*/ } else { activeComponent=null; } } @Override public Component getActiveComponent() { return activeComponent; } @Override public Credential getRemoteUser() throws PageException { if(remoteUser==null) { Key name = KeyImpl.init(Login.getApplicationName(applicationContext)); Resource roles = config.getConfigDir().getRealResource("roles"); if(applicationContext.getLoginStorage()==Scope.SCOPE_SESSION) { Object auth = sessionScope().get(name,null); if(auth!=null) { remoteUser=CredentialImpl.decode(auth,roles); } } else if(applicationContext.getLoginStorage()==Scope.SCOPE_COOKIE) { Object auth = cookieScope().get(name,null); if(auth!=null) { remoteUser=CredentialImpl.decode(auth,roles); } } } return remoteUser; } @Override public void clearRemoteUser() { if(remoteUser!=null)remoteUser=null; String name=Login.getApplicationName(applicationContext); cookieScope().removeEL(KeyImpl.init(name)); try { sessionScope().removeEL(KeyImpl.init(name)); } catch (PageException e) {} } @Override public void setRemoteUser(Credential remoteUser) { this.remoteUser = remoteUser; } @Override public VariableUtil getVariableUtil() { return variableUtil; } @Override public void throwCatch() throws PageException { if(exception!=null) throw exception; throw new ApplicationException("invalid context for tag/script expression rethow"); } @Override public PageException setCatch(Throwable t) { if(t==null) { exception=null; undefinedScope().removeEL(KeyConstants._cfcatch); } else { exception = Caster.toPageException(t); undefinedScope().setEL(KeyConstants._cfcatch,exception.getCatchBlock(config)); if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception); } return exception; } public void setCatch(PageException pe) { exception = pe; if(pe==null) { undefinedScope().removeEL(KeyConstants._cfcatch); } else { undefinedScope().setEL(KeyConstants._cfcatch,pe.getCatchBlock(config)); if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception); } } public void setCatch(PageException pe,boolean caught, boolean store) { if(fdEnabled){ FDSignal.signal(pe, caught); } exception = pe; if(store){ if(pe==null) { undefinedScope().removeEL(KeyConstants._cfcatch); } else { undefinedScope().setEL(KeyConstants._cfcatch,pe.getCatchBlock(config)); if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception); } } } /** * @return return current catch */ public PageException getCatch() { return exception; } @Override public void clearCatch() { exception = null; undefinedScope().removeEL(KeyConstants._cfcatch); } @Override public void addPageSource(PageSource ps, boolean alsoInclude) { pathList.add(ps); if(alsoInclude) includePathList.add(ps); } public void addPageSource(PageSource ps, PageSource psInc) { pathList.add(ps); if(psInc!=null) includePathList.add(psInc); } @Override public void removeLastPageSource(boolean alsoInclude) { if(!pathList.isEmpty())pathList.removeLast(); if(alsoInclude && !includePathList.isEmpty()) includePathList.removeLast(); } public UDF[] getUDFs() { return udfs.toArray(new UDF[udfs.size()]); } public void addUDF(UDF udf) { udfs.add(udf); } public void removeUDF() { if(!udfs.isEmpty())udfs.pop(); } @Override public FTPPool getFTPPool() { return ftpPool; } /* * * @return Returns the manager. * / public DataSourceManager getManager() { return manager; }*/ @Override public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) { session=null; application=null; client=null; this.applicationContext = applicationContext; int scriptProtect = applicationContext.getScriptProtect(); // ScriptProtecting if(config.mergeFormAndURL()) { form.setScriptProtecting(applicationContext, (scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0 || (scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0); } else { form.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0); url.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0); } cookie.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_COOKIE)>0); cgi.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_CGI)>0); undefined.reinitialize(this); } /** * @return return value of method "onApplicationStart" or true * @throws PageException */ public boolean initApplicationContext(ApplicationListener listener) throws PageException { boolean initSession=false; //AppListenerSupport listener = (AppListenerSupport) config.get ApplicationListener(); KeyLock<String> lock = config.getContextLock(); String name=StringUtil.emptyIfNull(applicationContext.getName()); String token=name+":"+getCFID(); Lock tokenLock = lock.lock(token,getRequestTimeout()); //print.o("outer-lock :"+token); try { // check session before executing any code initSession=applicationContext.isSetSessionManagement() && listener.hasOnSessionStart(this) && !scopeContext.hasExistingSessionScope(this); // init application Lock nameLock = lock.lock(name,getRequestTimeout()); //print.o("inner-lock :"+token); try { RefBoolean isNew=new RefBooleanImpl(false); application=scopeContext.getApplicationScope(this,isNew);// this is needed that the application scope is initilized if(isNew.toBooleanValue()) { try { if(!listener.onApplicationStart(this)) { scopeContext.removeApplicationScope(this); return false; } } catch (PageException pe) { scopeContext.removeApplicationScope(this); throw pe; } } } finally{ //print.o("inner-unlock:"+token); lock.unlock(nameLock); } // init session if(initSession) { scopeContext.getSessionScope(this, DUMMY_BOOL);// this is needed that the session scope is initilized listener.onSessionStart(this); } } finally{ //print.o("outer-unlock:"+token); lock.unlock(tokenLock); } return true; } /** * @return the scope factory */ public ScopeFactory getScopeFactory() { return scopeFactory; } @Override public Tag getCurrentTag() { return currentTag; } @Override public long getStartTime() { return startTime; } @Override public Thread getThread() { return thread; } public void setThread(Thread thread) { this.thread=thread; } // FUTURE add as long @Override public int getExecutionTime() { return (int)executionTime; } @Override public void setExecutionTime(int executionTime) { this.executionTime = executionTime; } @Override public synchronized void compile(PageSource pageSource) throws PageException { Resource classRootDir = pageSource.getMapping().getClassRootDirectory(); try { config.getCompiler().compile( config, pageSource, config.getTLDs(), config.getFLDs(), classRootDir, pageSource.getJavaName() ); } catch (Exception e) { throw Caster.toPageException(e); } } @Override public void compile(String realPath) throws PageException { SystemOut.printDate("method PageContext.compile(String) should no longer be used!"); compile(PageSourceImpl.best(getRelativePageSources(realPath))); } public HttpServlet getServlet() { return servlet; } @Override public railo.runtime.Component loadComponent(String compPath) throws PageException { return ComponentLoader.loadComponent(this,null,compPath,null,null); } /** * @return the base */ public PageSource getBase() { return base; } /** * @param base the base to set */ public void setBase(PageSource base) { this.base = base; } /** * @return the isCFCRequest */ public boolean isCFCRequest() { return isCFCRequest; } @Override public DataSourceManager getDataSourceManager() { return manager; } @Override public Object evaluate(String expression) throws PageException { return new CFMLExpressionInterpreter().interpret(this,expression); } @Override public String serialize(Object expression) throws PageException { return Serialize.call(this, expression); } /** * @return the activeUDF */ public UDF getActiveUDF() { return activeUDF; } public Collection.Key getActiveUDFCalledName() { return activeUDFCalledName; } public void setActiveUDFCalledName(Collection.Key activeUDFCalledName) { this.activeUDFCalledName=activeUDFCalledName; } /** * @param activeUDF the activeUDF to set */ public void setActiveUDF(UDF activeUDF) { this.activeUDF = activeUDF; } @Override public CFMLFactory getCFMLFactory() { return config.getFactory(); } @Override public PageContext getParentPageContext() { return parent; } @Override public String[] getThreadScopeNames() { if(threads==null)return new String[0]; return CollectionUtil.keysAsString(threads); //Set ks = threads.keySet(); //return (String[]) ks.toArray(new String[ks.size()]); } @Override public Threads getThreadScope(String name) { return getThreadScope(KeyImpl.init(name)); } public Threads getThreadScope(Collection.Key name) { if(threads==null)threads=new StructImpl(); Object obj = threads.get(name,null); if(obj instanceof Threads)return (Threads) obj; return null; } public Object getThreadScope(Collection.Key name,Object defaultValue) { if(threads==null)threads=new StructImpl(); if(name.equalsIgnoreCase(KeyConstants._cfthread)) return threads; return threads.get(name,defaultValue); } public Object getThreadScope(String name,Object defaultValue) { if(threads==null)threads=new StructImpl(); if(name.equalsIgnoreCase(KeyConstants._cfthread.getLowerString())) return threads; return threads.get(KeyImpl.init(name),defaultValue); } @Override public void setThreadScope(String name,Threads ct) { hasFamily=true; if(threads==null) threads=new StructImpl(); threads.setEL(KeyImpl.init(name), ct); } public void setThreadScope(Collection.Key name,Threads ct) { hasFamily=true; if(threads==null) threads=new StructImpl(); threads.setEL(name, ct); } @Override public boolean hasFamily() { return hasFamily; } public DatasourceConnection _getConnection(String datasource, String user,String pass) throws PageException { return _getConnection(config.getDataSource(datasource),user,pass); } public DatasourceConnection _getConnection(DataSource ds, String user,String pass) throws PageException { String id=DatasourceConnectionPool.createId(ds,user,pass); DatasourceConnection dc=conns.get(id); if(dc!=null && DatasourceConnectionPool.isValid(dc,null)){ return dc; } dc=config.getDatasourceConnectionPool().getDatasourceConnection(this,ds, user, pass); conns.put(id, dc); return dc; } @Override public TimeZone getTimeZone() { TimeZone tz = ((ApplicationContextPro)getApplicationContext()).getTimeZone(); if(tz!=null) return tz; if(timeZone!=null) return timeZone; return config.getTimeZone(); } @Override public void setTimeZone(TimeZone timeZone) { ((ApplicationContextPro)getApplicationContext()).setTimeZone(timeZone); this.timeZone=timeZone; } /** * @return the requestId */ public int getRequestId() { return requestId; } private Set<String> pagesUsed=new HashSet<String>(); private Stack<ActiveQuery> activeQueries=new Stack<ActiveQuery>(); private Stack<ActiveLock> activeLocks=new Stack<ActiveLock>(); public boolean isTrusted(Page page) { if(page==null)return false; short it = ((MappingImpl)page.getPageSource().getMapping()).getInspectTemplate(); if(it==ConfigImpl.INSPECT_NEVER)return true; if(it==ConfigImpl.INSPECT_ALWAYS)return false; return pagesUsed.contains(""+page.hashCode()); } public void setPageUsed(Page page) { pagesUsed.add(""+page.hashCode()); } @Override public void exeLogStart(int position,String id){ if(execLog!=null)execLog.start(position, id); } @Override public void exeLogEnd(int position,String id){ if(execLog!=null)execLog.end(position, id); } /** * @param create if set to true, railo creates a session when not exist * @return * @throws PageException */ public ORMSession getORMSession(boolean create) throws PageException { if(ormSession==null || !ormSession.isValid()) { if(!create) return null; ormSession=config.getORMEngine(this).createSession(this); } DatasourceManagerImpl manager = (DatasourceManagerImpl) getDataSourceManager(); manager.add(this,ormSession); return ormSession; } public ClassLoader getClassLoader() throws IOException { return getResourceClassLoader(); } public ClassLoader getClassLoader(Resource[] reses) throws IOException{ return getResourceClassLoader().getCustomResourceClassLoader(reses); } private ResourceClassLoader getResourceClassLoader() throws IOException { JavaSettingsImpl js = (JavaSettingsImpl) applicationContext.getJavaSettings(); if(js!=null) { return config.getResourceClassLoader().getCustomResourceClassLoader(js.getResourcesTranslated()); } return config.getResourceClassLoader(); } public ClassLoader getRPCClassLoader(boolean reload) throws IOException { JavaSettingsImpl js = (JavaSettingsImpl) applicationContext.getJavaSettings(); if(js!=null) { return ((PhysicalClassLoader)config.getRPCClassLoader(reload)).getCustomClassLoader(js.getResourcesTranslated(),reload); } return config.getRPCClassLoader(reload); } public void resetSession() { this.session=null; } /** * @return the gatewayContext */ public boolean isGatewayContext() { return gatewayContext; } /** * @param gatewayContext the gatewayContext to set */ public void setGatewayContext(boolean gatewayContext) { this.gatewayContext = gatewayContext; } public void setServerPassword(String serverPassword) { this.serverPassword=serverPassword; } public String getServerPassword() { return serverPassword; } public short getSessionType() { if(isGatewayContext())return Config.SESSION_TYPE_CFML; return applicationContext.getSessionType(); } // this is just a wrapper method for ACF public Scope SymTab_findBuiltinScope(String name) throws PageException { return scope(name, null); } // FUTURE add to PageContext public DataSource getDataSource(String datasource) throws PageException { DataSource ds = ((ApplicationContextPro)getApplicationContext()).getDataSource(datasource,null); if(ds==null) ds=getConfig().getDataSource(datasource); return ds; } // FUTURE add to PageContext public DataSource getDataSource(String datasource, DataSource defaultValue) { DataSource ds = ((ApplicationContextPro)getApplicationContext()).getDataSource(datasource,null); if(ds==null) ds=getConfig().getDataSource(datasource,defaultValue); return ds; } public void setActiveQuery(ActiveQuery activeQuery) { this.activeQueries.add(activeQuery); } public ActiveQuery[] getActiveQueries() { return activeQueries.toArray(new ActiveQuery[activeQueries.size()]); } public ActiveQuery releaseActiveQuery() { return activeQueries.pop(); } public void setActiveLock(ActiveLock activeLock) { this.activeLocks.add(activeLock); } public ActiveLock[] getActiveLocks() { return activeLocks.toArray(new ActiveLock[activeLocks.size()]); } public ActiveLock releaseActiveLock() { return activeLocks.pop(); } public PageException getPageException() { return pe; } }
package musikerverwaltung.Swing; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.Vector; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.table.DefaultTableModel; import musikerverwaltung.Database.DBMethods03; import musikerverwaltung.menschen.*; public class AnzeigeFormularBand01 extends JPanel { // JPanel private JPanel jpmainband, jpmainleft, jpmainmiddle, jpmainright, jpmainleftjl, jpmainleftjtf, jpmainleftehemalig, jpmainmiddlemitglieder, jpmainmiddletitel, jpmainrightreferenz, jpmainrightbuttons, jpinsert, jpinsertrbg; // JLabel private JLabel jlueschrift, jlname, jlmitglied, jlehemalig, jlstueckgruppe, jlreferenz, jlfueller, jlauswahl; // JTextField private JTextField jtfname, jtfmitglied, jtfstueckgruppe, jtfreferenz, jtfinsert; // Schrift: private Font ftfield; // JRadioButton private JRadioButton jrbehemaligja, jrbehemalignein, jrbreferenz, jrbstueckgruppe; // ButtonGroup private ButtonGroup bgehemalig, bginsert; // JComboBox private JComboBox<String> jcbmitgliedauswahl; // JTable private JTable jtbandmitglieder, jtbandtitles, jtbandreferenzen; // JScrollPane private JScrollPane jspmitglieder, jsptitles, jspreferenzen; // Instanz der Gruppe private Gruppe01 gruppe; // DefaultTableModel private TableModel dtm; // ListeSelcectionModel private ListSelectionModel cellSelectionModel; // Border private BorderSet border; // JButton private JButton jbsubmit, jbdelete, jbinsert; // HauptJPanel links private JPanel jpmainLeft(Object band) { // JPanel fuer JLabels jpmainleftjl = new JPanel(new GridLayout(12, 1, 1, 15)); // JLabel erzeugen jlueschrift = new JLabel("Tragen Sie eine Band ein: "); jlname = new JLabel("Name: "); jlmitglied = new JLabel("Mitglied: "); jlehemalig = new JLabel("Ehemalig: "); jlstueckgruppe = new JLabel("St\u00FCck: "); jlreferenz = new JLabel("Referenz: "); jlauswahl = new JLabel("Mitglied-Auswahl: "); // Label Right anordnen jlueschrift.setHorizontalAlignment(SwingConstants.RIGHT); jlname.setHorizontalAlignment(SwingConstants.RIGHT); jlmitglied.setHorizontalAlignment(SwingConstants.RIGHT); jlehemalig.setHorizontalAlignment(SwingConstants.RIGHT); jlstueckgruppe.setHorizontalAlignment(SwingConstants.RIGHT); jlreferenz.setHorizontalAlignment(SwingConstants.RIGHT); jlauswahl.setHorizontalAlignment(SwingConstants.RIGHT); // Label dem Panel hinzuf\u00FCgen jpmainleftjl.add(jlueschrift); jpmainleftjl.add(jlname); jpmainleftjl.add(jlstueckgruppe); jpmainleftjl.add(jlreferenz); jpmainleftjl.add(jlehemalig); jpmainleftjl.add(jlmitglied); jpmainleftjl.add(jlauswahl); // JPanel fuer JTFs jpmainleftjtf = new JPanel(new GridLayout(12, 1, 1, 15)); // JLabel erzeugen for (int i = 0; i < 1; i++) { jlfueller = new JLabel(""); jpmainleftjtf.add(jlfueller); } // JTextFields erzeugen jtfname = new JTextField(); jtfname.setText(String.valueOf(band)); jtfmitglied = new JTextField(); jtfstueckgruppe = new JTextField(); jtfreferenz = new JTextField(); // Schriften erzeugen ftfield = new Font(Font.SANS_SERIF, Font.BOLD + Font.ITALIC, 15); // JTextfield schrift festlegen jtfname.setFont(ftfield); jtfmitglied.setFont(ftfield); jtfstueckgruppe.setFont(ftfield); jtfreferenz.setFont(ftfield); // JRadioButton erzeugen jrbehemaligja = new JRadioButton("Ja"); jrbehemaligja.setActionCommand("j"); jrbehemalignein = new JRadioButton("Nein"); jrbehemalignein.setActionCommand("n"); // JRadioButtons ButtonGroup hinzuf\u00FCgen bgehemalig = new ButtonGroup(); bgehemalig.add(jrbehemaligja); bgehemalig.add(jrbehemalignein); // JPanel fuer die JRadioButtons jpmainleftehemalig = new JPanel(new GridLayout(1, 1, 0, 10)); jpmainleftehemalig.add(jrbehemaligja); jpmainleftehemalig.add(jrbehemalignein); // Instanz von Musiker erzeugen Musiker01 musiker = new Musiker01(); // Vector-Var um JComboxBox zu fuellen Vector<String> selectmitglied = musiker.getMusikerArray(); // Erzeugen der Combobox jcbmitgliedauswahl = new JComboBox<String>(); jcbmitgliedauswahl.setModel(new DefaultComboBoxModel<String>( selectmitglied)); // JTextfields und JRadioButtons hinzuf\u00FCgen jpmainleftjtf.add(jtfname); jpmainleftjtf.add(jtfstueckgruppe); jpmainleftjtf.add(jtfreferenz); jpmainleftjtf.add(jpmainleftehemalig); jpmainleftjtf.add(jtfmitglied); jpmainleftjtf.add(jcbmitgliedauswahl); // ToolTips hinzuf\u00FCgen jtfname.setToolTipText("Tragen Sie hier bitte den Namen der band ein"); jtfmitglied .setToolTipText("Tragen Sie hier bitte die Bandmitglieder ein"); jtfstueckgruppe .setToolTipText("Tragen Sie hier bitte ein Stueck der Gruppe ein"); jtfreferenz .setToolTipText("Hier k\u00F6nnen Sie eine Referenz zu einer Band eintragen"); jcbmitgliedauswahl.setToolTipText("Bitte waehle einen Musiker aus"); // HauptJPanel linke Seite erzeugen jpmainleft = new JPanel(new GridLayout(1, 2, 1, 1)); // JPanel mit JLabels der HauptPanel der linken Seite zurordnen jpmainleft.add(jpmainleftjl); // JPanel mit JTFs der HauptPanel der linken Seite zurordnen jpmainleft.add(jpmainleftjtf); // Border setzen fuer das linke JPanel border = new BorderSet(); border.setBorder(jpmainleft, "Band-Info's"); return jpmainleft; } // HauptJPanel mitte private JPanel jpmainMiddle(Object band) { jpmainmiddlemitglieder = new JPanel(new GridLayout(1, 1, 1, 0)); // Instanz des TablesModels erzeugen dtm = new TableModel(); // Instanz der Gruppe erzeugen um Tabelle fuellen zu koennen gruppe = new Gruppe01(String.valueOf(band)); // Erzeugung der Tabelle mit DefaultTableModel jtbandmitglieder = new JTable(dtm.dtm(1, 2, DBMethods03.COLUMN_IDENTIFIERSMEMBERS, gruppe.dbSelectMitglieder())); // Spalten nicht mehr verschiebbar jtbandmitglieder.getTableHeader().setReorderingAllowed(false); jtbandmitglieder.setCellSelectionEnabled(true); // Nur auswahl einer Zeile moeglich cellSelectionModel = jtbandmitglieder.getSelectionModel(); cellSelectionModel .setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // JTable der JScrollPane hinzufuegen jspmitglieder = new JScrollPane(jtbandmitglieder); // Groesse der Tabelle festlegen, das sonst keinen Scrollen vorhanden // ist, auerdem schoener:) //860 , 600 jspmitglieder.setPreferredSize(new Dimension(300, 500)); // Viewport setzen jspmitglieder.setViewportView(jtbandmitglieder); // JSP mit Mitgliedern und JLabel dem JPanel hinzufuegen jpmainmiddlemitglieder.add(jspmitglieder); // Border setzen border.setBorder(jpmainmiddlemitglieder, "Mitglieder-Liste"); // // JPanel erzeugen jpmainmiddletitel = new JPanel(new GridLayout(1, 1, 1, 0)); // Erzeugung der Tabelle mit DefaultTableModel jtbandtitles = new JTable(dtm.dtm(1, 2, DBMethods03.COLUMN_IDENTIFIERSTITLES, gruppe.dbSelectTitel())); // Spalten nicht mehr verschiebbar jtbandtitles.getTableHeader().setReorderingAllowed(false); jtbandtitles.setCellSelectionEnabled(true); // Nur auswahl einer Zeile moeglich cellSelectionModel = jtbandtitles.getSelectionModel(); cellSelectionModel .setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // JTable der JScrollPane hinzufuegen jsptitles = new JScrollPane(jtbandtitles); // Groesse der Tabelle festlegen, das sonst keinen Scrollen vorhanden // ist, auerdem schoener:) //860 , 600 jsptitles.setPreferredSize(new Dimension(300, 500)); // Viewport setzen jsptitles.setViewportView(jtbandtitles); // JSP mit Mitgliedern und JLabel dem JPanel hinzufuegen jpmainmiddletitel.add(jsptitles); // Border dem JPanel hinzufuegen border.setBorder(jpmainmiddletitel, "Titel-Liste"); // HauptJPanel mitte jpmainmiddle = new JPanel(new GridLayout(2, 1, 1, 10)); jpmainmiddle.add(jpmainmiddlemitglieder); jpmainmiddle.add(jpmainmiddletitel); return jpmainmiddle; } // HauptJPanel rechts private JPanel jpmainRight(Object band) { // JPanel fr Tabelle mit Referenzen jpmainrightreferenz = new JPanel(new GridLayout(1, 1, 1, 1)); // Erzeugung der Tabelle mit DefaultTableModel jtbandreferenzen = new JTable(dtm.dtm(1, 1, DBMethods03.COLUMN_IDENTIFIERSREFERENCES, gruppe.dbSelectReferenzen())); // Spalten nicht mehr verschiebbar jtbandreferenzen.getTableHeader().setReorderingAllowed(false); jtbandreferenzen.setCellSelectionEnabled(true); // Nur auswahl einer Zeile moeglich cellSelectionModel = jtbandreferenzen.getSelectionModel(); cellSelectionModel .setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // JTable der JScrollPane hinzufuegen jspreferenzen = new JScrollPane(jtbandreferenzen); // Groesse der Tabelle festlegen, das sonst keinen Scrollen vorhanden // ist, auerdem schoener:) //860 , 600 jspreferenzen.setPreferredSize(new Dimension(300, 500)); // Viewport setzen jspreferenzen.setViewportView(jtbandreferenzen); // JSP mit Mitgliedern und JLabel dem JPanel hinzufuegen jpmainrightreferenz.add(jspreferenzen); // Border dem JPanel hinzufuegen border.setBorder(jpmainrightreferenz, "Referenzen-Liste"); // jpinsert jpinsert = new JPanel(new GridLayout(3, 1, 1, 10)); // jtferzeugen jtfinsert = new JTextField(); // Einfuegenbutton jbinsert = new JButton("Einfgen"); jbinsert.setPreferredSize(new Dimension(10, 20)); // JRadioButton erzeugen jrbstueckgruppe = new JRadioButton("Stueck"); jrbstueckgruppe.setActionCommand("g"); jrbreferenz = new JRadioButton("Referenz"); jrbreferenz.setActionCommand("r"); // JRadioButtons ButtonGroup hinzuf\u00FCgen bginsert = new ButtonGroup(); bginsert.add(jrbstueckgruppe); bginsert.add(jrbreferenz); // JPanel fuer die JRadioButtons jpinsertrbg = new JPanel(new GridLayout(1, 1, 0, 10)); jpinsertrbg.add(jrbstueckgruppe); jpinsertrbg.add(jrbreferenz); // jtferzeugen dem jpinsert hinzufuegen jpinsert.add(jtfinsert); jpinsert.add(jpinsertrbg); jpinsert.add(jbinsert); // Border dem JPanel hinzufuegen border.setBorder(jpinsert, "Referenz oder Stueck hinzufuegen"); // // JPanel fuer Buttons jpmainrightbuttons = new JPanel(new GridLayout(5, 1, 1, 10)); // JButton erzeugen // Bestatigungsbutton jbsubmit = new JButton("Bearbeiten"); jbsubmit.setPreferredSize(new Dimension(10, 20)); // Loeschbutton jbdelete = new JButton("Lschen"); jbsubmit.setPreferredSize(new Dimension(10, 20)); // ToolTip hinzuf\u00FCgen jbsubmit.setToolTipText("Hier klicken, um die Band zubearbeiten"); jbdelete.setToolTipText("Hier klicken, um die Band zu lschen"); // L\u00FCenf\u00FCller einf\u00FCgen for (int i = 0; i < 3; i++) { jlfueller = new JLabel(""); jpmainrightbuttons.add(jlfueller); } jpmainrightbuttons.add(jbsubmit); jpmainrightbuttons.add(jbdelete); jpmainright = new JPanel(new GridLayout(3, 1, 1, 1)); jpmainright.add(jpmainrightreferenz); jpmainright.add(jpinsert); jpmainright.add(jpmainrightbuttons); return jpmainright; } // zusammenlegen der JPanels public JPanel jpmainBand(Object band) { jpmainband = new JPanel(new GridLayout(1, 3, 4, 4)); jpmainband.add(jpmainLeft(band)); jpmainband.add(jpmainMiddle(band)); jpmainband.add(jpmainRight(band)); bandActionListener(); // MouseListener hinzufuegen MouseListenerTable mlt = new MouseListenerTable(); mlt.mouseListenerBandMitglieder(jtbandmitglieder, jtfmitglied); mlt.mouseListenerBandReferenzen(jtbandreferenzen, jtfreferenz); mlt.mouseListenerBandTitel(jtbandtitles, jtfstueckgruppe); return jpmainband; } // ActionListener, setzt ausgewaehltes Textfeld nach Auswahl eines Items aus // JComboBox public void bandActionListener() { jcbmitgliedauswahl.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // Auswahl der aus der JComboBox in var speichern String mitglied = String.valueOf(jcbmitgliedauswahl .getSelectedItem()); // das ausgewaehlte Mitglied in das JTextfield einfuegen jtfmitglied.setText(mitglied); } }); /* * // delete-Button jbdelete.addActionListener(new ActionListener() { * public void actionPerformed(ActionEvent ae) * * { * * // Delete-Methode aufrufen * DBMethods03.deleteBand(musiker.getMusikerID());}}); */ } }
package org.bitcoinj.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; public class MasternodeSignature extends ChildMessage { private static final Logger log = LoggerFactory.getLogger(MasternodeSignature.class); byte [] bytes; MasternodeSignature(NetworkParameters params) { super(params); } public MasternodeSignature(NetworkParameters params, byte[] payload, int offset) throws ProtocolException { super(params, payload, offset); } /*public MasternodeSignature(NetworkParameters params, byte[] payloadBytes, int cursor, Message parent, boolean parseLazy, boolean parseRetain) { super(params, payloadBytes, cursor, parent, parseLazy, parseRetain, payloadBytes.length); }*/ public MasternodeSignature(byte [] signature) { bytes = new byte[signature.length]; System.arraycopy(signature, 0, bytes, 0, signature.length); length = VarInt.sizeOf(bytes.length) + bytes.length; } public MasternodeSignature(MasternodeSignature other) { super(other.getParams()); bytes = new byte[other.bytes.length]; System.arraycopy(other.bytes, 0, bytes, 0, other.bytes.length); length = other.getMessageSize(); } public static MasternodeSignature createEmpty() { return new MasternodeSignature(new byte[0]); } protected static int calcLength(byte[] buf, int offset) { VarInt varint; int cursor = offset; varint = new VarInt(buf, cursor); long len = varint.value; len += varint.getOriginalSizeInBytes(); cursor += len; return cursor - offset; } public int calculateMessageSizeInBytes() { return VarInt.sizeOf(bytes.length) + bytes.length; } @Override protected void parse() throws ProtocolException { cursor = offset; bytes = readByteArray(); length = cursor - offset; } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { stream.write(new VarInt(bytes.length).encode()); stream.write(bytes); } public String toString() { return "sig: " + Utils.HEX.encode(Utils.reverseBytes(bytes)); } public byte [] getBytes() { return bytes; } public boolean equals(Object o) { MasternodeSignature key = (MasternodeSignature)o; if(key.bytes.length == this.bytes.length) { if(Arrays.equals(key.bytes, this.bytes) == true) return true; } return false; } public MasternodeSignature duplicate() { MasternodeSignature copy = new MasternodeSignature(params, getBytes(), 0); return copy; } public boolean isEmpty() { return bytes.length == 0; } public void clear() { bytes = new byte[0]; } }
package com.haxademic.sketch.test; import processing.core.PApplet; import processing.core.PGraphics; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.draw.mesh.PGraphicsKeystone; import com.haxademic.core.draw.util.OpenGLUtil; @SuppressWarnings("serial") public class PGraphicsKeystoneTest extends PAppletHax { protected PGraphics _pg; protected PGraphicsKeystone _pgPinnable; public static void main(String args[]) { _isFullScreen = true; _hasChrome = false; PApplet.main(new String[] { PGraphicsKeystoneTest.class.getName() }); } protected void overridePropsFile() { _appConfig.setProperty( "fps", "60" ); _appConfig.setProperty( "width", "1432" ); _appConfig.setProperty( "height", "927" ); _appConfig.setProperty( "fills_screen", "false" ); _appConfig.setProperty( "fullscreen", "false" ); } public void setup() { super.setup(); buildCanvas(); } protected void buildCanvas() { _pg = p.createGraphics( p.width / 2, p.height / 2, P.OPENGL ); _pg.smooth(OpenGLUtil.SMOOTH_MEDIUM); _pgPinnable = new PGraphicsKeystone( p, _pg, 12 ); } protected void drawTestPattern( PGraphics pg ) { // redraw pgraphics grid pg.beginDraw(); pg.clear(); pg.noStroke(); for( int x=0; x < pg.width; x+= 50) { for( int y=0; y < pg.height; y+= 50) { if( ( x % 100 == 0 && y % 100 == 0 ) || ( x % 100 == 50 && y % 100 == 50 ) ) { pg.fill(0); } else { pg.fill(255); } pg.rect(x,y,50,50); } } pg.endDraw(); } public void drawApp() { p.background(0); // draw pinned pgraphics drawTestPattern( _pg ); _pgPinnable.update(p.g, true); } }
package com.jme.widget.scroller; import java.util.Observable; import java.util.Observer; import com.jme.input.MouseInput; import com.jme.math.Vector2f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.widget.WidgetAlignmentType; import com.jme.widget.layout.WidgetFlowLayout; import com.jme.widget.panel.WidgetPanel; import com.jme.widget.util.WidgetRepeater; /** * @author Gregg Patton * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class WidgetScrollerThumbTray extends WidgetPanel implements Observer { private WidgetRepeater repeat = new WidgetRepeater(); private boolean pagingUpLeft; private boolean pagingDownRight; WidgetScrollerThumb thumb = new WidgetScrollerThumb(); WidgetScrollerType type; double buttonSize = WidgetScrollerButton.DEFAULT_SCROLLER_BUTTON_SIZE; double range; double visibleRange; double ratio; double offset; double offsetAdjust = 0; double thumbPos; double thumbSize; double size; public WidgetScrollerThumbTray(WidgetScrollerType type) { super(); setLayout(new WidgetFlowLayout(WidgetAlignmentType.ALIGN_WEST)); this.type = type; Vector2f size = new Vector2f(); size.x = size.y = (float) buttonSize; thumb.setPreferredSize(size); add(thumb); thumb.addMouseDragObserver(this); setBgColor(new ColorRGBA(.7f, .7f, .7f, 1)); } private void calcRatio() { if (range != 0) { ratio = size / range; } } private void calcOffset() { if (ratio != 0) { offset = (thumbPos + (offsetAdjust * (thumbPos / (size - buttonSize)))) / ratio; } } private void calcThumbPos() { thumbPos = offset * ratio; clampThumbPos(); } private void calcThumbSize() { if (ratio != 0) { double ts = visibleRange * ratio; if (ts < buttonSize) { offsetAdjust = buttonSize - ts; thumbSize = (int) buttonSize; } else { thumbSize = (int) ts; offsetAdjust = 0; } } } private void clampThumbPos() { if (type == WidgetScrollerType.VERTICAL) { if (thumbPos < 0) { thumbPos = 0; } else if (thumbPos + thumbSize > getHeight()) { thumbPos = getHeight() - thumbSize; } } else if (type == WidgetScrollerType.HORIZONTAL) { if (thumbPos < 0) { thumbPos = 0; } else if (thumbPos + thumbSize > getWidth()) { thumbPos = getWidth() - thumbSize; } } } private void clampOffset() { if (offset < 0) { offset = 0; } else if (offset + visibleRange > range) { offset = range - visibleRange; } } void initExtents() { if (type == WidgetScrollerType.VERTICAL) { size = getHeight(); if (size > 0) { calcThumbSize(); calcThumbPos(); clampThumbPos(); thumb.setPreferredSize((int) buttonSize, (int) thumbSize); setPanYOffset((int) - thumbPos); } } else if (type == WidgetScrollerType.HORIZONTAL) { size = getWidth(); if (size > 0) { calcThumbSize(); calcThumbPos(); clampThumbPos(); thumb.setPreferredSize((int) thumbSize, (int) buttonSize); setPanXOffset((int) thumbPos); } } doLayout(); } public void update(Observable o, Object arg) { //WidgetMouseStateAbstract mouseState = WidgetImpl.getMouseState(); MouseInput mi = getMouseInput(); if (type == WidgetScrollerType.VERTICAL) { //thumbPos -= mouseState.dy; thumbPos -= mi.getYDelta(); clampThumbPos(); calcOffset(); setPanYOffset((int) - thumbPos); } else if (type == WidgetScrollerType.HORIZONTAL) { //thumbPos += mouseState.dx; thumbPos += mi.getXDelta(); clampThumbPos(); calcOffset(); setPanXOffset((int) thumbPos); } getNotifierMouseDrag().notifyObservers(this); } public void setRangeExtents(float range, float visibleRange) { this.range = range; this.visibleRange = visibleRange; calcRatio(); initExtents(); } public int getRange() { return (int) range; } public int getVisibleRange() { return (int) visibleRange; } public int getOffset() { return (int) offset; } public void setOffset(int i) { offset = i < 0 ? 0 : i; initExtents(); } public void decrement() { decrement(1); } public void pageUpLeft() { decrement((int) visibleRange); } public void pageDownRight() { increment((int) visibleRange); } public void decrement(int d) { offset -= d; clampOffset(); calcThumbPos(); if (type == WidgetScrollerType.VERTICAL) { setPanYOffset((int) - thumbPos); } else if (type == WidgetScrollerType.HORIZONTAL) { setPanXOffset((int) thumbPos); } getNotifierMouseDrag().notifyObservers(this); } public void increment() { increment(1); } public void increment(int i) { offset += i; calcThumbPos(); clampOffset(); if (type == WidgetScrollerType.VERTICAL) { setPanYOffset((int) - thumbPos); } else if (type == WidgetScrollerType.HORIZONTAL) { setPanXOffset((int) thumbPos); } getNotifierMouseDrag().notifyObservers(this); } public void doMouseButtonDown() { //WidgetMouseStateAbstract mouseState = WidgetImpl.getMouseState(); MouseInput mi = getMouseInput(); if (this.type == WidgetScrollerType.VERTICAL) { Vector2f l = thumb.getAbsoluteLocation(); if (mi.getYAbsolute() > l.y + thumbSize) { pageUpLeft(); this.pagingUpLeft = true; repeat.start(); } else if (mi.getYAbsolute() < l.y) { pageDownRight(); this.pagingDownRight = true; repeat.start(); } } else if (this.type == WidgetScrollerType.HORIZONTAL) { Vector2f l = thumb.getAbsoluteLocation(); if (mi.getXAbsolute() > l.x + thumbSize) { pageDownRight(); this.pagingDownRight = true; repeat.start(); } else if (mi.getXAbsolute() < l.x) { pageUpLeft(); this.pagingUpLeft = true; repeat.start(); } } } public void doMouseButtonUp() { pagingUpLeft = pagingDownRight = false; } public void draw(Renderer r) { if (isVisible() == false) return; if (pagingUpLeft) { if (repeat.doRepeat()) { pageUpLeft(); } } else if (pagingDownRight) { if (repeat.doRepeat()) { pageDownRight(); } } super.draw(r); } public void setSize(int width, int height) { super.setSize(width, height); if (type == WidgetScrollerType.VERTICAL) { size = getHeight(); } else if (this.type == WidgetScrollerType.HORIZONTAL) { size = getWidth(); } calcRatio(); initExtents(); } }
package org.mskcc.cbio.portal.dao; import org.mskcc.cbio.portal.model.*; import org.mskcc.cbio.portal.util.MutationKeywordUtils; import org.apache.commons.lang.StringUtils; import java.sql.*; import java.util.*; import java.util.regex.*; /** * Data access object for Mutation table */ public final class DaoMutation { public static final String NAN = "NaN"; public static int addMutation(ExtendedMutation mutation, boolean newMutationEvent) throws DaoException { if (!MySQLbulkLoader.isBulkLoad()) { throw new DaoException("You have to turn on MySQLbulkLoader in order to insert mutations"); } else { int result = 1; if (newMutationEvent) { //add event first, as mutation has a Foreign key constraint to the event: result = addMutationEvent(mutation.getEvent())+1; } MySQLbulkLoader.getMySQLbulkLoader("mutation").insertRecord( Long.toString(mutation.getMutationEventId()), Integer.toString(mutation.getGeneticProfileId()), Integer.toString(mutation.getSampleId()), Long.toString(mutation.getGene().getEntrezGeneId()), mutation.getSequencingCenter(), mutation.getSequencer(), mutation.getMutationStatus(), mutation.getValidationStatus(), mutation.getTumorSeqAllele1(), mutation.getTumorSeqAllele2(), mutation.getMatchedNormSampleBarcode(), mutation.getMatchNormSeqAllele1(), mutation.getMatchNormSeqAllele2(), mutation.getTumorValidationAllele1(), mutation.getTumorValidationAllele2(), mutation.getMatchNormValidationAllele1(), mutation.getMatchNormValidationAllele2(), mutation.getVerificationStatus(), mutation.getSequencingPhase(), mutation.getSequenceSource(), mutation.getValidationMethod(), mutation.getScore(), mutation.getBamFile(), Integer.toString(mutation.getTumorAltCount()), Integer.toString(mutation.getTumorRefCount()), Integer.toString(mutation.getNormalAltCount()), Integer.toString(mutation.getNormalRefCount()), //AminoAcidChange column is not used null, mutation.getDriverFilter(), mutation.getDriverFilterAnn(), mutation.getDriverTiersFilter(), mutation.getDriverTiersFilterAnn()); return result; } } public static int addMutationEvent(ExtendedMutation.MutationEvent event) throws DaoException { // use this code if bulk loading // write to the temp file maintained by the MySQLbulkLoader String keyword = MutationKeywordUtils.guessOncotatorMutationKeyword(event.getProteinChange(), event.getMutationType()); MySQLbulkLoader.getMySQLbulkLoader("mutation_event").insertRecord( Long.toString(event.getMutationEventId()), Long.toString(event.getGene().getEntrezGeneId()), event.getChr(), Long.toString(event.getStartPosition()), Long.toString(event.getEndPosition()), event.getReferenceAllele(), event.getTumorSeqAllele(), event.getProteinChange(), event.getMutationType(), event.getFunctionalImpactScore(), Float.toString(event.getFisValue()), event.getLinkXVar(), event.getLinkPdb(), event.getLinkMsa(), event.getNcbiBuild(), event.getStrand(), event.getVariantType(), event.getDbSnpRs(), event.getDbSnpValStatus(), event.getOncotatorDbSnpRs(), event.getOncotatorRefseqMrnaId(), event.getOncotatorCodonChange(), event.getOncotatorUniprotName(), event.getOncotatorUniprotAccession(), Integer.toString(event.getOncotatorProteinPosStart()), Integer.toString(event.getOncotatorProteinPosEnd()), boolToStr(event.isCanonicalTranscript()), keyword==null ? "\\N":(event.getGene().getHugoGeneSymbolAllCaps()+" "+keyword)); return 1; } public static int calculateMutationCount (int profileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "INSERT INTO mutation_count " + "SELECT genetic_profile.`GENETIC_PROFILE_ID`, `SAMPLE_ID`, COUNT(*) AS MUTATION_COUNT " + "FROM `mutation` , `genetic_profile` " + "WHERE mutation.`GENETIC_PROFILE_ID` = genetic_profile.`GENETIC_PROFILE_ID` " + "AND genetic_profile.`GENETIC_PROFILE_ID`=? " + "GROUP BY genetic_profile.`GENETIC_PROFILE_ID` , `SAMPLE_ID`;"); pstmt.setInt(1, profileId); return pstmt.executeUpdate(); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } public static int calculateMutationCountByKeyword(int profileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "INSERT INTO mutation_count_by_keyword " + "SELECT g2.`GENETIC_PROFILE_ID`, mutation_event.`KEYWORD`, m2.`ENTREZ_GENE_ID`, " + "IF(mutation_event.`KEYWORD` IS NULL, 0, COUNT(DISTINCT(m2.SAMPLE_ID))) AS KEYWORD_COUNT, " + "(SELECT COUNT(DISTINCT(m1.SAMPLE_ID)) FROM `mutation` AS m1 , `genetic_profile` AS g1 " + "WHERE m1.`GENETIC_PROFILE_ID` = g1.`GENETIC_PROFILE_ID` " + "AND g1.`GENETIC_PROFILE_ID`= g2.`GENETIC_PROFILE_ID` AND m1.`ENTREZ_GENE_ID` = m2.`ENTREZ_GENE_ID` " + "GROUP BY g1.`GENETIC_PROFILE_ID` , m1.`ENTREZ_GENE_ID`) AS GENE_COUNT " + "FROM `mutation` AS m2 , `genetic_profile` AS g2 , `mutation_event` " + "WHERE m2.`GENETIC_PROFILE_ID` = g2.`GENETIC_PROFILE_ID` " + "AND m2.`MUTATION_EVENT_ID` = mutation_event.`MUTATION_EVENT_ID` " + "AND g2.`GENETIC_PROFILE_ID`=? " + "GROUP BY g2.`GENETIC_PROFILE_ID` , mutation_event.`KEYWORD` , m2.`ENTREZ_GENE_ID`;"); pstmt.setInt(1, profileId); return pstmt.executeUpdate(); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, Collection<Integer> targetSampleList, long entrezGeneId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation " + "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE SAMPLE_ID IN ('" + org.apache.commons.lang.StringUtils.join(targetSampleList, "','") + "') AND GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID = ?"); pstmt.setInt(1, geneticProfileId); pstmt.setLong(2, entrezGeneId); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static HashMap getSimplifiedMutations (int geneticProfileId, Collection<Integer> targetSampleList, Collection<Long> entrezGeneIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; HashMap hm = new HashMap(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT SAMPLE_ID, ENTREZ_GENE_ID FROM mutation " + //"INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE SAMPLE_ID IN ('" + org.apache.commons.lang.StringUtils.join(targetSampleList, "','") + "') AND GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID IN ('" + org.apache.commons.lang.StringUtils.join(entrezGeneIds, "','") + "')"); pstmt.setInt(1, geneticProfileId); rs = pstmt.executeQuery(); while (rs.next()) { String tmpStr = new StringBuilder().append(Integer.toString(rs.getInt("SAMPLE_ID"))).append(Integer.toString(rs.getInt("ENTREZ_GENE_ID"))).toString(); hm.put(tmpStr, ""); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return hm; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, int sampleId, long entrezGeneId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation " + "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE SAMPLE_ID = ? AND GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID = ?"); pstmt.setInt(1, sampleId); pstmt.setInt(2, geneticProfileId); pstmt.setLong(3, entrezGeneId); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (NullPointerException e) { throw new DaoException(e); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * Gets all Genes in a Specific Genetic Profile. * * @param geneticProfileId Genetic Profile ID. * @return Set of Canonical Genes. * @throws DaoException Database Error. */ public static Set<CanonicalGene> getGenesInProfile(int geneticProfileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; Set<CanonicalGene> geneSet = new HashSet<CanonicalGene>(); DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT DISTINCT ENTREZ_GENE_ID FROM mutation WHERE GENETIC_PROFILE_ID = ?"); pstmt.setInt(1, geneticProfileId); rs = pstmt.executeQuery(); while (rs.next()) { geneSet.add(daoGene.getGene(rs.getLong("ENTREZ_GENE_ID"))); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return geneSet; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (long entrezGeneId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation " + "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE mutation.ENTREZ_GENE_ID = ?"); pstmt.setLong(1, entrezGeneId); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (long entrezGeneId, String aminoAcidChange) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation_event " + "INNER JOIN mutation ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE mutation.ENTREZ_GENE_ID = ? AND PROTEIN_CHANGE = ?"); pstmt.setLong(1, entrezGeneId); pstmt.setString(2, aminoAcidChange); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, int sampleId) throws DaoException { return getMutations(geneticProfileId, Arrays.asList(new Integer(sampleId))); } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, List<Integer> sampleIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation " + "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE GENETIC_PROFILE_ID = ? AND SAMPLE_ID in ('"+ StringUtils.join(sampleIds, "','")+"')"); pstmt.setInt(1, geneticProfileId); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static boolean hasAlleleFrequencyData (int geneticProfileId, int sampleId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT EXISTS (SELECT 1 FROM mutation " + "WHERE GENETIC_PROFILE_ID = ? AND SAMPLE_ID = ? AND TUMOR_ALT_COUNT>=0 AND TUMOR_REF_COUNT>=0)"); pstmt.setInt(1, geneticProfileId); pstmt.setInt(2, sampleId); rs = pstmt.executeQuery(); return rs.next() && rs.getInt(1)==1; } catch (NullPointerException e) { throw new DaoException(e); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (long entrezGeneId, String aminoAcidChange, int excludeSampleId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation, mutation_event " + "WHERE mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "AND mutation.ENTREZ_GENE_ID = ? AND PROTEIN_CHANGE = ? AND SAMPLE_ID <> ?"); pstmt.setLong(1, entrezGeneId); pstmt.setString(2, aminoAcidChange); pstmt.setInt(3, excludeSampleId); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (NullPointerException e) { throw new DaoException(e); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getMutations (int geneticProfileId, long entrezGeneId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation " + "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE GENETIC_PROFILE_ID = ? AND mutation.ENTREZ_GENE_ID = ?"); pstmt.setInt(1, geneticProfileId); pstmt.setLong(2, entrezGeneId); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } public static ArrayList<ExtendedMutation> getAllMutations () throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation " + "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID"); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * Similar to getAllMutations(), but filtered by a passed geneticProfileId * @param geneticProfileId * @return * @throws DaoException * * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static ArrayList<ExtendedMutation> getAllMutations (int geneticProfileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; ArrayList <ExtendedMutation> mutationList = new ArrayList <ExtendedMutation>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT * FROM mutation " + "INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE mutation.GENETIC_PROFILE_ID = ?"); pstmt.setInt(1, geneticProfileId); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation mutation = extractMutation(rs); mutationList.add(mutation); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return mutationList; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Set<ExtendedMutation.MutationEvent> getAllMutationEvents() throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; Set<ExtendedMutation.MutationEvent> events = new HashSet<ExtendedMutation.MutationEvent>(); try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement("SELECT * FROM mutation_event"); rs = pstmt.executeQuery(); while (rs.next()) { ExtendedMutation.MutationEvent event = extractMutationEvent(rs); events.add(event); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } return events; } /* * Returns an existing MutationEvent record from the database or null. */ public static ExtendedMutation.MutationEvent getMutationEvent(ExtendedMutation.MutationEvent event) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement("SELECT * from mutation_event WHERE" + " `ENTREZ_GENE_ID`=?" + " AND `CHR`=?" + " AND `START_POSITION`=?" + " AND `END_POSITION`=?" + " AND `TUMOR_SEQ_ALLELE`=?" + " AND `PROTEIN_CHANGE`=?" + " AND `MUTATION_TYPE`=?"); pstmt.setLong(1, event.getGene().getEntrezGeneId()); pstmt.setString(2, event.getChr()); pstmt.setLong(3, event.getStartPosition()); pstmt.setLong(4, event.getEndPosition()); pstmt.setString(5, event.getTumorSeqAllele()); pstmt.setString(6, event.getProteinChange()); pstmt.setString(7, event.getMutationType()); rs = pstmt.executeQuery(); if (rs.next()) { return extractMutationEvent(rs); } else { return null; } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } public static long getLargestMutationEventId() throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement("SELECT MAX(`MUTATION_EVENT_ID`) FROM `mutation_event`"); rs = pstmt.executeQuery(); return rs.next() ? rs.getLong(1) : 0; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } private static ExtendedMutation extractMutation(ResultSet rs) throws SQLException, DaoException { try { ExtendedMutation mutation = new ExtendedMutation(extractMutationEvent(rs)); mutation.setGeneticProfileId(rs.getInt("GENETIC_PROFILE_ID")); mutation.setSampleId(rs.getInt("SAMPLE_ID")); mutation.setSequencingCenter(rs.getString("CENTER")); mutation.setSequencer(rs.getString("SEQUENCER")); mutation.setMutationStatus(rs.getString("MUTATION_STATUS")); mutation.setValidationStatus(rs.getString("VALIDATION_STATUS")); mutation.setTumorSeqAllele1(rs.getString("TUMOR_SEQ_ALLELE1")); mutation.setTumorSeqAllele2(rs.getString("TUMOR_SEQ_ALLELE2")); mutation.setMatchedNormSampleBarcode(rs.getString("MATCHED_NORM_SAMPLE_BARCODE")); mutation.setMatchNormSeqAllele1(rs.getString("MATCH_NORM_SEQ_ALLELE1")); mutation.setMatchNormSeqAllele2(rs.getString("MATCH_NORM_SEQ_ALLELE2")); mutation.setTumorValidationAllele1(rs.getString("TUMOR_VALIDATION_ALLELE1")); mutation.setTumorValidationAllele2(rs.getString("TUMOR_VALIDATION_ALLELE2")); mutation.setMatchNormValidationAllele1(rs.getString("MATCH_NORM_VALIDATION_ALLELE1")); mutation.setMatchNormValidationAllele2(rs.getString("MATCH_NORM_VALIDATION_ALLELE2")); mutation.setVerificationStatus(rs.getString("VERIFICATION_STATUS")); mutation.setSequencingPhase(rs.getString("SEQUENCING_PHASE")); mutation.setSequenceSource(rs.getString("SEQUENCE_SOURCE")); mutation.setValidationMethod(rs.getString("VALIDATION_METHOD")); mutation.setScore(rs.getString("SCORE")); mutation.setBamFile(rs.getString("BAM_FILE")); mutation.setTumorAltCount(rs.getInt("TUMOR_ALT_COUNT")); mutation.setTumorRefCount(rs.getInt("TUMOR_REF_COUNT")); mutation.setNormalAltCount(rs.getInt("NORMAL_ALT_COUNT")); mutation.setNormalRefCount(rs.getInt("NORMAL_REF_COUNT")); return mutation; } catch(NullPointerException e) { throw new DaoException(e); } } private static ExtendedMutation.MutationEvent extractMutationEvent(ResultSet rs) throws SQLException, DaoException { ExtendedMutation.MutationEvent event = new ExtendedMutation.MutationEvent(); event.setMutationEventId(rs.getLong("MUTATION_EVENT_ID")); long entrezId = rs.getLong("mutation_event.ENTREZ_GENE_ID"); DaoGeneOptimized aDaoGene = DaoGeneOptimized.getInstance(); CanonicalGene gene = aDaoGene.getGene(entrezId); event.setGene(gene); event.setChr(rs.getString("CHR")); event.setStartPosition(rs.getLong("START_POSITION")); event.setEndPosition(rs.getLong("END_POSITION")); event.setProteinChange(rs.getString("PROTEIN_CHANGE")); event.setMutationType(rs.getString("MUTATION_TYPE")); event.setFunctionalImpactScore(rs.getString("FUNCTIONAL_IMPACT_SCORE")); event.setFisValue(rs.getFloat("FIS_VALUE")); event.setLinkXVar(rs.getString("LINK_XVAR")); event.setLinkPdb(rs.getString("LINK_PDB")); event.setLinkMsa(rs.getString("LINK_MSA")); event.setNcbiBuild(rs.getString("NCBI_BUILD")); event.setStrand(rs.getString("STRAND")); event.setVariantType(rs.getString("VARIANT_TYPE")); event.setDbSnpRs(rs.getString("DB_SNP_RS")); event.setDbSnpValStatus(rs.getString("DB_SNP_VAL_STATUS")); event.setReferenceAllele(rs.getString("REFERENCE_ALLELE")); event.setOncotatorDbSnpRs(rs.getString("ONCOTATOR_DBSNP_RS")); event.setOncotatorRefseqMrnaId(rs.getString("ONCOTATOR_REFSEQ_MRNA_ID")); event.setOncotatorCodonChange(rs.getString("ONCOTATOR_CODON_CHANGE")); event.setOncotatorUniprotName(rs.getString("ONCOTATOR_UNIPROT_ENTRY_NAME")); event.setOncotatorUniprotAccession(rs.getString("ONCOTATOR_UNIPROT_ACCESSION")); event.setOncotatorProteinPosStart(rs.getInt("ONCOTATOR_PROTEIN_POS_START")); event.setOncotatorProteinPosEnd(rs.getInt("ONCOTATOR_PROTEIN_POS_END")); event.setCanonicalTranscript(rs.getBoolean("CANONICAL_TRANSCRIPT")); event.setTumorSeqAllele(rs.getString("TUMOR_SEQ_ALLELE")); event.setKeyword(rs.getString("KEYWORD")); return event; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static int getCount() throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement("SELECT COUNT(*) FROM mutation"); rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } return 0; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * Get significantly mutated genes * @param profileId * @param entrezGeneIds * @param thresholdRecurrence * @param thresholdNumGenes * @param selectedCaseIds * @return * @throws DaoException * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Long, Map<String, String>> getSMGs(int profileId, Collection<Long> entrezGeneIds, int thresholdRecurrence, int thresholdNumGenes, Collection<Integer> selectedCaseIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement("SET SESSION group_concat_max_len = 1000000"); rs = pstmt.executeQuery(); String sql = "SELECT mutation.ENTREZ_GENE_ID, GROUP_CONCAT(mutation.SAMPLE_ID), COUNT(*), COUNT(*)/`LENGTH` AS count_per_nt" + " FROM mutation, gene" + " WHERE mutation.ENTREZ_GENE_ID=gene.ENTREZ_GENE_ID" + " AND GENETIC_PROFILE_ID=" + profileId + (entrezGeneIds==null?"":(" AND mutation.ENTREZ_GENE_ID IN("+StringUtils.join(entrezGeneIds,",")+")")) + (selectedCaseIds==null?"":(" AND mutation.SAMPLE_ID IN("+StringUtils.join(selectedCaseIds,",")+")")) + " GROUP BY mutation.ENTREZ_GENE_ID" + (thresholdRecurrence>0?(" HAVING COUNT(*)>="+thresholdRecurrence):"") + " ORDER BY count_per_nt DESC" + (thresholdNumGenes>0?(" LIMIT 0,"+thresholdNumGenes):""); pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); Map<Long, Map<String, String>> map = new HashMap(); while (rs.next()) { Map<String, String> value = new HashMap<>(); value.put("caseIds", rs.getString(2)); value.put("count", rs.getString(3)); map.put(rs.getLong(1), value); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * return the number of all mutations for a profile * @param profileId * @return Map &lt; case id, mutation count &gt; * @throws DaoException * * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static int countMutationEvents(int profileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT count(DISTINCT `SAMPLE_ID`, `MUTATION_EVENT_ID`) FROM mutation" + " WHERE `GENETIC_PROFILE_ID`=" + profileId; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt(1); } return 0; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * return the number of mutations for each sample * @param sampleIds if null, return all case available * @param profileId * @return Map &lt; sample id, mutation count &gt; * @throws DaoException * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Integer, Integer> countMutationEvents(int profileId, Collection<Integer> sampleIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql; if (sampleIds==null) { sql = "SELECT `SAMPLE_ID`, `MUTATION_COUNT` FROM mutation_count" + " WHERE `GENETIC_PROFILE_ID`=" + profileId; } else { sql = "SELECT `SAMPLE_ID`, `MUTATION_COUNT` FROM mutation_count" + " WHERE `GENETIC_PROFILE_ID`=" + profileId + " AND `SAMPLE_ID` IN ('" + StringUtils.join(sampleIds,"','") + "')"; } pstmt = con.prepareStatement(sql); Map<Integer, Integer> map = new HashMap<Integer, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getInt(1), rs.getInt(2)); } return map; } catch (NullPointerException e) { throw new DaoException(e); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * get events for each sample * @return Map &lt; sample id, list of event ids &gt; * @throws DaoException * * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Integer, Set<Long>> getSamplesWithMutations(Collection<Long> eventIds) throws DaoException { return getSamplesWithMutations(StringUtils.join(eventIds, ",")); } /** * get events for each sample * @param concatEventIds event ids concatenated by comma (,) * @return Map &lt; sample id, list of event ids &gt; * @throws DaoException * * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Integer, Set<Long>> getSamplesWithMutations(String concatEventIds) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT `SAMPLE_ID`, `MUTATION_EVENT_ID` FROM mutation" + " WHERE `MUTATION_EVENT_ID` IN (" + concatEventIds + ")"; pstmt = con.prepareStatement(sql); Map<Integer, Set<Long>> map = new HashMap<Integer, Set<Long>> (); rs = pstmt.executeQuery(); while (rs.next()) { int sampleId = rs.getInt("SAMPLE_ID"); long eventId = rs.getLong("MUTATION_EVENT_ID"); Set<Long> events = map.get(sampleId); if (events == null) { events = new HashSet<Long>(); map.put(sampleId, events); } events.add(eventId); } return map; } catch (NullPointerException e) { throw new DaoException(e); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @return Map &lt; sample, list of event ids &gt; * @throws DaoException * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Sample, Set<Long>> getSimilarSamplesWithMutationsByKeywords( Collection<Long> eventIds) throws DaoException { return getSimilarSamplesWithMutationsByKeywords(StringUtils.join(eventIds, ",")); } /** * @param concatEventIds event ids concatenated by comma (,) * @return Map &lt; sample, list of event ids &gt; * @throws DaoException */ public static Map<Sample, Set<Long>> getSimilarSamplesWithMutationsByKeywords( String concatEventIds) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT `SAMPLE_ID`, `GENETIC_PROFILE_ID`, me1.`MUTATION_EVENT_ID`" + " FROM mutation cme, mutation_event me1, mutation_event me2" + " WHERE me1.`MUTATION_EVENT_ID` IN ("+ concatEventIds + ")" + " AND me1.`KEYWORD`=me2.`KEYWORD`" + " AND cme.`MUTATION_EVENT_ID`=me2.`MUTATION_EVENT_ID`"; pstmt = con.prepareStatement(sql); Map<Sample, Set<Long>> map = new HashMap<Sample, Set<Long>> (); rs = pstmt.executeQuery(); while (rs.next()) { Sample sample = DaoSample.getSampleById(rs.getInt("SAMPLE_ID")); long eventId = rs.getLong("MUTATION_EVENT_ID"); Set<Long> events = map.get(sample); if (events == null) { events = new HashSet<Long>(); map.put(sample, events); } events.add(eventId); } return map; } catch (NullPointerException e) { throw new DaoException(e); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @param entrezGeneIds event ids concatenated by comma (,) * @return Map &lt; sample, list of event ids &gt; * @throws DaoException * * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Sample, Set<Long>> getSimilarSamplesWithMutatedGenes( Collection<Long> entrezGeneIds) throws DaoException { if (entrezGeneIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT `SAMPLE_ID`, `GENETIC_PROFILE_ID`, `ENTREZ_GENE_ID`" + " FROM mutation" + " WHERE `ENTREZ_GENE_ID` IN ("+ StringUtils.join(entrezGeneIds,",") + ")"; pstmt = con.prepareStatement(sql); Map<Sample, Set<Long>> map = new HashMap<Sample, Set<Long>> (); rs = pstmt.executeQuery(); while (rs.next()) { Sample sample = DaoSample.getSampleById(rs.getInt("SAMPLE_ID")); long entrez = rs.getLong("ENTREZ_GENE_ID"); Set<Long> genes = map.get(sample); if (genes == null) { genes = new HashSet<Long>(); map.put(sample, genes); } genes.add(entrez); } return map; } catch (NullPointerException e) { throw new DaoException(e); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Long, Integer> countSamplesWithMutationEvents(Collection<Long> eventIds, int profileId) throws DaoException { return countSamplesWithMutationEvents(StringUtils.join(eventIds, ","), profileId); } /** * return the number of samples for each mutation event * @param concatEventIds * @param profileId * @return Map &lt; event id, sampleCount &gt; * @throws DaoException * * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Long, Integer> countSamplesWithMutationEvents(String concatEventIds, int profileId) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT `MUTATION_EVENT_ID`, count(DISTINCT `SAMPLE_ID`) FROM mutation" + " WHERE `GENETIC_PROFILE_ID`=" + profileId + " AND `MUTATION_EVENT_ID` IN (" + concatEventIds + ") GROUP BY `MUTATION_EVENT_ID`"; pstmt = con.prepareStatement(sql); Map<Long, Integer> map = new HashMap<Long, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getLong(1), rs.getInt(2)); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Long, Integer> countSamplesWithMutatedGenes(Collection<Long> entrezGeneIds, int profileId) throws DaoException { return countSamplesWithMutatedGenes(StringUtils.join(entrezGeneIds, ","), profileId); } /** * return the number of samples for each mutated genes * @param concatEntrezGeneIds * @param profileId * @return Map &lt; entrez, sampleCount &gt; * @throws DaoException * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<Long, Integer> countSamplesWithMutatedGenes(String concatEntrezGeneIds, int profileId) throws DaoException { if (concatEntrezGeneIds.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID)" + " FROM mutation" + " WHERE GENETIC_PROFILE_ID=" + profileId + " AND ENTREZ_GENE_ID IN (" + concatEntrezGeneIds + ") GROUP BY `ENTREZ_GENE_ID`"; pstmt = con.prepareStatement(sql); Map<Long, Integer> map = new HashMap<Long, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getLong(1), rs.getInt(2)); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Map<String, Integer> countSamplesWithKeywords(Collection<String> keywords, int profileId) throws DaoException { if (keywords.isEmpty()) { return Collections.emptyMap(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT KEYWORD, count(DISTINCT SAMPLE_ID)" + " FROM mutation, mutation_event" + " WHERE GENETIC_PROFILE_ID=" + profileId + " AND mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID" + " AND KEYWORD IN ('" + StringUtils.join(keywords,"','") + "') GROUP BY `KEYWORD`"; pstmt = con.prepareStatement(sql); Map<String, Integer> map = new HashMap<String, Integer>(); rs = pstmt.executeQuery(); while (rs.next()) { map.put(rs.getString(1), rs.getInt(2)); } return map; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * * Counts all the samples in each cancer study in the collection of geneticProfileIds by mutation keyword * * @param keywords * @param internalProfileIds * @return Collection of Maps {"keyword" , "hugo" , "cancer_study" , "count"} where cancer_study == cancerStudy.getName(); * @throws DaoException * @author Gideon Dresdner <dresdnerg@cbio.mskcc.org> */ public static Collection<Map<String, Object>> countSamplesWithKeywords(Collection<String> keywords, Collection<Integer> internalProfileIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT KEYWORD, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID) FROM mutation, mutation_event " + "WHERE GENETIC_PROFILE_ID IN (" + StringUtils.join(internalProfileIds, ",") + ") " + "AND mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "AND KEYWORD IN ('" + StringUtils.join(keywords, "','") + "') " + "GROUP BY KEYWORD, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID"; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); while (rs.next()) { Map<String, Object> d = new HashMap<String, Object>(); String keyword = rs.getString(1); Integer geneticProfileId = rs.getInt(2); Long entrez = rs.getLong(3); Integer count = rs.getInt(4); // this is computing a join and in not optimal GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); Integer cancerStudyId = geneticProfile.getCancerStudyId(); CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId); String name = cancerStudy.getName(); String cancerType = cancerStudy.getTypeOfCancerId(); CanonicalGene gene = DaoGeneOptimized.getInstance().getGene(entrez); String hugo = gene.getHugoGeneSymbolAllCaps(); d.put("keyword", keyword); d.put("hugo", hugo); d.put("cancer_study", name); d.put("cancer_type", cancerType); d.put("count", count); data.add(d); } return data; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * * Counts up all the samples that have any mutation in a gene by genomic profile (ids) * * @param hugos * @param internalProfileIds * @return Collection of Maps {"hugo" , "cancer_study" , "count"} where cancer_study == cancerStudy.getName(); * and gene is the hugo gene symbol. * * @throws DaoException * @author Gideon Dresdner <dresdnerg@cbio.mskcc.org> */ public static Collection<Map<String, Object>> countSamplesWithGenes(Collection<String> hugos, Collection<Integer> internalProfileIds) throws DaoException { // convert hugos to entrezs // and simultaneously construct a map to turn them back into hugo gene symbols later List<Long> entrezs = new ArrayList<Long>(); Map<Long, CanonicalGene> entrez2CanonicalGene = new HashMap<Long, CanonicalGene>(); DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance(); for (String hugo : hugos) { CanonicalGene canonicalGene = daoGeneOptimized.getGene(hugo); Long entrez = canonicalGene.getEntrezGeneId(); entrezs.add(entrez); entrez2CanonicalGene.put(entrez, canonicalGene); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "select mutation.ENTREZ_GENE_ID, mutation.GENETIC_PROFILE_ID, count(distinct SAMPLE_ID) from mutation, mutation_event\n" + "where GENETIC_PROFILE_ID in (" + StringUtils.join(internalProfileIds, ",") + ")\n" + "and mutation.ENTREZ_GENE_ID in (" + StringUtils.join(entrezs, ",") + ")\n" + "and mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID\n" + "group by ENTREZ_GENE_ID, GENETIC_PROFILE_ID"; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); while (rs.next()) { Map<String, Object> d = new HashMap<String, Object>(); Long entrez = rs.getLong(1); Integer geneticProfileId = rs.getInt(2); Integer count = rs.getInt(3); // can you get a cancerStudy's name? // this is computing a join and in not optimal GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); Integer cancerStudyId = geneticProfile.getCancerStudyId(); CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId); String name = cancerStudy.getName(); String cancerType = cancerStudy.getTypeOfCancerId(); CanonicalGene canonicalGene = entrez2CanonicalGene.get(entrez); String hugo = canonicalGene.getHugoGeneSymbolAllCaps(); d.put("hugo", hugo); d.put("cancer_study", name); d.put("cancer_type", cancerType); d.put("count", count); data.add(d); } return data; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } public static Collection<Map<String, Object>> countSamplesWithProteinChanges( Collection<String> proteinChanges, Collection<Integer> internalProfileIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT PROTEIN_CHANGE, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID) FROM mutation, mutation_event " + "WHERE GENETIC_PROFILE_ID IN (" + StringUtils.join(internalProfileIds, ",") + ") " + "AND mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "AND PROTEIN_CHANGE IN ('" + StringUtils.join(proteinChanges, "','") + "') " + "GROUP BY PROTEIN_CHANGE, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID"; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); while (rs.next()) { Map<String, Object> d = new HashMap<String, Object>(); String proteinChange = rs.getString(1); Integer geneticProfileId = rs.getInt(2); Long entrez = rs.getLong(3); Integer count = rs.getInt(4); // can you get a cancerStudy's name? // this is computing a join and in not optimal GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); Integer cancerStudyId = geneticProfile.getCancerStudyId(); CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId); String name = cancerStudy.getName(); String cancerType = cancerStudy.getTypeOfCancerId(); CanonicalGene gene = DaoGeneOptimized.getInstance().getGene(entrez); String hugo = gene.getHugoGeneSymbolAllCaps(); d.put("protein_change", proteinChange); d.put("hugo", hugo); d.put("cancer_study", name); d.put("cancer_type", cancerType); d.put("count", count); data.add(d); } return data; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } public static Collection<Map<String, Object>> countSamplesWithProteinPosStarts( Collection<String> proteinPosStarts, Collection<Integer> internalProfileIds) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; //performance fix: mutation table contains geneId; by filtering on a geneId set before table join, the temporary table needed is smaller. //a geneticProfileId set filter alone can in some cases let almost all mutations into the temporary table HashSet<String> geneIdSet = new HashSet<String>(); if (proteinPosStarts != null) { Pattern geneIdPattern = Pattern.compile("\\(\\s*(\\d+)\\s*,"); for (String proteinPos : proteinPosStarts) { Matcher geneIdMatcher = geneIdPattern.matcher(proteinPos); if (geneIdMatcher.find()) { geneIdSet.add(geneIdMatcher.group(1)); } } } if (geneIdSet.size() == 0 || internalProfileIds.size() == 0) return new ArrayList<Map<String, Object>>(); //empty IN() clause would be a SQL error below try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT ONCOTATOR_PROTEIN_POS_START, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID, count(DISTINCT SAMPLE_ID) " + "FROM mutation INNER JOIN mutation_event ON mutation.MUTATION_EVENT_ID=mutation_event.MUTATION_EVENT_ID " + "WHERE mutation.ENTREZ_GENE_ID IN (" + StringUtils.join(geneIdSet, ",") + ") " + "AND GENETIC_PROFILE_ID IN (" + StringUtils.join(internalProfileIds, ",") + ") " + "AND (mutation.ENTREZ_GENE_ID, ONCOTATOR_PROTEIN_POS_START) IN (" + StringUtils.join(proteinPosStarts, ",") + ") " + "GROUP BY ONCOTATOR_PROTEIN_POS_START, GENETIC_PROFILE_ID, mutation.ENTREZ_GENE_ID"; pstmt = con.prepareStatement(sql); rs = pstmt.executeQuery(); Collection<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); while (rs.next()) { Map<String, Object> d = new HashMap<String, Object>(); String proteinPosStart = rs.getString(1); Integer geneticProfileId = rs.getInt(2); Long entrez = rs.getLong(3); Integer count = rs.getInt(4); // can you get a cancerStudy's name? // this is computing a join and in not optimal GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); Integer cancerStudyId = geneticProfile.getCancerStudyId(); CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByInternalId(cancerStudyId); String name = cancerStudy.getName(); String cancerType = cancerStudy.getTypeOfCancerId(); CanonicalGene gene = DaoGeneOptimized.getInstance().getGene(entrez); String hugo = gene.getHugoGeneSymbolAllCaps(); d.put("protein_pos_start", proteinPosStart); d.put("protein_start_with_hugo", hugo+"_"+proteinPosStart); d.put("hugo", hugo); d.put("cancer_study", name); d.put("cancer_type", cancerType); d.put("count", count); data.add(d); } return data; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Set<Long> getGenesOfMutations( Collection<Long> eventIds, int profileId) throws DaoException { return getGenesOfMutations(StringUtils.join(eventIds, ","), profileId); } /** * return entrez gene ids of the mutations specified by their mutaiton event ids. * @param concatEventIds * @param profileId * @return * @throws DaoException * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Set<Long> getGenesOfMutations(String concatEventIds, int profileId) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptySet(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT DISTINCT ENTREZ_GENE_ID FROM mutation_event " + "WHERE MUTATION_EVENT_ID in (" + concatEventIds + ")"; pstmt = con.prepareStatement(sql); Set<Long> set = new HashSet<Long>(); rs = pstmt.executeQuery(); while (rs.next()) { set.add(rs.getLong(1)); } return set; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * return keywords of the mutations specified by their mutaiton event ids. * @param concatEventIds * @param profileId * @return * @throws DaoException * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static Set<String> getKeywordsOfMutations(String concatEventIds, int profileId) throws DaoException { if (concatEventIds.isEmpty()) { return Collections.emptySet(); } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); String sql = "SELECT DISTINCT KEYWORD FROM mutation_event " + "WHERE MUTATION_EVENT_ID in (" + concatEventIds + ")"; pstmt = con.prepareStatement(sql); Set<String> set = new HashSet<String>(); rs = pstmt.executeQuery(); while (rs.next()) { set.add(rs.getString(1)); } return set; } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } protected static String boolToStr(boolean value) { return value ? "1" : "0"; } /** * @deprecated We believe that this method is no longer called by any part of the codebase, and it will soon be deleted. */ @Deprecated public static void deleteAllRecordsInGeneticProfile(long geneticProfileId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement("DELETE from mutation WHERE GENETIC_PROFILE_ID=?"); pstmt.setLong(1, geneticProfileId); pstmt.executeUpdate(); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } public static void deleteAllRecords() throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoMutation.class); JdbcUtil.disableForeignKeyCheck(con); pstmt = con.prepareStatement("TRUNCATE TABLE mutation"); pstmt.executeUpdate(); pstmt = con.prepareStatement("TRUNCATE TABLE mutation_event"); pstmt.executeUpdate(); JdbcUtil.enableForeignKeyCheck(con); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } /** * Gets all tiers in alphabetical order. * * @param * @return Ordered list of tiers. * @throws DaoException Database Error. */ public static List<String> getTiers(String _cancerStudyStableIds) throws DaoException { String[] cancerStudyStableIds = _cancerStudyStableIds.split(","); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<String> tiers = new ArrayList<String>(); ArrayList<GeneticProfile> geneticProfiles = new ArrayList<>(); for (String cancerStudyStableId: cancerStudyStableIds) { geneticProfiles.addAll(DaoGeneticProfile.getAllGeneticProfiles( DaoCancerStudy.getCancerStudyByStableId(cancerStudyStableId).getInternalId() )); } for (GeneticProfile geneticProfile : geneticProfiles) { if (geneticProfile.getGeneticAlterationType().equals(GeneticAlterationType.MUTATION_EXTENDED)) { try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT DISTINCT DRIVER_TIERS_FILTER FROM mutation " + "WHERE DRIVER_TIERS_FILTER is not NULL AND DRIVER_TIERS_FILTER <> '' AND GENETIC_PROFILE_ID=? " + "ORDER BY DRIVER_TIERS_FILTER"); pstmt.setLong(1, geneticProfile.getGeneticProfileId()); rs = pstmt.executeQuery(); while (rs.next()) { tiers.add(rs.getString("DRIVER_TIERS_FILTER")); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } } return tiers; } /** * Returns the number of tiers in the cancer study.. * * @param * @return Ordered list of tiers. * @throws DaoException Database Error. */ public static int numTiers(String _cancerStudyStableIds) throws DaoException { List<String> tiers = getTiers(_cancerStudyStableIds); return tiers.size(); } /** * Returns true if there are "Putative_Driver" or "Putative_Passenger" values in the * binary annotation column. Otherwise, it returns false. * * @param * @return Ordered list of tiers. * @throws DaoException Database Error. */ public static boolean hasDriverAnnotations(String _cancerStudyStableIds) throws DaoException { String[] cancerStudyStableIds = _cancerStudyStableIds.split(","); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<String> driverValues = new ArrayList<String>(); ArrayList<GeneticProfile> geneticProfiles = new ArrayList<>(); for (String cancerStudyStableId: cancerStudyStableIds) { geneticProfiles.addAll( DaoGeneticProfile.getAllGeneticProfiles(DaoCancerStudy.getCancerStudyByStableId(cancerStudyStableId).getInternalId()) ); } for (GeneticProfile geneticProfile : geneticProfiles) { if (geneticProfile.getGeneticAlterationType().equals(GeneticAlterationType.MUTATION_EXTENDED)) { try { con = JdbcUtil.getDbConnection(DaoMutation.class); pstmt = con.prepareStatement( "SELECT DISTINCT DRIVER_FILTER FROM mutation " + "WHERE DRIVER_FILTER is not NULL AND DRIVER_FILTER <> '' AND GENETIC_PROFILE_ID=? "); pstmt.setLong(1, geneticProfile.getGeneticProfileId()); rs = pstmt.executeQuery(); while (rs.next()) { driverValues.add(rs.getString("DRIVER_FILTER")); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoMutation.class, con, pstmt, rs); } } } if (driverValues.size() > 0) { return true; } return false; } }
package complex.reportdesign; import java.io.File; import java.util.ArrayList; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XNameAccess; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XModel; import com.sun.star.frame.XStorable; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sdb.XDocumentDataSource; import com.sun.star.sdb.XOfficeDatabaseDocument; import com.sun.star.sdb.XReportDocumentsSupplier; import com.sun.star.sdb.application.XDatabaseDocumentUI; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.util.XCloseable; // import util.BasicMacroTools; // import util.DesktopTools; // import util.dbg; // import complexlib.ComplexTestCase; // import util.utils; import helper.OfficeProvider; import helper.URLHelper; // import helper.OfficeWatcher; import convwatch.DB; // import java.util.Date; // import java.text.SimpleDateFormat; // import java.text.ParsePosition; // import java.sql.Time; // import java.io.BufferedReader; // import java.io.File; // import java.io.FileReader; // import java.io.IOException; // import java.io.FilenameFilter; // import java.util.Vector; // import helper.AppProvider; // import java.text.DecimalFormat; // import util.DynamicClassLoader; // import java.util.StringTokenizer; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.openoffice.test.OfficeConnection; import static org.junit.Assert.*; class PropertySetHelper { XPropertySet m_xPropertySet; public PropertySetHelper(Object _aObj) { m_xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, _aObj); } /** get a property and don't convert it @param _sName the string name of the property @return the object value of the property without any conversion */ public Object getPropertyValueAsObject(String _sName) { Object aObject = null; if (m_xPropertySet != null) { try { aObject = m_xPropertySet.getPropertyValue(_sName); } catch (com.sun.star.beans.UnknownPropertyException e) { System.out.println("ERROR: UnknownPropertyException caught. '" + _sName + "'"); System.out.println("Message: " + e.getMessage()); } catch (com.sun.star.lang.WrappedTargetException e) { System.out.println("ERROR: WrappedTargetException caught."); System.out.println("Message: " + e.getMessage()); } } return aObject; } } class PropertyHelper { /** Create a PropertyValue[] from a ArrayList @param _aArrayList @return a PropertyValue[] */ public static PropertyValue[] createPropertyValueArrayFormArrayList(ArrayList _aPropertyList) { // copy the whole PropertyValue List to an PropertyValue Array PropertyValue[] aSaveProperties = null; if (_aPropertyList == null) { aSaveProperties = new PropertyValue[0]; } else { if (_aPropertyList.size() > 0) { aSaveProperties = new PropertyValue[_aPropertyList.size()]; for (int i = 0;i<_aPropertyList.size(); i++) { aSaveProperties[i] = (PropertyValue) _aPropertyList.get(i); } } else { aSaveProperties = new PropertyValue[0]; } } return aSaveProperties; } } public class ReportDesignerTest { String mTestDocumentPath; // public String[] getTestMethodNames() // return new String[] {"firsttest"}; @Before public void before() { System.out.println("before"); // String tempdir = System.getProperty("java.io.tmpdir"); int dummy = 0; // m_xXMultiServiceFactory = getMSF(); } @After public void after() { System.out.println("after"); } // private void checkIfOfficeExists(String _sOfficePathWithTrash) // String sOfficePath = ""; // int nIndex = _sOfficePathWithTrash.indexOf("soffice.exe"); // if (nIndex > 0) // sOfficePath = _sOfficePathWithTrash.substring(0, nIndex + 11); // else // nIndex = _sOfficePathWithTrash.indexOf("soffice"); // if (nIndex > 0) // sOfficePath = _sOfficePathWithTrash.substring(0, nIndex + 7); // System.out.println(sOfficePath); // File sOffice = new File(sOfficePath); // if (! sOffice.exists()) // System.out.println("ERROR: There exists no office installation at given path: '" + sOfficePath + "'"); // System.exit(0); private XDesktop m_xDesktop = null; public XDesktop getXDesktop() { if (m_xDesktop == null) { try { XInterface xInterface = (XInterface) getMSF().createInstance( "com.sun.star.frame.Desktop" ); m_xDesktop = UnoRuntime.queryInterface(XDesktop.class, xInterface); assertNotNull("Can't get XDesktop", m_xDesktop); } catch (com.sun.star.uno.Exception e) { System.out.println("ERROR: uno.Exception caught"); System.out.println("Message: " + e.getMessage()); } } return m_xDesktop; } private void showElements(XNameAccess _xNameAccess) { if (_xNameAccess != null) { String[] sElementNames = _xNameAccess.getElementNames(); for(int i=0;i<sElementNames.length; i++) { System.out.println("Value: [" + i + "] := " + sElementNames[i]); } } else { System.out.println("Warning: Given object is null."); } } private OfficeProvider m_aProvider = null; // private void startOffice() // // int tempTime = param.getInt("SingleTimeOut"); // param.put("TimeOut", new Integer(300000)); // System.out.println("TimeOut: " + param.getInt("TimeOut")); // System.out.println("ThreadTimeOut: " + param.getInt("ThreadTimeOut")); // // OfficeProvider aProvider = null; // m_aProvider = new OfficeProvider(); // m_xXMultiServiceFactory = (XMultiServiceFactory) m_aProvider.getManager(param); // param.put("ServiceFactory", m_xXMultiServiceFactory); // private void stopOffice() // if (m_aProvider != null) // m_aProvider.closeExistingOffice(param, true); // m_aProvider = null; private String m_sMailAddress = null; private String m_sUPDMinor; private String m_sCWS_WORK_STAMP; private static final int WRITER = 1; private static final int CALC = 2; @Test public void firsttest() { // convwatch.GlobalLogWriter.set(log); // String sAppExecutionCommand = (String) param.get("AppExecutionCommand"); String sUser = System.getProperty("user.name"); System.out.println("user.name='" + sUser + "'"); String sVCSID = System.getProperty("VCSID"); System.out.println("VCSID='" + sVCSID + "'"); m_sMailAddress = sVCSID + "@openoffice.org"; System.out.println("Assumed mail address: " + m_sMailAddress); m_sUPDMinor = System.getProperty("UPDMINOR"); m_sCWS_WORK_STAMP = System.getProperty("CWS_WORK_STAMP"); // createDBEntry(); System.out.println("Current CWS: " + m_sCWS_WORK_STAMP); System.out.println("Current MWS: " + m_sUPDMinor); // System.exit(1); // sAppExecutionCommand = sAppExecutionCommand.replaceAll( "\\$\\{USERNAME\\}", sUser); // System.out.println("sAppExecutionCommand='" + sAppExecutionCommand + "'"); // an other way to replace strings // sAppExecutionCommand = utils.replaceAll13(sAppExecutionCommand, "${USERNAME}", sUser); // checkIfOfficeExists(sAppExecutionCommand); // param.put("AppExecutionCommand", new String(sAppExecutionCommand)); // startOffice(); // String sCurrentDirectory = System.getProperty("user.dir"); // System.out.println("Current Dir: " + sCurrentDirectory); String sWriterDocument = TestDocument.getUrl("RPTWriterTests.odb"); startTestForFile(sWriterDocument, WRITER); String sCalcDocument = TestDocument.getUrl("RPTCalcTests.odb"); startTestForFile(sCalcDocument, CALC); // catch (AssureException e) // stopOffice(); // throw new AssureException(e.getMessage()); // stopOffice(); } private void startTestForFile(String _sDocument, int _nType) { FileURL aFileURL = new FileURL(_sDocument); assertTrue("Test File doesn't '" + _sDocument + "'exist.", aFileURL.exists()); String sFileURL = _sDocument; // URLHelper.getFileURLFromSystemPath(_sDocument); System.out.println("File URL: " + sFileURL); XComponent xDocComponent = loadComponent(sFileURL, getXDesktop(), null); System.out.println("Load done"); assertNotNull("Can't load document ", xDocComponent); // context = createUnoService("com.sun.star.sdb.DatabaseContext") // oDataBase = context.getByName("hh") // oDBDoc = oDataBase.DatabaseDocument // dim args(1) as new com.sun.star.beans.PropertyValue // args(0).Name = "ActiveConnection" // args(0).Value = oDBDoc.getCurrentController().getPropertyValue("ActiveConnection") // reportContainer = oDBDoc.getReportDocuments() // report = reportContainer.loadComponentFromURL("Report40","",0,args) try { XInterface x = (XInterface)getMSF().createInstance("com.sun.star.sdb.DatabaseContext"); assertNotNull("can't create instance of com.sun.star.sdb.DatabaseContext", x); System.out.println("createInstance com.sun.star.sdb.DatabaseContext done"); XNameAccess xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, x); showElements(xNameAccess); Object aObj = xNameAccess.getByName(sFileURL); // System.out.println("1"); // PropertySetHelper aHelper = new PropertySetHelper(aObj); XDocumentDataSource xDataSource = UnoRuntime.queryInterface(XDocumentDataSource.class, aObj); // Object aDatabaseDocmuent = aHelper.getPropertyValueAsObject("DatabaseDocument"); XOfficeDatabaseDocument xOfficeDBDoc = xDataSource.getDatabaseDocument(); // XOfficeDatabaseDocument xOfficeDBDoc = (XOfficeDatabaseDocument)UnoRuntime.queryInterface(XOfficeDatabaseDocument.class, aDatabaseDocument); assertNotNull("can't access DatabaseDocument", xOfficeDBDoc); // System.out.println("2"); XModel xDBSource = UnoRuntime.queryInterface(XModel.class, xOfficeDBDoc); Object aController = xDBSource.getCurrentController(); assertNotNull("Controller of xOfficeDatabaseDocument is empty!", aController); // System.out.println("3"); XDatabaseDocumentUI aDBDocUI = UnoRuntime.queryInterface(XDatabaseDocumentUI.class, aController); /* boolean isConnect = */ // TODO: throws an exception in DEV300m78 aDBDocUI.connect(); // if (isConnect) // System.out.println("true"); // else // System.out.println("false"); // System.out.println("4"); // aHelper = new PropertySetHelper(aController); // Object aActiveConnectionObj = aHelper.getPropertyValueAsObject("ActiveConnection"); Object aActiveConnectionObj = aDBDocUI.getActiveConnection(); assertNotNull("ActiveConnection is empty", aActiveConnectionObj); // System.out.println("5"); XReportDocumentsSupplier xSupplier = UnoRuntime.queryInterface(XReportDocumentsSupplier.class, xOfficeDBDoc); xNameAccess = xSupplier.getReportDocuments(); assertNotNull("xOfficeDatabaseDocument returns no Report Document", xNameAccess); // System.out.println("5"); showElements(xNameAccess); ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>(); PropertyValue aActiveConnection = new PropertyValue(); aActiveConnection.Name = "ActiveConnection"; aActiveConnection.Value = aActiveConnectionObj; aPropertyList.add(aActiveConnection); loadAndStoreReports(xNameAccess, aPropertyList, _nType); createDBEntry(_nType); } catch(com.sun.star.uno.Exception e) { fail("ERROR: Exception caught" + e.getMessage()); } // String mTestDocumentPath = (String) param.get("TestDocumentPath"); // System.out.println("mTestDocumentPath: '" + mTestDocumentPath + "'"); // // workaround for issue using deprecated "DOCPTH" prop // System.setProperty("DOCPTH", mTestDocumentPath); // Close the document closeComponent(xDocComponent); } private String getDocumentPoolName(int _nType) { return getFileFormat(_nType); } private void createDBEntry(int _nType) { // try to connect the database String sDBConnection = ""; // (String)param.get( convwatch.PropertyName.DB_CONNECTION_STRING ); System.out.println("DBConnection: " + sDBConnection); DB.init(sDBConnection); String sDestinationVersion = m_sCWS_WORK_STAMP; if (sDestinationVersion.length() == 0) { sDestinationVersion = m_sUPDMinor; } String sDestinationName = ""; String sDestinationCreatorType = ""; String sDocumentPoolDir = getOutputPath(_nType); String sDocumentPoolName = getDocumentPoolName(_nType); String sSpecial = ""; String sFixRefSubDirectory = "ReportDesign_qa_complex_" + getFileFormat(_nType); // DB.insertinto_documentcompare(sFixRefSubDirectory, "", "fixref", // sDestinationVersion, sDestinationName, sDestinationCreatorType, // sDocumentPoolDir, sDocumentPoolName, m_sMailAddress, // sSpecial); // DB.test(); // System.exit(1); } private void loadAndStoreReports(XNameAccess _xNameAccess, ArrayList _aPropertyList, int _nType) { if (_xNameAccess != null) { String[] sElementNames = _xNameAccess.getElementNames(); for(int i=0;i<sElementNames.length; i++) { String sReportName = sElementNames[i]; XComponent xDoc = loadComponent(sReportName, _xNameAccess, _aPropertyList); // print? or store? storeComponent(sReportName, xDoc, _nType); closeComponent(xDoc); } } } private String getFormatExtension(int _nType) { String sExtension; switch(_nType) { case WRITER: sExtension = ".odt"; break; case CALC: sExtension = ".ods"; break; default: sExtension = ".UNKNOWN"; } return sExtension; } private String getFileFormat(int _nType) { String sFileType; switch(_nType) { case WRITER: sFileType = "writer8"; break; case CALC: sFileType = "calc8"; break; default: sFileType = "UNKNOWN"; } return sFileType; } private String getOutputPath(int _nType) { String sOutputPath = util.utils.getOfficeTemp/*Dir*/(getMSF());// (String)param.get( convwatch.PropertyName.DOC_COMPARATOR_OUTPUT_PATH ); if (!sOutputPath.endsWith("/") || // construct the output file name !sOutputPath.endsWith("\\")) { sOutputPath += System.getProperty("file.separator"); } sOutputPath += "tmp_123"; sOutputPath += System.getProperty("file.separator"); // sOutputPath += getFileFormat(_nType); // sOutputPath += System.getProperty("file.separator"); File aOutputFile = new File(sOutputPath); // create the directory of the given output path aOutputFile.mkdirs(); return sOutputPath; } /* store given _xComponent under the given Name in DOC_COMPARATOR_INPUTPATH */ private void storeComponent(String _sName, Object _xComponent, int _nType) { String sOutputPath = getOutputPath(_nType); // add DocumentPoolName sOutputPath += getDocumentPoolName(_nType); sOutputPath += System.getProperty("file.separator"); File aOutputFile = new File(sOutputPath); // create the directory of the given output path aOutputFile.mkdirs(); sOutputPath += _sName; sOutputPath += getFormatExtension(_nType); String sOutputURL = URLHelper.getFileURLFromSystemPath(sOutputPath); ArrayList<PropertyValue> aPropertyList = new ArrayList<PropertyValue>(); // set some properties for storeAsURL PropertyValue aFileFormat = new PropertyValue(); aFileFormat.Name = "FilterName"; aFileFormat.Value = getFileFormat(_nType); aPropertyList.add(aFileFormat); PropertyValue aOverwrite = new PropertyValue(); // always overwrite already exist files aOverwrite.Name = "Overwrite"; aOverwrite.Value = Boolean.TRUE; aPropertyList.add(aOverwrite); // store the document in an other directory XStorable aStorable = UnoRuntime.queryInterface(XStorable.class, _xComponent); if (aStorable != null) { System.out.println("store document as URL: '" + sOutputURL + "'"); try { aStorable.storeAsURL(sOutputURL, PropertyHelper.createPropertyValueArrayFormArrayList(aPropertyList)); } catch (com.sun.star.io.IOException e) { System.out.println("ERROR: Exception caught"); System.out.println("Can't write document URL: '" + sOutputURL + "'"); System.out.println("Message: " + e.getMessage()); } } } private XComponent loadComponent(String _sName, Object _xComponent, ArrayList _aPropertyList) { XComponent xDocComponent = null; XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, _xComponent); try { PropertyValue[] aLoadProperties = PropertyHelper.createPropertyValueArrayFormArrayList(_aPropertyList); System.out.println("Load component: '" + _sName + "'"); xDocComponent = xComponentLoader.loadComponentFromURL(_sName, "_blank", 0, aLoadProperties); } catch (com.sun.star.io.IOException e) { System.out.println("ERROR: Exception caught"); System.out.println("Can't load document '" + _sName + "'"); System.out.println("Message: " + e.getMessage()); } catch (com.sun.star.lang.IllegalArgumentException e) { System.out.println("ERROR: Exception caught"); System.out.println("Illegal Arguments given to loadComponentFromURL."); System.out.println("Message: " + e.getMessage()); } return xDocComponent; } private void closeComponent(XComponent _xDoc) { // Close the document XCloseable xCloseable = UnoRuntime.queryInterface(XCloseable.class, _xDoc); try { xCloseable.close(true); } catch (com.sun.star.util.CloseVetoException e) { System.out.println("ERROR: CloseVetoException caught"); System.out.println("CloseVetoException occured Can't close document."); System.out.println("Message: " + e.getMessage()); } } private XMultiServiceFactory getMSF() { final XMultiServiceFactory xMSF1 = UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager()); return xMSF1; } // setup and close connections @BeforeClass public static void setUpConnection() throws Exception { System.out.println("setUpConnection()"); connection.setUp(); } @AfterClass public static void tearDownConnection() throws InterruptedException, com.sun.star.uno.Exception { System.out.println("tearDownConnection()"); connection.tearDown(); } private static final OfficeConnection connection = new OfficeConnection(); }
package uk.bl.api; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URLDecoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.UUID; import play.Logger; import uk.bl.Const; /** * Helper class. */ public class Utils { /** * This method generates random Long ID. * @return new ID as Long value */ public static Long createId() { UUID id = UUID.randomUUID(); Logger.info("id: " + id.toString()); Long res = id.getMostSignificantBits(); if (res < 0) { res = res*(-1); } return res; } /** * This method normalizes boolean values expressed in different string values. * @param value * @return normalized boolean value (true or false) */ public static boolean getNormalizeBooleanString(String value) { boolean res = false; if (value != null && value.length() > 0) { if (value.equals("Yes") || value.equals("yes") || value.equals("True") || value.equals("true") || value.equals("On") || value.equals("on") || value.equals("Y") || value.equals("y")) { res = true; } } return res; } /** * This method converts Boolean value to string * @param value * @return */ public static String getStringFromBoolean(Boolean value) { String res = ""; if (value != null && value.toString().length() > 0) { res = value.toString(); } return res; } /** * This method creates CSV file for passed data. * @param sFileName */ public static void generateCsvFile(String sFileName, String data) { try { FileWriter writer = new FileWriter(sFileName); String decodedData = URLDecoder.decode(data, Const.STR_FORMAT); // Logger.info("generateCsvFile: " + decodedData); writer.append(decodedData); writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } } /** * This method generates current date for e.g. licence form. * @return */ public static String getCurrentDate() { return new SimpleDateFormat("dd-MM-yyyy").format(Calendar.getInstance().getTime()); } /** * Retrieve formatted timestamp * @param timestamp * @return formatted timestamp */ public static String showTimestamp(String timestamp) { String res = ""; if (timestamp.length() > 0) { try { Date resDate = new SimpleDateFormat("yyyyMMddHHMMss").parse(timestamp); if (resDate != null) { Calendar mydate = new GregorianCalendar(); mydate.setTime(resDate); res = Integer.toString(mydate.get(Calendar.DAY_OF_MONTH)) + "/" + Integer.toString(mydate.get(Calendar.MONTH)) + "/" + Integer.toString(mydate.get(Calendar.YEAR)); } } catch (ParseException e) { Logger.info("QA timestamp conversion error: " + e); } } return res; } /** * Convert long timestamp to a date for presentation in a table. * @param long timestamp * @return formatted timestamp "dd/MM/yyyy" */ public static String showTimestampInTable(String timestamp) { String res = ""; if (timestamp.length() > 0) { try { Date resDate = new Date(Long.parseLong(timestamp)*1000L); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // the format of date res = sdf.format(resDate); } catch (Exception e) { Logger.info("Long timestamp conversion error: " + e); } } return res; } /** * This method evaluates if element is in a list separated by list delimiter e.g. ', '. * @param elem The given element for searching * @param list The list that contains elements * @return true if in list */ public static boolean hasElementInList(String elem, String list) { boolean res = false; if (list != null) { if (list.contains(Const.LIST_DELIMITER)) { String[] parts = list.split(Const.LIST_DELIMITER); for (String part: parts) { if (part.equals(elem)) { res = true; break; } } } else { if (list.equals(elem)) { res = true; } } } return res; } /** * This method evaluates if element is in a list separated by list delimiter e.g. ', '. * @param elem The given element for searching * @param list The list that contains elements * @return true if in list */ public static String[] getMailArray(String list) { String[] mailArray = {"None"}; if (list != null) { if (list.contains(Const.LIST_DELIMITER)) { mailArray = list.split(Const.LIST_DELIMITER); } else { mailArray[0] = list; } } return mailArray; } /** * This method converts string array to a string. * @param arr * @return string value */ public static String convertStringArrayToString(String[] arr) { StringBuilder builder = new StringBuilder(); for(String s : arr) { builder.append(s); } return builder.toString(); } /** * This class reads text from a given text file. * @param fileName * @return string value */ public static String readTextFile(String fileName) { String res = ""; try { fileName = "conf" + System.getProperty("file.separator") + "templates" + System.getProperty("file.separator") + "default.txt"; System.out.println("template path: " + fileName); BufferedReader br = new BufferedReader(new FileReader(fileName)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.getProperty("line.separator")); line = br.readLine(); } res = sb.toString(); } finally { br.close(); } } catch (Exception e) { System.out.println("read text file error: " + e); } return res; } }
package org.realityforge.arez.api2; import java.util.ArrayList; import java.util.Comparator; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.TestOnly; public abstract class Observable extends Node { /** * The value that _lastTrackerTransactionId is set to to optimize the detection of duplicate, * existing and new dependencies during tracking completion. */ private static final int IN_CURRENT_TRACKING = -1; /** * The value that _lastTrackerTransactionId is when the observer has been added as new dependency * to derivation. */ private static final int NOT_IN_CURRENT_TRACKING = 0; private final ArrayList<Observer> _observers = new ArrayList<>(); /** * True if passivation has been requested in transaction. * Used to avoid adding duplicates to passivation list. */ private boolean _pendingPassivation; /** * The id of the tracking that last observed the observable. * This enables an optimization that skips adding this observer * to the same tracking multiple times. * * The value may also be set to {@link #IN_CURRENT_TRACKING} during the completion * of tracking operation. */ private int _lastTrackerTransactionId; /** * The state of the observer that is least stale. * This cached value is used to avoid redundant propagations. */ @Nonnull private ObserverState _leastStaleObserverState = ObserverState.NOT_TRACKING; /** * The derivation from which this observable is derived if any. */ @Nullable private final Observer _observer; Observable( @Nonnull final ArezContext context, @Nullable final String name, @Nullable final Observer observer ) { super( context, name ); _observer = observer; } final void resetPendingPassivation() { _pendingPassivation = false; } final void reportObserved() { getContext().getTransaction().observe( this ); } final int getLastTrackerTransactionId() { return _lastTrackerTransactionId; } final void setLastTrackerTransactionId( final int lastTrackerTransactionId ) { _lastTrackerTransactionId = lastTrackerTransactionId; } final boolean isInCurrentTracking() { return IN_CURRENT_TRACKING == _lastTrackerTransactionId; } final void putInCurrentTracking() { _lastTrackerTransactionId = IN_CURRENT_TRACKING; } final void removeFromCurrentTracking() { _lastTrackerTransactionId = NOT_IN_CURRENT_TRACKING; } @Nullable final Observer getObserver() { return _observer; } /** * Return true if this observable can passivate when it is no longer observable and activate when it is observable again. */ final boolean canPassivate() { return null != _observer; } /** * Return true if observable is active and notifying observers. */ private boolean isActive() { //return null == _observer || ObserverState.NOT_TRACKING != _observer.getState(); return true; } /** * Passivate the observable. * This means that the observable no longer has any listeners and can release resources associated * with generating values. (i.e. remove observers on any observables that are used to compute the * value of this observable). */ protected void passivate() { Guards.invariant( this::isActive, () -> String.format( "Invoked passivate on observable named '%s' when observable is not active.", getName() ) ); } /** * Activate the observable. * The reverse of {@link #passivate()}. */ protected void activate() { Guards.invariant( () -> !isActive(), () -> String.format( "Invoked activate on observable named '%s' when observable is already active.", getName() ) ); } @Nonnull final ArrayList<Observer> getObservers() { return _observers; } final boolean hasObservers() { return getObservers().size() > 0; } final void addObserver( @Nonnull final Observer observer ) { Guards.invariant( () -> !getObservers().contains( observer ), () -> String.format( "Attempting to add observer named '%s' to observable named '%s' when observer is already observing observable.", observer.getName(), getName() ) ); if ( !getObservers().add( observer ) ) { Guards.fail( () -> String.format( "Failed to add observer named '%s' to observable named '%s'.", observer.getName(), getName() ) ); } final ObserverState state = observer.getState(); if ( _leastStaleObserverState.ordinal() > state.ordinal() ) { _leastStaleObserverState = state; } } final void removeObserver( @Nonnull final Observer observer ) { Guards.invariant( () -> getContext().isTransactionActive(), () -> String.format( "Attempted to remove observer named '%s' from observable named '%s' when not in transaction.", observer.getName(), getName() ) ); final ArrayList<Observer> observers = getObservers(); if ( !observers.remove( observer ) ) { Guards.fail( () -> String.format( "Attempted to remove observer named '%s' from observable named '%s' when not in batch.", observer.getName(), getName() ) ); } if ( observers.isEmpty() && canPassivate() ) { queueForPassivation(); } } private void queueForPassivation() { if ( !_pendingPassivation ) { _pendingPassivation = true; getContext().getTransaction().queueForPassivation( this ); } } // Called by Atom when its value changes final void propagateChanged() { invariantLeastStaleObserverState(); if ( ObserverState.STALE != _leastStaleObserverState ) { _leastStaleObserverState = ObserverState.STALE; for ( final Observer observer : getObservers() ) { final ObserverState state = observer.getState(); if ( ObserverState.UP_TO_DATE == state ) { observer.setState( ObserverState.STALE ); } } } invariantLeastStaleObserverState(); } // Called by ComputedValue when it recalculate and its value changed final void propagateChangeConfirmed() { invariantLeastStaleObserverState(); if ( ObserverState.STALE != _leastStaleObserverState ) { _leastStaleObserverState = ObserverState.STALE; for ( final Observer observer : getObservers() ) { if ( ObserverState.POSSIBLY_STALE == observer.getState() ) { observer.setState( ObserverState.STALE ); } else if ( ObserverState.UP_TO_DATE == observer.getState() ) { // this happens during computing of `observer`, just keep _leastStaleObserverState up to date. _leastStaleObserverState = ObserverState.UP_TO_DATE; } } } invariantLeastStaleObserverState(); } // Used by computed when its dependency changed, but we don't wan't to immediately recompute. final void propagateMaybeChanged() { invariantLeastStaleObserverState(); if ( ObserverState.UP_TO_DATE == _leastStaleObserverState ) { _leastStaleObserverState = ObserverState.POSSIBLY_STALE; for ( final Observer observer : getObservers() ) { if ( ObserverState.UP_TO_DATE == observer.getState() ) { observer.setState( ObserverState.POSSIBLY_STALE ); } } } invariantLeastStaleObserverState(); } final void invariantLeastStaleObserverState() { final ObserverState leastStaleObserverState = getObservers().stream(). map( Observer::getState ).min( Comparator.comparing( Enum::ordinal ) ).orElse( ObserverState.NOT_TRACKING ); Guards.invariant( () -> leastStaleObserverState.ordinal() >= _leastStaleObserverState.ordinal(), () -> String.format( "Calculated leastStaleObserverState on observable named '%s' is '%s' which is unexpectedly less than cached value '%s'.", getName(), leastStaleObserverState.name(), _leastStaleObserverState.name() ) ); } @TestOnly final boolean isPendingPassivation() { return _pendingPassivation; } @TestOnly final void setLeastStaleObserverState( @Nonnull final ObserverState leastStaleObserverState ) { _leastStaleObserverState = leastStaleObserverState; } @Nonnull @TestOnly final ObserverState getLeastStaleObserverState() { return _leastStaleObserverState; } }
package xal.smf.proxy; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import xal.sim.scenario.Scenario; import xal.sim.scenario.ModelInput; import xal.sim.sync.SynchronizationManager; import xal.smf.AcceleratorNode; import xal.smf.impl.Electromagnet; import xal.smf.impl.PermanentMagnet; import xal.smf.impl.RfCavity; import xal.smf.impl.RfGap; import xal.ca.*; /** * @author Craig McChesney */ public class PrimaryPropertyAccessor { /** indicates the debugging status for diagnostic typeout */ private static final boolean DEBUG = false; // key = accelerator node, value = list of inputs for that node private Map<AcceleratorNode,Map<String,ModelInput>> nodeInputMap = new HashMap<AcceleratorNode,Map<String,ModelInput>>(); /** cache of values (excluding model inputs) for node properties keyed by node and the subsequent map is keyed by property to get the value */ final private Map<AcceleratorNode, Map<String,Double>> PROPERTY_VALUE_CACHE; /** batch accessor for node properties */ private BatchPropertyAccessor _batchAccessor; /** Constructor */ public PrimaryPropertyAccessor() { PROPERTY_VALUE_CACHE = new HashMap<AcceleratorNode, Map<String,Double>>(); _batchAccessor = BatchPropertyAccessor.getInstance( Scenario.SYNC_MODE_DESIGN ); } /** request values for the nodes and the specified sync mode */ public void requestValuesForNodes( final Collection<AcceleratorNode> nodes, final String syncMode ) { final BatchPropertyAccessor batchAccessor = BatchPropertyAccessor.getInstance( syncMode ); batchAccessor.requestValuesForNodes( nodes ); _batchAccessor = batchAccessor; } /** * Returns a Map of property values for the supplied node. The map's keys are the property names as defined by the node class' propertyNames * method, values are the Double value for that property on aNode. * @param objNode the AcclereatorNode whose properties to return * @return a Map of node property values * @throws ProxyException if the node's accessor encounters an error getting a property value */ public Map<String,Double> valueMapFor( final Object objNode ) { if ( (objNode == null) ) { throw new IllegalArgumentException( "null arguments not allowed by doubleValueFor" ); } if (! (objNode instanceof AcceleratorNode)) { throw new IllegalArgumentException( "expected instance of AcceleratorNode" ); } AcceleratorNode aNode = (AcceleratorNode) objNode; PropertyAccessor nodeAccessor = getAccessorFor( aNode ); if (nodeAccessor == null) { throw new IllegalArgumentException( "unknown node type: " + aNode.getClass().getName() ); } final Map<String,Double> valueMap = _batchAccessor.valueMapFor( aNode ); // cache the values PROPERTY_VALUE_CACHE.put( aNode, new HashMap<String,Double>( valueMap ) ); // need to copy it so we don't override the raw values // apply whatif settings addInputOverrides( aNode, valueMap ); if (DEBUG) printValueMap( aNode, valueMap ); return valueMap; } /** Use the cache rather than other sources for the value map and then apply the model inputs */ public Map<String,Double> getWhatifValueMapFromCache( final Object objNode ) { if ( objNode == null ) { throw new IllegalArgumentException( "null arguments not allowed by doubleValueFor" ); } else if ( !(objNode instanceof AcceleratorNode) ) { throw new IllegalArgumentException( "expected instance of AcceleratorNode" ); } final AcceleratorNode aNode = (AcceleratorNode)objNode; final Map<String,Double> valueMap = new HashMap<String,Double>( PROPERTY_VALUE_CACHE.get( aNode ) ); // need to copy it so we don't override the raw values addInputOverrides( aNode, valueMap ); return valueMap; } /** * Returns a List of property names for the supplied node. * @param aNode AcceleratorNode whose property names to return * @return a List of property names for aNode */ public List<String> propertyNamesFor( final AcceleratorNode aNode ) { return _batchAccessor.propertyNamesFor( aNode ); } /** get the accessor for the specified node */ public PropertyAccessor getAccessorFor( final AcceleratorNode node ) { return BatchPropertyAccessor.getAccessorFor( node ); } /** * Returns true if there is an accessor for the specified node type, false otherwise. * @param aNode AcceleratorNode whose type to find an accessor for * @return true if there is an accessor for the supplied node, false otherwise */ public boolean hasAccessorFor(AcceleratorNode aNode) { return _batchAccessor.hasAccessorFor( aNode ); } private void addInputOverrides( final AcceleratorNode aNode, final Map<String,Double> valueMap ) { Map<String,ModelInput> inputs = inputsForNode( aNode ); if (inputs == null) return; for ( final ModelInput input : inputs.values() ) { final String property = input.getProperty(); valueMap.put( property, input.getDoubleValue() ); } } /** * Sets the specified node's property to the specified value. Replaces the * existing value if there is one. * * @param aNode node whose property to set * @param property name of property to set * @param val double value for property */ public ModelInput setModelInput(AcceleratorNode aNode, String property, double val) { ModelInput existingInput = getInput( aNode, property ); if (existingInput != null) { existingInput.setDoubleValue(val); if ( aNode instanceof RfCavity ) applyModelInputToRFGaps( (RfCavity)aNode, property, val ); return existingInput; } else { ModelInput input = new ModelInput( aNode, property, val ); addInput(input); if ( aNode instanceof RfCavity ) applyModelInputToRFGaps( (RfCavity)aNode, property, val ); return input; } } /** * Workaround to address a bug in the way that cavities are handled. Whenever a cavity * input is changed its RF Gaps must be changed accordingly. * @param cavity the cavity whose inputs are being set * @param property the cavity's property being changed * @param value the new value of the cavity's property */ private void applyModelInputToRFGaps( final RfCavity cavity, final String property, final double value ) { if ( property.equals( RfCavityPropertyAccessor.PROPERTY_PHASE ) ) { applyCavityPhaseToRFGaps( cavity, value ); } else if ( property.equals( RfCavityPropertyAccessor.PROPERTY_AMPLITUDE ) ) { applyCavityAmplitudeToRFGaps( cavity, value ); } } /** * Workaround to address a bug in the way that cavities are handled. Whenever a cavity's amplitude * input is changed its RF Gaps must be changed accordingly. * @param cavity the cavity whose inputs are being set * @param cavityAmp the new value of the cavity's amplitude */ private void applyCavityAmplitudeToRFGaps( final RfCavity cavity, final double cavityAmp ) { for ( final RfGap gap : cavity.getGaps() ) { final double gapAmp = gap.toGapAmpFromCavityAmp( cavityAmp ); setModelInput( gap, RfGapPropertyAccessor.PROPERTY_E0, RfGapPropertyAccessor.SCALE_E0 * gapAmp ); setModelInput( gap, RfGapPropertyAccessor.PROPERTY_ETL, RfGapPropertyAccessor.SCALE_ETL * gap.toE0TLFromGapField( gapAmp ) ); } } /** * Workaround to address a bug in the way that cavities are handled. Whenever a cavity's phase * input is changed its RF Gaps must be changed accordingly. * @param cavity the cavity whose inputs are being set * @param cavityPhase the new value of the cavity's phase */ private void applyCavityPhaseToRFGaps( final RfCavity cavity, final double cavityPhase ) { for ( final RfGap gap : cavity.getGaps() ) { setModelInput( gap, RfGapPropertyAccessor.PROPERTY_PHASE, RfGapPropertyAccessor.SCALE_PHASE * gap.toGapPhaseFromCavityPhase( cavityPhase ) ); } } /** * Returns the ModelInput for the specified node's property, or null if there * is none. * * @param aNode node whose property to get a ModelInput for * @param propName name of property to get a ModelInput for */ public ModelInput getInput(AcceleratorNode aNode, String propName) { final Map<String,ModelInput> inputs = inputsForNode(aNode); return inputs != null ? inputs.get( propName ) : null; } protected void addInput( final ModelInput anInput ) { final AcceleratorNode node = anInput.getAcceleratorNode(); Map<String,ModelInput> inputs = inputsForNode(node); if (inputs == null) { inputs = new HashMap<String,ModelInput>(); nodeInputMap.put( node, inputs ); } inputs.put( anInput.getProperty(), anInput ); } public void removeInput(AcceleratorNode aNode, String property) { final Map<String,ModelInput> inputs = inputsForNode(aNode); if ( inputs != null ) { inputs.remove( property ); if ( aNode instanceof RfCavity ) removeRFCavityGapInputs( (RfCavity)aNode, property ); } } /** * Workaround to remove the cavity's associated gap inputs. * @param cavity the cavity for which to remove the input * @param property the property whose input is to be removed */ private void removeRFCavityGapInputs( final RfCavity cavity, final String property ) { if ( property.equals( RfCavityPropertyAccessor.PROPERTY_PHASE ) ) { removeRFCavityGapPhaseInputs( cavity ); } else if ( property.equals( RfCavityPropertyAccessor.PROPERTY_AMPLITUDE ) ) { removeRFCavityGapAmplitudeInputs( cavity ); } } /** * Workaround to remove an RF cavity's gap phase inputs. * @param cavity the cavity for which to remove the gap's inputs */ private void removeRFCavityGapPhaseInputs( final RfCavity cavity ) { for ( final RfGap gap : cavity.getGaps() ) { removeInput( gap, RfGapPropertyAccessor.PROPERTY_PHASE ); } } /** * Workaround to remove an RF cavity's gap amplitude inputs. * @param cavity the cavity for which to remove the gap's inputs */ private void removeRFCavityGapAmplitudeInputs( final RfCavity cavity ) { for ( final RfGap gap : cavity.getGaps() ) { removeInput( gap, RfGapPropertyAccessor.PROPERTY_E0 ); removeInput( gap, RfGapPropertyAccessor.PROPERTY_ETL ); } } private Map<String,ModelInput> inputsForNode( final AcceleratorNode aNode ) { return nodeInputMap.get( aNode ); } private static void printValueMap( final AcceleratorNode aNode, final Map<String,Double> values ) { System.out.println( "Properties for node: " + aNode ); for ( final String property : values.keySet() ) { Double val = values.get( property ); System.out.println("\t" + property + ": " + val); } System.out.println(); } } /** Accessor for property values in batch */ abstract class BatchPropertyAccessor { /** map of property accessors keyed by node */ final private static Map<Class<?>,PropertyAccessor> NODE_ACCESSORS = new HashMap<Class<?>,PropertyAccessor>(); // static initializer static { // Accessor Registration registerAccessorInstance( Electromagnet.class, new ElectromagnetPropertyAccessor() ); registerAccessorInstance( RfGap.class, new RfGapPropertyAccessor() ); registerAccessorInstance( RfCavity.class, new RfCavityPropertyAccessor() ); registerAccessorInstance( PermanentMagnet.class, new PermanentMagnetPropertyAccessor() ); } /** register the property accessor for each supported node class */ private static void registerAccessorInstance( final Class<?> nodeClass, final PropertyAccessor accessor ) { NODE_ACCESSORS.put( nodeClass, accessor ); } /** * Returns a List of property names for the supplied node. * @param aNode AcceleratorNode whose property names to return * @return a List of property names for aNode */ public List<String> propertyNamesFor( final AcceleratorNode aNode ) { if ( aNode == null ) throw new IllegalArgumentException("can't get property names for null node"); final PropertyAccessor nodeAccessor = getAccessorFor( aNode ); if (nodeAccessor == null) throw new IllegalArgumentException( "unregistered node type: " + aNode.getClass().getName() ); return nodeAccessor.propertyNames(); } /** get the accessor for the specified node */ protected static PropertyAccessor getAccessorFor( final AcceleratorNode node ) { for ( final Class<?> nodeClass : NODE_ACCESSORS.keySet() ) { if ( nodeClass.isInstance( node ) ) { return NODE_ACCESSORS.get( nodeClass ); } } return null; } /** * Returns true if there is an accessor for the specified node type, false otherwise. * @param aNode AcceleratorNode whose type to find an accessor for * @return true if there is an accessor for the supplied node, false otherwise */ public boolean hasAccessorFor(AcceleratorNode aNode) { return getAccessorFor( aNode ) != null; } /** make the request for values for the specified nodes */ abstract public void requestValuesForNodes( final Collection<AcceleratorNode> nodes ); /** * Get a Map of property values for the supplied node keyd by property name. * @param node the AcclereatorNode whose properties to return * @return a Map of node property values keyed by property name */ abstract public Map<String,Double> valueMapFor( final AcceleratorNode node ); /** get the instance for the specified synchronization mode */ static BatchPropertyAccessor getInstance( final String syncMode ) { if ( syncMode == null ) { throw new IllegalArgumentException( "Null Synchronization mode" ); } else if ( syncMode.equals( Scenario.SYNC_MODE_LIVE ) ) { return new LiveBatchPropertyAccessor(); } else if ( syncMode.equals( Scenario.SYNC_MODE_DESIGN ) ) { return new DesignBatchPropertyAccessor(); } else if ( syncMode.equals( Scenario.SYNC_MODE_RF_DESIGN ) ) { return new LiveRFDesignBatchPropertyAccessor(); } else { throw new IllegalArgumentException( "Unknown Synchronization mode: " + syncMode ); } } } /** Accessor for property values in batch */ class DesignBatchPropertyAccessor extends BatchPropertyAccessor { /** make the request for values for the specified nodes */ public void requestValuesForNodes( final Collection<AcceleratorNode> nodes ) {} /** * Get a Map of property values for the supplied node keyd by property name. * @param node the AcclereatorNode whose properties to return * @return a Map of node property values */ public Map<String,Double> valueMapFor( final AcceleratorNode node ) { final PropertyAccessor accessor = getAccessorFor( node ); return accessor.getDesignValueMap( node ); } } /** batch property accessor which is based on channels */ abstract class BatchChannelPropertyAccessor extends BatchPropertyAccessor { /** channel value keyed by channel */ protected Map<Channel,Double> _channelValues; /** make the request for values for the specified nodes */ @Override public void requestValuesForNodes( final Collection<AcceleratorNode> nodes ) { // assign an empty map at the start should something go wrong later _channelValues = Collections.<Channel,Double>emptyMap(); // collect all the channels from every node's properties final Set<Channel> channels = new HashSet<>(); for ( final AcceleratorNode node : nodes ) { final PropertyAccessor accessor = getAccessorFor( node ); channels.addAll( getChannels( accessor, node ) ); } // create and submit a batch channel Get request final BatchGetValueRequest request = new BatchGetValueRequest( channels ); request.submitAndWait( 5.0 ); // wait up to 5 seconds for a response // print an overview of the request status if ( !request.isComplete() ) { final int requestCount = channels.size(); final int recordCount = request.getRecordCount(); final int exceptionCount = request.getExceptionCount(); Logger.getLogger(BatchChannelPropertyAccessor.class.getName()).log(Level.WARNING, "Batch channel request for online model is incomplete. {0} of {1} channels succeeded. {2} channels had exceptions.", new Object[]{recordCount, requestCount, exceptionCount}); } // gather values for the channels in a map keyed by channel final Map<Channel,Double> channelValues = new HashMap<>(); final List<String> unreadChannels = new ArrayList<>(); for ( final Channel channel : channels ) { final ChannelRecord record = request.getRecord( channel ); if ( record != null ) { channelValues.put( channel, record.doubleValue() ); } else { unreadChannels.add(channel.getId()); } } if (!unreadChannels.isEmpty()){ Logger.getLogger(BatchChannelPropertyAccessor.class.getName()).log(Level.WARNING, "No record for channels: {0}", unreadChannels); } _channelValues = channelValues; } /** * Get a Map of property values for the supplied node keyd by property name. * @param node the AcclereatorNode whose properties to return * @return a Map of node property values */ @Override public Map<String,Double> valueMapFor( final AcceleratorNode node ) { final PropertyAccessor accessor = getAccessorFor( node ); return getValueMap( accessor, node ); } /** get the channels for the specified node */ protected abstract Collection<Channel> getChannels( final PropertyAccessor accessor, final AcceleratorNode node ); /** get the value map for the specified node */ protected abstract Map<String,Double> getValueMap( final PropertyAccessor accessor, final AcceleratorNode node ); } /** Accessor for property values in batch */ class LiveBatchPropertyAccessor extends BatchChannelPropertyAccessor { /** get the channels for the specified node */ @Override protected Collection<Channel> getChannels( final PropertyAccessor accessor, final AcceleratorNode node ) { return accessor.getLiveChannels( node ); } /** get the value map for the specified node */ @Override protected Map<String,Double> getValueMap( final PropertyAccessor accessor, final AcceleratorNode node ) { return accessor.getLiveValueMap( node, _channelValues ); } } /** Accessor for property values in batch */ class LiveRFDesignBatchPropertyAccessor extends BatchChannelPropertyAccessor { /** get the channels for the specified node */ @Override protected Collection<Channel> getChannels( final PropertyAccessor accessor, final AcceleratorNode node ) { return accessor.getLiveRFDesignChannels( node ); } /** get the value map for the specified node */ @Override protected Map<String,Double> getValueMap( final PropertyAccessor accessor, final AcceleratorNode node ) { return accessor.getLiveRFDesignValueMap( node, _channelValues ); } }
package com.williballenthin.RejistryView; import com.williballenthin.rejistry.RegistryParseException; import com.williballenthin.rejistry.RegistryValue; import javax.swing.*; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import java.awt.*; import java.io.UnsupportedEncodingException; import java.util.Iterator; public class RejTreeKeyView extends RejTreeNodeView { private final RejTreeKeyNode _node; public RejTreeKeyView(RejTreeKeyNode node) { super(new BorderLayout()); this._node = node; /** * @param 1 Name * @param 2 Number of subkeys * @param 3 Number of values */ String metadataTemplate = "" + "<html>" + "<i>Name:</i> <b>%1$s</b><br/>" + "<i>Number of subkeys:</i> %2$d<br/>" + "<i>Number values:</i> %3$d<br/>" + "</html>"; String keyName; int numSubkeys; int numValues; try { keyName = this._node.getKey().getName(); } catch (UnsupportedEncodingException e) { keyName = "FAILED TO PARSE KEY NAME"; } try { numSubkeys = this._node.getKey().getSubkeyList().size(); } catch (RegistryParseException e) { numSubkeys = -1; } try { numValues = this._node.getKey().getValueList().size(); } catch (RegistryParseException e) { numValues = -1; } JLabel metadataLabel = new JLabel(String.format(metadataTemplate, keyName, numSubkeys, numValues), JLabel.LEFT); metadataLabel.setBorder(BorderFactory.createTitledBorder("Metadata")); metadataLabel.setVerticalAlignment(SwingConstants.TOP); String[] columnNames = {"Name", "Type", "Value"}; Object[][] data = new Object[numValues][3]; try { Iterator<RegistryValue> valit = this._node.getKey().getValueList().iterator(); int i = 0; while (valit.hasNext()) { RegistryValue val = valit.next(); if (val.getName().length() == 0) { data[i][0] = "(Default)"; } else { data[i][0] = val.getName(); } data[i][1] = val.getValueType().toString(); data[i][2] = RegeditExeValueFormatter.format(val.getValue()); i++; } } catch (RegistryParseException e) { // TODO(wb): need to add some warning here... // not sure how to do it, though, since some data may have already been added // but not necessarily all of it } catch (UnsupportedEncodingException e) { // TODO(wb): need to add some warning here... } JTable table = new JTable(data, columnNames); table.setAutoCreateRowSorter(true); table.setCellSelectionEnabled(false); table.setRowSelectionAllowed(true); table.setIntercellSpacing(new Dimension(10, 1)); // inspiration for packing the columns from: if (table.getColumnCount() > 0) { int width[] = new int[table.getColumnCount()]; int total = 0; for (int j = 0; j < width.length; j++) { TableColumn column = table.getColumnModel().getColumn(j); int w = (int)table.getTableHeader().getDefaultRenderer().getTableCellRendererComponent(table, column.getIdentifier(), false, false, -1, j).getPreferredSize().getWidth(); if (table.getRowCount() > 0) { for (int i = 0; i < table.getRowCount(); i++) { int pw = (int)table.getCellRenderer(i, j).getTableCellRendererComponent(table, table.getValueAt(i, j), false, false, i, j).getPreferredSize().getWidth(); w = Math.max(w, pw); } } width[j] += w + table.getIntercellSpacing().width; total += w + table.getIntercellSpacing().width; } width[width.length - 1] += table.getVisibleRect().width - total; TableColumnModel columnModel = table.getColumnModel(); for (int j = 0; j < width.length; j++) { TableColumn column = columnModel.getColumn(j); table.getTableHeader().setResizingColumn(column); column.setWidth(width[j]); } } JScrollPane valuesPane = new JScrollPane(table); valuesPane.setBorder(BorderFactory.createTitledBorder("Values")); this.add(metadataLabel, BorderLayout.NORTH); this.add(valuesPane, BorderLayout.CENTER); } }
package club.zhcs.titans.gather; import java.util.List; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.nutz.lang.util.NutMap; /** * @author Kerbores(kerbores@gmail.com) * * @project gather * * @file Gathers.java * * @description * * @time 2016315 8:36:58 * */ public class Gathers { public static NutMap all() throws SigarException { Sigar sigar = new Sigar(); NutMap data = NutMap.NEW(); CPUGather cpu = CPUGather.gather(sigar); data.put("cpu", cpu); data.put("cpuUsage", cpu.getPerc().getCombined() * 100); MemoryGather memory = MemoryGather.gather(sigar); data.put("memory", memory); data.put("ramUasge", memory.getMem().getUsedPercent()); data.put("jvmUasge", memory.getJvm().getUsedPercent()); if (memory.getSwap().getTotal() == 0) { data.put("swapUasge", 0); } else { data.put("swapUasge", memory.getSwap().getUsed() * 100 / memory.getSwap().getTotal()); } List<DISKGather> disks = DISKGather.gather(sigar); data.put("disk", disks); long totle = 0, used = 0; for (DISKGather disk : disks) { if (disk.getStat() != null) { totle += disk.getStat().getTotal(); used += disk.getStat().getUsed(); } } data.put("diskUsage", used * 100 / totle); NetInterfaceGather ni = NetInterfaceGather.gather(sigar); data.put("network", ni); data.put("niUsage", ni.getRxbps() * 100 / ni.getStat().getSpeed()); data.put("noUsage", ni.getTxbps() * 100 / ni.getStat().getSpeed()); data.put("system", OSGather.init(sigar)); return data; } }
package org.bouncycastle.tls.test; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class AllTests extends TestCase { public static void main(String[] args) throws Exception { junit.textui.TestRunner.run(suite()); } public static Test suite() throws Exception { TestSuite suite = new TestSuite("TLS tests"); suite.addTestSuite(BasicTlsTest.class); suite.addTestSuite(DTLSProtocolTest.class); suite.addTest(DTLSTestSuite.suite()); suite.addTestSuite(PRFTest.class); suite.addTestSuite(TlsProtocolTest.class); suite.addTestSuite(TlsProtocolNonBlockingTest.class); suite.addTestSuite(TlsPSKProtocolTest.class); suite.addTestSuite(TlsSRPProtocolTest.class); suite.addTest(TlsTestSuite.suite()); suite.addTestSuite(TlsUtilsTest.class); return new BCTestSetup(suite); } static class BCTestSetup extends TestSetup { public BCTestSetup(Test test) { super(test); } protected void setUp() { } protected void tearDown() { } } }
package org.egordorichev.lasttry.entity.ai.ais; import org.egordorichev.lasttry.Globals; import org.egordorichev.lasttry.entity.CreatureWithAI; import org.egordorichev.lasttry.entity.ai.AI; import org.egordorichev.lasttry.entity.ai.AIID; import org.egordorichev.lasttry.entity.components.PhysicsComponent; public class ZombieAI extends AI { public ZombieAI() { super(AIID.zombie); } @Override public void init(CreatureWithAI creature) { creature.ai.setMax(3600); } @Override public void update(CreatureWithAI creature, int dt, int currentAi) { creature.physics.move((Float.compare(Globals.player.physics.getCenterX(), creature.physics.getCenterX()) == -1) ? PhysicsComponent.Direction.LEFT : PhysicsComponent.Direction.RIGHT); } @Override public boolean canSpawn() { return true; } }
package com.orbekk.same.config; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Enumeration; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Configuration { public final static String configurationProperty = "com.orbekk.same.config.file"; static final Logger logger = LoggerFactory.getLogger(Configuration.class); Properties configuration = new Properties(); public Configuration(Properties properties) { this.configuration = properties; } Configuration() { // Use factory methods. } public static Configuration loadOrDie() { Configuration configuration = new Configuration(); boolean status = configuration.loadDefault(); if (!status) { logger.error("Could not load configurotion."); System.exit(1); } return configuration; } public static Configuration load() { Configuration configuration = new Configuration(); configuration.loadDefault(); return configuration; } public boolean loadDefault() { String filename = System.getProperty(configurationProperty); if (filename != null) { try { configuration.load(new FileReader(filename)); return true; } catch (FileNotFoundException e) { logger.error("Failed to load configuration. {}", e); logger.error("Failed to load configuration. {}={}", configurationProperty, filename); } catch (IOException e) { logger.error("Failed to load configuration. {}", e); logger.error("Failed to load configuration. {}={}", configurationProperty, filename); } } else { logger.error("Failed to load configuration. {}={}", configurationProperty, filename); } return false; } public String get(String name) { String value = configuration.getProperty(name); if (value == null) { logger.error("Property {} = null", name); } return value; } public int getInt(String name) { return Integer.valueOf(get(name)); } }
package brooklyn.event.feed.http; import static brooklyn.test.TestUtils.executeUntilSucceeds; import static org.testng.Assert.assertEquals; import java.net.URL; import java.util.concurrent.Callable; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import brooklyn.entity.basic.ApplicationBuilder; import brooklyn.entity.basic.Entities; import brooklyn.entity.basic.EntityLocal; import brooklyn.entity.proxying.BasicEntitySpec; import brooklyn.event.AttributeSensor; import brooklyn.event.basic.BasicAttributeSensor; import brooklyn.location.Location; import brooklyn.location.basic.LocalhostMachineProvisioningLocation; import brooklyn.test.entity.TestApplication; import brooklyn.test.entity.TestEntity; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; public class HttpFeedTest { final static BasicAttributeSensor<String> SENSOR_STRING = new BasicAttributeSensor<String>(String.class, "aString", ""); final static BasicAttributeSensor<Integer> SENSOR_INT = new BasicAttributeSensor<Integer>(Integer.class, "aLong", ""); private static final long TIMEOUT_MS = 10*1000; private MockWebServer server; private URL baseUrl; private Location loc; private TestApplication app; private EntityLocal entity; private HttpFeed feed; @BeforeMethod(alwaysRun=true) public void setUp() throws Exception { server = new MockWebServer(); for (int i = 0; i < 100; i++) { server.enqueue(new MockResponse().setResponseCode(200).addHeader("content-type: application/json").setBody("{\"foo\":\"myfoo\"}")); } server.play(); baseUrl = server.getUrl("/"); loc = new LocalhostMachineProvisioningLocation(); app = ApplicationBuilder.builder(TestApplication.class).manage(); entity = app.createAndManageChild(BasicEntitySpec.newInstance(TestEntity.class)); app.start(ImmutableList.of(loc)); } @AfterMethod(alwaysRun=true) public void tearDown() throws Exception { if (feed != null) feed.stop(); if (server != null) server.shutdown(); if (app != null) Entities.destroyAll(app); feed = null; } @Test public void testPollsAndParsesHttpGetResponse() throws Exception { feed = HttpFeed.builder() .entity(entity) .baseUrl(baseUrl) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode())) .poll(new HttpPollConfig<String>(SENSOR_STRING) .period(100) .onSuccess(HttpValueFunctions.stringContentsFunction())) .build(); assertSensorEventually(SENSOR_INT, (Integer)200, TIMEOUT_MS); assertSensorEventually(SENSOR_STRING, "{\"foo\":\"myfoo\"}", TIMEOUT_MS); } @Test public void testPollsAndParsesHttpPostResponse() throws Exception { feed = HttpFeed.builder() .entity(entity) .baseUrl(baseUrl) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .method("post") .period(100) .onSuccess(HttpValueFunctions.responseCode())) .poll(new HttpPollConfig<String>(SENSOR_STRING) .method("post") .period(100) .onSuccess(HttpValueFunctions.stringContentsFunction())) .build(); assertSensorEventually(SENSOR_INT, (Integer)200, TIMEOUT_MS); assertSensorEventually(SENSOR_STRING, "{\"foo\":\"myfoo\"}", TIMEOUT_MS); } @Test(groups="Integration") // marked as integration so it doesn't fail the plain build in environments // with dodgy DNS (ie where "thisdoesnotexistdefinitely" resolves as a host // which happily serves you adverts for your ISP, yielding "success" here) public void testPollsAndParsesHttpErrorResponseWild() throws Exception { feed = HttpFeed.builder() .entity(entity) .baseUri("http://thisdoesnotexistdefinitely") .poll(new HttpPollConfig<String>(SENSOR_STRING) .onSuccess(Functions.constant("success")) .onError(Functions.constant("error"))) .build(); assertSensorEventually(SENSOR_STRING, "error", TIMEOUT_MS); } @Test public void testPollsAndParsesHttpErrorResponseLocal() throws Exception { feed = HttpFeed.builder() .entity(entity) // combo of port 46069 and unknown path will hopefully give an error // (without the port, in jenkins it returns some bogus success page) .baseUri("http://localhost:46069/path/should/not/exist") .poll(new HttpPollConfig<String>(SENSOR_STRING) .onSuccess(Functions.constant("success")) .onError(Functions.constant("error"))) .build(); assertSensorEventually(SENSOR_STRING, "error", TIMEOUT_MS); } private <T> void assertSensorEventually(final AttributeSensor<T> sensor, final T expectedVal, long timeout) { executeUntilSucceeds(ImmutableMap.of("timeout", timeout), new Callable<Void>() { public Void call() { assertEquals(entity.getAttribute(sensor), expectedVal); return null; }}); } }
package yunfeiImplementAlgs4; import edu.princeton.cs.algs4.BinaryIn; import edu.princeton.cs.algs4.BinaryOut; import edu.princeton.cs.algs4.TST; import java.util.HashMap; import java.util.Map; public class LZW { private static final int R = 4096; //# of elements in dictionary private static final int W = 12; //width of compressed code private static TST<Integer> initializeTST(int n) { TST<Integer> st = new TST<>(); for (int i = 0; i < n; i++) { st.put("" + (char) i, i); } return st; } public static void compress(BinaryIn in, BinaryOut out) { int count = 256; TST<Integer> st = initializeTST(count); String currentString = ""; while(!in.isEmpty()) { currentString += in.readChar(); if(st.contains(currentString)) { continue; } else { String prefix = st.longestPrefixOf(currentString); out.write(st.get(prefix), W); if(count < R - 1) st.put(currentString, count++); currentString = currentString.substring(prefix.length()); } } out.write(st.get(currentString), W); out.write(R-1, W); //mark end } public static void expand(BinaryIn in, BinaryOut out) { int count = 256; TST<Integer> st = initializeTST(count); String[] int2String = new String[R]; for (int i = 0; i < count; i++) { int2String[i] = "" + (char) i; } String currentString = ""; while(!in.isEmpty()) { int i = in.readInt(W); if (i == R - 1) break; if(int2String[i] == null) { //we see an unseen codeword, it must be the next //codeword that we'd like to add to the trie //therefore, the string must have same prefix as currentString //and the next string is just currentString+its 1st char int2String[count] = currentString + currentString.substring(0,1); } out.write(int2String[i]); if (count < R - 1) { for (int j = 0; j < int2String[i].length(); j++) { currentString += int2String[i].charAt(j); if (count < R - 1 && !st.contains(currentString)) { String prefix = st.longestPrefixOf(currentString); st.put(currentString, count); int2String[count] = currentString; currentString = currentString.substring(prefix.length()); count++; } } } } } public static void main(String[] args) { BinaryIn in = new BinaryIn(args[1]); BinaryOut out = new BinaryOut(args[2]); if (args[0].equals("-")) { compress(in, out); } else if (args[0].equals("+")) { expand(in, out); } else throw new IllegalArgumentException("Illegal command line argument"); out.close(); } }
package com.turn.ttorrent.client; import com.turn.ttorrent.ClientFactory; import com.turn.ttorrent.TempFiles; import com.turn.ttorrent.Utils; import com.turn.ttorrent.WaitFor; import com.turn.ttorrent.client.peer.SharingPeer; import com.turn.ttorrent.common.*; import com.turn.ttorrent.common.protocol.PeerMessage; import com.turn.ttorrent.tracker.TrackedPeer; import com.turn.ttorrent.tracker.TrackedTorrent; import com.turn.ttorrent.tracker.Tracker; import org.apache.commons.io.FileUtils; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.*; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.CRC32; import java.util.zip.Checksum; import static com.turn.ttorrent.ClientFactory.DEFAULT_POOL_SIZE; import static org.testng.Assert.*; @Test(timeOut = 600000) public class ClientTest { private ClientFactory clientFactory; private List<Client> clientList; private static final String TEST_RESOURCES = "src/test/resources"; private Tracker tracker; private TempFiles tempFiles; public ClientTest() { clientFactory = new ClientFactory(); if (Logger.getRootLogger().getAllAppenders().hasMoreElements()) return; BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("[%d{MMdd HH:mm:ss,SSS} %t] %6p - %20.20c - %m %n"))); TorrentCreator.setHashingThreadsCount(1); } @BeforeMethod public void setUp() throws IOException { tempFiles = new TempFiles(); clientList = new ArrayList<Client>(); Logger.getRootLogger().setLevel(Utils.getLogLevel()); startTracker(); } private void saveTorrent(Torrent torrent, File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); fos.write(new TorrentSerializer().serialize(torrent)); fos.close(); } public void testThatSeederIsNotReceivedHaveMessages() throws Exception { final ExecutorService workerES = Executors.newFixedThreadPool(10); final ExecutorService validatorES = Executors.newFixedThreadPool(4); final AtomicBoolean isSeederReceivedHaveMessage = new AtomicBoolean(false); Client seeder = new Client(workerES, validatorES) { @Override public SharingPeer createSharingPeer(String host, int port, ByteBuffer peerId, SharedTorrent torrent, ByteChannel channel) { return new SharingPeer(host, port, peerId, torrent, getConnectionManager(), this, channel) { @Override public synchronized void handleMessage(PeerMessage msg) { if (msg instanceof PeerMessage.HaveMessage) { isSeederReceivedHaveMessage.set(true); } super.handleMessage(msg); } }; } @Override public void stop() { super.stop(); workerES.shutdown(); validatorES.shutdown(); } }; clientList.add(seeder); File tempFile = tempFiles.createTempFile(100 * 1025 * 1024); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); Torrent torrent = TorrentCreator.create(tempFile, announceURI, "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); seeder.seedTorrent(torrentFile.getAbsolutePath(), tempFile.getParent()); seeder.start(InetAddress.getLocalHost()); waitForSeederIsAnnounsedOnTracker(torrent.getHexInfoHash()); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 10); assertFalse(isSeederReceivedHaveMessage.get()); } private void waitForSeederIsAnnounsedOnTracker(final String hexInfoHash) { final WaitFor waitFor = new WaitFor(10 * 1000) { @Override protected boolean condition() { return tracker.getTrackedTorrent(hexInfoHash) != null; } }; assertTrue(waitFor.isMyResult()); } // @Test(invocationCount = 50) public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir = tempFiles.createTempDir(); Client seeder = createClient("seeder"); seeder.start(InetAddress.getLocalHost()); Client leech = null; try { URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); final Set<String> names = new HashSet<String>(); List<File> filesToShare = new ArrayList<File>(); for (int i = 0; i < numFiles; i++) { File tempFile = tempFiles.createTempFile(513 * 1024); File srcFile = new File(srcDir, tempFile.getName()); assertTrue(tempFile.renameTo(srcFile)); Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test"); File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); filesToShare.add(srcFile); names.add(srcFile.getName()); } for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent()); } leech = createClient("leecher"); leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null); for (File f : filesToShare) { File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent"); leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); } new WaitFor(60 * 1000) { @Override protected boolean condition() { final Set<String> strings = listFileNames(downloadDir); int count = 0; final List<String> partItems = new ArrayList<String>(); for (String s : strings) { if (s.endsWith(".part")) { count++; partItems.add(s); } } if (count < 5) { System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray())); } return strings.containsAll(names); } }; assertEquals(listFileNames(downloadDir), names); } finally { leech.stop(); seeder.stop(); } } private Set<String> listFileNames(File downloadDir) { if (downloadDir == null) return Collections.emptySet(); Set<String> names = new HashSet<String>(); File[] files = downloadDir.listFiles(); if (files == null) return Collections.emptySet(); for (File f : files) { names.add(f.getName()); } return names; } // @Test(invocationCount = 50) public void large_file_download() throws IOException, URISyntaxException, NoSuchAlgorithmException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); File tempFile = tempFiles.createTempFile(201 * 1025 * 1024); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); Torrent torrent = TorrentCreator.create(tempFile, announceURI, "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); Client seeder = createClient(); seeder.addTorrent(torrentFile.getAbsolutePath(), tempFile.getParent()); final File downloadDir = tempFiles.createTempDir(); Client leech = createClient(); leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); try { seeder.start(InetAddress.getLocalHost()); leech.start(InetAddress.getLocalHost()); waitForFileInDir(downloadDir, tempFile.getName()); assertFilesEqual(tempFile, new File(downloadDir, tempFile.getName())); } finally { seeder.stop(); leech.stop(); } } @Test(enabled = false) public void endgameModeTest() throws Exception { this.tracker.setAcceptForeignTorrents(true); final int numSeeders = 2; List<Client> seeders = new ArrayList<Client>(); final AtomicInteger skipPiecesCount = new AtomicInteger(1); for (int i = 0; i < numSeeders; i++) { final ExecutorService es = Executors.newFixedThreadPool(10); final ExecutorService validatorES = Executors.newFixedThreadPool(4); final Client seeder = new Client(es, validatorES) { @Override public void stop() { super.stop(); es.shutdownNow(); validatorES.shutdownNow(); } @Override public SharingPeer createSharingPeer(String host, int port, ByteBuffer peerId, SharedTorrent torrent, ByteChannel channel) { return new SharingPeer(host, port, peerId, torrent, getConnectionManager(), this, channel) { @Override public void send(PeerMessage message) throws IllegalStateException { if (message instanceof PeerMessage.PieceMessage) { if (skipPiecesCount.getAndDecrement() > 0) { return; } } super.send(message); } }; } }; seeders.add(seeder); clientList.add(seeder); } File tempFile = tempFiles.createTempFile(1024 * 20 * 1024); Torrent torrent = TorrentCreator.create(tempFile, this.tracker.getAnnounceURI(), "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); for (int i = 0; i < numSeeders; i++) { Client client = seeders.get(i); client.addTorrent(torrentFile.getAbsolutePath(), tempFile.getParent(), true, false); client.start(InetAddress.getLocalHost()); } final File downloadDir = tempFiles.createTempDir(); Client leech = createClient(); leech.start(InetAddress.getLocalHost()); leech.downloadUninterruptibly( torrentFile.getAbsolutePath(), downloadDir.getParent(), 20); waitForFileInDir(downloadDir, tempFile.getName()); } public void more_than_one_seeder_for_same_torrent() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { this.tracker.setAcceptForeignTorrents(true); assertEquals(0, this.tracker.getTrackedTorrents().size()); final int numSeeders = 5; List<Client> seeders = new ArrayList<Client>(); for (int i = 0; i < numSeeders; i++) { seeders.add(createClient()); } try { File tempFile = tempFiles.createTempFile(100 * 1024); Torrent torrent = TorrentCreator.create(tempFile, this.tracker.getAnnounceURI(), "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); for (int i = 0; i < numSeeders; i++) { Client client = seeders.get(i); client.addTorrent(torrentFile.getAbsolutePath(), tempFile.getParent(), true, false); client.start(InetAddress.getLocalHost()); } new WaitFor() { @Override protected boolean condition() { for (TrackedTorrent tt : tracker.getTrackedTorrents()) { if (tt.getPeers().size() == numSeeders) return true; } return false; } }; Collection<TrackedTorrent> torrents = this.tracker.getTrackedTorrents(); assertEquals(torrents.size(), 1); assertEquals(numSeeders, torrents.iterator().next().seeders()); } finally { for (Client client : seeders) { client.stop(); } } } public void testThatDownloadStatisticProvidedToTracker() throws Exception { final ExecutorService executorService = Executors.newFixedThreadPool(8); final ExecutorService validatorES = Executors.newFixedThreadPool(4); final AtomicInteger countOfTrackerResponses = new AtomicInteger(0); Client leecher = new Client(executorService, validatorES) { @Override public void handleDiscoveredPeers(List<Peer> peers, String hexInfoHash) { super.handleDiscoveredPeers(peers, hexInfoHash); countOfTrackerResponses.incrementAndGet(); } @Override public void stop() { super.stop(); executorService.shutdownNow(); validatorES.shutdownNow(); } }; clientList.add(leecher); final int fileSize = 2 * 1025 * 1024; File tempFile = tempFiles.createTempFile(fileSize); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); Torrent torrent = TorrentCreator.create(tempFile, announceURI, "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); leecher.addTorrent(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), false, false); leecher.start(InetAddress.getLocalHost()); final AnnounceableFileTorrent announceableTorrent = (AnnounceableFileTorrent) leecher.getTorrentsStorage().announceableTorrents().iterator().next(); final SharedTorrent sharedTorrent = leecher.getTorrentsStorage().putIfAbsentActiveTorrent(announceableTorrent.getHexInfoHash(), leecher.getTorrentLoader().loadTorrent(announceableTorrent)); sharedTorrent.init(); new WaitFor(10 * 1000) { @Override protected boolean condition() { return countOfTrackerResponses.get() == 1; } }; final TrackedTorrent trackedTorrent = tracker.getTrackedTorrent(announceableTorrent.getHexInfoHash()); assertEquals(trackedTorrent.getPeers().size(), 1); final TrackedPeer trackedPeer = trackedTorrent.getPeers().values().iterator().next(); assertEquals(trackedPeer.getUploaded(), 0); assertEquals(trackedPeer.getDownloaded(), 0); assertEquals(trackedPeer.getLeft(), fileSize); Piece piece = sharedTorrent.getPiece(1); sharedTorrent.handlePieceCompleted(null, piece); sharedTorrent.markCompleted(piece); new WaitFor(10 * 1000) { @Override protected boolean condition() { return countOfTrackerResponses.get() >= 2; } }; int downloaded = 512 * 1024;//one piece assertEquals(trackedPeer.getUploaded(), 0); assertEquals(trackedPeer.getDownloaded(), downloaded); assertEquals(trackedPeer.getLeft(), fileSize - downloaded); } public void no_full_seeder_test() throws IOException, URISyntaxException, InterruptedException, NoSuchAlgorithmException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders * 3 + 15; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File tempFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(tempFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(tempFile, md5); validateMultipleClientsResults(clientsList, md5, tempFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } @Test(enabled = false) public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int numSeeders = 6; final int piecesCount = numSeeders + 7; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList); String baseMD5 = getFileMD5(baseFile, md5); final Client firstClient = clientsList.get(0); new WaitFor(10 * 1000) { @Override protected boolean condition() { return firstClient.getTorrentsStorage().activeTorrents().size() >= 1; } }; final SharedTorrent torrent = firstClient.getTorrents().iterator().next(); final File file = new File(torrent.getParentFile(), TorrentUtils.getTorrentFileNames(torrent).get(0)); final int oldByte; { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(0); oldByte = raf.read(); raf.seek(0); // replacing the byte if (oldByte != 35) { raf.write(35); } else { raf.write(45); } raf.close(); } final WaitFor waitFor = new WaitFor(60 * 1000) { @Override protected boolean condition() { for (Client client : clientsList) { final SharedTorrent next = client.getTorrents().iterator().next(); if (next.getCompletedPieces().cardinality() < next.getPieceCount() - 1) { return false; } } return true; } }; if (!waitFor.isMyResult()) { fail("All seeders didn't get their files"); } Thread.sleep(10 * 1000); { byte[] piece = new byte[pieceSize]; FileInputStream fin = new FileInputStream(baseFile); fin.read(piece); fin.close(); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); raf.seek(0); raf.write(oldByte); raf.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5); } finally { for (Client client : clientsList) { client.stop(); } } } public void testThatTorrentsHaveLazyInitAndRemovingAfterDownload() throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { final Client seeder = createClient(); File tempFile = tempFiles.createTempFile(100 * 1025 * 1024); URL announce = new URL("http://127.0.0.1:6969/announce"); URI announceURI = announce.toURI(); Torrent torrent = TorrentCreator.create(tempFile, announceURI, "Test"); File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); seeder.addTorrent(torrentFile.getAbsolutePath(), tempFile.getParentFile().getAbsolutePath(), true, false); final Client leecher = createClient(); File downloadDir = tempFiles.createTempDir(); leecher.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); seeder.start(InetAddress.getLocalHost()); assertEquals(1, seeder.getTorrentsStorage().announceableTorrents().size()); assertEquals(0, seeder.getTorrentsStorage().activeTorrents().size()); assertEquals(0, leecher.getTorrentsStorage().activeTorrents().size()); leecher.start(InetAddress.getLocalHost()); WaitFor waitFor = new WaitFor(10 * 1000) { @Override protected boolean condition() { return seeder.getTorrentsStorage().activeTorrents().size() == 1 && leecher.getTorrentsStorage().activeTorrents().size() == 1; } }; assertTrue(waitFor.isMyResult(), "Torrent was not successfully initialized"); assertEquals(1, seeder.getTorrentsStorage().activeTorrents().size()); assertEquals(1, leecher.getTorrentsStorage().activeTorrents().size()); waitForFileInDir(downloadDir, tempFile.getName()); assertFilesEqual(tempFile, new File(downloadDir, tempFile.getName())); waitFor = new WaitFor(10 * 1000) { @Override protected boolean condition() { return seeder.getTorrentsStorage().activeTorrents().size() == 0 && leecher.getTorrentsStorage().activeTorrents().size() == 0; } }; assertTrue(waitFor.isMyResult(), "Torrent was not successfully removed"); assertEquals(0, seeder.getTorrentsStorage().activeTorrents().size()); assertEquals(0, leecher.getTorrentsStorage().activeTorrents().size()); } public void corrupted_seeder() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException { this.tracker.setAcceptForeignTorrents(true); final int pieceSize = 48 * 1024; // lower piece size to reduce disk usage final int piecesCount = 35; final List<Client> clientsList; clientsList = new ArrayList<Client>(piecesCount); final MessageDigest md5 = MessageDigest.getInstance("MD5"); try { final File baseFile = tempFiles.createTempFile(piecesCount * pieceSize); final File badFile = tempFiles.createTempFile(piecesCount * pieceSize); final Client client2 = createAndStartClient(); final File client2Dir = tempFiles.createTempDir(); final File client2File = new File(client2Dir, baseFile.getName()); FileUtils.copyFile(badFile, client2File); final Torrent torrent = TorrentCreator.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); client2.addTorrent(torrentFile.getAbsolutePath(), client2Dir.getAbsolutePath()); final String baseMD5 = getFileMD5(baseFile, md5); final Client leech = createAndStartClient(); final File leechDestDir = tempFiles.createTempDir(); final AtomicReference<Exception> thrownException = new AtomicReference<Exception>(); final Thread th = new Thread(new Runnable() { @Override public void run() { try { leech.downloadUninterruptibly(torrentFile.getAbsolutePath(), leechDestDir.getAbsolutePath(), 7); } catch (Exception e) { thrownException.set(e); throw new RuntimeException(e); } } }); th.start(); final WaitFor waitFor = new WaitFor(30 * 1000) { @Override protected boolean condition() { return th.getState() == Thread.State.TERMINATED; } }; final Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) { System.out.printf("%s:%n", entry.getKey().getName()); for (StackTraceElement elem : entry.getValue()) { System.out.println(elem.toString()); } } assertTrue(waitFor.isMyResult()); assertNotNull(thrownException.get()); assertTrue(thrownException.get().getMessage().contains("Unable to download torrent completely")); } finally { for (Client client : clientsList) { client.stop(); } } } public void unlock_file_when_no_leechers() throws InterruptedException, NoSuchAlgorithmException, IOException { Client seeder = createClient(); tracker.setAcceptForeignTorrents(true); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent()); seeder.start(InetAddress.getLocalHost()); downloadAndStop(torrent, 15 * 1000, createClient()); Thread.sleep(2 * 1000); assertTrue(dwnlFile.exists() && dwnlFile.isFile()); final boolean delete = dwnlFile.delete(); assertTrue(delete && !dwnlFile.exists()); } public void download_many_times() throws InterruptedException, NoSuchAlgorithmException, IOException { Client seeder = createClient(); tracker.setAcceptForeignTorrents(true); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent()); seeder.start(InetAddress.getLocalHost()); for (int i = 0; i < 5; i++) { downloadAndStop(torrent, 250 * 1000, createClient()); Thread.sleep(3 * 1000); } } public void testConnectToAllDiscoveredPeers() throws Exception { tracker.setAcceptForeignTorrents(true); final ExecutorService executorService = Executors.newFixedThreadPool(8); final ExecutorService validatorES = Executors.newFixedThreadPool(4); Client leecher = new Client(executorService, validatorES) { @Override public void stop() { super.stop(); executorService.shutdownNow(); validatorES.shutdownNow(); } }; leecher.setMaxInConnectionsCount(10); leecher.setMaxOutConnectionsCount(10); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 34); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); final String hexInfoHash = leecher.addTorrent(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath()); final List<ServerSocket> serverSockets = new ArrayList<ServerSocket>(); final int startPort = 6885; int port = startPort; PeerUID[] peerUids = new PeerUID[]{ new PeerUID(new InetSocketAddress("127.0.0.1", port++), hexInfoHash), new PeerUID(new InetSocketAddress("127.0.0.1", port++), hexInfoHash), new PeerUID(new InetSocketAddress("127.0.0.1", port), hexInfoHash) }; final ExecutorService es = Executors.newSingleThreadExecutor(); try { leecher.start(InetAddress.getLocalHost()); WaitFor waitFor = new WaitFor(5000) { @Override protected boolean condition() { return tracker.getTrackedTorrent(hexInfoHash) != null; } }; assertTrue(waitFor.isMyResult()); final TrackedTorrent trackedTorrent = tracker.getTrackedTorrent(hexInfoHash); Map<PeerUID, TrackedPeer> trackedPeerMap = new HashMap<PeerUID, TrackedPeer>(); port = startPort; for (PeerUID uid : peerUids) { trackedPeerMap.put(uid, new TrackedPeer(trackedTorrent, "127.0.0.1", port, ByteBuffer.wrap("id".getBytes(Torrent.BYTE_ENCODING)))); serverSockets.add(new ServerSocket(port)); port++; } trackedTorrent.getPeers().putAll(trackedPeerMap); //wait until all server sockets accept connection from leecher for (final ServerSocket ss : serverSockets) { final Future<?> future = es.submit(new Runnable() { @Override public void run() { try { final Socket socket = ss.accept(); socket.close(); } catch (IOException e) { throw new RuntimeException("can not accept connection"); } } }); try { future.get(10, TimeUnit.SECONDS); } catch (ExecutionException e) { fail("get execution exception on accept connection", e); } catch (TimeoutException e) { fail("not received connection from leecher in specified timeout", e); } } } finally { for (ServerSocket ss : serverSockets) { try { ss.close(); } catch (IOException e) { fail("can not close server socket", e); } } es.shutdown(); leecher.stop(); } } public void download_io_error() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 34); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent()); seeder.start(InetAddress.getLocalHost()); final AtomicInteger interrupts = new AtomicInteger(0); final ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE); final ExecutorService validatorES = Executors.newFixedThreadPool(4); final Client leech = new Client(es, validatorES) { @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { super.handlePieceCompleted(peer, piece); if (piece.getIndex() % 4 == 0 && interrupts.incrementAndGet() <= 2) { peer.unbind(true); } } @Override public void stop(int timeout, TimeUnit timeUnit) { super.stop(timeout, timeUnit); es.shutdown(); validatorES.shutdown(); } }; //manually add leech here for graceful shutdown. clientList.add(leech); downloadAndStop(torrent, 45 * 1000, leech); Thread.sleep(2 * 1000); } public void download_uninterruptibly_positive() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent(), true, false); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 10); } public void download_uninterruptibly_negative() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); final AtomicInteger downloadedPiecesCount = new AtomicInteger(0); final Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent(), true, false); final ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE); final ExecutorService validatorES = Executors.newFixedThreadPool(4); final Client leecher = new Client(es, validatorES) { @Override public void stop(int timeout, TimeUnit timeUnit) { super.stop(timeout, timeUnit); es.shutdown(); validatorES.shutdown(); } @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { super.handlePieceCompleted(peer, piece); if (downloadedPiecesCount.incrementAndGet() > 10) { seeder.stop(); } } }; clientList.add(leecher); leecher.start(InetAddress.getLocalHost()); final File destDir = tempFiles.createTempDir(); try { leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), destDir.getAbsolutePath(), 5); fail("Must fail, because file wasn't downloaded completely"); } catch (IOException ex) { // ensure .part was deleted: assertEquals(0, destDir.list().length); } } public void download_uninterruptibly_timeout() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent()); final AtomicInteger piecesDownloaded = new AtomicInteger(0); final ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE); final ExecutorService validatorES = Executors.newFixedThreadPool(4); Client leecher = new Client(es, validatorES) { @Override public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException { piecesDownloaded.incrementAndGet(); try { Thread.sleep(piecesDownloaded.get() * 500); } catch (InterruptedException e) { } } @Override public void stop(int timeout, TimeUnit timeUnit) { super.stop(timeout, timeUnit); es.shutdown(); validatorES.shutdown(); } }; clientList.add(leecher); leecher.start(InetAddress.getLocalHost()); try { leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 5); fail("Must fail, because file wasn't downloaded completely"); } catch (IOException ex) { } } public void canStartAndStopClientTwice() throws Exception { final ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE); final ExecutorService validatorES = Executors.newFixedThreadPool(4); final Client client = new Client(es, validatorES); clientList.add(client); try { client.start(InetAddress.getLocalHost()); client.stop(); client.start(InetAddress.getLocalHost()); client.stop(); } finally { es.shutdown(); validatorES.shutdown(); } } public void peer_dies_during_download() throws InterruptedException, NoSuchAlgorithmException, IOException { tracker.setAnnounceInterval(5); final Client seed1 = createClient(); final Client seed2 = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 240); final Torrent torrent = TorrentCreator.create(dwnlFile, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seed1.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent()); seed1.start(InetAddress.getLocalHost()); seed1.setAnnounceInterval(5); seed2.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent()); seed2.start(InetAddress.getLocalHost()); seed2.setAnnounceInterval(5); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); leecher.setAnnounceInterval(5); final ExecutorService service = Executors.newFixedThreadPool(1); final Future<?> future = service.submit(new Runnable() { @Override public void run() { try { Thread.sleep(5 * 1000); seed1.removeTorrent(torrent); Thread.sleep(3 * 1000); seed1.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent()); seed2.removeTorrent(torrent); } catch (InterruptedException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); try { leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 60, 0, new AtomicBoolean(), 10); } finally { future.cancel(true); service.shutdown(); } } public void testThatProgressListenerInvoked() throws Exception { tracker.setAcceptForeignTorrents(true); Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent(), true, false); Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final AtomicInteger pieceLoadedInvocationCount = new AtomicInteger(); leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 10, 1, new AtomicBoolean(false), 5000, new DownloadProgressListener() { @Override public void pieceLoaded(int pieceIndex, int pieceSize) { pieceLoadedInvocationCount.incrementAndGet(); } }); assertEquals(pieceLoadedInvocationCount.get(), torrent.getPieceCount()); } public void interrupt_download() throws IOException, InterruptedException, NoSuchAlgorithmException { tracker.setAcceptForeignTorrents(true); final Client seeder = createClient(); final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 60); final Torrent torrent = TorrentCreator.create(dwnlFile, null, tracker.getAnnounceURI(), "Test"); final File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.start(InetAddress.getLocalHost()); seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent(), true, false); final Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); final AtomicBoolean interrupted = new AtomicBoolean(); final Thread th = new Thread() { @Override public void run() { try { leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 30); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { interrupted.set(true); return; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return; } } }; th.start(); Thread.sleep(100); th.interrupt(); new WaitFor(10 * 1000) { @Override protected boolean condition() { return !th.isAlive(); } }; assertTrue(interrupted.get()); } public void test_connect_to_unknown_host() throws InterruptedException, NoSuchAlgorithmException, IOException { final File torrent = new File("src/test/resources/torrents/file1.jar.torrent"); final TrackedTorrent tt = TrackedTorrent.load(torrent); final Client seeder = createAndStartClient(); final Client leecher = createAndStartClient(); final TrackedTorrent announce = tracker.announce(tt); final Random random = new Random(); final File leechFolder = tempFiles.createTempDir(); for (int i = 0; i < 40; i++) { byte[] data = new byte[20]; random.nextBytes(data); announce.addPeer(new TrackedPeer(tt, "my_unknown_and_unreachablehost" + i, 6881, ByteBuffer.wrap(data))); } File torrentFile = new File(TEST_RESOURCES + "/torrents", "file1.jar.torrent"); File parentFiles = new File(TEST_RESOURCES + "/parentFiles"); seeder.addTorrent(torrentFile.getAbsolutePath(), parentFiles.getAbsolutePath(), true, false); leecher.addTorrent(torrentFile.getAbsolutePath(), leechFolder.getAbsolutePath()); waitForFileInDir(leechFolder, "file1.jar"); } public void test_seeding_does_not_change_file_modification_date() throws IOException, InterruptedException, NoSuchAlgorithmException { File srcFile = tempFiles.createTempFile(1024); long time = srcFile.lastModified(); Thread.sleep(1000); Client seeder = createAndStartClient(); final Torrent torrent = TorrentCreator.create(srcFile, null, tracker.getAnnounceURI(), "Test"); File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); seeder.addTorrent(torrentFile.getAbsolutePath(), srcFile.getParent(), true, false); final File downloadDir = tempFiles.createTempDir(); Client leech = createClient(); leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath()); leech.start(InetAddress.getLocalHost()); waitForFileInDir(downloadDir, srcFile.getName()); assertEquals(time, srcFile.lastModified()); } private void downloadAndStop(Torrent torrent, long timeout, final Client leech) throws IOException, NoSuchAlgorithmException, InterruptedException { final File tempDir = tempFiles.createTempDir(); File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); leech.addTorrent(torrentFile.getAbsolutePath(), tempDir.getAbsolutePath()); leech.start(InetAddress.getLocalHost()); waitForFileInDir(tempDir, torrent.getFilenames().get(0)); leech.stop(); } private void validateMultipleClientsResults(final List<Client> clientsList, MessageDigest md5, final File baseFile, String baseMD5) throws IOException { final WaitFor waitFor = new WaitFor(75 * 1000) { @Override protected boolean condition() { boolean retval = true; for (Client client : clientsList) { if (!retval) return false; final AnnounceableFileTorrent torrent = (AnnounceableFileTorrent) client.getTorrentsStorage().announceableTorrents().iterator().next(); File downloadedFile = new File(torrent.getDownloadDirPath(), baseFile.getName()); retval = downloadedFile.isFile(); } return retval; } }; assertTrue(waitFor.isMyResult(), "All seeders didn't get their files"); // check file contents here: for (Client client : clientsList) { final AnnounceableFileTorrent torrent = (AnnounceableFileTorrent) client.getTorrentsStorage().announceableTorrents().iterator().next(); final File file = new File(torrent.getDownloadDirPath(), baseFile.getName()); assertEquals(baseMD5, getFileMD5(file, md5), String.format("MD5 hash is invalid. C:%s, O:%s ", file.getAbsolutePath(), baseFile.getAbsolutePath())); } } public void testManySeeders() throws Exception { File artifact = tempFiles.createTempFile(300 * 1024 * 1024); int seedersCount = 4; Torrent torrent = TorrentCreator.create(artifact, this.tracker.getAnnounceURI(), "test"); File torrentFile = tempFiles.createTempFile(); saveTorrent(torrent, torrentFile); for (int i = 0; i < seedersCount; i++) { Client seeder = createClient(); seeder.addTorrent(torrentFile.getAbsolutePath(), artifact.getParent(), true, false); seeder.start(InetAddress.getLocalHost()); } Client leecher = createClient(); leecher.start(InetAddress.getLocalHost()); leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 10); } private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders, List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException { List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount); FileInputStream fin = new FileInputStream(baseFile); for (int i = 0; i < piecesCount; i++) { byte[] piece = new byte[pieceSize]; fin.read(piece); piecesList.add(piece); } fin.close(); final long torrentFileLength = baseFile.length(); Torrent torrent = TorrentCreator.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize); File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent"); saveTorrent(torrent, torrentFile); for (int i = 0; i < numSeeders; i++) { final File baseDir = tempFiles.createTempDir(); final File seederPiecesFile = new File(baseDir, baseFile.getName()); RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw"); raf.setLength(torrentFileLength); for (int pieceIdx = i; pieceIdx < piecesCount; pieceIdx += numSeeders) { raf.seek(pieceIdx * pieceSize); raf.write(piecesList.get(pieceIdx)); } Client client = createClient(" client idx " + i); clientList.add(client); client.addTorrent(torrentFile.getAbsolutePath(), baseDir.getAbsolutePath()); client.start(InetAddress.getLocalHost()); } } private String getFileMD5(File file, MessageDigest digest) throws IOException { DigestInputStream dIn = new DigestInputStream(new FileInputStream(file), digest); while (dIn.read() >= 0) ; return dIn.getMessageDigest().toString(); } private void waitForFileInDir(final File downloadDir, final String fileName) { new WaitFor() { @Override protected boolean condition() { return new File(downloadDir, fileName).isFile(); } }; assertTrue(new File(downloadDir, fileName).isFile()); } @AfterMethod protected void tearDown() throws Exception { for (Client client : clientList) { client.stop(); } stopTracker(); tempFiles.cleanup(); } private void startTracker() throws IOException { this.tracker = new Tracker(6969); tracker.setAnnounceInterval(5); this.tracker.start(true); } private Client createAndStartClient() throws IOException, NoSuchAlgorithmException, InterruptedException { Client client = createClient(); client.start(InetAddress.getLocalHost()); return client; } private Client createClient(String name) throws IOException, NoSuchAlgorithmException, InterruptedException { final Client client = clientFactory.getClient(name); clientList.add(client); return client; } private Client createClient() throws IOException, NoSuchAlgorithmException, InterruptedException { return createClient(""); } private void stopTracker() { this.tracker.stop(); } private void assertFilesEqual(File f1, File f2) throws IOException { assertEquals(f1.length(), f2.length(), "Files sizes differ"); Checksum c1 = FileUtils.checksum(f1, new CRC32()); Checksum c2 = FileUtils.checksum(f2, new CRC32()); assertEquals(c1.getValue(), c2.getValue()); } }
package com.alorma.timeline; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; public abstract class TimelineView extends View { private int mLineColor = Color.GRAY; private float mLineWidth = 3f; private int mColorMiddle = -1; private float mMiddleSize = 2f; private int mFirstColor = -1; private float mStartSize = 2f; private int mLastColor = -1; private float mEndSize = 2f; private TimelineType timelineType = TimelineType.MIDDLE; private TimelineAlignment timelineAlignment = TimelineAlignment.MIDDLE; private Paint linePaint, middlePaint, firstPaint, lastPaint; public TimelineView(Context context) { super(context); init(context, null, 0); } public TimelineView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public TimelineView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } private void init(Context context, AttributeSet attrs, int defStyle) { isInEditMode(); mLineColor = fetchPrimaryColor(); mColorMiddle = mFirstColor = mLastColor = fetchAccentColor(); mLineWidth = getContext().getResources().getDimensionPixelOffset(R.dimen.timeline_lineWidth); mMiddleSize = mStartSize = mEndSize = getContext().getResources().getDimensionPixelOffset(R.dimen.timeline_itemSize); if (attrs != null) { final TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.TimelineView, defStyle, 0); if (a != null) { mLineColor = a.getColor(R.styleable.TimelineView_lineColor, mLineColor); mLineWidth = a.getDimension(R.styleable.TimelineView_lineWidth, mLineWidth); mColorMiddle = a.getColor(R.styleable.TimelineView_middleColor, mColorMiddle); mMiddleSize = a.getFloat(R.styleable.TimelineView_middleSize, mMiddleSize); mFirstColor = a.getColor(R.styleable.TimelineView_firstColor, mFirstColor); mStartSize = a.getFloat(R.styleable.TimelineView_firstSize, mStartSize); mLastColor = a.getColor(R.styleable.TimelineView_lastColor, mLastColor); mEndSize = a.getFloat(R.styleable.TimelineView_lastSize, mEndSize); int type = a.getInt(R.styleable.TimelineView_timeline_type, 0); this.timelineType = TimelineType.fromId(type); int alignment = a.getInt(R.styleable.TimelineView_timeline_alignment, 0); this.timelineAlignment = TimelineAlignment.fromId(alignment); a.recycle(); } } if (mColorMiddle == -1) { mColorMiddle = mLineColor; } if (mFirstColor == -1) { mFirstColor = mLineColor; } if (mLastColor == -1) { mLastColor = mLineColor; } linePaint = new Paint(); linePaint.setFlags(Paint.ANTI_ALIAS_FLAG); linePaint.setColor(mLineColor); middlePaint = new Paint(); middlePaint.setFlags(Paint.ANTI_ALIAS_FLAG); middlePaint.setColor(mColorMiddle); middlePaint.setStyle(Paint.Style.FILL_AND_STROKE); middlePaint.setStrokeWidth(mMiddleSize); firstPaint = new Paint(); firstPaint.setFlags(Paint.ANTI_ALIAS_FLAG); firstPaint.setColor(mFirstColor); firstPaint.setStyle(Paint.Style.FILL_AND_STROKE); firstPaint.setStrokeWidth(mStartSize); lastPaint = new Paint(); lastPaint.setFlags(Paint.ANTI_ALIAS_FLAG); lastPaint.setColor(mLastColor); lastPaint.setStyle(Paint.Style.FILL_AND_STROKE); lastPaint.setStrokeWidth(mEndSize); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int contentWidth = getWidth() - getPaddingLeft() - getPaddingRight(); int contentHeight = getHeight() - getPaddingTop() - getPaddingBottom(); float startX = contentWidth / 2 - mLineWidth / 2; float endX = contentWidth / 2 + mLineWidth / 2; int startY = getPaddingTop(); int centerX = contentWidth / 2; int centerY = contentHeight / 2; if (timelineType == TimelineType.START) { canvas.drawRect(startX, centerY, endX, contentHeight, linePaint); drawStart(canvas, firstPaint, centerX, centerY, mStartSize); } else if (timelineType == TimelineType.MIDDLE) { canvas.drawRect(startX, startY, endX, contentHeight, linePaint); switch (timelineAlignment) { case START: startY += (mMiddleSize * 2); drawMiddle(canvas, middlePaint, centerX, startY, mMiddleSize); break; case MIDDLE: default: drawMiddle(canvas, middlePaint, centerX, centerY, mMiddleSize); break; case END: contentHeight -= (mMiddleSize * 2); drawMiddle(canvas, middlePaint, centerX, contentHeight, mMiddleSize); break; } } else if (timelineType == TimelineType.END) { canvas.drawRect(startX, startY, endX, centerY, linePaint); drawEnd(canvas, lastPaint, centerX, centerY, mEndSize); } else { canvas.drawRect(startX, startY, endX, contentHeight, linePaint); } } public void setmLineColor(int mLineColor) { this.mLineColor = mLineColor; invalidate(); } public void setmLineWidth(float mLineWidth) { this.mLineWidth = mLineWidth; invalidate(); } public void setmColorMiddle(int mColorMiddle) { this.mColorMiddle = mColorMiddle; invalidate(); } public void setmMiddleSize(float mMiddleSize) { this.mMiddleSize = mMiddleSize; invalidate(); } public void setmFirstColor(int mFirstColor) { this.mFirstColor = mFirstColor; invalidate(); } public void setmStartSize(float mStartSize) { this.mStartSize = mStartSize; invalidate(); } public void setmLastColor(int mLastColor) { this.mLastColor = mLastColor; invalidate(); } public void setmEndSize(float mEndSize) { this.mEndSize = mEndSize; invalidate(); } public void setItemColor(int color) { mColorMiddle = mFirstColor = mLastColor = color; invalidate(); } public void setItemSize(int size) { mMiddleSize = mStartSize = mEndSize = size; invalidate(); } public void setTimelineType(TimelineType timelineType) { this.timelineType = timelineType; invalidate(); } public void setTimelineAlignment(TimelineAlignment timelineAlignment) { this.timelineAlignment = timelineAlignment; invalidate(); } protected abstract void drawStart(Canvas canvas, Paint firstPaint, float centerX, float centerY, float mStartSize); protected abstract void drawMiddle(Canvas canvas, Paint middlePaint, float centerX, float centerY, float mMiddleSize); protected abstract void drawEnd(Canvas canvas, Paint lastPaint, float centerX, float centerY, float mEndSize); private int fetchPrimaryColor() { TypedValue typedValue = new TypedValue(); TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimary}); int color = a.getColor(0, 0); a.recycle(); return color; } private int fetchAccentColor() { TypedValue typedValue = new TypedValue(); TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorAccent}); int color = a.getColor(0, 0); a.recycle(); return color; } }
package se.sics.cooja.plugins; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.NumberFormat; import java.util.*; import javax.swing.*; import javax.swing.event.*; import org.apache.log4j.Logger; import se.sics.cooja.*; /** * The Control Panel is a simple control panel for simulations. * * @author Fredrik Osterlind */ @ClassDescription("Control Panel") @VisPluginType(VisPluginType.SIM_STANDARD_PLUGIN) public class SimControl extends VisPlugin { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(SimControl.class); private static final int MIN_DELAY_TIME = 0; private static final int MAX_DELAY_TIME = 100; private Simulation simulation; private JSlider sliderDelay; private JLabel simulationTime; private JButton startButton, stopButton; private JFormattedTextField stopTimeTextField; private int simulationStopTime = -1; private Observer simObserver; private Observer tickObserver; private long lastTextUpdateTime = -1; /** * Create a new simulation control panel. * * @param simulationToControl Simulation to control */ public SimControl(Simulation simulationToControl) { super("Control Panel - " + simulationToControl.getTitle()); simulation = simulationToControl; JButton button; JPanel smallPanel; // Register as tickobserver simulation.addTickObserver(tickObserver = new Observer() { public void update(Observable obs, Object obj) { if (simulation == null || simulationTime == null) return; // During simulation running, only update text 10 times each second if (lastTextUpdateTime < System.currentTimeMillis() - 100) { lastTextUpdateTime = System.currentTimeMillis(); simulationTime.setText("Current simulation time: " + simulation.getSimulationTime()); } if (simulationStopTime > 0 && simulationStopTime <= simulation.getSimulationTime() && simulation.isRunning()) { // Time to stop simulation now simulation.stopSimulation(); simulationStopTime = -1; } } }); // Register as simulation observer simulation.addObserver(simObserver = new Observer() { public void update(Observable obs, Object obj) { if (simulation.isRunning()) { startButton.setEnabled(false); stopButton.setEnabled(true); } else { startButton.setEnabled(true); stopButton.setEnabled(false); simulationStopTime = -1; } sliderDelay.setValue((int) simulation.getDelayTime()); simulationTime.setText("Current simulation time: " + simulation.getSimulationTime()); } }); // Main panel JPanel controlPanel = new JPanel(); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS)); setContentPane(controlPanel); // Add control buttons smallPanel = new JPanel(); smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.X_AXIS)); smallPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); button = new JButton("Start"); button.setActionCommand("start"); button.addActionListener(myEventHandler); startButton = button; smallPanel.add(button); button = new JButton("Stop"); button.setActionCommand("stop"); button.addActionListener(myEventHandler); stopButton = button; smallPanel.add(button); button = new JButton("Tick all motes once"); button.setActionCommand("tickall"); button.addActionListener(myEventHandler); smallPanel.add(button); smallPanel.setAlignmentX(Component.LEFT_ALIGNMENT); controlPanel.add(smallPanel); smallPanel = new JPanel(); smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.X_AXIS)); smallPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 10, 5)); button = new JButton("Run until"); button.setActionCommand("rununtil"); button.addActionListener(myEventHandler); smallPanel.add(button); smallPanel.add(Box.createHorizontalStrut(10)); NumberFormat integerFormat = NumberFormat.getIntegerInstance(); stopTimeTextField = new JFormattedTextField(integerFormat); stopTimeTextField.setValue(simulation.getSimulationTime()); stopTimeTextField.addPropertyChangeListener("value", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { JFormattedTextField numberTextField = (JFormattedTextField) e.getSource(); int untilTime = ((Number) numberTextField.getValue()).intValue(); if (untilTime < simulation.getSimulationTime()) { numberTextField.setValue(new Integer(simulation.getSimulationTime() + simulation.getTickTime())); } } }); smallPanel.add(stopTimeTextField); smallPanel.setAlignmentX(Component.LEFT_ALIGNMENT); controlPanel.add(smallPanel); // Add delay slider smallPanel = new JPanel(); smallPanel.setLayout(new BoxLayout(smallPanel, BoxLayout.Y_AXIS)); smallPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); simulationTime = new JLabel(); simulationTime.setText("Current simulation time: " + simulation.getSimulationTime()); smallPanel.add(simulationTime); smallPanel.add(Box.createRigidArea(new Dimension(0, 10))); smallPanel.add(new JLabel("Delay (ms) between each tick")); JSlider slider; if (simulation.getDelayTime() > MAX_DELAY_TIME) slider = new JSlider(JSlider.HORIZONTAL, MIN_DELAY_TIME, simulation.getDelayTime(), simulation.getDelayTime()); else slider = new JSlider(JSlider.HORIZONTAL, MIN_DELAY_TIME, MAX_DELAY_TIME, simulation.getDelayTime()); slider.addChangeListener(myEventHandler); slider.setMajorTickSpacing(20); slider.setPaintTicks(true); slider.setPaintLabels(true); sliderDelay = slider; smallPanel.add(slider); controlPanel.add(smallPanel); pack(); try { setSelected(true); } catch (java.beans.PropertyVetoException e) { // Could not select } } private class MyEventHandler implements ActionListener, ChangeListener { public void stateChanged(ChangeEvent e) { if (e.getSource() == sliderDelay) { simulation.setDelayTime(sliderDelay.getValue()); } else logger.debug("Unhandled state change: " + e); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("start")) { simulationStopTime = -1; // Reset until time simulation.startSimulation(); } else if (e.getActionCommand().equals("stop")) { simulationStopTime = -1; // Reset until time if (simulation.isRunning()) simulation.stopSimulation(); } else if (e.getActionCommand().equals("tickall")) { simulationStopTime = -1; // Reset until time simulation.tickSimulation(); } else if (e.getActionCommand().equals("rununtil")) { // Set new stop time simulationStopTime = ((Number) stopTimeTextField.getValue()).intValue(); if (simulationStopTime > simulation.getSimulationTime() && !simulation.isRunning()) { simulation.startSimulation(); } else { if (simulation.isRunning()) simulation.stopSimulation(); simulationStopTime = -1; } } else logger.debug("Unhandled action: " + e.getActionCommand()); } } MyEventHandler myEventHandler = new MyEventHandler(); public void closePlugin() { // Remove log observer from all log interfaces if (simObserver != null) simulation.deleteObserver(simObserver); if (tickObserver != null) simulation.deleteTickObserver(tickObserver); } }
package de.andreasgiemza.mangadownloader.sites; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import de.andreasgiemza.mangadownloader.data.Chapter; import de.andreasgiemza.mangadownloader.data.Image; import de.andreasgiemza.mangadownloader.data.Manga; import de.andreasgiemza.mangadownloader.helpers.JsoupHelper; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * * @author Andreas Giemza <andreas@giemza.net> */ public class Tapastic implements Site { private final String baseUrl = "http://tapastic.com"; @Override public List<Manga> getMangaList() throws IOException { List<Manga> mangas = new LinkedList<>(); Document doc = JsoupHelper.getHTMLPage(baseUrl + "/browse/list"); int max = Integer.parseInt(doc.select("div[class^=g-pagination-wrap]").first().select("a[class=page-num paging-btn g-act]").last().text()); for (int i = 1; i <= max; i++) { if (i != 1) { doc = JsoupHelper.getHTMLPage(baseUrl + "/browse/list?pageNumber=" + i); } Elements rows = doc.select("ul[class=page-list-wrap]").first().select("li"); for (Element row : rows) { mangas.add(new Manga(row.select("a[class=title]").first().attr("href"), row.select("a[class=title]").first().text())); } } return mangas; } @Override public List<Chapter> getChapterList(Manga manga) throws IOException { List<Chapter> chapters = new LinkedList<>(); Document doc = JsoupHelper.getHTMLPage(baseUrl + manga.getLink()); Scanner scanner = new Scanner(doc.toString()); String line = null; while (scanner.hasNextLine()) { line = scanner.nextLine(); if (line.contains("episodeList")) { break; } } if (line == null) { return chapters; } line = line.split("episodeList : \\[")[1]; line = line.substring(0, line.length() - 2); String[] jsons = line.replace("},{", "}},{{").split("\\},\\{"); for (int i = 0; i < jsons.length; i++) { JsonObject jsonObject = new JsonParser().parse(jsons[i]).getAsJsonObject(); chapters.add(new Chapter(jsonObject.get("id").toString(), "(" + i + ") " + jsonObject.get("title").toString())); } return chapters; } @Override public List<Image> getChapterImageLinks(Chapter chapter) throws IOException { List<Image> imageLinks = new LinkedList<>(); String referrer = baseUrl + "/episode/" + chapter.getLink(); Document doc = JsoupHelper.getHTMLPage(referrer); // Get pages linkes Elements images = doc.select("article[class^=ep-contents]").first().select("img[class=art-image]"); for (Element image : images) { String link = image.attr("src"); String extension = link.substring(link.length() - 3, link.length()); imageLinks.add(new Image(link, referrer, extension)); } return imageLinks; } }
package de.espend.idea.laravel.blade; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProvider; import com.intellij.navigation.GotoRelatedItem; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.ConstantFunction; import com.intellij.util.indexing.FileBasedIndexImpl; import com.intellij.util.indexing.ID; import com.jetbrains.php.PhpIcons; import com.jetbrains.php.blade.BladeFileType; import com.jetbrains.php.blade.psi.BladePsiDirectiveParameter; import com.jetbrains.php.blade.psi.BladeTokenTypes; import de.espend.idea.laravel.LaravelIcons; import de.espend.idea.laravel.LaravelProjectComponent; import de.espend.idea.laravel.blade.util.BladePsiUtil; import de.espend.idea.laravel.blade.util.BladeTemplateUtil; import de.espend.idea.laravel.stub.*; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; import java.util.stream.Collectors; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class TemplateLineMarker implements LineMarkerProvider { @Nullable @Override public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) { return null; } @Override public void collectSlowLineMarkers(@NotNull List<PsiElement> psiElements, @NotNull Collection<LineMarkerInfo> collection) { // we need project element; so get it from first item if(psiElements.size() == 0) { return; } Project project = psiElements.get(0).getProject(); if(!LaravelProjectComponent.isEnabled(project)) { return; } for(PsiElement psiElement: psiElements) { if(psiElement instanceof PsiFile) { collectTemplateFileRelatedFiles((PsiFile) psiElement, collection); } else if(psiElement.getNode().getElementType() == BladeTokenTypes.SECTION_DIRECTIVE) { Pair<PsiElement, String> section = extractSectionParameter(psiElement); if(section != null) { collectOverwrittenSection(section.getFirst(), collection, section.getSecond()); collectImplementsSection(section.getFirst(), collection, section.getSecond()); } } else if(psiElement.getNode().getElementType() == BladeTokenTypes.YIELD_DIRECTIVE) { Pair<PsiElement, String> section = extractSectionParameter(psiElement); if(section != null) { collectImplementsSection(section.getFirst(), collection, section.getSecond()); } } else if(psiElement.getNode().getElementType() == BladeTokenTypes.STACK_DIRECTIVE) { Pair<PsiElement, String> section = extractSectionParameter(psiElement); if(section != null) { collectStackImplements(section.getFirst(), collection, section.getSecond()); } } else if(psiElement.getNode().getElementType() == BladeTokenTypes.PUSH_DIRECTIVE) { Pair<PsiElement, String> section = extractSectionParameter(psiElement); if(section != null) { collectPushOverwrites(section.getFirst(), collection, section.getSecond()); } } } } /** * Extract parameter: @foobar('my_value') */ @Nullable private Pair<PsiElement, String> extractSectionParameter(@NotNull PsiElement psiElement) { PsiElement nextSibling = psiElement.getNextSibling(); if(nextSibling instanceof BladePsiDirectiveParameter) { String sectionName = BladePsiUtil.getSection(nextSibling); if (sectionName != null && StringUtils.isNotBlank(sectionName)) { return Pair.create(nextSibling, sectionName); } } return null; } /** * like this @section('sidebar') */ private void collectOverwrittenSection(final PsiElement psiElement, @NotNull Collection<LineMarkerInfo> collection, final String sectionName) { final List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>(); for(PsiElement psiElement1 : psiElement.getContainingFile().getChildren()) { PsiElement extendDirective = psiElement1.getFirstChild(); if(extendDirective != null && extendDirective.getNode().getElementType() == BladeTokenTypes.EXTENDS_DIRECTIVE) { PsiElement bladeParameter = extendDirective.getNextSibling(); if(bladeParameter instanceof BladePsiDirectiveParameter) { String extendTemplate = BladePsiUtil.getSection(bladeParameter); if(extendTemplate != null) { Set<VirtualFile> virtualFiles = BladeTemplateUtil.resolveTemplateName(psiElement.getProject(), extendTemplate); for(VirtualFile virtualFile: virtualFiles) { PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile); if(psiFile != null) { visitOverwrittenTemplateFile(psiFile, gotoRelatedItems, sectionName); } } } } } } if(gotoRelatedItems.size() == 0) { return; } collection.add(getRelatedPopover("Parent Section", "Blade Section", psiElement, gotoRelatedItems, PhpIcons.OVERRIDES)); } private void collectTemplateFileRelatedFiles(final PsiFile psiFile, @NotNull Collection<LineMarkerInfo> collection) { Set<String> collectedTemplates = BladeTemplateUtil.getFileTemplateName(psiFile.getProject(), psiFile.getVirtualFile()); if(collectedTemplates.size() == 0) { return; } // lowercase for index Set<String> templateNames = new HashSet<>(); for (String templateName : collectedTemplates) { templateNames.add(templateName); templateNames.add(templateName.toLowerCase()); } // normalize all template names and support both: "foo.bar" and "foo/bar" templateNames.addAll(new HashSet<>(templateNames) .stream().map(templateName -> templateName.replace(".", "/")) .collect(Collectors.toList()) ); final List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>(); for(ID<String, Void> key : Arrays.asList(BladeExtendsStubIndex.KEY, BladeSectionStubIndex.KEY, BladeIncludeStubIndex.KEY, BladeEachStubIndex.KEY)) { for(String templateName: templateNames) { FileBasedIndexImpl.getInstance().getFilesWithKey(key, new HashSet<>(Collections.singletonList(templateName)), virtualFile -> { PsiFile psiFileTarget = PsiManager.getInstance(psiFile.getProject()).findFile(virtualFile); if(psiFileTarget != null) { gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(psiFileTarget).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL)); } return true; }, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(psiFile.getProject()), BladeFileType.INSTANCE, BladeFileType.INSTANCE)); } } // collect tagged index files Collection<VirtualFile> files = new HashSet<>(); for(final String templateName: templateNames) { files.addAll( FileBasedIndexImpl.getInstance().getContainingFiles(PhpTemplateUsageStubIndex.KEY, templateName, GlobalSearchScope.allScope(psiFile.getProject())) ); } for (VirtualFile file : files) { PsiFile psiFileTarget = PsiManager.getInstance(psiFile.getProject()).findFile(file); if(psiFileTarget == null) { continue; } Collection<Pair<String, PsiElement>> pairs = BladeTemplateUtil.getViewTemplatesPairScope(psiFileTarget); for (String templateName : templateNames) { for (Pair<String, PsiElement> pair : pairs) { if(templateName.equalsIgnoreCase(pair.first)) { gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(pair.getSecond()).withIcon(PhpIcons.IMPLEMENTED, PhpIcons.IMPLEMENTED)); } } } } if(gotoRelatedItems.size() == 0) { return; } collection.add(getRelatedPopover("Template", "Blade File", psiFile, gotoRelatedItems, PhpIcons.IMPLEMENTED)); } private LineMarkerInfo getRelatedPopover(String singleItemTitle, String singleItemTooltipPrefix, PsiElement lineMarkerTarget, List<GotoRelatedItem> gotoRelatedItems, Icon icon) { // single item has no popup String title = singleItemTitle; if(gotoRelatedItems.size() == 1) { String customName = gotoRelatedItems.get(0).getCustomName(); if(customName != null) { title = String.format(singleItemTooltipPrefix, customName); } } return new LineMarkerInfo<>( lineMarkerTarget, lineMarkerTarget.getTextRange(), icon, 6, new ConstantFunction<>(title), new RelatedPopupGotoLineMarker.NavigationHandler(gotoRelatedItems), GutterIconRenderer.Alignment.RIGHT ); } private void visitOverwrittenTemplateFile(final PsiFile psiFile, final List<GotoRelatedItem> gotoRelatedItems, final String sectionName) { visitOverwrittenTemplateFile(psiFile, gotoRelatedItems, sectionName, 10); } private void visitOverwrittenTemplateFile(final PsiFile psiFile, final List<GotoRelatedItem> gotoRelatedItems, final String sectionName, int depth) { // simple secure recursive calls if(depth return; } BladeTemplateUtil.DirectiveParameterVisitor visitor = parameter -> { if (sectionName.equalsIgnoreCase(parameter.getContent())) { gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL)); } }; BladeTemplateUtil.visitSection(psiFile, visitor); BladeTemplateUtil.visitYield(psiFile, visitor); final int finalDepth = depth; BladeTemplateUtil.visitExtends(psiFile, parameter -> { Set<VirtualFile> virtualFiles = BladeTemplateUtil.resolveTemplateName(psiFile.getProject(), parameter.getContent()); for (VirtualFile virtualFile : virtualFiles) { PsiFile templatePsiFile = PsiManager.getInstance(psiFile.getProject()).findFile(virtualFile); if (templatePsiFile != null) { visitOverwrittenTemplateFile(templatePsiFile, gotoRelatedItems, sectionName, finalDepth); } } }); } /** * Find all sub implementations of a section that are overwritten by an extends tag * Possible targets are: @section('sidebar') */ private void collectImplementsSection(PsiElement psiElement, @NotNull Collection<LineMarkerInfo> collection, final String sectionName) { Set<String> templateNames = BladeTemplateUtil.getFileTemplateName(psiElement.getProject(), psiElement.getContainingFile().getVirtualFile()); if(templateNames.size() == 0) { return; } final List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>(); Set<VirtualFile> virtualFiles = BladeTemplateUtil.getExtendsImplementations(psiElement.getProject(), templateNames); if(virtualFiles.size() == 0) { return; } for(VirtualFile virtualFile: virtualFiles) { PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile); if(psiFile != null) { BladeTemplateUtil.visitSection(psiFile, parameter -> { if (sectionName.equalsIgnoreCase(parameter.getContent())) { gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL)); } }); } } if(gotoRelatedItems.size() == 0) { return; } collection.add(getRelatedPopover("Template", "Blade File", psiElement, gotoRelatedItems, PhpIcons.IMPLEMENTED)); } /** * Support: @stack('foobar') */ private void collectStackImplements(final PsiElement psiElement, @NotNull Collection<LineMarkerInfo> collection, final String sectionName) { Set<String> templateNames = BladeTemplateUtil.getFileTemplateName(psiElement.getProject(), psiElement.getContainingFile().getVirtualFile()); if(templateNames.size() == 0) { return; } final List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>(); Set<VirtualFile> virtualFiles = BladeTemplateUtil.getExtendsImplementations(psiElement.getProject(), templateNames); if(virtualFiles.size() == 0) { return; } for(VirtualFile virtualFile: virtualFiles) { PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile); if(psiFile != null) { BladeTemplateUtil.visit(psiFile, BladeTokenTypes.PUSH_DIRECTIVE, parameter -> { if (sectionName.equalsIgnoreCase(parameter.getContent())) { gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL)); } }); } } if(gotoRelatedItems.size() == 0) { return; } collection.add(getRelatedPopover("Push Implementation", "Push Implementation", psiElement, gotoRelatedItems, PhpIcons.IMPLEMENTED)); } /** * Support: @push('foobar') */ private void collectPushOverwrites(final PsiElement psiElement, @NotNull Collection<LineMarkerInfo> collection, final String sectionName) { final List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>(); BladeTemplateUtil.visitUpPath(psiElement.getContainingFile(), 10, parameter -> { if(sectionName.equalsIgnoreCase(parameter.getContent())) { gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL)); } }, BladeTokenTypes.STACK_DIRECTIVE); if(gotoRelatedItems.size() == 0) { return; } collection.add(getRelatedPopover("Stack Section", "Stack Overwrites", psiElement, gotoRelatedItems, PhpIcons.OVERRIDES)); } }
package de.lmu.ifi.dbs.elki.index; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.database.ids.DBIDRef; import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery; import de.lmu.ifi.dbs.elki.database.query.knn.AbstractDistanceKNNQuery; import de.lmu.ifi.dbs.elki.database.query.range.AbstractDistanceRangeQuery; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.logging.statistics.Counter; /** * Abstract base class for Filter-refinement indexes. * * The number of refinements will be counted as individual page accesses. * * @author Erich Schubert * * @apiviz.excludeSubtypes * @apiviz.has AbstractRangeQuery * @apiviz.has AbstractKNNQuery * * @param <O> Object type */ public abstract class AbstractRefiningIndex<O> extends AbstractIndex<O> { /** * Refinement counter. */ private Counter refinements; /** * Constructor. * * @param relation Relation indexed */ public AbstractRefiningIndex(Relation<O> relation) { super(relation); Logging log = getLogger(); refinements = log.isStatistics() ? log.newCounter(this.getClass().getName() + ".refinements") : null; } /** * Get the class logger. * * @return Logger */ abstract public Logging getLogger(); /** * Increment the refinement counter, if in use. * * @param i Increment. */ protected void countRefinements(int i) { if (refinements != null) { refinements.increment(i); } } @Override public void logStatistics() { if (refinements != null) { getLogger().statistics(refinements); } } /** * Refine a given object (and count the refinement!). * * @param id Object id * @return refined object */ protected O refine(DBID id) { countRefinements(1); return relation.get(id); } /** * Range query for this index. * * @author Erich Schubert * * @apiviz.excludeSubtypes */ public abstract class AbstractRangeQuery<D extends Distance<D>> extends AbstractDistanceRangeQuery<O, D> { /** * Constructor. * * @param distanceQuery Distance query object */ public AbstractRangeQuery(DistanceQuery<O, D> distanceQuery) { super(distanceQuery); } /** * Refinement distance computation. * * @param id Candidate ID * @param q Query object * @return Distance */ protected D refine(DBIDRef id, O q) { AbstractRefiningIndex.this.countRefinements(1); return distanceQuery.distance(q, id); } /** * Count extra refinements. * * @param c Refinements */ protected void incRefinements(int c) { AbstractRefiningIndex.this.countRefinements(c); } } /** * KNN query for this index. * * @author Erich Schubert * * @apiviz.excludeSubtypes */ public abstract class AbstractKNNQuery<D extends Distance<D>> extends AbstractDistanceKNNQuery<O, D> { /** * Constructor. * * @param distanceQuery Distance query object */ public AbstractKNNQuery(DistanceQuery<O, D> distanceQuery) { super(distanceQuery); } /** * Refinement distance computation. * * @param id Candidate ID * @param q Query object * @return Distance */ protected D refine(DBID id, O q) { AbstractRefiningIndex.this.countRefinements(1); return distanceQuery.distance(q, id); } /** * Count extra refinements. * * @param c Refinements */ protected void incRefinements(int c) { AbstractRefiningIndex.this.countRefinements(c); } } }
package de.lmu.ifi.dbs.elki.utilities.output; import java.text.NumberFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.List; import java.util.Locale; /** * Utility methods for output formatting of various number objects */ public final class FormatUtil { /** * Number Formatter (2 digits) for output purposes. */ public static final NumberFormat NF2 = NumberFormat.getInstance(Locale.US); /** * Number Formatter (4 digits) for output purposes. */ public static final NumberFormat NF4 = NumberFormat.getInstance(Locale.US); /** * Number Formatter (8 digits) for output purposes. */ public static final NumberFormat NF8 = NumberFormat.getInstance(Locale.US); static { NF2.setMinimumFractionDigits(2); NF2.setMaximumFractionDigits(2); NF4.setMinimumFractionDigits(4); NF4.setMaximumFractionDigits(4); NF8.setMinimumFractionDigits(8); NF8.setMaximumFractionDigits(8); } /** * Whitespace. The string should cover the commonly used length. */ private static final String WHITESPACE_BUFFER = " "; /** * The system newline setting. */ public static final String NEWLINE = System.getProperty("line.separator"); /** * Formats the double d with the specified fraction digits. * * @param d the double array to be formatted * @param digits the number of fraction digits * @return a String representing the double d */ public static String format(final double d, int digits) { final NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setMaximumFractionDigits(digits); nf.setMinimumFractionDigits(digits); nf.setGroupingUsed(false); return nf.format(d); } /** * Formats the double d with the specified number format. * * @param d the double array to be formatted * @param nf the number format to be used for formatting * @return a String representing the double d */ public static String format(final double d, NumberFormat nf) { return nf.format(d); } /** * Formats the double d with 2 fraction digits. * * @param d the double to be formatted * @return a String representing the double d */ public static String format(final double d) { return format(d, 2); } /** * Formats the double array d with the specified separator. * * @param d the double array to be formatted * @param sep the separator between the single values of the double array, * e.g. ',' * @return a String representing the double array d */ public static String format(double[] d, String sep) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < d.length; i++) { if(i < d.length - 1) { buffer.append(d[i]).append(sep); } else { buffer.append(d[i]); } } return buffer.toString(); } /** * Formats the double array d with the specified separator and the specified * fraction digits. * * @param d the double array to be formatted * @param sep the separator between the single values of the double array, * e.g. ',' * @param digits the number of fraction digits * @return a String representing the double array d */ public static String format(double[] d, String sep, int digits) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < d.length; i++) { if(i < d.length - 1) { buffer.append(format(d[i], digits)).append(sep); } else { buffer.append(format(d[i], digits)); } } return buffer.toString(); } /** * Formats the double array d with the specified number format. * * @param d the double array to be formatted * @param nf the number format to be used for formatting * @return a String representing the double array d */ public static String format(double[] d, NumberFormat nf) { return format(d, " ", nf); } /** * Formats the double array d with the specified number format. * * @param d the double array to be formatted * @param sep the separator between the single values of the double array, * e.g. ',' * @param nf the number format to be used for formatting * @return a String representing the double array d */ public static String format(double[] d, String sep, NumberFormat nf) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < d.length; i++) { if(i < d.length - 1) { buffer.append(format(d[i], nf)).append(sep); } else { buffer.append(format(d[i], nf)); } } return buffer.toString(); } /** * Formats the double array d with ',' as separator and 2 fraction digits. * * @param d the double array to be formatted * @return a String representing the double array d */ public static String format(double[] d) { return format(d, ", ", 2); } /** * Formats the double array d with ', ' as separator and with the specified * fraction digits. * * @param d the double array to be formatted * @param digits the number of fraction digits * @return a String representing the double array d */ public static String format(double[] d, int digits) { return format(d, ", ", digits); } /** * Formats the double array d with ',' as separator and 2 fraction digits. * * @param d the double array to be formatted * @return a String representing the double array d */ public static String format(double[][] d) { StringBuffer buffer = new StringBuffer(); for(double[] array : d) { buffer.append(format(array, ", ", 2)).append("\n"); } return buffer.toString(); } /** * Formats the array of double arrays d with 'the specified separators and * fraction digits. * * @param d the double array to be formatted * @param sep1 the first separator of the outer array * @param sep2 the second separator of the inner array * @param digits the number of fraction digits * @return a String representing the double array d */ public static String format(double[][] d, String sep1, String sep2, int digits) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < d.length; i++) { if(i < d.length - 1) { buffer.append(format(d[i], sep2, digits)).append(sep1); } else { buffer.append(format(d[i], sep2, digits)); } } return buffer.toString(); } /** * Formats the Double array f with the specified separator and the specified * fraction digits. * * @param f the Double array to be formatted * @param sep the separator between the single values of the Double array, e.g. * ',' * @param digits the number of fraction digits * @return a String representing the Double array f */ public static String format(Double[] f, String sep, int digits) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < f.length; i++) { if(i < f.length - 1) { buffer.append(format(f[i], digits)).append(sep); } else { buffer.append(format(f[i], digits)); } } return buffer.toString(); } /** * Formats the Double array f with ',' as separator and 2 fraction digits. * * @param f the Double array to be formatted * @return a String representing the Double array f */ public static String format(Double[] f) { return format(f, ", ", 2); } /** * Formats the float array f with the specified separator and the specified * fraction digits. * * @param f the float array to be formatted * @param sep the separator between the single values of the float array, e.g. * ',' * @param digits the number of fraction digits * @return a String representing the float array f */ public static String format(float[] f, String sep, int digits) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < f.length; i++) { if(i < f.length - 1) { buffer.append(format(f[i], digits)).append(sep); } else { buffer.append(format(f[i], digits)); } } return buffer.toString(); } /** * Formats the float array f with ',' as separator and 2 fraction digits. * * @param f the float array to be formatted * @return a String representing the float array f */ public static String format(float[] f) { return format(f, ", ", 2); } /** * Formats the int array a for printing purposes. * * @param a the int array to be formatted * @param sep the separator between the single values of the float array, e.g. * ',' * @return a String representing the int array a */ public static String format(int[] a, String sep) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < a.length; i++) { if(i < a.length - 1) { buffer.append(a[i]).append(sep); } else { buffer.append(a[i]); } } return buffer.toString(); } /** * Formats the int array a for printing purposes. * * @param a the int array to be formatted * @return a String representing the int array a */ public static String format(int[] a) { return format(a, ", "); } /** * Formats the Integer array a for printing purposes. * * @param a the Integer array to be formatted * @param sep the separator between the single values of the float array, e.g. * ',' * @return a String representing the Integer array a */ public static String format(Integer[] a, String sep) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < a.length; i++) { if(i < a.length - 1) { buffer.append(a[i]).append(sep); } else { buffer.append(a[i]); } } return buffer.toString(); } /** * Formats the Integer array a for printing purposes. * * @param a the Integer array to be formatted * @return a String representing the Integer array a */ public static String format(Integer[] a) { return format(a, ", "); } /** * Formats the long array a for printing purposes. * * @param a the long array to be formatted * @return a String representing the long array a */ public static String format(long[] a) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < a.length; i++) { if(i < a.length - 1) { buffer.append(a[i]).append(", "); } else { buffer.append(a[i]); } } return buffer.toString(); } /** * Formats the byte array a for printing purposes. * * @param a the byte array to be formatted * @return a String representing the byte array a */ public static String format(byte[] a) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < a.length; i++) { if(i < a.length - 1) { buffer.append(a[i]).append(", "); } else { buffer.append(a[i]); } } return buffer.toString(); } /** * Formats the boolean array b with ',' as separator. * * @param b the boolean array to be formatted * @param sep the separator between the single values of the double array, * e.g. ',' * @return a String representing the boolean array b */ public static String format(boolean[] b, final String sep) { StringBuffer buffer = new StringBuffer(); for(int i = 0; i < b.length; i++) { if(i < b.length - 1) { buffer.append(format(b[i])).append(sep); } else { buffer.append(format(b[i])); } } return buffer.toString(); } /** * Formats the boolean b. * * @param b the boolean to be formatted * @return a String representing of the boolean b */ public static String format(final boolean b) { if(b) { return "1"; } return "0"; } /** * Returns a string representation of the specified bit set. * * @param bitSet the bitSet * @param dim the overall dimensionality of the bit set * @param sep the separator * @return a string representation of the specified bit set. */ public static String format(BitSet bitSet, int dim, String sep) { StringBuffer msg = new StringBuffer(); for(int d = 0; d < dim; d++) { if(d > 0) { msg.append(sep); } if(bitSet.get(d)) { msg.append("1"); } else { msg.append("0"); } } return msg.toString(); } /** * Returns a string representation of the specified bit set. * * @param dim the overall dimensionality of the bit set * @param bitSet the bitSet * @return a string representation of the specified bit set. */ public static String format(int dim, BitSet bitSet) { // TODO: removed whitespace - hierarchy reading to be adapted! return format(bitSet, dim, ","); } /** * Formats the String cCollection with the specified separator. * * @param d the String Collection to format * @param sep the separator between the single values of the double array, * e.g. ' ' * @return a String representing the String Collection d */ public static String format(Collection<String> d, String sep) { StringBuffer buffer = new StringBuffer(); boolean first = true; for(String str : d) { if (!first) { buffer.append(sep); } buffer.append(str); first = false; } return buffer.toString(); } /** * Find the first space before position w or if there is none after w. * * @param s String * @param width Width * @return index of best whitespace or <code>-1</code> if no whitespace was * found. */ public static int findSplitpoint(String s, int width) { // the newline (or EOS) is the fallback split position. int in = s.indexOf(NEWLINE); if (in < 0) { in = s.length(); } // Good enough? if (in < width) { return in; } // otherwise, search for whitespace int iw = s.lastIndexOf(' ', width); // good whitespace found? if (iw >= 0 && iw < width) { return iw; } // sub-optimal splitpoint - retry AFTER the given position int bp = nextPosition(s.indexOf(' ', width), s.indexOf(NEWLINE, width)); if (bp >= 0) { return bp; } // even worse - can't split! return s.length(); } /** * Helper that is similar to {@code Math.min(a,b)}, except that negative values are considered "invalid". * * @param a String position * @param b String position * @return {@code Math.min(a,b)} if {@code a >= 0} and {@code b >= 0}, otherwise whichever is positive. */ private static int nextPosition(int a, int b) { if (a < 0) { return b; } if (b < 0) { return a; } return Math.min(a,b); } /** * Splits the specified string at the last blank before width. If there is no * blank before the given width, it is split at the next. * * @param s the string to be split * @param width int * @return string fragments */ public static List<String> splitAtLastBlank(String s, int width) { List<String> chunks = new ArrayList<String>(); if(s.length() <= width) { chunks.add(s); return chunks; } String tmp = s; while(tmp.length() > 0) { int index = findSplitpoint(tmp, width); // store first part chunks.add(tmp.substring(0, index)); // skip whitespace at beginning of line while(index < tmp.length() && tmp.charAt(index) == ' ') { index += 1; } // remove a newline if (index < tmp.length() && tmp.regionMatches(index, NEWLINE, 0, NEWLINE.length())) { index += NEWLINE.length(); } if (index >= tmp.length()) { break; } tmp = tmp.substring(index); } return chunks; } /** * Returns a string with the specified number of whitespace. * * @param n the number of whitespace characters * @return a string with the specified number of blanks */ public static String whitespace(int n) { if(n < WHITESPACE_BUFFER.length()) { return WHITESPACE_BUFFER.substring(0, n); } char[] buf = new char[n]; for(int i = 0; i < n; i++) { buf[i] = WHITESPACE_BUFFER.charAt(0); } return new String(buf); } /** * Pad a string to a given length by adding whitespace to the right. * * @param o original string * @param len destination length * @return padded string of at least length len (and o otherwise) */ public static String pad(String o, int len) { if(o.length() >= len) { return o; } return o + whitespace(len - o.length()); } /** * Pad a string to a given length by adding whitespace to the left. * * @param o original string * @param len destination length * @return padded string of at least length len (and o otherwise) */ public static String padRightAligned(String o, int len) { if(o.length() >= len) { return o; } return whitespace(len - o.length()) + o; } }
package dr.evomodel.antigenic; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; import dr.inference.model.Variable; import dr.inference.operators.MCMCOperator; import dr.inference.operators.SimpleMCMCOperator; import dr.math.MathUtils; import dr.xml.*; import javax.lang.model.element.Element; /** * An operator to split or merge clusters. * * @author Andrew Rambaut * @author Marc Suchard * @version $Id: DirichletProcessGibbsOperator.java,v 1.16 2005/06/14 10:40:34 rambaut Exp $ */ public class ClusterSplitMergeOperator extends SimpleMCMCOperator { public final static boolean DEBUG = false; public final static String CLUSTER_SPLIT_MERGE_OPERATOR = "clusterSplitMergeOperator"; private final int N; // the number of items private int K; // the number of occupied clusters private final Parameter allocationParameter; private final MatrixParameter clusterLocations; public ClusterSplitMergeOperator(Parameter allocationParameter, MatrixParameter clusterLocations, double weight) { this.allocationParameter = allocationParameter; this.clusterLocations = clusterLocations; this.N = allocationParameter.getDimension(); setWeight(weight); } /** * @return the parameter this operator acts on. */ public Parameter getParameter() { return (Parameter) allocationParameter; } /** * @return the Variable this operator acts on. */ public Variable getVariable() { return allocationParameter; } /** * change the parameter and return the hastings ratio. */ public final double doOperation() { // get a copy of the allocations to work with... int[] allocations = new int[allocationParameter.getDimension()]; // construct cluster occupancy vector excluding the selected item and count // the unoccupied clusters. int[] occupancy = new int[N]; int[] occupiedIndices = new int[N]; // for testing, set these to -1 to force out of bounds exception if // used but not set for (int i = 0; i < occupiedIndices.length; i++) { occupiedIndices[i] = -1; } int K = 0; // k = number of unoccupied clusters for (int i = 0; i < allocations.length; i++) { allocations[i] = (int) allocationParameter.getParameterValue(i); occupancy[allocations[i]] += 1; if (occupancy[allocations[i]] == 1) { // first item in cluster occupiedIndices[K] = allocations[i]; K++; } } // Container for split/merge random variable (only 2 draws in 2D) int paramDim = clusterLocations.getParameter(0).getDimension(); double[] splitDraw = new double[paramDim]; // Need to keep these for computing MHG ratio double scale = 1.0; // TODO make tunable // always split when K = 1, always merge when K = N, otherwise 50:50 boolean doSplit = K == 1 || (K != N && MathUtils.nextBoolean()); if (doSplit) { // Split operation int cluster1; do { // pick an occupied cluster cluster1 = occupiedIndices[MathUtils.nextInt(K)]; // For reversibility, merge step requires that both resulting clusters are occupied, // so we should resample until condition is true } while (occupancy[cluster1] == 0); // find the first unoccupied cluster int cluster2 = 0; while (occupancy[cluster2] > 0) { cluster2 ++; } int count = 0; for (int i = 0; i < allocations.length; i++) { if (allocations[i] == cluster1) { if (MathUtils.nextBoolean()) { count ++; allocations[i] = cluster2; // keep occupancy up to date (remove if not need) occupancy[cluster1] occupancy[cluster2] ++; } } } if (occupancy[cluster1] == 0 || occupancy[cluster2] == 0) { // either all the items were moved or none... // todo Perhaps we should draw the number to split and then allocate items? } K++; // set both clusters to a location based on the first cluster with some random jitter... Parameter param1 = clusterLocations.getParameter(cluster1); Parameter param2 = clusterLocations.getParameter(cluster2); double[] loc = param1.getParameterValues(); for (int dim = 0; dim < param1.getDimension(); dim++) { splitDraw[dim] = MathUtils.nextGaussian(); param1.setParameterValue(dim, loc[dim] + (splitDraw[dim] * scale)); param2.setParameterValue(dim, loc[dim] - (splitDraw[dim] * scale)); // Move in opposite direction } if (DEBUG) { System.err.println("Split: " + count + " items from cluster " + cluster1 + " to create cluster " + cluster2); } } else { // Merge operation // pick 2 occupied clusters int cluster1 = occupiedIndices[MathUtils.nextInt(K)]; int cluster2; do { cluster2 = occupiedIndices[MathUtils.nextInt(K)]; // resample until cluster1 != cluster2 to maintain reversibility, because split assumes they are different } while (cluster1 == cluster2); for (int i = 0; i < allocations.length; i++) { if (allocations[i] == cluster2) { allocations[i] = cluster1; // keep occupancy up to date (remove if not need) occupancy[cluster1] ++; occupancy[cluster2] } } K // set the merged cluster to the mean location of the two original clusters Parameter loc1 = clusterLocations.getParameter(cluster1); Parameter loc2 = clusterLocations.getParameter(cluster2); for (int dim = 0; dim < loc1.getDimension(); dim++) { double average = (loc1.getParameterValue(dim) + loc2.getParameterValue(dim)) / 2.0; splitDraw[dim] = (loc1.getParameterValue(dim) - average) / scale; // Record that the reverse step would need to draw loc1.setParameterValue(dim, average); } if (DEBUG) { System.err.println("Merge: " + occupancy[cluster1] + "items into cluster " + cluster1 + " from " + cluster2); } } // set the final allocations (only for those that have changed) for (int i = 0; i < allocations.length; i++) { int k = (int) allocationParameter.getParameterValue(i); if (allocations[i] != k) { allocationParameter.setParameterValue(i, allocations[i]); } } // todo the Hastings ratio return 0.0; } //MCMCOperator INTERFACE public final String getOperatorName() { return CLUSTER_SPLIT_MERGE_OPERATOR +"(" + allocationParameter.getId() + ")"; } public final void optimize(double targetProb) { throw new RuntimeException("This operator cannot be optimized!"); } public boolean isOptimizing() { return false; } public void setOptimizing(boolean opt) { throw new RuntimeException("This operator cannot be optimized!"); } public double getMinimumAcceptanceLevel() { return 0.1; } public double getMaximumAcceptanceLevel() { return 0.4; } public double getMinimumGoodAcceptanceLevel() { return 0.20; } public double getMaximumGoodAcceptanceLevel() { return 0.30; } public String getPerformanceSuggestion() { if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) { return ""; } else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) { return ""; } else { return ""; } } public String toString() { return getOperatorName(); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public final static String CHI = "chi"; public final static String LIKELIHOOD = "likelihood"; public String getParserName() { return CLUSTER_SPLIT_MERGE_OPERATOR; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); Parameter allocationParameter = (Parameter) xo.getChild(Parameter.class); MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild("locations"); return new ClusterSplitMergeOperator(allocationParameter, locationsParameter, weight); }
package edu.ucsb.cs56.w15.drawings.vgandolfo; import javax.swing.*; /** SimpleGui1 comes from Head First Java 2nd Edition p. 355. It illustrates a simple GUI with a Button that doesn't do anything yet. @author Head First Java, 2nd Edition p. 355 @author P. Conrad (who only typed it in and added the Javadoc comments) @author Vincent Gandolfo @version CS56, Winter 2015, UCSB */ public class SimpleGui1 { /** main method to fire up a JFrame on the screen @param args not used */ public static void main (String[] args) { JFrame frame = new JFrame() ; JButton button = new JButton("click me for free money") ; java.awt.Color myColor = new java.awt.Color(000,204,255); // R, G, B values. button.setBackground(myColor); button.setOpaque(true); frame. setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE) ; frame. getContentPane() . add(button) ; frame. setSize(300,300) ; frame. setVisible(true) ; } }
package com.dmdirc.addons.ui_swing; import com.dmdirc.DMDircMBassador; import com.dmdirc.addons.ui_swing.components.SplitPane; import com.dmdirc.addons.ui_swing.components.frames.TextFrame; import com.dmdirc.addons.ui_swing.components.menubar.MenuBar; import com.dmdirc.addons.ui_swing.components.statusbar.SwingStatusBar; import com.dmdirc.addons.ui_swing.dialogs.StandardQuestionDialog; import com.dmdirc.addons.ui_swing.events.SwingActiveWindowChangeRequestEvent; import com.dmdirc.addons.ui_swing.events.SwingEventBus; import com.dmdirc.addons.ui_swing.events.SwingWindowAddedEvent; import com.dmdirc.addons.ui_swing.events.SwingWindowDeletedEvent; import com.dmdirc.addons.ui_swing.events.SwingWindowSelectedEvent; import com.dmdirc.addons.ui_swing.framemanager.FrameManager; import com.dmdirc.addons.ui_swing.framemanager.FramemanagerPosition; import com.dmdirc.addons.ui_swing.framemanager.ctrltab.CtrlTabWindowManager; import com.dmdirc.addons.ui_swing.events.ClientMinimisedEvent; import com.dmdirc.addons.ui_swing.events.ClientUnminimisedEvent; import com.dmdirc.events.FrameTitleChangedEvent; import com.dmdirc.events.UnreadStatusChangedEvent; import com.dmdirc.interfaces.LifecycleController; import com.dmdirc.interfaces.config.AggregateConfigProvider; import com.dmdirc.interfaces.config.ConfigChangeListener; import com.dmdirc.interfaces.ui.Window; import com.dmdirc.ui.CoreUIUtils; import com.dmdirc.addons.ui_swing.components.IconManager; import com.dmdirc.util.collections.QueuedLinkedHashSet; import java.awt.Dialog; import java.awt.Dimension; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.Optional; import javax.inject.Provider; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import net.miginfocom.swing.MigLayout; import net.engio.mbassy.listener.Handler; import static com.dmdirc.addons.ui_swing.SwingPreconditions.checkOnEDT; import static java.util.function.Predicate.isEqual; /** * The main application frame. */ public class MainFrame extends JFrame implements WindowListener, ConfigChangeListener { /** A version number for this class. */ private static final long serialVersionUID = 9; /** Focus queue. */ private final QueuedLinkedHashSet<Optional<TextFrame>> focusOrder; /** Apple instance. */ private final Apple apple; /** Controller to use to end the program. */ private final LifecycleController lifecycleController; /** The global config to read settings from. */ private final AggregateConfigProvider globalConfig; /** The icon manager to use to get icons. */ private final IconManager iconManager; /** The quit worker to use when quitting the app. */ private final Provider<QuitWorker> quitWorker; /** Client Version. */ private final String version; /** Frame manager used for ctrl tab frame switching. */ private CtrlTabWindowManager frameManager; /** Provider of frame managers. */ private final Provider<FrameManager> frameManagerProvider; /** The bus to despatch events on. */ private final DMDircMBassador eventBus; /** Swing event bus to post events to. */ private final SwingEventBus swingEventBus; /** The main application icon. */ private ImageIcon imageIcon; /** The frame manager that's being used. */ private FrameManager mainFrameManager; /** Active frame. */ private Optional<TextFrame> activeFrame; /** Panel holding frame. */ private JPanel framePanel; /** Main panel. */ private JPanel frameManagerPanel; /** Frame manager position. */ private FramemanagerPosition position; /** Show version? */ private boolean showVersion; /** Exit code. */ private int exitCode; /** Status bar. */ private SwingStatusBar statusBar; /** Main split pane. */ private SplitPane mainSplitPane; /** Are we quitting or closing? */ private boolean quitting; /** Have we initialised our settings and listeners? */ private boolean initDone; /** * Creates new form MainFrame. * * @param apple Apple instance * @param lifecycleController Controller to use to end the application. * @param globalConfig The config to read settings from. * @param quitWorker The quit worker to use when quitting the app. * @param iconManager The icon manager to use to get icons. * @param frameManagerProvider Provider to use to retrieve frame managers. * @param eventBus The event bus to post events to. * @param swingEventBus The event bus to post swing events to. */ public MainFrame( final Apple apple, final LifecycleController lifecycleController, final AggregateConfigProvider globalConfig, final Provider<QuitWorker> quitWorker, final IconManager iconManager, final Provider<FrameManager> frameManagerProvider, final DMDircMBassador eventBus, final SwingEventBus swingEventBus) { checkOnEDT(); this.apple = apple; this.lifecycleController = lifecycleController; this.globalConfig = globalConfig; this.quitWorker = quitWorker; this.iconManager = iconManager; this.frameManagerProvider = frameManagerProvider; this.eventBus = eventBus; this.swingEventBus = swingEventBus; activeFrame = Optional.empty(); version = globalConfig.getOption("version", "version"); focusOrder = new QueuedLinkedHashSet<>(); } @Override public void setVisible(final boolean visible) { if (!initDone) { swingEventBus.subscribe(this); imageIcon = new ImageIcon(iconManager.getImage("icon")); setIconImage(imageIcon.getImage()); CoreUIUtils.centreWindow(this); addWindowListener(this); showVersion = globalConfig.getOptionBool("ui", "showversion"); globalConfig.addChangeListener("ui", "showversion", this); globalConfig.addChangeListener("ui", "framemanager", this); globalConfig.addChangeListener("ui", "framemanagerPosition", this); globalConfig.addChangeListener("icon", "icon", this); addWindowFocusListener(new EventTriggeringFocusListener(eventBus)); setTitle(getTitlePrefix()); initDone = true; } super.setVisible(visible); } /** * Returns the size of the frame manager. * * @return Frame manager size. */ public int getFrameManagerSize() { if (position == FramemanagerPosition.LEFT || position == FramemanagerPosition.RIGHT) { return frameManagerPanel.getWidth(); } else { return frameManagerPanel.getHeight(); } } @Override public MenuBar getJMenuBar() { return (MenuBar) super.getJMenuBar(); } @Override public void setTitle(final String title) { UIUtilities.invokeLater(() -> { if (title == null || !activeFrame.isPresent()) { MainFrame.super.setTitle(getTitlePrefix()); } else { MainFrame.super.setTitle(getTitlePrefix() + " - " + title); } }); } /** * Gets the string which should be prefixed to this frame's title. * * @return This frame's title prefix */ private String getTitlePrefix() { return "DMDirc" + (showVersion ? ' ' + version : ""); } @Override public void windowOpened(final WindowEvent windowEvent) { //ignore } @Override public void windowClosing(final WindowEvent windowEvent) { quit(exitCode); } @Override public void windowClosed(final WindowEvent windowEvent) { UIUtilities.invokeOffEDTNoLogging(() -> lifecycleController.quit(exitCode)); } @Override public void windowIconified(final WindowEvent windowEvent) { eventBus.publishAsync(new ClientMinimisedEvent()); } @Override public void windowDeiconified(final WindowEvent windowEvent) { eventBus.publishAsync(new ClientUnminimisedEvent()); } @Override public void windowActivated(final WindowEvent windowEvent) { //ignore } @Override public void windowDeactivated(final WindowEvent windowEvent) { //ignore } /** Initialiases the frame managers. */ private void initFrameManagers() { UIUtilities.invokeAndWait(() -> { frameManagerPanel.removeAll(); if (mainFrameManager != null) { swingEventBus.unsubscribe(mainFrameManager); } mainFrameManager = frameManagerProvider.get(); mainFrameManager.setParent(frameManagerPanel); swingEventBus.subscribe(mainFrameManager); }); } /** * Initialises the components for this frame. */ public void initComponents() { UIUtilities.invokeAndWait(() -> { frameManagerPanel = new JPanel(); activeFrame = Optional.empty(); framePanel = new JPanel(new MigLayout("fill, ins 0")); initFrameManagers(); mainSplitPane = initSplitPane(); setPreferredSize(new Dimension(800, 600)); getContentPane().setLayout(new MigLayout( "fill, ins rel, wrap 1, hidemode 2")); layoutComponents(); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); pack(); }); } /** * Sets the menu bar that this frame will use. * * <p> * Must be called prior to {@link #initComponents()}. * * @param menuBar The menu bar to use. */ public void setMenuBar(final MenuBar menuBar) { UIUtilities.invokeAndWait(() -> { apple.setMenuBar(menuBar); setJMenuBar(menuBar); }); } /** * Sets the window manager that this frame will use. * * <p> * Must be called prior to {@link #initComponents()}. * * @param windowManager The window manager to use. */ public void setWindowManager(final CtrlTabWindowManager windowManager) { this.frameManager = windowManager; } /** * Sets the status bar that will be used. * * <p> * Must be called prior to {@link #initComponents()}. * * @param statusBar The status bar to be used. */ public void setStatusBar(final SwingStatusBar statusBar) { this.statusBar = statusBar; } /** * Lays out the this component. */ private void layoutComponents() { getContentPane().add(mainSplitPane, "grow, push"); getContentPane().add(statusBar, "wmax 100%-2*rel, " + "wmin 100%-2*rel, south, gap rel rel 0 rel"); } /** * Initialises the split pane. * * @return Returns the initialised split pane */ private SplitPane initSplitPane() { final SplitPane splitPane = new SplitPane(globalConfig, SplitPane.Orientation.HORIZONTAL); position = FramemanagerPosition.getPosition( globalConfig.getOption("ui", "framemanagerPosition")); if (position == FramemanagerPosition.UNKNOWN) { position = FramemanagerPosition.LEFT; } if (!mainFrameManager.canPositionVertically() && (position == FramemanagerPosition.LEFT || position == FramemanagerPosition.RIGHT)) { position = FramemanagerPosition.BOTTOM; } if (!mainFrameManager.canPositionHorizontally() && (position == FramemanagerPosition.TOP || position == FramemanagerPosition.BOTTOM)) { position = FramemanagerPosition.LEFT; } switch (position) { case TOP: splitPane.setTopComponent(frameManagerPanel); splitPane.setBottomComponent(framePanel); splitPane.setResizeWeight(0.0); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( Integer.MAX_VALUE, globalConfig.getOptionInt("ui", "frameManagerSize"))); break; case LEFT: splitPane.setLeftComponent(frameManagerPanel); splitPane.setRightComponent(framePanel); splitPane.setResizeWeight(0.0); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( globalConfig.getOptionInt("ui", "frameManagerSize"), Integer.MAX_VALUE)); break; case BOTTOM: splitPane.setTopComponent(framePanel); splitPane.setBottomComponent(frameManagerPanel); splitPane.setResizeWeight(1.0); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( Integer.MAX_VALUE, globalConfig.getOptionInt("ui", "frameManagerSize"))); break; case RIGHT: splitPane.setLeftComponent(framePanel); splitPane.setRightComponent(frameManagerPanel); splitPane.setResizeWeight(1.0); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); frameManagerPanel.setPreferredSize(new Dimension( globalConfig.getOptionInt("ui", "frameManagerSize"), Integer.MAX_VALUE)); break; default: break; } return splitPane; } /** * Exits with an "OK" status code. */ public void quit() { quit(0); } /** * Exit code call to quit. * * @param exitCode Exit code */ public void quit(final int exitCode) { if (exitCode == 0 && globalConfig.getOptionBool("ui", "confirmQuit")) { new StandardQuestionDialog(this, Dialog.ModalityType.APPLICATION_MODAL, "Quit confirm", "You are about to quit DMDirc, are you sure?", () -> { doQuit(0); return true;}).display(); return; } doQuit(exitCode); } /** * Exit code call to quit. * * @param exitCode Exit code */ public void doQuit(final int exitCode) { this.exitCode = exitCode; quitting = true; quitWorker.get().execute(); } @Override public void configChanged(final String domain, final String key) { if ("ui".equals(domain)) { switch (key) { case "framemanager": case "framemanagerPosition": UIUtilities.invokeAndWait(() -> { setVisible(false); getContentPane().remove(mainSplitPane); initFrameManagers(); getContentPane().removeAll(); layoutComponents(); setVisible(true); }); break; default: showVersion = globalConfig.getOptionBool("ui", "showversion"); break; } } else { imageIcon = new ImageIcon(iconManager.getImage("icon")); UIUtilities.invokeLater(() -> setIconImage(imageIcon.getImage())); } } @Handler(invocation = EdtHandlerInvocation.class) public void setActiveFrame(final SwingActiveWindowChangeRequestEvent event) { focusOrder.offerAndMove(activeFrame); framePanel.setVisible(false); framePanel.removeAll(); activeFrame = event.getWindow(); if (activeFrame.isPresent()) { framePanel.add(activeFrame.get().getDisplayFrame(), "grow"); setTitle(activeFrame.get().getContainer().getTitle()); activeFrame.get().getContainer().getUnreadStatusManager().clearStatus(); } else { framePanel.add(new JPanel(), "grow"); setTitle(null); } framePanel.setVisible(true); if (activeFrame.isPresent()) { final TextFrame textFrame = activeFrame.get(); textFrame.requestFocus(); textFrame.requestFocusInWindow(); textFrame.activateFrame(); } swingEventBus.publish(new SwingWindowSelectedEvent(activeFrame)); } @Handler public void doWindowAdded(final SwingWindowAddedEvent event) { if (!activeFrame.isPresent()) { setActiveFrame(new SwingActiveWindowChangeRequestEvent( Optional.of(event.getChildWindow()))); } } @Handler public void doWindowDeleted(final SwingWindowDeletedEvent event) { final Optional<TextFrame> window = Optional.of(event.getChildWindow()); focusOrder.remove(window); if (activeFrame.equals(window)) { activeFrame = Optional.empty(); framePanel.setVisible(false); framePanel.removeAll(); framePanel.setVisible(true); if (focusOrder.peek() == null) { SwingUtilities.invokeLater(frameManager::scrollUp); } else { setActiveFrame(new SwingActiveWindowChangeRequestEvent(focusOrder.peek())); } } } @Handler public void titleChanged(final FrameTitleChangedEvent event) { activeFrame.map(Window::getContainer) .filter(isEqual(event.getContainer())) .ifPresent(c -> setTitle(event.getTitle())); } @Handler public void unreadStatusChanged(final UnreadStatusChangedEvent event) { activeFrame.map(Window::getContainer) .filter(isEqual(event.getSource())) .ifPresent(c -> event.getManager().clearStatus()); } @Override public void dispose() { if (!quitting) { removeWindowListener(this); } globalConfig.removeListener(this); super.dispose(); } }
package edu.washington.escience.myria.operator; import java.util.LinkedList; import java.util.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.TupleBatch; /** * Unions the output of a set of operators without eliminating duplicates. * */ public final class UnionAll extends NAryOperator { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * List of children that have not yet returned EOS. */ private transient LinkedList<Operator> childrenWithData; /** * @param children the children to be united. * */ public UnionAll(final Operator[] children) { super(children); } @Override protected void cleanup() throws DbException { } @Override protected TupleBatch fetchNextReady() throws DbException { /* * If this variable gets to 0, it means that we've checked every child that could have data and none currently do. * At that point, we return null and sleep until one of those children gets data. */ int uncheckedChildren = childrenWithData.size(); while (!childrenWithData.isEmpty()) { if (uncheckedChildren == 0) { return null; } uncheckedChildren Operator child = childrenWithData.removeFirst(); if (child.eos()) { continue; } TupleBatch tb = child.nextReady(); if (!child.eos()) { childrenWithData.addLast(child); } if (tb != null) { return tb; } } return null; } @Override public void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { final Operator[] children = Objects.requireNonNull(getChildren()); Preconditions.checkArgument(children.length > 0); childrenWithData = new LinkedList<Operator>(); for (Operator child : getChildren()) { Preconditions.checkNotNull(child); Preconditions.checkArgument(getSchema().equals(child.getSchema())); childrenWithData.add(child); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mtrn.form; import erp.client.SClientInterface; import erp.data.SDataConstants; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.lib.SLibUtilities; import erp.lib.form.SFormField; import erp.lib.form.SFormUtilities; import erp.lib.form.SFormValidation; import erp.mfin.data.SDataAccount; import erp.mfin.data.SDataCostCenter; import erp.mfin.data.SFinUtilities; import erp.mfin.form.SPanelAccount; import erp.mtrn.data.SDataDps; import erp.mtrn.data.SDataDpsEntry; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JOptionPane; public class SDialogUpdateDpsAccountCenterCost extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener { private erp.client.SClientInterface miClient; private int mnFormResult; private int mnFormStatus; private boolean mbFirstTime; private java.util.Vector<erp.lib.form.SFormField> mvFields; private erp.mtrn.data.SDataDps moDps; private erp.mtrn.data.SDataDpsEntry moDpsEntry; private erp.mtrn.form.SPanelDps moPanelDps; private erp.mfin.form.SPanelAccount moPanelAccountOldId; private erp.mfin.form.SPanelAccount moPanelCostCenterOldId_n; private erp.mfin.form.SPanelAccount moPanelAccountNewId; private erp.mfin.form.SPanelAccount moPanelCostCenterNewId_n; private SDataAccount moAccountNew; private SDataCostCenter moCostCenterNew; /** Creates new form SDialogUpdateDpsAccountCenterCost * @param client */ public SDialogUpdateDpsAccountCenterCost(erp.client.SClientInterface client) { super(client.getFrame(), true); miClient = client; initComponents(); initComponentsExtra(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jpDps = new javax.swing.JPanel(); jlPanelDps = new javax.swing.JLabel(); jpDpsComms = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jPanel48 = new javax.swing.JPanel(); jlItem = new javax.swing.JLabel(); jtfItem = new javax.swing.JTextField(); jlDummy = new javax.swing.JLabel(); jlOriginalQuantity = new javax.swing.JLabel(); jtfOriginalQuantity = new javax.swing.JTextField(); jtfOriginalUnitSymbolRo = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jpPanelAccountsOld = new javax.swing.JPanel(); jlDummyAccountOld = new javax.swing.JLabel(); jlDummyCostCenterOld_n = new javax.swing.JLabel(); jpPanelAccountsNew = new javax.swing.JPanel(); jlDummyAccountNew = new javax.swing.JLabel(); jlDummyCostCenterNew_n = new javax.swing.JLabel(); jpControls = new javax.swing.JPanel(); jbOk = new javax.swing.JButton(); jbCancel = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Modificación de contabilización"); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jpDps.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:")); jpDps.setLayout(new java.awt.BorderLayout()); jlPanelDps.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jlPanelDps.setText("[Panel de documento de compras-ventas]"); jlPanelDps.setPreferredSize(new java.awt.Dimension(100, 200)); jpDps.add(jlPanelDps, java.awt.BorderLayout.NORTH); jpDpsComms.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos adicionales:")); jpDpsComms.setLayout(new java.awt.BorderLayout(0, 5)); jPanel1.setLayout(new java.awt.GridLayout(1, 1, 5, 1)); jPanel48.setPreferredSize(new java.awt.Dimension(108, 23)); jPanel48.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 0)); jlItem.setText("Ítem:"); jlItem.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel48.add(jlItem); jtfItem.setEditable(false); jtfItem.setText("ITEM"); jtfItem.setFocusable(false); jtfItem.setPreferredSize(new java.awt.Dimension(277, 23)); jPanel48.add(jtfItem); jlDummy.setPreferredSize(new java.awt.Dimension(5, 23)); jPanel48.add(jlDummy); jlOriginalQuantity.setText("Cantidad:"); jlOriginalQuantity.setPreferredSize(new java.awt.Dimension(150, 23)); jPanel48.add(jlOriginalQuantity); jtfOriginalQuantity.setEditable(false); jtfOriginalQuantity.setHorizontalAlignment(javax.swing.JTextField.TRAILING); jtfOriginalQuantity.setText("0.0000"); jtfOriginalQuantity.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel48.add(jtfOriginalQuantity); jtfOriginalUnitSymbolRo.setEditable(false); jtfOriginalUnitSymbolRo.setText("UN"); jtfOriginalUnitSymbolRo.setFocusable(false); jtfOriginalUnitSymbolRo.setPreferredSize(new java.awt.Dimension(65, 23)); jPanel48.add(jtfOriginalUnitSymbolRo); jPanel1.add(jPanel48); jpDpsComms.add(jPanel1, java.awt.BorderLayout.NORTH); jPanel2.setLayout(new java.awt.GridLayout(1, 1)); jpPanelAccountsOld.setBorder(javax.swing.BorderFactory.createTitledBorder("Contabilización actual:")); jpPanelAccountsOld.setLayout(new java.awt.GridLayout(2, 1, 0, 1)); jlDummyAccountOld.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jlDummyAccountOld.setText("[Panel cuenta contable actual]"); jlDummyAccountOld.setPreferredSize(new java.awt.Dimension(100, 50)); jpPanelAccountsOld.add(jlDummyAccountOld); jlDummyCostCenterOld_n.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jlDummyCostCenterOld_n.setText("[Panel centro costo-beneficio actual]"); jlDummyCostCenterOld_n.setPreferredSize(new java.awt.Dimension(100, 50)); jpPanelAccountsOld.add(jlDummyCostCenterOld_n); jPanel2.add(jpPanelAccountsOld); jpPanelAccountsNew.setBorder(javax.swing.BorderFactory.createTitledBorder("Contabilización nueva:")); jpPanelAccountsNew.setLayout(new java.awt.GridLayout(2, 1, 0, 1)); jlDummyAccountNew.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jlDummyAccountNew.setText("[Panel cuenta contable nueva]"); jlDummyAccountNew.setPreferredSize(new java.awt.Dimension(100, 50)); jpPanelAccountsNew.add(jlDummyAccountNew); jlDummyCostCenterNew_n.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jlDummyCostCenterNew_n.setText("[Panel centro costo-beneficio nueva]"); jlDummyCostCenterNew_n.setPreferredSize(new java.awt.Dimension(100, 50)); jpPanelAccountsNew.add(jlDummyCostCenterNew_n); jPanel2.add(jpPanelAccountsNew); jpDpsComms.add(jPanel2, java.awt.BorderLayout.CENTER); jpDps.add(jpDpsComms, java.awt.BorderLayout.CENTER); getContentPane().add(jpDps, java.awt.BorderLayout.CENTER); jpControls.setPreferredSize(new java.awt.Dimension(392, 33)); jpControls.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); jbOk.setText("Aceptar"); jbOk.setToolTipText("[Ctrl + Enter]"); jbOk.setPreferredSize(new java.awt.Dimension(75, 23)); jpControls.add(jbOk); jbCancel.setText("Cancelar"); jbCancel.setToolTipText("[Escape]"); jpControls.add(jbCancel); getContentPane().add(jpControls, java.awt.BorderLayout.PAGE_END); setSize(new java.awt.Dimension(900, 500)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated windowActivated(); }//GEN-LAST:event_formWindowActivated private void initComponentsExtra() { mvFields = new java.util.Vector<erp.lib.form.SFormField>(); try { moPanelDps = new SPanelDps(miClient, ""); moPanelAccountOldId = new SPanelAccount(miClient, SDataConstants.FIN_ACC, false, true, false); moPanelCostCenterOldId_n = new SPanelAccount(miClient, SDataConstants.FIN_CC, false, false, false); moPanelAccountNewId = new SPanelAccount(miClient, SDataConstants.FIN_ACC, false, true, false); moPanelCostCenterNewId_n = new SPanelAccount(miClient, SDataConstants.FIN_CC, false, false, false); } catch (Exception e) { SLibUtilities.renderException(this, e); } jpDps.remove(jlPanelDps); jpDps.add(moPanelDps, BorderLayout.NORTH); jpPanelAccountsOld.remove(jlDummyAccountOld); jpPanelAccountsOld.remove(jlDummyCostCenterOld_n); jpPanelAccountsOld.add(moPanelAccountOldId); jpPanelAccountsOld.add(moPanelCostCenterOldId_n); jpPanelAccountsNew.remove(jlDummyAccountNew); jpPanelAccountsNew.remove(jlDummyCostCenterNew_n); jpPanelAccountsNew.add(moPanelAccountNewId); jpPanelAccountsNew.add(moPanelCostCenterNewId_n); jbOk.addActionListener(this); jbCancel.addActionListener(this); AbstractAction actionOk = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { actionOk(); } }; SFormUtilities.putActionMap(getRootPane(), actionOk, "ok", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK); AbstractAction actionCancel = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { actionCancel(); } }; SFormUtilities.putActionMap(getRootPane(), actionCancel, "cancel", KeyEvent.VK_ESCAPE, 0); } private void windowActivated() { if (mbFirstTime) { mbFirstTime = false; moPanelAccountNewId.getFieldAccount().getComponent().requestFocus(); } } private void renderItem() { jtfItem.setText(moDpsEntry.getDbmsItem()); jtfOriginalQuantity.setText(miClient.getSessionXXX().getFormatters().getDecimalsQuantityFormat().format(moDpsEntry.getOriginalQuantity())); jtfOriginalUnitSymbolRo.setText(moDpsEntry.getDbmsOriginalUnitSymbol()); } private void renderAccount(String account) { moPanelAccountOldId.getFieldAccount().setFieldValue(account); moPanelAccountOldId.refreshPanel(); moPanelAccountOldId.enableFields(false); moPanelAccountNewId.getFieldAccount().setFieldValue(account); moPanelAccountNewId.refreshPanel(); } private void renderCostCenter(String centerCost) { moPanelCostCenterOldId_n.getFieldAccount().setFieldValue(centerCost.isEmpty() ? moPanelCostCenterOldId_n.getEmptyAccountId() : centerCost); moPanelCostCenterOldId_n.refreshPanel(); moPanelCostCenterOldId_n.enableFields(false); moPanelCostCenterNewId_n.getFieldAccount().setFieldValue(centerCost.isEmpty() ? moPanelCostCenterNewId_n.getEmptyAccountId() : centerCost); moPanelCostCenterNewId_n.refreshPanel(); } private void actionOk() { SFormValidation validation = formValidate(); if (validation.getIsError()) { if (validation.getComponent() != null) { validation.getComponent().requestFocus(); } if (validation.getMessage().length() > 0) { miClient.showMsgBoxWarning(validation.getMessage()); } } else { try { if (miClient.showMsgBoxConfirm("¿Esta seguro que desea modificar la contabilización actual de la partida?") == JOptionPane.OK_OPTION) { mnFormResult = SLibConstants.FORM_RESULT_OK; //Parameters added: original quantity and subtotal to use as filter in the query: SFinUtilities.updateAccountCostCenterForDpsEntry(miClient, (int[]) moDpsEntry.getPrimaryKey(), moAccountNew.getPkAccountIdXXX(), (moCostCenterNew == null ? "" : moCostCenterNew.getPkCostCenterIdXXX()), moDpsEntry.getOriginalQuantity(), moDpsEntry.getSubtotal_r()); } this.setVisible(false); } catch (Exception e) { SLibUtilities.renderException(this, e); //print out exception was changed to render Exception, to show message to user } } } private void actionCancel() { mnFormResult = SLibConstants.FORM_RESULT_CANCEL; setVisible(false); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel48; private javax.swing.JButton jbCancel; private javax.swing.JButton jbOk; private javax.swing.JLabel jlDummy; private javax.swing.JLabel jlDummyAccountNew; private javax.swing.JLabel jlDummyAccountOld; private javax.swing.JLabel jlDummyCostCenterNew_n; private javax.swing.JLabel jlDummyCostCenterOld_n; private javax.swing.JLabel jlItem; private javax.swing.JLabel jlOriginalQuantity; private javax.swing.JLabel jlPanelDps; private javax.swing.JPanel jpControls; private javax.swing.JPanel jpDps; private javax.swing.JPanel jpDpsComms; private javax.swing.JPanel jpPanelAccountsNew; private javax.swing.JPanel jpPanelAccountsOld; private javax.swing.JTextField jtfItem; private javax.swing.JTextField jtfOriginalQuantity; private javax.swing.JTextField jtfOriginalUnitSymbolRo; // End of variables declaration//GEN-END:variables @Override public void formClearRegistry() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void formReset() { mnFormResult = SLibConstants.UNDEFINED; mnFormStatus = SLibConstants.UNDEFINED; mbFirstTime = true; moAccountNew = null; moCostCenterNew = null; moDps = null; moPanelDps.setDps(null, null); moPanelAccountOldId.resetPanel(); moPanelCostCenterOldId_n.resetPanel(); moPanelAccountNewId.resetPanel(); moPanelCostCenterNewId_n.resetPanel(); for (SFormField field : mvFields) { field.resetField(); } } @Override public void formRefreshCatalogues() { } @Override public erp.lib.form.SFormValidation formValidate() { SDataAccount accountMajor = null; SFormValidation validation = new SFormValidation(); String message = ""; for (SFormField field : mvFields) { if (!field.validateField()) { validation.setIsError(true); validation.setComponent(field.getComponent()); } } moAccountNew = moPanelAccountNewId.getCurrentInputAccount(); moCostCenterNew = moPanelCostCenterNewId_n.getCurrentInputCostCenter(); if (!validation.getIsError()) { // Validate account: message = SDataUtilities.validateAccount(miClient, moAccountNew, null); if (message.length() > 0) { validation.setMessage(message); validation.setComponent(moPanelAccountNewId.getFieldAccount().getComponent()); } else { accountMajor = (SDataAccount) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.FIN_ACC, new Object[] { moAccountNew.getDbmsPkAccountMajorId() }, SLibConstants.EXEC_MODE_VERBOSE); if (accountMajor.getIsRequiredCostCenter() && moCostCenterNew == null) { validation.setMessage("La cuenta contable ('" + moAccountNew.getAccount() + "') tiene un inconveniente:\nRequiere centro de costos y no está definido."); validation.setComponent(moPanelCostCenterNewId_n.getFieldAccount().getComponent()); } } } if (!validation.getIsError()) { // Validate cost center: if (moCostCenterNew != null) { message = SDataUtilities.validateCostCenter(miClient, moCostCenterNew, null); if (message.length() > 0) { validation.setMessage(message); validation.setComponent(moPanelCostCenterNewId_n.getFieldAccount().getComponent()); } } } return validation; } @Override public void setFormStatus(int status) { mnFormStatus = status; } @Override public void setFormVisible(boolean visible) { setVisible(visible); } @Override public int getFormStatus() { return mnFormStatus; } @Override public int getFormResult() { return mnFormResult; } @Override public void setRegistry(erp.lib.data.SDataRegistry registry) { throw new UnsupportedOperationException("Not supported yet."); } @Override public erp.lib.data.SDataRegistry getRegistry() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setValue(int type, java.lang.Object value) { switch (type) { case SDataConstants.TRN_DPS: moDps = (SDataDps) SDataUtilities.readRegistry(miClient, SDataConstants.TRN_DPS, value, SLibConstants.EXEC_MODE_VERBOSE); moPanelDps.setDps(moDps, null); break; case SDataConstants.TRN_DPS_ETY: moDpsEntry = (SDataDpsEntry) SDataUtilities.readRegistry(miClient, SDataConstants.TRN_DPS_ETY, value, SLibConstants.EXEC_MODE_VERBOSE); renderItem(); break; case SDataConstants.FIN_ACC: renderAccount(((String[]) value)[0]); renderCostCenter(((String[]) value)[1]); break; default: } } @Override public java.lang.Object getValue(int type) { throw new UnsupportedOperationException("Not supported yet."); } @Override public javax.swing.JLabel getTimeoutLabel() { return null; } @Override public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getSource() instanceof javax.swing.JButton) { JButton button = (JButton) e.getSource(); if (button == jbOk) { actionOk(); } else if (button == jbCancel) { actionCancel(); } } } }
package org.sikuli.script; import java.io.*; import java.awt.Window; import javax.swing.JWindow; //import com.sun.awt.AWTUtilities; public class LinuxUtil implements OSUtil { public int switchApp(String appName, int winNum){ try{ String cmd[] = {"wmctrl", "-a", appName}; Debug.history("switchApp: " + appName); Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); return p.exitValue(); } catch(Exception e){ Debug.error("switchApp: " + e.toString()); return -1; } } public int switchApp(String appName){ return switchApp(appName, 0); } public int openApp(String appName){ try{ Debug.history("openApp: " + appName); String cmd[] = {"sh", "-c", "("+ appName + ") &\necho -n $!"}; Process p = Runtime.getRuntime().exec(cmd); InputStream in = p.getInputStream(); byte pidBytes[]=new byte[64]; int len=in.read(pidBytes); String pidStr=new String(pidBytes,0,len); int pid=Integer.parseInt(new String(pidStr)); p.waitFor(); return pid; //return p.exitValue(); } catch(Exception e){ Debug.error("openApp, crash: " + e.toString()); return 0; } } public int closeApp(String appName){ try{ String cmd[] = {"killall", appName}; Debug.history("closeApp: " + appName); Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); return p.exitValue(); } catch(Exception e){ Debug.error("closeApp: " + e.toString()); return -1; } } private enum SearchType { APP_NAME, WINDOW_ID, PID }; public Region getFocusedWindow(){ String cmd[] = {"xdotool", "getactivewindow"}; try { Process p = Runtime.getRuntime().exec(cmd); InputStream in = p.getInputStream(); BufferedReader bufin = new BufferedReader(new InputStreamReader(in)); String str = bufin.readLine(); long id=Integer.parseInt(str); String hexid=String.format("0x%08x",id); return findRegion(hexid,0,SearchType.WINDOW_ID); } catch(IOException e) { System.err.println("xdotool Error:"+e.toString()); return null; } } public Region getWindow(String appName){ return getWindow(appName, 0); } private Region findRegion(String appName, int winNum,SearchType type){ String[] winLine = findWindow(appName,winNum,type); if(winLine.length>=7){ int x = new Integer(winLine[3]); int y = Integer.parseInt(winLine[4]); int w = Integer.parseInt(winLine[5]); int h = Integer.parseInt(winLine[6]); Region r = new Region(x, y, w, h); return r; } return null; } private String[] findWindow(String appName, int winNum,SearchType type){ //Debug.log("findWindow: " + appName + " " + winNum + " " + type); String[] found = {}; int numFound=0; try { String cmd[] = {"wmctrl", "-lpGx"}; Process p = Runtime.getRuntime().exec(cmd); InputStream in = p.getInputStream(); BufferedReader bufin = new BufferedReader(new InputStreamReader(in)); String str; int slash=appName.lastIndexOf("/"); if(slash>=0) { // remove path: /usr/bin/.... appName=appName.substring(slash+1); } if(type==SearchType.APP_NAME) { appName=appName.toLowerCase(); } while ((str = bufin.readLine()) !=null) { //Debug.log("read: " + str); String winLine[]=str.split("\\s+"); boolean ok=false; if(type==SearchType.WINDOW_ID) { if(appName.equals(winLine[0])) { ok=true; } } else if(type==SearchType.PID) { if(appName.equals(winLine[2])) { ok=true; } } else if(type==SearchType.APP_NAME) { String pidFile="/proc/"+winLine[2]+"/status"; char buf[]=new char[1024]; FileReader pidReader=null; try { pidReader = new FileReader(pidFile); pidReader.read(buf); String pidName=new String(buf); String nameLine[]=pidName.split("[:\n]"); String name=nameLine[1].trim(); if(name.equals(appName)) { ok=true; } } catch(FileNotFoundException e) { // pid killed before we could read /proc/ } finally { if(pidReader!=null) pidReader.close(); } if(!ok && winLine[7].toLowerCase().indexOf(appName)>=0) { ok=true; } } if(ok) { if(numFound>=winNum) { //Debug.log("Found window" + winLine); found=winLine; break; } numFound++; } } in.close(); p.waitFor(); } catch(Exception e){ Debug.error("findWindow Error:"+e.toString()); return null; } return found; } public Region getWindow(String appName, int winNum){ return findRegion(appName,winNum,SearchType.APP_NAME); } public Region getWindow(int pid){ return getWindow(pid,0); } public Region getWindow(int pid, int winNum){ return findRegion(""+pid,winNum,SearchType.PID); } public int closeApp(int pid){ Debug.log(3, "close: " + pid); String winLine[]=findWindow(""+pid,0,SearchType.PID); if(winLine==null) return -1; String cmd[] = {"wmctrl", "-ic", winLine[0]}; try { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); return p.exitValue(); } catch(Exception e) { Debug.error("closeApp Error:"+e.toString()); return -1; } } public int switchApp(int pid, int num){ String winLine[]=findWindow(""+pid,num,SearchType.PID); if(winLine==null) return -1; String cmd[] = {"wmctrl", "-ia", winLine[0]}; try { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); return p.exitValue(); } catch(Exception e) { Debug.error("closeApp Error:"+e.toString()); return -1; } } public void setWindowOpacity(Window win, float alpha){ //AWTUtilities.setWindowOpacity(win, alpha); } public void setWindowOpaque(Window win, boolean opaque){ //AWTUtilities.setWindowOpaque(win, opaque); } public void bringWindowToFront(Window win, boolean ignoreMouse){} }
package eu.visualize.ini.convnet; import ch.unizh.ini.jaer.projects.util.ColorHelper; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.GLException; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.Format; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.tracking.RectangularClusterTrackerEvent; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.util.filter.ParticleFilter.DynamicEvaluator; import net.sf.jaer.util.filter.ParticleFilter.MeasurmentEvaluator; import net.sf.jaer.util.filter.ParticleFilter.ParticleFilter; import net.sf.jaer.eventprocessing.tracking.RectangularClusterTracker; import net.sf.jaer.graphics.AEFrameChipRenderer; import net.sf.jaer.util.filter.ParticleFilter.AverageEvaluator; import net.sf.jaer.util.filter.ParticleFilter.Particle; import net.sf.jaer.util.filter.ParticleFilter.SimpleParticle; /** * * @author hongjie and liu min */ @Description("Particle Filter for tracking") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class ParticleFilterTracking extends EventFilter2D implements PropertyChangeListener, FrameAnnotater { public static final String PROP_SURROUNDINHIBITIONCOST = "PROP_SURROUNDINHIBITIONCOST"; private DynamicEvaluator dynamic; private MeasurmentEvaluator measurement; private AverageEvaluator average; private ParticleFilter filter; private boolean Useframe = false; private boolean UseClustersFrametime = false; private boolean UseClustersRealtime = false; private boolean filterEventsEnabled = getBoolean("filterEventsEnabled", false); // enables filtering events so private float threshold = getFloat("threshold", 2); private int decay = getInt("decay", 1); private int startPositionX = getInt("x", 0); private int startPositionY = getInt("y", 0); private int particlesCount = getInt("particlesCount", 1000); private boolean UsePureEvents = getBoolean("UsePureEvents", false); private boolean displayParticles = getBoolean("displayParticles", false); private int eventsNumToProcess = getInt("eventsNumToProcess", 10); FilterChain trackingFilterChain; private RectangularClusterTracker tracker; private HeatMapCNN heatMapCNN; private String outputFilename; private double outputX, outputY; private List<Float> measurementLocationsX = new ArrayList<Float>(), measurementLocationsY = new ArrayList<Float>(); private List<Boolean> enableFlg = new ArrayList<Boolean>(); // enable flag for the measurement private List<Double> measurementWeight = new ArrayList<Double>(); // private final AEFrameChipRenderer renderer; public ParticleFilterTracking(AEChip chip) { super(chip); this.outputX = getStartPositionX(); this.outputY = getStartPositionY(); dynamic = new DynamicEvaluator(); measurement = new MeasurmentEvaluator(); average = new AverageEvaluator(); filter = new ParticleFilter(dynamic, measurement, average); Random r = new Random(); for(int i = 0; i < particlesCount; i++) { // double x = (chip.getSizeX()/2) * (r.nextDouble()*2 - 1) + chip.getSizeX()/2; // double y = (chip.getSizeX()/2) * (r.nextDouble()*2 - 1) + chip.getSizeX()/2; double x = r.nextGaussian() + getStartPositionX(); double y = r.nextGaussian() + getStartPositionY(); filter.addParticle(new SimpleParticle(x, y)); } tracker = new RectangularClusterTracker(chip); heatMapCNN = new HeatMapCNN(chip); trackingFilterChain = new FilterChain(chip); trackingFilterChain.add(tracker); trackingFilterChain.add(heatMapCNN); tracker.setFilterEnabled(false); tracker.setEnclosed(true, this); this.heatMapCNN.setTracker(this); heatMapCNN.getSupport().addPropertyChangeListener(HeatMapCNN.OUTPUT_AVAILBLE, this); setEnclosedFilterChain(trackingFilterChain); // Save the result to the file Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss"); // Instantiate a Date object Date date = new Date(); outputFilename = "PF_Output_Location" + formatter.format(date); setPropertyTooltip("colorClustersDifferentlyEnabled", "each cluster gets assigned a random color, otherwise color indicates ages."); setPropertyTooltip("threshold", "The resample threshold"); setPropertyTooltip("displayParticles", "Display all the particles"); setPropertyTooltip("startPositionX", "Particles start position x"); setPropertyTooltip("startPositionY", "Particles start position y"); setPropertyTooltip("UsePureEvents", "Only use events"); setPropertyTooltip("eventsNumToProcess", "The events in the packet will be processed"); // setPropertyTooltip("filterEventsEnabled", "Just for test"); } @Override public EventPacket<?> filterPacket(EventPacket<?> in) { if (!filterEnabled) { return in; } if(in.size == 0) { // Empty packet return in; } EventPacket filtered = getEnclosedFilterChain().filterPacket(in); if (in instanceof ApsDvsEventPacket) { checkOutputPacketEventType(in); // make sure memory is allocated to avoid leak } else if (isFilterEventsEnabled()) { checkOutputPacketEventType(RectangularClusterTrackerEvent.class); } // updated at every income event, notice: compuatation very expensive. if(UsePureEvents) { // Clear the measurement list first measurementLocationsX.removeAll(measurementLocationsX); measurementLocationsY.removeAll(measurementLocationsY); enableFlg.removeAll(enableFlg); measurementWeight.removeAll(measurementWeight); int numProcessEvents = eventsNumToProcess; if(eventsNumToProcess > in.getSize()) { numProcessEvents = in.getSize(); } for(int nCnt = 0; nCnt < numProcessEvents; nCnt++) { if(measurementLocationsX.size() <= 0) { measurementLocationsX.add(0, (float)in.getEvent(nCnt).getX()); measurementLocationsY.add(0, (float)in.getEvent(nCnt).getY()); enableFlg.add(0, true); measurementWeight.add(0, 1.0); } else { measurementLocationsX.set(0, (float)in.getEvent(nCnt).getX()); measurementLocationsY.set(0, (float)in.getEvent(nCnt).getY()); enableFlg.set(0, true); measurementWeight.set(0, 1.0); } Random r = new Random(); filterProcess(); outputX = filter.getAverageX(); outputY = filter.getAverageY(); if(outputX > 240 || outputY > 180 || outputX < 0 || outputY < 0) { for(int i = 0; i < filter.getParticleCount(); i++) { filter.get(i).setX(120 + 50 * (r.nextDouble() * 2 - 1)); filter.get(i).setY(90 + 50 * (r.nextDouble() * 2 - 1)); } } } return in; } int i = 0, visibleCnt = 0; int numMeasure = 0; if(tracker.isFilterEnabled()) { for (RectangularClusterTracker.Cluster c : tracker.getClusters()) { if(measurementLocationsX.size() <= i) { measurementLocationsX.add(i, c.location.x); measurementLocationsY.add(i, c.location.y); enableFlg.add(i, c.isVisible()); measurementWeight.add(1.0); } else { measurementLocationsX.set(i, c.location.x); measurementLocationsY.set(i, c.location.y); enableFlg.set(i, c.isVisible()); } i = i + 1; if(c.isVisible()) { visibleCnt = visibleCnt + 1; } } numMeasure = tracker.getMaxNumClusters(); } else { numMeasure = 0; } // If heatMap is enabled, then the number of the measurement should add 1. if(heatMapCNN.isFilterEnabled()) { if(measurementLocationsX.size() == numMeasure + 1) { measurementWeight.set(measurementWeight.size() - 1, measurementWeight.get(numMeasure)*decay); numMeasure = numMeasure + 1; } } if(measurementLocationsX.size() > numMeasure) { // We should make the size of the measurement always equal to the clusters number for(int removeCnt = measurementLocationsX.size() - 1; removeCnt >= numMeasure; removeCnt measurementLocationsX.remove(removeCnt); measurementLocationsY.remove(removeCnt); enableFlg.remove(removeCnt); measurementWeight.remove(removeCnt); } } Random r = new Random(); filterProcess(); outputX = filter.getAverageX(); outputY = filter.getAverageY(); if(outputX > 240 || outputY > 180 || outputX < 0 || outputY < 0) { for(i = 0; i < filter.getParticleCount(); i++) { filter.get(i).setX(120 + 50 * (r.nextDouble() * 2 - 1)); filter.get(i).setY(90 + 50 * (r.nextDouble() * 2 - 1)); } } try (FileWriter outFile = new FileWriter(outputFilename,true)) { outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + (int)outputX + " " + (int)outputY + "\n")); outFile.close(); } catch (IOException ex) { Logger.getLogger(ParticleFilter.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { log.warning("Caught " + e + ". See following stack trace."); e.printStackTrace(); } return in; } @Override public void resetFilter() { } @Override public void initFilter() { List<Float> xArray = new ArrayList<Float>(); List<Float> yArray = new ArrayList<Float>(); for(int i = 0; i < tracker.getMaxNumClusters(); i ++) { xArray.add((float)0); yArray.add((float)0); } measurement.setMu(xArray, yArray); } @Override public synchronized void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(HeatMapCNN.OUTPUT_AVAILBLE)) { float[] map = this.heatMapCNN.getHeatMap(); int clustersNum = 0; if(tracker.isFilterEnabled()) { clustersNum = tracker.getMaxNumClusters(); } else { measurementLocationsX.removeAll(measurementLocationsX); measurementLocationsY.removeAll(measurementLocationsY); enableFlg.removeAll(enableFlg); measurementWeight.removeAll(measurementWeight); clustersNum = 0; } if(measurementLocationsX.size() <= clustersNum) { measurementLocationsX.add((float)heatMapCNN.getOutputX()); measurementLocationsY.add((float)heatMapCNN.getOutputY()); enableFlg.add(true); measurementWeight.add(1.0); } else { measurementLocationsX.set(clustersNum, (float)heatMapCNN.getOutputX()); measurementLocationsY.set(clustersNum, (float)heatMapCNN.getOutputY()); enableFlg.set(clustersNum, true); measurementWeight.set(clustersNum, 1.0); } } } @Override public void annotate(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); try { gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glBlendEquation(GL.GL_FUNC_ADD); } catch (final GLException e) { e.printStackTrace(); } gl.glColor4f(1f, .1f, .1f, .25f); gl.glLineWidth(1f); if(displayParticles) { gl.glColor4f(.1f, 1f, .1f, .25f); for(int i = 0; i < filter.getParticleCount(); i ++) { gl.glRectd(filter.get(i).getX() - 0.5, filter.get(i).getY() - 0.5, filter.get(i).getX() + 0.5, filter.get(i).getY() + 0.5); } } gl.glColor4f(1f, .1f, .1f, .25f); gl.glRectf((int)outputX - 10, (int)outputY - 10, (int)outputX + 12, (int)outputY + 12); } public void filterProcess() { Random r = new Random(); measurement.setMu(measurementLocationsX, measurementLocationsY); measurement.setMeasurementWeight(measurementWeight); double originSum = 0; double effectiveNum = 0; // if(visibleCnt != 0) { measurement.setVisibleCluster(enableFlg); filter.evaluateStrength(); originSum = filter.normalize(); // The sum value before normalize effectiveNum = filter.calculateNeff(); if(originSum > threshold /* && effectiveNum < filter.getParticleCount() * 0.75*/) { filter.resample(r); } else { filter.updateWeight(); } } public double getOutputX() { return outputX; } public double getOutputY() { return outputY; } /** * @return the filterEventsEnabled */ public boolean isFilterEventsEnabled() { return filterEventsEnabled; } /** * @param filterEventsEnabled the filterEventsEnabled to set */ public void setFilterEventsEnabled(boolean filterEventsEnabled) { super.setFilterEnabled(false); this.filterEventsEnabled = filterEventsEnabled; putBoolean("filterEventsEnabled", filterEventsEnabled); } /** * @return the tracker */ public RectangularClusterTracker getTracker() { return tracker; } /** * @param tracker the tracker to set */ public void setTracker(RectangularClusterTracker tracker) { this.tracker = tracker; } /** * @return the startPositionX */ public int getStartPositionX() { return startPositionX; } /** * @param startPositionX the startPositionX to set */ public void setStartPositionX(int startPositionX) { putInt("x", startPositionX); this.startPositionX = startPositionX; } /** * @return the startPositionY */ public int getStartPositionY() { return startPositionY; } /** * @param startPositionY the startPositionY to set */ public void setStartPositionY(int startPositionY) { putInt("y", startPositionY); this.startPositionY = startPositionY; } /** * @return the threshold */ public float getThreshold() { return threshold; } /** * @param threshold the threshold to set */ public void setThreshold(float threshold) { putFloat("threshold", threshold); this.threshold = threshold; } public float getUseframe() { return threshold; } /** * @param Useframe the Useframe to set */ public boolean isUseframe() { return Useframe; } /** * @param Useframe the Useframe to set */ public void setUseframe(boolean Useframe) { this.Useframe = Useframe; } /** * @return the UseClustersFrametime */ public boolean isUseClustersFrametime() { return UseClustersFrametime; } /** * @param UseClustersFrametime the UseClustersFrametime to set */ public void setUseClustersFrametime(boolean UseClustersFrametime) { this.UseClustersFrametime = UseClustersFrametime; } /** * @return the UseClustersRealtime */ public boolean isUseClustersRealtime() { return UseClustersRealtime; } /** * @param UseClustersRealtime the UseClustersRealtime to set */ public void setUseClustersRealtime(boolean UseClustersRealtime) { this.UseClustersRealtime = UseClustersRealtime; } /** * @return the particlesCount */ public int getParticlesCount() { return particlesCount; } /** * @param particlesCount the particlesCount to set */ public void setParticlesCount(int particlesCount) { this.particlesCount = particlesCount; putInt("particlesCount", particlesCount); } /** * @return the UsePureEvents */ public boolean isUsePureEvents() { return UsePureEvents; } /** * @param UsePureEvents the UsePureEvents to set */ public void setUsePureEvents(boolean UsePureEvents) { this.UsePureEvents = UsePureEvents; putBoolean("UsePureEvents", UsePureEvents); } /** * @return the displayParticles */ public boolean isDisplayParticles() { return displayParticles; } /** * @param displayParticles the displayParticles to set */ public void setDisplayParticles(boolean displayParticles) { this.displayParticles = displayParticles; putBoolean("displayParticles", displayParticles); } /** * @return the decay */ public int getDecay() { return decay; } /** * @param decay the decay to set */ public void setDecay(int decay) { this.decay = decay; putInt("decay", decay); } /** * @return the eventsNumToProcess */ public int getEventsNumToProcess() { return eventsNumToProcess; } /** * @param eventsNumToProcess the eventsNumToProcess to set */ public void setEventsNumToProcess(int eventsNumToProcess) { this.eventsNumToProcess = eventsNumToProcess; putInt("eventsNumToProcess", eventsNumToProcess); } }
package github.irengrig.exploreTrace.actions; import com.intellij.codeEditor.JavaEditorFileSwapper; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.ide.highlighter.JavaClassFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packageDependencies.DefaultScopesProvider; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiMethod; import com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex; import com.intellij.psi.search.EverythingGlobalScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopes; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.util.Function; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import java.util.*; public class LineParser { private final static String ourIndent = " "; private String myLine; private String myClassName; private String myMethod; private int myLineNum; private boolean mySuccessful; private boolean myAt; private List<Pair<String, HyperlinkInfo>> myResult; private int myClassBoundary; private int myOpen; private int myClose; public LineParser(final String line) { myLine = line.trim(); myResult = new ArrayList<>(); } public void parse(final Project project) { parseImpl(); findObjectsAndFillResult(project); } private boolean parseImpl() { if (! myLine.startsWith("at ")) return true; myAt = true; myLine = myLine.substring(3); myOpen = myLine.indexOf('('); if (myOpen < 0) return true; myClose = myLine.indexOf(')', myOpen + 1); if (myClose < 0) return true; int colon = myLine.indexOf(".java:", myOpen + 1); if (colon < 0 || colon > myClose) return true; final String number = myLine.substring(colon + 6, myClose); try { myLineNum = Integer.parseInt(number); } catch (NumberFormatException e) { return true; } myClassBoundary = myLine.lastIndexOf('.', myOpen); if (myClassBoundary < 0) return true; myClassName = myLine.substring(0, myClassBoundary).trim(); myMethod = myLine.substring(myClassBoundary + 1, myOpen); mySuccessful = true; return false; } public List<Pair<String, HyperlinkInfo>> getResult() { return myResult; } private void findObjectsAndFillResult(final Project project) { if (! mySuccessful) { if (myAt) { myResult.add(Pair.<String, HyperlinkInfo>create(ourIndent + "at " + myLine, null)); } else { myResult.add(Pair.<String, HyperlinkInfo>create(ourIndent + myLine, null)); } return; } PsiClass[] result = findClasses(project); List<PsiClass> psiClasses = Arrays.asList(result); /*psiClasses = ContainerUtil.filter(psiClasses, new Condition<PsiClass>() { @Override public boolean value(final PsiClass psiClass) { return myClassName.equals(psiClass.getQualifiedName()); } });*/ final List<Pair<PsiClass, VirtualFile>> convertedFiles = new ArrayList<>(); for (PsiClass psiClass : psiClasses) { VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile(); if (virtualFile.getFileType().equals(JavaClassFileType.INSTANCE)) { VirtualFile sourceFile = JavaEditorFileSwapper.findSourceFile(project, virtualFile); if (sourceFile != null) { virtualFile = sourceFile; } } convertedFiles.add(Pair.create(psiClass, virtualFile)); } final List<Pair<VirtualFile, PsiMethod>> psiMethods = new ArrayList<>(); final Function<Pair<PsiClass, VirtualFile>, PsiMethod[]> function = getMethodsFromClass(); final Iterator<Pair<PsiClass, VirtualFile>> iterator = convertedFiles.iterator(); while (iterator.hasNext()) { final Pair<PsiClass, VirtualFile> pair = iterator.next(); PsiMethod[] methods = function.fun(pair); if (methods.length == 0) { iterator.remove(); } for (PsiMethod method : methods) { psiMethods.add(Pair.create(pair.getSecond(), method)); } } if (psiClasses.isEmpty()) { myResult.add(Pair.<String, HyperlinkInfo>create(ourIndent + "at " + myLine, null)); } else { myResult.add(Pair.<String, HyperlinkInfo>create(ourIndent + "at " + myLine.substring(0, myClassBoundary + 1), null)); myResult.add(Pair.<String, HyperlinkInfo>create(myLine.substring(myClassBoundary + 1, myOpen), new MethodHyperlinkInfo(psiMethods))); myResult.add(Pair.<String, HyperlinkInfo>create("(", null)); myResult.add(Pair.<String, HyperlinkInfo>create(myLine.substring(myOpen + 1, myClose), new MultiClassesHyperlinkInfo(convertedFiles, myLineNum))); myResult.add(Pair.<String, HyperlinkInfo>create(")", null)); } } private PsiClass[] findClasses(final Project project) { final GlobalSearchScope scope = new EverythingGlobalScope(project); JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); int idxInner = myClassName.indexOf("$"); if (idxInner > 0) { final List<PsiClass> result = new ArrayList<>(); final String outerName = myClassName.substring(0, idxInner); final String innerName = myClassName.substring(idxInner + 1); final PsiClass[] outerClasses = psiFacade.findClasses(outerName, scope); for (PsiClass outerClass : outerClasses) { final PsiClass[] inner = outerClass.getInnerClasses(); for (PsiClass psiClass : inner) { if (innerName.equals(psiClass.getName())) { result.add(psiClass); } } } return result.toArray(new PsiClass[result.size()]); } else { return psiFacade.findClasses(myClassName, scope); } } private Function<Pair<PsiClass, VirtualFile>, PsiMethod[]> getMethodsFromClass() { return new Function<Pair<PsiClass, VirtualFile>, PsiMethod[]>() { @Override public PsiMethod[] fun(final Pair<PsiClass, VirtualFile> pair) { if (myMethod.equals("<init>")) { return pair.getFirst().getConstructors(); } else { final PsiMethod[] methods = pair.getFirst().getMethods(); final List<PsiMethod> methodList = new ArrayList<>(2); for (PsiMethod psiMethod : methods) { if (myMethod.equals(psiMethod.getName())) { methodList.add(psiMethod); } } return methodList.toArray(new PsiMethod[methodList.size()]); } } }; } public String getClassName() { return myClassName; } public String getMethod() { return myMethod; } public int getLineNum() { return myLineNum; } public boolean isSuccessful() { return mySuccessful; } }
package org.jfree.chart.renderer.xy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collections; import java.util.LinkedList; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.XYToolTipGenerator; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.urls.XYURLGenerator; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; import org.jfree.util.ShapeUtilities; /** * A renderer for an {@link XYPlot} that highlights the differences between two * series. The example shown here is generated by the * <code>DifferenceChartDemo1.java</code> program included in the JFreeChart * demo collection: * <br><br> * <img src="../../../../../images/XYDifferenceRendererSample.png" * alt="XYDifferenceRendererSample.png" /> */ public class XYDifferenceRenderer extends AbstractXYItemRenderer implements XYItemRenderer, PublicCloneable { /** For serialization. */ private static final long serialVersionUID = -8447915602375584857L; /** The paint used to highlight positive differences (y(0) > y(1)). */ private transient Paint positivePaint; /** The paint used to highlight negative differences (y(0) < y(1)). */ private transient Paint negativePaint; /** Display shapes at each point? */ private boolean shapesVisible; /** The shape to display in the legend item. */ private transient Shape legendLine; /** * This flag controls whether or not the x-coordinates (in Java2D space) * are rounded to integers. When set to true, this can avoid the vertical * striping that anti-aliasing can generate. However, the rounding may not * be appropriate for output in high resolution formats (for example, * vector graphics formats such as SVG and PDF). * * @since 1.0.4 */ private boolean roundXCoordinates; /** * Creates a new renderer with default attributes. */ public XYDifferenceRenderer() { this(Color.green, Color.red, false); } /** * Creates a new renderer. * * @param positivePaint the highlight color for positive differences * (<code>null</code> not permitted). * @param negativePaint the highlight color for negative differences * (<code>null</code> not permitted). * @param shapes draw shapes? */ public XYDifferenceRenderer(Paint positivePaint, Paint negativePaint, boolean shapes) { if (positivePaint == null) { throw new IllegalArgumentException( "Null 'positivePaint' argument."); } if (negativePaint == null) { throw new IllegalArgumentException( "Null 'negativePaint' argument."); } this.positivePaint = positivePaint; this.negativePaint = negativePaint; this.shapesVisible = shapes; this.legendLine = new Line2D.Double(-7.0, 0.0, 7.0, 0.0); this.roundXCoordinates = false; } /** * Returns the paint used to highlight positive differences. * * @return The paint (never <code>null</code>). * * @see #setPositivePaint(Paint) */ public Paint getPositivePaint() { return this.positivePaint; } /** * Sets the paint used to highlight positive differences and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getPositivePaint() */ public void setPositivePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.positivePaint = paint; fireChangeEvent(); } /** * Returns the paint used to highlight negative differences. * * @return The paint (never <code>null</code>). * * @see #setNegativePaint(Paint) */ public Paint getNegativePaint() { return this.negativePaint; } /** * Sets the paint used to highlight negative differences. * * @param paint the paint (<code>null</code> not permitted). * * @see #getNegativePaint() */ public void setNegativePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.negativePaint = paint; notifyListeners(new RendererChangeEvent(this)); } /** * Returns a flag that controls whether or not shapes are drawn for each * data value. * * @return A boolean. * * @see #setShapesVisible(boolean) */ public boolean getShapesVisible() { return this.shapesVisible; } /** * Sets a flag that controls whether or not shapes are drawn for each * data value, and sends a {@link RendererChangeEvent} to all registered * listeners. * * @param flag the flag. * * @see #getShapesVisible() */ public void setShapesVisible(boolean flag) { this.shapesVisible = flag; fireChangeEvent(); } /** * Returns the shape used to represent a line in the legend. * * @return The legend line (never <code>null</code>). * * @see #setLegendLine(Shape) */ public Shape getLegendLine() { return this.legendLine; } /** * Sets the shape used as a line in each legend item and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param line the line (<code>null</code> not permitted). * * @see #getLegendLine() */ public void setLegendLine(Shape line) { if (line == null) { throw new IllegalArgumentException("Null 'line' argument."); } this.legendLine = line; fireChangeEvent(); } /** * Returns the flag that controls whether or not the x-coordinates (in * Java2D space) are rounded to integer values. * * @return The flag. * * @since 1.0.4 * * @see #setRoundXCoordinates(boolean) */ public boolean getRoundXCoordinates() { return this.roundXCoordinates; } /** * Sets the flag that controls whether or not the x-coordinates (in * Java2D space) are rounded to integer values, and sends a * {@link RendererChangeEvent} to all registered listeners. * * @param round the new flag value. * * @since 1.0.4 * * @see #getRoundXCoordinates() */ public void setRoundXCoordinates(boolean round) { this.roundXCoordinates = round; fireChangeEvent(); } /** * Initialises the renderer and returns a state object that should be * passed to subsequent calls to the drawItem() method. This method will * be called before the first item is rendered, giving the renderer an * opportunity to initialise any state information it wants to maintain. * The renderer can do nothing if it chooses. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param plot the plot. * @param data the data. * @param info an optional info collection object to return data back to * the caller. * * @return A state object. */ public XYItemRendererState initialise(Graphics2D g2, Rectangle2D dataArea, XYPlot plot, XYDataset data, PlotRenderingInfo info) { XYItemRendererState state = super.initialise(g2, dataArea, plot, data, info); state.setProcessVisibleItemsOnly(false); return state; } /** * Returns <code>2</code>, the number of passes required by the renderer. * The {@link XYPlot} will run through the dataset this number of times. * * @return The number of passes required by the renderer. */ public int getPassCount() { return 2; } /** * Draws the visual representation of a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain (horizontal) axis. * @param rangeAxis the range (vertical) axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (pass == 0) { drawItemPass0(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState); } else if (pass == 1) { drawItemPass1(g2, dataArea, info, plot, domainAxis, rangeAxis, dataset, series, item, crosshairState); } } /** * Draws the visual representation of a single data item, first pass. * * @param x_graphics the graphics device. * @param x_dataArea the area within which the data is being drawn. * @param x_info collects information about the drawing. * @param x_plot the plot (can be used to obtain standard color * information etc). * @param x_domainAxis the domain (horizontal) axis. * @param x_rangeAxis the range (vertical) axis. * @param x_dataset the dataset. * @param x_series the series index (zero-based). * @param x_item the item index (zero-based). * @param x_crosshairState crosshair information for the plot * (<code>null</code> permitted). */ protected void drawItemPass0(Graphics2D x_graphics, Rectangle2D x_dataArea, PlotRenderingInfo x_info, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, XYDataset x_dataset, int x_series, int x_item, CrosshairState x_crosshairState) { if (!((0 == x_series) && (0 == x_item))) { return; } boolean b_impliedZeroSubtrahend = (1 == x_dataset.getSeriesCount()); // check if either series is a degenerate case (i.e. less than 2 points) if (isEitherSeriesDegenerate(x_dataset, b_impliedZeroSubtrahend)) { return; } // check if series are disjoint (i.e. domain-spans do not overlap) if (!b_impliedZeroSubtrahend && areSeriesDisjoint(x_dataset)) { return; } // polygon definitions LinkedList l_minuendXs = new LinkedList(); LinkedList l_minuendYs = new LinkedList(); LinkedList l_subtrahendXs = new LinkedList(); LinkedList l_subtrahendYs = new LinkedList(); LinkedList l_polygonXs = new LinkedList(); LinkedList l_polygonYs = new LinkedList(); // state int l_minuendItem = 0; int l_minuendItemCount = x_dataset.getItemCount(0); Double l_minuendCurX = null; Double l_minuendNextX = null; Double l_minuendCurY = null; Double l_minuendNextY = null; double l_minuendMaxY = Double.NEGATIVE_INFINITY; double l_minuendMinY = Double.POSITIVE_INFINITY; int l_subtrahendItem = 0; int l_subtrahendItemCount = 0; // actual value set below Double l_subtrahendCurX = null; Double l_subtrahendNextX = null; Double l_subtrahendCurY = null; Double l_subtrahendNextY = null; double l_subtrahendMaxY = Double.NEGATIVE_INFINITY; double l_subtrahendMinY = Double.POSITIVE_INFINITY; // if a subtrahend is not specified, assume it is zero if (b_impliedZeroSubtrahend) { l_subtrahendItem = 0; l_subtrahendItemCount = 2; l_subtrahendCurX = new Double(x_dataset.getXValue(0, 0)); l_subtrahendNextX = new Double(x_dataset.getXValue(0, (l_minuendItemCount - 1))); l_subtrahendCurY = new Double(0.0); l_subtrahendNextY = new Double(0.0); l_subtrahendMaxY = 0.0; l_subtrahendMinY = 0.0; l_subtrahendXs.add(l_subtrahendCurX); l_subtrahendYs.add(l_subtrahendCurY); } else { l_subtrahendItemCount = x_dataset.getItemCount(1); } boolean b_minuendDone = false; boolean b_minuendAdvanced = true; boolean b_minuendAtIntersect = false; boolean b_minuendFastForward = false; boolean b_subtrahendDone = false; boolean b_subtrahendAdvanced = true; boolean b_subtrahendAtIntersect = false; boolean b_subtrahendFastForward = false; boolean b_colinear = false; boolean b_positive; // coordinate pairs double l_x1 = 0.0, l_y1 = 0.0; // current minuend point double l_x2 = 0.0, l_y2 = 0.0; // next minuend point double l_x3 = 0.0, l_y3 = 0.0; // current subtrahend point double l_x4 = 0.0, l_y4 = 0.0; // next subtrahend point // fast-forward through leading tails boolean b_fastForwardDone = false; while (!b_fastForwardDone) { // get the x and y coordinates l_x1 = x_dataset.getXValue(0, l_minuendItem); l_y1 = x_dataset.getYValue(0, l_minuendItem); l_x2 = x_dataset.getXValue(0, l_minuendItem + 1); l_y2 = x_dataset.getYValue(0, l_minuendItem + 1); l_minuendCurX = new Double(l_x1); l_minuendCurY = new Double(l_y1); l_minuendNextX = new Double(l_x2); l_minuendNextY = new Double(l_y2); if (b_impliedZeroSubtrahend) { l_x3 = l_subtrahendCurX.doubleValue(); l_y3 = l_subtrahendCurY.doubleValue(); l_x4 = l_subtrahendNextX.doubleValue(); l_y4 = l_subtrahendNextY.doubleValue(); } else { l_x3 = x_dataset.getXValue(1, l_subtrahendItem); l_y3 = x_dataset.getYValue(1, l_subtrahendItem); l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1); l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1); l_subtrahendCurX = new Double(l_x3); l_subtrahendCurY = new Double(l_y3); l_subtrahendNextX = new Double(l_x4); l_subtrahendNextY = new Double(l_y4); } if (l_x2 <= l_x3) { // minuend needs to be fast forwarded l_minuendItem++; b_minuendFastForward = true; continue; } if (l_x4 <= l_x1) { // subtrahend needs to be fast forwarded l_subtrahendItem++; b_subtrahendFastForward = true; continue; } // check if initial polygon needs to be clipped if ((l_x3 < l_x1) && (l_x1 < l_x4)) { // project onto subtrahend double l_slope = (l_y4 - l_y3) / (l_x4 - l_x3); l_subtrahendCurX = l_minuendCurX; l_subtrahendCurY = new Double((l_slope * l_x1) + (l_y3 - (l_slope * l_x3))); l_subtrahendXs.add(l_subtrahendCurX); l_subtrahendYs.add(l_subtrahendCurY); } if ((l_x1 < l_x3) && (l_x3 < l_x2)) { // project onto minuend double l_slope = (l_y2 - l_y1) / (l_x2 - l_x1); l_minuendCurX = l_subtrahendCurX; l_minuendCurY = new Double((l_slope * l_x3) + (l_y1 - (l_slope * l_x1))); l_minuendXs.add(l_minuendCurX); l_minuendYs.add(l_minuendCurY); } l_minuendMaxY = l_minuendCurY.doubleValue(); l_minuendMinY = l_minuendCurY.doubleValue(); l_subtrahendMaxY = l_subtrahendCurY.doubleValue(); l_subtrahendMinY = l_subtrahendCurY.doubleValue(); b_fastForwardDone = true; } // start of algorithm while (!b_minuendDone && !b_subtrahendDone) { if (!b_minuendDone && !b_minuendFastForward && b_minuendAdvanced) { l_x1 = x_dataset.getXValue(0, l_minuendItem); l_y1 = x_dataset.getYValue(0, l_minuendItem); l_minuendCurX = new Double(l_x1); l_minuendCurY = new Double(l_y1); if (!b_minuendAtIntersect) { l_minuendXs.add(l_minuendCurX); l_minuendYs.add(l_minuendCurY); } l_minuendMaxY = Math.max(l_minuendMaxY, l_y1); l_minuendMinY = Math.min(l_minuendMinY, l_y1); l_x2 = x_dataset.getXValue(0, l_minuendItem + 1); l_y2 = x_dataset.getYValue(0, l_minuendItem + 1); l_minuendNextX = new Double(l_x2); l_minuendNextY = new Double(l_y2); } // never updated the subtrahend if it is implied to be zero if (!b_impliedZeroSubtrahend && !b_subtrahendDone && !b_subtrahendFastForward && b_subtrahendAdvanced) { l_x3 = x_dataset.getXValue(1, l_subtrahendItem); l_y3 = x_dataset.getYValue(1, l_subtrahendItem); l_subtrahendCurX = new Double(l_x3); l_subtrahendCurY = new Double(l_y3); if (!b_subtrahendAtIntersect) { l_subtrahendXs.add(l_subtrahendCurX); l_subtrahendYs.add(l_subtrahendCurY); } l_subtrahendMaxY = Math.max(l_subtrahendMaxY, l_y3); l_subtrahendMinY = Math.min(l_subtrahendMinY, l_y3); l_x4 = x_dataset.getXValue(1, l_subtrahendItem + 1); l_y4 = x_dataset.getYValue(1, l_subtrahendItem + 1); l_subtrahendNextX = new Double(l_x4); l_subtrahendNextY = new Double(l_y4); } // deassert b_*FastForward (only matters for 1st time through loop) b_minuendFastForward = false; b_subtrahendFastForward = false; Double l_intersectX = null; Double l_intersectY = null; boolean b_intersect = false; b_minuendAtIntersect = false; b_subtrahendAtIntersect = false; // check for intersect if ((l_x2 == l_x4) && (l_y2 == l_y4)) { // check if line segments are colinear if ((l_x1 == l_x3) && (l_y1 == l_y3)) { b_colinear = true; } else { // the intersect is at the next point for both the minuend // and subtrahend l_intersectX = new Double(l_x2); l_intersectY = new Double(l_y2); b_intersect = true; b_minuendAtIntersect = true; b_subtrahendAtIntersect = true; } } else { // compute common denominator double l_denominator = ((l_y4 - l_y3) * (l_x2 - l_x1)) - ((l_x4 - l_x3) * (l_y2 - l_y1)); // compute common deltas double l_deltaY = l_y1 - l_y3; double l_deltaX = l_x1 - l_x3; // compute numerators double l_numeratorA = ((l_x4 - l_x3) * l_deltaY) - ((l_y4 - l_y3) * l_deltaX); double l_numeratorB = ((l_x2 - l_x1) * l_deltaY) - ((l_y2 - l_y1) * l_deltaX); // check if line segments are colinear if ((0 == l_numeratorA) && (0 == l_numeratorB) && (0 == l_denominator)) { b_colinear = true; } else { // check if previously colinear if (b_colinear) { // clear colinear points and flag l_minuendXs.clear(); l_minuendYs.clear(); l_subtrahendXs.clear(); l_subtrahendYs.clear(); l_polygonXs.clear(); l_polygonYs.clear(); b_colinear = false; // set new starting point for the polygon boolean b_useMinuend = ((l_x3 <= l_x1) && (l_x1 <= l_x4)); l_polygonXs.add(b_useMinuend ? l_minuendCurX : l_subtrahendCurX); l_polygonYs.add(b_useMinuend ? l_minuendCurY : l_subtrahendCurY); } } // compute slope components double l_slopeA = l_numeratorA / l_denominator; double l_slopeB = l_numeratorB / l_denominator; // test if both grahphs have a vertical rise at the same x-value boolean b_vertical = (l_x1 == l_x2) && (l_x3 == l_x4) && (l_x2 == l_x4); // check if the line segments intersect if (((0 < l_slopeA) && (l_slopeA <= 1) && (0 < l_slopeB) && (l_slopeB <= 1))|| b_vertical) { // compute the point of intersection double l_xi; double l_yi; if(b_vertical){ b_colinear = false; l_xi = l_x2; l_yi = l_x4; } else{ l_xi = l_x1 + (l_slopeA * (l_x2 - l_x1)); l_yi = l_y1 + (l_slopeA * (l_y2 - l_y1)); } l_intersectX = new Double(l_xi); l_intersectY = new Double(l_yi); b_intersect = true; b_minuendAtIntersect = ((l_xi == l_x2) && (l_yi == l_y2)); b_subtrahendAtIntersect = ((l_xi == l_x4) && (l_yi == l_y4)); // advance minuend and subtrahend to intesect l_minuendCurX = l_intersectX; l_minuendCurY = l_intersectY; l_subtrahendCurX = l_intersectX; l_subtrahendCurY = l_intersectY; } } if (b_intersect) { // create the polygon // add the minuend's points to polygon l_polygonXs.addAll(l_minuendXs); l_polygonYs.addAll(l_minuendYs); // add intersection point to the polygon l_polygonXs.add(l_intersectX); l_polygonYs.add(l_intersectY); // add the subtrahend's points to the polygon in reverse Collections.reverse(l_subtrahendXs); Collections.reverse(l_subtrahendYs); l_polygonXs.addAll(l_subtrahendXs); l_polygonYs.addAll(l_subtrahendYs); // create an actual polygon b_positive = (l_subtrahendMaxY <= l_minuendMaxY) && (l_subtrahendMinY <= l_minuendMinY); createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis, x_rangeAxis, b_positive, l_polygonXs, l_polygonYs); // clear the point vectors l_minuendXs.clear(); l_minuendYs.clear(); l_subtrahendXs.clear(); l_subtrahendYs.clear(); l_polygonXs.clear(); l_polygonYs.clear(); // set the maxY and minY values to intersect y-value double l_y = l_intersectY.doubleValue(); l_minuendMaxY = l_y; l_subtrahendMaxY = l_y; l_minuendMinY = l_y; l_subtrahendMinY = l_y; // add interection point to new polygon l_polygonXs.add(l_intersectX); l_polygonYs.add(l_intersectY); } // advance the minuend if needed if (l_x2 <= l_x4) { l_minuendItem++; b_minuendAdvanced = true; } else { b_minuendAdvanced = false; } // advance the subtrahend if needed if (l_x4 <= l_x2) { l_subtrahendItem++; b_subtrahendAdvanced = true; } else { b_subtrahendAdvanced = false; } b_minuendDone = (l_minuendItem == (l_minuendItemCount - 1)); b_subtrahendDone = (l_subtrahendItem == (l_subtrahendItemCount - 1)); } // check if the final polygon needs to be clipped if (b_minuendDone && (l_x3 < l_x2) && (l_x2 < l_x4)) { // project onto subtrahend double l_slope = (l_y4 - l_y3) / (l_x4 - l_x3); l_subtrahendNextX = l_minuendNextX; l_subtrahendNextY = new Double((l_slope * l_x2) + (l_y3 - (l_slope * l_x3))); } if (b_subtrahendDone && (l_x1 < l_x4) && (l_x4 < l_x2)) { // project onto minuend double l_slope = (l_y2 - l_y1) / (l_x2 - l_x1); l_minuendNextX = l_subtrahendNextX; l_minuendNextY = new Double((l_slope * l_x4) + (l_y1 - (l_slope * l_x1))); } // consider last point of minuend and subtrahend for determining // positivity l_minuendMaxY = Math.max(l_minuendMaxY, l_minuendNextY.doubleValue()); l_subtrahendMaxY = Math.max(l_subtrahendMaxY, l_subtrahendNextY.doubleValue()); l_minuendMinY = Math.min(l_minuendMinY, l_minuendNextY.doubleValue()); l_subtrahendMinY = Math.min(l_subtrahendMinY, l_subtrahendNextY.doubleValue()); // add the last point of the minuned and subtrahend l_minuendXs.add(l_minuendNextX); l_minuendYs.add(l_minuendNextY); l_subtrahendXs.add(l_subtrahendNextX); l_subtrahendYs.add(l_subtrahendNextY); // create the polygon // add the minuend's points to polygon l_polygonXs.addAll(l_minuendXs); l_polygonYs.addAll(l_minuendYs); // add the subtrahend's points to the polygon in reverse Collections.reverse(l_subtrahendXs); Collections.reverse(l_subtrahendYs); l_polygonXs.addAll(l_subtrahendXs); l_polygonYs.addAll(l_subtrahendYs); // create an actual polygon b_positive = (l_subtrahendMaxY <= l_minuendMaxY) && (l_subtrahendMinY <= l_minuendMinY); createPolygon(x_graphics, x_dataArea, x_plot, x_domainAxis, x_rangeAxis, b_positive, l_polygonXs, l_polygonYs); } /** * Draws the visual representation of a single data item, second pass. In * the second pass, the renderer draws the lines and shapes for the * individual points in the two series. * * @param x_graphics the graphics device. * @param x_dataArea the area within which the data is being drawn. * @param x_info collects information about the drawing. * @param x_plot the plot (can be used to obtain standard color * information etc). * @param x_domainAxis the domain (horizontal) axis. * @param x_rangeAxis the range (vertical) axis. * @param x_dataset the dataset. * @param x_series the series index (zero-based). * @param x_item the item index (zero-based). * @param x_crosshairState crosshair information for the plot * (<code>null</code> permitted). */ protected void drawItemPass1(Graphics2D x_graphics, Rectangle2D x_dataArea, PlotRenderingInfo x_info, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, XYDataset x_dataset, int x_series, int x_item, CrosshairState x_crosshairState) { Shape l_entityArea = null; EntityCollection l_entities = null; if (null != x_info) { l_entities = x_info.getOwner().getEntityCollection(); } Paint l_seriesPaint = getItemPaint(x_series, x_item); Stroke l_seriesStroke = getItemStroke(x_series, x_item); x_graphics.setPaint(l_seriesPaint); x_graphics.setStroke(l_seriesStroke); PlotOrientation l_orientation = x_plot.getOrientation(); RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge(); RectangleEdge l_rangeAxisLocation = x_plot.getRangeAxisEdge(); double l_x0 = x_dataset.getXValue(x_series, x_item); double l_y0 = x_dataset.getYValue(x_series, x_item); double l_x1 = x_domainAxis.valueToJava2D(l_x0, x_dataArea, l_domainAxisLocation); double l_y1 = x_rangeAxis.valueToJava2D(l_y0, x_dataArea, l_rangeAxisLocation); if (getShapesVisible()) { Shape l_shape = getItemShape(x_series, x_item); if (l_orientation == PlotOrientation.HORIZONTAL) { l_shape = ShapeUtilities.createTranslatedShape(l_shape, l_y1, l_x1); } else { l_shape = ShapeUtilities.createTranslatedShape(l_shape, l_x1, l_y1); } if (l_shape.intersects(x_dataArea)) { x_graphics.setPaint(getItemPaint(x_series, x_item)); x_graphics.fill(l_shape); } l_entityArea = l_shape; } // add an entity for the item... if (null != l_entities) { if (null == l_entityArea) { l_entityArea = new Rectangle2D.Double((l_x1 - 2), (l_y1 - 2), 4, 4); } String l_tip = null; XYToolTipGenerator l_tipGenerator = getToolTipGenerator(x_series, x_item); if (null != l_tipGenerator) { l_tip = l_tipGenerator.generateToolTip(x_dataset, x_series, x_item); } String l_url = null; XYURLGenerator l_urlGenerator = getURLGenerator(); if (null != l_urlGenerator) { l_url = l_urlGenerator.generateURL(x_dataset, x_series, x_item); } XYItemEntity l_entity = new XYItemEntity(l_entityArea, x_dataset, x_series, x_item, l_tip, l_url); l_entities.add(l_entity); } // draw the item label if there is one... if (isItemLabelVisible(x_series, x_item)) { drawItemLabel(x_graphics, l_orientation, x_dataset, x_series, x_item, l_x1, l_y1, (l_y1 < 0.0)); } int l_domainAxisIndex = x_plot.getDomainAxisIndex(x_domainAxis); int l_rangeAxisIndex = x_plot.getRangeAxisIndex(x_rangeAxis); updateCrosshairValues(x_crosshairState, l_x0, l_y0, l_domainAxisIndex, l_rangeAxisIndex, l_x1, l_y1, l_orientation); if (0 == x_item) { return; } double l_x2 = x_domainAxis.valueToJava2D(x_dataset.getXValue(x_series, (x_item - 1)), x_dataArea, l_domainAxisLocation); double l_y2 = x_rangeAxis.valueToJava2D(x_dataset.getYValue(x_series, (x_item - 1)), x_dataArea, l_rangeAxisLocation); Line2D l_line = null; if (PlotOrientation.HORIZONTAL == l_orientation) { l_line = new Line2D.Double(l_y1, l_x1, l_y2, l_x2); } else if (PlotOrientation.VERTICAL == l_orientation) { l_line = new Line2D.Double(l_x1, l_y1, l_x2, l_y2); } if ((null != l_line) && l_line.intersects(x_dataArea)) { x_graphics.setPaint(getItemPaint(x_series, x_item)); x_graphics.setStroke(getItemStroke(x_series, x_item)); x_graphics.draw(l_line); } } /** * Determines if a dataset is degenerate. A degenerate dataset is a * dataset where either series has less than two (2) points. * * @param x_dataset the dataset. * @param x_impliedZeroSubtrahend if false, do not check the subtrahend * * @return true if the dataset is degenerate. */ private boolean isEitherSeriesDegenerate(XYDataset x_dataset, boolean x_impliedZeroSubtrahend) { if (x_impliedZeroSubtrahend) { return (x_dataset.getItemCount(0) < 2); } return ((x_dataset.getItemCount(0) < 2) || (x_dataset.getItemCount(1) < 2)); } /** * Determines if the two (2) series are disjoint. * Disjoint series do not overlap in the domain space. * * @param x_dataset the dataset. * * @return true if the dataset is degenerate. */ private boolean areSeriesDisjoint(XYDataset x_dataset) { int l_minuendItemCount = x_dataset.getItemCount(0); double l_minuendFirst = x_dataset.getXValue(0, 0); double l_minuendLast = x_dataset.getXValue(0, l_minuendItemCount - 1); int l_subtrahendItemCount = x_dataset.getItemCount(1); double l_subtrahendFirst = x_dataset.getXValue(1, 0); double l_subtrahendLast = x_dataset.getXValue(1, l_subtrahendItemCount - 1); return ((l_minuendLast < l_subtrahendFirst) || (l_subtrahendLast < l_minuendFirst)); } /** * Draws the visual representation of a polygon * * @param x_graphics the graphics device. * @param x_dataArea the area within which the data is being drawn. * @param x_plot the plot (can be used to obtain standard color * information etc). * @param x_domainAxis the domain (horizontal) axis. * @param x_rangeAxis the range (vertical) axis. * @param x_positive indicates if the polygon is positive (true) or * negative (false). * @param x_xValues a linked list of the x values (expects values to be * of type Double). * @param x_yValues a linked list of the y values (expects values to be * of type Double). */ private void createPolygon (Graphics2D x_graphics, Rectangle2D x_dataArea, XYPlot x_plot, ValueAxis x_domainAxis, ValueAxis x_rangeAxis, boolean x_positive, LinkedList x_xValues, LinkedList x_yValues) { PlotOrientation l_orientation = x_plot.getOrientation(); RectangleEdge l_domainAxisLocation = x_plot.getDomainAxisEdge(); RectangleEdge l_rangeAxisLocation = x_plot.getRangeAxisEdge(); Object[] l_xValues = x_xValues.toArray(); Object[] l_yValues = x_yValues.toArray(); GeneralPath l_path = new GeneralPath(); if (PlotOrientation.VERTICAL == l_orientation) { double l_x = x_domainAxis.valueToJava2D(( (Double) l_xValues[0]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } double l_y = x_rangeAxis.valueToJava2D(( (Double) l_yValues[0]).doubleValue(), x_dataArea, l_rangeAxisLocation); l_path.moveTo((float) l_x, (float) l_y); for (int i = 1; i < l_xValues.length; i++) { l_x = x_domainAxis.valueToJava2D(( (Double) l_xValues[i]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_y = x_rangeAxis.valueToJava2D(( (Double) l_yValues[i]).doubleValue(), x_dataArea, l_rangeAxisLocation); l_path.lineTo((float) l_x, (float) l_y); } l_path.closePath(); } else { double l_x = x_domainAxis.valueToJava2D(( (Double) l_xValues[0]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } double l_y = x_rangeAxis.valueToJava2D(( (Double) l_yValues[0]).doubleValue(), x_dataArea, l_rangeAxisLocation); l_path.moveTo((float) l_y, (float) l_x); for (int i = 1; i < l_xValues.length; i++) { l_x = x_domainAxis.valueToJava2D(( (Double) l_xValues[i]).doubleValue(), x_dataArea, l_domainAxisLocation); if (this.roundXCoordinates) { l_x = Math.rint(l_x); } l_y = x_rangeAxis.valueToJava2D(( (Double) l_yValues[i]).doubleValue(), x_dataArea, l_rangeAxisLocation); l_path.lineTo((float) l_y, (float) l_x); } l_path.closePath(); } if (l_path.intersects(x_dataArea)) { x_graphics.setPaint(x_positive ? getPositivePaint() : getNegativePaint()); x_graphics.fill(l_path); } } /** * Returns a default legend item for the specified series. Subclasses * should override this method to generate customised items. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return A legend item for the series. */ public LegendItem getLegendItem(int datasetIndex, int series) { LegendItem result = null; XYPlot p = getPlot(); if (p != null) { XYDataset dataset = p.getDataset(datasetIndex); if (dataset != null) { if (getItemVisible(series, 0)) { String label = getLegendItemLabelGenerator().generateLabel( dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel( dataset, series); } Paint paint = lookupSeriesPaint(series); Stroke stroke = lookupSeriesStroke(series); Shape line = getLegendLine(); result = new LegendItem(label, description, toolTipText, urlText, line, stroke, paint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getSeriesKey(series)); result.setSeriesIndex(series); } } } return result; } /** * Tests this renderer for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYDifferenceRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYDifferenceRenderer that = (XYDifferenceRenderer) obj; if (!PaintUtilities.equal(this.positivePaint, that.positivePaint)) { return false; } if (!PaintUtilities.equal(this.negativePaint, that.negativePaint)) { return false; } if (this.shapesVisible != that.shapesVisible) { return false; } if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) { return false; } if (this.roundXCoordinates != that.roundXCoordinates) { return false; } return true; } /** * Returns a clone of the renderer. * * @return A clone. * * @throws CloneNotSupportedException if the renderer cannot be cloned. */ public Object clone() throws CloneNotSupportedException { XYDifferenceRenderer clone = (XYDifferenceRenderer) super.clone(); clone.legendLine = ShapeUtilities.clone(this.legendLine); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writePaint(this.positivePaint, stream); SerialUtilities.writePaint(this.negativePaint, stream); SerialUtilities.writeShape(this.legendLine, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.positivePaint = SerialUtilities.readPaint(stream); this.negativePaint = SerialUtilities.readPaint(stream); this.legendLine = SerialUtilities.readShape(stream); } }
/** * @author sguruswami * * $Id: ViewModelAction.java,v 1.27 2006-04-19 18:50:01 georgeda Exp $ * * $Log: not supported by cvs2svn $ * Revision 1.26 2006/04/17 19:09:41 pandyas * caMod 2.1 OM changes * * Revision 1.25 2005/11/21 18:38:31 georgeda * Defect #35. Trim whitespace from items that are freeform text * * Revision 1.24 2005/11/15 22:13:46 georgeda * Cleanup of drug screening * * Revision 1.23 2005/11/14 14:21:44 georgeda * Added sorting and spontaneous mutation * * Revision 1.22 2005/11/11 18:39:30 georgeda * Removed unneeded call * * Revision 1.21 2005/11/10 22:07:36 georgeda * Fixed part of bug #21 * * Revision 1.20 2005/11/10 18:12:23 georgeda * Use constant * * Revision 1.19 2005/11/07 13:57:39 georgeda * Minor tweaks * * Revision 1.18 2005/11/03 15:47:11 georgeda * Fixed slow invivo results * * Revision 1.17 2005/10/27 18:13:48 guruswas * Show all publications in the publications display page. * * Revision 1.16 2005/10/20 21:35:37 georgeda * Fixed xenograft display bug * * Revision 1.15 2005/10/19 18:56:00 guruswas * implemented invivo details page * * Revision 1.14 2005/10/11 18:15:25 georgeda * More comment changes * * Revision 1.13 2005/10/10 14:12:24 georgeda * Changes for comment curation * * Revision 1.12 2005/10/07 21:15:03 georgeda * Added caarray variables * * Revision 1.11 2005/10/06 13:37:01 georgeda * Removed informational message * * Revision 1.10 2005/09/30 18:42:24 guruswas * intial implementation of drug screening search and display page * * Revision 1.9 2005/09/22 21:34:51 guruswas * First stab at carcinogenic intervention pages * * Revision 1.8 2005/09/22 15:23:41 georgeda * Cleaned up warnings * * Revision 1.7 2005/09/21 21:02:24 guruswas * Display the organ, disease names from NCI Thesaurus * * Revision 1.6 2005/09/21 20:47:16 georgeda * Cleaned up * * Revision 1.5 2005/09/16 19:30:00 guruswas * Display invivo data (from DTP) in the therapuetic approaches page * * Revision 1.4 2005/09/16 15:52:56 georgeda * Changes due to manager re-write * * */ package gov.nih.nci.camod.webapp.action; import gov.nih.nci.cabio.domain.Gene; import gov.nih.nci.cabio.domain.impl.GeneImpl; import gov.nih.nci.camod.Constants; import gov.nih.nci.camod.domain.*; import gov.nih.nci.camod.service.*; import gov.nih.nci.camod.service.impl.QueryManagerSingleton; import gov.nih.nci.camod.util.EvsTreeUtil; import gov.nih.nci.common.domain.DatabaseCrossReference; import gov.nih.nci.common.domain.impl.DatabaseCrossReferenceImpl; import gov.nih.nci.system.applicationservice.ApplicationService; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.*; public class ViewModelAction extends BaseAction { /** * sets the cancer model object in the session * * @param request * the httpRequest */ private void setCancerModel(HttpServletRequest request) { String modelID = request.getParameter(Constants.Parameters.MODELID); System.out.println("<setCancerModel> modelID" + modelID); AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager"); AnimalModel am = null; try { am = animalModelManager.get(modelID); } catch (Exception e) { log.error("Unable to get cancer model in setCancerModel"); e.printStackTrace(); } request.getSession().setAttribute(Constants.ANIMALMODEL, am); } /** * sets the cancer model object in the session * * @param request * the httpRequest * @throws Exception */ private void setComments(HttpServletRequest request, String inSection) throws Exception { String theCommentsId = request.getParameter(Constants.Parameters.COMMENTSID); CommentsManager theCommentsManager = (CommentsManager) getBean("commentsManager"); System.out.println("Comments id: " + theCommentsId); List<Comments> theCommentsList = new ArrayList<Comments>(); if (theCommentsId != null && theCommentsId.length() > 0) { Comments theComments = theCommentsManager.get(theCommentsId); if (theComments != null) { System.out.println("Found a comment: " + theComments.getRemark()); theCommentsList.add(theComments); } } // Get all comments that are either approved or owned by this user else { PersonManager thePersonManager = (PersonManager) getBean("personManager"); Person theCurrentUser = thePersonManager.getByUsername((String) request.getSession().getAttribute( Constants.CURRENTUSER)); AnimalModel theAnimalModel = (AnimalModel) request.getSession().getAttribute(Constants.ANIMALMODEL); theCommentsList = theCommentsManager.getAllBySection(inSection, theCurrentUser, theAnimalModel); } request.setAttribute(Constants.Parameters.COMMENTSLIST, theCommentsList); } /** * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward populateModelCharacteristics(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); setComments(request, Constants.Pages.MODEL_CHARACTERISTICS); return mapping.findForward("viewModelCharacteristics"); } public ActionForward populateEngineeredGene(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("<populateEngineeredGene> modelID" + request.getParameter("aModelID")); String modelID = request.getParameter("aModelID"); AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager"); AnimalModel am = animalModelManager.get(modelID); final Set egc = am.getEngineeredGeneCollection(); final int egcCnt = (egc != null) ? egc.size() : 0; final List<EngineeredGene> tgc = new ArrayList<EngineeredGene>(); int tgCnt = 0;// Transgene final List<EngineeredGene> gsc = new ArrayList<EngineeredGene>(); int gsCnt = 0;// GenomicSegment final List<EngineeredGene> tmc = new ArrayList<EngineeredGene>(); int tmCnt = 0;// TargetedModification final Map tmGeneMap = new HashMap(); final List<EngineeredGene> imc = new ArrayList<EngineeredGene>(); final List<SpontaneousMutation> smc = new ArrayList<SpontaneousMutation>(am.getSpontaneousMutationCollection()); Iterator it = egc.iterator(); int imCnt = 0;// InducedMutation while (it.hasNext()) { EngineeredGene eg = (EngineeredGene) it.next(); if (eg instanceof Transgene) { tgc.add(eg); tgCnt++; } else if (eg instanceof GenomicSegment) { gsc.add(eg); gsCnt++; } else if (eg instanceof TargetedModification) { tmc.add(eg); tmCnt++; // now go to caBIO and query the gene object.... TargetedModification tm = (TargetedModification) eg; String geneId = tm.getGeneId(); if (geneId != null) { log.info("Connecting to caBIO to look up gene " + geneId); // the geneId is available try { ApplicationService appService = EvsTreeUtil.getApplicationService(); DatabaseCrossReference dcr = new DatabaseCrossReferenceImpl(); dcr.setCrossReferenceId(geneId); dcr.setType("gov.nih.nci.cabio.domain.Gene"); dcr.setDataSourceName("LOCUS_LINK_ID"); List resultList = appService.search(DatabaseCrossReference.class, dcr); final int resultCount = (resultList != null) ? resultList.size() : 0; log.info("Got " + resultCount + " dataCrossReferences...."); if (resultCount > 0) { dcr = (DatabaseCrossReference) resultList.get(0); Gene myGene = new GeneImpl(); List<DatabaseCrossReference> cfcoll = new ArrayList<DatabaseCrossReference>(); cfcoll.add(dcr); myGene.setDatabaseCrossReferenceCollection(cfcoll); resultList = appService.search(Gene.class, myGene); final int geneCount = (resultList != null) ? resultList.size() : 0; log.info("Got " + geneCount + " Gene Objects"); if (geneCount > 0) { myGene = (Gene) resultList.get(0); log.info("Gene:" + geneId + " ==>" + myGene); tmGeneMap.put(tm.getId(), myGene); } } } catch (Exception e) { log.error("Unable to get information from caBIO", e); } } } else if (eg instanceof InducedMutation) { imc.add(eg); imCnt++; } } System.out.println("<populateEngineeredGene> " + "egcCnt=" + egcCnt + "tgc=" + tgCnt + "gsc=" + gsCnt + "tmc=" + tmCnt + "imc=" + imCnt); request.getSession().setAttribute(Constants.ANIMALMODEL, am); request.getSession().setAttribute(Constants.TRANSGENE_COLL, tgc); request.getSession().setAttribute(Constants.GENOMIC_SEG_COLL, gsc); request.getSession().setAttribute(Constants.TARGETED_MOD_COLL, tmc); request.getSession().setAttribute(Constants.TARGETED_MOD_GENE_MAP, tmGeneMap); request.getSession().setAttribute(Constants.INDUCED_MUT_COLL, imc); request.getSession().setAttribute(Constants.SPONTANEOUS_MUT_COLL, smc); System.out.println("<populateEngineeredGene> set attributes done."); setComments(request, Constants.Pages.GENETIC_DESCRIPTION); return mapping.findForward("viewGeneticDescription"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateCarcinogenicInterventions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); String modelID = request.getParameter(Constants.Parameters.MODELID); AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager"); AnimalModel am = animalModelManager.get(modelID); final Set ceColl = am.getCarcinogenExposureCollection(); Iterator it = ceColl.iterator(); final Map<String, List> interventionTypeMap = new HashMap<String, List>(); final int cc = (ceColl != null) ? ceColl.size() : 0; while (it.hasNext()) { CarcinogenExposure ce = (CarcinogenExposure) it.next(); if (ce != null ) { log.info("Checking agent:" + ce.getEnvironmentalFactor().getNscNumber()); String myType = ce.getEnvironmentalFactor().getType(); if (myType == null || myType.length() == 0) { myType = ce.getEnvironmentalFactor().getTypeUnctrlVocab(); if (myType == null || myType.length() == 0) { myType = "Not specified"; } } List myTypeColl = (List) interventionTypeMap.get(myType); if (myTypeColl == null) { myTypeColl = new ArrayList(); interventionTypeMap.put(myType, myTypeColl); } myTypeColl.add(ce); } } request.getSession().setAttribute(Constants.CARCINOGENIC_INTERVENTIONS_COLL, interventionTypeMap); setComments(request, Constants.Pages.CARCINOGENIC_INTERVENTION); return mapping.findForward("viewCarcinogenicInterventions"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populatePublications(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); String modelID = request.getParameter("aModelID"); List pubs = null; try { pubs = QueryManagerSingleton.instance().getAllPublications(Long.valueOf(modelID).longValue()); } catch (Exception e) { log.error("Unable to get publications"); e.printStackTrace(); } request.getSession().setAttribute(Constants.PUBLICATIONS, pubs); setComments(request, Constants.Pages.PUBLICATIONS); return mapping.findForward("viewPublications"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateHistopathology(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); setComments(request, Constants.Pages.HISTOPATHOLOGY); return mapping.findForward("viewHistopathology"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateTherapeuticApproaches(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); // query caBIO and load clinical protocols information // store clinicalProtocol info in a hashmap keyed by NSC final HashMap<Long, Collection> clinProtocols = new HashMap<Long, Collection>(); final HashMap<Long, Collection> yeastResults = new HashMap<Long, Collection>(); final HashMap<Long, Collection> invivoResults = new HashMap<Long, Collection>(); final List<Therapy> therapeuticApprochesColl = new ArrayList<Therapy>(); String modelID = request.getParameter(Constants.Parameters.MODELID); AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager"); AnimalModel am = animalModelManager.get(modelID); final Set therapyColl = am.getTherapyCollection(); Iterator it = therapyColl.iterator(); final int cc = (therapyColl != null) ? therapyColl.size() : 0; log.info("Looking up clinical protocols for " + cc + " agents..."); while (it.hasNext()) { Therapy t = (Therapy) it.next(); if (t != null) { therapeuticApprochesColl.add(t); } Agent a = t.getAgent(); AgentManager myAgentManager = (AgentManager) getBean("agentManager"); if (a != null) { Long nscNumber = a.getNscNumber(); if (nscNumber != null) { Collection protocols = myAgentManager.getClinicalProtocols(a); clinProtocols.put(nscNumber, protocols); log.info("\n Number of clinical protocols from caBio " + protocols.size()); log.info("\n Print each protocol (for debugging) :"); for (int j = 0; j < protocols.size(); j++) { log.info("\n" + protocols.toString()); } log.info("\n<ViewModelAction> populateTherapeuticApproaches"); log.info("\n Remove the following printout - for debugging only"); for (int k = 0; k < clinProtocols.size(); k++) { log.info("Print what is in clinProtolos collection: " + clinProtocols.toString()); } // get the yeast data List yeastStages = myAgentManager.getYeastResults(a, true); if (yeastStages.size() > 0) { yeastResults.put(a.getId(), yeastStages); } // now get invivo/Xenograft data List xenograftResults = QueryManagerSingleton.instance().getInvivoResults(a, true); invivoResults.put(a.getId(), xenograftResults); } } } request.getSession().setAttribute(Constants.THERAPEUTIC_APPROACHES_COLL, therapeuticApprochesColl); request.getSession().setAttribute(Constants.CLINICAL_PROTOCOLS, clinProtocols); request.getSession().setAttribute(Constants.YEAST_DATA, yeastResults); request.getSession().setAttribute(Constants.INVIVO_DATA, invivoResults); setComments(request, Constants.Pages.THERAPEUTIC_APPROACHES); return mapping.findForward("viewTherapeuticApproaches"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateCellLines(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); setComments(request, Constants.Pages.CELL_LINES); return mapping.findForward("viewCellLines"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateImages(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); setComments(request, Constants.Pages.IMAGES); return mapping.findForward("viewImages"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateMicroarrays(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); ResourceBundle theBundle = ResourceBundle.getBundle(Constants.CAMOD_BUNDLE); request.setAttribute("uri_start", theBundle.getString(Constants.CaArray.URI_START)); request.setAttribute("uri_end", theBundle.getString(Constants.CaArray.URI_END)); setComments(request, Constants.Pages.MICROARRAY); return mapping.findForward("viewMicroarrays"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateTransplantXenograft(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setCancerModel(request); setComments(request, Constants.Pages.XENOGRAFT); return mapping.findForward("viewTransplantXenograft"); } /** * Populate the session and/or request with the objects necessary to display * the page. * * @param mapping * the struts action mapping * @param form * the web form * @param request * HTTPRequest * @param response * HTTPResponse * @return * @throws Exception */ public ActionForward populateXenograftDetails(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String modelID = request.getParameter("xModelID"); String nsc = request.getParameter("nsc"); if (nsc != null && nsc.length() == 0) return mapping.findForward("viewModelCharacteristics"); log.info("<populateXenograftDetails> modelID:" + modelID); log.info("<populateXenograftDetails> nsc:" + nsc); XenograftManager mgr = (XenograftManager) getBean("xenograftManager"); Xenograft x = mgr.get(modelID); setCancerModel(request); request.getSession().setAttribute(Constants.XENOGRAFTMODEL, x); request.getSession().setAttribute(Constants.NSC_NUMBER, nsc); request.getSession().setAttribute(Constants.XENOGRAFTRESULTLIST, x.getInvivoResultCollectionByNSC(nsc)); return mapping.findForward("viewInvivoDetails"); } }
// Vilya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.ezgame.server; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import com.samskivert.util.ArrayIntSet; import com.samskivert.util.ArrayUtil; import com.samskivert.util.CollectionUtil; import com.samskivert.util.HashIntMap; import com.samskivert.util.Interval; import com.samskivert.util.IntListUtil; import com.samskivert.util.RandomUtil; import com.samskivert.util.ResultListener; import com.threerings.util.Name; import com.threerings.presents.data.ClientObject; import com.threerings.presents.data.InvocationCodes; import com.threerings.presents.dobj.AccessController; import com.threerings.presents.dobj.DObjectManager; import com.threerings.presents.dobj.DSet; import com.threerings.presents.dobj.MessageEvent; import com.threerings.presents.client.InvocationService; import com.threerings.presents.server.InvocationException; import com.threerings.crowd.data.BodyObject; import com.threerings.crowd.data.OccupantInfo; import com.threerings.crowd.data.PlaceObject; import com.threerings.crowd.server.CrowdServer; import com.threerings.parlor.game.data.GameConfig; import com.threerings.parlor.game.server.GameManager; import com.threerings.parlor.turn.server.TurnGameManager; import com.threerings.ezgame.data.EZGameMarshaller; import com.threerings.ezgame.data.EZGameObject; import com.threerings.ezgame.data.PropertySetEvent; import com.threerings.ezgame.data.UserCookie; import static com.threerings.ezgame.server.Log.log; /** * A manager for "ez" games. */ public class EZGameManager extends GameManager implements EZGameProvider, TurnGameManager { public EZGameManager () { addDelegate(_turnDelegate = new EZGameTurnDelegate(this)); } // from TurnGameManager public void turnWillStart () { } // from TurnGameManager public void turnDidStart () { } // from TurnGameManager public void turnDidEnd () { } // from EZGameProvider public void endTurn (ClientObject caller, int nextPlayerId, InvocationService.InvocationListener listener) throws InvocationException { validateStateModification(caller, true); Name nextTurnHolder = null; if (nextPlayerId != 0) { BodyObject target = getPlayerByOid(nextPlayerId); if (target != null) { nextTurnHolder = target.getVisibleName(); } } _turnDelegate.endTurn(nextTurnHolder); } // from EZGameProvider public void endRound (ClientObject caller, int nextRoundDelay, InvocationService.InvocationListener listener) throws InvocationException { validateStateModification(caller, false); // let the game know that it is doing something stupid if (_gameObj.roundId < 0) { throw new InvocationException("m.round_already_ended"); } // while we are between rounds, our round id is the negation of the round that just ended _gameObj.setRoundId(-_gameObj.roundId); // queue up the start of the next round if requested if (nextRoundDelay > 0) { new Interval(CrowdServer.omgr) { public void expired () { if (_gameObj.isInPlay()) { _gameObj.setRoundId(-_gameObj.roundId + 1); } } }.schedule(nextRoundDelay * 1000L); } } // from EZGameProvider public void endGame (ClientObject caller, int[] winnerOids, InvocationService.InvocationListener listener) throws InvocationException { if (!_gameObj.isInPlay()) { throw new InvocationException("e.already_ended"); } validateStateModification(caller, false); _winnerIds = winnerOids; endGame(); } // from EZGameProvider public void sendMessage (ClientObject caller, String msg, Object data, int playerId, InvocationService.InvocationListener listener) throws InvocationException { validateUser(caller); if (playerId == 0) { _gameObj.postMessage(EZGameObject.USER_MESSAGE, msg, data); } else { sendPrivateMessage(playerId, msg, data); } } // from EZGameProvider public void setProperty (ClientObject caller, String propName, Object data, int index, boolean testAndSet, Object testValue, InvocationService.InvocationListener listener) throws InvocationException { validateUser(caller); if (testAndSet && !_gameObj.testProperty(propName, index, testValue)) { return; // the test failed: do not set the property } setProperty(propName, data, index); } // from EZGameProvider public void getDictionaryLetterSet (ClientObject caller, String locale, int count, InvocationService.ResultListener listener) throws InvocationException { getDictionaryManager().getLetterSet(locale, count, listener); } // from EZGameProvider public void checkDictionaryWord (ClientObject caller, String locale, String word, InvocationService.ResultListener listener) throws InvocationException { getDictionaryManager().checkWord(locale, word, listener); } /** * Returns the dictionary manager if it has been properly initialized. Throws an INTERNAL_ERROR * exception if it has not. */ protected DictionaryManager getDictionaryManager () throws InvocationException { DictionaryManager dictionary = DictionaryManager.getInstance(); if (dictionary == null) { log.warning("DictionaryManager not initialized."); throw new InvocationException(INTERNAL_ERROR); } return dictionary; } // from EZGameProvider public void addToCollection (ClientObject caller, String collName, byte[][] data, boolean clearExisting, InvocationService.InvocationListener listener) throws InvocationException { validateUser(caller); if (_collections == null) { _collections = new HashMap<String, ArrayList<byte[]>>(); } // figure out if we're adding to an existing collection or creating a new one ArrayList<byte[]> list = null; if (!clearExisting) { list = _collections.get(collName); } if (list == null) { list = new ArrayList<byte[]>(); _collections.put(collName, list); } CollectionUtil.addAll(list, data); } // from EZGameProvider public void getFromCollection (ClientObject caller, String collName, boolean consume, int count, String msgOrPropName, int playerId, InvocationService.ConfirmListener listener) throws InvocationException { validateUser(caller); int srcSize = 0; if (_collections != null) { ArrayList<byte[]> src = _collections.get(collName); srcSize = (src == null) ? 0 : src.size(); if (srcSize >= count) { byte[][] result = new byte[count][]; for (int ii=0; ii < count; ii++) { int pick = RandomUtil.getInt(srcSize); if (consume) { result[ii] = src.remove(pick); srcSize } else { result[ii] = src.get(pick); } } if (playerId == 0) { setProperty(msgOrPropName, result, -1); } else { sendPrivateMessage(playerId, msgOrPropName, result); } listener.requestProcessed(); // SUCCESS! return; } } // TODO: decide what we want to return here throw new InvocationException(String.valueOf(srcSize)); } // from EZGameProvider public void mergeCollection (ClientObject caller, String srcColl, String intoColl, InvocationService.InvocationListener listener) throws InvocationException { validateUser(caller); // non-existent collections are treated as empty, so if the source doesn't exist, we // silently accept it if (_collections != null) { ArrayList<byte[]> src = _collections.remove(srcColl); if (src != null) { ArrayList<byte[]> dest = _collections.get(intoColl); if (dest == null) { _collections.put(intoColl, src); } else { dest.addAll(src); } } } } // from EZGameProvider public void setTicker (ClientObject caller, String tickerName, int msOfDelay, InvocationService.InvocationListener listener) throws InvocationException { validateUser(caller); Ticker t; if (msOfDelay >= MIN_TICKER_DELAY) { if (_tickers != null) { t = _tickers.get(tickerName); } else { _tickers = new HashMap<String, Ticker>(); t = null; } if (t == null) { if (_tickers.size() >= MAX_TICKERS) { throw new InvocationException(ACCESS_DENIED); } t = new Ticker(tickerName, _gameObj); _tickers.put(tickerName, t); } t.start(msOfDelay); } else if (msOfDelay <= 0) { if (_tickers != null) { t = _tickers.remove(tickerName); if (t != null) { t.stop(); } } } else { throw new InvocationException(ACCESS_DENIED); } } // from EZGameProvider public void getCookie (ClientObject caller, final int playerId, InvocationService.InvocationListener listener) throws InvocationException { GameCookieManager gcm = getCookieManager(); if (_gameObj.userCookies.containsKey(playerId)) { // already loaded: we do nothing return; } if (_cookieLookups == null) { _cookieLookups = new ArrayIntSet(); } // we only start looking up the cookie if nobody else already is if (!_cookieLookups.contains(playerId)) { BodyObject body = getOccupantByOid(playerId); if (body == null) { log.fine("getCookie() called with invalid occupant [occupantId=" + playerId + "]."); throw new InvocationException(INTERNAL_ERROR); } gcm.getCookie(_gameconfig.getGameId(), body, new ResultListener<byte[]>() { public void requestCompleted (byte[] result) { // Result may be null: that's ok, it means we've looked up the user's // nonexistant cookie. Only set the cookie if the playerIndex is still in the // lookup set, otherwise they left! if (_cookieLookups.remove(playerId) && _gameObj.isActive()) { _gameObj.addToUserCookies(new UserCookie(playerId, result)); } } public void requestFailed (Exception cause) { log.warning("Unable to retrieve cookie [cause=" + cause + "]."); requestCompleted(null); } }); // indicate that we're looking up a cookie _cookieLookups.add(playerId); } } // from EZGameProvider public void setCookie (ClientObject caller, byte[] value, InvocationService.InvocationListener listener) throws InvocationException { validateUser(caller); GameCookieManager gcm = getCookieManager(); UserCookie cookie = new UserCookie(caller.getOid(), value); if (_gameObj.userCookies.containsKey(cookie.getKey())) { _gameObj.updateUserCookies(cookie); } else { _gameObj.addToUserCookies(cookie); } gcm.setCookie(_gameconfig.getGameId(), caller, value); } /** * Get the cookie manager, and do a bit of other setup. */ protected GameCookieManager getCookieManager () throws InvocationException { GameCookieManager gcm = GameCookieManager.getInstance(); if (gcm == null) { log.warning("GameCookieManager not initialized."); throw new InvocationException(INTERNAL_ERROR); } if (_gameObj.userCookies == null) { // lazy-init this _gameObj.setUserCookies(new DSet<UserCookie>()); } return gcm; } /** * Helper method to send a private message to the specified player oid (must already be * verified). */ protected void sendPrivateMessage ( int playerId, String msg, Object data) throws InvocationException { BodyObject target = getPlayerByOid(playerId); if (target == null) { // TODO: this code has no corresponding translation throw new InvocationException("m.player_not_around"); } target.postMessage(EZGameObject.USER_MESSAGE + ":" + _gameObj.getOid(), new Object[] { msg, data }); } /** * Helper method to post a property set event. */ protected void setProperty (String propName, Object value, int index) { // apply the property set immediately Object oldValue = _gameObj.applyPropertySet(propName, value, index); _gameObj.postEvent( new PropertySetEvent(_gameObj.getOid(), propName, value, index, oldValue)); } /** * Validate that the specified user has access to do things in the game. */ protected void validateUser (ClientObject caller) throws InvocationException { BodyObject body = (BodyObject)caller; switch (getMatchType()) { case GameConfig.PARTY: return; // always validate. default: if (getPlayerIndex(body.getVisibleName()) == -1) { throw new InvocationException(InvocationCodes.ACCESS_DENIED); } return; } } /** * Validate that the specified listener has access to make a change. */ protected void validateStateModification (ClientObject caller, boolean requireHoldsTurn) throws InvocationException { validateUser(caller); if (requireHoldsTurn) { Name holder = _gameObj.turnHolder; if (holder != null && !holder.equals(((BodyObject) caller).getVisibleName())) { throw new InvocationException(InvocationCodes.ACCESS_DENIED); } } } /** * Get the specified player body by Oid. */ protected BodyObject getPlayerByOid (int oid) { // verify that they're a player switch (getMatchType()) { case GameConfig.PARTY: // all occupants are players in a party game break; default: if (!IntListUtil.contains(_playerOids, oid)) { return null; // not a player! } break; } return getOccupantByOid(oid); } /** * Get the specified occupant body by Oid. */ protected BodyObject getOccupantByOid (int oid) { if (!_gameObj.occupants.contains(oid)) { return null; } // return the body return (BodyObject) CrowdServer.omgr.getObject(oid); } @Override protected PlaceObject createPlaceObject () { return new EZGameObject(); } @Override protected void didStartup () { super.didStartup(); _gameObj = (EZGameObject) _plobj; _gameObj.setEzGameService( (EZGameMarshaller) CrowdServer.invmgr.registerDispatcher(new EZGameDispatcher(this))); // if we don't need the no-show timer, start. if (!needsNoShowTimer()) { startGame(); } } @Override // from PlaceManager protected void bodyEntered (int bodyOid) { super.bodyEntered(bodyOid); // if we have no controller, then our new friend gets control if (_gameObj.controllerOid == 0) { _gameObj.setControllerOid(bodyOid); } } @Override // from PlaceManager protected void bodyUpdated (OccupantInfo info) { super.bodyUpdated(info); // if the controller just disconnected, reassign control if (info.status == OccupantInfo.DISCONNECTED && info.bodyOid == _gameObj.controllerOid) { _gameObj.setControllerOid(getControllerOid()); // if everyone in the room was disconnected and this client just reconnected, it becomes // the new controller } else if (_gameObj.controllerOid == 0) { _gameObj.setControllerOid(info.bodyOid); } } @Override // from PlaceManager protected void bodyLeft (int bodyOid) { super.bodyLeft(bodyOid); // if this player was the controller, reassign control if (bodyOid == _gameObj.controllerOid) { _gameObj.setControllerOid(getControllerOid()); } } @Override protected void didShutdown () { CrowdServer.invmgr.clearDispatcher(_gameObj.ezGameService); stopTickers(); super.didShutdown(); } @Override protected void gameDidEnd () { stopTickers(); super.gameDidEnd(); } @Override protected void playerGameDidEnd (int pidx) { super.playerGameDidEnd(pidx); // kill any of their cookies if (_gameObj.userCookies != null && _gameObj.userCookies.containsKey(pidx)) { _gameObj.removeFromUserCookies(pidx); } // halt the loading of their cookie, if in progress if (_cookieLookups != null) { _cookieLookups.remove(pidx); } } @Override protected void assignWinners (boolean[] winners) { if (_winnerIds != null) { for (int oid : _winnerIds) { int index = IntListUtil.indexOf(_playerOids, oid); if (index >= 0 && index < winners.length) { winners[index] = true; } } _winnerIds = null; } } /** * Stop and clear all tickers. */ protected void stopTickers () { if (_tickers != null) { for (Ticker ticker : _tickers.values()) { ticker.stop(); } _tickers = null; } } /** * Returns the oid of a player to whom to assign control of the game or zero if no players * qualify for control. */ protected int getControllerOid () { for (OccupantInfo info : _gameObj.occupantInfo) { if (info.status != OccupantInfo.DISCONNECTED) { return info.bodyOid; } } return 0; } /** * A timer that fires message events to a game. */ protected static class Ticker { /** * Create a Ticker. */ public Ticker (String name, EZGameObject gameObj) { _name = name; // once we are constructed, we want to avoid calling methods on dobjs. _oid = gameObj.getOid(); _omgr = gameObj.getManager(); } public void start (int msOfDelay) { _value = 0; _interval.schedule(0, msOfDelay); } public void stop () { _interval.cancel(); } /** * The interval that does our work. Note well that this is not a 'safe' interval that * operates using a RunQueue. This interval instead does something that we happen to know * is safe for any thread: posting an event to the dobj manager. If we were using a * RunQueue it would be the same event queue and we would be posted there, wait our turn, * and then do the same thing: post this event. We just expedite the process. */ protected Interval _interval = new Interval() { public void expired () { _omgr.postEvent( new MessageEvent(_oid, EZGameObject.TICKER, new Object[] { _name, _value++ })); } }; protected int _oid; protected DObjectManager _omgr; protected String _name; protected int _value; } // End: static class Ticker /** A nice casted reference to the game object. */ protected EZGameObject _gameObj; /** Our turn delegate. */ protected EZGameTurnDelegate _turnDelegate; /** The map of collections, lazy-initialized. */ protected HashMap<String, ArrayList<byte[]>> _collections; /** The map of tickers, lazy-initialized. */ protected HashMap<String, Ticker> _tickers; /** Tracks which cookies are currently being retrieved from the db. */ protected ArrayIntSet _cookieLookups; // /** User tokens, lazy-initialized. */ // protected HashIntMap<HashSet<String>> _tokens; /** The array of winner oids, after the user has filled it in. */ protected int[] _winnerIds; /** The minimum delay a ticker can have. */ protected static final int MIN_TICKER_DELAY = 50; /** The maximum number of tickers allowed at one time. */ protected static final int MAX_TICKERS = 3; }