lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | e003f32391150b04a7c7a324b693708265f3f1b1 | 0 | Codewaves/Sticky-Header-Grid | package com.codewaves.stickyheadergrid;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Sergej Kravcenko on 4/24/2017.
* Copyright (c) 2017 Sergej Kravcenko
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class StickyHeaderGridLayoutManager extends RecyclerView.LayoutManager {
public static final String TAG = "StickyLayoutManager";
private int mSpanCount;
private StickyHeaderGridAdapter mAdapter;
private int mHeadersStartPosition;
private View mTopView;
private View mBottomView;
private View mFloatingHeaderView;
private int mFloatingHeaderPosition;
private int mStickOffset;
public StickyHeaderGridLayoutManager(int spanCount) {
mSpanCount = spanCount;
if (spanCount < 1) {
throw new IllegalArgumentException("Span count should be at least 1. Provided " + spanCount);
}
}
@Override
public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
super.onAdapterChanged(oldAdapter, newAdapter);
try {
mAdapter = (StickyHeaderGridAdapter)newAdapter;
} catch (ClassCastException e) {
throw new ClassCastException("Adapter used with StickyHeaderGridLayoutManager must be kind of StickyHeaderGridAdapter");
}
removeAllViews();
clearState();
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
try {
mAdapter = (StickyHeaderGridAdapter)view.getAdapter();
} catch (ClassCastException e) {
throw new ClassCastException("Adapter used with StickyHeaderGridLayoutManager must be kind of StickyHeaderGridAdapter");
}
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public boolean canScrollVertically() {
return true;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (state.getItemCount() == 0) {
removeAndRecycleAllViews(recycler);
return;
}
// TODO: check this detach logic
detachAndScrapAttachedViews(recycler);
clearState();
int firstAdapterPosition = 0;
if (firstAdapterPosition > state.getItemCount()) {
firstAdapterPosition = 0;
}
int left = getPaddingLeft();
int right = getWidth() - getPaddingRight();
final int bottom = getHeight() - getPaddingBottom();
int totalHeight = 0;
while (true) {
final int adapterPosition = mBottomView == null ? firstAdapterPosition : getPosition(mBottomView) + 1;
if (adapterPosition >= state.getItemCount()) {
break;
}
final int top = mBottomView == null ? getPaddingTop() : getDecoratedBottom(mBottomView);
final int viewType = mAdapter.getItemViewInternalType(adapterPosition);
if (viewType == StickyHeaderGridAdapter.TYPE_HEADER) {
final View v = recycler.getViewForPosition(adapterPosition);
addView(v, mHeadersStartPosition);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top, right, top + height);
if (mTopView == null) {
mTopView = v;
}
mBottomView = v;
}
else {
final View v = fillBottomRow(recycler, state, adapterPosition, top);
if (mTopView == null) {
mTopView = v;
}
mBottomView = v;
}
if (getDecoratedBottom(mBottomView) >= bottom) {
break;
}
}
if (getDecoratedBottom(mBottomView) < bottom) {
scrollVerticallyBy(getDecoratedBottom(mBottomView) - bottom, recycler, state);
}
else {
stickTopHeader(recycler);
}
}
private int getSpanWidth(int recyclerWidth, int spanIndex, int spanSize) {
final int spanWidth = recyclerWidth / mSpanCount;
final int spanWidthReminder = recyclerWidth - spanWidth * mSpanCount;
final int widthCorrection = Math.min(Math.max(0, spanWidthReminder - spanIndex), spanSize);
return spanWidth * spanSize + widthCorrection;
}
private View fillBottomRow(RecyclerView.Recycler recycler, RecyclerView.State state, int adapterPosition, int top) {
final int recyclerWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int left = getPaddingLeft();
int spanIndex = 0;
View v = null;
while (spanIndex < mSpanCount) {
final int spanWidth = getSpanWidth(recyclerWidth, spanIndex, 1);
v = recycler.getViewForPosition(adapterPosition);
addView(v, mHeadersStartPosition++);
measureChildWithMargins(v, recyclerWidth - spanWidth, 0);
final int height = getDecoratedMeasuredHeight(v);
final int width = getDecoratedMeasuredWidth(v);
layoutDecorated(v, left, top, left + width, top + height);
left += spanWidth;
// Check next
adapterPosition++;
if (adapterPosition >= state.getItemCount() || mAdapter.getItemViewInternalType(adapterPosition) != StickyHeaderGridAdapter.TYPE_ITEM) {
break;
}
spanIndex += 1;
}
return v;
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildCount() == 0) {
return 0;
}
int scrolled = 0;
int left = getPaddingLeft();
int right = getWidth() - getPaddingRight();
final int recyclerTop = getPaddingTop();
final int recyclerBottom = getHeight() - getPaddingBottom();
// If we have simple header stick, offset it back
final int topViewType = getViewType(mTopView);
if (topViewType == StickyHeaderGridAdapter.TYPE_HEADER) {
mTopView.offsetTopAndBottom(-mStickOffset);
}
if (dy >= 0) {
// Up
while (scrolled < dy) {
final int scrollChunk = -Math.min(Math.max(getDecoratedBottom(mBottomView) - recyclerBottom, 0), dy - scrolled);
offsetChildrenVertical(scrollChunk);
scrolled -= scrollChunk;
final int top = getDecoratedBottom(mBottomView);
int adapterPosition = getPosition(mBottomView) + 1;
if (scrolled >= dy || adapterPosition >= state.getItemCount()) {
break;
}
final int viewType = mAdapter.getItemViewInternalType(adapterPosition);
if (viewType == StickyHeaderGridAdapter.TYPE_HEADER) {
final View v = recycler.getViewForPosition(adapterPosition);
addView(v, mHeadersStartPosition);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top, right, top + height);
mBottomView = v;
}
else {
mBottomView = fillBottomRow(recycler, state, adapterPosition, top);
}
}
}
else {
// Down
while (scrolled > dy) {
final int scrollChunk = Math.min(Math.max(-getDecoratedTop(mTopView) + recyclerTop, 0), scrolled - dy);
offsetChildrenVertical(scrollChunk);
scrolled -= scrollChunk;
final int top = getDecoratedTop(mTopView);
int adapterPosition = getPosition(mTopView) - 1;
if (scrolled <= dy || adapterPosition >= state.getItemCount() || adapterPosition < 0) {
break;
}
if (mFloatingHeaderView != null && adapterPosition == mFloatingHeaderPosition) {
removeAndRecycleView(mFloatingHeaderView, recycler);
mFloatingHeaderView = null;
mFloatingHeaderPosition = -1;
}
final View v = recycler.getViewForPosition(adapterPosition);
mTopView = v;
final int viewType = getViewType(v);
if (viewType == StickyHeaderGridAdapter.TYPE_HEADER) {
addView(v);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top - height, right, top);
}
else {
addView(v, 0);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top - height, right, top);
mHeadersStartPosition++;
}
}
}
// Remove hidden item views
for (int i = 0; i < mHeadersStartPosition; ++i) {
final View v = getChildAt(i);
if (getDecoratedBottom(v) < recyclerTop || getDecoratedTop(v) > recyclerBottom) {
removeAndRecycleView(v, recycler);
mHeadersStartPosition--;
i--;
}
}
// Remove hidden header views
for (int i = mHeadersStartPosition; i < getChildCount(); ++i) {
final View v = getChildAt(i);
if (v != mFloatingHeaderView && (getDecoratedBottom(v) < recyclerTop || getDecoratedTop(v) > recyclerBottom)) {
removeAndRecycleView(v, recycler);
i--;
}
}
// Update top/bottom views
if (getChildCount() > 0) {
mTopView = getTopmostView();
mBottomView = getBottommostView();
stickTopHeader(recycler);
}
else {
mTopView = mBottomView = null;
}
return scrolled;
}
private View getTopmostView() {
View top = null;
if (getChildCount() > 0 && mHeadersStartPosition > 0) {
top = getChildAt(0);
}
for (int i = getChildCount() - 1; i >= mHeadersStartPosition ; --i) {
final View topHeader = getChildAt(i);
if (topHeader == mFloatingHeaderView) {
continue;
}
if (top == null || getDecoratedTop(topHeader) < getDecoratedTop(top)) {
top = topHeader;
break;
}
}
return top;
}
private View getBottommostView() {
View bottom = null;
if (getChildCount() > 0 && mHeadersStartPosition > 0) {
bottom = getChildAt(mHeadersStartPosition - 1);
}
if (mHeadersStartPosition < getChildCount()) {
final View bottomHeader = getChildAt(mHeadersStartPosition);
if (bottom == null || getDecoratedBottom(bottomHeader) > getDecoratedBottom(bottom)) {
bottom = bottomHeader;
}
}
return bottom;
}
private View getNextHeader(View fromHeader) {
boolean found = false;
for (int i = getChildCount() - 1; i >= mHeadersStartPosition ; --i) {
final View header = getChildAt(i);
if (header == fromHeader) {
found = true;
continue;
}
if (found) {
return header;
}
}
return null;
}
private void stickTopHeader(RecyclerView.Recycler recycler) {
final int topViewType = getViewType(mTopView);
final int top = getPaddingTop();
final int left = getPaddingLeft();
final int right = getWidth() - getPaddingRight();
if (topViewType == StickyHeaderGridAdapter.TYPE_HEADER) {
final int height = getDecoratedMeasuredHeight(mTopView);
final View nextHeader = getNextHeader(mTopView);
int offset = 0;
if (nextHeader != null) {
offset = Math.max(top - getDecoratedTop(nextHeader), -height) + height;
}
if (offset <= 0) {
mStickOffset = top - getDecoratedTop(mTopView);
mTopView.offsetTopAndBottom(mStickOffset);
}
else {
mStickOffset = 0;
}
}
else {
// Find section number and create header if needed
final int adapterPosition = getPosition(mTopView);
final int section = mAdapter.getPositionSection(adapterPosition);
if (section != -1) {
final int headerPosition = mAdapter.getSectionHeaderPosition(section);
if (mFloatingHeaderView == null || mFloatingHeaderPosition != headerPosition) {
if (mFloatingHeaderView != null) {
removeAndRecycleView(mFloatingHeaderView, recycler);
}
// Create floating header
final View v = recycler.getViewForPosition(headerPosition);
addView(v);
measureChildWithMargins(v, 0, 0);
mFloatingHeaderView = v;
mFloatingHeaderPosition = headerPosition;
}
// Push floating header up, if needed
final int height = getDecoratedMeasuredHeight(mFloatingHeaderView);
int offset = 0;
if (getChildCount() - mHeadersStartPosition > 1) {
final View nextHeader = getChildAt(getChildCount() - 2);
offset = Math.max(top - getDecoratedTop(nextHeader), -height) + height;
}
layoutDecorated(mFloatingHeaderView, left, top - offset, right, top + height - offset);
}
}
}
private int getViewType(View view) {
return getItemViewType(view) & 0xFF;
}
private int getViewType(int position) {
return mAdapter.getItemViewType(position) & 0xFF;
}
private void clearState() {
mTopView = mBottomView = null;
mHeadersStartPosition = 0;
mStickOffset = 0;
mFloatingHeaderView = null;
}
public static class LayoutParams extends RecyclerView.LayoutParams {
public static final int INVALID_SPAN_ID = -1;
int mSpanIndex = INVALID_SPAN_ID;
int mSpanSize = 0;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(RecyclerView.LayoutParams source) {
super(source);
}
public int getSpanIndex() {
return mSpanIndex;
}
public int getSpanSize() {
return mSpanSize;
}
}
}
| stickyheadergrid/src/main/java/com/codewaves/stickyheadergrid/StickyHeaderGridLayoutManager.java | package com.codewaves.stickyheadergrid;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Sergej Kravcenko on 4/24/2017.
* Copyright (c) 2017 Sergej Kravcenko
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class StickyHeaderGridLayoutManager extends RecyclerView.LayoutManager {
public static final String TAG = "StickyLayoutManager";
private int mSpanCount;
private StickyHeaderGridAdapter mAdapter;
private int mHeadersStartPosition;
private View mTopView;
private View mBottomView;
private View mFloatingHeaderView;
private int mFloatingHeaderPosition;
private int mStickOffset;
public StickyHeaderGridLayoutManager(int spanCount) {
mSpanCount = spanCount;
if (spanCount < 1) {
throw new IllegalArgumentException("Span count should be at least 1. Provided " + spanCount);
}
}
@Override
public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
super.onAdapterChanged(oldAdapter, newAdapter);
try {
mAdapter = (StickyHeaderGridAdapter)newAdapter;
} catch (ClassCastException e) {
throw new ClassCastException("Adapter used with StickyHeaderGridLayoutManager must be kind of StickyHeaderGridAdapter");
}
removeAllViews();
clearState();
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
try {
mAdapter = (StickyHeaderGridAdapter)view.getAdapter();
} catch (ClassCastException e) {
throw new ClassCastException("Adapter used with StickyHeaderGridLayoutManager must be kind of StickyHeaderGridAdapter");
}
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public boolean canScrollVertically() {
return true;
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
if (state.getItemCount() == 0) {
removeAndRecycleAllViews(recycler);
return;
}
// TODO: check this detach logic
detachAndScrapAttachedViews(recycler);
clearState();
int firstAdapterPosition = 0;
if (firstAdapterPosition > state.getItemCount()) {
firstAdapterPosition = 0;
}
int left = getPaddingLeft();
int right = getWidth() - getPaddingRight();
final int bottom = getHeight() - getPaddingBottom();
int totalHeight = 0;
while (true) {
final int adapterPosition = mBottomView == null ? firstAdapterPosition : getPosition(mBottomView) + 1;
if (adapterPosition >= state.getItemCount()) {
break;
}
final int top = mBottomView == null ? getPaddingTop() : getDecoratedBottom(mBottomView);
final int viewType = mAdapter.getItemViewInternalType(adapterPosition);
if (viewType == StickyHeaderGridAdapter.TYPE_HEADER) {
final View v = recycler.getViewForPosition(adapterPosition);
addView(v, mHeadersStartPosition);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top, right, top + height);
if (mTopView == null) {
mTopView = v;
}
mBottomView = v;
}
else {
final View v = fillBottomRow(recycler, state, adapterPosition, top);
if (mTopView == null) {
mTopView = v;
}
mBottomView = v;
}
if (getDecoratedBottom(mBottomView) >= bottom) {
break;
}
}
if (getDecoratedBottom(mBottomView) < bottom) {
scrollVerticallyBy(getDecoratedBottom(mBottomView) - bottom, recycler, state);
}
else {
stickTopHeader(recycler);
}
}
private View fillBottomRow(RecyclerView.Recycler recycler, RecyclerView.State state, int adapterPosition, int top) {
final int contentWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int left = getPaddingLeft();
int spanRemainder = mSpanCount;
View bottomView = null;
while (spanRemainder > 0) {
bottomView = recycler.getViewForPosition(adapterPosition);
addView(bottomView, mHeadersStartPosition++);
measureChildWithMargins(bottomView, contentWidth / mSpanCount * 2, 0);
final int height = getDecoratedMeasuredHeight(bottomView);
final int width = getDecoratedMeasuredWidth(bottomView);
layoutDecorated(bottomView, left, top, left + width, top + height);
left += contentWidth / mSpanCount;
// Check next
adapterPosition++;
if (adapterPosition >= state.getItemCount() || mAdapter.getItemViewInternalType(adapterPosition) != StickyHeaderGridAdapter.TYPE_ITEM) {
break;
}
spanRemainder -= 1;
}
return bottomView;
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildCount() == 0) {
return 0;
}
int scrolled = 0;
int left = getPaddingLeft();
int right = getWidth() - getPaddingRight();
final int recyclerTop = getPaddingTop();
final int recyclerBottom = getHeight() - getPaddingBottom();
// If we have simple header stick, offset it back
final int topViewType = getViewType(mTopView);
if (topViewType == StickyHeaderGridAdapter.TYPE_HEADER) {
mTopView.offsetTopAndBottom(-mStickOffset);
}
if (dy >= 0) {
// Up
while (scrolled < dy) {
final int scrollChunk = -Math.min(Math.max(getDecoratedBottom(mBottomView) - recyclerBottom, 0), dy - scrolled);
offsetChildrenVertical(scrollChunk);
scrolled -= scrollChunk;
final int top = getDecoratedBottom(mBottomView);
int adapterPosition = getPosition(mBottomView) + 1;
if (scrolled >= dy || adapterPosition >= state.getItemCount()) {
break;
}
final int viewType = mAdapter.getItemViewInternalType(adapterPosition);
if (viewType == StickyHeaderGridAdapter.TYPE_HEADER) {
final View v = recycler.getViewForPosition(adapterPosition);
addView(v, mHeadersStartPosition);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top, right, top + height);
mBottomView = v;
}
else {
mBottomView = fillBottomRow(recycler, state, adapterPosition, top);
}
}
}
else {
// Down
while (scrolled > dy) {
final int scrollChunk = Math.min(Math.max(-getDecoratedTop(mTopView) + recyclerTop, 0), scrolled - dy);
offsetChildrenVertical(scrollChunk);
scrolled -= scrollChunk;
final int top = getDecoratedTop(mTopView);
int adapterPosition = getPosition(mTopView) - 1;
if (scrolled <= dy || adapterPosition >= state.getItemCount() || adapterPosition < 0) {
break;
}
if (mFloatingHeaderView != null && adapterPosition == mFloatingHeaderPosition) {
removeAndRecycleView(mFloatingHeaderView, recycler);
mFloatingHeaderView = null;
mFloatingHeaderPosition = -1;
}
final View v = recycler.getViewForPosition(adapterPosition);
mTopView = v;
final int viewType = getViewType(v);
if (viewType == StickyHeaderGridAdapter.TYPE_HEADER) {
addView(v);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top - height, right, top);
}
else {
addView(v, 0);
measureChildWithMargins(v, 0, 0);
final int height = getDecoratedMeasuredHeight(v);
layoutDecorated(v, left, top - height, right, top);
mHeadersStartPosition++;
}
}
}
// Remove hidden item views
for (int i = 0; i < mHeadersStartPosition; ++i) {
final View v = getChildAt(i);
if (getDecoratedBottom(v) < recyclerTop || getDecoratedTop(v) > recyclerBottom) {
removeAndRecycleView(v, recycler);
mHeadersStartPosition--;
i--;
}
}
// Remove hidden header views
for (int i = mHeadersStartPosition; i < getChildCount(); ++i) {
final View v = getChildAt(i);
if (v != mFloatingHeaderView && (getDecoratedBottom(v) < recyclerTop || getDecoratedTop(v) > recyclerBottom)) {
removeAndRecycleView(v, recycler);
i--;
}
}
// Update top/bottom views
if (getChildCount() > 0) {
mTopView = getTopmostView();
mBottomView = getBottommostView();
stickTopHeader(recycler);
}
else {
mTopView = mBottomView = null;
}
return scrolled;
}
private View getTopmostView() {
View top = null;
if (getChildCount() > 0 && mHeadersStartPosition > 0) {
top = getChildAt(0);
}
for (int i = getChildCount() - 1; i >= mHeadersStartPosition ; --i) {
final View topHeader = getChildAt(i);
if (topHeader == mFloatingHeaderView) {
continue;
}
if (top == null || getDecoratedTop(topHeader) < getDecoratedTop(top)) {
top = topHeader;
break;
}
}
return top;
}
private View getBottommostView() {
View bottom = null;
if (getChildCount() > 0 && mHeadersStartPosition > 0) {
bottom = getChildAt(mHeadersStartPosition - 1);
}
if (mHeadersStartPosition < getChildCount()) {
final View bottomHeader = getChildAt(mHeadersStartPosition);
if (bottom == null || getDecoratedBottom(bottomHeader) > getDecoratedBottom(bottom)) {
bottom = bottomHeader;
}
}
return bottom;
}
private View getNextHeader(View fromHeader) {
boolean found = false;
for (int i = getChildCount() - 1; i >= mHeadersStartPosition ; --i) {
final View header = getChildAt(i);
if (header == fromHeader) {
found = true;
continue;
}
if (found) {
return header;
}
}
return null;
}
private void stickTopHeader(RecyclerView.Recycler recycler) {
final int topViewType = getViewType(mTopView);
final int top = getPaddingTop();
final int left = getPaddingLeft();
final int right = getWidth() - getPaddingRight();
if (topViewType == StickyHeaderGridAdapter.TYPE_HEADER) {
final int height = getDecoratedMeasuredHeight(mTopView);
final View nextHeader = getNextHeader(mTopView);
int offset = 0;
if (nextHeader != null) {
offset = Math.max(top - getDecoratedTop(nextHeader), -height) + height;
}
if (offset <= 0) {
mStickOffset = top - getDecoratedTop(mTopView);
mTopView.offsetTopAndBottom(mStickOffset);
}
else {
mStickOffset = 0;
}
}
else {
// Find section number and create header if needed
final int adapterPosition = getPosition(mTopView);
final int section = mAdapter.getPositionSection(adapterPosition);
if (section != -1) {
final int headerPosition = mAdapter.getSectionHeaderPosition(section);
if (mFloatingHeaderView == null || mFloatingHeaderPosition != headerPosition) {
if (mFloatingHeaderView != null) {
removeAndRecycleView(mFloatingHeaderView, recycler);
}
// Create floating header
final View v = recycler.getViewForPosition(headerPosition);
addView(v);
measureChildWithMargins(v, 0, 0);
mFloatingHeaderView = v;
mFloatingHeaderPosition = headerPosition;
}
// Push floating header up, if needed
final int height = getDecoratedMeasuredHeight(mFloatingHeaderView);
int offset = 0;
if (getChildCount() - mHeadersStartPosition > 1) {
final View nextHeader = getChildAt(getChildCount() - 2);
offset = Math.max(top - getDecoratedTop(nextHeader), -height) + height;
}
layoutDecorated(mFloatingHeaderView, left, top - offset, right, top + height - offset);
}
}
}
private int getViewType(View view) {
return getItemViewType(view) & 0xFF;
}
private int getViewType(int position) {
return mAdapter.getItemViewType(position) & 0xFF;
}
private void clearState() {
mTopView = mBottomView = null;
mHeadersStartPosition = 0;
mStickOffset = 0;
mFloatingHeaderView = null;
}
public static class LayoutParams extends RecyclerView.LayoutParams {
public static final int INVALID_SPAN_ID = -1;
int mSpanIndex = INVALID_SPAN_ID;
int mSpanSize = 0;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(RecyclerView.LayoutParams source) {
super(source);
}
public int getSpanIndex() {
return mSpanIndex;
}
public int getSpanSize() {
return mSpanSize;
}
}
}
| Add span width correction
| stickyheadergrid/src/main/java/com/codewaves/stickyheadergrid/StickyHeaderGridLayoutManager.java | Add span width correction | <ide><path>tickyheadergrid/src/main/java/com/codewaves/stickyheadergrid/StickyHeaderGridLayoutManager.java
<ide> }
<ide> }
<ide>
<add> private int getSpanWidth(int recyclerWidth, int spanIndex, int spanSize) {
<add> final int spanWidth = recyclerWidth / mSpanCount;
<add> final int spanWidthReminder = recyclerWidth - spanWidth * mSpanCount;
<add> final int widthCorrection = Math.min(Math.max(0, spanWidthReminder - spanIndex), spanSize);
<add>
<add> return spanWidth * spanSize + widthCorrection;
<add> }
<add>
<ide> private View fillBottomRow(RecyclerView.Recycler recycler, RecyclerView.State state, int adapterPosition, int top) {
<del> final int contentWidth = getWidth() - getPaddingLeft() - getPaddingRight();
<add> final int recyclerWidth = getWidth() - getPaddingLeft() - getPaddingRight();
<ide> int left = getPaddingLeft();
<del> int spanRemainder = mSpanCount;
<del> View bottomView = null;
<del>
<del> while (spanRemainder > 0) {
<del> bottomView = recycler.getViewForPosition(adapterPosition);
<del> addView(bottomView, mHeadersStartPosition++);
<del> measureChildWithMargins(bottomView, contentWidth / mSpanCount * 2, 0);
<del>
<del> final int height = getDecoratedMeasuredHeight(bottomView);
<del> final int width = getDecoratedMeasuredWidth(bottomView);
<del> layoutDecorated(bottomView, left, top, left + width, top + height);
<del> left += contentWidth / mSpanCount;
<add> int spanIndex = 0;
<add> View v = null;
<add>
<add> while (spanIndex < mSpanCount) {
<add> final int spanWidth = getSpanWidth(recyclerWidth, spanIndex, 1);
<add>
<add> v = recycler.getViewForPosition(adapterPosition);
<add> addView(v, mHeadersStartPosition++);
<add> measureChildWithMargins(v, recyclerWidth - spanWidth, 0);
<add>
<add> final int height = getDecoratedMeasuredHeight(v);
<add> final int width = getDecoratedMeasuredWidth(v);
<add> layoutDecorated(v, left, top, left + width, top + height);
<add> left += spanWidth;
<ide>
<ide> // Check next
<ide> adapterPosition++;
<ide> if (adapterPosition >= state.getItemCount() || mAdapter.getItemViewInternalType(adapterPosition) != StickyHeaderGridAdapter.TYPE_ITEM) {
<ide> break;
<ide> }
<del> spanRemainder -= 1;
<del> }
<del>
<del> return bottomView;
<add> spanIndex += 1;
<add> }
<add>
<add> return v;
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 9f312e01dc1f221bb9ec05ff4298f0fdf73c7331 | 0 | aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips,aterai/java-swing-tips | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Collections;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
int n = 1024 * 1024 - 2;
String txt = String.join("", Collections.nCopies(n, "a")) + "x\n";
// Java 11: String txt = "a".repeat(n) + "x\n";
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new NoWrapEditorKit2());
JTextArea textArea = new JTextArea();
JButton editorPaneButton = new JButton("JEditorPane");
JButton textAreaButton = new JButton("JTextArea");
// JTextPane textPane = new JTextPane() {
// // Non Wrapping(Wrap) TextPane : TextField : Swing JFC : Java
// // http://www.java2s.com/Code/Java/Swing-JFC/NonWrappingWrapTextPane.htm
// @Override public boolean getScrollableTracksViewportWidth() {
// Component p = getParent();
// if (Objects.isNull(p)) {
// return true;
// }
// return getUI().getPreferredSize(this).width <= p.getSize().width;
// }
// };
// textPane.setEditorKit(new NoWrapEditorKit1());
ActionListener longTextListener = e -> {
if (editorPaneButton.equals(e.getSource())) {
editorPane.setText(txt);
} else {
textArea.setText(txt);
}
};
editorPaneButton.addActionListener(longTextListener);
textAreaButton.addActionListener(longTextListener);
JButton clearButton = new JButton("clear all");
clearButton.addActionListener(e -> {
editorPane.setText("");
textArea.setText("");
});
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(editorPaneButton);
box.add(textAreaButton);
box.add(clearButton);
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(makeTitledPanel("NoWrapEditorKit(JEditorPane)", editorPane));
p.add(makeTitledPanel("JTextArea", textArea));
add(box, BorderLayout.NORTH);
add(p);
setPreferredSize(new Dimension(320, 240));
}
private static Component makeTitledPanel(String title, Component c) {
JScrollPane sp = new JScrollPane(c);
sp.setBorder(BorderFactory.createTitledBorder(title));
return sp;
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
/*
class NoWrapEditorKit1 extends StyledEditorKit {
@Override public ViewFactory getViewFactory() {
return new StyledViewFactory();
}
static class StyledViewFactory implements ViewFactory {
@Override public View create(Element elem) {
String kind = elem.getName();
if (Objects.nonNull(kind)) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new LabelView(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (kind.equals(AbstractDocument.SectionElementName)) {
return new NoWrapBoxView(elem, View.Y_AXIS);
} else if (kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
return new LabelView(elem);
}
}
static class NoWrapBoxView extends BoxView {
protected NoWrapBoxView(Element elem, int axis) {
super(elem, axis);
}
@Override public void layout(int width, int height) {
super.layout(Integer.MAX_VALUE - 64, height);
// ??? Integer.MAX_VALUE - 64 = error?
// ??? Integer.MAX_VALUE - 64 = ok?
}
}
}
/*/
// https://community.oracle.com/thread/1353861 Disabling word wrap for JTextPane
class NoWrapParagraphView extends ParagraphView {
protected NoWrapParagraphView(Element elem) {
super(elem);
}
@Override protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
SizeRequirements req = super.calculateMinorAxisRequirements(axis, r);
req.minimum = req.preferred;
return req;
}
@Override public int getFlowSpan(int index) {
return Integer.MAX_VALUE;
}
}
class NoWrapViewFactory implements ViewFactory {
@Override public View create(Element elem) {
switch (elem.getName()) {
// case AbstractDocument.ContentElementName:
// return new LabelView(elem);
case AbstractDocument.ParagraphElementName:
return new NoWrapParagraphView(elem);
case AbstractDocument.SectionElementName:
return new BoxView(elem, View.Y_AXIS);
case StyleConstants.ComponentElementName:
return new ComponentView(elem);
case StyleConstants.IconElementName:
return new IconView(elem);
default:
return new LabelView(elem);
}
}
}
class NoWrapEditorKit2 extends StyledEditorKit {
@Override public ViewFactory getViewFactory() {
return new NoWrapViewFactory();
}
}
//*/
| NoWrapTextPane/src/java/example/MainPanel.java | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.ParagraphView;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
public final class MainPanel extends JPanel {
private static String text;
private MainPanel(ExecutorService threadPool) {
super(new BorderLayout());
// JTextPane textPane;
JEditorPane editorPane = new JEditorPane();
JTextArea textArea = new JTextArea();
JButton editorPaneButton = new JButton("JEditorPane");
JButton textAreaButton = new JButton("JTextArea");
// textPane = new JTextPane() {
// // Non Wrapping(Wrap) TextPane : TextField : Swing JFC : Java
// // http://www.java2s.com/Code/Java/Swing-JFC/NonWrappingWrapTextPane.htm
// @Override public boolean getScrollableTracksViewportWidth() {
// Component p = getParent();
// if (Objects.isNull(p)) {
// return true;
// }
// return getUI().getPreferredSize(this).width <= p.getSize().width;
// }
// };
// textPane.setEditorKit(new NoWrapEditorKit1());
editorPane.setEditorKit(new NoWrapEditorKit2());
ActionListener longTextListener = e -> threadPool.execute(() -> {
if (Objects.nonNull(text)) {
if (editorPaneButton.equals(e.getSource())) {
editorPane.setText(text);
} else {
textArea.setText(text);
}
}
});
editorPaneButton.addActionListener(longTextListener);
textAreaButton.addActionListener(longTextListener);
JButton clearButton = new JButton("clear all");
clearButton.addActionListener(e -> {
editorPane.setText("");
textArea.setText("");
});
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(editorPaneButton);
box.add(textAreaButton);
box.add(clearButton);
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(makeTitledPanel("NoWrapEditorKit(JEditorPane)", editorPane));
p.add(makeTitledPanel("JTextArea", textArea));
add(box, BorderLayout.NORTH);
add(p);
setPreferredSize(new Dimension(320, 240));
}
private static Component makeTitledPanel(String title, Component c) {
JScrollPane sp = new JScrollPane(c);
sp.setBorder(BorderFactory.createTitledBorder(title));
return sp;
}
public static void initLongLineStringInBackground(ExecutorService threadPool, int length) {
threadPool.execute(() -> {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length - 2; i++) {
sb.append('a');
}
sb.append("x\n");
text = sb.toString();
});
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
ExecutorService threadPool = Executors.newCachedThreadPool();
initLongLineStringInBackground(threadPool, 1024 * 1024);
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel(threadPool));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
/*
class NoWrapEditorKit1 extends StyledEditorKit {
@Override public ViewFactory getViewFactory() {
return new StyledViewFactory();
}
static class StyledViewFactory implements ViewFactory {
@Override public View create(Element elem) {
String kind = elem.getName();
if (Objects.nonNull(kind)) {
if (kind.equals(AbstractDocument.ContentElementName)) {
return new LabelView(elem);
} else if (kind.equals(AbstractDocument.ParagraphElementName)) {
return new ParagraphView(elem);
} else if (kind.equals(AbstractDocument.SectionElementName)) {
return new NoWrapBoxView(elem, View.Y_AXIS);
} else if (kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
} else if (kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
return new LabelView(elem);
}
}
static class NoWrapBoxView extends BoxView {
protected NoWrapBoxView(Element elem, int axis) {
super(elem, axis);
}
@Override public void layout(int width, int height) {
super.layout(Integer.MAX_VALUE - 64, height);
// ??? Integer.MAX_VALUE - 64 = error?
// ??? Integer.MAX_VALUE - 64 = ok?
}
}
}
/*/
// https://community.oracle.com/thread/1353861 Disabling word wrap for JTextPane
class NoWrapParagraphView extends ParagraphView {
protected NoWrapParagraphView(Element elem) {
super(elem);
}
@Override protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) {
SizeRequirements req = super.calculateMinorAxisRequirements(axis, r);
req.minimum = req.preferred;
return req;
}
@Override public int getFlowSpan(int index) {
return Integer.MAX_VALUE;
}
}
class NoWrapViewFactory implements ViewFactory {
@Override public View create(Element elem) {
switch (elem.getName()) {
// case AbstractDocument.ContentElementName:
// return new LabelView(elem);
case AbstractDocument.ParagraphElementName:
return new NoWrapParagraphView(elem);
case AbstractDocument.SectionElementName:
return new BoxView(elem, View.Y_AXIS);
case StyleConstants.ComponentElementName:
return new ComponentView(elem);
case StyleConstants.IconElementName:
return new IconView(elem);
default:
return new LabelView(elem);
}
}
}
class NoWrapEditorKit2 extends StyledEditorKit {
@Override public ViewFactory getViewFactory() {
return new NoWrapViewFactory();
}
}
//*/
| PMD: CloseResource
| NoWrapTextPane/src/java/example/MainPanel.java | PMD: CloseResource | <ide><path>oWrapTextPane/src/java/example/MainPanel.java
<ide>
<ide> import java.awt.*;
<ide> import java.awt.event.ActionListener;
<del>import java.util.Objects;
<del>import java.util.concurrent.ExecutorService;
<del>import java.util.concurrent.Executors;
<add>import java.util.Collections;
<ide> import javax.swing.*;
<ide> import javax.swing.text.AbstractDocument;
<ide> import javax.swing.text.BoxView;
<ide> import javax.swing.text.ViewFactory;
<ide>
<ide> public final class MainPanel extends JPanel {
<del> private static String text;
<add> private MainPanel() {
<add> super(new BorderLayout());
<add> int n = 1024 * 1024 - 2;
<add> String txt = String.join("", Collections.nCopies(n, "a")) + "x\n";
<add> // Java 11: String txt = "a".repeat(n) + "x\n";
<ide>
<del> private MainPanel(ExecutorService threadPool) {
<del> super(new BorderLayout());
<add> JEditorPane editorPane = new JEditorPane();
<add> editorPane.setEditorKit(new NoWrapEditorKit2());
<ide>
<del> // JTextPane textPane;
<del> JEditorPane editorPane = new JEditorPane();
<ide> JTextArea textArea = new JTextArea();
<add>
<ide> JButton editorPaneButton = new JButton("JEditorPane");
<ide> JButton textAreaButton = new JButton("JTextArea");
<ide>
<del> // textPane = new JTextPane() {
<add> // JTextPane textPane = new JTextPane() {
<ide> // // Non Wrapping(Wrap) TextPane : TextField : Swing JFC : Java
<ide> // // http://www.java2s.com/Code/Java/Swing-JFC/NonWrappingWrapTextPane.htm
<ide> // @Override public boolean getScrollableTracksViewportWidth() {
<ide> // };
<ide> // textPane.setEditorKit(new NoWrapEditorKit1());
<ide>
<del> editorPane.setEditorKit(new NoWrapEditorKit2());
<del>
<del> ActionListener longTextListener = e -> threadPool.execute(() -> {
<del> if (Objects.nonNull(text)) {
<del> if (editorPaneButton.equals(e.getSource())) {
<del> editorPane.setText(text);
<del> } else {
<del> textArea.setText(text);
<del> }
<add> ActionListener longTextListener = e -> {
<add> if (editorPaneButton.equals(e.getSource())) {
<add> editorPane.setText(txt);
<add> } else {
<add> textArea.setText(txt);
<ide> }
<del> });
<add> };
<ide> editorPaneButton.addActionListener(longTextListener);
<ide> textAreaButton.addActionListener(longTextListener);
<ide>
<ide> return sp;
<ide> }
<ide>
<del> public static void initLongLineStringInBackground(ExecutorService threadPool, int length) {
<del> threadPool.execute(() -> {
<del> StringBuilder sb = new StringBuilder(length);
<del> for (int i = 0; i < length - 2; i++) {
<del> sb.append('a');
<del> }
<del> sb.append("x\n");
<del> text = sb.toString();
<del> });
<del> }
<del>
<ide> public static void main(String[] args) {
<ide> EventQueue.invokeLater(MainPanel::createAndShowGui);
<ide> }
<ide> ex.printStackTrace();
<ide> Toolkit.getDefaultToolkit().beep();
<ide> }
<del> ExecutorService threadPool = Executors.newCachedThreadPool();
<del> initLongLineStringInBackground(threadPool, 1024 * 1024);
<ide> JFrame frame = new JFrame("@title@");
<ide> frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
<del> frame.getContentPane().add(new MainPanel(threadPool));
<add> frame.getContentPane().add(new MainPanel());
<ide> frame.pack();
<ide> frame.setLocationRelativeTo(null);
<ide> frame.setVisible(true); |
|
JavaScript | agpl-3.0 | c7b457afb105dc9a16472ae46cea2bacb64205b9 | 0 | axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit | /*
* Axelor Business Solutions
*
* Copyright (C) 2005-2014 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function(){
var ui = angular.module('axelor.ui');
var popoverElem = null;
var popoverTimer = null;
function canDisplayPopover(scope, details) {
var mode = __appSettings['application.mode'];
var tech = __appSettings['user.technical'];
if(mode == 'prod' && !tech) {
return details ? false : scope.field && scope.field.help;
}
return true;
}
function makePopover(scope, element, callback, placement) {
var mode = __appSettings['application.mode'];
var tech = __appSettings['user.technical'];
var doc = $(document);
var table = null;
function addRow(label, text, klass) {
if (table === null) {
table = $('<table class="field-details"></table>');
}
var tr = $('<tr></tr>').appendTo(table);
if (label) {
$('<th></th>').text(label).appendTo(tr);
}
if (klass == null) {
text = '<code>' + text + '</code>';
}
var td = $('<td></td>').html(text).addClass(klass).appendTo(tr);
if (!label) {
td.attr('colspan', 2);
}
return table;
}
element.popover({
html: true,
delay: { show: 1000, hide: 100 },
animate: true,
placement: function() {
if (placement) return placement;
var coord = $(element.get(0)).offset(),
viewport = {height: innerHeight, width: window.innerWidth};
if(viewport.height < (coord.top + 100))
return 'top';
if(coord.left > (viewport.width / 2))
return 'left';
return 'right';
},
trigger: 'manual',
container: 'body',
title: function() {
return element.text();
},
content: function() {
if (table) {
table.remove();
table = null;
}
callback(scope, addRow);
if (table) return table;
return "";
}
});
element.on('mouseenter.popover', enter);
element.on('mouseleave.popover', leave);
function enter(e) {
if (popoverTimer) {
clearTimeout(popoverTimer);
}
popoverTimer = setTimeout(function () {
if (popoverElem === null) {
popoverElem = element;
popoverElem.popover('show');
}
var tip = element.data('popover').$tip;
if (tip) {
tip.attr('tabIndex', 0);
tip.css('outline', 'none');
}
}, 1000);
}
function leave(e) {
if (e.ctrlKey) {
doc.off('mousemove.popover');
doc.on('mousemove.popover', leave);
return;
}
if (popoverTimer) {
clearTimeout(popoverTimer);
popoverTimer = null;
}
if (popoverElem) {
popoverElem.popover('hide');
popoverElem = null;
doc.off('mousemove.popover');
}
}
function destroy() {
if (element) {
element.off('mouseenter.popover');
element.off('mouseleave.popover');
element.popover('destroy');
element = null;
}
if (table) {
table.remove();
table = null;
}
doc.off('mousemove.popover');
}
scope.$on('$destroy', destroy);
}
ui.directive('uiTabPopover', function() {
function getHelp(scope, addRow) {
var tab = scope.tab || {};
var type = tab.viewType;
var view = _.findWhere(tab.views, {type: type});
var viewScope = tab.$viewScope;
if (viewScope && viewScope.schema) {
view = viewScope.schema;
}
if (tab.action) {
addRow(_t('Action'), tab.action);
}
if (tab.model) {
addRow(_t('Object'), tab.model);
}
if (tab.domain) {
addRow(_t('Domain'), tab.domain);
}
if (view && view.name) {
addRow(_t('View'), view.name);
}
}
return function (scope, element, attrs) {
if(canDisplayPopover(scope, true)) {
return makePopover(scope, element, getHelp, 'bottom');
}
};
});
ui.directive('uiHelpPopover', function() {
function getHelp(scope, addRow) {
var field = scope.field;
var text = field.help;
if (text) {
text = text.replace(/\\n/g, '<br>');
addRow(null, text, 'help-text');
}
if (text) {
addRow(null, '<hr noshade>', 'help-text');
}
if(!canDisplayPopover(scope, true)) {
return;
}
var model = scope._model;
if (model === field.target) {
model = scope._parentModel || scope.$parent._model;
}
addRow(_t('Object'), model);
addRow(_t('Field Name'), field.name);
addRow(_t('Field Type'), field.serverType);
if (field.type === 'text') {
return;
}
if (field.domain) {
addRow(_t('Filter'), field.domain);
}
if (field.target) {
addRow(_t('Reference'), field.target);
}
var value = scope.$eval('$$original.' + field.name);
if (value && /-one$/.test(field.serverType)) {
value = _.compact([value.id, value[field.targetName]]).join(',');
value = '(' + value + ')';
}
if (value && field.type === "password") {
value = _.str.repeat('*', value.length);
}
if (value && /^(string|image|binary)$/.test(field.type)) {
var length = value.length;
value = _.first(value, 50);
if (length > 50) {
value.push('...');
}
value = value.join('');
}
if (value && /(panel-related|one-to-many|many-to-many)/.test(field.serverType)) {
var length = value.length;
value = _.first(value, 5);
value = _.map(value, function(v){
return v.id;
});
if (length > 5) {
value.push('...');
}
value = value.join(', ');
}
addRow(_t('Orig. Value'), value);
}
function doLink(scope, element, attrs) {
var field = scope.field;
if (field == null) {
return;
}
if(canDisplayPopover(scope, false)) {
makePopover(scope, element, getHelp);
}
};
return function(scope, element, attrs) {
var field = scope.field;
if (!_.isEmpty(field)) {
return doLink(scope, element, attrs);
}
var unwatch = scope.$watch('field', function(field, old) {
if (!field) {
return;
}
unwatch();
doLink(scope, element, attrs);
}, true);
};
});
/**
* The Label widget.
*
*/
ui.formItem('Label', {
css: 'label-item',
cellCss: 'form-label',
transclude: true,
link: function(scope, element, attrs) {
var field = scope.field;
if (field && field.required) {
element.addClass('required');
}
},
template: '<label><sup ng-if="field.help">?</sup><span ui-help-popover ng-transclude></span></label>'
});
/**
* The Spacer widget.
*
*/
ui.formItem('Spacer', {
css: 'spacer-item',
template: '<div> </div>'
});
/**
* The Separator widget.
*
*/
ui.formItem('Separator', {
css: 'separator-item',
showTitle: false,
template: '<div><span>{{field.title}}</span><hr></div>'
});
/**
* The Static Text widget.
*
*/
ui.formItem('Static', {
css: 'static-item',
transclude: true,
template: '<label ng-transclude></label>'
});
/**
* The button widget.
*/
ui.formItem('Button', {
css: 'button-item',
transclude: true,
link: function(scope, element, attrs, model) {
var field = scope.field || {};
var icon = field.icon || "";
var iconHover = field.iconHover || "";
var isIcon = icon.indexOf('fa-') === 0;
if (isIcon || icon) {
element.prepend(' ');
}
if (isIcon) {
var e = $('<i>').addClass('fa').addClass(icon).prependTo(element);
if (iconHover) {
e.hover(function() {
$(this).removeClass(icon).addClass(iconHover);
}, function() {
$(this).removeClass(iconHover).addClass(icon);
});
}
} else if (icon) {
$('<img>').attr('src', icon).prependTo(element);
}
if (!field.title) {
element.addClass("button-icon");
}
if (_.isString(field.link)) {
element.removeClass('btn');
element.attr("href", field.link);
}
element.tooltip({
html: true,
title: function() {
if (field.help) {
return field.help;
}
if (element.innerWidth() < element[0].scrollWidth) {
return field.title;
}
},
delay: { show: 1000, hide: 100 },
container: 'body'
});
element.on("click", function(e) {
if (scope.isReadonlyExclusive() || element.hasClass('disabled')) {
return;
}
function enable() {
scope.ajaxStop(function () {
setDisabled(scope.isReadonly());
}, 100);
}
function setEnable(p) {
if (p && p.then) {
p.then(enable, enable);
} else {
scope.ajaxStop(enable, 500);
}
}
function doClick() {
setEnable(scope.fireAction("onClick"));
}
setDisabled(true);
if (scope.waitForActions) {
return scope.waitForActions(doClick);
}
return doClick();
});
function setDisabled(disabled) {
if (disabled || disabled === undefined) {
return element.addClass("disabled").attr('tabindex', -1);
}
return element.removeClass("disabled").removeAttr('tabindex');
}
var readonlySet = false;
scope.$watch('isReadonlyExclusive()', function(readonly, old) {
if (readonly === old && readonlySet) return;
readonlySet = true;
return setDisabled(readonly);
});
scope.$watch('attr("title")', function(title, old) {
if (!title || title === old) return;
if (element.is('button')) {
return element.html(title);
}
element.children('.btn-text').html(title);
});
},
template: '<a href="" class="btn">'+
'<span class="btn-text" ng-transclude></span>'+
'</a>'
});
ui.formItem('ToolButton', 'Button', {
getViewDef: function(element) {
return this.btn;
},
link: function(scope, element, attrs) {
this._super.apply(this, arguments);
var field = scope.field;
if (field == null) {
return;
}
scope.title = field.title;
scope.btn.isHidden = function() {
return scope.isHidden();
};
},
template: '<button class="btn" ui-show="!isHidden()" name="{{btn.name}}" ui-actions ui-widget-states>{{title}}</button>'
});
})(this);
| axelor-web/src/main/webapp/js/form/form.input.static.js | /*
* Axelor Business Solutions
*
* Copyright (C) 2005-2014 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function(){
var ui = angular.module('axelor.ui');
var popoverElem = null;
var popoverTimer = null;
function canDisplayPopover(scope, details) {
var mode = __appSettings['application.mode'];
var tech = __appSettings['user.technical'];
if(mode == 'prod' && !tech) {
return details ? false : scope.field && scope.field.help;
}
return true;
}
function makePopover(scope, element, callback, placement) {
var mode = __appSettings['application.mode'];
var tech = __appSettings['user.technical'];
var doc = $(document);
var table = null;
function addRow(label, text, klass) {
if (table === null) {
table = $('<table class="field-details"></table>');
}
var tr = $('<tr></tr>').appendTo(table);
if (label) {
$('<th></th>').text(label).appendTo(tr);
}
if (klass == null) {
text = '<code>' + text + '</code>';
}
var td = $('<td></td>').html(text).addClass(klass).appendTo(tr);
if (!label) {
td.attr('colspan', 2);
}
return table;
}
element.popover({
html: true,
delay: { show: 1000, hide: 100 },
animate: true,
placement: function() {
if (placement) return placement;
var coord = $(element.get(0)).offset(),
viewport = {height: innerHeight, width: window.innerWidth};
if(viewport.height < (coord.top + 100))
return 'top';
if(coord.left > (viewport.width / 2))
return 'left';
return 'right';
},
trigger: 'manual',
container: 'body',
title: function() {
return element.text();
},
content: function() {
if (table) {
table.remove();
table = null;
}
callback(scope, addRow);
if (table) return table;
return "";
}
});
element.on('mouseenter.popover', enter);
element.on('mouseleave.popover', leave);
function enter(e) {
if (popoverTimer) {
clearTimeout(popoverTimer);
}
popoverTimer = setTimeout(function () {
if (popoverElem === null) {
popoverElem = element;
popoverElem.popover('show');
}
var tip = element.data('popover').$tip;
if (tip) {
tip.attr('tabIndex', 0);
tip.css('outline', 'none');
}
}, 1000);
}
function leave(e) {
if (e.ctrlKey) {
doc.off('mousemove.popover');
doc.on('mousemove.popover', leave);
return;
}
if (popoverTimer) {
clearTimeout(popoverTimer);
popoverTimer = null;
}
if (popoverElem) {
popoverElem.popover('hide');
popoverElem = null;
doc.off('mousemove.popover');
}
}
function destroy() {
if (element) {
element.off('mouseenter.popover');
element.off('mouseleave.popover');
element.popover('destroy');
element = null;
}
if (table) {
table.remove();
table = null;
}
doc.off('mousemove.popover');
}
scope.$on('$destroy', destroy);
}
ui.directive('uiTabPopover', function() {
function getHelp(scope, addRow) {
var tab = scope.tab || {};
var type = tab.viewType;
var view = _.findWhere(tab.views, {type: type});
var viewScope = tab.$viewScope;
if (viewScope && viewScope.schema) {
view = viewScope.schema;
}
if (tab.action) {
addRow(_t('Action'), tab.action);
}
if (tab.model) {
addRow(_t('Object'), tab.model);
}
if (tab.domain) {
addRow(_t('Domain'), tab.domain);
}
if (view && view.name) {
addRow(_t('View'), view.name);
}
}
return function (scope, element, attrs) {
if(canDisplayPopover(scope, true)) {
return makePopover(scope, element, getHelp, 'bottom');
}
};
});
ui.directive('uiHelpPopover', function() {
function getHelp(scope, addRow) {
var field = scope.field;
var text = field.help;
if (text) {
text = text.replace(/\\n/g, '<br>');
addRow(null, text, 'help-text');
}
if (text) {
addRow(null, '<hr noshade>', 'help-text');
}
if(!canDisplayPopover(scope, true)) {
return;
}
var model = scope._model;
if (model === field.target) {
model = scope._parentModel || scope.$parent._model;
}
addRow(_t('Object'), model);
addRow(_t('Field Name'), field.name);
addRow(_t('Field Type'), field.serverType);
if (field.type === 'text') {
return;
}
if (field.domain) {
addRow(_t('Filter'), field.domain);
}
if (field.target) {
addRow(_t('Reference'), field.target);
}
var value = scope.$eval('$$original.' + field.name);
if (value && /-one$/.test(field.serverType)) {
value = _.compact([value.id, value[field.targetName]]).join(',');
value = '(' + value + ')';
}
if (value && field.type === "password") {
value = _.str.repeat('*', value.length);
}
if (value && /^(string|image|binary)$/.test(field.type)) {
var length = value.length;
value = _.first(value, 50);
if (length > 50) {
value.push('...');
}
value = value.join('');
}
if (value && /(panel-related|one-to-many|many-to-many)/.test(field.serverType)) {
var length = value.length;
value = _.first(value, 5);
value = _.map(value, function(v){
return v.id;
});
if (length > 5) {
value.push('...');
}
value = value.join(', ');
}
addRow(_t('Orig. Value'), value);
}
function doLink(scope, element, attrs) {
var field = scope.field;
if (field == null) {
return;
}
if(canDisplayPopover(scope, false)) {
makePopover(scope, element, getHelp);
}
};
return function(scope, element, attrs) {
var field = scope.field;
if (!_.isEmpty(field)) {
return doLink(scope, element, attrs);
}
var unwatch = scope.$watch('field', function(field, old) {
if (!field) {
return;
}
unwatch();
doLink(scope, element, attrs);
}, true);
};
});
/**
* The Label widget.
*
*/
ui.formItem('Label', {
css: 'label-item',
cellCss: 'form-label',
transclude: true,
link: function(scope, element, attrs) {
var field = scope.field;
if (field && field.required) {
element.addClass('required');
}
},
template: '<label><sup ng-if="field.help">?</sup><span ui-help-popover ng-transclude></span></label>'
});
/**
* The Spacer widget.
*
*/
ui.formItem('Spacer', {
css: 'spacer-item',
template: '<div> </div>'
});
/**
* The Separator widget.
*
*/
ui.formItem('Separator', {
css: 'separator-item',
showTitle: false,
template: '<div><span>{{field.title}}</span><hr></div>'
});
/**
* The Static Text widget.
*
*/
ui.formItem('Static', {
css: 'static-item',
transclude: true,
template: '<label ng-transclude></label>'
});
/**
* The button widget.
*/
ui.formItem('Button', {
css: 'button-item',
transclude: true,
link: function(scope, element, attrs, model) {
var field = scope.field || {};
var icon = field.icon || "";
var iconHover = field.iconHover || "";
var isIcon = icon.indexOf('fa-') === 0;
if (isIcon || icon) {
element.prepend(' ');
}
if (isIcon) {
var e = $('<i>').addClass('fa').addClass(icon).prependTo(element);
if (iconHover) {
e.hover(function() {
$(this).removeClass(icon).addClass(iconHover);
}, function() {
$(this).removeClass(iconHover).addClass(icon);
});
}
} else if (icon) {
$('<img>').attr('src', icon).prependTo(element);
}
if (!field.title) {
element.addClass("button-icon");
}
if (_.isString(field.link)) {
element.removeClass('btn');
element.attr("href", field.link);
}
element.tooltip({
html: true,
title: function() {
if (field.help) {
return field.help;
}
if (element.innerWidth() < element[0].scrollWidth) {
return field.title;
}
},
delay: { show: 1000, hide: 100 },
container: 'body'
});
element.on("click", function(e) {
if (scope.isReadonlyExclusive() || element.hasClass('disabled')) {
return;
}
function enable() {
scope.ajaxStop(function () {
setDisabled(false);
}, 100);
}
function setEnable(p) {
if (p && p.then) {
p.then(enable, enable);
} else {
scope.ajaxStop(enable, 500);
}
}
function doClick() {
setEnable(scope.fireAction("onClick"));
}
setDisabled(true);
if (scope.waitForActions) {
return scope.waitForActions(doClick);
}
return doClick();
});
function setDisabled(disabled) {
if (disabled || disabled === undefined) {
return element.addClass("disabled").attr('tabindex', -1);
}
return element.removeClass("disabled").removeAttr('tabindex');
}
var readonlySet = false;
scope.$watch('isReadonlyExclusive()', function(readonly, old) {
if (readonly === old && readonlySet) return;
readonlySet = true;
return setDisabled(readonly);
});
scope.$watch('attr("title")', function(title, old) {
if (!title || title === old) return;
if (element.is('button')) {
return element.html(title);
}
element.children('.btn-text').html(title);
});
},
template: '<a href="" class="btn">'+
'<span class="btn-text" ng-transclude></span>'+
'</a>'
});
ui.formItem('ToolButton', 'Button', {
getViewDef: function(element) {
return this.btn;
},
link: function(scope, element, attrs) {
this._super.apply(this, arguments);
var field = scope.field;
if (field == null) {
return;
}
scope.title = field.title;
scope.btn.isHidden = function() {
return scope.isHidden();
};
},
template: '<button class="btn" ui-show="!isHidden()" name="{{btn.name}}" ui-actions ui-widget-states>{{title}}</button>'
});
})(this);
| Fix button widget readonly issue
Fixes RM-3223
| axelor-web/src/main/webapp/js/form/form.input.static.js | Fix button widget readonly issue | <ide><path>xelor-web/src/main/webapp/js/form/form.input.static.js
<ide>
<ide> function enable() {
<ide> scope.ajaxStop(function () {
<del> setDisabled(false);
<add> setDisabled(scope.isReadonly());
<ide> }, 100);
<ide> }
<ide> |
|
Java | apache-2.0 | b97b9318b2c05f82e47341d6d6589a40fedbdef0 | 0 | markfisher/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,trisberg/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,spring-cloud/spring-cloud-data,mminella/spring-cloud-data,spring-cloud/spring-cloud-data,jvalkeal/spring-cloud-dataflow,cppwfs/spring-cloud-dataflow,trisberg/spring-cloud-dataflow,markfisher/spring-cloud-dataflow,markfisher/spring-cloud-data,spring-cloud/spring-cloud-dataflow,markfisher/spring-cloud-data,mminella/spring-cloud-data,ghillert/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,spring-cloud/spring-cloud-data,ilayaperumalg/spring-cloud-dataflow,jvalkeal/spring-cloud-data,trisberg/spring-cloud-dataflow,markpollack/spring-cloud-dataflow,ilayaperumalg/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,jvalkeal/spring-cloud-data,markfisher/spring-cloud-dataflow,markfisher/spring-cloud-data,markpollack/spring-cloud-dataflow,markfisher/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,cppwfs/spring-cloud-dataflow,markpollack/spring-cloud-dataflow,cppwfs/spring-cloud-dataflow,ghillert/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,trisberg/spring-cloud-dataflow,jvalkeal/spring-cloud-data,ilayaperumalg/spring-cloud-dataflow | /*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.core.dsl;
import java.util.List;
import java.util.Properties;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Parse streams and verify either the correct abstract syntax tree is produced or the
* current exception comes out.
*
* @author Andy Clement
* @author David Turanski
* @author Ilayaperumal Gopinathan
* @author Mark Fisher
* @author Eric Bottard
*/
public class StreamParserTests {
private StreamNode sn;
// This is not a well formed stream but we are testing single app parsing
@Test
public void oneApp() {
sn = parse("foo");
assertEquals(1, sn.getAppNodes().size());
AppNode appNode = sn.getApp("foo");
assertEquals("foo", appNode.getName());
assertEquals(0, appNode.getArguments().length);
assertEquals(0, appNode.startPos);
assertEquals(3, appNode.endPos);
}
@Test
public void hyphenatedAppName() {
sn = parse("gemfire-cq");
assertEquals("[(AppNode:gemfire-cq:0>10)]", sn.stringify(true));
}
// Just to make the testing easier the parser supports stream naming easier.
@Test
public void streamNaming() {
sn = parse("mystream = foo");
assertEquals("[mystream = (AppNode:foo:11>14)]", sn.stringify(true));
assertEquals("mystream", sn.getName());
}
@Test
public void testStreamNameAsAppName() {
String streamName = "bar";
String stream = "bar = foo | bar";
sn = parse(stream);
assertEquals(streamName, sn.getName());
}
// Pipes are used to connect apps
@Test
public void twoApps() {
StreamNode ast = parse("foo | bar");
assertEquals("[(AppNode:foo:0>3)(AppNode:bar:6>9)]", ast.stringify(true));
}
// Apps can be labeled
@Test
public void appLabels() {
StreamNode ast = parse("label: http");
assertEquals("[((Label:label:0>5) AppNode:http:0>11)]", ast.stringify(true));
}
@Test
public void appLabels3() {
StreamNode ast = parse("food = http | label3: foo");
assertEquals("[food = (AppNode:http:7>11)((Label:label3:14>20) AppNode:foo:14>25)]", ast.stringify(true));
sn = parse("http | foo: bar | file");
assertEquals("[(AppNode:http)((Label:foo) AppNode:bar)(AppNode:file)]", sn.stringify());
checkForParseError("http | foo: goggle: bar | file", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 18);
checkForParseError("http | foo :bar | file", DSLMessage.NO_WHITESPACE_BETWEEN_LABEL_NAME_AND_COLON, 11);
}
// Apps can take parameters
@Test
public void oneAppWithParam() {
StreamNode ast = parse("foo --name=value");
assertEquals("[(AppNode:foo --name=value:0>16)]", ast.stringify(true));
}
// Apps can take two parameters
@Test
public void oneAppWithTwoParams() {
StreamNode sn = parse("foo --name=value --x=y");
List<AppNode> appNodes = sn.getAppNodes();
assertEquals(1, appNodes.size());
AppNode mn = appNodes.get(0);
assertEquals("foo", mn.getName());
ArgumentNode[] args = mn.getArguments();
assertNotNull(args);
assertEquals(2, args.length);
assertEquals("name", args[0].getName());
assertEquals("value", args[0].getValue());
assertEquals("x", args[1].getName());
assertEquals("y", args[1].getValue());
assertEquals("[(AppNode:foo --name=value --x=y:0>22)]", sn.stringify(true));
}
@Test
public void testParameters() {
String app = "gemfire-cq --query='Select * from /Stocks where symbol=''VMW''' --regionName=foo --foo=bar";
StreamNode ast = parse(app);
AppNode gemfireApp = ast.getApp("gemfire-cq");
Properties parameters = gemfireApp.getArgumentsAsProperties();
assertEquals(3, parameters.size());
assertEquals("Select * from /Stocks where symbol='VMW'", parameters.get("query"));
assertEquals("foo", parameters.get("regionName"));
assertEquals("bar", parameters.get("foo"));
app = "test";
parameters = parse(app).getApp("test").getArgumentsAsProperties();
assertEquals(0, parameters.size());
app = "foo --x=1 --y=two ";
parameters = parse(app).getApp("foo").getArgumentsAsProperties();
assertEquals(2, parameters.size());
assertEquals("1", parameters.get("x"));
assertEquals("two", parameters.get("y"));
app = "foo --x=1a2b --y=two ";
parameters = parse(app).getApp("foo").getArgumentsAsProperties();
assertEquals(2, parameters.size());
assertEquals("1a2b", parameters.get("x"));
assertEquals("two", parameters.get("y"));
app = "foo --x=2";
parameters = parse(app).getApp("foo").getArgumentsAsProperties();
assertEquals(1, parameters.size());
assertEquals("2", parameters.get("x"));
app = "--foo = bar";
try {
parse(app);
fail(app + " is invalid. Should throw exception");
}
catch (Exception e) {
// success
}
}
@Test
public void testInvalidApps() {
String config = "test | foo--x=13";
StreamParser parser = new StreamParser("t", config);
try {
parser.parse();
fail(config + " is invalid. Should throw exception");
}
catch (Exception e) {
// success
}
}
@Test
public void tapWithLabelReference() {
parse("mystream = http | filter | group1: transform | group2: transform | file");
StreamNode ast = parse(":mystream.group1 > file");
assertEquals("[(mystream.group1)>(AppNode:file)]", ast.stringify());
ast = parse(":mystream.group2 > file");
assertEquals("[(mystream.group2)>(AppNode:file)]", ast.stringify());
}
@Test
public void tapWithQualifiedAppReference() {
parse("mystream = http | foobar | file");
StreamNode sn = parse(":mystream.foobar > file");
assertEquals("[(mystream.foobar:1>16)>(AppNode:file:19>23)]", sn.stringify(true));
}
@Test
public void expressions_xd159() {
StreamNode ast = parse("foo | transform --expression=--payload | bar");
AppNode mn = ast.getApp("transform");
Properties props = mn.getArgumentsAsProperties();
assertEquals("--payload", props.get("expression"));
}
@Test
public void expressions_xd159_2() {
// need quotes around an argument value with a space in it
checkForParseError("foo | transform --expression=new StringBuilder(payload).reverse() | bar",
DSLMessage.UNEXPECTED_DATA, 46);
}
@Test
public void ensureStreamNamesValid_xd1344() {
// Similar rules to a java identifier but also allowed '-' after the first char
checkForIllegalStreamName("foo.bar", "http | transform | sink");
checkForIllegalStreamName("-bar", "http | transform | sink");
checkForIllegalStreamName(".bar", "http | transform | sink");
checkForIllegalStreamName("foo-.-bar", "http | transform | sink");
checkForIllegalStreamName("0foobar", "http | transform | sink");
checkForIllegalStreamName("foo%bar", "http | transform | sink");
parse("foo-bar", "http | transform | sink");
parse("foo_bar", "http | transform | sink");
}
@Test
public void parametersContainingNewlineCarriageReturn() {
StreamNode ast = parse(":producer > foobar --expression='aaa=bbb \n ccc=ddd' > :consumer");
assertEquals("aaa=bbb \n ccc=ddd", ast.getApp("foobar").getArguments()[0].getValue());
ast = parse(":producer > foobar --expression='aaa=bbb \r ccc=ddd' > :consumer");
assertEquals("aaa=bbb \r ccc=ddd", ast.getApp("foobar").getArguments()[0].getValue());
}
@Test
public void expressions_xd159_3() {
StreamNode ast = parse("foo | transform --expression='new StringBuilder(payload).reverse()' | bar");
AppNode mn = ast.getApp("transform");
Properties props = mn.getArgumentsAsProperties();
assertEquals("new StringBuilder(payload).reverse()", props.get("expression"));
}
@Test
public void testUnbalancedSingleQuotes() {
checkForParseError("foo | bar --expression='select foo", DSLMessage.NON_TERMINATING_QUOTED_STRING, 23);
}
@Test
public void testUnbalancedDoubleQuotes() {
checkForParseError("foo | bar --expression=\"select foo", DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 23);
}
@Test
public void appArguments_xd1613() {
StreamNode ast = null;
// notice no space between the ' and final >
ast = parse(":producer > transform --expression='payload.toUpperCase()' | filter --expression='payload.length"
+ "() > 4'> :consumer");
assertEquals("payload.toUpperCase()", ast.getApp("transform").getArguments()[0].getValue());
assertEquals("payload.length() > 4", ast.getApp("filter").getArguments()[0].getValue());
ast = parse("time | transform --expression='T(org.joda.time.format.DateTimeFormat).forPattern(\"yyyy-MM-dd "
+ "HH:mm:ss\").parseDateTime(payload)'");
assertEquals(
"T(org.joda.time.format.DateTimeFormat).forPattern(\"yyyy-MM-dd HH:mm:ss\").parseDateTime(payload)",
ast.getApp("transform").getArguments()[0].getValue());
// allow for pipe/semicolon if quoted
ast = parse("http | transform --outputType='text/plain|charset=UTF-8' | log");
assertEquals("text/plain|charset=UTF-8", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --outputType='text/plain;charset=UTF-8' | log");
assertEquals("text/plain;charset=UTF-8", ast.getApp("transform").getArguments()[0].getValue());
// Want to treat all of 'hi'+payload as the argument value
ast = parse("http | transform --expression='hi'+payload | log");
assertEquals("'hi'+payload", ast.getApp("transform").getArguments()[0].getValue());
// Want to treat all of payload+'hi' as the argument value
ast = parse("http | transform --expression=payload+'hi' | log");
assertEquals("payload+'hi'", ast.getApp("transform").getArguments()[0].getValue());
// Alternatively, can quote all around it to achieve the same thing
ast = parse("http | transform --expression='payload+''hi''' | log");
assertEquals("payload+'hi'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression='''hi''+payload' | log");
assertEquals("'hi'+payload", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"payload+'hi'\" | log");
assertEquals("payload+'hi'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"'hi'+payload\" | log");
assertEquals("'hi'+payload", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=payload+'hi'--param2='foobar' | log");
assertEquals("payload+'hi'--param2='foobar'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression='hi'+payload--param2='foobar' | log");
assertEquals("'hi'+payload--param2='foobar'", ast.getApp("transform").getArguments()[0].getValue());
// This also works, which is cool
ast = parse("http | transform --expression='hi'+'world' | log");
assertEquals("'hi'+'world'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"'hi'+'world'\" | log");
assertEquals("'hi'+'world'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | filter --expression=payload.matches('hello world') | log");
assertEquals("payload.matches('hello world')", ast.getApp("filter").getArguments()[0].getValue());
ast = parse("http | transform --expression='''hi''' | log");
assertEquals("'hi'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"''''hi''''\" | log");
assertEquals("''''hi''''", ast.getApp("transform").getArguments()[0].getValue());
}
@Test
public void expressions_xd159_4() {
StreamNode ast = parse("foo | transform --expression=\"'Hello, world!'\" | bar");
AppNode mn = ast.getApp("transform");
Properties props = mn.getArgumentsAsProperties();
assertEquals("'Hello, world!'", props.get("expression"));
ast = parse("foo | transform --expression='''Hello, world!''' | bar");
mn = ast.getApp("transform");
props = mn.getArgumentsAsProperties();
assertEquals("'Hello, world!'", props.get("expression"));
// Prior to the change for XD-1613, this error should point to the comma:
// checkForParseError("foo | transform --expression=''Hello, world!'' | bar",
// DSLMessage.UNEXPECTED_DATA,
// 37);
// but now it points to the !
checkForParseError("foo | transform --expression=''Hello, world!'' | bar", DSLMessage.UNEXPECTED_DATA, 44);
}
@Test
public void expressions_gh1() {
StreamNode ast = parse("http --port=9014 | filter --expression=\"payload == 'foo'\" | log");
AppNode mn = ast.getApp("filter");
Properties props = mn.getArgumentsAsProperties();
assertEquals("payload == 'foo'", props.get("expression"));
}
@Test
public void expressions_gh1_2() {
StreamNode ast = parse("http --port=9014 | filter --expression='new Foo()' | log");
AppNode mn = ast.getApp("filter");
Properties props = mn.getArgumentsAsProperties();
assertEquals("new Foo()", props.get("expression"));
}
@Test
public void sourceDestination() {
StreamNode sn = parse(":foobar > file");
assertEquals("[(foobar:1>7)>(AppNode:file:10>14)]", sn.stringify(true));
}
@Test
public void sinkDestination() {
StreamNode sn = parse("http > :foo");
assertEquals("[(AppNode:http:0>4)>(foo:8>11)]", sn.stringify(true));
}
@Test
public void destinationVariants() {
checkForParseError("http > :test value", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 13);
checkForParseError(":boo .xx > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 5);
checkForParseError(":boo . xx > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 5);
checkForParseError(":boo. xx > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 6);
checkForParseError(":boo.xx. yy > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 9);
checkForParseError(":boo.xx .yy > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 8);
checkForParseError(":boo.xx . yy > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 8);
sn = parse("wibble: http > :bar");
assertEquals("[((Label:wibble) AppNode:http)>(bar)]", sn.stringify());
}
@Test
public void sourceDestination2() {
parse("foo = http | bar | file");
StreamNode ast = parse(":foo.bar > file");
assertEquals("[(foo.bar:1>8)>(AppNode:file:11>15)]", ast.stringify(true));
assertEquals("foo.bar", ast.getSourceDestinationNode().getDestinationName());
}
@Test
public void sourceTapDestination() {
parse("mystream = http | file");
StreamNode ast = parse(":mystream.http > file");
assertEquals("[(mystream.http:1>14)>(AppNode:file:17>21)]", ast.stringify(true));
SourceDestinationNode sourceDestinationNode = ast.getSourceDestinationNode();
assertEquals("mystream.http", sourceDestinationNode.getDestinationName());
}
@Test
public void nameSpaceTestWithSpaces() {
checkForParseError("trigger > :myjob too", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 19, "too");
}
@Test
public void errorCases01() {
checkForParseError(".", DSLMessage.EXPECTED_APPNAME, 0, ".");
checkForParseError(";", DSLMessage.EXPECTED_APPNAME, 0, ";");
}
@Test
public void errorCases04() {
checkForParseError("foo bar=yyy", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 4, "bar");
checkForParseError("foo bar", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 4, "bar");
}
@Test
public void errorCases05() {
checkForParseError("foo --", DSLMessage.OOD, 6);
checkForParseError("foo --bar", DSLMessage.OOD, 9);
checkForParseError("foo --bar=", DSLMessage.OOD, 10);
}
@Test
public void errorCases06() {
checkForParseError("|", DSLMessage.EXPECTED_APPNAME, 0);
}
@Test
public void errorCases07() {
checkForParseError("foo > bar", DSLMessage.EXPECTED_DESTINATION_PREFIX, 6, "bar");
checkForParseError(":foo >", DSLMessage.OOD, 6);
checkForParseError(":foo > --2323", DSLMessage.EXPECTED_APPNAME, 7, "--");
checkForParseError(":foo > *", DSLMessage.UNEXPECTED_DATA, 7, "*");
}
@Test
public void errorCases08() {
checkForParseError(":foo | bar", DSLMessage.EXPECTED_APPNAME, 0, ":");
}
@Test
public void errorCases09() {
checkForParseError("* = http | file", DSLMessage.UNEXPECTED_DATA, 0, "*");
checkForParseError(": = http | file", DSLMessage.ILLEGAL_STREAM_NAME, 0, ":");
}
@Test
public void duplicateExplicitLabels() {
checkForParseError("xxx: http | xxx: file", DSLMessage.DUPLICATE_LABEL, 12, "xxx", "http", 0, "file", 1);
checkForParseError("xxx: http | yyy: filter | transform | xxx: transform | file", DSLMessage.DUPLICATE_LABEL,
38, "xxx", "http", 0, "transform", 3);
checkForParseError("xxx: http | yyy: filter | transform | xxx: transform | xxx: file",
DSLMessage.DUPLICATE_LABEL, 38, "xxx", "http", 0, "transform", 3);
}
@Test
public void addingALabelLiftsAmbiguity() {
StreamNode ast = parse("file | out: file");
assertEquals("file", ast.getAppNodes().get(0).getLabelName());
assertEquals("out", ast.getAppNodes().get(1).getLabelName());
}
@Test
public void duplicateImplicitLabels() {
checkForParseError("http | filter | transform | transform | file", DSLMessage.DUPLICATE_LABEL, 28, "transform",
"transform", 2, "transform", 3);
}
@Test
public void tapWithLabels() {
parse("mystream = http | flibble: transform | file");
sn = parse(":mystream.flibble > file");
assertEquals("mystream.flibble", sn.getSourceDestinationNode().getDestinationName());
}
@Test
public void bridge01() {
StreamNode sn = parse(":bar > :boo");
assertEquals("[(bar:1>4)>(AppNode:bridge:5>6)>(boo:8>11)]", sn.stringify(true));
}
@Test
public void testSourceDestinationArgs() {
StreamNode sn = parse(":test --group=test > file");
assertEquals("[(test:1>5 --group=test)>(AppNode:file:21>25)]", sn.stringify(true));
}
// Parameters must be constructed via adjacent tokens
@Test
public void needAdjacentTokensForParameters() {
checkForParseError("foo -- name=value", DSLMessage.NO_WHITESPACE_BEFORE_ARG_NAME, 7);
checkForParseError("foo --name =value", DSLMessage.NO_WHITESPACE_BEFORE_ARG_EQUALS, 11);
checkForParseError("foo --name= value", DSLMessage.NO_WHITESPACE_BEFORE_ARG_VALUE, 12);
}
// ---
@Test
public void testComposedOptionNameErros() {
checkForParseError("foo --name.=value", DSLMessage.NOT_EXPECTED_TOKEN, 11);
checkForParseError("foo --name .sub=value", DSLMessage.NO_WHITESPACE_IN_DOTTED_NAME, 11);
checkForParseError("foo --name. sub=value", DSLMessage.NO_WHITESPACE_IN_DOTTED_NAME, 12);
}
@Test
public void testXD2416() {
StreamNode ast = parse("http | transform --expression='payload.replace(\"abc\", \"\")' | log");
assertThat((String) ast.getAppNodes().get(1).getArgumentsAsProperties().get("expression"),
equalTo("payload" + ".replace(\"abc\", \"\")"));
ast = parse("http | transform --expression='payload.replace(\"abc\", '''')' | log");
assertThat((String) ast.getAppNodes().get(1).getArgumentsAsProperties().get("expression"),
equalTo("payload" + ".replace(\"abc\", '')"));
}
StreamNode parse(String streamDefinition) {
return new StreamParser(streamDefinition).parse();
}
StreamNode parse(String streamName, String streamDefinition) {
return new StreamParser(streamName, streamDefinition).parse();
}
private void checkForIllegalStreamName(String streamName, String streamDef) {
try {
StreamNode sn = parse(streamName, streamDef);
fail("expected to fail but parsed " + sn.stringify());
}
catch (ParseException e) {
assertEquals(DSLMessage.ILLEGAL_STREAM_NAME, e.getMessageCode());
assertEquals(0, e.getPosition());
assertEquals(streamName, e.getInserts()[0]);
}
}
private void checkForParseError(String stream, DSLMessage msg, int pos, Object... inserts) {
try {
StreamNode sn = parse(stream);
fail("expected to fail but parsed " + sn.stringify());
}
catch (ParseException e) {
assertEquals(msg, e.getMessageCode());
assertEquals(pos, e.getPosition());
if (inserts != null) {
for (int i = 0; i < inserts.length; i++) {
assertEquals(inserts[i], e.getInserts()[i]);
}
}
}
}
}
| spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java | /*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.core.dsl;
import java.util.List;
import java.util.Properties;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Parse streams and verify either the correct abstract syntax tree is produced or the
* current exception comes out.
*
* @author Andy Clement
* @author David Turanski
* @author Ilayaperumal Gopinathan
* @author Mark Fisher
* @author Eric Bottard
*/
public class StreamParserTests {
private StreamNode sn;
// This is not a well formed stream but we are testing single app parsing
@Test
public void oneApp() {
sn = parse("foo");
assertEquals(1, sn.getAppNodes().size());
AppNode appNode = sn.getApp("foo");
assertEquals("foo", appNode.getName());
assertEquals(0, appNode.getArguments().length);
assertEquals(0, appNode.startPos);
assertEquals(3, appNode.endPos);
}
@Test
public void hyphenatedAppName() {
sn = parse("gemfire-cq");
assertEquals("[(AppNode:gemfire-cq:0>10)]", sn.stringify(true));
}
// Just to make the testing easier the parser supports stream naming easier.
@Test
public void streamNaming() {
sn = parse("mystream = foo");
assertEquals("[mystream = (AppNode:foo:11>14)]", sn.stringify(true));
assertEquals("mystream", sn.getName());
}
@Test
public void testStreamNameAsAppName() {
String streamName = "bar";
String stream = "bar = foo | bar";
sn = parse(stream);
assertEquals(streamName, sn.getName());
}
// Pipes are used to connect apps
@Test
public void twoApps() {
StreamNode ast = parse("foo | bar");
assertEquals("[(AppNode:foo:0>3)(AppNode:bar:6>9)]", ast.stringify(true));
}
// Apps can be labeled
@Test
public void appLabels() {
StreamNode ast = parse("label: http");
assertEquals("[((Label:label:0>5) AppNode:http:0>11)]", ast.stringify(true));
}
@Test
public void appLabels3() {
StreamNode ast = parse("food = http | label3: foo");
assertEquals("[food = (AppNode:http:7>11)((Label:label3:14>20) AppNode:foo:14>25)]", ast.stringify(true));
sn = parse("http | foo: bar | file");
assertEquals("[(AppNode:http)((Label:foo) AppNode:bar)(AppNode:file)]", sn.stringify());
checkForParseError("http | foo: goggle: bar | file", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 18);
checkForParseError("http | foo :bar | file", DSLMessage.NO_WHITESPACE_BETWEEN_LABEL_NAME_AND_COLON, 11);
}
// Apps can take parameters
@Test
public void oneAppWithParam() {
StreamNode ast = parse("foo --name=value");
assertEquals("[(AppNode:foo --name=value:0>16)]", ast.stringify(true));
}
// Apps can take two parameters
@Test
public void oneAppWithTwoParams() {
StreamNode sn = parse("foo --name=value --x=y");
List<AppNode> appNodes = sn.getAppNodes();
assertEquals(1, appNodes.size());
AppNode mn = appNodes.get(0);
assertEquals("foo", mn.getName());
ArgumentNode[] args = mn.getArguments();
assertNotNull(args);
assertEquals(2, args.length);
assertEquals("name", args[0].getName());
assertEquals("value", args[0].getValue());
assertEquals("x", args[1].getName());
assertEquals("y", args[1].getValue());
assertEquals("[(AppNode:foo --name=value --x=y:0>22)]", sn.stringify(true));
}
@Test
public void testParameters() {
String app = "gemfire-cq --query='Select * from /Stocks where symbol=''VMW''' --regionName=foo --foo=bar";
StreamNode ast = parse(app);
AppNode gemfireApp = ast.getApp("gemfire-cq");
Properties parameters = gemfireApp.getArgumentsAsProperties();
assertEquals(3, parameters.size());
assertEquals("Select * from /Stocks where symbol='VMW'", parameters.get("query"));
assertEquals("foo", parameters.get("regionName"));
assertEquals("bar", parameters.get("foo"));
app = "test";
parameters = parse(app).getApp("test").getArgumentsAsProperties();
assertEquals(0, parameters.size());
app = "foo --x=1 --y=two ";
parameters = parse(app).getApp("foo").getArgumentsAsProperties();
assertEquals(2, parameters.size());
assertEquals("1", parameters.get("x"));
assertEquals("two", parameters.get("y"));
app = "foo --x=1a2b --y=two ";
parameters = parse(app).getApp("foo").getArgumentsAsProperties();
assertEquals(2, parameters.size());
assertEquals("1a2b", parameters.get("x"));
assertEquals("two", parameters.get("y"));
app = "foo --x=2";
parameters = parse(app).getApp("foo").getArgumentsAsProperties();
assertEquals(1, parameters.size());
assertEquals("2", parameters.get("x"));
app = "--foo = bar";
try {
parse(app);
fail(app + " is invalid. Should throw exception");
}
catch (Exception e) {
// success
}
}
@Test
public void testInvalidApps() {
String config = "test | foo--x=13";
StreamParser parser = new StreamParser("t", config);
try {
parser.parse();
fail(config + " is invalid. Should throw exception");
}
catch (Exception e) {
// success
}
}
@Test
public void tapWithLabelReference() {
parse("mystream = http | filter | group1: transform | group2: transform | file");
StreamNode ast = parse(":mystream.group1 > file");
assertEquals("[(mystream.group1)>(AppNode:file)]", ast.stringify());
ast = parse(":mystream.group2 > file");
assertEquals("[(mystream.group2)>(AppNode:file)]", ast.stringify());
}
@Test
public void tapWithQualifiedAppReference() {
parse("mystream = http | foobar | file");
StreamNode sn = parse(":mystream.foobar > file");
assertEquals("[(mystream.foobar:1>16)>(AppNode:file:19>23)]", sn.stringify(true));
}
@Test
public void expressions_xd159() {
StreamNode ast = parse("foo | transform --expression=--payload | bar");
AppNode mn = ast.getApp("transform");
Properties props = mn.getArgumentsAsProperties();
assertEquals("--payload", props.get("expression"));
}
@Test
public void expressions_xd159_2() {
// need quotes around an argument value with a space in it
checkForParseError("foo | transform --expression=new StringBuilder(payload).reverse() | bar",
DSLMessage.UNEXPECTED_DATA, 46);
}
@Test
public void ensureStreamNamesValid_xd1344() {
// Similar rules to a java identifier but also allowed '-' after the first char
checkForIllegalStreamName("foo.bar", "http | transform | sink");
checkForIllegalStreamName("-bar", "http | transform | sink");
checkForIllegalStreamName(".bar", "http | transform | sink");
checkForIllegalStreamName("foo-.-bar", "http | transform | sink");
checkForIllegalStreamName("0foobar", "http | transform | sink");
checkForIllegalStreamName("foo%bar", "http | transform | sink");
parse("foo-bar", "http | transform | sink");
parse("foo_bar", "http | transform | sink");
}
@Test
public void expressions_xd159_3() {
StreamNode ast = parse("foo | transform --expression='new StringBuilder(payload).reverse()' | bar");
AppNode mn = ast.getApp("transform");
Properties props = mn.getArgumentsAsProperties();
assertEquals("new StringBuilder(payload).reverse()", props.get("expression"));
}
@Test
public void testUnbalancedSingleQuotes() {
checkForParseError("foo | bar --expression='select foo", DSLMessage.NON_TERMINATING_QUOTED_STRING, 23);
}
@Test
public void testUnbalancedDoubleQuotes() {
checkForParseError("foo | bar --expression=\"select foo", DSLMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 23);
}
@Test
public void appArguments_xd1613() {
StreamNode ast = null;
// notice no space between the ' and final >
ast = parse(":producer > transform --expression='payload.toUpperCase()' | filter --expression='payload.length"
+ "() > 4'> :consumer");
assertEquals("payload.toUpperCase()", ast.getApp("transform").getArguments()[0].getValue());
assertEquals("payload.length() > 4", ast.getApp("filter").getArguments()[0].getValue());
ast = parse("time | transform --expression='T(org.joda.time.format.DateTimeFormat).forPattern(\"yyyy-MM-dd "
+ "HH:mm:ss\").parseDateTime(payload)'");
assertEquals(
"T(org.joda.time.format.DateTimeFormat).forPattern(\"yyyy-MM-dd HH:mm:ss\").parseDateTime(payload)",
ast.getApp("transform").getArguments()[0].getValue());
// allow for pipe/semicolon if quoted
ast = parse("http | transform --outputType='text/plain|charset=UTF-8' | log");
assertEquals("text/plain|charset=UTF-8", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --outputType='text/plain;charset=UTF-8' | log");
assertEquals("text/plain;charset=UTF-8", ast.getApp("transform").getArguments()[0].getValue());
// Want to treat all of 'hi'+payload as the argument value
ast = parse("http | transform --expression='hi'+payload | log");
assertEquals("'hi'+payload", ast.getApp("transform").getArguments()[0].getValue());
// Want to treat all of payload+'hi' as the argument value
ast = parse("http | transform --expression=payload+'hi' | log");
assertEquals("payload+'hi'", ast.getApp("transform").getArguments()[0].getValue());
// Alternatively, can quote all around it to achieve the same thing
ast = parse("http | transform --expression='payload+''hi''' | log");
assertEquals("payload+'hi'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression='''hi''+payload' | log");
assertEquals("'hi'+payload", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"payload+'hi'\" | log");
assertEquals("payload+'hi'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"'hi'+payload\" | log");
assertEquals("'hi'+payload", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=payload+'hi'--param2='foobar' | log");
assertEquals("payload+'hi'--param2='foobar'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression='hi'+payload--param2='foobar' | log");
assertEquals("'hi'+payload--param2='foobar'", ast.getApp("transform").getArguments()[0].getValue());
// This also works, which is cool
ast = parse("http | transform --expression='hi'+'world' | log");
assertEquals("'hi'+'world'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"'hi'+'world'\" | log");
assertEquals("'hi'+'world'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | filter --expression=payload.matches('hello world') | log");
assertEquals("payload.matches('hello world')", ast.getApp("filter").getArguments()[0].getValue());
ast = parse("http | transform --expression='''hi''' | log");
assertEquals("'hi'", ast.getApp("transform").getArguments()[0].getValue());
ast = parse("http | transform --expression=\"''''hi''''\" | log");
assertEquals("''''hi''''", ast.getApp("transform").getArguments()[0].getValue());
}
@Test
public void expressions_xd159_4() {
StreamNode ast = parse("foo | transform --expression=\"'Hello, world!'\" | bar");
AppNode mn = ast.getApp("transform");
Properties props = mn.getArgumentsAsProperties();
assertEquals("'Hello, world!'", props.get("expression"));
ast = parse("foo | transform --expression='''Hello, world!''' | bar");
mn = ast.getApp("transform");
props = mn.getArgumentsAsProperties();
assertEquals("'Hello, world!'", props.get("expression"));
// Prior to the change for XD-1613, this error should point to the comma:
// checkForParseError("foo | transform --expression=''Hello, world!'' | bar",
// DSLMessage.UNEXPECTED_DATA,
// 37);
// but now it points to the !
checkForParseError("foo | transform --expression=''Hello, world!'' | bar", DSLMessage.UNEXPECTED_DATA, 44);
}
@Test
public void expressions_gh1() {
StreamNode ast = parse("http --port=9014 | filter --expression=\"payload == 'foo'\" | log");
AppNode mn = ast.getApp("filter");
Properties props = mn.getArgumentsAsProperties();
assertEquals("payload == 'foo'", props.get("expression"));
}
@Test
public void expressions_gh1_2() {
StreamNode ast = parse("http --port=9014 | filter --expression='new Foo()' | log");
AppNode mn = ast.getApp("filter");
Properties props = mn.getArgumentsAsProperties();
assertEquals("new Foo()", props.get("expression"));
}
@Test
public void sourceDestination() {
StreamNode sn = parse(":foobar > file");
assertEquals("[(foobar:1>7)>(AppNode:file:10>14)]", sn.stringify(true));
}
@Test
public void sinkDestination() {
StreamNode sn = parse("http > :foo");
assertEquals("[(AppNode:http:0>4)>(foo:8>11)]", sn.stringify(true));
}
@Test
public void destinationVariants() {
checkForParseError("http > :test value", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 13);
checkForParseError(":boo .xx > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 5);
checkForParseError(":boo . xx > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 5);
checkForParseError(":boo. xx > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 6);
checkForParseError(":boo.xx. yy > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 9);
checkForParseError(":boo.xx .yy > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 8);
checkForParseError(":boo.xx . yy > file", DSLMessage.NO_WHITESPACE_IN_DESTINATION_DEFINITION, 8);
sn = parse("wibble: http > :bar");
assertEquals("[((Label:wibble) AppNode:http)>(bar)]", sn.stringify());
}
@Test
public void sourceDestination2() {
parse("foo = http | bar | file");
StreamNode ast = parse(":foo.bar > file");
assertEquals("[(foo.bar:1>8)>(AppNode:file:11>15)]", ast.stringify(true));
assertEquals("foo.bar", ast.getSourceDestinationNode().getDestinationName());
}
@Test
public void sourceTapDestination() {
parse("mystream = http | file");
StreamNode ast = parse(":mystream.http > file");
assertEquals("[(mystream.http:1>14)>(AppNode:file:17>21)]", ast.stringify(true));
SourceDestinationNode sourceDestinationNode = ast.getSourceDestinationNode();
assertEquals("mystream.http", sourceDestinationNode.getDestinationName());
}
@Test
public void nameSpaceTestWithSpaces() {
checkForParseError("trigger > :myjob too", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 19, "too");
}
@Test
public void errorCases01() {
checkForParseError(".", DSLMessage.EXPECTED_APPNAME, 0, ".");
checkForParseError(";", DSLMessage.EXPECTED_APPNAME, 0, ";");
}
@Test
public void errorCases04() {
checkForParseError("foo bar=yyy", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 4, "bar");
checkForParseError("foo bar", DSLMessage.UNEXPECTED_DATA_AFTER_STREAMDEF, 4, "bar");
}
@Test
public void errorCases05() {
checkForParseError("foo --", DSLMessage.OOD, 6);
checkForParseError("foo --bar", DSLMessage.OOD, 9);
checkForParseError("foo --bar=", DSLMessage.OOD, 10);
}
@Test
public void errorCases06() {
checkForParseError("|", DSLMessage.EXPECTED_APPNAME, 0);
}
@Test
public void errorCases07() {
checkForParseError("foo > bar", DSLMessage.EXPECTED_DESTINATION_PREFIX, 6, "bar");
checkForParseError(":foo >", DSLMessage.OOD, 6);
checkForParseError(":foo > --2323", DSLMessage.EXPECTED_APPNAME, 7, "--");
checkForParseError(":foo > *", DSLMessage.UNEXPECTED_DATA, 7, "*");
}
@Test
public void errorCases08() {
checkForParseError(":foo | bar", DSLMessage.EXPECTED_APPNAME, 0, ":");
}
@Test
public void errorCases09() {
checkForParseError("* = http | file", DSLMessage.UNEXPECTED_DATA, 0, "*");
checkForParseError(": = http | file", DSLMessage.ILLEGAL_STREAM_NAME, 0, ":");
}
@Test
public void duplicateExplicitLabels() {
checkForParseError("xxx: http | xxx: file", DSLMessage.DUPLICATE_LABEL, 12, "xxx", "http", 0, "file", 1);
checkForParseError("xxx: http | yyy: filter | transform | xxx: transform | file", DSLMessage.DUPLICATE_LABEL,
38, "xxx", "http", 0, "transform", 3);
checkForParseError("xxx: http | yyy: filter | transform | xxx: transform | xxx: file",
DSLMessage.DUPLICATE_LABEL, 38, "xxx", "http", 0, "transform", 3);
}
@Test
public void addingALabelLiftsAmbiguity() {
StreamNode ast = parse("file | out: file");
assertEquals("file", ast.getAppNodes().get(0).getLabelName());
assertEquals("out", ast.getAppNodes().get(1).getLabelName());
}
@Test
public void duplicateImplicitLabels() {
checkForParseError("http | filter | transform | transform | file", DSLMessage.DUPLICATE_LABEL, 28, "transform",
"transform", 2, "transform", 3);
}
@Test
public void tapWithLabels() {
parse("mystream = http | flibble: transform | file");
sn = parse(":mystream.flibble > file");
assertEquals("mystream.flibble", sn.getSourceDestinationNode().getDestinationName());
}
@Test
public void bridge01() {
StreamNode sn = parse(":bar > :boo");
assertEquals("[(bar:1>4)>(AppNode:bridge:5>6)>(boo:8>11)]", sn.stringify(true));
}
@Test
public void testSourceDestinationArgs() {
StreamNode sn = parse(":test --group=test > file");
assertEquals("[(test:1>5 --group=test)>(AppNode:file:21>25)]", sn.stringify(true));
}
// Parameters must be constructed via adjacent tokens
@Test
public void needAdjacentTokensForParameters() {
checkForParseError("foo -- name=value", DSLMessage.NO_WHITESPACE_BEFORE_ARG_NAME, 7);
checkForParseError("foo --name =value", DSLMessage.NO_WHITESPACE_BEFORE_ARG_EQUALS, 11);
checkForParseError("foo --name= value", DSLMessage.NO_WHITESPACE_BEFORE_ARG_VALUE, 12);
}
// ---
@Test
public void testComposedOptionNameErros() {
checkForParseError("foo --name.=value", DSLMessage.NOT_EXPECTED_TOKEN, 11);
checkForParseError("foo --name .sub=value", DSLMessage.NO_WHITESPACE_IN_DOTTED_NAME, 11);
checkForParseError("foo --name. sub=value", DSLMessage.NO_WHITESPACE_IN_DOTTED_NAME, 12);
}
@Test
public void testXD2416() {
StreamNode ast = parse("http | transform --expression='payload.replace(\"abc\", \"\")' | log");
assertThat((String) ast.getAppNodes().get(1).getArgumentsAsProperties().get("expression"),
equalTo("payload" + ".replace(\"abc\", \"\")"));
ast = parse("http | transform --expression='payload.replace(\"abc\", '''')' | log");
assertThat((String) ast.getAppNodes().get(1).getArgumentsAsProperties().get("expression"),
equalTo("payload" + ".replace(\"abc\", '')"));
}
StreamNode parse(String streamDefinition) {
return new StreamParser(streamDefinition).parse();
}
StreamNode parse(String streamName, String streamDefinition) {
return new StreamParser(streamName, streamDefinition).parse();
}
private void checkForIllegalStreamName(String streamName, String streamDef) {
try {
StreamNode sn = parse(streamName, streamDef);
fail("expected to fail but parsed " + sn.stringify());
}
catch (ParseException e) {
assertEquals(DSLMessage.ILLEGAL_STREAM_NAME, e.getMessageCode());
assertEquals(0, e.getPosition());
assertEquals(streamName, e.getInserts()[0]);
}
}
private void checkForParseError(String stream, DSLMessage msg, int pos, Object... inserts) {
try {
StreamNode sn = parse(stream);
fail("expected to fail but parsed " + sn.stringify());
}
catch (ParseException e) {
assertEquals(msg, e.getMessageCode());
assertEquals(pos, e.getPosition());
if (inserts != null) {
for (int i = 0; i < inserts.length; i++) {
assertEquals(inserts[i], e.getInserts()[i]);
}
}
}
}
}
| Test for quoted newlines in app argument values
| spring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java | Test for quoted newlines in app argument values | <ide><path>pring-cloud-dataflow-core/src/test/java/org/springframework/cloud/dataflow/core/dsl/StreamParserTests.java
<ide> parse("foo-bar", "http | transform | sink");
<ide> parse("foo_bar", "http | transform | sink");
<ide> }
<add>
<add> @Test
<add> public void parametersContainingNewlineCarriageReturn() {
<add> StreamNode ast = parse(":producer > foobar --expression='aaa=bbb \n ccc=ddd' > :consumer");
<add> assertEquals("aaa=bbb \n ccc=ddd", ast.getApp("foobar").getArguments()[0].getValue());
<add> ast = parse(":producer > foobar --expression='aaa=bbb \r ccc=ddd' > :consumer");
<add> assertEquals("aaa=bbb \r ccc=ddd", ast.getApp("foobar").getArguments()[0].getValue());
<add> }
<ide>
<ide> @Test
<ide> public void expressions_xd159_3() { |
|
Java | apache-2.0 | 57208e650f94edece537ccdeb1a2c19b4f7ccca8 | 0 | twalthr/flink,WangTaoTheTonic/flink,tzulitai/flink,fhueske/flink,lincoln-lil/flink,shaoxuan-wang/flink,zentol/flink,fhueske/flink,GJL/flink,rmetzger/flink,shaoxuan-wang/flink,tillrohrmann/flink,hongyuhong/flink,shaoxuan-wang/flink,kl0u/flink,fanyon/flink,apache/flink,kl0u/flink,fhueske/flink,zimmermatt/flink,fhueske/flink,gyfora/flink,mylog00/flink,gustavoanatoly/flink,twalthr/flink,xccui/flink,zjureel/flink,apache/flink,zhangminglei/flink,shaoxuan-wang/flink,ueshin/apache-flink,twalthr/flink,godfreyhe/flink,fanyon/flink,ueshin/apache-flink,tzulitai/flink,tillrohrmann/flink,zohar-mizrahi/flink,zohar-mizrahi/flink,bowenli86/flink,zentol/flink,tony810430/flink,zjureel/flink,mtunique/flink,tillrohrmann/flink,PangZhi/flink,gyfora/flink,darionyaphet/flink,godfreyhe/flink,wwjiang007/flink,gustavoanatoly/flink,darionyaphet/flink,zentol/flink,tony810430/flink,lincoln-lil/flink,xccui/flink,kaibozhou/flink,hwstreaming/flink,yew1eb/flink,wwjiang007/flink,haohui/flink,lincoln-lil/flink,GJL/flink,godfreyhe/flink,apache/flink,hequn8128/flink,kl0u/flink,kaibozhou/flink,zimmermatt/flink,gustavoanatoly/flink,greghogan/flink,StephanEwen/incubator-flink,tony810430/flink,clarkyzl/flink,bowenli86/flink,DieBauer/flink,WangTaoTheTonic/flink,Xpray/flink,StephanEwen/incubator-flink,gyfora/flink,mbode/flink,shaoxuan-wang/flink,hwstreaming/flink,kaibozhou/flink,GJL/flink,mtunique/flink,PangZhi/flink,Xpray/flink,tillrohrmann/flink,sunjincheng121/flink,DieBauer/flink,tillrohrmann/flink,tzulitai/flink,xccui/flink,rmetzger/flink,hequn8128/flink,aljoscha/flink,mbode/flink,fanyon/flink,jinglining/flink,fanzhidongyzby/flink,hequn8128/flink,zjureel/flink,hequn8128/flink,zohar-mizrahi/flink,aljoscha/flink,bowenli86/flink,apache/flink,fanzhidongyzby/flink,haohui/flink,bowenli86/flink,gyfora/flink,rmetzger/flink,mbode/flink,tzulitai/flink,hequn8128/flink,wwjiang007/flink,hongyuhong/flink,zimmermatt/flink,yew1eb/flink,kl0u/flink,greghogan/flink,WangTaoTheTonic/flink,apache/flink,yew1eb/flink,tzulitai/flink,GJL/flink,gustavoanatoly/flink,lincoln-lil/flink,gyfora/flink,darionyaphet/flink,mylog00/flink,zhangminglei/flink,wwjiang007/flink,kaibozhou/flink,clarkyzl/flink,zjureel/flink,twalthr/flink,lincoln-lil/flink,ueshin/apache-flink,DieBauer/flink,lincoln-lil/flink,darionyaphet/flink,rmetzger/flink,sunjincheng121/flink,jinglining/flink,clarkyzl/flink,fhueske/flink,aljoscha/flink,hwstreaming/flink,GJL/flink,zentol/flink,aljoscha/flink,zentol/flink,hwstreaming/flink,kaibozhou/flink,yew1eb/flink,tillrohrmann/flink,twalthr/flink,greghogan/flink,PangZhi/flink,yew1eb/flink,DieBauer/flink,tzulitai/flink,fanzhidongyzby/flink,greghogan/flink,Xpray/flink,zjureel/flink,jinglining/flink,gyfora/flink,godfreyhe/flink,godfreyhe/flink,mbode/flink,tillrohrmann/flink,mbode/flink,apache/flink,zhangminglei/flink,rmetzger/flink,apache/flink,zhangminglei/flink,twalthr/flink,ueshin/apache-flink,zentol/flink,godfreyhe/flink,gyfora/flink,sunjincheng121/flink,greghogan/flink,WangTaoTheTonic/flink,mylog00/flink,greghogan/flink,tony810430/flink,kaibozhou/flink,hongyuhong/flink,mylog00/flink,tony810430/flink,DieBauer/flink,mtunique/flink,GJL/flink,gustavoanatoly/flink,StephanEwen/incubator-flink,aljoscha/flink,haohui/flink,StephanEwen/incubator-flink,bowenli86/flink,sunjincheng121/flink,jinglining/flink,zimmermatt/flink,PangZhi/flink,jinglining/flink,rmetzger/flink,sunjincheng121/flink,xccui/flink,mylog00/flink,twalthr/flink,zentol/flink,fanzhidongyzby/flink,hongyuhong/flink,clarkyzl/flink,zohar-mizrahi/flink,shaoxuan-wang/flink,fanzhidongyzby/flink,clarkyzl/flink,xccui/flink,fanyon/flink,rmetzger/flink,hequn8128/flink,StephanEwen/incubator-flink,haohui/flink,mtunique/flink,kl0u/flink,ueshin/apache-flink,fanyon/flink,hwstreaming/flink,kl0u/flink,zjureel/flink,wwjiang007/flink,haohui/flink,lincoln-lil/flink,zjureel/flink,hongyuhong/flink,Xpray/flink,xccui/flink,zimmermatt/flink,sunjincheng121/flink,PangZhi/flink,darionyaphet/flink,wwjiang007/flink,zohar-mizrahi/flink,WangTaoTheTonic/flink,Xpray/flink,mtunique/flink,wwjiang007/flink,jinglining/flink,aljoscha/flink,zhangminglei/flink,StephanEwen/incubator-flink,tony810430/flink,xccui/flink,godfreyhe/flink,fhueske/flink,tony810430/flink,bowenli86/flink | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.metrics;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Metric;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.View;
import org.apache.flink.metrics.reporter.MetricReporter;
import org.apache.flink.metrics.reporter.Scheduled;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.metrics.dump.MetricQueryService;
import org.apache.flink.runtime.metrics.groups.AbstractMetricGroup;
import org.apache.flink.runtime.metrics.groups.FrontMetricGroup;
import org.apache.flink.runtime.metrics.scope.ScopeFormats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A MetricRegistry keeps track of all registered {@link Metric Metrics}. It serves as the
* connection between {@link MetricGroup MetricGroups} and {@link MetricReporter MetricReporters}.
*/
public class MetricRegistry {
static final Logger LOG = LoggerFactory.getLogger(MetricRegistry.class);
private List<MetricReporter> reporters;
private ScheduledExecutorService executor;
private ActorRef queryService;
private ViewUpdater viewUpdater;
private final ScopeFormats scopeFormats;
private final char globalDelimiter;
private final List<Character> delimiters = new ArrayList<>();
/**
* Creates a new MetricRegistry and starts the configured reporter.
*/
public MetricRegistry(MetricRegistryConfiguration config) {
this.scopeFormats = config.getScopeFormats();
this.globalDelimiter = config.getDelimiter();
// second, instantiate any custom configured reporters
this.reporters = new ArrayList<>();
List<Tuple2<String, Configuration>> reporterConfigurations = config.getReporterConfigurations();
this.executor = Executors.newSingleThreadScheduledExecutor(new MetricRegistryThreadFactory());
if (reporterConfigurations.isEmpty()) {
// no reporters defined
// by default, don't report anything
LOG.info("No metrics reporter configured, no metrics will be exposed/reported.");
} else {
// we have some reporters so
for (Tuple2<String, Configuration> reporterConfiguration: reporterConfigurations) {
String namedReporter = reporterConfiguration.f0;
Configuration reporterConfig = reporterConfiguration.f1;
final String className = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX, null);
if (className == null) {
LOG.error("No reporter class set for reporter " + namedReporter + ". Metrics might not be exposed/reported.");
continue;
}
try {
String configuredPeriod = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_INTERVAL_SUFFIX, null);
TimeUnit timeunit = TimeUnit.SECONDS;
long period = 10;
if (configuredPeriod != null) {
try {
String[] interval = configuredPeriod.split(" ");
period = Long.parseLong(interval[0]);
timeunit = TimeUnit.valueOf(interval[1]);
}
catch (Exception e) {
LOG.error("Cannot parse report interval from config: " + configuredPeriod +
" - please use values like '10 SECONDS' or '500 MILLISECONDS'. " +
"Using default reporting interval.");
}
}
Class<?> reporterClass = Class.forName(className);
MetricReporter reporterInstance = (MetricReporter) reporterClass.newInstance();
MetricConfig metricConfig = new MetricConfig();
reporterConfig.addAllToProperties(metricConfig);
reporterInstance.open(metricConfig);
if (reporterInstance instanceof Scheduled) {
LOG.info("Periodically reporting metrics in intervals of {} {} for reporter {} of type {}.", period, timeunit.name(), namedReporter, className);
executor.scheduleWithFixedDelay(
new MetricRegistry.ReporterTask((Scheduled) reporterInstance), period, period, timeunit);
} else {
LOG.info("Reporting metrics for reporter {} of type {}.", namedReporter, className);
}
reporters.add(reporterInstance);
String delimiterForReporter = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER, String.valueOf(globalDelimiter));
if (delimiterForReporter.length() != 1) {
LOG.warn("Failed to parse delimiter '{}' for reporter '{}', using global delimiter '{}'.", delimiterForReporter, namedReporter, globalDelimiter);
delimiterForReporter = String.valueOf(globalDelimiter);
}
this.delimiters.add(delimiterForReporter.charAt(0));
}
catch (Throwable t) {
LOG.error("Could not instantiate metrics reporter {}. Metrics might not be exposed/reported.", namedReporter, t);
}
}
}
}
/**
* Initializes the MetricQueryService.
*
* @param actorSystem ActorSystem to create the MetricQueryService on
* @param resourceID resource ID used to disambiguate the actor name
*/
public void startQueryService(ActorSystem actorSystem, ResourceID resourceID) {
try {
queryService = MetricQueryService.startMetricQueryService(actorSystem, resourceID);
} catch (Exception e) {
LOG.warn("Could not start MetricDumpActor. No metrics will be submitted to the WebInterface.", e);
}
}
/**
* Returns the global delimiter.
*
* @return global delimiter
*/
public char getDelimiter() {
return this.globalDelimiter;
}
/**
* Returns the configured delimiter for the reporter with the given index.
*
* @param reporterIndex index of the reporter whose delimiter should be used
* @return configured reporter delimiter, or global delimiter if index is invalid
*/
public char getDelimiter(int reporterIndex) {
try {
return delimiters.get(reporterIndex);
} catch (IndexOutOfBoundsException e) {
LOG.warn("Delimiter for reporter index {} not found, returning global delimiter.", reporterIndex);
return this.globalDelimiter;
}
}
public List<MetricReporter> getReporters() {
return reporters;
}
/**
* Shuts down this registry and the associated {@link MetricReporter}.
*/
public void shutdown() {
if (reporters != null) {
for (MetricReporter reporter : reporters) {
try {
reporter.close();
} catch (Throwable t) {
LOG.warn("Metrics reporter did not shut down cleanly", t);
}
}
reporters = null;
}
shutdownExecutor();
}
private void shutdownExecutor() {
if (executor != null) {
executor.shutdown();
try {
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
}
}
}
public ScopeFormats getScopeFormats() {
return scopeFormats;
}
// ------------------------------------------------------------------------
// Metrics (de)registration
// ------------------------------------------------------------------------
/**
* Registers a new {@link Metric} with this registry.
*
* @param metric the metric that was added
* @param metricName the name of the metric
* @param group the group that contains the metric
*/
public void register(Metric metric, String metricName, AbstractMetricGroup group) {
try {
if (reporters != null) {
for (int i = 0; i < reporters.size(); i++) {
MetricReporter reporter = reporters.get(i);
if (reporter != null) {
FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
reporter.notifyOfAddedMetric(metric, metricName, front);
}
}
}
if (queryService != null) {
MetricQueryService.notifyOfAddedMetric(queryService, metric, metricName, group);
}
if (metric instanceof View) {
if (viewUpdater == null) {
viewUpdater = new ViewUpdater(executor);
}
viewUpdater.notifyOfAddedView((View) metric);
}
} catch (Exception e) {
LOG.error("Error while registering metric.", e);
}
}
/**
* Un-registers the given {@link Metric} with this registry.
*
* @param metric the metric that should be removed
* @param metricName the name of the metric
* @param group the group that contains the metric
*/
public void unregister(Metric metric, String metricName, AbstractMetricGroup group) {
try {
if (reporters != null) {
for (int i = 0; i < reporters.size(); i++) {
MetricReporter reporter = reporters.get(i);
if (reporter != null) {
FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
reporter.notifyOfRemovedMetric(metric, metricName, front);
}
}
}
if (queryService != null) {
MetricQueryService.notifyOfRemovedMetric(queryService, metric);
}
if (metric instanceof View) {
if (viewUpdater != null) {
viewUpdater.notifyOfRemovedView((View) metric);
}
}
} catch (Exception e) {
LOG.error("Error while registering metric.", e);
}
}
// ------------------------------------------------------------------------
/**
* This task is explicitly a static class, so that it does not hold any references to the enclosing
* MetricsRegistry instance.
*
* This is a subtle difference, but very important: With this static class, the enclosing class instance
* may become garbage-collectible, whereas with an anonymous inner class, the timer thread
* (which is a GC root) will hold a reference via the timer task and its enclosing instance pointer.
* Making the MetricsRegistry garbage collectible makes the java.util.Timer garbage collectible,
* which acts as a fail-safe to stop the timer thread and prevents resource leaks.
*/
private static final class ReporterTask extends TimerTask {
private final Scheduled reporter;
private ReporterTask(Scheduled reporter) {
this.reporter = reporter;
}
@Override
public void run() {
try {
reporter.report();
} catch (Throwable t) {
LOG.warn("Error while reporting metrics", t);
}
}
}
private static final class MetricRegistryThreadFactory implements ThreadFactory {
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
MetricRegistryThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, "Flink-MetricRegistry-" + threadNumber.incrementAndGet(), 0);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
}
| flink-runtime/src/main/java/org/apache/flink/runtime/metrics/MetricRegistry.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.metrics;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Metric;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.View;
import org.apache.flink.metrics.reporter.MetricReporter;
import org.apache.flink.metrics.reporter.Scheduled;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.metrics.dump.MetricQueryService;
import org.apache.flink.runtime.metrics.groups.AbstractMetricGroup;
import org.apache.flink.runtime.metrics.groups.FrontMetricGroup;
import org.apache.flink.runtime.metrics.scope.ScopeFormats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* A MetricRegistry keeps track of all registered {@link Metric Metrics}. It serves as the
* connection between {@link MetricGroup MetricGroups} and {@link MetricReporter MetricReporters}.
*/
public class MetricRegistry {
static final Logger LOG = LoggerFactory.getLogger(MetricRegistry.class);
private List<MetricReporter> reporters;
private ScheduledExecutorService executor;
private ActorRef queryService;
private ViewUpdater viewUpdater;
private final ScopeFormats scopeFormats;
private final char globalDelimiter;
private final List<Character> delimiters = new ArrayList<>();
/**
* Creates a new MetricRegistry and starts the configured reporter.
*/
public MetricRegistry(MetricRegistryConfiguration config) {
this.scopeFormats = config.getScopeFormats();
this.globalDelimiter = config.getDelimiter();
// second, instantiate any custom configured reporters
this.reporters = new ArrayList<>();
List<Tuple2<String, Configuration>> reporterConfigurations = config.getReporterConfigurations();
this.executor = Executors.newSingleThreadScheduledExecutor();
if (reporterConfigurations.isEmpty()) {
// no reporters defined
// by default, don't report anything
LOG.info("No metrics reporter configured, no metrics will be exposed/reported.");
} else {
// we have some reporters so
for (Tuple2<String, Configuration> reporterConfiguration: reporterConfigurations) {
String namedReporter = reporterConfiguration.f0;
Configuration reporterConfig = reporterConfiguration.f1;
final String className = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX, null);
if (className == null) {
LOG.error("No reporter class set for reporter " + namedReporter + ". Metrics might not be exposed/reported.");
continue;
}
try {
String configuredPeriod = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_INTERVAL_SUFFIX, null);
TimeUnit timeunit = TimeUnit.SECONDS;
long period = 10;
if (configuredPeriod != null) {
try {
String[] interval = configuredPeriod.split(" ");
period = Long.parseLong(interval[0]);
timeunit = TimeUnit.valueOf(interval[1]);
}
catch (Exception e) {
LOG.error("Cannot parse report interval from config: " + configuredPeriod +
" - please use values like '10 SECONDS' or '500 MILLISECONDS'. " +
"Using default reporting interval.");
}
}
Class<?> reporterClass = Class.forName(className);
MetricReporter reporterInstance = (MetricReporter) reporterClass.newInstance();
MetricConfig metricConfig = new MetricConfig();
reporterConfig.addAllToProperties(metricConfig);
reporterInstance.open(metricConfig);
if (reporterInstance instanceof Scheduled) {
LOG.info("Periodically reporting metrics in intervals of {} {} for reporter {} of type {}.", period, timeunit.name(), namedReporter, className);
executor.scheduleWithFixedDelay(
new MetricRegistry.ReporterTask((Scheduled) reporterInstance), period, period, timeunit);
} else {
LOG.info("Reporting metrics for reporter {} of type {}.", namedReporter, className);
}
reporters.add(reporterInstance);
String delimiterForReporter = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER, String.valueOf(globalDelimiter));
if (delimiterForReporter.length() != 1) {
LOG.warn("Failed to parse delimiter '{}' for reporter '{}', using global delimiter '{}'.", delimiterForReporter, namedReporter, globalDelimiter);
delimiterForReporter = String.valueOf(globalDelimiter);
}
this.delimiters.add(delimiterForReporter.charAt(0));
}
catch (Throwable t) {
LOG.error("Could not instantiate metrics reporter {}. Metrics might not be exposed/reported.", namedReporter, t);
}
}
}
}
/**
* Initializes the MetricQueryService.
*
* @param actorSystem ActorSystem to create the MetricQueryService on
* @param resourceID resource ID used to disambiguate the actor name
*/
public void startQueryService(ActorSystem actorSystem, ResourceID resourceID) {
try {
queryService = MetricQueryService.startMetricQueryService(actorSystem, resourceID);
} catch (Exception e) {
LOG.warn("Could not start MetricDumpActor. No metrics will be submitted to the WebInterface.", e);
}
}
/**
* Returns the global delimiter.
*
* @return global delimiter
*/
public char getDelimiter() {
return this.globalDelimiter;
}
/**
* Returns the configured delimiter for the reporter with the given index.
*
* @param reporterIndex index of the reporter whose delimiter should be used
* @return configured reporter delimiter, or global delimiter if index is invalid
*/
public char getDelimiter(int reporterIndex) {
try {
return delimiters.get(reporterIndex);
} catch (IndexOutOfBoundsException e) {
LOG.warn("Delimiter for reporter index {} not found, returning global delimiter.", reporterIndex);
return this.globalDelimiter;
}
}
public List<MetricReporter> getReporters() {
return reporters;
}
/**
* Shuts down this registry and the associated {@link MetricReporter}.
*/
public void shutdown() {
if (reporters != null) {
for (MetricReporter reporter : reporters) {
try {
reporter.close();
} catch (Throwable t) {
LOG.warn("Metrics reporter did not shut down cleanly", t);
}
}
reporters = null;
}
shutdownExecutor();
}
private void shutdownExecutor() {
if (executor != null) {
executor.shutdown();
try {
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
}
}
}
public ScopeFormats getScopeFormats() {
return scopeFormats;
}
// ------------------------------------------------------------------------
// Metrics (de)registration
// ------------------------------------------------------------------------
/**
* Registers a new {@link Metric} with this registry.
*
* @param metric the metric that was added
* @param metricName the name of the metric
* @param group the group that contains the metric
*/
public void register(Metric metric, String metricName, AbstractMetricGroup group) {
try {
if (reporters != null) {
for (int i = 0; i < reporters.size(); i++) {
MetricReporter reporter = reporters.get(i);
if (reporter != null) {
FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
reporter.notifyOfAddedMetric(metric, metricName, front);
}
}
}
if (queryService != null) {
MetricQueryService.notifyOfAddedMetric(queryService, metric, metricName, group);
}
if (metric instanceof View) {
if (viewUpdater == null) {
viewUpdater = new ViewUpdater(executor);
}
viewUpdater.notifyOfAddedView((View) metric);
}
} catch (Exception e) {
LOG.error("Error while registering metric.", e);
}
}
/**
* Un-registers the given {@link Metric} with this registry.
*
* @param metric the metric that should be removed
* @param metricName the name of the metric
* @param group the group that contains the metric
*/
public void unregister(Metric metric, String metricName, AbstractMetricGroup group) {
try {
if (reporters != null) {
for (int i = 0; i < reporters.size(); i++) {
MetricReporter reporter = reporters.get(i);
if (reporter != null) {
FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
reporter.notifyOfRemovedMetric(metric, metricName, front);
}
}
}
if (queryService != null) {
MetricQueryService.notifyOfRemovedMetric(queryService, metric);
}
if (metric instanceof View) {
if (viewUpdater != null) {
viewUpdater.notifyOfRemovedView((View) metric);
}
}
} catch (Exception e) {
LOG.error("Error while registering metric.", e);
}
}
// ------------------------------------------------------------------------
/**
* This task is explicitly a static class, so that it does not hold any references to the enclosing
* MetricsRegistry instance.
*
* This is a subtle difference, but very important: With this static class, the enclosing class instance
* may become garbage-collectible, whereas with an anonymous inner class, the timer thread
* (which is a GC root) will hold a reference via the timer task and its enclosing instance pointer.
* Making the MetricsRegistry garbage collectible makes the java.util.Timer garbage collectible,
* which acts as a fail-safe to stop the timer thread and prevents resource leaks.
*/
private static final class ReporterTask extends TimerTask {
private final Scheduled reporter;
private ReporterTask(Scheduled reporter) {
this.reporter = reporter;
}
@Override
public void run() {
try {
reporter.report();
} catch (Throwable t) {
LOG.warn("Error while reporting metrics", t);
}
}
}
}
| [hotfix] [metrics] Supply name to view/reporter thread
| flink-runtime/src/main/java/org/apache/flink/runtime/metrics/MetricRegistry.java | [hotfix] [metrics] Supply name to view/reporter thread | <ide><path>link-runtime/src/main/java/org/apache/flink/runtime/metrics/MetricRegistry.java
<ide> import java.util.TimerTask;
<ide> import java.util.concurrent.Executors;
<ide> import java.util.concurrent.ScheduledExecutorService;
<add>import java.util.concurrent.ThreadFactory;
<ide> import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> /**
<ide> * A MetricRegistry keeps track of all registered {@link Metric Metrics}. It serves as the
<ide>
<ide> List<Tuple2<String, Configuration>> reporterConfigurations = config.getReporterConfigurations();
<ide>
<del> this.executor = Executors.newSingleThreadScheduledExecutor();
<add> this.executor = Executors.newSingleThreadScheduledExecutor(new MetricRegistryThreadFactory());
<ide>
<ide> if (reporterConfigurations.isEmpty()) {
<ide> // no reporters defined
<ide> }
<ide> }
<ide> }
<add>
<add> private static final class MetricRegistryThreadFactory implements ThreadFactory {
<add> private final ThreadGroup group;
<add> private final AtomicInteger threadNumber = new AtomicInteger(1);
<add>
<add> MetricRegistryThreadFactory() {
<add> SecurityManager s = System.getSecurityManager();
<add> group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
<add> }
<add>
<add> public Thread newThread(Runnable r) {
<add> Thread t = new Thread(group, r, "Flink-MetricRegistry-" + threadNumber.incrementAndGet(), 0);
<add> if (t.isDaemon()) {
<add> t.setDaemon(false);
<add> }
<add> if (t.getPriority() != Thread.NORM_PRIORITY) {
<add> t.setPriority(Thread.NORM_PRIORITY);
<add> }
<add> return t;
<add> }
<add> }
<ide> } |
|
Java | bsd-3-clause | e30a31f8ba4b6e411c1a796acecdf54b1ff66673 | 0 | ktgw0316/LightZone,ktgw0316/LightZone,ktgw0316/LightZone,ktgw0316/LightZone,ktgw0316/LightZone,ktgw0316/LightZone,ktgw0316/LightZone | /* Copyright (C) 2005-2011 Fabio Riccardi */
/* Copyright (C) 2019- Masahiro Kitagawa */
package com.lightcrafts.ui.editor;
import com.lightcrafts.model.CropBounds;
import com.lightcrafts.model.Operation;
import com.lightcrafts.platform.Platform;
import com.lightcrafts.ui.crop.CropListener;
import com.lightcrafts.ui.crop.CropMode;
import com.lightcrafts.ui.mode.AbstractMode;
import com.lightcrafts.ui.mode.Mode;
import com.lightcrafts.ui.mode.ModeOverlay;
import com.lightcrafts.ui.operation.OpControl;
import com.lightcrafts.ui.operation.OpControlModeListener;
import com.lightcrafts.ui.operation.OpStackListener;
import com.lightcrafts.ui.operation.SelectableControl;
import com.lightcrafts.ui.region.RegionOverlay;
import com.lightcrafts.utils.awt.geom.HiDpi;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
/**
* Handle switching among all the Modes. Lots of special mode-transition
* logic lives here, plus the affine transform updates for Modes.
* <p>
* ModeManager sets and resets the crop when CropMode starts and ends.
* The pan mode is entered on a key press and exited on release. The
* temporary Modes defined by OpControls are added and removed here too.
*/
public class ModeManager
implements OpStackListener, OpControlModeListener, XFormListener
{
// Look for the special key events to enter and exit the pan mode,
// taking care to filter out auto-repeat events:
private static int PanKeyCode = Platform.isMac()
? KeyEvent.VK_META
: KeyEvent.VK_CONTROL;
private KeyEventPostProcessor panModeKeyProcessor =
new KeyEventPostProcessor() {
private boolean isPanMode;
public boolean postProcessKeyEvent(KeyEvent e) {
final boolean wasPanMode = (overlay.peekMode() == transientPanMode);
if (e.getKeyCode() == PanKeyCode) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
isPanMode = true;
}
if (e.getID() == KeyEvent.KEY_RELEASED) {
if (Platform.isMac()) {
isPanMode = false;
}
else {
// Detect and ignore auto-repeat release events
final boolean isReallyPressed =
Platform.getPlatform().isKeyPressed(
PanKeyCode
);
isPanMode = isReallyPressed;
}
}
}
if (isPanMode && ! wasPanMode) {
overlay.pushMode(transientPanMode);
}
if (wasPanMode && ! isPanMode) {
overlay.popMode();
}
return false; // these key events have other interpretations
}
};
private Document doc;
private ModeOverlay overlay;
private AffineTransform xform;
private Mode regionMode;
private CropMode cropMode;
private AbstractMode transientPanMode; // works with other modes (space key)
private AbstractMode permanentPanMode; // present in "no mode" (arrow cursor)
private CropMode rotateMode;
// The "extras" component for the region mode
private JComponent regionExtras;
// If someone clicks "Commit" in crop mode, we must update the mode buttons
private ModeButtons modeButtons;
// OpControls can ask for short-term Mode push/pops:
private OpControl control; // add and remove the listener
private Mode controlMode; // update the AffineTransform
// Keep track of where the underlay is, so the crop overlay can be
// initialized the first time it's entered.
private Rectangle underlayBounds;
ModeManager(
Mode regionMode,
CropMode cropMode,
AbstractMode transientPanMode,// After spacebar
AbstractMode permanentPanMode,// Always-on
CropMode rotateMode,
ModeOverlay overlay,
Component underlay,
JComponent regionExtras, // The curve-type buttons
Document doc // For zoom-to-fit around the crop mode
) {
this.overlay = overlay;
this.regionExtras = regionExtras;
this.doc = doc;
xform = new AffineTransform();
this.regionMode = regionMode;
this.cropMode = cropMode;
this.transientPanMode = transientPanMode;
this.permanentPanMode = permanentPanMode;
this.rotateMode = rotateMode;
// The AffineTransform in the Modes sometimes depends on the size
// of the ModeOverlay:
overlay.addComponentListener(
new ComponentAdapter() {
public void componentResized(ComponentEvent event) {
setTransform(xform);
}
}
);
// Modes also require notification about the location and size of
// their underlay:
underlay.addComponentListener(
new ComponentAdapter() {
public void componentResized(ComponentEvent event) {
Rectangle bounds = event.getComponent().getBounds();
setUnderlayBounds(bounds);
}
public void componentMoved(ComponentEvent event) {
Rectangle bounds = event.getComponent().getBounds();
setUnderlayBounds(bounds);
}
}
);
// The crop and rotate modes likes to end themselves:
cropMode.addCropListener(
new CropListener() {
public void cropCommitted(CropBounds bounds) {
// This may be called because someone already switched
// away from the crop mode, but it may also be called
// from the "Commit" crop mode popup menu item, in which
// case we must handle the mode switch ourselves.
EventQueue.invokeLater(
new Runnable() {
public void run() {
if (modeButtons != null) {
if (modeButtons.isCropSelected()) {
setEditorMode( EditorMode.ARROW );
}
}
}
}
);
}
public void unCrop() {
}
}
);
rotateMode.addCropListener(
new CropListener() {
public void cropCommitted(CropBounds bounds) {
// This may be called because someone already switched
// away from the rotate mode, but it may also be called
// from the "Commit" crop mode popup menu item, in which
// case we must handle the mode switch ourselves.
EventQueue.invokeLater(
new Runnable() {
public void run() {
if (modeButtons != null) {
if (modeButtons.isRotateSelected()) {
setEditorMode( EditorMode.ARROW );
}
}
}
}
);
}
public void unCrop() {
}
}
);
registerPanModeListener();
setMode(this.permanentPanMode);
}
public EditorMode getMode() {
return m_editorMode;
}
void setModeButtons(ModeButtons buttons) {
modeButtons = buttons;
}
// Start OpStackListener:
public void opAdded(OpControl control) {
}
public void opChanged(OpControl control) {
if (isControlModeActive()) {
exitMode(null);
}
if (this.control != null) {
this.control.removeModeListener(this);
} else
setEditorMode( EditorMode.ARROW );
this.control = control;
if (control != null && ! control.isLocked()) {
control.addModeListener(this);
}
// Some OpControls don't get regions.
final boolean isLocked = (control != null) && control.isLocked();
final boolean isRaw = (control != null) && control.isRawCorrection();
if (isLocked || isRaw) {
modeButtons.setRegionsEnabled(false);
} else {
modeButtons.setRegionsEnabled(true);
}
if ( control != null ) {
final Operation op = control.getOperation();
final EditorMode prefMode = op.getPreferredMode();
if ( isLocked || isRaw ||
prefMode != EditorMode.ARROW ||
m_editorMode == EditorMode.ARROW )
setEditorMode( prefMode );
}
}
public void opChanged(SelectableControl control) {
if (this.control != null) {
this.control.removeModeListener(this);
this.control = null;
}
if ( control instanceof ProofSelectableControl )
setMode( null );
if ( control == null )
setMode( null );
}
public void opLockChanged(OpControl control) {
if (this.control == control) {
opChanged(control);
}
}
public void opRemoved(OpControl control) {
// Since region mode interacts with the tool stack selection,
// be sure to pop out of that mode if it's the current mode at
// the time a tool is deleted.
if (overlay.peekMode() == regionMode) {
if (this.control != null) {
Operation op = this.control.getOperation();
if (op.getPreferredMode() != EditorMode.REGION) {
EventQueue.invokeLater(
new Runnable() {
public void run() {
setEditorMode( EditorMode.ARROW );
}
}
);
}
}
}
}
// End OpStackListener.
public void setEditorMode( EditorMode mode ) {
if ( mode == m_editorMode )
return;
if ( modeButtons != null )
switch ( mode ) {
case ARROW:
modeButtons.clickNoMode();
break;
case CROP:
modeButtons.clickCropButton();
break;
case REGION:
modeButtons.clickRegionButton();
break;
case ROTATE:
modeButtons.clickRotateButton();
}
m_editorMode = mode;
}
// Start OpControlModeListener:
public void enterMode(Mode mode) {
mode.enter();
assert (! isControlModeActive());
controlMode = mode;
controlMode.setTransform(getOverlayTransform());
overlay.pushMode(controlMode);
}
public void exitMode(Mode mode) {
assert isControlModeActive();
if ( mode != null )
mode.exit();
overlay.popMode();
controlMode = null;
}
// End OpControlModeListener.
// Start XFormListener:
public void xFormChanged(AffineTransform xform) {
// First, validate from the overlay's validate root, because the
// overlay bounds partly determine the overlay affine transform.
JScrollPane scroll = (JScrollPane) SwingUtilities.getAncestorOfClass(
JScrollPane.class, overlay
);
if (scroll != null){
overlay.invalidate(); // mark the overay as needing to update
scroll.validate(); // update the layout under the scroll pane
}
setTransform(xform);
}
// End XFormListener.
private boolean isControlModeActive() {
return (controlMode != null) && overlay.peekMode().equals(controlMode);
}
private boolean isTransientPanModeActive() {
return overlay.peekMode().equals(transientPanMode);
}
private void setTransform(AffineTransform xform) {
//
// The given AffineTranform maps original image coordinates to the
// coordinates of the image component on the screen. The Modes
// require an AffineTransform mapping original image coordinates to
// coordinates of the Mode overlay component.
//
// Referring to ModeOverlay, the origin of a Mode's overlay component
// does not necessarily coincide with the origin of the image
// component. If the image is zoomed out to a size smaller than an
// enclosing scroll pane viewport, then the Mode overlay component
// will be larger than the image, filling the viewport.
//
// So, depending on this viewport condition, we may need to add a
// translation to the transform:
//
this.xform = xform;
AffineTransform overlayTransform = getOverlayTransform();
regionMode.setTransform(overlayTransform);
cropMode.setTransform(overlayTransform);
transientPanMode.setTransform(overlayTransform);
rotateMode.setTransform(overlayTransform);
if (controlMode != null) {
controlMode.setTransform(overlayTransform);
}
}
// Also used from DocPanel to forward mouse motion to the Previews.
AffineTransform getOverlayTransform() {
AffineTransform overlayXform = overlay.getTransform();
AffineTransform totalXform = (AffineTransform) xform.clone();
totalXform.preConcatenate(overlayXform);
return totalXform;
}
private void setUnderlayBounds(Rectangle bounds) {
if (bounds.equals(underlayBounds)) {
return;
}
underlayBounds = bounds;
regionMode.setUnderlayBounds(bounds);
cropMode.setUnderlayBounds(bounds);
transientPanMode.setUnderlayBounds(bounds);
rotateMode.setUnderlayBounds(bounds);
if (controlMode != null) {
controlMode.setUnderlayBounds(bounds);
}
// The default crop bounds depend on the underlay bounds.
CropBounds crop = cropMode.getCrop();
CropBounds initCrop = getInitialCropBounds();
if (crop == null) {
cropMode.setCropWithConstraints(initCrop);
}
cropMode.setResetCropBounds(initCrop);
}
JComponent setNoMode() {
boolean wasCrop =
((overlay.peekMode() == cropMode) ||
(overlay.peekMode() == rotateMode));
setMode(null);
m_editorMode = EditorMode.ARROW;
if (wasCrop) {
boolean isFitMode = doc.popFitMode();
if (! isFitMode) {
doc.zoomToFit();
}
}
return null;
}
EditorMode m_editorMode;
JComponent setCropMode() {
doc.markDirty();
setMode(cropMode);
m_editorMode = EditorMode.CROP;
doc.pushFitMode();
doc.zoomToFit();
return cropMode.getControl();
}
JComponent setRotateMode() {
doc.markDirty();
setMode(rotateMode);
m_editorMode = EditorMode.ROTATE;
doc.pushFitMode();
doc.zoomToFit();
// The "reset" button in rotate mode depends on the initial crop:
CropBounds crop = cropMode.getCrop();
rotateMode.setCrop(crop);
rotateMode.setResetCropBounds(crop);
return rotateMode.getControl().getResetButton();
}
JComponent setRegionMode() {
boolean wasCrop =
((overlay.peekMode() == cropMode) ||
(overlay.peekMode() == rotateMode));
setMode(regionMode);
m_editorMode = EditorMode.REGION;
if (wasCrop) {
boolean isFitMode = doc.popFitMode();
if (! isFitMode) {
doc.zoomToFit();
}
}
return regionExtras;
}
private void setMode(Mode newMode) {
// Peel off any temporary Modes we may have pushed.
while (isControlModeActive() || isTransientPanModeActive()) {
overlay.popMode();
controlMode = null;
}
// See if that did the trick, to avoid duplicate pushes.
Mode oldMode = overlay.peekMode();
if (oldMode == newMode) {
return;
}
// If the current Mode is one of ours, pop it before pushing the next:
if (oldMode == regionMode ||
oldMode == cropMode ||
oldMode == rotateMode) {
// If we are in region mode make sure we exit edit mode
if (oldMode == regionMode && regionMode instanceof RegionOverlay)
((RegionOverlay) regionMode).finishEditingCurve();
overlay.popMode();
// The CropModes need setup and teardown:
if ((oldMode == cropMode) || (oldMode == rotateMode)) {
CropMode crop = (CropMode) oldMode;
crop.doCrop();
}
oldMode.exit();
}
if (newMode != null) {
overlay.pushMode(newMode);
newMode.enter();
}
// The CropModes need setup and teardown:
if ((newMode == cropMode) || (newMode == rotateMode)) {
CropMode crop = (CropMode) newMode;
crop.resetCrop();
}
// The CropModes need to be kept in sync with each other:
if (oldMode == cropMode) {
rotateMode.setCrop(cropMode.getCrop());
}
if (oldMode == rotateMode) {
cropMode.setCrop(rotateMode.getCrop());
}
}
// Get a default CropBounds for the CropMode overlay, in image
// coordinates.
private CropBounds getInitialCropBounds() {
final int x = underlayBounds.x;
final int y = underlayBounds.y;
final int width = underlayBounds.width;
final int height = underlayBounds.height;
Rectangle inset = new Rectangle(x, y, width, height);
CropBounds crop = new CropBounds(HiDpi.imageSpaceRectFrom(inset));
try {
AffineTransform inverse = getOverlayTransform().createInverse();
crop = CropBounds.transform(inverse, crop);
return crop;
}
catch (NoninvertibleTransformException e) {
// Leave the crop overlay uninitialized.
}
return null;
}
// Don't rely on keyboard focus to switch the pan mode.
// Instead, postprocess unclaimed key events:
private void registerPanModeListener() {
KeyboardFocusManager focus =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
focus.addKeyEventPostProcessor(panModeKeyProcessor);
}
void dispose() {
KeyboardFocusManager focus =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
focus.removeKeyEventPostProcessor(panModeKeyProcessor);
}
}
| lightcrafts/src/com/lightcrafts/ui/editor/ModeManager.java | /* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.ui.editor;
import com.lightcrafts.model.CropBounds;
import com.lightcrafts.model.Operation;
import com.lightcrafts.platform.Platform;
import com.lightcrafts.ui.crop.CropListener;
import com.lightcrafts.ui.crop.CropMode;
import com.lightcrafts.ui.mode.AbstractMode;
import com.lightcrafts.ui.mode.Mode;
import com.lightcrafts.ui.mode.ModeOverlay;
import com.lightcrafts.ui.operation.OpControl;
import com.lightcrafts.ui.operation.OpControlModeListener;
import com.lightcrafts.ui.operation.OpStackListener;
import com.lightcrafts.ui.operation.SelectableControl;
import com.lightcrafts.ui.region.RegionOverlay;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Rectangle2D;
/**
* Handle switching among all the Modes. Lots of special mode-transition
* logic lives here, plus the affine transform updates for Modes.
* <p>
* ModeManager sets and resets the crop when CropMode starts and ends.
* The pan mode is entered on a key press and exited on release. The
* temporary Modes defined by OpControls are added and removed here too.
*/
public class ModeManager
implements OpStackListener, OpControlModeListener, XFormListener
{
// Look for the special key events to enter and exit the pan mode,
// taking care to filter out auto-repeat events:
private static int PanKeyCode = Platform.isMac()
? KeyEvent.VK_META
: KeyEvent.VK_CONTROL;
private KeyEventPostProcessor panModeKeyProcessor =
new KeyEventPostProcessor() {
private boolean isPanMode;
public boolean postProcessKeyEvent(KeyEvent e) {
final boolean wasPanMode = (overlay.peekMode() == transientPanMode);
if (e.getKeyCode() == PanKeyCode) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
isPanMode = true;
}
if (e.getID() == KeyEvent.KEY_RELEASED) {
if (Platform.isMac()) {
isPanMode = false;
}
else {
// Detect and ignore auto-repeat release events
final boolean isReallyPressed =
Platform.getPlatform().isKeyPressed(
PanKeyCode
);
isPanMode = isReallyPressed;
}
}
}
if (isPanMode && ! wasPanMode) {
overlay.pushMode(transientPanMode);
}
if (wasPanMode && ! isPanMode) {
overlay.popMode();
}
return false; // these key events have other interpretations
}
};
private Document doc;
private ModeOverlay overlay;
private AffineTransform xform;
private Mode regionMode;
private CropMode cropMode;
private AbstractMode transientPanMode; // works with other modes (space key)
private AbstractMode permanentPanMode; // present in "no mode" (arrow cursor)
private CropMode rotateMode;
// The "extras" component for the region mode
private JComponent regionExtras;
// If someone clicks "Commit" in crop mode, we must update the mode buttons
private ModeButtons modeButtons;
// OpControls can ask for short-term Mode push/pops:
private OpControl control; // add and remove the listener
private Mode controlMode; // update the AffineTransform
// Keep track of where the underlay is, so the crop overlay can be
// initialized the first time it's entered.
private Rectangle underlayBounds;
ModeManager(
Mode regionMode,
CropMode cropMode,
AbstractMode transientPanMode,// After spacebar
AbstractMode permanentPanMode,// Always-on
CropMode rotateMode,
ModeOverlay overlay,
Component underlay,
JComponent regionExtras, // The curve-type buttons
Document doc // For zoom-to-fit around the crop mode
) {
this.overlay = overlay;
this.regionExtras = regionExtras;
this.doc = doc;
xform = new AffineTransform();
this.regionMode = regionMode;
this.cropMode = cropMode;
this.transientPanMode = transientPanMode;
this.permanentPanMode = permanentPanMode;
this.rotateMode = rotateMode;
// The AffineTransform in the Modes sometimes depends on the size
// of the ModeOverlay:
overlay.addComponentListener(
new ComponentAdapter() {
public void componentResized(ComponentEvent event) {
setTransform(xform);
}
}
);
// Modes also require notification about the location and size of
// their underlay:
underlay.addComponentListener(
new ComponentAdapter() {
public void componentResized(ComponentEvent event) {
Rectangle bounds = event.getComponent().getBounds();
setUnderlayBounds(bounds);
}
public void componentMoved(ComponentEvent event) {
Rectangle bounds = event.getComponent().getBounds();
setUnderlayBounds(bounds);
}
}
);
// The crop and rotate modes likes to end themselves:
cropMode.addCropListener(
new CropListener() {
public void cropCommitted(CropBounds bounds) {
// This may be called because someone already switched
// away from the crop mode, but it may also be called
// from the "Commit" crop mode popup menu item, in which
// case we must handle the mode switch ourselves.
EventQueue.invokeLater(
new Runnable() {
public void run() {
if (modeButtons != null) {
if (modeButtons.isCropSelected()) {
setEditorMode( EditorMode.ARROW );
}
}
}
}
);
}
public void unCrop() {
}
}
);
rotateMode.addCropListener(
new CropListener() {
public void cropCommitted(CropBounds bounds) {
// This may be called because someone already switched
// away from the rotate mode, but it may also be called
// from the "Commit" crop mode popup menu item, in which
// case we must handle the mode switch ourselves.
EventQueue.invokeLater(
new Runnable() {
public void run() {
if (modeButtons != null) {
if (modeButtons.isRotateSelected()) {
setEditorMode( EditorMode.ARROW );
}
}
}
}
);
}
public void unCrop() {
}
}
);
registerPanModeListener();
setMode(this.permanentPanMode);
}
public EditorMode getMode() {
return m_editorMode;
}
void setModeButtons(ModeButtons buttons) {
modeButtons = buttons;
}
// Start OpStackListener:
public void opAdded(OpControl control) {
}
public void opChanged(OpControl control) {
if (isControlModeActive()) {
exitMode(null);
}
if (this.control != null) {
this.control.removeModeListener(this);
} else
setEditorMode( EditorMode.ARROW );
this.control = control;
if (control != null && ! control.isLocked()) {
control.addModeListener(this);
}
// Some OpControls don't get regions.
final boolean isLocked = (control != null) && control.isLocked();
final boolean isRaw = (control != null) && control.isRawCorrection();
if (isLocked || isRaw) {
modeButtons.setRegionsEnabled(false);
} else {
modeButtons.setRegionsEnabled(true);
}
if ( control != null ) {
final Operation op = control.getOperation();
final EditorMode prefMode = op.getPreferredMode();
if ( isLocked || isRaw ||
prefMode != EditorMode.ARROW ||
m_editorMode == EditorMode.ARROW )
setEditorMode( prefMode );
}
}
public void opChanged(SelectableControl control) {
if (this.control != null) {
this.control.removeModeListener(this);
this.control = null;
}
if ( control instanceof ProofSelectableControl )
setMode( null );
if ( control == null )
setMode( null );
}
public void opLockChanged(OpControl control) {
if (this.control == control) {
opChanged(control);
}
}
public void opRemoved(OpControl control) {
// Since region mode interacts with the tool stack selection,
// be sure to pop out of that mode if it's the current mode at
// the time a tool is deleted.
if (overlay.peekMode() == regionMode) {
if (this.control != null) {
Operation op = this.control.getOperation();
if (op.getPreferredMode() != EditorMode.REGION) {
EventQueue.invokeLater(
new Runnable() {
public void run() {
setEditorMode( EditorMode.ARROW );
}
}
);
}
}
}
}
// End OpStackListener.
public void setEditorMode( EditorMode mode ) {
if ( mode == m_editorMode )
return;
if ( modeButtons != null )
switch ( mode ) {
case ARROW:
modeButtons.clickNoMode();
break;
case CROP:
modeButtons.clickCropButton();
break;
case REGION:
modeButtons.clickRegionButton();
break;
case ROTATE:
modeButtons.clickRotateButton();
}
m_editorMode = mode;
}
// Start OpControlModeListener:
public void enterMode(Mode mode) {
mode.enter();
assert (! isControlModeActive());
controlMode = mode;
controlMode.setTransform(getOverlayTransform());
overlay.pushMode(controlMode);
}
public void exitMode(Mode mode) {
assert isControlModeActive();
if ( mode != null )
mode.exit();
overlay.popMode();
controlMode = null;
}
// End OpControlModeListener.
// Start XFormListener:
public void xFormChanged(AffineTransform xform) {
// First, validate from the overlay's validate root, because the
// overlay bounds partly determine the overlay affine transform.
JScrollPane scroll = (JScrollPane) SwingUtilities.getAncestorOfClass(
JScrollPane.class, overlay
);
if (scroll != null){
overlay.invalidate(); // mark the overay as needing to update
scroll.validate(); // update the layout under the scroll pane
}
setTransform(xform);
}
// End XFormListener.
private boolean isControlModeActive() {
return (controlMode != null) && overlay.peekMode().equals(controlMode);
}
private boolean isTransientPanModeActive() {
return overlay.peekMode().equals(transientPanMode);
}
private void setTransform(AffineTransform xform) {
//
// The given AffineTranform maps original image coordinates to the
// coordinates of the image component on the screen. The Modes
// require an AffineTransform mapping original image coordinates to
// coordinates of the Mode overlay component.
//
// Referring to ModeOverlay, the origin of a Mode's overlay component
// does not necessarily coincide with the origin of the image
// component. If the image is zoomed out to a size smaller than an
// enclosing scroll pane viewport, then the Mode overlay component
// will be larger than the image, filling the viewport.
//
// So, depending on this viewport condition, we may need to add a
// translation to the transform:
//
this.xform = xform;
AffineTransform overlayTransform = getOverlayTransform();
regionMode.setTransform(overlayTransform);
cropMode.setTransform(overlayTransform);
transientPanMode.setTransform(overlayTransform);
rotateMode.setTransform(overlayTransform);
if (controlMode != null) {
controlMode.setTransform(overlayTransform);
}
}
// Also used from DocPanel to forward mouse motion to the Previews.
AffineTransform getOverlayTransform() {
AffineTransform overlayXform = overlay.getTransform();
AffineTransform totalXform = (AffineTransform) xform.clone();
totalXform.preConcatenate(overlayXform);
return totalXform;
}
private void setUnderlayBounds(Rectangle bounds) {
if (bounds.equals(underlayBounds)) {
return;
}
underlayBounds = bounds;
regionMode.setUnderlayBounds(bounds);
cropMode.setUnderlayBounds(bounds);
transientPanMode.setUnderlayBounds(bounds);
rotateMode.setUnderlayBounds(bounds);
if (controlMode != null) {
controlMode.setUnderlayBounds(bounds);
}
// The default crop bounds depend on the underlay bounds.
CropBounds crop = cropMode.getCrop();
CropBounds initCrop = getInitialCropBounds();
if (crop == null) {
cropMode.setCropWithConstraints(initCrop);
}
cropMode.setResetCropBounds(initCrop);
}
JComponent setNoMode() {
boolean wasCrop =
((overlay.peekMode() == cropMode) ||
(overlay.peekMode() == rotateMode));
setMode(null);
m_editorMode = EditorMode.ARROW;
if (wasCrop) {
boolean isFitMode = doc.popFitMode();
if (! isFitMode) {
doc.zoomToFit();
}
}
return null;
}
EditorMode m_editorMode;
JComponent setCropMode() {
doc.markDirty();
setMode(cropMode);
m_editorMode = EditorMode.CROP;
doc.pushFitMode();
doc.zoomToFit();
return cropMode.getControl();
}
JComponent setRotateMode() {
doc.markDirty();
setMode(rotateMode);
m_editorMode = EditorMode.ROTATE;
doc.pushFitMode();
doc.zoomToFit();
// The "reset" button in rotate mode depends on the initial crop:
CropBounds crop = cropMode.getCrop();
rotateMode.setCrop(crop);
rotateMode.setResetCropBounds(crop);
return rotateMode.getControl().getResetButton();
}
JComponent setRegionMode() {
boolean wasCrop =
((overlay.peekMode() == cropMode) ||
(overlay.peekMode() == rotateMode));
setMode(regionMode);
m_editorMode = EditorMode.REGION;
if (wasCrop) {
boolean isFitMode = doc.popFitMode();
if (! isFitMode) {
doc.zoomToFit();
}
}
return regionExtras;
}
private void setMode(Mode newMode) {
// Peel off any temporary Modes we may have pushed.
while (isControlModeActive() || isTransientPanModeActive()) {
overlay.popMode();
controlMode = null;
}
// See if that did the trick, to avoid duplicate pushes.
Mode oldMode = overlay.peekMode();
if (oldMode == newMode) {
return;
}
// If the current Mode is one of ours, pop it before pushing the next:
if (oldMode == regionMode ||
oldMode == cropMode ||
oldMode == rotateMode) {
// If we are in region mode make sure we exit edit mode
if (oldMode == regionMode && regionMode instanceof RegionOverlay)
((RegionOverlay) regionMode).finishEditingCurve();
overlay.popMode();
// The CropModes need setup and teardown:
if ((oldMode == cropMode) || (oldMode == rotateMode)) {
CropMode crop = (CropMode) oldMode;
crop.doCrop();
}
oldMode.exit();
}
if (newMode != null) {
overlay.pushMode(newMode);
newMode.enter();
}
// The CropModes need setup and teardown:
if ((newMode == cropMode) || (newMode == rotateMode)) {
CropMode crop = (CropMode) newMode;
crop.resetCrop();
}
// The CropModes need to be kept in sync with each other:
if (oldMode == cropMode) {
rotateMode.setCrop(cropMode.getCrop());
}
if (oldMode == rotateMode) {
cropMode.setCrop(rotateMode.getCrop());
}
}
// Get a default CropBounds for the CropMode overlay, in image
// coordinates.
private CropBounds getInitialCropBounds() {
double x = underlayBounds.getX();
double y = underlayBounds.getY();
double width = underlayBounds.getWidth();
double height = underlayBounds.getHeight();
Rectangle2D inset = new Rectangle2D.Double(
x, y, width, height
);
CropBounds crop = new CropBounds(inset);
try {
AffineTransform inverse = getOverlayTransform().createInverse();
crop = CropBounds.transform(inverse, crop);
return crop;
}
catch (NoninvertibleTransformException e) {
// Leave the crop overlay uninitialized.
}
return null;
}
// Don't rely on keyboard focus to switch the pan mode.
// Instead, postprocess unclaimed key events:
private void registerPanModeListener() {
KeyboardFocusManager focus =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
focus.addKeyEventPostProcessor(panModeKeyProcessor);
}
void dispose() {
KeyboardFocusManager focus =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
focus.removeKeyEventPostProcessor(panModeKeyProcessor);
}
}
| Correct initial crop size on HiDPI display
| lightcrafts/src/com/lightcrafts/ui/editor/ModeManager.java | Correct initial crop size on HiDPI display | <ide><path>ightcrafts/src/com/lightcrafts/ui/editor/ModeManager.java
<ide> /* Copyright (C) 2005-2011 Fabio Riccardi */
<add>/* Copyright (C) 2019- Masahiro Kitagawa */
<ide>
<ide> package com.lightcrafts.ui.editor;
<ide>
<ide> import com.lightcrafts.ui.operation.OpStackListener;
<ide> import com.lightcrafts.ui.operation.SelectableControl;
<ide> import com.lightcrafts.ui.region.RegionOverlay;
<add>import com.lightcrafts.utils.awt.geom.HiDpi;
<ide>
<ide> import javax.swing.*;
<ide> import java.awt.*;
<ide> import java.awt.event.KeyEvent;
<ide> import java.awt.geom.AffineTransform;
<ide> import java.awt.geom.NoninvertibleTransformException;
<del>import java.awt.geom.Rectangle2D;
<ide>
<ide> /**
<ide> * Handle switching among all the Modes. Lots of special mode-transition
<ide> // Get a default CropBounds for the CropMode overlay, in image
<ide> // coordinates.
<ide> private CropBounds getInitialCropBounds() {
<del> double x = underlayBounds.getX();
<del> double y = underlayBounds.getY();
<del> double width = underlayBounds.getWidth();
<del> double height = underlayBounds.getHeight();
<del> Rectangle2D inset = new Rectangle2D.Double(
<del> x, y, width, height
<del> );
<del> CropBounds crop = new CropBounds(inset);
<add> final int x = underlayBounds.x;
<add> final int y = underlayBounds.y;
<add> final int width = underlayBounds.width;
<add> final int height = underlayBounds.height;
<add> Rectangle inset = new Rectangle(x, y, width, height);
<add> CropBounds crop = new CropBounds(HiDpi.imageSpaceRectFrom(inset));
<ide> try {
<ide> AffineTransform inverse = getOverlayTransform().createInverse();
<ide> crop = CropBounds.transform(inverse, crop); |
|
JavaScript | mit | b13fe14ea18d0b36eafd1120170ad11f41af03c4 | 0 | javapark/jqgrid | /*
* jqFilter jQuery jqGrid filter addon.
* Copyright (c) 2011, Tony Tomov, [email protected]
* Dual licensed under the MIT and GPL licenses
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*
* The work is inspired from this Stefan Pirvu
* http://www.codeproject.com/KB/scripting/json-filtering.aspx
*
* The filter uses JSON entities to hold filter rules and groups. Here is an example of a filter:
{ "groupOp": "AND",
"groups" : [
{ "groupOp": "OR",
"rules": [
{ "field": "name", "op": "eq", "data": "England" },
{ "field": "id", "op": "le", "data": "5"}
]
}
],
"rules": [
{ "field": "name", "op": "eq", "data": "Romania" },
{ "field": "id", "op": "le", "data": "1"}
]
}
*/
;(function ($) {
$.fn.jqFilter = function( arg ) {
if (typeof arg == 'string') {
var fn = $.fn.jqFilter[arg];
if (!fn) {
throw ("jqFilter - No such method: " + arg);
}
var args = $.makeArray(arguments).slice(1);
return fn.apply(this,args);
}
var p = $.extend(true,{
filter: null,
columns: [],
onChange : null,
checkValues : null,
error: false,
errmsg : "",
errorcheck : true,
showQuery : true,
ops : [
{"name": "eq", "description": "equal", "operator":"="},
{"name": "ne", "description": "not equal", "operator":"<>"},
{"name": "bw", "description": "begins with", "operator":"LIKE"},
{"name": "bn", "description": "does not begin with", "operator":"NOT LIKE"},
{"name": "lt", "description": "less", "operator":"<"},
{"name": "le", "description": "less or equal","operator":"<="},
{"name": "gt", "description": "greater", "operator":">"},
{"name": "ge", "description": "greater or equal", "operator":">="},
{"name": "ew", "description": "ends with", "operator":"LIKE"},
{"name": "en", "description": "does not end with", "operator":"NOT LIKE"},
{"name": "cn", "description": "contains", "operator":"LIKE"},
{"name": "nc", "description": "does not contain", "operator":"NOT LIKE"},
{"name": "nu", "description": "is null", "operator":"IS NULL"},
{"name": "nn", "description": "is not null", "operator":"IS NOT NULL"},
{"name": "in", "description": "in", "operator":"IN"},
{"name": "ni", "description": "not in", "operator":"NOT IN"},
],
numopts : ['eq','ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'],
stropts : ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'in', 'ni'],
groupOps : ["AND", "OR"]
}, arg || {});
return this.each( function() {
if (this.filter) {return;}
this.p = p;
// setup filter in case if they is not defined
if (this.p.filter === null || this.p.filter === undefined) {
this.p.filter = {
groupOp: this.p.groupOps[0],
rules: [],
groups: []
}
}
this.p.initFilter = $.extend(true,{},this.p.filter);
// set default values for the columns if they are not set
var i, len = this.p.columns.length, cl;
if( !len ) {return;}
for(i=0; i < len; i++) {
cl = this.p.columns[i];
if( cl.stype ) {
// grid compatibility
cl.inputtype = cl.stype;
} else if(!cl.inputtype) {
cl.inputtype = 'text';
}
if( cl.sorttype ) {
// grid compatibility
cl.searchtype = cl.sorttype;
} else if (!cl.searchtype) {
cl.searchtype = 'string';
}
if(cl.hidden === undefined) {
// jqGrid compatibility
cl.hidden = false;
}
if(!cl.label) {
cl.label = cl.name;
}
if(!cl.hasOwnProperty('searchoptions')) {
cl.searchoptions = {};
}
if(!cl.hasOwnProperty('searchrules')) {
cl.searchrules = {};
}
}
if(this.p.showQuery) {
$(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;'><tbody><tr><td class='query'></td></tr></tbody></table>")
}
/*
*Perform checking.
*
*/
var checkData = function(val, colModelItem) {
var ret = [true,""];
if($.isFunction(colModelItem.searchrules)) {
ret = colModelItem.searchrules(val, colModelItem);
} else if($.jgrid && $.jgrid.checkValues) {
try {
ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
} catch (e) {}
}
if(ret && ret.length && ret[0] === false) {
p.error = !ret[0];
p.errmsg = ret[1];
}
};
this.onchange = function ( ){
// clear any error
this.p.error = false;
this.p.errmsg="";
return $.isFunction(this.p.onChange) ? this.p.onChange.call( this, this.p ) : false;
},
/*
* Redrow the filter every time when new field is added/deleted
* and field is changed
*/
this.reDraw = function() {
$("table.group:first",this).remove();
var t = this.createTableForGroup(p.filter, null);
$(this).append(t);
},
/*
* Creates a grouping data for the filter
* @param group - object
* @param parentgroup - object
*/
this.createTableForGroup = function(group, parentgroup) {
var that = this, i;
// this table will hold all the group (tables) and rules (rows)
var table = $("<table class='group ui-widget ui-widget-content' style='border:0px none;'><tbody>")
// create error message row
if(parentgroup == null) {
$(table).append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='left'></th></tr>");
}
var tr = $("<tr></tr>");
$(table).append(tr);
// this header will hold the group operator type and group action buttons for
// creating subgroup "+ {}", creating rule "+" or deleting the group "-"
var th = $("<th colspan='5' align='left'></th>");
tr.append(th);
// dropdown for: choosing group operator type
var groupOpSelect = $("<select class='opsel'></select>");
th.append(groupOpSelect);
// populate dropdown with all posible group operators: or, and
var str= "", selected;
for (i = 0; i < p.groupOps.length; i++) {
selected = group.groupOp == p.groupOps[i] ? "selected='selected'" :"";
str += "<option value='"+p.groupOps[i]+"'" + selected+">"+p.groupOps[i]+"</option>"
}
groupOpSelect
.append(str)
.bind('change',function() {
group.groupOp = $(groupOpSelect).val();
that.onchange(); // signals that the filter has changed
});
// button for adding a new subgroup
var inputAddSubgroup = $("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>");
inputAddSubgroup.bind('click',function() {
if (group.groups == undefined ) {
group.groups = [];
}
group.groups.push({
groupOp: p.groupOps[0],
rules: [],
groups: []
}); // adding a new group
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
th.append(inputAddSubgroup);
// button for adding a new rule
var inputAddRule = $("<input type='button' value='+' title='Add rule' class='add-rule'/>"), cm;
inputAddRule.bind('click',function() {
//if(!group) { group = {};}
if (group.rules == undefined)
group.rules = [];
for (i = 0; i < that.p.columns.length; i++) {
// but show only serchable and serchhidden = true fields
var searchable = (typeof that.p.columns[i].search === 'undefined') ? true: that.p.columns[i].search ,
hidden = (that.p.columns[i].hidden === true),
ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
if ((ignoreHiding && searchable) || (searchable && !hidden)) {
cm = that.p.columns[i];
break;
}
}
var opr;
if( cm.opts ) {opr = cm.opts;}
else if (cm.searchtype=='string') {opr = that.p.stropts;}
else {opr = that.p.numopts;}
group.rules.push({
field: cm.name,
op: opr[0],
data: ""
}); // adding a new rule
that.reDraw(); // the html has changed, force reDraw
// for the moment no change have been made to the rule, so
// this will not trigger onchange event
return false;
});
th.append(inputAddRule);
// button for delete the group
if (parentgroup != null) { // ignore the first group
var inputDeleteGroup = $("<input type='button' value='-' title='Delete group' class='delete-group'/>");
th.append(inputDeleteGroup);
inputDeleteGroup.bind('click',function() {
// remove group from parent
for (i = 0; i < parentgroup.groups.length; i++) {
if (parentgroup.groups[i] == group) {
parentgroup.groups.splice(i, 1);
break;
}
}
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
}
// append subgroup rows
if (group.groups != undefined) {
for (i = 0; i < group.groups.length; i++) {
var trHolderForSubgroup = $("<tr></tr>");
table.append(trHolderForSubgroup);
var tdFirstHolderForSubgroup = $("<td class='first'></td>");
trHolderForSubgroup.append(tdFirstHolderForSubgroup);
var tdMainHolderForSubgroup = $("<td colspan='4'></td>");
tdMainHolderForSubgroup.append(this.createTableForGroup(group.groups[i], group));
trHolderForSubgroup.append(tdMainHolderForSubgroup);
}
}
if(group.groupOp == undefined) {
group.groupOp = that.p.groupOps[0];
}
// append rules rows
if (group.rules != undefined) {
for (i = 0; i < group.rules.length; i++) {
table.append(
this.createTableRowForRule(group.rules[i], group)
);
}
}
return table;
},
/*
* Create the rule data for the filter
*/
this.createTableRowForRule = function(rule, group) {
// save current entity in a variable so that it could
// be referenced in anonimous method calls
var that=this, tr = $("<tr></tr>"),
//document.createElement("tr"),
// first column used for padding
//tdFirstHolderForRule = document.createElement("td"),
i, o, df, op, trpar, cm, str="", selected;
//tdFirstHolderForRule.setAttribute("class", "first");
tr.append("<td class='first'></td>");
// create field container
var ruleFieldTd = $("<td class='columns'></td>");
tr.append(ruleFieldTd);
// dropdown for: choosing field
var ruleFieldSelect = $("<select></select>");
ruleFieldTd.append(ruleFieldSelect);
ruleFieldSelect.bind('change',function() {
rule.field = $(ruleFieldSelect).val();
trpar = $(this).parents("tr:first");
for (i=0;i<that.p.columns.length;i++) {
if(that.p.columns[i].name == rule.field) {
cm = that.p.columns[i];
break;
}
}
if(!cm) {return false;}
var elm = $.jgrid.createEl(cm.inputtype,cm.searchoptions, "", true, that.p.ajaxSelectOptions);
$(elm).addClass("input-elm");
//that.createElement(rule, "");
if( cm.opts ) {op = cm.opts;}
else if (cm.searchtype=='string') {op = that.p.stropts;}
else {op = that.p.numopts;}
// operators
var s ="",so="";
for ( i = 0; i < that.p.ops.length; i++) {
if($.inArray(that.p.ops[i].name, op) !== -1) {
so = rule.op == that.p.ops[i].name ? "selected=selected" : "";
s += "<option value='"+that.p.ops[i].name+"' "+ so+">"+that.p.ops[i].description+"</option>";
}
}
$(".selectopts",trpar).empty().append( s );
// data
$(".data",trpar).empty().append( elm );
$(".input-elm",trpar).bind('change',function() {
rule.data = $(this).val();
if($.isArray(rule.data)) rule.data = rule.data.join(",")
that.onchange(); // signals that the filter has changed
});
rule.data = $(elm).val();
that.onchange(); // signals that the filter has changed
});
// populate drop down with user provided column definitions
var j=0;
for (i = 0; i < that.p.columns.length; i++) {
// but show only serchable and serchhidden = true fields
var searchable = (typeof that.p.columns[i].search === 'undefined') ? true: that.p.columns[i].search ,
hidden = (that.p.columns[i].hidden === true),
ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
if ((ignoreHiding && searchable) || (searchable && !hidden)) {
selected = "";
if(rule.field == that.p.columns[i].name) {
selected = "selected='selected'";
j=i;
}
str += "<option value='"+that.p.columns[i].name+"'" +selected+">"+that.p.columns[i].label+"</option>";
}
}
ruleFieldSelect.append( str )
// create operator container
var ruleOperatorTd = $("<td class='operators'></td>");
tr.append(ruleOperatorTd);
cm = p.columns[j];
// create it here so it can be referentiated in the onchange event
//var RD = that.createElement(rule, rule.data);
var ruleDataInput = $.jgrid.createEl(cm.inputtype,cm.searchoptions, rule.data, true, that.p.ajaxSelectOptions);
// dropdown for: choosing operator
var ruleOperatorSelect = $("<select class='selectopts'></select>");
ruleOperatorTd.append(ruleOperatorSelect);
ruleOperatorSelect.bind('change',function() {
rule.op = $(ruleOperatorSelect).val();
trpar = $(this).parents("tr:first");
var rd = $(".input-elm",trpar)[0];
if (rule.op == "nu" || rule.op == "nn") { // disable for operator "is null" and "is not null"
rule.data = "";
rd.value = "";
rd.setAttribute("readonly", "true");
rd.setAttribute("disabled", "true");
} else {
rd.removeAttribute("readonly");
rd.removeAttribute("disabled");
}
that.onchange(); // signals that the filter has changed
});
// populate drop down with all available operators
if( cm.opts ) {op = cm.opts;}
else if (cm.searchtype=='string') {op = p.stropts;}
else {op = that.p.numopts;}
str="";
for ( i = 0; i < that.p.ops.length; i++) {
if($.inArray(that.p.ops[i].name, op) !== -1) {
selected = rule.op == that.p.ops[i].name ? "selected='selected'" : "";
str += "<option value='"+that.p.ops[i].name+"'>"+that.p.ops[i].description+"</option>";
}
}
ruleOperatorSelect.append( str );
// create data container
var ruleDataTd = $("<td class='data'></td>");
tr.append(ruleDataTd);
// textbox for: data
// is created previously
//ruleDataInput.setAttribute("type", "text");
ruleDataTd.append(ruleDataInput);
$(ruleDataInput)
.addClass("input-elm")
.bind('change', function() {
rule.data = $(this).val();
if($.isArray(rule.data)) rule.data = rule.data.join(",");
that.onchange(); // signals that the filter has changed
});
// create action container
var ruleDeleteTd = $("<td></td>");
tr.append(ruleDeleteTd);
// create button for: delete rule
var ruleDeleteInput = $("<input type='button' value='-' title='Delete rule' class='delete-rule'/>");
ruleDeleteTd.append(ruleDeleteInput);
//$(ruleDeleteInput).html("").height(20).width(30).button({icons: { primary: "ui-icon-minus", text:false}});
ruleDeleteInput.bind('click',function() {
// remove rule from group
for (i = 0; i < group.rules.length; i++) {
if (group.rules[i] == rule) {
group.rules.splice(i, 1);
break;
}
}
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
return tr;
},
this.getStringForGroup = function(group) {
var s = "(", index;
if (group.groups != undefined) {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1)
s += " " + group.groupOp + " ";
try {
s += this.getStringForGroup(group.groups[index]);
} catch (e) {alert(e);}
}
}
if (group.rules != undefined) {
try{
for (index = 0; index < group.rules.length; index++) {
if (s.length > 1)
s += " " + group.groupOp + " ";
s += this.getStringForRule(group.rules[index]);
}
} catch (e) {alert(e);}
}
s += ")";
if (s == "()")
return ""; // ignore groups that don't have rules
else
return s;
},
this.getStringForRule = function(rule) {
var opUF = "",opC="", i, cm, ret, val,
numtypes = ['int', 'integer', 'float', 'number', 'currency']; // jqGrid
for (i = 0; i < this.p.ops.length; i++) {
if (this.p.ops[i].name == rule.op) {
opUF = this.p.ops[i].operator;
opC = this.p.ops[i].name;
break;
}
}
for (i=0; i<this.p.columns.length; i++) {
if(this.p.columns[i].name == rule.field) {
cm = this.p.columns[i];
break;
}
}
val = rule.data;
if(opC == 'bw' || opC == 'bn') val = val+"%";
if(opC == 'ew' || opC == 'en') val = "%"+val;
if(opC == 'cn' || opC == 'nc') val = "%"+val+"%";
if(opC == 'in' || opC == 'ni') val = " ("+val+")";
if(p.errorcheck) {checkData(rule.data, cm);}
if($.inArray(cm.searchtype, numtypes) !== -1 || opC=='nn' || opC=='nu') ret = rule.field + " " + opUF + " " + val + "";
else ret = rule.field + " " + opUF + " \"" + val + "\"";
return ret;
},
this.resetFilter = function () {
this.p.filter = $.extend(true,{},this.p.initFilter);
this.reDraw();
},
this.hideError = function() {
$("th.ui-state-error", this).html("");
$("tr.error", this).hide();
},
this.showError = function() {
$("th.ui-state-error", this).html(this.p.errmsg);
$("tr.error", this).show();
},
this.toUserFriendlyString = function() {
return this.getStringForGroup(p.filter);
},
this.toString = function() {
// this will obtain a string that can be used to match an item.
function getStringForGroup(group) {
var s = "(", index;
if (group.groups != undefined) {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1) {
if (group.groupOp == "OR")
s += " || ";
else
s += " && ";
}
s += getStringForGroup(group.groups[index]);
}
}
if (group.rules != undefined) {
for (index = 0; index < group.rules.length; index++) {
if (s.length > 1) {
if (group.groupOp == "OR")
s += " || ";
else
s += " && ";
}
s += getStringForRule(group.rules[index]);
}
}
s += ")";
if (s == "()")
return ""; // ignore groups that don't have rules
else
return s;
}
function getStringForRule(rule) {
if(p.errorcheck) {
var i, cm;
for (i=0; i<p.columns.length; i++) {
if(p.columns[i].name == rule.field) {
cm = p.columns[i];
break;
}
}
if(cm) {checkData(rule.data, cm);}
}
return rule.op + "(item." + rule.field + ",'" + rule.data + "')";
}
return getStringForGroup(this.p.filter);
};
// Here we init the filter
this.reDraw();
if(this.p.showQuery) {
this.onchange();
}
// mark is as created so that it will not be created twice on this element
this.filter = true;
});
};
$.extend($.fn.jqFilter,{
/*
* Return SQL like string. Can be used directly
*/
toSQLString : function()
{
var s ="";
this.each(function(){
s = this.toUserFriendlyString();
});
return s;
},
/*
* Return filter data as object.
*/
filterData : function()
{
var s;
this.each(function(){
s = this.p.filter;
});
return s;
},
getParameter : function (param) {
if(param !== undefined) {
if (this.p.hasOwnProperty(param) )
return this.p[param];
}
return this.p;
},
resetFilter: function() {
return this.each(function(){
this.resetFilter();
});
}
});
})(jQuery);
| js/grid.filter.js | /*
* jqFilter jQuery jqGrid filter addon.
* Copyright (c) 2011, Tony Tomov, [email protected]
* Dual licensed under the MIT and GPL licenses
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*
* The work is inspired from this Stefan Pirvu
* http://www.codeproject.com/KB/scripting/json-filtering.aspx
*
* The filter uses JSON entities to hold filter rules and groups. Here is an example of a filter:
{ "groupOp": "AND",
"groups" : [
{ "groupOp": "OR",
"rules": [
{ "field": "name", "op": "eq", "data": "England" },
{ "field": "id", "op": "le", "data": "5"}
]
}
],
"rules": [
{ "field": "name", "op": "eq", "data": "Romania" },
{ "field": "id", "op": "le", "data": "1"}
]
}
*/
;(function ($) {
$.fn.jqFilter = function( arg ) {
if (typeof arg == 'string') {
var fn = $.fn.jqFilter[arg];
if (!fn) {
throw ("jqFilter - No such method: " + arg);
}
var args = $.makeArray(arguments).slice(1);
return fn.apply(this,args);
}
var p = $.extend(true,{
filter: null,
columns: [],
onChange : null,
checkValues : null,
error: false,
errmsg : "",
errorcheck : true,
showQuery : true,
ops : [
{"name": "eq", "description": "equal", "operator":"="},
{"name": "ne", "description": "not equal", "operator":"<>"},
{"name": "bw", "description": "begins with", "operator":"LIKE"},
{"name": "bn", "description": "does not begin with", "operator":"NOT LIKE"},
{"name": "lt", "description": "less", "operator":"<"},
{"name": "le", "description": "less or equal","operator":"<="},
{"name": "gt", "description": "greater", "operator":">"},
{"name": "ge", "description": "greater or equal", "operator":">="},
{"name": "ew", "description": "ends with", "operator":"LIKE"},
{"name": "en", "description": "does not end with", "operator":"NOT LIKE"},
{"name": "cn", "description": "contains", "operator":"LIKE"},
{"name": "nc", "description": "does not contain", "operator":"NOT LIKE"},
{"name": "nu", "description": "is null", "operator":"IS NULL"},
{"name": "nn", "description": "is not null", "operator":"IS NOT NULL"},
{"name": "in", "description": "in", "operator":"IN"},
{"name": "ni", "description": "not in", "operator":"NOT IN"},
],
numopts : ['eq','ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'],
stropts : ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn', 'nc', 'nu', 'nn', 'in', 'ni'],
groupOps : ["AND", "OR"]
}, arg || {});
return this.each( function() {
if (this.filter) {return;}
this.p = p;
// setup filter in case if they is not defined
if (this.p.filter === null || this.p.filter === undefined) {
this.p.filter = {
groupOp: this.p.groupOps[0],
rules: [],
groups: []
}
}
this.p.initFilter = $.extend(true,{},this.p.filter);
// set default values for the columns if they are not set
var i, len = this.p.columns.length, cl;
if( !len ) {return;}
for(i=0; i < len; i++) {
cl = this.p.columns[i];
if( cl.stype ) {
// grid compatibility
cl.inputtype = cl.stype;
} else if(!cl.inputtype) {
cl.inputtype = 'text';
}
if( cl.sorttype ) {
// grid compatibility
cl.searchtype = cl.sorttype;
} else if (!cl.searchtype) {
cl.searchtype = 'string';
}
if(cl.hidden === undefined) {
// jqGrid compatibility
cl.hidden = false;
}
if(!cl.label) {
cl.label = cl.name;
}
if(!cl.hasOwnProperty('searchoptions')) {
cl.searchoptions = {};
}
if(!cl.hasOwnProperty('searchrules')) {
cl.searchrules = {};
}
}
if(this.p.showQuery) {
$(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;'><tbody><tr><td class='query'></td></tr></tbody></table>")
}
/*
*Perform checking.
*
*/
var checkData = function(val, colModelItem) {
var ret = [true,""];
if($.isFunction(colModelItem.searchrules)) {
ret = colModelItem.searchrules(val, colModelItem);
} else if($.jgrid && $.jgrid.checkValues) {
try {
ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
} catch (e) {}
}
if(ret && ret.length && ret[0] === false) {
p.error = !ret[0];
p.errmsg = ret[1];
}
};
this.onchange = function ( ){
// clear any error
this.p.error = false;
this.p.errmsg="";
return $.isFunction(this.p.onChange) ? this.p.onChange.call( this, this.p ) : false;
},
/*
* Redrow the filter every time when new field is added/deleted
* and field is changed
*/
this.reDraw = function() {
$("table.group:first",this).remove();
var t = this.createTableForGroup(p.filter, null);
$(this).append(t);
},
/*
* Creates a grouping data for the filter
* @param group - object
* @param parentgroup - object
*/
this.createTableForGroup = function(group, parentgroup) {
var that = this, i;
// this table will hold all the group (tables) and rules (rows)
var table = $("<table class='group ui-widget ui-widget-content' style='border:0px none;'><tbody>")
// create error message row
if(parentgroup == null) {
$(table).append("<tr class='error' style='display:none;'><th colspan='5' class='ui-state-error' align='left'></th></tr>");
}
var tr = $("<tr></tr>");
$(table).append(tr);
// this header will hold the group operator type and group action buttons for
// creating subgroup "+ {}", creating rule "+" or deleting the group "-"
var th = $("<th colspan='5' align='left'></th>");
tr.append(th);
// dropdown for: choosing group operator type
var groupOpSelect = $("<select class='opsel'></select>");
th.append(groupOpSelect);
// populate dropdown with all posible group operators: or, and
var str= "", selected;
for (i = 0; i < p.groupOps.length; i++) {
selected = group.groupOp == p.groupOps[i] ? "selected='selected'" :"";
str += "<option value='"+p.groupOps[i]+"'" + selected+">"+p.groupOps[i]+"</option>"
}
groupOpSelect
.append(str)
.bind('change',function() {
group.groupOp = $(groupOpSelect).val();
that.onchange(); // signals that the filter has changed
});
// button for adding a new subgroup
var inputAddSubgroup = $("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>");
inputAddSubgroup.bind('click',function() {
if (group.groups == undefined ) {
group.groups = [];
}
group.groups.push({
groupOp: p.groupOps[0],
rules: [],
groups: []
}); // adding a new group
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
th.append(inputAddSubgroup);
// button for adding a new rule
var inputAddRule = $("<input type='button' value='+' title='Add rule' class='add-rule'/>");
inputAddRule.bind('click',function() {
//if(!group) { group = {};}
if (group.rules == undefined)
group.rules = [];
group.rules.push({
field: that.p.columns[0].name,
op: that.p.ops[0].name,
data: ""
}); // adding a new rule
that.reDraw(); // the html has changed, force reDraw
// for the moment no change have been made to the rule, so
// this will not trigger onchange event
return false;
});
th.append(inputAddRule);
// button for delete the group
if (parentgroup != null) { // ignore the first group
var inputDeleteGroup = $("<input type='button' value='-' title='Delete group' class='delete-group'/>");
th.append(inputDeleteGroup);
inputDeleteGroup.bind('click',function() {
// remove group from parent
for (i = 0; i < parentgroup.groups.length; i++) {
if (parentgroup.groups[i] == group) {
parentgroup.groups.splice(i, 1);
break;
}
}
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
}
// append subgroup rows
if (group.groups != undefined) {
for (i = 0; i < group.groups.length; i++) {
var trHolderForSubgroup = $("<tr></tr>");
table.append(trHolderForSubgroup);
var tdFirstHolderForSubgroup = $("<td class='first'></td>");
trHolderForSubgroup.append(tdFirstHolderForSubgroup);
var tdMainHolderForSubgroup = $("<td colspan='4'></td>");
tdMainHolderForSubgroup.append(this.createTableForGroup(group.groups[i], group));
trHolderForSubgroup.append(tdMainHolderForSubgroup);
}
}
if(group.groupOp == undefined) {
group.groupOp = that.p.groupOps[0];
}
// append rules rows
if (group.rules != undefined) {
for (i = 0; i < group.rules.length; i++) {
table.append(
this.createTableRowForRule(group.rules[i], group)
);
}
}
return table;
},
/*
* Create the rule data for the filter
*/
this.createTableRowForRule = function(rule, group) {
// save current entity in a variable so that it could
// be referenced in anonimous method calls
var that=this, tr = $("<tr></tr>"),
//document.createElement("tr"),
// first column used for padding
//tdFirstHolderForRule = document.createElement("td"),
i, o, df, op, trpar, cm, str="", selected;
//tdFirstHolderForRule.setAttribute("class", "first");
tr.append("<td class='first'></td>");
// create field container
var ruleFieldTd = $("<td class='columns'></td>");
tr.append(ruleFieldTd);
// dropdown for: choosing field
var ruleFieldSelect = $("<select></select>");
ruleFieldTd.append(ruleFieldSelect);
ruleFieldSelect.bind('change',function() {
rule.field = $(ruleFieldSelect).val();
trpar = $(this).parents("tr:first");
for (i=0;i<that.p.columns.length;i++) {
if(that.p.columns[i].name == rule.field) {
cm = that.p.columns[i];
break;
}
}
if(!cm) {return false;}
var elm = $.jgrid.createEl(cm.inputtype,cm.searchoptions, "", true, that.p.ajaxSelectOptions);
$(elm).addClass("input-elm");
//that.createElement(rule, "");
if( cm.opts ) {op = cm.opts;}
else if (cm.searchtype=='string') {op = p.stropts;}
else {op = that.p.numopts;}
// operators
var s ="",so="";
for ( i = 0; i < that.p.ops.length; i++) {
if($.inArray(that.p.ops[i].name, op) !== -1) {
so = rule.op == that.p.ops[i].name ? "selected=selected" : "";
s += "<option value='"+that.p.ops[i].name+"' "+ so+">"+that.p.ops[i].description+"</option>";
}
}
$(".selectopts",trpar).empty().append( s );
// data
$(".data",trpar).empty().append( elm );
$(".input-elm",trpar).bind('change',function() {
rule.data = $(this).val();
if($.isArray(rule.data)) rule.data = rule.data.join(",")
that.onchange(); // signals that the filter has changed
});
rule.data = $(elm).val();
that.onchange(); // signals that the filter has changed
});
// populate drop down with user provided column definitions
var j=0;
for (i = 0; i < that.p.columns.length; i++) {
// but show only serchable and serchhidden = true fields
var searchable = (typeof that.p.columns[i].search === 'undefined') ? true: that.p.columns[i].search ,
hidden = (that.p.columns[i].hidden === true),
ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
if ((ignoreHiding && searchable) || (searchable && !hidden)) {
selected = "";
if(rule.field == that.p.columns[i].name) {
selected = "selected='selected'";
j=i;
}
str += "<option value='"+that.p.columns[i].name+"'" +selected+">"+that.p.columns[i].label+"</option>";
}
}
ruleFieldSelect.append( str )
// create operator container
var ruleOperatorTd = $("<td class='operators'></td>");
tr.append(ruleOperatorTd);
cm = p.columns[j];
// create it here so it can be referentiated in the onchange event
//var RD = that.createElement(rule, rule.data);
var ruleDataInput = $.jgrid.createEl(cm.inputtype,cm.searchoptions, rule.data, true, that.p.ajaxSelectOptions);
// dropdown for: choosing operator
var ruleOperatorSelect = $("<select class='selectopts'></select>");
ruleOperatorTd.append(ruleOperatorSelect);
ruleOperatorSelect.bind('change',function() {
rule.op = $(ruleOperatorSelect).val();
trpar = $(this).parents("tr:first");
var rd = $(".input-elm",trpar)[0];
if (rule.op == "nu" || rule.op == "nn") { // disable for operator "is null" and "is not null"
rule.data = "";
rd.value = "";
rd.setAttribute("readonly", "true");
rd.setAttribute("disabled", "true");
} else {
rd.removeAttribute("readonly");
rd.removeAttribute("disabled");
}
that.onchange(); // signals that the filter has changed
});
// populate drop down with all available operators
if( cm.opts ) {op = cm.opts;}
else if (cm.searchtype=='string') {op = p.stropts;}
else {op = that.p.numopts;}
str="";
for ( i = 0; i < that.p.ops.length; i++) {
if($.inArray(that.p.ops[i].name, op) !== -1) {
selected = rule.op == that.p.ops[i].name ? "selected='selected'" : "";
str += "<option value='"+that.p.ops[i].name+"'>"+that.p.ops[i].description+"</option>";
}
}
ruleOperatorSelect.append( str );
// create data container
var ruleDataTd = $("<td class='data'></td>");
tr.append(ruleDataTd);
// textbox for: data
// is created previously
//ruleDataInput.setAttribute("type", "text");
ruleDataTd.append(ruleDataInput);
$(ruleDataInput)
.addClass("input-elm")
.bind('change', function() {
rule.data = $(this).val();
if($.isArray(rule.data)) rule.data = rule.data.join(",");
that.onchange(); // signals that the filter has changed
});
// create action container
var ruleDeleteTd = $("<td></td>");
tr.append(ruleDeleteTd);
// create button for: delete rule
var ruleDeleteInput = $("<input type='button' value='-' title='Delete rule' class='delete-rule'/>");
ruleDeleteTd.append(ruleDeleteInput);
//$(ruleDeleteInput).html("").height(20).width(30).button({icons: { primary: "ui-icon-minus", text:false}});
ruleDeleteInput.bind('click',function() {
// remove rule from group
for (i = 0; i < group.rules.length; i++) {
if (group.rules[i] == rule) {
group.rules.splice(i, 1);
break;
}
}
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
return tr;
},
this.getStringForGroup = function(group) {
var s = "(", index;
if (group.groups != undefined) {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1)
s += " " + group.groupOp + " ";
try {
s += this.getStringForGroup(group.groups[index]);
} catch (e) {alert(e);}
}
}
if (group.rules != undefined) {
try{
for (index = 0; index < group.rules.length; index++) {
if (s.length > 1)
s += " " + group.groupOp + " ";
s += this.getStringForRule(group.rules[index]);
}
} catch (e) {alert(e);}
}
s += ")";
if (s == "()")
return ""; // ignore groups that don't have rules
else
return s;
},
this.getStringForRule = function(rule) {
var opUF = "",opC="", i, cm, ret, val,
numtypes = ['int', 'integer', 'float', 'number', 'currency']; // jqGrid
for (i = 0; i < this.p.ops.length; i++) {
if (this.p.ops[i].name == rule.op) {
opUF = this.p.ops[i].operator;
opC = this.p.ops[i].name;
break;
}
}
for (i=0; i<this.p.columns.length; i++) {
if(this.p.columns[i].name == rule.field) {
cm = this.p.columns[i];
break;
}
}
val = rule.data;
if(opC == 'bw' || opC == 'bn') val = val+"%";
if(opC == 'ew' || opC == 'en') val = "%"+val;
if(opC == 'cn' || opC == 'nc') val = "%"+val+"%";
if(opC == 'in' || opC == 'ni') val = " ("+val+")";
if(p.errorcheck) { checkData(rule.data, cm); }
if($.inArray(cm.searchtype, numtypes) !== -1 || opC=='nn' || opC=='nu') ret = rule.field + " " + opUF + " " + val + "";
else ret = rule.field + " " + opUF + " \"" + val + "\"";
return ret;
},
this.resetFilter = function () {
this.p.filter = $.extend(true,{},this.p.initFilter);
this.reDraw();
}
this.hideError = function() {
$("th.ui-state-error", this).html("");
$("tr.error", this).hide();
},
this.showError = function() {
$("th.ui-state-error", this).html(this.p.errmsg);
$("tr.error", this).show();
},
this.toUserFriendlyString = function() {
return this.getStringForGroup(p.filter);
},
this.toString = function() {
// this will obtain a string that can be used to match an item.
function getStringForGroup(group) {
var s = "(", index;
if (group.groups != undefined) {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1) {
if (group.groupOp == "OR")
s += " || ";
else
s += " && ";
}
s += getStringForGroup(group.groups[index]);
}
}
if (group.rules != undefined) {
for (index = 0; index < group.rules.length; index++) {
if (s.length > 1) {
if (group.groupOp == "OR")
s += " || ";
else
s += " && ";
}
s += getStringForRule(group.rules[index]);
}
}
s += ")";
if (s == "()")
return ""; // ignore groups that don't have rules
else
return s;
}
function getStringForRule(rule) {
if(p.errorcheck) {
var i, cm;
for (i=0; i<p.columns.length; i++) {
if(p.columns[i].name == rule.field) {
cm = p.columns[i];
break;
}
}
if(cm) { checkData(rule.data, cm); }
}
return rule.op + "(item." + rule.field + ",'" + rule.data + "')";
}
return getStringForGroup(this.p.filter);
};
// Here we init the filter
this.reDraw();
if(this.p.showQuery) {
this.onchange();
}
// mark is as created so that it will not be created twice on this element
this.filter = true;
});
};
$.extend($.fn.jqFilter,{
/*
* Return SQL like string. Can be used directly
*/
toSQLString : function()
{
var s ="";
this.each(function(){
s = this.toUserFriendlyString();
});
return s;
},
/*
* Return filter data as object.
*/
filterData : function()
{
var s;
this.each(function(){
s = this.p.filter;
});
return s;
},
getParameter : function (param) {
if(param !== undefined) {
if (this.p.hasOwnProperty(param) )
return this.p[param];
}
return this.p;
}
});
})(jQuery);
| Add a method resetFilter. Fix when adding a new group - we add the first enabled field.
| js/grid.filter.js | Add a method resetFilter. Fix when adding a new group - we add the first enabled field. | <ide><path>s/grid.filter.js
<ide> th.append(inputAddSubgroup);
<ide>
<ide> // button for adding a new rule
<del> var inputAddRule = $("<input type='button' value='+' title='Add rule' class='add-rule'/>");
<add> var inputAddRule = $("<input type='button' value='+' title='Add rule' class='add-rule'/>"), cm;
<ide> inputAddRule.bind('click',function() {
<ide> //if(!group) { group = {};}
<ide> if (group.rules == undefined)
<ide> group.rules = [];
<add> for (i = 0; i < that.p.columns.length; i++) {
<add> // but show only serchable and serchhidden = true fields
<add> var searchable = (typeof that.p.columns[i].search === 'undefined') ? true: that.p.columns[i].search ,
<add> hidden = (that.p.columns[i].hidden === true),
<add> ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
<add> if ((ignoreHiding && searchable) || (searchable && !hidden)) {
<add> cm = that.p.columns[i];
<add> break;
<add> }
<add> }
<add> var opr;
<add> if( cm.opts ) {opr = cm.opts;}
<add> else if (cm.searchtype=='string') {opr = that.p.stropts;}
<add> else {opr = that.p.numopts;}
<ide>
<ide> group.rules.push({
<del> field: that.p.columns[0].name,
<del> op: that.p.ops[0].name,
<add> field: cm.name,
<add> op: opr[0],
<ide> data: ""
<ide> }); // adding a new rule
<ide>
<ide> //that.createElement(rule, "");
<ide>
<ide> if( cm.opts ) {op = cm.opts;}
<del> else if (cm.searchtype=='string') {op = p.stropts;}
<add> else if (cm.searchtype=='string') {op = that.p.stropts;}
<ide> else {op = that.p.numopts;}
<ide> // operators
<ide> var s ="",so="";
<ide> if(opC == 'ew' || opC == 'en') val = "%"+val;
<ide> if(opC == 'cn' || opC == 'nc') val = "%"+val+"%";
<ide> if(opC == 'in' || opC == 'ni') val = " ("+val+")";
<del> if(p.errorcheck) { checkData(rule.data, cm); }
<add> if(p.errorcheck) {checkData(rule.data, cm);}
<ide> if($.inArray(cm.searchtype, numtypes) !== -1 || opC=='nn' || opC=='nu') ret = rule.field + " " + opUF + " " + val + "";
<ide> else ret = rule.field + " " + opUF + " \"" + val + "\"";
<ide> return ret;
<ide> this.resetFilter = function () {
<ide> this.p.filter = $.extend(true,{},this.p.initFilter);
<ide> this.reDraw();
<del> }
<add> },
<ide> this.hideError = function() {
<ide> $("th.ui-state-error", this).html("");
<ide> $("tr.error", this).hide();
<ide> break;
<ide> }
<ide> }
<del> if(cm) { checkData(rule.data, cm); }
<add> if(cm) {checkData(rule.data, cm);}
<ide> }
<ide> return rule.op + "(item." + rule.field + ",'" + rule.data + "')";
<ide> }
<ide> return this.p[param];
<ide> }
<ide> return this.p;
<add> },
<add> resetFilter: function() {
<add> return this.each(function(){
<add> this.resetFilter();
<add> });
<ide> }
<ide>
<ide> }); |
|
Java | mit | 645c0973be1de7c678d4b86658bf1af4e9f0a44e | 0 | nking/curvature-scale-space-corners-and-transformations,nking/curvature-scale-space-corners-and-transformations | package algorithms.imageProcessing;
import java.util.logging.Logger;
/**
* NOTE: need to edit these comments. for this color version of canny,
* using the "L" and "C" images of LCH CIELUV color space.
* May also add use of "H"...still experimenting.
*
*
*
* The CannyEdge filter is an algorithm to operate on an image to
* replace objects with their edges.
*
* The class began by following the general advice given in
* "Performance Analysis of Adaptive Canny Edge Detector
* Using Bilateral Filter" by Rashmi, Kumar, Jaiswal, and Saxena,
* but made modifications afterwards and added a "C" gradient of colorspace
* LCH to the greyscale gradient.
*
* Their paper has the following qualities:
*<pre>
* -- instead of a Gaussian filter, uses a bilateral filter
* -- an adaptive threshold algorithm is used in the 2 layer filter
*
</pre>
* This class uses 2 one dimensional binomial filters for smoothing.
*
* <pre>
* Usage:
* Note, by default, a histogram equalization is not performed.
* By default, the number of neighbor histogram levels is 1 in the
* adaptive thresholding.
* To use the filter in adaptive mode, use filter.overrideDefaultNumberOfLevels
* and a number 16 of higher is recommended.
*
* To see a difference in the adaptive approach, run this class on the test
* image susan-in.gif using filter.overrideToUseAdaptiveThreshold()
*
* To adjust the filter to remove lower intensity edges, use
* filter.setOtsuScaleFactor. The default factor is 0.45
* (determined w/ a checkerboard image).
* For the Lena test image for example, one might prefer only the brightest
* edges, so use a higher setting than the default.
*
* Not ready for use yet...
*
* @author nichole
*/
public class CannyEdgeColorAdaptive {
/** the factor that the low threshold is below the high threshold in the
2 layer filter.
*/
protected float factorBelowHighThreshold = 2.f;
private EdgeFilterProducts filterProducts = null;
private boolean performNonMaxSuppr = true;
private boolean debug = false;
private boolean restoreJunctions = true;
/**
* the sigma from the blur combined with the sigma present in the gradient
* are present in this variable by the end of processing.
* The variable is used to interpret resolution of theta angles, for example.
* The sigmas are combined using: sigma^2 = sigma_1^2 + sigma_2^2.
* The FWHM of a gaussian is approx 2.35 * sigma.
* (HWZI is about 5 * sigma, by the way).
* So, for the default use of the filter, a sigma of 1 combined with sqrt(1)/2
* results in a minimum resolution of 3 pixels, hence about 19 degrees.
*/
private double approxProcessedSigma = 0;
private boolean useAdaptiveThreshold = false;
private boolean useAdaptive2Layer = true;
private float otsuScaleFactor = 0.75f;//0.65f;
protected Logger log = Logger.getLogger(this.getClass().getName());
protected boolean useLineThinner = true;
public CannyEdgeColorAdaptive() {
}
public void setToDebug() {
debug = true;
}
public void overrideToNotUseLineThinner() {
useLineThinner = false;
}
/**
* to enable more complete contours, use this to restore pixels that were
* removed during non-maximum suppression that disconnected edges and
* have values above the low threshold of the 2 layer adaptive filter.
*/
public void setToNotRestoreJunctions() {
restoreJunctions = false;
}
/**
* by default this is 0.45.
* @param factor
*/
public void setOtsuScaleFactor(float factor) {
otsuScaleFactor = factor;
}
public void setToNotUseNonMaximumSuppression() {
performNonMaxSuppr = false;
}
/**
* set this to use the adaptive threshold in the 2 layer
* filter. it adjusts the threshold by regions of size
* 15. Note that if the image has alot of noise, this
* will include alot of noise in the result.
*/
public void overrideToUseAdaptiveThreshold() {
useAdaptiveThreshold = true;
}
public void setToUseSingleThresholdIn2LayerFilter() {
useAdaptive2Layer = false;
}
/**
* override the default factor of low threshold below high threshold, which
* is 2.
* @param factor
*/
public void override2LayerFactorBelowHighThreshold(float factor) {
factorBelowHighThreshold = factor;
}
/**
* apply the filter. note that unlike the other canny filters in this
* project, the input is not modified.
* @param input
*/
public void applyFilter(Image input) {
if (input.getWidth() < 3 || input.getHeight() < 3) {
throw new IllegalArgumentException("images should be >= 3x3 in size");
}
ImageProcessor imageProcessor = new ImageProcessor();
GreyscaleImage[] lch = imageProcessor.createLCHForLUV(input);
CannyEdgeFilterAdaptive cannyL = new CannyEdgeFilterAdaptive();
CannyEdgeFilterAdaptive cannyC = new CannyEdgeFilterAdaptive();
if (!useLineThinner) {
cannyL.overrideToNotUseLineThinner();
cannyC.overrideToNotUseLineThinner();
}
if (useAdaptiveThreshold) {
cannyL.overrideToUseAdaptiveThreshold();
cannyC.overrideToUseAdaptiveThreshold();
}
cannyL.override2LayerFactorBelowHighThreshold(factorBelowHighThreshold);
cannyC.override2LayerFactorBelowHighThreshold(factorBelowHighThreshold);
if (!performNonMaxSuppr) {
cannyL.setToNotUseNonMaximumSuppression();
cannyC.setToNotUseNonMaximumSuppression();
}
if (!restoreJunctions) {
cannyL.setToNotRestoreJunctions();
cannyC.setToNotRestoreJunctions();
}
if (!useAdaptive2Layer) {
cannyL.setToUseSingleThresholdIn2LayerFilter();
cannyC.setToUseSingleThresholdIn2LayerFilter();
}
if (!useLineThinner) {
cannyL.overrideToNotUseLineThinner();
cannyC.overrideToNotUseLineThinner();
}
if (debug) {
cannyL.setToDebug();
cannyC.setToDebug();
}
cannyL.setOtsuScaleFactor(otsuScaleFactor);
cannyC.setOtsuScaleFactor(otsuScaleFactor);
//cannyC.setOtsuScaleFactor(1.0f); // less sensitive and less noisey
cannyL.applyFilter(lch[0]);
cannyC.applyFilter(lch[1]);
EdgeFilterProducts edgeProductsL = cannyL.getFilterProducts();
EdgeFilterProducts edgeProductsC = cannyC.getFilterProducts();
// DEBUG: temporary look at recalculating the L thresholds
// to filter out scaled C values to reduce noise.
// assuming not adaptive for now.
int tLowL = edgeProductsL.getGradientXY().min();
float lFactor = 255.f/(float)edgeProductsL.getGradientXY().max();
float cFactor = 255.f/(float)edgeProductsC.getGradientXY().max();
GreyscaleImage combXY = edgeProductsL.getGradientXY()
.createWithDimensions();
GreyscaleImage combX = edgeProductsL.getGradientX()
.createWithDimensions();
GreyscaleImage combY = edgeProductsL.getGradientY()
.createWithDimensions();
int n = combXY.getNPixels();
int v0, v1, v, vx, vy;
for (int i = 0; i < n; ++i) {
v0 = edgeProductsL.getGradientXY().getValue(i);
v1 = edgeProductsC.getGradientXY().getValue(i);
v0 = Math.round(v0 * lFactor);
if (v0 > 255) {
v0 = 255;
}
v1 = Math.round(v1 * cFactor);
if (v1 > 255) {
v1 = 255;
}
if (cFactor > 1) {
if (v1 < tLowL) {
v1 = 0;
}
}
// choosing the largest of both instead of avg
if (v0 > v1) {
v = v0;
vx = edgeProductsL.getGradientX().getValue(i);
vy = edgeProductsL.getGradientY().getValue(i);
} else {
v = v1;
vx = edgeProductsC.getGradientX().getValue(i);
vy = edgeProductsC.getGradientY().getValue(i);
}
combXY.setValue(i, v);
combX.setValue(i, vx);
combY.setValue(i, vy);
}
GreyscaleImage combTheta =
imageProcessor.computeTheta180(combX, combY);
EdgeFilterProducts efp = new EdgeFilterProducts();
efp.setGradientX(combX);
efp.setGradientY(combY);
efp.setGradientXY(combXY);
efp.setTheta(combTheta);
this.filterProducts = efp;
}
/**
* get the filter products for gradient and orientation.
* note that the orientation image has values between 0 and 180.
* @return the filterProducts
*/
public EdgeFilterProducts getFilterProducts() {
return filterProducts;
}
}
| src/algorithms/imageProcessing/CannyEdgeColorAdaptive.java | package algorithms.imageProcessing;
import algorithms.misc.Misc;
import algorithms.misc.MiscDebug;
import algorithms.misc.MiscMath;
import java.util.logging.Logger;
import java.util.HashSet;
import algorithms.util.PairInt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* NOTE: need to edit these comments. for this color version of canny,
* using the "L" and "C" images of LCH CIELUV color space.
* May also add use of "H"...still experimenting.
*
*
*
* The CannyEdge filter is an algorithm to operate on an image to
* replace objects with their edges.
*
* The class began by following the general advice given in
* "Performance Analysis of Adaptive Canny Edge Detector
* Using Bilateral Filter" by Rashmi, Kumar, Jaiswal, and Saxena,
* but made modifications afterwards and added a "C" gradient of colorspace
* LCH to the greyscale gradient.
*
* Their paper has the following qualities:
*<pre>
* -- instead of a Gaussian filter, uses a bilateral filter
* -- an adaptive threshold algorithm is used in the 2 layer filter
*
</pre>
* This class uses 2 one dimensional binomial filters for smoothing.
*
* <pre>
* Usage:
* Note, by default, a histogram equalization is not performed.
* By default, the number of neighbor histogram levels is 1 in the
* adaptive thresholding.
* To use the filter in adaptive mode, use filter.overrideDefaultNumberOfLevels
* and a number 16 of higher is recommended.
*
* To see a difference in the adaptive approach, run this class on the test
* image susan-in.gif using filter.overrideToUseAdaptiveThreshold()
*
* To adjust the filter to remove lower intensity edges, use
* filter.setOtsuScaleFactor. The default factor is 0.45
* (determined w/ a checkerboard image).
* For the Lena test image for example, one might prefer only the brightest
* edges, so use a higher setting than the default.
*
* Not ready for use yet...
*
* @author nichole
*/
public class CannyEdgeColorAdaptive {
/** the factor that the low threshold is below the high threshold in the
2 layer filter.
*/
protected float factorBelowHighThreshold = 2.f;
private EdgeFilterProducts filterProducts = null;
private boolean performNonMaxSuppr = true;
private boolean debug = false;
private boolean restoreJunctions = true;
/**
* the sigma from the blur combined with the sigma present in the gradient
* are present in this variable by the end of processing.
* The variable is used to interpret resolution of theta angles, for example.
* The sigmas are combined using: sigma^2 = sigma_1^2 + sigma_2^2.
* The FWHM of a gaussian is approx 2.35 * sigma.
* (HWZI is about 5 * sigma, by the way).
* So, for the default use of the filter, a sigma of 1 combined with sqrt(1)/2
* results in a minimum resolution of 3 pixels, hence about 19 degrees.
*/
private double approxProcessedSigma = 0;
private boolean useAdaptiveThreshold = false;
private boolean useAdaptive2Layer = true;
private float otsuScaleFactor = 0.75f;//0.65f;
protected Logger log = Logger.getLogger(this.getClass().getName());
protected boolean useLineThinner = true;
public CannyEdgeColorAdaptive() {
}
public void setToDebug() {
debug = true;
}
public void overrideToNotUseLineThinner() {
useLineThinner = false;
}
/**
* to enable more complete contours, use this to restore pixels that were
* removed during non-maximum suppression that disconnected edges and
* have values above the low threshold of the 2 layer adaptive filter.
*/
public void setToNotRestoreJunctions() {
restoreJunctions = false;
}
/**
* by default this is 0.45.
* @param factor
*/
public void setOtsuScaleFactor(float factor) {
otsuScaleFactor = factor;
}
public void setToNotUseNonMaximumSuppression() {
performNonMaxSuppr = false;
}
/**
* set this to use the adaptive threshold in the 2 layer
* filter. it adjusts the threshold by regions of size
* 15. Note that if the image has alot of noise, this
* will include alot of noise in the result.
*/
public void overrideToUseAdaptiveThreshold() {
useAdaptiveThreshold = true;
}
public void setToUseSingleThresholdIn2LayerFilter() {
useAdaptive2Layer = false;
}
/**
* override the default factor of low threshold below high threshold, which
* is 2.
* @param factor
*/
public void override2LayerFactorBelowHighThreshold(float factor) {
factorBelowHighThreshold = factor;
}
/**
* apply the filter. note that unlike the other canny filters in this
* project, the input is not modified.
* @param input
*/
public void applyFilter(Image input) {
if (input.getWidth() < 3 || input.getHeight() < 3) {
throw new IllegalArgumentException("images should be >= 3x3 in size");
}
ImageProcessor imageProcessor = new ImageProcessor();
GreyscaleImage[] lch = imageProcessor.createLCHForLUV(input);
CannyEdgeFilterAdaptive cannyL = new CannyEdgeFilterAdaptive();
CannyEdgeFilterAdaptive cannyC = new CannyEdgeFilterAdaptive();
if (!useLineThinner) {
cannyL.overrideToNotUseLineThinner();
cannyC.overrideToNotUseLineThinner();
}
if (useAdaptiveThreshold) {
cannyL.overrideToUseAdaptiveThreshold();
cannyC.overrideToUseAdaptiveThreshold();
}
cannyL.override2LayerFactorBelowHighThreshold(factorBelowHighThreshold);
cannyC.override2LayerFactorBelowHighThreshold(factorBelowHighThreshold);
if (!performNonMaxSuppr) {
cannyL.setToNotUseNonMaximumSuppression();
cannyC.setToNotUseNonMaximumSuppression();
}
if (!restoreJunctions) {
cannyL.setToNotRestoreJunctions();
cannyC.setToNotRestoreJunctions();
}
if (!useAdaptive2Layer) {
cannyL.setToUseSingleThresholdIn2LayerFilter();
cannyC.setToUseSingleThresholdIn2LayerFilter();
}
if (!useLineThinner) {
cannyL.overrideToNotUseLineThinner();
cannyC.overrideToNotUseLineThinner();
}
if (debug) {
cannyL.setToDebug();
cannyC.setToDebug();
}
cannyL.setOtsuScaleFactor(otsuScaleFactor);
//cannyC.setOtsuScaleFactor(otsuScaleFactor);
cannyC.setOtsuScaleFactor(1.0f); // less sensitive and less noisey
cannyL.applyFilter(lch[0]);
cannyC.applyFilter(lch[1]);
EdgeFilterProducts edgeProductsL = cannyL.getFilterProducts();
EdgeFilterProducts edgeProductsC = cannyC.getFilterProducts();
// DEBUG: temporary look at recalculating the L thresholds
// to filter out scaled C values to reduce noise.
// assuming not adaptive for now.
int tLowL = edgeProductsL.getGradientXY().min();
float lFactor = 255.f/(float)edgeProductsL.getGradientXY().max();
float cFactor = 255.f/(float)edgeProductsC.getGradientXY().max();
GreyscaleImage combXY = edgeProductsL.getGradientXY()
.createWithDimensions();
GreyscaleImage combX = edgeProductsL.getGradientX()
.createWithDimensions();
GreyscaleImage combY = edgeProductsL.getGradientY()
.createWithDimensions();
int n = combXY.getNPixels();
int v0, v1, v, vx, vy;
for (int i = 0; i < n; ++i) {
v0 = edgeProductsL.getGradientXY().getValue(i);
v1 = edgeProductsC.getGradientXY().getValue(i);
v0 = Math.round(v0 * lFactor);
if (v0 > 255) {
v0 = 255;
}
v1 = Math.round(v1 * cFactor);
if (v1 > 255) {
v1 = 255;
}
if (cFactor > 1) {
if (v1 < tLowL) {
v1 = 0;
}
}
// choosing the largest of both instead of avg
if (v0 > v1) {
v = v0;
vx = edgeProductsL.getGradientX().getValue(i);
vy = edgeProductsL.getGradientY().getValue(i);
} else {
v = v1;
vx = edgeProductsC.getGradientX().getValue(i);
vy = edgeProductsC.getGradientY().getValue(i);
}
combXY.setValue(i, v);
combX.setValue(i, vx);
combY.setValue(i, vy);
}
GreyscaleImage combTheta =
imageProcessor.computeTheta180(combX, combY);
EdgeFilterProducts efp = new EdgeFilterProducts();
efp.setGradientX(combX);
efp.setGradientY(combY);
efp.setGradientXY(combXY);
efp.setTheta(combTheta);
this.filterProducts = efp;
}
/**
* get the filter products for gradient and orientation.
* note that the orientation image has values between 0 and 180.
* @return the filterProducts
*/
public EdgeFilterProducts getFilterProducts() {
return filterProducts;
}
}
| changed the threshold of the "C" portion of
the canny color edge filter.
| src/algorithms/imageProcessing/CannyEdgeColorAdaptive.java | changed the threshold of the "C" portion of the canny color edge filter. | <ide><path>rc/algorithms/imageProcessing/CannyEdgeColorAdaptive.java
<ide> package algorithms.imageProcessing;
<ide>
<del>import algorithms.misc.Misc;
<del>import algorithms.misc.MiscDebug;
<del>import algorithms.misc.MiscMath;
<ide> import java.util.logging.Logger;
<del>import java.util.HashSet;
<del>import algorithms.util.PairInt;
<del>import java.util.ArrayList;
<del>import java.util.Arrays;
<del>import java.util.List;
<del>import java.util.Set;
<ide>
<ide> /**
<ide> * NOTE: need to edit these comments. for this color version of canny,
<ide> }
<ide>
<ide> cannyL.setOtsuScaleFactor(otsuScaleFactor);
<del> //cannyC.setOtsuScaleFactor(otsuScaleFactor);
<del> cannyC.setOtsuScaleFactor(1.0f); // less sensitive and less noisey
<add> cannyC.setOtsuScaleFactor(otsuScaleFactor);
<add> //cannyC.setOtsuScaleFactor(1.0f); // less sensitive and less noisey
<ide>
<ide> cannyL.applyFilter(lch[0]);
<ide> cannyC.applyFilter(lch[1]); |
|
Java | bsd-2-clause | c7036f04418a121129d74b26a4d9d6ae503e8369 | 0 | llwanghong/jslint4java,nikgoodley-ibboost/jslint4java,mmayorivera/jslint4java,llwanghong/jslint4java,llwanghong/jslint4java,rsingla/jslint4java,mmayorivera/jslint4java,nikgoodley-ibboost/jslint4java,nikgoodley-ibboost/jslint4java,rsingla/jslint4java,rsingla/jslint4java,nikgoodley-ibboost/jslint4java,llwanghong/jslint4java,rsingla/jslint4java,mmayorivera/jslint4java,nikgoodley-ibboost/jslint4java,mmayorivera/jslint4java,llwanghong/jslint4java,mmayorivera/jslint4java,rsingla/jslint4java |
package com.googlecode.jslint4java;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
/**
* @author dom
*/
public class JSLintTest {
private static final String EXPECTED_SEMICOLON = "Expected ';' and instead saw '(end)'.";
private JSLint lint = null;
// Check that the issues list matches zero or more reasons.
private void assertIssues(List<Issue> issues, String... reasons) {
assertThat(issues, is(notNullValue()));
String msg = "Actual issues: " + issues;
assertThat(msg, issues.size(), is(reasons.length));
for (int i = 0; i < reasons.length; i++) {
assertThat(issues.get(i).getReason(), is(reasons[i]));
}
}
// small helper function.
private JSLintResult lint(Reader reader) throws IOException {
return lint.lint("-", reader);
}
// small helper function.
private JSLintResult lint(String source) {
return lint.lint("-", source);
}
@Before
public void setUp() throws IOException {
lint = new JSLintBuilder().fromDefault();
// Turn off a few options. These used to be the default.
lint.addOption(Option.SLOPPY);
}
@Test
public void testAccurateColumnNumbers() {
List<Issue> issues = lint("var foo = 1").getIssues();
// ....................... 123456789012
assertIssues(issues, EXPECTED_SEMICOLON);
assertThat(issues.get(0).getCharacter(), is(12));
}
@Test
public void testAccurateLineNumbers() {
List<Issue> issues = lint("var foo = 1").getIssues();
assertIssues(issues, EXPECTED_SEMICOLON);
assertThat(issues.get(0).getLine(), is(1));
}
/**
* See what information we can return about a single function.
* @throws Exception
*/
@Test
public void testDataFunctions() throws Exception {
lint.addOption(Option.WHITE);
JSLintResult result = lint("var z = 5; function foo(x) {var y = x + z; alert(y); return y; }");
assertIssues(result.getIssues());
List<JSFunction> functions = result.getFunctions();
assertThat(functions.size(), is(1));
JSFunction f1 = functions.get(0);
assertThat(f1.getName(), is("foo"));
assertThat(f1.getLine(), is(1));
assertThat(f1.getParams().size(), is(1));
assertThat(f1.getParams().get(0), is("x"));
// TODO: how to test getClosure()?
assertThat(f1.getVars().size(), is(1));
assertThat(f1.getVars().get(0), is("y"));
// TODO: test getException()
// TODO: test getOuter()
// TODO: test getUnused()
assertThat(f1.getUndef().size(), is(1));
assertThat(f1.getUndef().get(0), is("alert"));
assertThat(f1.getGlobal().size(), is(1));
assertThat(f1.getGlobal().get(0), is("z"));
// TODO: test getLabel()
}
@Test
public void testDataGlobals() throws Exception {
JSLintResult result = lint("var foo = 12;");
assertTrue(result.getIssues().isEmpty());
assertThat(result.getGlobals(), hasItem("foo"));
}
@Test
public void testDataJsonness() throws Exception {
JSLintResult result = lint("{\"a\":100}");
assertIssues(result.getIssues());
assertTrue(result.isJson());
}
@Test
public void testEmptySource() throws Exception {
assertIssues(lint("").getIssues());
}
@Test
public void testGetEdition() throws Exception {
String edition = lint.getEdition();
assertThat(edition, is(notNullValue()));
String dateRe = "^\\d\\d\\d\\d-\\d\\d-\\d\\d$";
assertTrue(edition + " matches " + dateRe, edition.matches(dateRe));
}
// Issue 16.
@Test
public void testGlobalName() throws Exception {
String src = "/*global name: true */\nname = \"fred\";";
assertIssues(lint(src).getIssues());
}
@Test
public void testLintReader() throws Exception {
Reader reader = new StringReader("var foo = 1");
List<Issue> issues = lint(reader).getIssues();
assertIssues(issues, EXPECTED_SEMICOLON);
}
@Test
public void testMaxErr() throws Exception {
lint.addOption(Option.WHITE, "false");
lint.addOption(Option.MAXERR, "2");
// Just some nasty thing I threw together. :)
JSLintResult result = lint("if (foo=42) {\n println(\"bother\")\n}\n");
assertIssues(result.getIssues(), "'foo' was used before it was defined.",
"Missing space between 'foo' and '='.",
"Too many errors. (25% scanned).");
}
@Test
public void testMaxLen() {
lint.addOption(Option.MAXLEN, "1");
JSLintResult result = lint("var foo = 42;");
assertIssues(result.getIssues(), "Line too long.");
}
@Test
public void testNoProblems() throws IOException {
List<Issue> problems = lint("var foo = 1;").getIssues();
assertIssues(problems);
}
@Test
public void testNullSource() throws Exception {
List<Issue> issues = lint((String) null).getIssues();
assertIssues(issues);
}
@Test
public void testOneProblem() throws IOException {
// There is a missing semicolon here.
List<Issue> problems = lint("var foo = 1").getIssues();
assertIssues(problems, EXPECTED_SEMICOLON);
}
/**
* We're testing this so that we know arrays get passed into JavaScript
* correctly.
*/
@Test
public void testPredefOption() throws Exception {
lint.addOption(Option.PREDEF, "foo,bar");
List<Issue> issues = lint("foo(bar(42));").getIssues();
assertIssues(issues);
}
@Test
public void testProperties() {
// issue 42: beware numeric keys…
JSLintResult result = lint("var obj = {\"a\": 1, \"b\": 42, 3: \"c\"};");
assertIssues(result.getIssues());
Set<String> properties = result.getProperties();
assertThat(properties.size(), is(3));
assertThat(properties, hasItems("a", "b", "3"));
}
@Test
public void testReportErrorsOnly() throws Exception {
String html = lint.report("var foo = 42", true);
assertThat(html, containsString("<cite><address>"));
assertThat(html, containsString(EXPECTED_SEMICOLON));
}
@Test
public void testReportFull() throws Exception {
String html = lint.report("var foo = 42;");
assertThat(html, containsString("<dt>global</dt><dd>foo</dd>"));
}
@Test
public void testReportInResult() throws Exception {
String html = lint("var foo = 42").getReport();
assertThat(html, containsString("<cite><address>"));
assertThat(html, containsString(EXPECTED_SEMICOLON));
}
@Test
public void testResetOptions() throws Exception {
String eval_js = "eval('1');";
lint.addOption(Option.EVIL);
lint.resetOptions();
List<Issue> issues = lint(eval_js).getIssues();
assertIssues(issues, "eval is evil.");
}
@Test
public void testSetOption() throws Exception {
String eval_js = "eval('1');";
// should be disallowed by default.
List<Issue> issues = lint(eval_js).getIssues();
assertIssues(issues, "eval is evil.");
// Now should be a problem.
lint.addOption(Option.EVIL);
issues = lint(eval_js).getIssues();
assertIssues(issues);
}
@Test
public void testSetOptionWithArgument() throws Exception {
// This should only pass when indent=2.
String js = "var x = 0;\nif (!x) {\n x = 1;\n}";
lint.addOption(Option.WHITE);
lint.addOption(Option.INDENT, "2");
List<Issue> issues = lint(js).getIssues();
assertIssues(issues);
}
/**
* issue 62: tabs getting munged. The root cause here is that JSLint expands
* tabs to spaces. It does this on the basis of the <i>indent</i> option, at
* initialisation time (if you have a /*jslint comment to alter the ident,
* it doesn't affect the tab expansion).
*
* <p>
* Now, it turns out that jslint.com always defaults <i>indent</i> to four.
* We have no default, so it gets set to zero. That means that the tab
* expansion value gets set to "". Which means {@code var\ti} ends up as
* {@code vari}. In order to avoid this, we need to ensure we always pass in
* a default of four.
*
* <p>
* Just to make life even more interesting, I forgot that we set
* "default options" in setUp (including <i>indent</i>) which meant the
* behaviour didn't show the first time.
*/
@Test
public void testTabSanity() {
// We need to turn on undefined variable checking here.
lint.resetOptions();
lint.addOption(Option.SLOPPY);
lint.addOption(Option.WHITE);
// This is coming out as "vari"...
String js = "var\ti = 0;\n";
JSLintResult result = lint(js);
assertIssues(result.getIssues());
}
// http://code.google.com/p/jslint4java/issues/detail?id=1
@Test
public void testUnableToContinue() throws Exception {
// This isn't the originally reported problem, but it tickles the
// "can't continue" message.
List<Issue> issues = lint("\"").getIssues();
// This looks like a bug in JSLint…
assertIssues(issues, "Unclosed string.", "Stopping. (100% scanned).");
}
/**
* Normally, these only get reported as part of .data(), but JSLint treats them as errors.
*/
@Test
public void testUnusedWarnings() {
lint.addOption(Option.WARNINGS);
String js = "function foo(a, b) {\n return a;\n}";
List<Issue> issues = lint(js).getIssues();
assertIssues(issues, "Unused variable: 'b' in foo.");
}
} | jslint4java/src/test/java/com/googlecode/jslint4java/JSLintTest.java |
package com.googlecode.jslint4java;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
/**
* @author dom
*/
public class JSLintTest {
private static final String EXPECTED_SEMICOLON = "Expected ';' and instead saw '(end)'.";
private JSLint lint = null;
// Check that the issues list matches zero or more reasons.
private void assertIssues(List<Issue> issues, String... reasons) {
assertThat(issues, is(notNullValue()));
String msg = "Actual issues: " + issues;
assertThat(msg, issues.size(), is(reasons.length));
for (int i = 0; i < reasons.length; i++) {
assertThat(issues.get(i).getReason(), is(reasons[i]));
}
}
// small helper function.
private JSLintResult lint(Reader reader) throws IOException {
return lint.lint("-", reader);
}
// small helper function.
private JSLintResult lint(String source) {
return lint.lint("-", source);
}
@Before
public void setUp() throws IOException {
lint = new JSLintBuilder().fromDefault();
// Turn off a few options. These used to be the default.
lint.addOption(Option.SLOPPY);
}
@Test
public void testAccurateColumnNumbers() {
List<Issue> issues = lint("var foo = 1").getIssues();
// ....................... 123456789012
assertIssues(issues, EXPECTED_SEMICOLON);
assertThat(issues.get(0).getCharacter(), is(12));
}
@Test
public void testAccurateLineNumbers() {
List<Issue> issues = lint("var foo = 1").getIssues();
assertIssues(issues, EXPECTED_SEMICOLON);
assertThat(issues.get(0).getLine(), is(1));
}
/**
* See what information we can return about a single function.
* @throws Exception
*/
@Test
public void testDataFunctions() throws Exception {
lint.addOption(Option.WHITE);
JSLintResult result = lint("var z = 5; function foo(x) {var y = x + z; alert(y); return y; }");
assertIssues(result.getIssues());
List<JSFunction> functions = result.getFunctions();
assertThat(functions.size(), is(1));
JSFunction f1 = functions.get(0);
assertThat(f1.getName(), is("foo"));
assertThat(f1.getLine(), is(1));
assertThat(f1.getParams().size(), is(1));
assertThat(f1.getParams().get(0), is("x"));
// TODO: how to test getClosure()?
assertThat(f1.getVars().size(), is(1));
assertThat(f1.getVars().get(0), is("y"));
// TODO: test getException()
// TODO: test getOuter()
// TODO: test getUnused()
assertThat(f1.getUndef().size(), is(1));
assertThat(f1.getUndef().get(0), is("alert"));
assertThat(f1.getGlobal().size(), is(1));
assertThat(f1.getGlobal().get(0), is("z"));
// TODO: test getLabel()
}
@Test
public void testDataGlobals() throws Exception {
JSLintResult result = lint("var foo = 12;");
assertTrue(result.getIssues().isEmpty());
assertThat(result.getGlobals(), hasItem("foo"));
}
@Test
public void testDataJsonness() throws Exception {
JSLintResult result = lint("{\"a\":100}");
assertIssues(result.getIssues());
assertTrue(result.isJson());
}
@Test
public void testEmptySource() throws Exception {
assertIssues(lint("").getIssues());
}
@Test
public void testGetEdition() throws Exception {
String edition = lint.getEdition();
assertThat(edition, is(notNullValue()));
String dateRe = "^\\d\\d\\d\\d-\\d\\d-\\d\\d$";
assertTrue(edition + " matches " + dateRe, edition.matches(dateRe));
}
// Issue 16.
@Test
public void testGlobalName() throws Exception {
String src = "/*global name: true */\nname = \"fred\";";
assertIssues(lint(src).getIssues());
}
@Test
public void testLintReader() throws Exception {
Reader reader = new StringReader("var foo = 1");
List<Issue> issues = lint(reader).getIssues();
assertIssues(issues, EXPECTED_SEMICOLON);
}
@Test
public void testMaxErr() throws Exception {
lint.addOption(Option.WHITE, "false");
lint.addOption(Option.MAXERR, "2");
// Just some nasty thing I threw together. :)
JSLintResult result = lint("if (foo=42) {\n println(\"bother\")\n}\n");
assertIssues(result.getIssues(), "'foo' was used before it was defined.",
"Missing space between 'foo' and '='.",
"Too many errors. (25% scanned).");
}
@Test
public void testMaxLen() {
lint.addOption(Option.MAXLEN, "1");
JSLintResult result = lint("var foo = 42;");
assertIssues(result.getIssues(), "Line too long.");
}
@Test
public void testNoProblems() throws IOException {
List<Issue> problems = lint("var foo = 1;").getIssues();
assertIssues(problems);
}
@Test
public void testNullSource() throws Exception {
List<Issue> issues = lint((String) null).getIssues();
assertIssues(issues);
}
@Test
public void testOneProblem() throws IOException {
// There is a missing semicolon here.
List<Issue> problems = lint("var foo = 1").getIssues();
assertIssues(problems, EXPECTED_SEMICOLON);
}
/**
* We're testing this so that we know arrays get passed into JavaScript
* correctly.
*/
@Test
public void testPredefOption() throws Exception {
lint.addOption(Option.PREDEF, "foo,bar");
List<Issue> issues = lint("foo(bar(42));").getIssues();
assertIssues(issues);
}
@Test
public void testProperties() {
// issue 42: beware numeric keys…
JSLintResult result = lint("var obj = {\"a\": 1, \"b\": 42, 3: \"c\"};");
assertIssues(result.getIssues());
Set<String> properties = result.getProperties();
assertThat(properties.size(), is(3));
assertThat(properties, hasItems("a", "b", "3"));
}
@Test
public void testReportErrorsOnly() throws Exception {
String html = lint.report("var foo = 42", true);
assertThat(html, containsString("<cite><address>"));
assertThat(html, containsString(EXPECTED_SEMICOLON));
}
@Test
public void testReportFull() throws Exception {
String html = lint.report("var foo = 42;");
assertThat(html, containsString("<dt>global</dt><dd>foo</dd>"));
}
@Test
public void testReportInResult() throws Exception {
String html = lint("var foo = 42").getReport();
assertThat(html, containsString("<cite><address>"));
assertThat(html, containsString(EXPECTED_SEMICOLON));
}
@Test
public void testResetOptions() throws Exception {
String eval_js = "eval('1');";
lint.addOption(Option.EVIL);
lint.resetOptions();
List<Issue> issues = lint(eval_js).getIssues();
assertIssues(issues, "eval is evil.");
}
@Test
public void testSetOption() throws Exception {
String eval_js = "eval('1');";
// should be disallowed by default.
List<Issue> issues = lint(eval_js).getIssues();
assertIssues(issues, "eval is evil.");
// Now should be a problem.
lint.addOption(Option.EVIL);
issues = lint(eval_js).getIssues();
assertIssues(issues);
}
@Test
public void testSetOptionWithArgument() throws Exception {
// This should only pass when indent=2.
String js = "var x = 0;\nif (!x) {\n x = 1;\n}";
lint.addOption(Option.WHITE);
lint.addOption(Option.INDENT, "2");
List<Issue> issues = lint(js).getIssues();
assertIssues(issues);
}
/**
* issue 62: tabs getting munged. The root cause here is that JSLint expands
* tabs to spaces. It does this on the basis of the <i>indent</i> option, at
* initialisation time (if you have a /*jslint comment to alter the ident,
* it doesn't affect the tab expansion).
*
* <p>
* Now, it turns out that jslint.com always defaults <i>indent</i> to four.
* We have no default, so it gets set to zero. That means that the tab
* expansion value gets set to "". Which means {@code var\ti} ends up as
* {@code vari}. In order to avoid this, we need to ensure we always pass in
* a default of four.
*
* <p>
* Just to make life even more interesting, I forgot that we set
* "default options" in setUp (including <i>indent</i>) which meant the
* behaviour didn't show the first time.
*/
@Test
public void testTabSanity() {
// We need to turn on undefined variable checking here.
lint.resetOptions();
lint.addOption(Option.SLOPPY);
lint.addOption(Option.WHITE);
// This is coming out as "vari"...
String js = "var\ti = 0;\n";
JSLintResult result = lint(js);
assertIssues(result.getIssues());
}
// http://code.google.com/p/jslint4java/issues/detail?id=1
@Test
public void testUnableToContinue() throws Exception {
// This isn't the originally reported problem, but it tickles the
// "can't continue" message.
List<Issue> issues = lint("\"").getIssues();
// This looks like a bug in JSLint…
assertIssues(issues, "Unclosed string.", "Stopping. (200% scanned).");
}
/**
* Normally, these only get reported as part of .data(), but JSLint treats them as errors.
*/
@Test
public void testUnusedWarnings() {
lint.addOption(Option.WARNINGS);
String js = "function foo(a, b) {\n return a;\n}";
List<Issue> issues = lint(js).getIssues();
assertIssues(issues, "Unused variable: 'b' in foo.");
}
} | The parser got fixed. :) | jslint4java/src/test/java/com/googlecode/jslint4java/JSLintTest.java | The parser got fixed. :) | <ide><path>slint4java/src/test/java/com/googlecode/jslint4java/JSLintTest.java
<ide> // "can't continue" message.
<ide> List<Issue> issues = lint("\"").getIssues();
<ide> // This looks like a bug in JSLint…
<del> assertIssues(issues, "Unclosed string.", "Stopping. (200% scanned).");
<add> assertIssues(issues, "Unclosed string.", "Stopping. (100% scanned).");
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 0941cc9884e0a1a91fd1bc0ba8b4cff271a5eb14 | 0 | savelichalex/react,nhunzaker/react,psibi/react,neusc/react,edvinerikson/react,yulongge/react,yungsters/react,arush/react,zs99/react,negativetwelve/react,rohannair/react,orzyang/react,lennerd/react,sdiaz/react,flowbywind/react,usgoodus/react,rohannair/react,vincentism/react,lastjune/react,lastjune/react,edvinerikson/react,miaozhirui/react,silvestrijonathan/react,krasimir/react,patrickgoudjoako/react,richiethomas/react,yhagio/react,yjyi/react,free-memory/react,acdlite/react,dgreensp/react,rgbkrk/react,jorrit/react,mcanthony/react,miaozhirui/react,cmfcmf/react,nhunzaker/react,TylerBrock/react,kevin0307/react,patryknowak/react,ouyangwenfeng/react,rgbkrk/react,roth1002/react,ABaldwinHunter/react-classic,rohannair/react,labs00/react,joshblack/react,wmydz1/react,DJCordhose/react,benchling/react,gitoneman/react,nickdima/react,6feetsong/react,sejoker/react,roth1002/react,ashwin01/react,JoshKaufman/react,pyitphyoaung/react,sugarshin/react,yulongge/react,isathish/react,kaushik94/react,felixgrey/react,tarjei/react,chrisjallen/react,linmic/react,james4388/react,reactkr/react,flarnie/react,joecritch/react,it33/react,tjsavage/react,algolia/react,xiaxuewuhen001/react,nickpresta/react,JasonZook/react,chicoxyzzy/react,trellowebinars/react,yongxu/react,mjackson/react,jdlehman/react,digideskio/react,kaushik94/react,dittos/react,kamilio/react,kolmstead/react,jzmq/react,k-cheng/react,psibi/react,trueadm/react,VioletLife/react,sitexa/react,haoxutong/react,javascriptit/react,perperyu/react,dustin-H/react,brigand/react,mhhegazy/react,rlugojr/react,ameyms/react,Jyrno42/react,conorhastings/react,hejld/react,blainekasten/react,aaron-goshine/react,blue68/react,zyt01/react,tomv564/react,aickin/react,joaomilho/react,apaatsio/react,ericyang321/react,davidmason/react,orneryhippo/react,theseyi/react,ajdinhedzic/react,agileurbanite/react,pdaddyo/react,airondumael/react,alvarojoao/react,agideo/react,ericyang321/react,bspaulding/react,zhengqiangzi/react,gleborgne/react,joaomilho/react,pdaddyo/react,zs99/react,jontewks/react,psibi/react,speedyGonzales/react,Simek/react,BorderTravelerX/react,stanleycyang/react,claudiopro/react,ramortegui/react,aickin/react,sugarshin/react,manl1100/react,chicoxyzzy/react,rasj/react,tom-wang/react,gpbl/react,apaatsio/react,8398a7/react,pswai/react,cmfcmf/react,maxschmeling/react,aaron-goshine/react,wushuyi/react,Diaosir/react,brigand/react,howtolearntocode/react,dfosco/react,studiowangfei/react,nsimmons/react,anushreesubramani/react,silppuri/react,ZhouYong10/react,blainekasten/react,luomiao3/react,joon1030/react,howtolearntocode/react,facebook/react,reactkr/react,wjb12/react,jordanpapaleo/react,andrewsokolov/react,jameszhan/react,sejoker/react,STRML/react,cmfcmf/react,tomocchino/react,yiminghe/react,demohi/react,ABaldwinHunter/react-engines,AnSavvides/react,SpencerCDixon/react,isathish/react,darobin/react,luomiao3/react,stardev24/react,LoQIStar/react,ridixcr/react,Spotinux/react,nsimmons/react,chacbumbum/react,zhangwei001/react,syranide/react,ZhouYong10/react,zofuthan/react,tomv564/react,TaaKey/react,yongxu/react,patrickgoudjoako/react,savelichalex/react,mhhegazy/react,mcanthony/react,nickdima/react,kevin0307/react,jquense/react,cody/react,easyfmxu/react,cpojer/react,chrismoulton/react,jbonta/react,demohi/react,zhangwei001/react,wjb12/react,chinakids/react,cinic/react,tom-wang/react,camsong/react,reactkr/react,kaushik94/react,yasaricli/react,studiowangfei/react,patryknowak/react,silvestrijonathan/react,DigitalCoder/react,gpbl/react,edmellum/react,perterest/react,pandoraui/react,jzmq/react,JoshKaufman/react,afc163/react,TaaKey/react,jmptrader/react,wushuyi/react,cpojer/react,ashwin01/react,gfogle/react,ms-carterk/react,k-cheng/react,hawsome/react,kaushik94/react,edvinerikson/react,staltz/react,andrerpena/react,Simek/react,pwmckenna/react,easyfmxu/react,eoin/react,edvinerikson/react,bestwpw/react,krasimir/react,empyrical/react,nLight/react,greglittlefield-wf/react,dgreensp/react,linalu1/react,juliocanares/react,rgbkrk/react,trueadm/react,yangshun/react,kolmstead/react,shergin/react,arush/react,TaaKey/react,pze/react,bhamodi/react,studiowangfei/react,yut148/react,trungda/react,sarvex/react,yut148/react,TaaKey/react,conorhastings/react,yisbug/react,airondumael/react,JoshKaufman/react,obimod/react,yangshun/react,wushuyi/react,pze/react,ericyang321/react,vipulnsward/react,Flip120/react,dmitriiabramov/react,elquatro/react,maxschmeling/react,genome21/react,reactkr/react,usgoodus/react,mnordick/react,ashwin01/react,crsr/react,reggi/react,shergin/react,ms-carterk/react,mnordick/react,pswai/react,diegobdev/react,wesbos/react,rasj/react,pdaddyo/react,Spotinux/react,alwayrun/react,niubaba63/react,blainekasten/react,speedyGonzales/react,jsdf/react,mjackson/react,rricard/react,dgladkov/react,jbonta/react,dmatteo/react,juliocanares/react,ThinkedCoder/react,VioletLife/react,leohmoraes/react,leexiaosi/react,Flip120/react,apaatsio/react,dfosco/react,nLight/react,mcanthony/react,anushreesubramani/react,LoQIStar/react,jkcaptain/react,xiaxuewuhen001/react,DigitalCoder/react,savelichalex/react,negativetwelve/react,trungda/react,bhamodi/react,tomocchino/react,rlugojr/react,IndraVikas/react,dgladkov/react,insionng/react,benchling/react,cmfcmf/react,easyfmxu/react,rickbeerendonk/react,nLight/react,rwwarren/react,Jonekee/react,microlv/react,DigitalCoder/react,dustin-H/react,savelichalex/react,JungMinu/react,jordanpapaleo/react,inuscript/react,chrisjallen/react,lonely8rain/react,jontewks/react,pandoraui/react,genome21/react,jiangzhixiao/react,alvarojoao/react,with-git/react,honger05/react,dgladkov/react,manl1100/react,inuscript/react,iamchenxin/react,dmitriiabramov/react,rricard/react,JasonZook/react,brigand/react,TaaKey/react,benjaffe/react,ledrui/react,ning-github/react,nathanmarks/react,reggi/react,gregrperkins/react,ABaldwinHunter/react-classic,skevy/react,mhhegazy/react,jmptrader/react,phillipalexander/react,musofan/react,TheBlasfem/react,zanjs/react,savelichalex/react,christer155/react,slongwang/react,andrerpena/react,mingyaaaa/react,andrescarceller/react,AlmeroSteyn/react,jontewks/react,claudiopro/react,dfosco/react,jdlehman/react,ThinkedCoder/react,tzq668766/react,guoshencheng/react,gitignorance/react,ouyangwenfeng/react,niubaba63/react,JanChw/react,BreemsEmporiumMensToiletriesFragrances/react,ArunTesco/react,ericyang321/react,popovsh6/react,kolmstead/react,conorhastings/react,stevemao/react,wesbos/react,jeromjoy/react,linmic/react,chrisjallen/react,AmericanSundown/react,wuguanghai45/react,acdlite/react,neusc/react,mik01aj/react,mosoft521/react,alwayrun/react,andrewsokolov/react,joe-strummer/react,alexanther1012/react,rickbeerendonk/react,benchling/react,ZhouYong10/react,chacbumbum/react,jorrit/react,savelichalex/react,jsdf/react,niole/react,ThinkedCoder/react,pswai/react,demohi/react,cpojer/react,insionng/react,andrerpena/react,TaaKey/react,gregrperkins/react,juliocanares/react,facebook/react,Datahero/react,BorderTravelerX/react,venkateshdaram434/react,chippieTV/react,TaaKey/react,jordanpapaleo/react,labs00/react,camsong/react,dortonway/react,perterest/react,crsr/react,neomadara/react,skevy/react,tom-wang/react,digideskio/react,6feetsong/react,dilidili/react,acdlite/react,mhhegazy/react,yiminghe/react,huanglp47/react,staltz/react,bspaulding/react,gpazo/react,prometheansacrifice/react,dortonway/react,eoin/react,chippieTV/react,prometheansacrifice/react,LoQIStar/react,gitignorance/react,concerned3rdparty/react,yasaricli/react,wjb12/react,kieranjones/react,yuhualingfeng/react,jimfb/react,staltz/react,TaaKey/react,lina/react,richiethomas/react,apaatsio/react,vipulnsward/react,kalloc/react,Rafe/react,joe-strummer/react,bhamodi/react,andrescarceller/react,tomocchino/react,rgbkrk/react,empyrical/react,ABaldwinHunter/react-engines,andrescarceller/react,jordanpapaleo/react,shergin/react,skevy/react,claudiopro/react,hejld/react,Spotinux/react,niole/react,cesine/react,richiethomas/react,niole/react,gold3bear/react,gxr1020/react,edvinerikson/react,rlugojr/react,yisbug/react,joecritch/react,ameyms/react,nsimmons/react,joon1030/react,wudouxingjun/react,obimod/react,gitoneman/react,brigand/react,salier/react,mcanthony/react,empyrical/react,wjb12/react,BreemsEmporiumMensToiletriesFragrances/react,gold3bear/react,mgmcdermott/react,ramortegui/react,hejld/react,psibi/react,easyfmxu/react,lonely8rain/react,Furzikov/react,jimfb/react,dortonway/react,wmydz1/react,VioletLife/react,easyfmxu/react,tlwirtz/react,facebook/react,gougouGet/react,cesine/react,Simek/react,jdlehman/react,theseyi/react,miaozhirui/react,dgreensp/react,lennerd/react,joe-strummer/react,ABaldwinHunter/react-classic,temnoregg/react,concerned3rdparty/react,guoshencheng/react,vipulnsward/react,rlugojr/react,sejoker/react,AnSavvides/react,joshblack/react,flipactual/react,krasimir/react,terminatorheart/react,afc163/react,staltz/react,mosoft521/react,aickin/react,skyFi/react,honger05/react,psibi/react,haoxutong/react,ABaldwinHunter/react-classic,neusc/react,mingyaaaa/react,mcanthony/react,orneryhippo/react,zs99/react,roylee0704/react,slongwang/react,agileurbanite/react,perperyu/react,rlugojr/react,skyFi/react,kalloc/react,gfogle/react,gregrperkins/react,nickpresta/react,skomski/react,christer155/react,Rafe/react,shergin/react,ledrui/react,marocchino/react,brian-murray35/react,gxr1020/react,scottburch/react,aaron-goshine/react,usgoodus/react,spt110/react,dortonway/react,wangyzyoga/react,easyfmxu/react,ameyms/react,greglittlefield-wf/react,pandoraui/react,jbonta/react,nickpresta/react,AmericanSundown/react,szhigunov/react,guoshencheng/react,yungsters/react,wuguanghai45/react,alwayrun/react,shadowhunter2/react,ThinkedCoder/react,joaomilho/react,chacbumbum/react,pwmckenna/react,flarnie/react,Riokai/react,tom-wang/react,isathish/react,orzyang/react,silppuri/react,pandoraui/react,manl1100/react,ABaldwinHunter/react-engines,trungda/react,chinakids/react,christer155/react,jessebeach/react,sekiyaeiji/react,musofan/react,pyitphyoaung/react,zyt01/react,reggi/react,trungda/react,Furzikov/react,slongwang/react,Duc-Ngo-CSSE/react,iammerrick/react,pyitphyoaung/react,iOSDevBlog/react,bspaulding/react,flarnie/react,terminatorheart/react,yongxu/react,ajdinhedzic/react,BreemsEmporiumMensToiletriesFragrances/react,ericyang321/react,roth1002/react,with-git/react,inuscript/react,jeromjoy/react,alexanther1012/react,reactjs-vn/reactjs_vndev,joaomilho/react,PeterWangPo/react,jmptrader/react,jdlehman/react,dgreensp/react,cesine/react,trellowebinars/react,pze/react,iammerrick/react,yungsters/react,yongxu/react,Diaosir/react,empyrical/react,sarvex/react,ridixcr/react,yuhualingfeng/react,michaelchum/react,Simek/react,chippieTV/react,nickpresta/react,rlugojr/react,hawsome/react,mik01aj/react,greyhwndz/react,zeke/react,camsong/react,lonely8rain/react,miaozhirui/react,ManrajGrover/react,AlmeroSteyn/react,gajus/react,zanjs/react,zanjs/react,eoin/react,ZhouYong10/react,yiminghe/react,mingyaaaa/react,microlv/react,rohannair/react,glenjamin/react,DJCordhose/react,albulescu/react,gajus/react,joaomilho/react,iOSDevBlog/react,AmericanSundown/react,henrik/react,dfosco/react,liyayun/react,mik01aj/react,salier/react,ashwin01/react,rricard/react,sekiyaeiji/react,nickdima/react,STRML/react,slongwang/react,digideskio/react,benjaffe/react,yjyi/react,AnSavvides/react,ipmobiletech/react,ning-github/react,quip/react,nomanisan/react,huanglp47/react,it33/react,garbles/react,tarjei/react,brillantesmanuel/react,zhangwei001/react,zorojean/react,mosoft521/react,yongxu/react,mhhegazy/react,cody/react,iamchenxin/react,lastjune/react,VioletLife/react,billfeller/react,vincentism/react,roylee0704/react,tomv564/react,tlwirtz/react,edmellum/react,TaaKey/react,brillantesmanuel/react,negativetwelve/react,ilyachenko/react,davidmason/react,kamilio/react,studiowangfei/react,terminatorheart/react,digideskio/react,edvinerikson/react,sasumi/react,greysign/react,obimod/react,ledrui/react,insionng/react,stardev24/react,jeromjoy/react,richiethomas/react,tomocchino/react,jmptrader/react,davidmason/react,yangshun/react,brigand/react,theseyi/react,AlmeroSteyn/react,prometheansacrifice/react,linalu1/react,kaushik94/react,jameszhan/react,andrescarceller/react,dmatteo/react,mgmcdermott/react,jsdf/react,jkcaptain/react,greglittlefield-wf/react,yjyi/react,joaomilho/react,sejoker/react,AlmeroSteyn/react,javascriptit/react,IndraVikas/react,nathanmarks/react,concerned3rdparty/react,nhunzaker/react,dfosco/react,quip/react,gpbl/react,yhagio/react,Flip120/react,ms-carterk/react,salier/react,chrisjallen/react,k-cheng/react,neomadara/react,perterest/react,rricard/react,jedwards1211/react,dgreensp/react,jagdeesh109/react,JoshKaufman/react,yisbug/react,flipactual/react,javascriptit/react,jagdeesh109/react,james4388/react,kieranjones/react,ilyachenko/react,AlmeroSteyn/react,cody/react,jimfb/react,TaaKey/react,mjackson/react,krasimir/react,yulongge/react,bspaulding/react,billfeller/react,michaelchum/react,andrerpena/react,blainekasten/react,popovsh6/react,ericyang321/react,with-git/react,dilidili/react,anushreesubramani/react,neomadara/react,JasonZook/react,nickpresta/react,carlosipe/react,zyt01/react,brillantesmanuel/react,nickpresta/react,rohannair/react,sarvex/react,chacbumbum/react,shergin/react,jmptrader/react,elquatro/react,k-cheng/react,pyitphyoaung/react,chenglou/react,yangshun/react,dustin-H/react,michaelchum/react,afc163/react,zilaiyedaren/react,TylerBrock/react,jfschwarz/react,salzhrani/react,Duc-Ngo-CSSE/react,nLight/react,vincentism/react,Jyrno42/react,tywinstark/react,trueadm/react,tywinstark/react,ridixcr/react,gitoneman/react,silvestrijonathan/react,chicoxyzzy/react,willhackett/react,negativetwelve/react,lucius-feng/react,tlwirtz/react,dgreensp/react,iammerrick/react,glenjamin/react,jordanpapaleo/react,Simek/react,zyt01/react,8398a7/react,bspaulding/react,zeke/react,hawsome/react,nLight/react,roylee0704/react,neomadara/react,gajus/react,cmfcmf/react,gregrperkins/react,Furzikov/react,kay-is/react,edmellum/react,marocchino/react,dmitriiabramov/react,wushuyi/react,trueadm/react,temnoregg/react,tywinstark/react,jiangzhixiao/react,studiowangfei/react,benchling/react,alexanther1012/react,pod4g/react,greyhwndz/react,carlosipe/react,darobin/react,nathanmarks/react,wzpan/react,reactjs-vn/reactjs_vndev,roylee0704/react,getshuvo/react,benchling/react,wmydz1/react,AlmeroSteyn/react,jabhishek/react,silvestrijonathan/react,niubaba63/react,tlwirtz/react,yangshun/react,reactkr/react,Galactix/react,algolia/react,dilidili/react,tjsavage/react,szhigunov/react,flarnie/react,elquatro/react,ianb/react,pze/react,gfogle/react,jsdf/react,sergej-kucharev/react,mingyaaaa/react,wuguanghai45/react,tomocchino/react,niole/react,skevy/react,SpencerCDixon/react,camsong/react,bspaulding/react,usgoodus/react,empyrical/react,hawsome/react,kolmstead/react,deepaksharmacse12/react,jbonta/react,rricard/react,microlv/react,chacbumbum/react,insionng/react,kaushik94/react,stevemao/react,huanglp47/react,bhamodi/react,howtolearntocode/react,jontewks/react,chippieTV/react,Jyrno42/react,Jonekee/react,pyitphyoaung/react,syranide/react,chenglou/react,afc163/react,yangshun/react,sarvex/react,perterest/react,zyt01/react,gpazo/react,trungda/react,zeke/react,lina/react,STRML/react,chenglou/react,dilidili/react,manl1100/react,andrewsokolov/react,linalu1/react,apaatsio/react,TheBlasfem/react,rricard/react,gougouGet/react,Spotinux/react,zhangwei001/react,glenjamin/react,k-cheng/react,orneryhippo/react,it33/react,joecritch/react,Furzikov/react,jsdf/react,joshblack/react,jedwards1211/react,linqingyicen/react,chenglou/react,hawsome/react,jorrit/react,gfogle/react,huanglp47/react,glenjamin/react,rickbeerendonk/react,wesbos/react,pod4g/react,Jonekee/react,sugarshin/react,airondumael/react,vincentism/react,gxr1020/react,PeterWangPo/react,benjaffe/react,yuhualingfeng/react,musofan/react,gregrperkins/react,ssyang0102/react,nhunzaker/react,reggi/react,skevy/react,roth1002/react,ipmobiletech/react,Nieralyte/react,jorrit/react,yulongge/react,staltz/react,concerned3rdparty/react,iamchenxin/react,mardigtch/react,howtolearntocode/react,mingyaaaa/react,joecritch/react,haoxutong/react,hejld/react,VioletLife/react,deepaksharmacse12/react,felixgrey/react,carlosipe/react,reactkr/react,tarjei/react,diegobdev/react,yabhis/react,ning-github/react,iammerrick/react,genome21/react,luomiao3/react,leeleo26/react,scottburch/react,JanChw/react,elquatro/react,ashwin01/react,gold3bear/react,ms-carterk/react,Datahero/react,rickbeerendonk/react,zs99/react,wmydz1/react,JungMinu/react,agideo/react,facebook/react,vipulnsward/react,haoxutong/react,ABaldwinHunter/react-classic,aickin/react,neomadara/react,yiminghe/react,chrisbolin/react,garbles/react,IndraVikas/react,brigand/react,quip/react,jsdf/react,reactjs-vn/reactjs_vndev,garbles/react,aaron-goshine/react,niole/react,jquense/react,mohitbhatia1994/react,chrismoulton/react,stardev24/react,vipulnsward/react,supriyantomaftuh/react,jfschwarz/react,yasaricli/react,jquense/react,james4388/react,trueadm/react,concerned3rdparty/react,reggi/react,yiminghe/react,trellowebinars/react,linmic/react,STRML/react,linmic/react,jfschwarz/react,jameszhan/react,lucius-feng/react,ManrajGrover/react,DJCordhose/react,henrik/react,apaatsio/react,yisbug/react,willhackett/react,digideskio/react,gxr1020/react,conorhastings/react,Furzikov/react,cpojer/react,dilidili/react,glenjamin/react,trungda/react,rickbeerendonk/react,yut148/react,gpbl/react,TheBlasfem/react,mnordick/react,liyayun/react,yut148/react,nickdima/react,blainekasten/react,honger05/react,chicoxyzzy/react,ramortegui/react,pswai/react,neusc/react,venkateshdaram434/react,eoin/react,acdlite/react,tzq668766/react,AnSavvides/react,ajdinhedzic/react,roth1002/react,iOSDevBlog/react,mhhegazy/react,with-git/react,mik01aj/react,Datahero/react,neusc/react,DJCordhose/react,vipulnsward/react,Rafe/react,jimfb/react,kamilio/react,crsr/react,rwwarren/react,jabhishek/react,dittos/react,rwwarren/react,nLight/react,soulcm/react,yasaricli/react,ZhouYong10/react,alvarojoao/react,guoshencheng/react,claudiopro/react,kevin0307/react,microlv/react,nhunzaker/react,orneryhippo/react,hawsome/react,terminatorheart/react,vincentnacar02/react,jessebeach/react,flowbywind/react,ZhouYong10/react,stardev24/react,mgmcdermott/react,billfeller/react,free-memory/react,mgmcdermott/react,vincentism/react,getshuvo/react,tjsavage/react,zorojean/react,chenglou/react,Flip120/react,Nieralyte/react,davidmason/react,pwmckenna/react,gj262/react,jquense/react,lastjune/react,STRML/react,skomski/react,conorhastings/react,honger05/react,orneryhippo/react,misnet/react,linqingyicen/react,howtolearntocode/react,jameszhan/react,roth1002/react,kamilio/react,leexiaosi/react,chrisbolin/react,glenjamin/react,Jyrno42/react,tarjei/react,theseyi/react,acdlite/react,gajus/react,salier/react,nhunzaker/react,lennerd/react,reactjs-vn/reactjs_vndev,iamchenxin/react,marocchino/react,brillantesmanuel/react,pod4g/react,mik01aj/react,pswai/react,maxschmeling/react,jzmq/react,ridixcr/react,gj262/react,prometheansacrifice/react,wmydz1/react,STRML/react,blue68/react,ramortegui/react,ameyms/react,jagdeesh109/react,chenglou/react,phillipalexander/react,lennerd/react,haoxutong/react,tom-wang/react,roth1002/react,shergin/react,DJCordhose/react,obimod/react,elquatro/react,tomocchino/react,nathanmarks/react,zhangwei900808/react,DJCordhose/react,usgoodus/react,cody/react,linqingyicen/react,maxschmeling/react,nickdima/react,tzq668766/react,quip/react,jquense/react,dmatteo/react,patrickgoudjoako/react,dustin-H/react,SpencerCDixon/react,gleborgne/react,zorojean/react,pze/react,Rafe/react,mjackson/react,aaron-goshine/react,xiaxuewuhen001/react,rlugojr/react,edmellum/react,cody/react,szhigunov/react,gj262/react,musofan/react,gpbl/react,sekiyaeiji/react,jiangzhixiao/react,christer155/react,ianb/react,gajus/react,salzhrani/react,theseyi/react,temnoregg/react,zs99/react,prometheansacrifice/react,apaatsio/react,yut148/react,lastjune/react,jbonta/react,leohmoraes/react,syranide/react,joshblack/react,jordanpapaleo/react,1yvT0s/react,zeke/react,TheBlasfem/react,Flip120/react,spt110/react,rickbeerendonk/react,james4388/react,Riokai/react,dittos/react,aaron-goshine/react,soulcm/react,trueadm/react,yungsters/react,roylee0704/react,scottburch/react,jagdeesh109/react,jameszhan/react,mardigtch/react,chinakids/react,jorrit/react,dortonway/react,sdiaz/react,shergin/react,quip/react,agideo/react,JasonZook/react,jbonta/react,pwmckenna/react,nhunzaker/react,it33/react,ouyangwenfeng/react,dittos/react,gougouGet/react,misnet/react,flarnie/react,pyitphyoaung/react,chippieTV/react,Riokai/react,yisbug/react,ms-carterk/react,zeke/react,ridixcr/react,AmericanSundown/react,jfschwarz/react,obimod/react,yisbug/react,Galactix/react,stanleycyang/react,mgmcdermott/react,zorojean/react,james4388/react,flarnie/react,rasj/react,jedwards1211/react,orzyang/react,perperyu/react,ManrajGrover/react,reactjs-vn/reactjs_vndev,skevy/react,1yvT0s/react,Diaosir/react,chicoxyzzy/react,stanleycyang/react,glenjamin/react,eoin/react,greysign/react,ameyms/react,blainekasten/react,jzmq/react,dustin-H/react,free-memory/react,chrisjallen/react,zorojean/react,niubaba63/react,kalloc/react,guoshencheng/react,JoshKaufman/react,inuscript/react,gold3bear/react,edmellum/react,gfogle/react,krasimir/react,iammerrick/react,deepaksharmacse12/react,joe-strummer/react,trellowebinars/react,sasumi/react,jedwards1211/react,kolmstead/react,dustin-H/react,gpazo/react,tomv564/react,pandoraui/react,ms-carterk/react,chrismoulton/react,leohmoraes/react,alvarojoao/react,JasonZook/react,dmatteo/react,ledrui/react,henrik/react,ThinkedCoder/react,billfeller/react,zeke/react,stanleycyang/react,stardev24/react,pwmckenna/react,claudiopro/react,benchling/react,ABaldwinHunter/react-engines,camsong/react,cinic/react,crsr/react,yuhualingfeng/react,ABaldwinHunter/react-classic,bestwpw/react,JungMinu/react,popovsh6/react,sejoker/react,anushreesubramani/react,crsr/react,yut148/react,howtolearntocode/react,manl1100/react,yasaricli/react,dmitriiabramov/react,gitoneman/react,usgoodus/react,algolia/react,sasumi/react,gleborgne/react,ameyms/react,patrickgoudjoako/react,krasimir/react,garbles/react,claudiopro/react,yungsters/react,ABaldwinHunter/react-engines,chicoxyzzy/react,nathanmarks/react,deepaksharmacse12/react,chenglou/react,mjackson/react,with-git/react,dmitriiabramov/react,mcanthony/react,iOSDevBlog/react,brian-murray35/react,jontewks/react,sasumi/react,mjackson/react,ilyachenko/react,iOSDevBlog/react,gpazo/react,felixgrey/react,salzhrani/react,wudouxingjun/react,zofuthan/react,yuhualingfeng/react,garbles/react,AlmeroSteyn/react,nomanisan/react,jzmq/react,marocchino/react,aickin/react,airondumael/react,empyrical/react,sugarshin/react,bspaulding/react,insionng/react,ArunTesco/react,Jyrno42/react,vincentnacar02/react,maxschmeling/react,hejld/react,supriyantomaftuh/react,wzpan/react,zofuthan/react,zhangwei001/react,niubaba63/react,rohannair/react,sdiaz/react,sugarshin/react,richiethomas/react,jontewks/react,dilidili/react,jameszhan/react,leohmoraes/react,vincentism/react,with-git/react,kay-is/react,davidmason/react,zhangwei900808/react,dortonway/react,aickin/react,niubaba63/react,marocchino/react,microlv/react,linqingyicen/react,bestwpw/react,gregrperkins/react,STRML/react,patrickgoudjoako/react,agileurbanite/react,theseyi/react,tlwirtz/react,ljhsai/react,linmic/react,leeleo26/react,BreemsEmporiumMensToiletriesFragrances/react,mhhegazy/react,IndraVikas/react,jkcaptain/react,patrickgoudjoako/react,Riokai/react,supriyantomaftuh/react,orneryhippo/react,jimfb/react,pdaddyo/react,tywinstark/react,mosoft521/react,joon1030/react,AnSavvides/react,JoshKaufman/react,nathanmarks/react,TylerBrock/react,wzpan/react,chicoxyzzy/react,tarjei/react,rickbeerendonk/react,claudiopro/react,sitexa/react,silvestrijonathan/react,diegobdev/react,zhangwei900808/react,rgbkrk/react,arush/react,aickin/react,gpbl/react,salzhrani/react,dmitriiabramov/react,skyFi/react,staltz/react,joshblack/react,jzmq/react,sugarshin/react,ramortegui/react,dittos/react,VioletLife/react,spt110/react,jorrit/react,negativetwelve/react,elquatro/react,salzhrani/react,niubaba63/react,TheBlasfem/react,Riokai/react,terminatorheart/react,kay-is/react,chippieTV/react,IndraVikas/react,phillipalexander/react,linmic/react,sarvex/react,leohmoraes/react,musofan/react,salier/react,brillantesmanuel/react,airondumael/react,haoxutong/react,tywinstark/react,isathish/react,flipactual/react,lonely8rain/react,salzhrani/react,jessebeach/react,prometheansacrifice/react,gitoneman/react,gxr1020/react,flarnie/react,syranide/react,ridixcr/react,ericyang321/react,trellowebinars/react,iamchenxin/react,linqingyicen/react,jedwards1211/react,ArunTesco/react,wmydz1/react,greysign/react,yabhis/react,jquense/react,liyayun/react,yangshun/react,yulongge/react,ljhsai/react,felixgrey/react,anushreesubramani/react,albulescu/react,yabhis/react,silvestrijonathan/react,roylee0704/react,quip/react,gpazo/react,joecritch/react,lonely8rain/react,zilaiyedaren/react,cody/react,bleyle/react,joe-strummer/react,andrerpena/react,spt110/react,wangyzyoga/react,mgmcdermott/react,Rafe/react,IndraVikas/react,james4388/react,AnSavvides/react,VioletLife/react,Diaosir/react,chrisbolin/react,ABaldwinHunter/react-engines,cinic/react,silvestrijonathan/react,lucius-feng/react,camsong/react,stardev24/react,mardigtch/react,scottburch/react,jdlehman/react,yungsters/react,ssyang0102/react,afc163/react,andrescarceller/react,leexiaosi/react,evilemon/react,evilemon/react,it33/react,wmydz1/react,richiethomas/react,facebook/react,it33/react,darobin/react,yiminghe/react,zs99/react,gold3bear/react,neusc/react,yungsters/react,stanleycyang/react,digideskio/react,Galactix/react,cpojer/react,speedyGonzales/react,Furzikov/react,jquense/react,albulescu/react,cpojer/react,iamchenxin/react,trellowebinars/react,edmellum/react,trueadm/react,wjb12/react,joe-strummer/react,inuscript/react,cpojer/react,jessebeach/react,felixgrey/react,cmfcmf/react,pyitphyoaung/react,zofuthan/react,sarvex/react,mosoft521/react,camsong/react,acdlite/react,Simek/react,bhamodi/react,spt110/react,Diaosir/react,yhagio/react,8398a7/react,tom-wang/react,sergej-kucharev/react,miaozhirui/react,leeleo26/react,bleyle/react,krasimir/react,brillantesmanuel/react,bhamodi/react,billfeller/react,evilemon/react,maxschmeling/react,willhackett/react,dmatteo/react,deepaksharmacse12/react,sergej-kucharev/react,bleyle/react,spt110/react,brian-murray35/react,lennerd/react,temnoregg/react,scottburch/react,ledrui/react,slongwang/react,zorojean/react,concerned3rdparty/react,mosoft521/react,Duc-Ngo-CSSE/react,iOSDevBlog/react,kamilio/react,skomski/react,maxschmeling/react,mosoft521/react,hejld/react,supriyantomaftuh/react,patryknowak/react,dittos/react,Chiens/react,conorhastings/react,BreemsEmporiumMensToiletriesFragrances/react,guoshencheng/react,lonely8rain/react,stanleycyang/react,temnoregg/react,salier/react,ljhsai/react,blue68/react,zyt01/react,tomv564/react,sasumi/react,6feetsong/react,gpazo/react,jorrit/react,rohannair/react,zilaiyedaren/react,mohitbhatia1994/react,musofan/react,acdlite/react,shadowhunter2/react,ssyang0102/react,wudouxingjun/react,facebook/react,pswai/react,ipmobiletech/react,davidmason/react,getshuvo/react,shadowhunter2/react,gitignorance/react,richiethomas/react,TaaKey/react,alvarojoao/react,BorderTravelerX/react,zhengqiangzi/react,billfeller/react,isathish/react,Jyrno42/react,lina/react,miaozhirui/react,k-cheng/react,terminatorheart/react,zofuthan/react,eoin/react,dilidili/react,mjackson/react,pdaddyo/react,quip/react,jessebeach/react,PeterWangPo/react,kaushik94/react,labs00/react,billfeller/react,TheBlasfem/react,reggi/react,ianb/react,christer155/react,jdlehman/react,facebook/react,joecritch/react,jordanpapaleo/react,supriyantomaftuh/react,Chiens/react,insionng/react,tomocchino/react,jzmq/react,flowbywind/react,sitexa/react,Spotinux/react,wushuyi/react,wangyzyoga/react,huanglp47/react,andrerpena/react,kieranjones/react,gajus/react,jfschwarz/react,anushreesubramani/react,prometheansacrifice/react,gfogle/react,Simek/react,vincentnacar02/react,inuscript/react,ashwin01/react,reactjs-vn/reactjs_vndev,soulcm/react,silppuri/react,perterest/react,zhengqiangzi/react,jedwards1211/react,edvinerikson/react,empyrical/react,jabhishek/react,jagdeesh109/react,tlwirtz/react,yiminghe/react,Nieralyte/react,jimfb/react,JanChw/react,with-git/react,mohitbhatia1994/react,1yvT0s/react,nomanisan/react,kamilio/react,jdlehman/react,anushreesubramani/react,Riokai/react,zhangwei001/react,joecritch/react,jameszhan/react,Spotinux/react,misnet/react,garbles/react,greyhwndz/react,venkateshdaram434/react,honger05/react,microlv/react,alvarojoao/react,AmericanSundown/react,marocchino/react,Chiens/react,brigand/react,stevemao/react | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var mocks = require('mocks');
describe('ReactMount', function() {
var React = require('React');
var ReactMount = require('ReactMount');
var ReactTestUtils = require('ReactTestUtils');
var WebComponents = WebComponents;
try {
if (WebComponents === undefined && typeof jest !== 'undefined') {
WebComponents = require('WebComponents');
}
} catch(e) {
// Parse error expected on engines that don't support setters
// or otherwise aren't supportable by the polyfill.
// Leave WebComponents undefined.
}
describe('unmountComponentAtNode', function() {
it('throws when given a non-node', function() {
var nodeArray = document.getElementsByTagName('div');
expect(function() {
React.unmountComponentAtNode(nodeArray);
}).toThrow(
'Invariant Violation: unmountComponentAtNode(...): Target container ' +
'is not a DOM element.'
);
});
});
it('throws when given a string', function() {
expect(function() {
ReactTestUtils.renderIntoDocument('div');
}).toThrow(
'Invariant Violation: React.render(): Invalid component element. ' +
'Instead of passing an element string, make sure to instantiate it ' +
'by passing it to React.createElement.'
);
});
it('throws when given a factory', function() {
var Component = React.createClass({
render: function() {
return <div />;
},
});
expect(function() {
ReactTestUtils.renderIntoDocument(Component);
}).toThrow(
'Invariant Violation: React.render(): Invalid component element. ' +
'Instead of passing a component class, make sure to instantiate it ' +
'by passing it to React.createElement.'
);
});
it('should render different components in same root', function() {
var container = document.createElement('container');
document.body.appendChild(container);
ReactMount.render(<div></div>, container);
expect(container.firstChild.nodeName).toBe('DIV');
ReactMount.render(<span></span>, container);
expect(container.firstChild.nodeName).toBe('SPAN');
});
it('should unmount and remount if the key changes', function() {
var container = document.createElement('container');
var mockMount = mocks.getMockFunction();
var mockUnmount = mocks.getMockFunction();
var Component = React.createClass({
componentDidMount: mockMount,
componentWillUnmount: mockUnmount,
render: function() {
return <span>{this.props.text}</span>;
},
});
expect(mockMount.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0);
ReactMount.render(<Component text="orange" key="A" />, container);
expect(container.firstChild.innerHTML).toBe('orange');
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0);
// If we change the key, the component is unmounted and remounted
ReactMount.render(<Component text="green" key="B" />, container);
expect(container.firstChild.innerHTML).toBe('green');
expect(mockMount.mock.calls.length).toBe(2);
expect(mockUnmount.mock.calls.length).toBe(1);
// But if we don't change the key, the component instance is reused
ReactMount.render(<Component text="blue" key="B" />, container);
expect(container.firstChild.innerHTML).toBe('blue');
expect(mockMount.mock.calls.length).toBe(2);
expect(mockUnmount.mock.calls.length).toBe(1);
});
it('should reuse markup if rendering to the same target twice', function() {
var container = document.createElement('container');
var instance1 = React.render(<div />, container);
var instance2 = React.render(<div />, container);
expect(instance1 === instance2).toBe(true);
});
it('should warn if mounting into dirty rendered markup', function() {
var container = document.createElement('container');
container.innerHTML = React.renderToString(<div />) + ' ';
spyOn(console, 'error');
ReactMount.render(<div />, container);
expect(console.error.calls.length).toBe(1);
container.innerHTML = ' ' + React.renderToString(<div />);
ReactMount.render(<div />, container);
expect(console.error.calls.length).toBe(2);
});
it('should not warn if mounting into non-empty node', function() {
var container = document.createElement('container');
container.innerHTML = '<div></div>';
spyOn(console, 'error');
ReactMount.render(<div />, container);
expect(console.error.calls.length).toBe(0);
});
it('should warn when mounting into document.body', function () {
var iFrame = document.createElement('iframe');
document.body.appendChild(iFrame);
spyOn(console, 'error');
ReactMount.render(<div />, iFrame.contentDocument.body);
expect(console.error.calls.length).toBe(1);
expect(console.error.calls[0].args[0]).toContain(
'Rendering components directly into document.body is discouraged'
);
});
it('should account for escaping on a checksum mismatch', function () {
var div = document.createElement('div');
var markup = React.renderToString(
<div>This markup contains an nbsp entity: server text</div>);
div.innerHTML = markup;
spyOn(console, 'error');
React.render(
<div>This markup contains an nbsp entity: client text</div>,
div
);
expect(console.error.calls.length).toBe(1);
expect(console.error.calls[0].args[0]).toContain(
' (client) nbsp entity: client text</div>\n' +
' (server) nbsp entity: server text</div>'
);
});
if (WebComponents !== undefined) {
it('should allow mounting/unmounting to document fragment container',
function() {
var shadowRoot;
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
shadowRoot = this.createShadowRoot();
React.render(<div>Hi, from within a WC!</div>, shadowRoot);
expect(shadowRoot.firstChild.tagName).toBe('DIV');
React.render(<span>Hi, from within a WC!</span>, shadowRoot);
expect(shadowRoot.firstChild.tagName).toBe('SPAN');
},
},
});
proto.unmount = function() {
React.unmountComponentAtNode(shadowRoot);
};
document.registerElement('x-foo', {prototype: proto});
var element = document.createElement('x-foo');
element.unmount();
});
}
});
| src/renderers/dom/client/__tests__/ReactMount-test.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var mocks = require('mocks');
describe('ReactMount', function() {
var React = require('React');
var ReactMount = require('ReactMount');
var ReactTestUtils = require('ReactTestUtils');
var WebComponents = WebComponents;
try {
if (WebComponents === undefined && typeof jest !== 'undefined') {
WebComponents = require('WebComponents');
}
} catch(e) {
// Parse error expected on engines that don't support setters
// or otherwise aren't supportable by the polyfill.
// Leave WebComponents undefined.
}
describe('unmountComponentAtNode', function() {
it('throws when given a non-node', function() {
var nodeArray = document.getElementsByTagName('div');
expect(function() {
React.unmountComponentAtNode(nodeArray);
}).toThrow(
'Invariant Violation: unmountComponentAtNode(...): Target container ' +
'is not a DOM element.'
);
});
});
it('throws when given a string', function() {
expect(function() {
ReactTestUtils.renderIntoDocument('div');
}).toThrow(
'Invariant Violation: React.render(): Invalid component element. ' +
'Instead of passing an element string, make sure to instantiate it ' +
'by passing it to React.createElement.'
);
});
it('throws when given a factory', function() {
var Component = React.createClass({
render: function() {
return <div />;
},
});
expect(function() {
ReactTestUtils.renderIntoDocument(Component);
}).toThrow(
'Invariant Violation: React.render(): Invalid component element. ' +
'Instead of passing a component class, make sure to instantiate it ' +
'by passing it to React.createElement.'
);
});
it('should render different components in same root', function() {
var container = document.createElement('container');
document.body.appendChild(container);
ReactMount.render(<div></div>, container);
expect(container.firstChild.nodeName).toBe('DIV');
ReactMount.render(<span></span>, container);
expect(container.firstChild.nodeName).toBe('SPAN');
});
it('should unmount and remount if the key changes', function() {
var container = document.createElement('container');
var mockMount = mocks.getMockFunction();
var mockUnmount = mocks.getMockFunction();
var Component = React.createClass({
componentDidMount: mockMount,
componentWillUnmount: mockUnmount,
render: function() {
return <span>{this.props.text}</span>;
},
});
expect(mockMount.mock.calls.length).toBe(0);
expect(mockUnmount.mock.calls.length).toBe(0);
ReactMount.render(<Component text="orange" key="A" />, container);
expect(container.firstChild.innerHTML).toBe('orange');
expect(mockMount.mock.calls.length).toBe(1);
expect(mockUnmount.mock.calls.length).toBe(0);
// If we change the key, the component is unmounted and remounted
ReactMount.render(<Component text="green" key="B" />, container);
expect(container.firstChild.innerHTML).toBe('green');
expect(mockMount.mock.calls.length).toBe(2);
expect(mockUnmount.mock.calls.length).toBe(1);
// But if we don't change the key, the component instance is reused
ReactMount.render(<Component text="blue" key="B" />, container);
expect(container.firstChild.innerHTML).toBe('blue');
expect(mockMount.mock.calls.length).toBe(2);
expect(mockUnmount.mock.calls.length).toBe(1);
});
it('should reuse markup if rendering to the same target twice', function() {
var container = document.createElement('container');
var instance1 = React.render(<div />, container);
var instance2 = React.render(<div />, container);
expect(instance1 === instance2).toBe(true);
});
it('should warn if mounting into dirty rendered markup', function() {
var container = document.createElement('container');
container.innerHTML = React.renderToString(<div />) + ' ';
spyOn(console, 'error');
ReactMount.render(<div />, container);
expect(console.error.calls.length).toBe(1);
container.innerHTML = ' ' + React.renderToString(<div />);
ReactMount.render(<div />, container);
expect(console.error.calls.length).toBe(2);
});
it('should not warn if mounting into non-empty node', function() {
var container = document.createElement('container');
container.innerHTML = '<div></div>';
spyOn(console, 'error');
ReactMount.render(<div />, container);
expect(console.error.calls.length).toBe(0);
});
it('should warn when mounting into document.body', function () {
var iFrame = document.createElement('iframe');
document.body.appendChild(iFrame);
spyOn(console, 'error');
ReactMount.render(<div />, iFrame.contentDocument.body);
expect(console.error.calls.length).toBe(1);
expect(console.error.calls[0].args[0]).toContain(
'Rendering components directly into document.body is discouraged'
);
});
it('should account for escaping on a checksum mismatch', function () {
var div = document.createElement('div');
var markup = React.renderToString(
<div>This markup contains an html entity: & server text</div>);
div.innerHTML = markup;
spyOn(console, 'error');
React.render(
<div>This markup contains an html entity: & client text</div>, div);
expect(console.error.calls.length).toBe(1);
expect(console.error.calls[0].args[0]).toContain(
' (client) html entity: & client text</div>\n' +
' (server) html entity: & server text</div>'
);
});
if (WebComponents !== undefined) {
it('should allow mounting/unmounting to document fragment container',
function() {
var shadowRoot;
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
shadowRoot = this.createShadowRoot();
React.render(<div>Hi, from within a WC!</div>, shadowRoot);
expect(shadowRoot.firstChild.tagName).toBe('DIV');
React.render(<span>Hi, from within a WC!</span>, shadowRoot);
expect(shadowRoot.firstChild.tagName).toBe('SPAN');
},
},
});
proto.unmount = function() {
React.unmountComponentAtNode(shadowRoot);
};
document.registerElement('x-foo', {prototype: proto});
var element = document.createElement('x-foo');
element.unmount();
});
}
});
| Use a test case that demonstrates the fix.
| src/renderers/dom/client/__tests__/ReactMount-test.js | Use a test case that demonstrates the fix. | <ide><path>rc/renderers/dom/client/__tests__/ReactMount-test.js
<ide> it('should account for escaping on a checksum mismatch', function () {
<ide> var div = document.createElement('div');
<ide> var markup = React.renderToString(
<del> <div>This markup contains an html entity: & server text</div>);
<add> <div>This markup contains an nbsp entity: server text</div>);
<ide> div.innerHTML = markup;
<ide>
<ide> spyOn(console, 'error');
<ide> React.render(
<del> <div>This markup contains an html entity: & client text</div>, div);
<add> <div>This markup contains an nbsp entity: client text</div>,
<add> div
<add> );
<ide> expect(console.error.calls.length).toBe(1);
<ide> expect(console.error.calls[0].args[0]).toContain(
<del> ' (client) html entity: & client text</div>\n' +
<del> ' (server) html entity: & server text</div>'
<add> ' (client) nbsp entity: client text</div>\n' +
<add> ' (server) nbsp entity: server text</div>'
<ide> );
<ide> });
<ide> |
|
Java | bsd-3-clause | 5fc52fe87ba0e8b47c3f8085ca753b9fabb7dc53 | 0 | CBIIT/common-security-module,NCIP/common-security-module,CBIIT/common-security-module,CBIIT/common-security-module,NCIP/common-security-module,NCIP/common-security-module,NCIP/common-security-module,CBIIT/common-security-module,CBIIT/common-security-module | // PrivilegeTest.java
package test.gov.nih.nci.security.authorization.domainobjects;
import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.Privilege;
import gov.nih.nci.security.dao.hibernate.HibernateSessionFactory;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
/**
* PrivilegeTest (Copyright 2001 Your Company)
*
* <p>
* This class performs unit tests on
* gov.nih.nci.security.authorization.domainobjects.Privilege
* </p>
*
* <p>
* Explanation about the tested class and its responsibilities
* </p>
*
* <p>
* Relations: Privilege extends java.lang.Object <br>
*
* @author Your Name Your email - Your Company
* @date $Date: 2004-12-13 22:26:05 $
* @version $Revision: 1.2 $
*
* @see gov.nih.nci.security.authorization.domainobjects.Privilege
* @see some.other.package
*/
public class PrivilegeTest extends TestCase {
/**
* Constructor (needed for JTest)
*
* @param name
* Name of Object
*/
public PrivilegeTest(String name) {
super(name);
}
public void testCreateAndDelete() throws Exception {
Privilege p = create();
delete(p);
}
protected Privilege create() throws Exception {
UserProvisioningManager upm = SecurityServiceProvider
.getUserProvisioningManger("Security");
Privilege p = new Privilege();
p.setName("ReadTest123");
p.setDesc("Reading test123");
upm.createPrivilege(p);
System.out.println("Created privilege with id: " + p.getId());
return p;
}
private void delete(Privilege p) throws Exception {
UserProvisioningManager upm = SecurityServiceProvider
.getUserProvisioningManger("security");
upm.removePrivilege("" + p.getId());
System.out.println( "Deleted privilege: " + p.getId());
}
/**
* Main method needed to make a self runnable class
*
* @param args
* This is required for main method
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(new TestSuite(PrivilegeTest.class));
}
} | api/src/test/gov/nih/nci/security/authorization/domainobjects/PrivilegeTest.java | // PrivilegeTest.java
package test.gov.nih.nci.security.authorization.domainobjects;
import gov.nih.nci.security.authorization.domainobjects.Privilege;
import gov.nih.nci.security.dao.hibernate.HibernateSessionFactory;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
/**
* PrivilegeTest (Copyright 2001 Your Company)
*
* <p>
* This class performs unit tests on
* gov.nih.nci.security.authorization.domainobjects.Privilege
* </p>
*
* <p>
* Explanation about the tested class and its responsibilities
* </p>
*
* <p>
* Relations: Privilege extends java.lang.Object <br>
*
* @author Your Name Your email - Your Company
* @date $Date: 2004-12-07 21:35:04 $
* @version $Revision: 1.1 $
*
* @see gov.nih.nci.security.authorization.domainobjects.Privilege
* @see some.other.package
*/
public class PrivilegeTest extends TestCase {
/**
* Constructor (needed for JTest)
*
* @param name
* Name of Object
*/
public PrivilegeTest(String name) {
super(name);
}
/**
* Used by JUnit (called before each test method)
*/
protected void setUp() {
//privilege = new Privilege();
}
/**
* Used by JUnit (called after each test method)
*/
protected void tearDown() {
privilege = null;
}
/**
* Test the constructor: Privilege()
*/
public void testPrivilege() {
}
/**
* Test method: void finalize() finalize throws java.lang.Throwable
*/
public void testFinalize() {
}
/**
* Test method: String getName()
*/
public void testGetName() {
}
/**
* Test method: void setName(String)
*/
public void testSetName() {
//Must test for the following parameters!
String str[] = { null, "\u0000", " " };
}
/**
* Test method: String getDesc()
*/
public void testGetDesc() {
}
/**
* Test method: java.lang.Long getId()
*/
public void testGetId() {
}
/**
* Test method: void setDesc(String)
*/
public void testSetDesc() {
//Must test for the following parameters!
String str[] = { null, "\u0000", " " };
}
/**
* Test method: void setId(Long)
*/
public void testSetId() {
//Must test for the following parameters!
//Long;
}
public void testCreate() throws Exception {
Session s = null;
Transaction t = null;
System.out.println("Running create test...");
try {
s = HibernateSessionFactory.currentSession();
t = s.beginTransaction();
Privilege p = new Privilege();
p.setDesc("TestDesc");
p.setName("TestName");
s.save(p);
t.commit();
System.out.println( "Privilege ID is: " + p.getId().doubleValue() );
} catch (Exception ex) {
try {
s.close();
} catch (Exception ex2) {
}
try {
t.rollback();
} catch (Exception ex3) {
}
throw ex;
}
}
/**
* Main method needed to make a self runnable class
*
* @param args
* This is required for main method
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(new TestSuite(PrivilegeTest.class));
}
private Privilege privilege;
} | modified to use the Manager
SVN-Revision: 185
| api/src/test/gov/nih/nci/security/authorization/domainobjects/PrivilegeTest.java | modified to use the Manager | <ide><path>pi/src/test/gov/nih/nci/security/authorization/domainobjects/PrivilegeTest.java
<ide>
<ide> package test.gov.nih.nci.security.authorization.domainobjects;
<ide>
<add>import gov.nih.nci.security.SecurityServiceProvider;
<add>import gov.nih.nci.security.UserProvisioningManager;
<ide> import gov.nih.nci.security.authorization.domainobjects.Privilege;
<ide> import gov.nih.nci.security.dao.hibernate.HibernateSessionFactory;
<ide> import junit.framework.TestCase;
<ide> * Relations: Privilege extends java.lang.Object <br>
<ide> *
<ide> * @author Your Name Your email - Your Company
<del> * @date $Date: 2004-12-07 21:35:04 $
<del> * @version $Revision: 1.1 $
<add> * @date $Date: 2004-12-13 22:26:05 $
<add> * @version $Revision: 1.2 $
<ide> *
<ide> * @see gov.nih.nci.security.authorization.domainobjects.Privilege
<ide> * @see some.other.package
<ide> super(name);
<ide> }
<ide>
<del> /**
<del> * Used by JUnit (called before each test method)
<del> */
<del> protected void setUp() {
<del> //privilege = new Privilege();
<del> }
<add>
<ide>
<del> /**
<del> * Used by JUnit (called after each test method)
<del> */
<del> protected void tearDown() {
<del> privilege = null;
<del> }
<add> public void testCreateAndDelete() throws Exception {
<ide>
<del> /**
<del> * Test the constructor: Privilege()
<del> */
<del> public void testPrivilege() {
<add> Privilege p = create();
<add> delete(p);
<ide>
<ide> }
<ide>
<del> /**
<del> * Test method: void finalize() finalize throws java.lang.Throwable
<del> */
<del> public void testFinalize() {
<add> protected Privilege create() throws Exception {
<add> UserProvisioningManager upm = SecurityServiceProvider
<add> .getUserProvisioningManger("Security");
<add>
<add> Privilege p = new Privilege();
<add> p.setName("ReadTest123");
<add> p.setDesc("Reading test123");
<add>
<add> upm.createPrivilege(p);
<add> System.out.println("Created privilege with id: " + p.getId());
<add>
<add> return p;
<ide>
<ide> }
<ide>
<del> /**
<del> * Test method: String getName()
<del> */
<del> public void testGetName() {
<add> private void delete(Privilege p) throws Exception {
<ide>
<del> }
<add> UserProvisioningManager upm = SecurityServiceProvider
<add> .getUserProvisioningManger("security");
<ide>
<del> /**
<del> * Test method: void setName(String)
<del> */
<del> public void testSetName() {
<del> //Must test for the following parameters!
<del> String str[] = { null, "\u0000", " " };
<del>
<del> }
<del>
<del> /**
<del> * Test method: String getDesc()
<del> */
<del> public void testGetDesc() {
<del>
<del> }
<del>
<del> /**
<del> * Test method: java.lang.Long getId()
<del> */
<del> public void testGetId() {
<del>
<del> }
<del>
<del> /**
<del> * Test method: void setDesc(String)
<del> */
<del> public void testSetDesc() {
<del> //Must test for the following parameters!
<del> String str[] = { null, "\u0000", " " };
<del>
<del> }
<del>
<del> /**
<del> * Test method: void setId(Long)
<del> */
<del> public void testSetId() {
<del> //Must test for the following parameters!
<del> //Long;
<del>
<del> }
<del>
<del> public void testCreate() throws Exception {
<del> Session s = null;
<del> Transaction t = null;
<del> System.out.println("Running create test...");
<del> try {
<del> s = HibernateSessionFactory.currentSession();
<del>
<del> t = s.beginTransaction();
<del> Privilege p = new Privilege();
<del>
<del> p.setDesc("TestDesc");
<del> p.setName("TestName");
<del> s.save(p);
<del> t.commit();
<del> System.out.println( "Privilege ID is: " + p.getId().doubleValue() );
<del> } catch (Exception ex) {
<del> try {
<del> s.close();
<del> } catch (Exception ex2) {
<del> }
<del> try {
<del> t.rollback();
<del> } catch (Exception ex3) {
<del> }
<del> throw ex;
<del> }
<del>
<add> upm.removePrivilege("" + p.getId());
<add> System.out.println( "Deleted privilege: " + p.getId());
<ide> }
<ide>
<ide> /**
<ide> junit.textui.TestRunner.run(new TestSuite(PrivilegeTest.class));
<ide> }
<ide>
<del> private Privilege privilege;
<add>
<ide> } |
|
JavaScript | mit | de7cf99389a3e3a985ad26b50b0282b9852a34ee | 0 | City-of-Helsinki/helerm-ui,City-of-Helsinki/helerm-ui,City-of-Helsinki/helerm-ui | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators, compose } from 'redux';
import { withRouter, Link } from 'react-router';
import get from 'lodash/get';
import { fetchTOS } from 'components/Tos/reducer';
import { setValidationVisibility } from 'components/Tos/ValidationBar/reducer';
import { getStatusLabel, formatDateTime, getNewPath } from 'utils/helpers';
import MetaDataTable from './MetaDataTable';
import PrintPhase from './PrintPhase';
import './PrintView.scss';
class PrintView extends React.Component {
static BODY_CLASS = 'helerm-tos-print-view';
componentDidMount () {
const {
fetchTOS,
TOS,
hideNavigation,
params: { id, version }
} = this.props;
this.addBodyClass();
hideNavigation();
const tosAvailable = TOS.id === id && (!version || TOS.version === version);
if (!tosAvailable) {
let params = {};
if (typeof version !== 'undefined') {
params.version = version;
}
fetchTOS(id, params);
}
}
componentWillUnmount () {
this.removeBodyClass();
}
addBodyClass () {
if (document.body) {
document.body.className = document.body.className + PrintView.BODY_CLASS;
}
}
removeBodyClass () {
if (document.body) {
document.body.className = document.body.className.replace(
PrintView.BODY_CLASS,
''
);
}
}
render () {
const { TOS, getAttributeName, sortAttributeKeys, location } = this.props;
if (!TOS.id) return null;
return (
<article>
<header>
<div className='no-print btn-group'>
<Link
className='btn btn-primary'
to={getNewPath(location.pathname, '..')}
>
Takaisin <i className='fa fa-close' />
</Link>
<button
type='button'
className='btn btn-success'
onClick={window.print}
>
Tulosta <i className='fa fa-print' />
</button>
</div>
<h1>
{TOS.function_id} {TOS.name}
</h1>
</header>
<MetaDataTable
rows={[
['Versionumero', TOS.version.toString()],
['Tila', getStatusLabel(TOS.status)],
['Muokkausajankohta', formatDateTime(TOS.modified_at)],
['Muokkaaja', TOS.modified_by],
...sortAttributeKeys(Object.keys(TOS.attributes)).map(key => [
getAttributeName(key),
TOS.attributes[key]
])
]}
/>
{Object.keys(TOS.phases).map(key => (
<PrintPhase
key={TOS.phases[key].id}
phase={TOS.phases[key]}
getAttributeName={getAttributeName}
sortAttributeKeys={sortAttributeKeys}
/>
))}
</article>
);
}
}
PrintView.propTypes = {
TOS: PropTypes.object,
fetchTOS: PropTypes.func.isRequired,
getAttributeName: PropTypes.func.isRequired,
hideNavigation: PropTypes.func.isRequired,
location: PropTypes.object.isRequired,
params: PropTypes.object,
sortAttributeKeys: PropTypes.func.isRequired
};
const denormalizeTOS = tos => ({
...tos,
phases: Object.values(tos.phases)
.sort((a, b) => a.index - b.inded)
.map(phase => ({
...phase,
actions: phase.actions.map(actionKey => {
const action = tos.actions[actionKey];
return {
...action,
records: action.records.map(recordKey => tos.records[recordKey])
};
})
}))
});
const mapStateToProps = state => ({
TOS: denormalizeTOS(state.selectedTOS),
getAttributeName: key => get(state.ui.attributeTypes, [key, 'name'], key),
sortAttributeKeys: keys =>
keys.sort(key => get(state.ui.attributeTypes, [key, 'index'], Infinity))
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
fetchTOS,
hideNavigation: () => setValidationVisibility(false)
},
dispatch
);
export default compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps)
)(PrintView);
| src/components/Tos/Print/PrintView.js | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators, compose } from 'redux';
import { withRouter, Link } from 'react-router';
import get from 'lodash/get';
import { fetchTOS } from 'components/Tos/reducer';
import { setValidationVisibility } from 'components/Tos/ValidationBar/reducer';
import { getStatusLabel, formatDateTime, getNewPath } from 'utils/helpers';
import MetaDataTable from './MetaDataTable';
import PrintPhase from './PrintPhase';
import './PrintView.scss';
class PrintView extends React.Component {
static BODY_CLASS = 'helerm-tos-print-view';
componentDidMount () {
const { fetchTOS, TOS, hideNavigation, params: { id } } = this.props;
this.addBodyClass();
hideNavigation();
const tosAvailable = TOS.id === id;
if (!tosAvailable) {
fetchTOS(id);
}
}
componentWillUnmount () {
this.removeBodyClass();
}
addBodyClass () {
if (document.body) {
document.body.className = document.body.className + PrintView.BODY_CLASS;
}
}
removeBodyClass () {
if (document.body) {
document.body.className = document.body.className.replace(
PrintView.BODY_CLASS,
''
);
}
}
render () {
const { TOS, getAttributeName, sortAttributeKeys, location } = this.props;
if (!TOS.id) return null;
return (
<article>
<header>
<div className='no-print btn-group'>
<Link
className='btn btn-primary'
to={getNewPath(location.pathname, '..')}
>
Takaisin <i className='fa fa-close' />
</Link>
<button
type='button'
className='btn btn-success'
onClick={window.print}
>
Tulosta <i className='fa fa-print' />
</button>
</div>
<h1>
{TOS.function_id} {TOS.name}
</h1>
</header>
<MetaDataTable
rows={[
['Versionumero', TOS.version.toString()],
['Tila', getStatusLabel(TOS.status)],
['Muokkausajankohta', formatDateTime(TOS.modified_at)],
['Muokkaaja', TOS.modified_by],
...sortAttributeKeys(Object.keys(TOS.attributes)).map(key => [
getAttributeName(key),
TOS.attributes[key]
])
]}
/>
{Object.keys(TOS.phases).map(key => (
<PrintPhase
key={TOS.phases[key].id}
phase={TOS.phases[key]}
getAttributeName={getAttributeName}
sortAttributeKeys={sortAttributeKeys}
/>
))}
</article>
);
}
}
PrintView.propTypes = {
TOS: PropTypes.object,
fetchTOS: PropTypes.func.isRequired,
getAttributeName: PropTypes.func.isRequired,
hideNavigation: PropTypes.func.isRequired,
location: PropTypes.object.isRequired,
params: PropTypes.object,
sortAttributeKeys: PropTypes.func.isRequired
};
const denormalizeTOS = tos => ({
...tos,
phases: Object.values(tos.phases)
.sort((a, b) => a.index - b.inded)
.map(phase => ({
...phase,
actions: phase.actions.map(actionKey => {
const action = tos.actions[actionKey];
return {
...action,
records: action.records.map(recordKey => tos.records[recordKey])
};
})
}))
});
const mapStateToProps = state => ({
TOS: denormalizeTOS(state.selectedTOS),
getAttributeName: key => get(state.ui.attributeTypes, [key, 'name'], key),
sortAttributeKeys: keys =>
keys.sort(key => get(state.ui.attributeTypes, [key, 'index'], Infinity))
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
fetchTOS,
hideNavigation: () => setValidationVisibility(false)
},
dispatch
);
export default compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps)
)(PrintView);
| Fix tos fetching in print view to use version parameter
| src/components/Tos/Print/PrintView.js | Fix tos fetching in print view to use version parameter | <ide><path>rc/components/Tos/Print/PrintView.js
<ide> static BODY_CLASS = 'helerm-tos-print-view';
<ide>
<ide> componentDidMount () {
<del> const { fetchTOS, TOS, hideNavigation, params: { id } } = this.props;
<add> const {
<add> fetchTOS,
<add> TOS,
<add> hideNavigation,
<add> params: { id, version }
<add> } = this.props;
<ide> this.addBodyClass();
<ide> hideNavigation();
<ide>
<del> const tosAvailable = TOS.id === id;
<add> const tosAvailable = TOS.id === id && (!version || TOS.version === version);
<ide> if (!tosAvailable) {
<del> fetchTOS(id);
<add> let params = {};
<add> if (typeof version !== 'undefined') {
<add> params.version = version;
<add> }
<add> fetchTOS(id, params);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 5e3fe8f99264ee797a68e149d0fb5c0a3dcfda09 | 0 | carlphilipp/chicago-commutes,carlphilipp/chicago-commutes,carlphilipp/chicago-commutes | /**
* Copyright 2014 Carl-Philipp Harmant
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cph.chicago.activity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.collections4.MultiMap;
import org.apache.commons.collections4.map.MultiValueMap;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils.TruncateAt;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import fr.cph.chicago.ChicagoTracker;
import fr.cph.chicago.R;
import fr.cph.chicago.connection.CtaConnect;
import fr.cph.chicago.connection.CtaRequestType;
import fr.cph.chicago.connection.GStreetViewConnect;
import fr.cph.chicago.data.DataHolder;
import fr.cph.chicago.data.Preferences;
import fr.cph.chicago.data.TrainData;
import fr.cph.chicago.entity.Eta;
import fr.cph.chicago.entity.Position;
import fr.cph.chicago.entity.Station;
import fr.cph.chicago.entity.Stop;
import fr.cph.chicago.entity.TrainArrival;
import fr.cph.chicago.entity.enumeration.TrainDirection;
import fr.cph.chicago.entity.enumeration.TrainLine;
import fr.cph.chicago.exception.ConnectException;
import fr.cph.chicago.exception.ParserException;
import fr.cph.chicago.exception.TrackerException;
import fr.cph.chicago.util.Util;
import fr.cph.chicago.xml.Xml;
/**
* Activity that represents the train station
*
* @author Carl-Philipp Harmant
* @version 1
*/
public class StationActivity extends Activity {
/** Train data **/
private TrainData data;
/** Train arrival **/
private TrainArrival arrival;
/** The station id **/
private Integer stationId;
/** The station **/
private Station station;
/** Street view image **/
private ImageView streetViewImage;
/** Street view text **/
private TextView streetViewText;
/** Map image **/
private ImageView mapImage;
/** Direction image **/
private ImageView directionImage;
/** Favorite image **/
private ImageView favoritesImage;
/** Is favorite **/
private boolean isFavorite;
/** Map of ids **/
private Map<String, Integer> ids;
/** Params stops **/
private LinearLayout.LayoutParams paramsStop;
/** The menu **/
private Menu menu;
/** The first load **/
private boolean firstLoad = true;
@SuppressWarnings("unchecked")
@Override
protected final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ChicagoTracker.checkData(this);
if (!this.isFinishing()) {
// Load data
DataHolder dataHolder = DataHolder.getInstance();
this.data = dataHolder.getTrainData();
ids = new HashMap<String, Integer>();
// Load right xml
setContentView(R.layout.activity_station);
// Get station id from bundle extra
if (stationId == null) {
stationId = getIntent().getExtras().getInt("stationId");
}
// Get station from station id
station = data.getStation(stationId);
MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
reqParams.put("mapid", String.valueOf(station.getId()));
new LoadData().execute(reqParams);
// Call google street api to load image
new DisplayGoogleStreetPicture().execute(station.getStops().get(0).getPosition());
this.isFavorite = isFavorite();
TextView textView = (TextView) findViewById(R.id.activity_station_station_name);
textView.setText(station.getName().toString());
streetViewImage = (ImageView) findViewById(R.id.activity_station_streetview_image);
streetViewText = (TextView) findViewById(R.id.activity_station_steetview_text);
mapImage = (ImageView) findViewById(R.id.activity_station_map_image);
directionImage = (ImageView) findViewById(R.id.activity_station_map_direction);
int line1PaddingColor = (int) getResources().getDimension(R.dimen.activity_station_stops_line1_padding_color);
int line1PaddingTop = (int) getResources().getDimension(R.dimen.activity_station_stops_line1_padding_top);
favoritesImage = (ImageView) findViewById(R.id.activity_station_favorite_star);
if (isFavorite) {
favoritesImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_active));
}
favoritesImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StationActivity.this.switchFavorite();
}
});
LinearLayout stopsView = (LinearLayout) findViewById(R.id.activity_station_stops);
Map<TrainLine, List<Stop>> stops = station.getStopByLines();
CheckBox checkBox = null;
for (Entry<TrainLine, List<Stop>> e : stops.entrySet()) {
RelativeLayout line1 = new RelativeLayout(this);
line1.setPadding(0, line1PaddingTop, 0, 0);
paramsStop = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
line1.setLayoutParams(paramsStop);
final TrainLine line = e.getKey();
List<Stop> stopss = e.getValue();
Collections.sort(stopss);
TextView textView2 = new TextView(this);
textView2.setText(ChicagoTracker.getAppContext().getResources().getString(R.string.T));
textView2.setTypeface(Typeface.DEFAULT_BOLD);
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
textView2.setTextColor(getResources().getColor(R.color.grey_M_B));
int id = Util.generateViewId();
textView2.setId(id);
textView2.setPadding(0, 0, line1PaddingColor, 0);
line1.addView(textView2);
textView2 = new TextView(this);
textView2.setBackgroundColor(line.getColor());
int id2 = Util.generateViewId();
textView2.setId(id2);
RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(stopsView.getLayoutParams());
layoutParam.addRule(RelativeLayout.RIGHT_OF, id);
layoutParam.addRule(RelativeLayout.ALIGN_BASELINE, id);
layoutParam.width = 15;
textView2.setTextSize(ChicagoTracker.getAppContext().getResources().getDimension(R.dimen.activity_train_line_color));
textView2.setLayoutParams(layoutParam);
line1.addView(textView2);
textView2 = new TextView(this);
textView2.setText(line.toStringWithLine());
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
textView2.setPadding(line1PaddingColor, 0, 0, 0);
textView2.setTextColor(getResources().getColor(R.color.grey));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
layoutParams.addRule(RelativeLayout.ALIGN_BASELINE, id);
layoutParams.addRule(RelativeLayout.RIGHT_OF, id2);
textView2.setLayoutParams(layoutParams);
line1.addView(textView2);
stopsView.addView(line1);
for (final Stop stop : stopss) {
LinearLayout line2 = new LinearLayout(this);
line2.setOrientation(LinearLayout.HORIZONTAL);
line2.setLayoutParams(paramsStop);
checkBox = new CheckBox(this);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Preferences.saveTrainFilter(stationId, line, stop.getDirection(), isChecked);
}
});
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Update timing
MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
reqParams.put("mapid", String.valueOf(station.getId()));
new LoadData().execute(reqParams);
}
});
checkBox.setChecked(Preferences.getTrainFilter(stationId, line, stop.getDirection()));
checkBox.setText(stop.getDirection().toString());
checkBox.setTextColor(getResources().getColor(R.color.grey));
line2.addView(checkBox);
stopsView.addView(line2);
LinearLayout line3 = new LinearLayout(this);
line3.setOrientation(LinearLayout.VERTICAL);
line3.setLayoutParams(paramsStop);
int id3 = Util.generateViewId();
line3.setId(id3);
ids.put(line.toString() + "_" + stop.getDirection().toString(), id3);
stopsView.addView(line3);
}
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
stationId = savedInstanceState.getInt("stationId");
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("stationId", stationId);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public final boolean onCreateOptionsMenu(final Menu menu) {
super.onCreateOptionsMenu(menu);
this.menu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_no_search, menu);
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.setActionView(R.layout.progressbar);
refreshMenuItem.expandActionView();
return true;
}
@SuppressWarnings("unchecked")
@Override
public final boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_refresh:
MenuItem menuItem = item;
menuItem.setActionView(R.layout.progressbar);
menuItem.expandActionView();
MultiMap<String, String> params = new MultiValueMap<String, String>();
List<Integer> favorites = Preferences.getTrainFavorites(ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
for (Integer fav : favorites) {
params.put("mapid", String.valueOf(fav));
}
MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
reqParams.put("mapid", String.valueOf(station.getId()));
new LoadData().execute(reqParams);
Toast.makeText(this, "Refresh...!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Is favorite or not ?
*
* @return if the station is favorite
*/
private boolean isFavorite() {
boolean isFavorite = false;
List<Integer> favorites = Preferences.getTrainFavorites(ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
for (Integer fav : favorites) {
if (fav.intValue() == stationId.intValue()) {
isFavorite = true;
break;
}
}
return isFavorite;
}
/**
* Display google street view image
*
* @author Carl-Philipp Harmant
* @version 1
*/
private final class DisplayGoogleStreetPicture extends AsyncTask<Position, Void, Drawable> {
/** **/
private Position position;
@Override
protected final Drawable doInBackground(final Position... params) {
GStreetViewConnect connect = GStreetViewConnect.getInstance();
try {
this.position = params[0];
return connect.connect(params[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected final void onPostExecute(final Drawable result) {
int height = (int) getResources().getDimension(R.dimen.activity_station_street_map_height);
android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) StationActivity.this.streetViewImage
.getLayoutParams();
ViewGroup.LayoutParams params2 = StationActivity.this.streetViewImage.getLayoutParams();
params2.height = height;
params2.width = params.width;
StationActivity.this.streetViewImage.setLayoutParams(params2);
StationActivity.this.streetViewImage.setImageDrawable(result);
StationActivity.this.streetViewImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = String.format(Locale.ENGLISH, "google.streetview:cbll=%f,%f&cbp=1,180,,0,1&mz=1", position.getLatitude(),
position.getLongitude());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?q=&layer=c&cbll=%f,%f&cbp=11,0,0,0,0",
position.getLatitude(), position.getLongitude());
Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(unrestrictedIntent);
}
}
});
StationActivity.this.mapImage.setImageDrawable(ChicagoTracker.getAppContext().getResources().getDrawable(R.drawable.da_turn_arrive));
StationActivity.this.mapImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = "http://maps.google.com/maps?z=12&t=m&q=loc:" + position.getLatitude() + "+" + position.getLongitude();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(i);
}
});
StationActivity.this.directionImage.setImageDrawable(ChicagoTracker.getAppContext().getResources()
.getDrawable(R.drawable.ic_directions_walking));
StationActivity.this.directionImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = "http://maps.google.com/?f=d&daddr=" + position.getLatitude() + "," + position.getLongitude() + "&dirflg=w";
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(i);
}
});
StationActivity.this.streetViewText.setText(ChicagoTracker.getAppContext().getResources()
.getString(R.string.station_activity_street_view));
if (menu != null) {
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.collapseActionView();
refreshMenuItem.setActionView(null);
}
firstLoad = false;
}
}
/**
* Load train arrivals
*
* @author Carl-Philipp Harmant
* @version 1
*/
private class LoadData extends AsyncTask<MultiMap<String, String>, Void, TrainArrival> {
/** The exception that might be thrown **/
private TrackerException trackerException;
@Override
protected final TrainArrival doInBackground(final MultiMap<String, String>... params) {
// Get menu item and put it to loading mod
publishProgress((Void[]) null);
SparseArray<TrainArrival> arrivals = new SparseArray<TrainArrival>();
CtaConnect connect = CtaConnect.getInstance();
try {
Xml xml = new Xml();
String xmlResult = connect.connect(CtaRequestType.TRAIN_ARRIVALS, params[0]);
// String xmlResult = connectTest();
arrivals = xml.parseArrivals(xmlResult, StationActivity.this.data);
// Apply filters
int index = 0;
while (index < arrivals.size()) {
TrainArrival arri = arrivals.valueAt(index++);
List<Eta> etas = arri.getEtas();
// Sort Eta by arriving time
Collections.sort(etas);
// Copy data into new list to be able to avoid looping on a list that we want to
// modify
List<Eta> etas2 = new ArrayList<Eta>();
etas2.addAll(etas);
int j = 0;
Eta eta = null;
Station station = null;
TrainLine line = null;
TrainDirection direction = null;
for (int i = 0; i < etas2.size(); i++) {
eta = etas2.get(i);
station = eta.getStation();
line = eta.getRouteName();
direction = eta.getStop().getDirection();
boolean toRemove = Preferences.getTrainFilter(station.getId(), line, direction);
if (!toRemove) {
etas.remove(i - j++);
}
}
}
} catch (ParserException e) {
this.trackerException = e;
} catch (ConnectException e) {
this.trackerException = e;
}
if (arrivals.size() == 1) {
@SuppressWarnings("unchecked")
String id = ((List<String>) params[0].get("mapid")).get(0);
return arrivals.get(Integer.valueOf(id));
} else {
return null;
}
}
@Override
protected final void onProgressUpdate(final Void... values) {
// Get menu item and put it to loading mod
if (menu != null) {
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.setActionView(R.layout.progressbar);
refreshMenuItem.expandActionView();
}
}
@Override
protected final void onPostExecute(final TrainArrival result) {
if (this.trackerException == null) {
arrival = result;
List<Eta> etas;
if (arrival != null) {
etas = arrival.getEtas();
} else {
etas = new ArrayList<Eta>();
}
reset(StationActivity.this.station);
for (Eta eta : etas) {
drawLine3(eta);
}
if (!firstLoad) {
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.collapseActionView();
refreshMenuItem.setActionView(null);
}
} else {
ChicagoTracker.displayError(StationActivity.this, trackerException);
}
}
}
/**
* Reset arrival layouts
*
* @param station
* the station
*/
private final void reset(final Station station) {
Set<TrainLine> setTL = station.getLines();
for (TrainLine tl : setTL) {
for (TrainDirection d : TrainDirection.values()) {
Integer id = ids.get(tl.toString() + "_" + d.toString());
if (id != null) {
LinearLayout line3View = (LinearLayout) findViewById(id);
if (line3View != null) {
line3View.setVisibility(View.GONE);
if (line3View.getChildCount() > 0) {
for (int i = 0; i < line3View.getChildCount(); i++) {
LinearLayout view = (LinearLayout) line3View.getChildAt(i);
TextView timing = (TextView) view.getChildAt(1);
if (timing != null) {
timing.setText("");
}
}
}
}
}
}
}
}
/**
* Draw line
*
* @param eta
* the eta
*/
private final void drawLine3(final Eta eta) {
TrainLine line = eta.getRouteName();
Stop stop = eta.getStop();
int line3Padding = (int) getResources().getDimension(R.dimen.activity_station_stops_line3);
Integer viewId = ids.get(line.toString() + "_" + stop.getDirection().toString());
if (viewId != null) {
LinearLayout line3View = (LinearLayout) findViewById(viewId);
Integer id = ids.get(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName());
if (id == null) {
LinearLayout insideLayout = new LinearLayout(this);
insideLayout.setOrientation(LinearLayout.HORIZONTAL);
insideLayout.setLayoutParams(paramsStop);
int newId = Util.generateViewId();
insideLayout.setId(newId);
ids.put(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName(), newId);
TextView stopName = new TextView(this);
stopName.setText(eta.getDestName() + ": ");
stopName.setTextColor(getResources().getColor(R.color.grey));
stopName.setPadding(line3Padding, 0, 0, 0);
insideLayout.addView(stopName);
TextView timing = new TextView(this);
timing.setText(eta.getTimeLeftDueDelay() + " ");
timing.setTextColor(getResources().getColor(R.color.grey));
timing.setLines(1);
timing.setEllipsize(TruncateAt.END);
insideLayout.addView(timing);
line3View.addView(insideLayout);
} else {
LinearLayout insideLayout = (LinearLayout) findViewById(id);
TextView timing = (TextView) insideLayout.getChildAt(1);
timing.setText(timing.getText() + eta.getTimeLeftDueDelay() + " ");
}
line3View.setVisibility(View.VISIBLE);
}
}
/**
* Add/remove favorites
*/
private final void switchFavorite() {
if (isFavorite) {
Util.removeFromTrainFavorites(stationId, ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
isFavorite = false;
} else {
Util.addToTrainFavorites(stationId, ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
isFavorite = true;
}
if (isFavorite) {
favoritesImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_active));
} else {
favoritesImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_disabled));
}
}
}
| ChicagoTracker/src/fr/cph/chicago/activity/StationActivity.java | /**
* Copyright 2014 Carl-Philipp Harmant
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.cph.chicago.activity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.collections4.MultiMap;
import org.apache.commons.collections4.map.MultiValueMap;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils.TruncateAt;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import fr.cph.chicago.ChicagoTracker;
import fr.cph.chicago.R;
import fr.cph.chicago.connection.CtaConnect;
import fr.cph.chicago.connection.CtaRequestType;
import fr.cph.chicago.connection.GStreetViewConnect;
import fr.cph.chicago.data.DataHolder;
import fr.cph.chicago.data.Preferences;
import fr.cph.chicago.data.TrainData;
import fr.cph.chicago.entity.Eta;
import fr.cph.chicago.entity.Position;
import fr.cph.chicago.entity.Station;
import fr.cph.chicago.entity.Stop;
import fr.cph.chicago.entity.TrainArrival;
import fr.cph.chicago.entity.enumeration.TrainDirection;
import fr.cph.chicago.entity.enumeration.TrainLine;
import fr.cph.chicago.exception.ConnectException;
import fr.cph.chicago.exception.ParserException;
import fr.cph.chicago.exception.TrackerException;
import fr.cph.chicago.util.Util;
import fr.cph.chicago.xml.Xml;
/**
* Activity that represents the train station
*
* @author Carl-Philipp Harmant
* @version 1
*/
public class StationActivity extends Activity {
/** Train data **/
private TrainData data;
/** Train arrival **/
private TrainArrival arrival;
/** The station id **/
private Integer stationId;
/** The station **/
private Station station;
/** Street view image **/
private ImageView streetViewImage;
/** Street view text **/
private TextView streetViewText;
/** Map image **/
private ImageView mapImage;
/** Direction image **/
private ImageView directionImage;
/** Favorite image **/
private ImageView favoritesImage;
/** Is favorite **/
private boolean isFavorite;
/** Map of ids **/
private Map<String, Integer> ids;
/** Params stops **/
private LinearLayout.LayoutParams paramsStop;
/** The menu **/
private Menu menu;
/** The first load **/
private boolean firstLoad = true;
@SuppressWarnings("unchecked")
@Override
protected final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ChicagoTracker.checkData(this);
if (!this.isFinishing()) {
// Load data
DataHolder dataHolder = DataHolder.getInstance();
this.data = dataHolder.getTrainData();
ids = new HashMap<String, Integer>();
// Load right xml
setContentView(R.layout.activity_station);
// Get station id from bundle extra
if (stationId == null) {
stationId = getIntent().getExtras().getInt("stationId");
}
// Get station from station id
station = data.getStation(stationId);
MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
reqParams.put("mapid", String.valueOf(station.getId()));
new LoadData().execute(reqParams);
// Call google street api to load image
new DisplayGoogleStreetPicture().execute(station.getStops().get(0).getPosition());
this.isFavorite = isFavorite();
TextView textView = (TextView) findViewById(R.id.activity_station_station_name);
textView.setText(station.getName().toString());
streetViewImage = (ImageView) findViewById(R.id.activity_station_streetview_image);
streetViewText = (TextView) findViewById(R.id.activity_station_steetview_text);
mapImage = (ImageView) findViewById(R.id.activity_station_map_image);
directionImage = (ImageView) findViewById(R.id.activity_station_map_direction);
int line1PaddingColor = (int) getResources().getDimension(R.dimen.activity_station_stops_line1_padding_color);
int line1PaddingTop = (int) getResources().getDimension(R.dimen.activity_station_stops_line1_padding_top);
favoritesImage = (ImageView) findViewById(R.id.activity_station_favorite_star);
if (isFavorite) {
favoritesImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_active));
}
favoritesImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StationActivity.this.switchFavorite();
}
});
LinearLayout stopsView = (LinearLayout) findViewById(R.id.activity_station_stops);
Map<TrainLine, List<Stop>> stops = station.getStopByLines();
CheckBox checkBox = null;
for (Entry<TrainLine, List<Stop>> e : stops.entrySet()) {
RelativeLayout line1 = new RelativeLayout(this);
line1.setPadding(0, line1PaddingTop, 0, 0);
paramsStop = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
line1.setLayoutParams(paramsStop);
final TrainLine line = e.getKey();
List<Stop> stopss = e.getValue();
Collections.sort(stopss);
TextView textView2 = new TextView(this);
textView2.setText(ChicagoTracker.getAppContext().getResources().getString(R.string.T));
textView2.setTypeface(Typeface.DEFAULT_BOLD);
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
textView2.setTextColor(getResources().getColor(R.color.grey_M_B));
int id = Util.generateViewId();
textView2.setId(id);
textView2.setPadding(0, 0, line1PaddingColor, 0);
line1.addView(textView2);
textView2 = new TextView(this);
textView2.setBackgroundColor(line.getColor());
int id2 = Util.generateViewId();
textView2.setId(id2);
RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(stopsView.getLayoutParams());
layoutParam.addRule(RelativeLayout.RIGHT_OF, id);
layoutParam.addRule(RelativeLayout.ALIGN_BASELINE, id);
layoutParam.width = 15;
textView2.setTextSize(ChicagoTracker.getAppContext().getResources().getDimension(R.dimen.activity_train_line_color));
textView2.setLayoutParams(layoutParam);
line1.addView(textView2);
textView2 = new TextView(this);
textView2.setText(line.toStringWithLine());
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
textView2.setPadding(line1PaddingColor, 0, 0, 0);
textView2.setTextColor(getResources().getColor(R.color.grey));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
layoutParams.addRule(RelativeLayout.ALIGN_BASELINE, id);
layoutParams.addRule(RelativeLayout.RIGHT_OF, id2);
textView2.setLayoutParams(layoutParams);
line1.addView(textView2);
stopsView.addView(line1);
for (final Stop stop : stopss) {
LinearLayout line2 = new LinearLayout(this);
line2.setOrientation(LinearLayout.HORIZONTAL);
line2.setLayoutParams(paramsStop);
checkBox = new CheckBox(this);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Preferences.saveTrainFilter(stationId, line, stop.getDirection(), isChecked);
}
});
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Update timing
MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
reqParams.put("mapid", String.valueOf(station.getId()));
new LoadData().execute(reqParams);
}
});
checkBox.setChecked(Preferences.getTrainFilter(stationId, line, stop.getDirection()));
checkBox.setText(stop.getDirection().toString());
checkBox.setTextColor(getResources().getColor(R.color.grey));
line2.addView(checkBox);
stopsView.addView(line2);
LinearLayout line3 = new LinearLayout(this);
line3.setOrientation(LinearLayout.VERTICAL);
line3.setLayoutParams(paramsStop);
int id3 = Util.generateViewId();
line3.setId(id3);
ids.put(line.toString() + "_" + stop.getDirection().toString(), id3);
stopsView.addView(line3);
}
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
stationId = savedInstanceState.getInt("stationId");
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("stationId", stationId);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public final boolean onCreateOptionsMenu(final Menu menu) {
super.onCreateOptionsMenu(menu);
this.menu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_no_search, menu);
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.setActionView(R.layout.progressbar);
refreshMenuItem.expandActionView();
return true;
}
@SuppressWarnings("unchecked")
@Override
public final boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_refresh:
MenuItem menuItem = item;
menuItem.setActionView(R.layout.progressbar);
menuItem.expandActionView();
MultiMap<String, String> params = new MultiValueMap<String, String>();
List<Integer> favorites = Preferences.getTrainFavorites(ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
for (Integer fav : favorites) {
params.put("mapid", String.valueOf(fav));
}
MultiMap<String, String> reqParams = new MultiValueMap<String, String>();
reqParams.put("mapid", String.valueOf(station.getId()));
new LoadData().execute(reqParams);
Toast.makeText(this, "Refresh...!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Is favorite or not ?
*
* @return if the station is favorite
*/
private boolean isFavorite() {
boolean isFavorite = false;
List<Integer> favorites = Preferences.getTrainFavorites(ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
for (Integer fav : favorites) {
if (fav.intValue() == stationId.intValue()) {
isFavorite = true;
break;
}
}
return isFavorite;
}
/**
* Display google street view image
*
* @author Carl-Philipp Harmant
* @version 1
*/
private final class DisplayGoogleStreetPicture extends AsyncTask<Position, Void, Drawable> {
/** **/
private Position position;
@Override
protected final Drawable doInBackground(final Position... params) {
GStreetViewConnect connect = GStreetViewConnect.getInstance();
try {
this.position = params[0];
return connect.connect(params[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected final void onPostExecute(final Drawable result) {
int height = (int) getResources().getDimension(R.dimen.activity_station_street_map_height);
android.widget.RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) StationActivity.this.streetViewImage
.getLayoutParams();
ViewGroup.LayoutParams params2 = StationActivity.this.streetViewImage.getLayoutParams();
params2.height = height;
params2.width = params.width;
StationActivity.this.streetViewImage.setLayoutParams(params2);
StationActivity.this.streetViewImage.setImageDrawable(result);
StationActivity.this.streetViewImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = String.format(Locale.ENGLISH, "google.streetview:cbll=%f,%f&cbp=1,180,,0,1&mz=1", position.getLatitude(),
position.getLongitude());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?q=&layer=c&cbll=%f,%f&cbp=11,0,0,0,0",
position.getLatitude(), position.getLongitude());
Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(unrestrictedIntent);
}
}
});
StationActivity.this.mapImage.setImageDrawable(ChicagoTracker.getAppContext().getResources().getDrawable(R.drawable.da_turn_arrive));
StationActivity.this.mapImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = "http://maps.google.com/maps?z=12&t=m&q=loc:" + position.getLatitude() + "+" + position.getLongitude();
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(i);
}
});
StationActivity.this.directionImage.setImageDrawable(ChicagoTracker.getAppContext().getResources()
.getDrawable(R.drawable.ic_directions_walking));
StationActivity.this.directionImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = "http://maps.google.com/?f=d&daddr=" + position.getLatitude() + "," + position.getLongitude() + "&dirflg=w";
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
i.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(i);
}
});
StationActivity.this.streetViewText.setText(ChicagoTracker.getAppContext().getResources()
.getString(R.string.station_activity_street_view));
if (menu != null) {
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.collapseActionView();
refreshMenuItem.setActionView(null);
}
firstLoad = false;
}
}
/**
* Load train arrivals
*
* @author Carl-Philipp Harmant
* @version 1
*/
private class LoadData extends AsyncTask<MultiMap<String, String>, Void, TrainArrival> {
/** The exception that might be thrown **/
private TrackerException trackerException;
@Override
protected final TrainArrival doInBackground(final MultiMap<String, String>... params) {
// Get menu item and put it to loading mod
publishProgress((Void[]) null);
SparseArray<TrainArrival> arrivals = new SparseArray<TrainArrival>();
CtaConnect connect = CtaConnect.getInstance();
try {
Xml xml = new Xml();
String xmlResult = connect.connect(CtaRequestType.TRAIN_ARRIVALS, params[0]);
// String xmlResult = connectTest();
arrivals = xml.parseArrivals(xmlResult, StationActivity.this.data);
// Apply filters
int index = 0;
while (index < arrivals.size()) {
TrainArrival arri = arrivals.valueAt(index++);
List<Eta> etas = arri.getEtas();
// Sort Eta by arriving time
Collections.sort(etas);
// Copy data into new list to be able to avoid looping on a list that we want to
// modify
List<Eta> etas2 = new ArrayList<Eta>();
etas2.addAll(etas);
int j = 0;
Eta eta = null;
Station station = null;
TrainLine line = null;
TrainDirection direction = null;
for (int i = 0; i < etas2.size(); i++) {
eta = etas2.get(i);
station = eta.getStation();
line = eta.getRouteName();
direction = eta.getStop().getDirection();
boolean toRemove = Preferences.getTrainFilter(station.getId(), line, direction);
if (!toRemove) {
etas.remove(i - j++);
}
}
}
} catch (ParserException e) {
this.trackerException = e;
} catch (ConnectException e) {
this.trackerException = e;
}
if (arrivals.size() == 1) {
@SuppressWarnings("unchecked")
String id = ((List<String>) params[0].get("mapid")).get(0);
return arrivals.get(Integer.valueOf(id));
} else {
return null;
}
}
@Override
protected final void onProgressUpdate(final Void... values) {
// Get menu item and put it to loading mod
if (menu != null) {
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.setActionView(R.layout.progressbar);
refreshMenuItem.expandActionView();
}
}
@Override
protected final void onPostExecute(final TrainArrival result) {
if (this.trackerException == null) {
arrival = result;
List<Eta> etas;
if (arrival != null) {
etas = arrival.getEtas();
} else {
etas = new ArrayList<Eta>();
}
reset(StationActivity.this.station);
for (Eta eta : etas) {
drawLine3(eta);
}
if (!firstLoad) {
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.collapseActionView();
refreshMenuItem.setActionView(null);
}
} else {
ChicagoTracker.displayError(StationActivity.this, trackerException);
}
}
}
/**
* Reset arrival layouts
*
* @param station
* the station
*/
private final void reset(final Station station) {
Set<TrainLine> setTL = station.getLines();
for (TrainLine tl : setTL) {
for (TrainDirection d : TrainDirection.values()) {
Integer id = ids.get(tl.toString() + "_" + d.toString());
if (id != null) {
LinearLayout line3View = (LinearLayout) findViewById(id);
if (line3View != null) {
line3View.setVisibility(View.GONE);
if (line3View.getChildCount() > 0) {
for (int i = 0; i < line3View.getChildCount(); i++) {
LinearLayout view = (LinearLayout) line3View.getChildAt(i);
TextView timing = (TextView) view.getChildAt(1);
if (timing != null) {
timing.setText("");
}
}
}
}
}
}
}
}
/**
* Draw line
*
* @param eta
* the eta
*/
private final void drawLine3(final Eta eta) {
TrainLine line = eta.getRouteName();
Stop stop = eta.getStop();
int line3Padding = (int) getResources().getDimension(R.dimen.activity_station_stops_line3);
LinearLayout line3View = (LinearLayout) findViewById(ids.get(line.toString() + "_" + stop.getDirection().toString()));
Integer id = ids.get(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName());
if (id == null) {
LinearLayout insideLayout = new LinearLayout(this);
insideLayout.setOrientation(LinearLayout.HORIZONTAL);
insideLayout.setLayoutParams(paramsStop);
int newId = Util.generateViewId();
insideLayout.setId(newId);
ids.put(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName(), newId);
TextView stopName = new TextView(this);
stopName.setText(eta.getDestName() + ": ");
stopName.setTextColor(getResources().getColor(R.color.grey));
stopName.setPadding(line3Padding, 0, 0, 0);
insideLayout.addView(stopName);
TextView timing = new TextView(this);
timing.setText(eta.getTimeLeftDueDelay() + " ");
timing.setTextColor(getResources().getColor(R.color.grey));
timing.setLines(1);
timing.setEllipsize(TruncateAt.END);
insideLayout.addView(timing);
line3View.addView(insideLayout);
} else {
LinearLayout insideLayout = (LinearLayout) findViewById(id);
TextView timing = (TextView) insideLayout.getChildAt(1);
timing.setText(timing.getText() + eta.getTimeLeftDueDelay() + " ");
}
line3View.setVisibility(View.VISIBLE);
}
/**
* Add/remove favorites
*/
private final void switchFavorite() {
if (isFavorite) {
Util.removeFromTrainFavorites(stationId, ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
isFavorite = false;
} else {
Util.addToTrainFavorites(stationId, ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
isFavorite = true;
}
if (isFavorite) {
favoritesImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_active));
} else {
favoritesImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_save_disabled));
}
}
}
| Fixed issue when cta API provide wrong data | ChicagoTracker/src/fr/cph/chicago/activity/StationActivity.java | Fixed issue when cta API provide wrong data | <ide><path>hicagoTracker/src/fr/cph/chicago/activity/StationActivity.java
<ide> TrainLine line = eta.getRouteName();
<ide> Stop stop = eta.getStop();
<ide> int line3Padding = (int) getResources().getDimension(R.dimen.activity_station_stops_line3);
<del> LinearLayout line3View = (LinearLayout) findViewById(ids.get(line.toString() + "_" + stop.getDirection().toString()));
<del>
<del> Integer id = ids.get(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName());
<del> if (id == null) {
<del> LinearLayout insideLayout = new LinearLayout(this);
<del> insideLayout.setOrientation(LinearLayout.HORIZONTAL);
<del> insideLayout.setLayoutParams(paramsStop);
<del> int newId = Util.generateViewId();
<del> insideLayout.setId(newId);
<del> ids.put(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName(), newId);
<del>
<del> TextView stopName = new TextView(this);
<del> stopName.setText(eta.getDestName() + ": ");
<del> stopName.setTextColor(getResources().getColor(R.color.grey));
<del> stopName.setPadding(line3Padding, 0, 0, 0);
<del> insideLayout.addView(stopName);
<del>
<del> TextView timing = new TextView(this);
<del> timing.setText(eta.getTimeLeftDueDelay() + " ");
<del> timing.setTextColor(getResources().getColor(R.color.grey));
<del> timing.setLines(1);
<del> timing.setEllipsize(TruncateAt.END);
<del> insideLayout.addView(timing);
<del>
<del> line3View.addView(insideLayout);
<del> } else {
<del> LinearLayout insideLayout = (LinearLayout) findViewById(id);
<del> TextView timing = (TextView) insideLayout.getChildAt(1);
<del> timing.setText(timing.getText() + eta.getTimeLeftDueDelay() + " ");
<del> }
<del> line3View.setVisibility(View.VISIBLE);
<add> Integer viewId = ids.get(line.toString() + "_" + stop.getDirection().toString());
<add> if (viewId != null) {
<add> LinearLayout line3View = (LinearLayout) findViewById(viewId);
<add>
<add> Integer id = ids.get(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName());
<add> if (id == null) {
<add> LinearLayout insideLayout = new LinearLayout(this);
<add> insideLayout.setOrientation(LinearLayout.HORIZONTAL);
<add> insideLayout.setLayoutParams(paramsStop);
<add> int newId = Util.generateViewId();
<add> insideLayout.setId(newId);
<add> ids.put(line.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName(), newId);
<add>
<add> TextView stopName = new TextView(this);
<add> stopName.setText(eta.getDestName() + ": ");
<add> stopName.setTextColor(getResources().getColor(R.color.grey));
<add> stopName.setPadding(line3Padding, 0, 0, 0);
<add> insideLayout.addView(stopName);
<add>
<add> TextView timing = new TextView(this);
<add> timing.setText(eta.getTimeLeftDueDelay() + " ");
<add> timing.setTextColor(getResources().getColor(R.color.grey));
<add> timing.setLines(1);
<add> timing.setEllipsize(TruncateAt.END);
<add> insideLayout.addView(timing);
<add>
<add> line3View.addView(insideLayout);
<add> } else {
<add> LinearLayout insideLayout = (LinearLayout) findViewById(id);
<add> TextView timing = (TextView) insideLayout.getChildAt(1);
<add> timing.setText(timing.getText() + eta.getTimeLeftDueDelay() + " ");
<add> }
<add> line3View.setVisibility(View.VISIBLE);
<add> }
<ide> }
<ide>
<ide> /** |
|
Java | bsd-2-clause | 8e8a59de203ba755db6a252739bdf735bd07a832 | 0 | thasmin/Podax,thasmin/Podax,thasmin/Podax,thasmin/Podax | package com.axelby.podax.ui;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import com.axelby.podax.Constants;
import com.axelby.podax.R;
import com.axelby.podax.SubscriptionProvider;
import org.acra.ACRA;
public class SubscriptionSettingsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
boolean init = false;
private Uri _subscriptionUri;
private String _feedTitle;
private EditText _name;
private CheckBox _autoName;
private RadioGroup _autoQueue;
private RadioGroup _expiration;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long _subscriptionId = getActivity().getIntent().getLongExtra(Constants.EXTRA_SUBSCRIPTION_ID, -1);
if (_subscriptionId == -1)
_subscriptionId = getArguments().getLong(Constants.EXTRA_SUBSCRIPTION_ID, -1);
if (_subscriptionId == -1)
ACRA.getErrorReporter().handleSilentException(new Exception("subscription settings got a -1"));
_subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, _subscriptionId);
Bundle bundle = new Bundle();
bundle.putLong("id", _subscriptionId);
getLoaderManager().initLoader(0, bundle, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.subscription_settings, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
_name = (EditText) getActivity().findViewById(R.id.name);
_name.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String newTitle = s.toString();
ContentValues values = new ContentValues();
if (newTitle.equals(_feedTitle)) {
values.putNull(SubscriptionProvider.COLUMN_TITLE_OVERRIDE);
_autoName.setChecked(true);
} else {
values.put(SubscriptionProvider.COLUMN_TITLE_OVERRIDE, newTitle);
_autoName.setChecked(false);
}
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
_autoName = (CheckBox) getActivity().findViewById(R.id.nameAuto);
_autoQueue = (RadioGroup) getActivity().findViewById(R.id.autoQueueGroup);
_expiration = (RadioGroup) getActivity().findViewById(R.id.expireGroup);
}
@Override
public void onPause() {
super.onPause();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(_name.getWindowToken(), 0);
}
public void initializeControls() {
_autoName.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton button, boolean checked) {
ContentValues values = new ContentValues();
values.putNull(SubscriptionProvider.COLUMN_TITLE_OVERRIDE);
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
if (checked)
_name.setText(_feedTitle);
}
});
_autoQueue.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
ContentValues values = new ContentValues();
values.put(SubscriptionProvider.COLUMN_QUEUE_NEW, checkedId == R.id.autoQueueYes);
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
}
});
_expiration.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
ContentValues values = new ContentValues();
switch (checkedId) {
case R.id.expire0:
values.putNull(SubscriptionProvider.COLUMN_EXPIRATION);
break;
case R.id.expire7:
values.put(SubscriptionProvider.COLUMN_EXPIRATION, 7);
break;
case R.id.expire14:
values.put(SubscriptionProvider.COLUMN_EXPIRATION, 14);
break;
}
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
}
});
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
String[] projection = {
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_TITLE_OVERRIDE,
SubscriptionProvider.COLUMN_QUEUE_NEW,
SubscriptionProvider.COLUMN_EXPIRATION,
};
long subscriptionId = bundle.getLong("id");
if (subscriptionId == -1)
return null;
Uri uri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId);
return new CursorLoader(getActivity(), uri, projection, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (loader.getId() != 0)
return;
if (init)
return;
init = true;
if (getActivity() == null)
return;
if (!cursor.moveToFirst()) {
cursor.close();
getActivity().finish();
}
_feedTitle = cursor.getString(0);
if (!cursor.isNull(1)) {
_name.setText(cursor.getString(1));
_autoName.setChecked(false);
} else {
_name.setText(_feedTitle);
_autoName.setChecked(true);
}
if (!cursor.isNull(2) && cursor.getInt(2) == 0)
_autoQueue.check(R.id.autoQueueNo);
if (!cursor.isNull(3)) {
switch (cursor.getInt(3)) {
case 7:
_expiration.check(R.id.expire7);
break;
case 14:
_expiration.check(R.id.expire14);
break;
}
}
initializeControls();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
| src/com/axelby/podax/ui/SubscriptionSettingsFragment.java | package com.axelby.podax.ui;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import com.axelby.podax.Constants;
import com.axelby.podax.R;
import com.axelby.podax.SubscriptionProvider;
import org.acra.ACRA;
public class SubscriptionSettingsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
boolean init = false;
private Uri _subscriptionUri;
private String _feedTitle;
private EditText _name;
private CheckBox _autoName;
private RadioGroup _autoQueue;
private RadioGroup _expiration;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long _subscriptionId = getActivity().getIntent().getLongExtra(Constants.EXTRA_SUBSCRIPTION_ID, -1);
if (_subscriptionId == -1)
_subscriptionId = getArguments().getLong(Constants.EXTRA_SUBSCRIPTION_ID, -1);
if (_subscriptionId == -1)
ACRA.getErrorReporter().handleSilentException(new Exception("subscription settings got a -1"));
_subscriptionUri = ContentUris.withAppendedId(SubscriptionProvider.URI, _subscriptionId);
Bundle bundle = new Bundle();
bundle.putLong("id", _subscriptionId);
getLoaderManager().initLoader(0, bundle, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.subscription_settings, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
_name = (EditText) getActivity().findViewById(R.id.name);
_name.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
String newTitle = s.toString();
ContentValues values = new ContentValues();
if (newTitle.equals(_feedTitle)) {
values.putNull(SubscriptionProvider.COLUMN_TITLE_OVERRIDE);
_autoName.setChecked(true);
} else {
values.put(SubscriptionProvider.COLUMN_TITLE_OVERRIDE, newTitle);
_autoName.setChecked(false);
}
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
_autoName = (CheckBox) getActivity().findViewById(R.id.nameAuto);
_autoQueue = (RadioGroup) getActivity().findViewById(R.id.autoQueueGroup);
_expiration = (RadioGroup) getActivity().findViewById(R.id.expireGroup);
}
@Override
public void onPause() {
super.onPause();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(_name.getWindowToken(), 0);
}
public void initializeControls() {
_autoName.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton button, boolean checked) {
ContentValues values = new ContentValues();
values.putNull(SubscriptionProvider.COLUMN_TITLE_OVERRIDE);
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
if (checked)
_name.setText(_feedTitle);
}
});
_autoQueue.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
ContentValues values = new ContentValues();
values.put(SubscriptionProvider.COLUMN_QUEUE_NEW, checkedId == R.id.autoQueueYes);
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
}
});
_expiration.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
ContentValues values = new ContentValues();
switch (checkedId) {
case R.id.expire0:
values.putNull(SubscriptionProvider.COLUMN_EXPIRATION);
break;
case R.id.expire7:
values.put(SubscriptionProvider.COLUMN_EXPIRATION, 7);
break;
case R.id.expire14:
values.put(SubscriptionProvider.COLUMN_EXPIRATION, 14);
break;
}
getActivity().getContentResolver().update(_subscriptionUri, values, null, null);
}
});
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
String[] projection = {
SubscriptionProvider.COLUMN_TITLE,
SubscriptionProvider.COLUMN_TITLE_OVERRIDE,
SubscriptionProvider.COLUMN_QUEUE_NEW,
SubscriptionProvider.COLUMN_EXPIRATION,
};
long subscriptionId = bundle.getLong("id");
if (subscriptionId == -1)
return null;
Uri uri = ContentUris.withAppendedId(SubscriptionProvider.URI, subscriptionId);
return new CursorLoader(getActivity(), uri, projection, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (loader.getId() != 0)
return;
if (init)
return;
init = true;
if (getActivity() == null)
return;
if (!cursor.moveToFirst())
getActivity().finish();
_feedTitle = cursor.getString(0);
if (!cursor.isNull(1)) {
_name.setText(cursor.getString(1));
_autoName.setChecked(false);
} else {
_name.setText(_feedTitle);
_autoName.setChecked(true);
}
if (!cursor.isNull(2) && cursor.getInt(2) == 0)
_autoQueue.check(R.id.autoQueueNo);
if (!cursor.isNull(3)) {
switch (cursor.getInt(3)) {
case 7:
_expiration.check(R.id.expire7);
break;
case 14:
_expiration.check(R.id.expire14);
break;
}
}
initializeControls();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
| fix memory leak in rare circumstance in subscription settings
| src/com/axelby/podax/ui/SubscriptionSettingsFragment.java | fix memory leak in rare circumstance in subscription settings | <ide><path>rc/com/axelby/podax/ui/SubscriptionSettingsFragment.java
<ide>
<ide> if (getActivity() == null)
<ide> return;
<del> if (!cursor.moveToFirst())
<add> if (!cursor.moveToFirst()) {
<add> cursor.close();
<ide> getActivity().finish();
<add> }
<ide>
<ide> _feedTitle = cursor.getString(0);
<ide> if (!cursor.isNull(1)) { |
|
Java | apache-2.0 | c276d923fde300d3750428a3c46b0932e9a85f66 | 0 | metaborg/spoofax-eclipse,metaborg/spoofax,metaborg/spoofax,metaborg/spoofax,metaborg/spoofax | package org.strategoxt.imp.runtime.services.outline;
import java.util.LinkedList;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.imp.parser.IModelListener;
import org.eclipse.imp.parser.IParseController;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.jsglr.client.imploder.ImploderAttachment;
import org.spoofax.jsglr.client.imploder.ImploderOriginTermFactory;
import org.spoofax.terms.TermFactory;
import org.spoofax.terms.attachments.OriginAttachment;
import org.strategoxt.imp.runtime.EditorState;
import org.strategoxt.imp.runtime.dynamicloading.BadDescriptorException;
import org.strategoxt.imp.runtime.services.StrategoObserver;
import org.strategoxt.imp.runtime.stratego.SourceAttachment;
import org.strategoxt.imp.runtime.stratego.StrategoTermPath;
import org.strategoxt.lang.Context;
/**
* @author Oskar van Rest
*/
public class SpoofaxOutlinePage extends ContentOutlinePage implements IModelListener {
public final static String OUTLINE_STRATEGY = "outline-strategy";
private EditorState editorState;
private ImploderOriginTermFactory factory = new ImploderOriginTermFactory(new TermFactory());
private StrategoObserver observer;
private boolean debounceSelectionChanged;
private IStrategoTerm outline;
public SpoofaxOutlinePage(EditorState editorState) {
this.editorState = editorState;
try {
observer = editorState.getDescriptor().createService(StrategoObserver.class, editorState.getParseController());
}
catch (BadDescriptorException e) {
e.printStackTrace();
}
editorState.getEditor().addModelListener(this);
editorState.getEditor().getSelectionProvider().addSelectionChangedListener(this);
}
@Override
public void dispose() {
editorState.getEditor().removeModelListener(this);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
getTreeViewer().setContentProvider(new SpoofaxOutlineContentProvider());
String pluginPath = editorState.getDescriptor().getBasePath().toPortableString();
getTreeViewer().setLabelProvider(new SpoofaxOutlineLabelProvider(pluginPath));
if (editorState.getCurrentAst() != null) {
update();
}
}
public AnalysisRequired getAnalysisRequired() {
return AnalysisRequired.NONE;
}
public void update(IParseController controller, IProgressMonitor monitor) {
update();
}
public void update() {
observer.getLock().lock();
try {
outline = observer.invokeSilent(OUTLINE_STRATEGY, editorState.getCurrentAst(), SourceAttachment.getFile(editorState.getCurrentAst()));
if (outline == null) { // outline-strategy undefined or failed
return;
}
// ensures propagation of origin information
factory.makeLink(outline, editorState.getCurrentAst());
Display.getDefault().asyncExec(new Runnable() {
public void run() {
getTreeViewer().setInput(outline);
getTreeViewer().expandToLevel(2);
}
});
}
finally {
observer.getLock().unlock();
}
}
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (event.getSource() == getTreeViewer()) {
super.selectionChanged(event);
}
if (debounceSelectionChanged) {
return;
}
debounceSelectionChanged = true;
if (event.getSource() == getTreeViewer()) {
outlineSelectionToTextSelection();
}
else {
textSelectionToOutlineSelection();
}
debounceSelectionChanged = false;
}
public void outlineSelectionToTextSelection() {
TreeSelection treeSelection = (TreeSelection) getSelection();
if (treeSelection.isEmpty()) {
return;
}
IStrategoTerm firstElem = (IStrategoTerm) treeSelection.getFirstElement();
IStrategoTerm origin = OriginAttachment.getOrigin(firstElem.getSubterm(0));
if (origin == null) {
origin = firstElem.getSubterm(0);
}
if (ImploderAttachment.hasImploderOrigin(origin)) {
int startOffset = (ImploderAttachment.getLeftToken(origin).getStartOffset());
int endOffset = (ImploderAttachment.getRightToken(origin).getEndOffset()) + 1;
TextSelection newSelection = new TextSelection(startOffset, endOffset - startOffset);
editorState.getEditor().getSelectionProvider().setSelection(newSelection);
}
}
public void textSelectionToOutlineSelection() {
IStrategoTerm textSelection = null;
try {
textSelection = editorState.getSelectionAst(true);
}
catch (IndexOutOfBoundsException e) {
// hack: happens when user selects text, deletes it and then chooses 'undo'
// TODO: fix EditorState.getSelectionAst()
}
if (textSelection == null) {
return;
}
Context context = observer.getRuntime().getCompiledContext();
IStrategoList path = StrategoTermPath.getTermPathWithOrigin(context, outline, textSelection);
if (path == null) {
return;
}
TreePath treePath = termPathToTreePath(path);
// TreeSelection selection = new TreeSelection(new TreePath(objectPath));
// setSelection(selection);
}
private TreePath termPathToTreePath(IStrategoList path) {
return new TreePath(termPathToTreePath(path, new LinkedList<Object>()).toArray());
}
private LinkedList<Object> termPathToTreePath(IStrategoList path, LinkedList<Object> result) {
return result;
}
@Override
public void setFocus() {
super.setFocus();
outlineSelectionToTextSelection();
}
}
| org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/outline/SpoofaxOutlinePage.java | package org.strategoxt.imp.runtime.services.outline;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.imp.parser.IModelListener;
import org.eclipse.imp.parser.IParseController;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.jsglr.client.imploder.ImploderAttachment;
import org.spoofax.jsglr.client.imploder.ImploderOriginTermFactory;
import org.spoofax.terms.TermFactory;
import org.spoofax.terms.attachments.OriginAttachment;
import org.strategoxt.imp.runtime.EditorState;
import org.strategoxt.imp.runtime.dynamicloading.BadDescriptorException;
import org.strategoxt.imp.runtime.services.StrategoObserver;
import org.strategoxt.imp.runtime.stratego.SourceAttachment;
import org.strategoxt.imp.runtime.stratego.StrategoTermPath;
import org.strategoxt.lang.Context;
/**
* @author Oskar van Rest
*/
public class SpoofaxOutlinePage extends ContentOutlinePage implements IModelListener {
public final static String OUTLINE_STRATEGY = "outline-strategy";
private EditorState editorState;
private ImploderOriginTermFactory factory = new ImploderOriginTermFactory(new TermFactory());
private StrategoObserver observer;
private boolean debounceSelectionChanged;
private IStrategoTerm outline;
public SpoofaxOutlinePage(EditorState editorState) {
this.editorState = editorState;
try {
observer = editorState.getDescriptor().createService(StrategoObserver.class, editorState.getParseController());
}
catch (BadDescriptorException e) {
e.printStackTrace();
}
editorState.getEditor().addModelListener(this);
editorState.getEditor().getSelectionProvider().addSelectionChangedListener(this);
}
@Override
public void dispose() {
editorState.getEditor().removeModelListener(this);
}
@Override
public void createControl(Composite parent) {
super.createControl(parent);
getTreeViewer().setContentProvider(new SpoofaxOutlineContentProvider());
String pluginPath = editorState.getDescriptor().getBasePath().toPortableString();
getTreeViewer().setLabelProvider(new SpoofaxOutlineLabelProvider(pluginPath));
if (editorState.getCurrentAst() != null) {
update();
}
}
public AnalysisRequired getAnalysisRequired() {
return AnalysisRequired.NONE;
}
public void update(IParseController controller, IProgressMonitor monitor) {
update();
}
public void update() {
observer.getLock().lock();
try {
outline = observer.invokeSilent(OUTLINE_STRATEGY, editorState.getCurrentAst(), SourceAttachment.getFile(editorState.getCurrentAst()));
if (outline == null) { // outline-strategy undefined or failed
System.out.println("outline failed");
return;
}
// ensures propagation of origin information
factory.makeLink(outline, editorState.getCurrentAst());
Display.getDefault().asyncExec(new Runnable() {
public void run() {
getTreeViewer().setInput(outline);
getTreeViewer().expandToLevel(2);
}
});
}
finally {
observer.getLock().unlock();
}
}
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (event.getSource() == getTreeViewer()) {
super.selectionChanged(event);
}
if (debounceSelectionChanged) {
debounceSelectionChanged = false;
return;
}
else {
if (event.getSource() == getTreeViewer()) {
outlineSelectionToTextSelection();
}
else {
textSelectionToOutlineSelection();
}
}
}
public void outlineSelectionToTextSelection() {
TreeSelection treeSelection = (TreeSelection) getSelection();
if (treeSelection.isEmpty()) {
return;
}
IStrategoTerm firstElem = (IStrategoTerm) treeSelection.getFirstElement();
IStrategoTerm origin = OriginAttachment.getOrigin(firstElem.getSubterm(0));
if (origin == null) {
origin = firstElem.getSubterm(0);
}
if (ImploderAttachment.hasImploderOrigin(origin)) {
int startOffset = (ImploderAttachment.getLeftToken(origin).getStartOffset());
int endOffset = (ImploderAttachment.getRightToken(origin).getEndOffset()) + 1;
TextSelection newSelection = new TextSelection(startOffset, endOffset - startOffset);
ISelectionProvider selectionProvider = editorState.getEditor().getSelectionProvider();
TextSelection currentSelection = (TextSelection) selectionProvider.getSelection();
if (!(newSelection.getOffset()==currentSelection.getOffset() && newSelection.getLength()==currentSelection.getLength())) {
debounceSelectionChanged = true;
selectionProvider.setSelection(newSelection);
}
}
}
public void textSelectionToOutlineSelection() {
IStrategoTerm textSelection = null;
try {
textSelection = editorState.getSelectionAst(true);
}
catch (IndexOutOfBoundsException e) {
// hack: happens when user selects text, deletes it and then chooses 'undo'
// TODO: fix EditorState.getSelectionAst()
}
if (textSelection == null) {
return;
}
Context context = observer.getRuntime().getCompiledContext();
IStrategoList path = StrategoTermPath.getTermPathWithOrigin(context, outline, textSelection);
if (path == null) {
return;
}
IStrategoTerm[] outlineNodes = StrategoTermPath.getTermAtPath(context, outline, path).getAllSubterms();
// System.out.println(outline.getSubterm(1));
// Object[] objectPath = {outline.getSubterm(1)};
// TreeSelection selection = new TreeSelection(new TreePath(objectPath));
// setSelection(selection);
}
@Override
public void setFocus() {
super.setFocus();
outlineSelectionToTextSelection();
}
}
| debouncer
| org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/outline/SpoofaxOutlinePage.java | debouncer | <ide><path>rg.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/outline/SpoofaxOutlinePage.java
<ide> package org.strategoxt.imp.runtime.services.outline;
<add>
<add>import java.util.LinkedList;
<ide>
<ide> import org.eclipse.core.runtime.IProgressMonitor;
<ide> import org.eclipse.core.runtime.Platform;
<ide> outline = observer.invokeSilent(OUTLINE_STRATEGY, editorState.getCurrentAst(), SourceAttachment.getFile(editorState.getCurrentAst()));
<ide>
<ide> if (outline == null) { // outline-strategy undefined or failed
<del> System.out.println("outline failed");
<ide> return;
<ide> }
<ide>
<ide> }
<ide>
<ide> if (debounceSelectionChanged) {
<del> debounceSelectionChanged = false;
<ide> return;
<ide> }
<del> else {
<del> if (event.getSource() == getTreeViewer()) {
<del> outlineSelectionToTextSelection();
<del> }
<del> else {
<del> textSelectionToOutlineSelection();
<del> }
<del> }
<add>
<add> debounceSelectionChanged = true;
<add> if (event.getSource() == getTreeViewer()) {
<add> outlineSelectionToTextSelection();
<add> }
<add> else {
<add> textSelectionToOutlineSelection();
<add> }
<add> debounceSelectionChanged = false;
<ide> }
<ide>
<ide> public void outlineSelectionToTextSelection() {
<ide> int endOffset = (ImploderAttachment.getRightToken(origin).getEndOffset()) + 1;
<ide>
<ide> TextSelection newSelection = new TextSelection(startOffset, endOffset - startOffset);
<del> ISelectionProvider selectionProvider = editorState.getEditor().getSelectionProvider();
<del> TextSelection currentSelection = (TextSelection) selectionProvider.getSelection();
<del> if (!(newSelection.getOffset()==currentSelection.getOffset() && newSelection.getLength()==currentSelection.getLength())) {
<del> debounceSelectionChanged = true;
<del> selectionProvider.setSelection(newSelection);
<del> }
<add> editorState.getEditor().getSelectionProvider().setSelection(newSelection);
<ide> }
<ide> }
<ide>
<ide> if (path == null) {
<ide> return;
<ide> }
<del>
<del> IStrategoTerm[] outlineNodes = StrategoTermPath.getTermAtPath(context, outline, path).getAllSubterms();
<del>
<del>// System.out.println(outline.getSubterm(1));
<del>// Object[] objectPath = {outline.getSubterm(1)};
<add>
<add> TreePath treePath = termPathToTreePath(path);
<ide> // TreeSelection selection = new TreeSelection(new TreePath(objectPath));
<ide> // setSelection(selection);
<ide> }
<ide>
<del> @Override
<add> private TreePath termPathToTreePath(IStrategoList path) {
<add> return new TreePath(termPathToTreePath(path, new LinkedList<Object>()).toArray());
<add> }
<add>
<add> private LinkedList<Object> termPathToTreePath(IStrategoList path, LinkedList<Object> result) {
<add>
<add>
<add> return result;
<add>
<add> }
<add>
<add> @Override
<ide> public void setFocus() {
<ide> super.setFocus();
<ide> outlineSelectionToTextSelection(); |
|
JavaScript | mit | 98c3e16d1fe0ed50334272bbb00367432ed1104d | 0 | WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos | /* In the Margins Side Panel Functions */
/* Based on https://github.com/AndreaLombardo/BootSideMenu */
function getSide(listClasses){
var side;
for (var i = 0; i<listClasses.length; i++) {
if (listClasses[i]=='sidebar-left') {
side = "left";
break;
} else if (listClasses[i]=='sidebar-right') {
side = "right";
break;
} else {
side = null;
}
}
return side;
}
function doAnimation(container, containerWidth, sidebarSide, sidebarStatus) {
var toggler = container.children()[1];
if (sidebarStatus == "opened") {
if (sidebarSide == "left") {
container.animate({
left: -(containerWidth+2)
});
toggleArrow("left");
} else if (sidebarSide == "right") {
container.animate({
right: -(containerWidth +2)
});
toggleArrow("right");
}
container.attr('data-status', 'closed');
} else {
if (sidebarSide == "left") {
container.animate({
left:0
});
toggleArrow("right");
} else if (sidebarSide == "right") {
container.animate({
right:0
});
toggleArrow("left");
}
container.attr('data-status', 'opened');
}
}
function toggleArrow(side){
if (side=="left") {
$("#toggler").children(".glyphicon-chevron-right").css('display', 'block');
$("#toggler").children(".glyphicon-chevron-left").css('display', 'none');
} else if (side=="right") {
$("#toggler").children(".glyphicon-chevron-left").css('display', 'block');
$("#toggler").children(".glyphicon-chevron-right").css('display', 'none');
}
}
/* In the Margins API Functions */
function callAPI(slug, type) {
// No reason not to hard code this here since we only need the slug
var url = "http://scalar.usc.edu/works/lexos/rdf/node/"+slug+"?rec=0&format=json";
// Ajax call
$.ajax({
type:"GET",
url:url,
dataType:'jsonp',
success: function(data){
processData(data, type, url);
},
error: handleError
});
}
function handleError(XMLHttpRequest, textStatus, errorThrown) {
$('#status').html(textstatus+'"<br>"'+errorThrown).show();
}
function processData(data, type, url) {
for (var nodeProp in data) {
node = data[nodeProp]
content_path = node['http://rdfs.org/sioc/ns#content'];
if (node['http://purl.org/dc/terms/title'] != null) {
var title = node['http://purl.org/dc/terms/title'][0].value;
var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
}
if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
var video_url = node['http://simile.mit.edu/2003/10/ontologies/artstor#url'][0].value;
//var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
}
if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
}
if (content_path != null) {
var content = content_path[0].value;
content = content.replace(new RegExp('\r?\n\r?\n','g'), '<br><br>'); // Replace line breaks
}
}
displayITMcontent(content, title, url, type, video_url);
}
function displayITMcontent(content, title, url, type, video_url) {
// Fork here based on type
switch (type) {
case "panel":
$("#panel-content").remove();
titleLink = '<h4><a href="'+url+'" target="_blank">'+title+'</a></h4>';
$("#itm-content").append('<div id="panel-content">'+titleLink+content+'<br/></div>');
// Next two lines determine the panel height and change on window resize
//var height = $("#panel-content").visibleHeight()+"px";
//$("#panel-content").css("height", height);
$("#panel-status").hide();
break;
case "dialog":
titleLink = '<a href="'+url+'" target="_blank">'+title+'</a>';
$('#ITM-modal .modal-title').html(titleLink);
msg = "<h4>This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display <em>In the Margins</em> content. Click the <strong>Show Video</strong> button to see some sample video content.</h4>";
$('#ITM-modal .modal-body').empty();
$('#ITM-modal .modal-body').append(msg);
$('#ITM-modal .modal-body').append(content);
$("#dialog-status").hide();
break;
// Works only with YouTube videos
case "video-dialog":
var youtube_url = video_url.replace("https://www.youtube.com/watch?v=", "https://www.youtube.com/embed/");
titleLink = '<a href="'+url+'" target="_blank">'+title+'</a>';
$('#ITM-modal .modal-title').html(titleLink);
msg = "<h4>This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display <em>In the Margins</em> content. Click the <strong>Show Video</strong> button to see some sample video content.</h4>";
$('#ITM-modal .modal-body').empty();
$('#ITM-modal .modal-body').html("");
$('#ITM-modal .modal-body').append('<iframe style="min-height:500px;min-width:99%;" src="'+youtube_url+'"></iframe>');
$("#dialog-status").hide();
break;
}
}
/* Gets the height of the viewport relative to a specified element.
See http://stackoverflow.com/questions/24768795/get-the-visible-height-of-a-div-with-jquery */
$.fn.visibleHeight = function() {
var elBottom, elTop, scrollBot, scrollTop, visibleBottom, visibleTop;
scrollTop = $(window).scrollTop();
scrollBot = scrollTop + $(window).height();
elTop = this.offset().top;
elBottom = elTop + this.outerHeight();
visibleTop = elTop < scrollTop ? scrollTop : elTop;
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
return visibleBottom - visibleTop
}
/* Document Ready Functions */
$(document).ready(function() {
/* Get the viewport height after the window is resized */
//$(window).on('scroll resize', getVisible);
/* ITM Panel Setup */
var container = $("#toggler").parent();
var containerWidth = container.width();
container.css({left:-(containerWidth+2)});
container.attr('data-status', 'closed');
/* ITM Panel Toggle Events */
/* Note: This function currently only works with side-panel toggle icon.
To enable the use of other triggers, a class trigger should be used. */
$('#toggler').click(function() {
var container = $(this).parent();
var listClasses = $(container[0]).attr('class').split(/\s+/); //IE9 Fix
var side = getSide(listClasses);
var containerWidth = container.width();
var status = container.attr('data-status');
var dataSlug = $("#ITMPanel-itm-content").attr('data-slug');
var slug = (dataSlug == "") ? "index" : dataSlug;
if(!status) {
status = "opened";
}
doAnimation(container, containerWidth, side, status);
if (status == "closed") {
$("#panel-status").show();
callAPI(slug, "panel");
}
});
/* Populate a Bootstrap modal */
$('#ITM-modal').on('show.bs.modal', function(e) {
var button = $(e.relatedTarget) // Button that triggered the modal
var slug = button.data('slug'); // Extract info from data-slug attribute
var type = button.data('type'); // Extract info from data-type attribute
$("#dialog-status").show();
callAPI(slug, type);
//callAPI("best-practices", "dialog");
});
/* Empty a Bootstrap modal */
$('#ITM-modal').on('hide.bs.modal', function() {
$('#ITM-modal').removeData('bs.modal');
icon = $('#dialog-status').parent().html();
$('#ITM-modal .modal-body').html("");
$('#ITM-modal .modal-body').html(icon);
$("#dialog-status").hide();
callAPI("best-practices", "dialog");
});
/* Handle Show Video Button in Bootstrap Modal */
/* $('#show-video').click(function() {
callAPI("how-to-read-a-dendrogram", "video-dialog")
});*/
});
/* Initialise Bootstrap Modal */
$('#ITM-modal').modal();
| static/js/scripts_ITM.js | /* In the Margins Side Panel Functions */
/* Based on https://github.com/AndreaLombardo/BootSideMenu */
function getSide(listClasses){
var side;
for (var i = 0; i<listClasses.length; i++) {
if (listClasses[i]=='sidebar-left') {
side = "left";
break;
} else if (listClasses[i]=='sidebar-right') {
side = "right";
break;
} else {
side = null;
}
}
return side;
}
function doAnimation(container, containerWidth, sidebarSide, sidebarStatus) {
var toggler = container.children()[1];
if (sidebarStatus == "opened") {
if (sidebarSide == "left") {
container.animate({
left: -(containerWidth+2)
});
toggleArrow("left");
} else if (sidebarSide == "right") {
container.animate({
right: -(containerWidth +2)
});
toggleArrow("right");
}
container.attr('data-status', 'closed');
} else {
if (sidebarSide == "left") {
container.animate({
left:0
});
toggleArrow("right");
} else if (sidebarSide == "right") {
container.animate({
right:0
});
toggleArrow("left");
}
container.attr('data-status', 'opened');
}
}
function toggleArrow(side){
if (side=="left") {
$("#toggler").children(".glyphicon-chevron-right").css('display', 'block');
$("#toggler").children(".glyphicon-chevron-left").css('display', 'none');
} else if (side=="right") {
$("#toggler").children(".glyphicon-chevron-left").css('display', 'block');
$("#toggler").children(".glyphicon-chevron-right").css('display', 'none');
}
}
/* In the Margins API Functions */
function callAPI(slug, type) {
// No reason not to hard code this here since we only need the slug
var url = "http://scalar.usc.edu/works/lexos/rdf/node/"+slug+"?rec=0&format=json";
// Ajax call
$.ajax({
type:"GET",
url:url,
dataType:'jsonp',
success: function(data){
processData(data, type, url);
},
error: handleError
});
}
function handleError(XMLHttpRequest, textStatus, errorThrown) {
$('#status').html(textstatus+'"<br>"'+errorThrown).show();
}
function processData(data, type, url) {
for (var nodeProp in data) {
node = data[nodeProp]
content_path = node['http://rdfs.org/sioc/ns#content'];
if (node['http://purl.org/dc/terms/title'] != null) {
var title = node['http://purl.org/dc/terms/title'][0].value;
var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
}
if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
var video_url = node['http://simile.mit.edu/2003/10/ontologies/artstor#url'][0].value;
//var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
}
if (node['http://simile.mit.edu/2003/10/ontologies/artstor#url'] != null) {
var url = node['http://purl.org/dc/terms/isVersionOf'][0].value;
}
if (content_path != null) {
var content = content_path[0].value;
content = content.replace(new RegExp('\r?\n\r?\n','g'), '<br><br>'); // Replace line breaks
}
}
displayITMcontent(content, title, url, type, video_url);
}
function displayITMcontent(content, title, url, type, video_url) {
// Fork here based on type
switch (type) {
case "panel":
$("#panel-content").remove();
titleLink = '<h4><a href="'+url+'" target="_blank">'+title+'</a></h4>';
$("#itm-content").append('<div id="panel-content">'+titleLink+content+'<br/></div>');
// Next two lines determine the panel height and change on window resize
//var height = $("#panel-content").visibleHeight()+"px";
//$("#panel-content").css("height", height);
$("#panel-status").hide();
break;
case "dialog":
titleLink = '<a href="'+url+'" target="_blank">'+title+'</a>';
$('#ITM-modal .modal-title').html(titleLink);
msg = "<h4>This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display <em>In the Margins</em> content. Click the <strong>Show Video</strong> button to see some sample video content.</h4>";
$('#ITM-modal .modal-body').empty();
$('#ITM-modal .modal-body').append(msg);
$('#ITM-modal .modal-body').append(content);
$("#dialog-status").hide();
break;
// Works only with YouTube videos
case "video-dialog":
var youtube_url = video_url.replace("https://www.youtube.com/watch?v=", "https://www.youtube.com/embed/");
titleLink = '<a href="'+url+'" target="_blank">'+title+'</a>';
$('#ITM-modal .modal-title').html(titleLink);
msg = "<h4>This is just a sample modal. Ultimately, it will open a settings dialog, but for now it can be used as a trigger to display <em>In the Margins</em> content. Click the <strong>Show Video</strong> button to see some sample video content.</h4>";
$('#ITM-modal .modal-body').empty();
$('#ITM-modal .modal-body').html("");
$('#ITM-modal .modal-body').append('<iframe style="min-height:500px;min-width:99%;" src="'+youtube_url+'"></iframe>');
$("#dialog-status").hide();
break;
}
}
/* Gets the height of the viewport relative to a specified element.
See http://stackoverflow.com/questions/24768795/get-the-visible-height-of-a-div-with-jquery */
$.fn.visibleHeight = function() {
var elBottom, elTop, scrollBot, scrollTop, visibleBottom, visibleTop;
scrollTop = $(window).scrollTop();
scrollBot = scrollTop + $(window).height();
elTop = this.offset().top;
elBottom = elTop + this.outerHeight();
visibleTop = elTop < scrollTop ? scrollTop : elTop;
visibleBottom = elBottom > scrollBot ? scrollBot : elBottom;
return visibleBottom - visibleTop
}
/* Document Ready Functions */
$(document).ready(function() {
/* Get the viewport height after the window is resized */
//$(window).on('scroll resize', getVisible);
/* ITM Panel Setup */
var container = $("#toggler").parent();
var containerWidth = container.width();
container.css({left:-(containerWidth+2)});
container.attr('data-status', 'closed');
/* ITM Panel Toggle Events */
/* Note: This function currentl only works with side-panel toggle icon.
To enable the use of other triggers, a class trigger should be used. */
$('#toggler').click(function() {
var container = $(this).parent();
var listClasses = $(container[0]).attr('class').split(/\s+/); //IE9 Fix
var side = getSide(listClasses);
var containerWidth = container.width();
var status = container.attr('data-status');
var dataSlug = $("#ITMPanel-itm-content").attr('data-slug');
var slug = (dataSlug == "") ? "index" : dataSlug;
if(!status) {
status = "opened";
}
doAnimation(container, containerWidth, side, status);
if (status == "closed") {
$("#panel-status").show();
callAPI(slug, "panel");
}
});
/* Populate a Bootstrap modal */
$('#ITM-modal').on('show.bs.modal', function(e) {
var button = $(e.relatedTarget) // Button that triggered the modal
var slug = button.data('slug'); // Extract info from data-slug attribute
var type = button.data('type'); // Extract info from data-type attribute
$("#dialog-status").show();
callAPI(slug, type);
//callAPI("best-practices", "dialog");
});
/* Empty a Bootstrap modal */
$('#ITM-modal').on('hide.bs.modal', function() {
$('#ITM-modal').removeData('bs.modal');
icon = $('#dialog-status').parent().html();
$('#ITM-modal .modal-body').html("");
$('#ITM-modal .modal-body').html(icon);
$("#dialog-status").hide();
callAPI("best-practices", "dialog");
});
/* Handle Show Video Button in Bootstrap Modal */
/* $('#show-video').click(function() {
callAPI("how-to-read-a-dendrogram", "video-dialog")
});*/
});
/* Initialise Bootstrap Modal */
$('#ITM-modal').modal();
| Fixed typo
| static/js/scripts_ITM.js | Fixed typo | <ide><path>tatic/js/scripts_ITM.js
<ide> container.attr('data-status', 'closed');
<ide>
<ide> /* ITM Panel Toggle Events */
<del> /* Note: This function currentl only works with side-panel toggle icon.
<add> /* Note: This function currently only works with side-panel toggle icon.
<ide> To enable the use of other triggers, a class trigger should be used. */
<ide> $('#toggler').click(function() {
<ide> var container = $(this).parent(); |
|
JavaScript | mit | 98475c37e8abc4f515032f479a05e82c1f5b4203 | 0 | myabc/refinerycms,rafamvc/jobs-refinery,myabc/refinerycms,kritik/portfolio,johnreilly/johnandkaty,mdoyle13/haymarket-ref,ashrafuzzaman/stips,kritik/portfolio,kritik/diamond-tours,mdoyle13/haymarket-ref,mdoyle13/haymarket-ref,kritik/diamond-tours,mdoyle13/haymarket-ref,clanplaid/wow.clanplaid.net,clanplaid/wow.clanplaid.net,rafamvc/jobs-refinery,captproton/fugu,captproton/fugu,ashrafuzzaman/stips,johnreilly/johnandkaty | /*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File: jquery.refinery.wymeditor.js
*
* Main JS file with core classes and functions.
* See the documentation for more info.
*
* About: authors
*
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Volker Mische (vmx a-t gmx dotde)
* Scott Lewis (lewiscot a-t gmail dotcom)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Daniel Reszka (d.reszka a-t wymeditor dotorg)
* Jonatan Lundin (jonatan.lundin _at_ gmail.com)
*/
/*
Namespace: WYMeditor
Global WYMeditor namespace.
*/
if(!WYMeditor) var WYMeditor = {};
//Wrap the Firebug console in WYMeditor.console
(function() {
if ( !window.console || !console.firebug ) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
WYMeditor.console = {};
for (var i = 0; i < names.length; ++i)
WYMeditor.console[names[i]] = function() {}
} else WYMeditor.console = window.console;
})();
jQuery.extend(WYMeditor, {
/*
Constants: Global WYMeditor constants.
VERSION - Defines WYMeditor version.
INSTANCES - An array of loaded WYMeditor.editor instances.
STRINGS - An array of loaded WYMeditor language pairs/values.
SKINS - An array of loaded WYMeditor skins.
NAME - The "name" attribute.
INDEX - A string replaced by the instance index.
WYM_INDEX - A string used to get/set the instance index.
BASE_PATH - A string replaced by WYMeditor's base path.
SKIN_PATH - A string replaced by WYMeditor's skin path.
WYM_PATH - A string replaced by WYMeditor's main JS file path.
SKINS_DEFAULT_PATH - The skins default base path.
SKINS_DEFAULT_CSS - The skins default CSS file.
LANG_DEFAULT_PATH - The language files default path.
IFRAME_BASE_PATH - A string replaced by the designmode iframe's base path.
IFRAME_DEFAULT - The iframe's default base path.
JQUERY_PATH - A string replaced by the computed jQuery path.
DIRECTION - A string replaced by the text direction (rtl or ltr).
LOGO - A string replaced by WYMeditor logo.
TOOLS - A string replaced by the toolbar's HTML.
TOOLS_ITEMS - A string replaced by the toolbar items.
TOOL_NAME - A string replaced by a toolbar item's name.
TOOL_TITLE - A string replaced by a toolbar item's title.
TOOL_CLASS - A string replaced by a toolbar item's class.
CLASSES - A string replaced by the classes panel's HTML.
CLASSES_ITEMS - A string replaced by the classes items.
CLASS_NAME - A string replaced by a class item's name.
CLASS_TITLE - A string replaced by a class item's title.
CONTAINERS - A string replaced by the containers panel's HTML.
CONTAINERS_ITEMS - A string replaced by the containers items.
CONTAINER_NAME - A string replaced by a container item's name.
CONTAINER_TITLE - A string replaced by a container item's title.
CONTAINER_CLASS - A string replaced by a container item's class.
HTML - A string replaced by the HTML view panel's HTML.
IFRAME - A string replaced by the designmode iframe.
STATUS - A string replaced by the status panel's HTML.
DIALOG_TITLE - A string replaced by a dialog's title.
DIALOG_BODY - A string replaced by a dialog's HTML body.
BODY - The BODY element.
STRING - The "string" type.
BODY,DIV,P,
H1,H2,H3,H4,H5,H6,
PRE,BLOCKQUOTE,
A,BR,IMG,
TABLE,TD,TH,
UL,OL,LI - HTML elements string representation.
CLASS,HREF,SRC,
TITLE,ALT - HTML attributes string representation.
DIALOG_LINK - A link dialog type.
DIALOG_IMAGE - An image dialog type.
DIALOG_TABLE - A table dialog type.
DIALOG_PASTE - A 'Paste from Word' dialog type.
BOLD - Command: (un)set selection to <strong>.
ITALIC - Command: (un)set selection to <em>.
CREATE_LINK - Command: open the link dialog or (un)set link.
INSERT_IMAGE - Command: open the image dialog or insert an image.
INSERT_TABLE - Command: open the table dialog.
PASTE - Command: open the paste dialog.
INDENT - Command: nest a list item.
OUTDENT - Command: unnest a list item.
TOGGLE_HTML - Command: display/hide the HTML view.
FORMAT_BLOCK - Command: set a block element to another type.
PREVIEW - Command: open the preview dialog.
UNLINK - Command: unset a link.
INSERT_UNORDEREDLIST- Command: insert an unordered list.
INSERT_ORDEREDLIST - Command: insert an ordered list.
MAIN_CONTAINERS - An array of the main HTML containers used in WYMeditor.
BLOCKS - An array of the HTML block elements.
KEY - Standard key codes.
NODE - Node types.
*/
VERSION : "0.5-b2-refinery",
INSTANCES : [],
STRINGS : [],
SKINS : [],
NAME : "name",
INDEX : "{Wym_Index}",
WYM_INDEX : "wym_index",
BASE_PATH : "{Wym_Base_Path}",
CSS_PATH : "{Wym_Css_Path}",
WYM_PATH : "{Wym_Wym_Path}",
SKINS_DEFAULT_PATH : "/images/wymeditor/skins/",
SKINS_DEFAULT_CSS : "skin.css",
SKINS_DEFAULT_JS : "skin.js",
LANG_DEFAULT_PATH : "lang/",
IFRAME_BASE_PATH : "{Wym_Iframe_Base_Path}",
IFRAME_DEFAULT : "iframe/default/",
JQUERY_PATH : "{Wym_Jquery_Path}",
DIRECTION : "{Wym_Direction}",
LOGO : "{Wym_Logo}",
TOOLS : "{Wym_Tools}",
TOOLS_ITEMS : "{Wym_Tools_Items}",
TOOL_NAME : "{Wym_Tool_Name}",
TOOL_TITLE : "{Wym_Tool_Title}",
TOOL_CLASS : "{Wym_Tool_Class}",
CLASSES : "{Wym_Classes}",
CLASSES_ITEMS : "{Wym_Classes_Items}",
CLASS_NAME : "{Wym_Class_Name}",
CLASS_TITLE : "{Wym_Class_Title}",
CONTAINERS : "{Wym_Containers}",
CONTAINERS_ITEMS : "{Wym_Containers_Items}",
CONTAINER_NAME : "{Wym_Container_Name}",
CONTAINER_TITLE : "{Wym_Containers_Title}",
CONTAINER_CLASS : "{Wym_Container_Class}",
HTML : "{Wym_Html}",
IFRAME : "{Wym_Iframe}",
STATUS : "{Wym_Status}",
DIALOG_TITLE : "{Wym_Dialog_Title}",
DIALOG_BODY : "{Wym_Dialog_Body}",
STRING : "string",
BODY : "body",
DIV : "div",
P : "p",
H1 : "h1",
H2 : "h2",
H3 : "h3",
H4 : "h4",
H5 : "h5",
H6 : "h6",
PRE : "pre",
BLOCKQUOTE : "blockquote",
A : "a",
BR : "br",
IMG : "img",
TABLE : "table",
TD : "td",
TH : "th",
UL : "ul",
OL : "ol",
LI : "li",
CLASS : "class",
HREF : "href",
SRC : "src",
TITLE : "title",
TARGET : "target",
ALT : "alt",
DIALOG_LINK : "Link",
DIALOG_IMAGE : "Image",
DIALOG_TABLE : "Table",
DIALOG_PASTE : "Paste_From_Word",
DIALOG_CLASS : "Css_Class",
BOLD : "Bold",
ITALIC : "Italic",
CREATE_LINK : "CreateLink",
INSERT_IMAGE : "InsertImage",
INSERT_TABLE : "InsertTable",
INSERT_HTML : "InsertHTML",
APPLY_CLASS : "Apply_Style",
PASTE : "Paste",
INDENT : "Indent",
OUTDENT : "Outdent",
TOGGLE_HTML : "ToggleHtml",
FORMAT_BLOCK : "FormatBlock",
PREVIEW : "Preview",
UNLINK : "Unlink",
INSERT_UNORDEREDLIST : "InsertUnorderedList",
INSERT_ORDEREDLIST : "InsertOrderedList",
MAIN_CONTAINERS : new Array("p","h1","h2","h3","h4","h5","h6","pre","blockquote"),
BLOCKS : new Array("address", "blockquote", "div", "dl",
"fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6", "hr",
"noscript", "ol", "p", "pre", "table", "ul", "dd", "dt",
"li", "tbody", "td", "tfoot", "th", "thead", "tr"),
KEY : {
BACKSPACE: 8,
ENTER: 13,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
CURSOR: new Array(37, 38, 39, 40),
DELETE: 46
},
NODE : {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3
},
/*
Class: WYMeditor.editor
WYMeditor editor main class, instanciated for each editor occurrence.
*/
editor : function(elem, options) {
/*
Constructor: WYMeditor.editor
Initializes main values (index, elements, paths, ...)
and call WYMeditor.editor.init which initializes the editor.
Parameters:
elem - The HTML element to be replaced by the editor.
options - The hash of options.
Returns:
Nothing.
See Also:
<WYMeditor.editor.init>
*/
//store the instance in the INSTANCES array and store the index
this._index = WYMeditor.INSTANCES.push(this) - 1;
//store the element replaced by the editor
this._element = elem;
//store the options
this._options = options;
//store the element's inner value
this._html = jQuery(elem).val();
//store the HTML option, if any
if(this._options.html) this._html = this._options.html;
//get or compute the base path (where the main JS file is located)
this._options.basePath = this._options.basePath || this.computeBasePath();
//get or set the skin path (where the skin files are located)
this._options.skinPath = this._options.skinPath || this._options.basePath + WYMeditor.SKINS_DEFAULT_PATH + this._options.skin + '/';
// set css and js skin paths
this._options.cssSkinPath = (this._options.cssSkinPath || this._options.skinPath) + this._options.skin + "/";
this._options.jsSkinPath = (this._options.jsSkinPath || this._options.skinPath) + this._options.skin + "/";
//get or compute the main JS file location
this._options.wymPath = this._options.wymPath || this.computeWymPath();
//get or set the language files path
this._options.langPath = this._options.langPath || this._options.basePath + WYMeditor.LANG_DEFAULT_PATH;
//get or set the designmode iframe's base path
this._options.iframeBasePath = this._options.iframeBasePath || this._options.basePath + WYMeditor.IFRAME_DEFAULT;
//get or compute the jQuery JS file location
this._options.jQueryPath = this._options.jQueryPath || this.computeJqueryPath();
//initialize the editor instance
this.init();
}
});
/********** JQUERY **********/
/**
* Replace an HTML element by WYMeditor
*
* @example jQuery(".wymeditor").wymeditor(
* {
*
* }
* );
* @desc Example description here
*
* @name WYMeditor
* @description WYMeditor is a web-based WYSIWYM XHTML editor
* @param Hash hash A hash of parameters
* @option Integer iExample Description here
* @option String sExample Description here
*
* @type jQuery
* @cat Plugins/WYMeditor
* @author Jean-Francois Hovinne
*/
jQuery.fn.wymeditor = function(options) {
options = jQuery.extend({
html: "",
basePath: false,
skinPath: false,
jsSkinPath: false,
cssSkinPath: false,
wymPath: false,
iframeBasePath: false,
jQueryPath: false,
styles: false,
stylesheet: false,
skin: "default",
initSkin: true,
loadSkin: true,
lang: "en",
direction: "ltr",
boxHtml: "<div class='wym_box'>"
+ "<div class='wym_area_top'>"
+ WYMeditor.TOOLS
+ "</div>"
+ "<div class='wym_area_left'></div>"
+ "<div class='wym_area_right'>"
+ WYMeditor.CONTAINERS
+ WYMeditor.CLASSES
+ "</div>"
+ "<div class='wym_area_main'>"
+ WYMeditor.HTML
+ WYMeditor.IFRAME
+ WYMeditor.STATUS
+ "</div>"
+ "<div class='wym_area_bottom'>"
+ WYMeditor.LOGO
+ "</div>"
+ "</div>",
logoHtml: "<a class='wym_wymeditor_link' "
+ "href='http://www.wymeditor.org/'>WYMeditor</a>",
iframeHtml:"<div class='wym_iframe wym_section'>"
+ "<iframe "
+ "src='"
+ WYMeditor.IFRAME_BASE_PATH
+ "wymiframe.html' "
+ "onload='this.contentWindow.parent.WYMeditor.INSTANCES["
+ WYMeditor.INDEX + "].initIframe(this)'"
+ "></iframe>"
+ "</div>",
editorStyles: [],
toolsHtml: "<div class='wym_tools wym_section'>"
+ "<h2>{Tools}</h2>"
+ "<ul>"
+ WYMeditor.TOOLS_ITEMS
+ "</ul>"
+ "</div>",
toolsItemHtml: "<li class='"
+ WYMeditor.TOOL_CLASS
+ "'><a href='#' name='"
+ WYMeditor.TOOL_NAME
+ "' title='"
+ WYMeditor.TOOL_TITLE
+ "'>"
+ WYMeditor.TOOL_TITLE
+ "</a></li>",
toolsItems: [
{'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'},
{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
{'name': 'Superscript', 'title': 'Superscript',
'css': 'wym_tools_superscript'},
{'name': 'Subscript', 'title': 'Subscript',
'css': 'wym_tools_subscript'},
{'name': 'InsertOrderedList', 'title': 'Ordered_List',
'css': 'wym_tools_ordered_list'},
{'name': 'InsertUnorderedList', 'title': 'Unordered_List',
'css': 'wym_tools_unordered_list'},
{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'},
{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'},
{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'},
{'name': 'Paste', 'title': 'Paste_From_Word',
'css': 'wym_tools_paste'},
{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},
{'name': 'Preview', 'title': 'Preview', 'css': 'wym_tools_preview'}
],
containersHtml: "<div class='wym_containers wym_section'>"
+ "<h2>{Containers}</h2>"
+ "<ul>"
+ WYMeditor.CONTAINERS_ITEMS
+ "</ul>"
+ "</div>",
containersItemHtml:"<li class='"
+ WYMeditor.CONTAINER_CLASS
+ "'>"
+ "<a href='#' name='"
+ WYMeditor.CONTAINER_NAME
+ "'>"
+ WYMeditor.CONTAINER_TITLE
+ "</a></li>",
containersItems: [
{'name': 'P', 'title': 'Paragraph', 'css': 'wym_containers_p'},
{'name': 'H1', 'title': 'Heading_1', 'css': 'wym_containers_h1'},
{'name': 'H2', 'title': 'Heading_2', 'css': 'wym_containers_h2'},
{'name': 'H3', 'title': 'Heading_3', 'css': 'wym_containers_h3'},
{'name': 'H4', 'title': 'Heading_4', 'css': 'wym_containers_h4'},
{'name': 'H5', 'title': 'Heading_5', 'css': 'wym_containers_h5'},
{'name': 'H6', 'title': 'Heading_6', 'css': 'wym_containers_h6'},
{'name': 'PRE', 'title': 'Preformatted', 'css': 'wym_containers_pre'},
{'name': 'BLOCKQUOTE', 'title': 'Blockquote',
'css': 'wym_containers_blockquote'},
{'name': 'TH', 'title': 'Table_Header', 'css': 'wym_containers_th'}
],
classesHtml: "<div class='wym_classes wym_section'>"
+ "<h2>{Classes}</h2><ul>"
+ WYMeditor.CLASSES_ITEMS
+ "</ul></div>",
classesItemHtml: "<li><a href='#' name='"
+ WYMeditor.CLASS_NAME
+ "'>"
+ WYMeditor.CLASS_TITLE
+ "</a></li>",
classesItems: [],
statusHtml: "<div class='wym_status wym_section'>"
+ "<h2>{Status}</h2>"
+ "</div>",
htmlHtml: "<div class='wym_html wym_section'>"
+ "<h2>{Source_Code}</h2>"
+ "<textarea class='wym_html_val'></textarea>"
+ "</div>",
boxSelector: ".wym_box",
toolsSelector: ".wym_tools",
toolsListSelector: " ul",
containersSelector:".wym_containers",
classesSelector: ".wym_classes",
htmlSelector: ".wym_html",
iframeSelector: ".wym_iframe iframe",
iframeBodySelector:".wym_iframe",
statusSelector: ".wym_status",
toolSelector: ".wym_tools a",
containerSelector: ".wym_containers a",
classSelector: ".wym_classes a",
classUnhiddenSelector: ".wym_classes",
classHiddenSelector: ".wym_classes_hidden",
htmlValSelector: ".wym_html_val",
hrefSelector: ".wym_href",
srcSelector: ".wym_src",
titleSelector: ".wym_title",
targetSelector: ".wym_target",
altSelector: ".wym_alt",
textSelector: ".wym_text",
rowsSelector: ".wym_rows",
colsSelector: ".wym_cols",
captionSelector: ".wym_caption",
summarySelector: ".wym_summary",
submitSelector: ".wym_submit",
cancelSelector: ".wym_cancel",
previewSelector: "",
dialogTypeSelector: ".wym_dialog_type",
dialogLinkSelector: ".wym_dialog_link",
dialogImageSelector: ".wym_dialog_image",
dialogTableSelector: ".wym_dialog_table",
dialogPasteSelector: ".wym_dialog_paste",
dialogPreviewSelector: ".wym_dialog_preview",
updateSelector: ".wymupdate",
updateEvent: "click",
dialogFeatures: "menubar=no,titlebar=no,toolbar=no,resizable=no"
+ ",width=560,height=300,top=0,left=0",
dialogHtml: "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'"
+ " 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
+ "<html dir='"
+ WYMeditor.DIRECTION
+ "'><head>"
+ "<link rel='stylesheet' type='text/css' media='screen'"
+ " href='"
+ WYMeditor.CSS_PATH
+ "' />"
+ "<title>"
+ WYMeditor.DIALOG_TITLE
+ "</title>"
+ "<script type='text/javascript'"
+ " src='"
+ WYMeditor.JQUERY_PATH
+ "'></script>"
+ "<script type='text/javascript'"
+ " src='"
+ WYMeditor.WYM_PATH
+ "'></script>"
+ "</head>"
+ WYMeditor.DIALOG_BODY
+ "</html>",
dialogLinkHtml: "<div class='wym_dialog wym_dialog_link'>"
+ "<form>"
+ "<fieldset>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_LINK
+ "' />"
+ "<legend>{Link}</legend>"
+ "<div class='row'>"
+ "<label>{URL}</label>"
+ "<input type='text' class='wym_href' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Title}</label>"
+ "<input type='text' class='wym_title' value='' size='40' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogImageHtml: "<div class='wym_dialog wym_dialog_image'>"
+ "<form>"
+ "<fieldset>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_IMAGE
+ "' />"
+ "<legend>{Image}</legend>"
+ "<div class='row'>"
+ "<label>{URL}</label>"
+ "<input type='text' class='wym_src' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Alternative_Text}</label>"
+ "<input type='text' class='wym_alt' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Title}</label>"
+ "<input type='text' class='wym_title' value='' size='40' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogTableHtml: "<div class='wym_dialog wym_dialog_table'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_TABLE
+ "' />"
+ "<div class='row'>"
+ "<label>{Caption}</label>"
+ "<input type='text' class='wym_caption' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Summary}</label>"
+ "<input type='text' class='wym_summary' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Number_Of_Rows}</label>"
+ "<input type='text' class='wym_rows' value='3' size='3' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Number_Of_Cols}</label>"
+ "<input type='text' class='wym_cols' value='2' size='3' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</form>"
+ "</div>",
dialogPasteHtml: "<div class='wym_dialog wym_dialog_paste'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_PASTE
+ "' />"
+ "<fieldset>"
+ "<legend>{Paste_From_Word}</legend>"
+ "<div class='row'>"
+ "<textarea class='wym_text' rows='10' cols='50'></textarea>"
+ "</div>"
+ "<div class='row'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogPreviewHtml: "<div class='wym_dialog wym_dialog_preview'></div>",
dialogStyles: [],
stringDelimiterLeft: "{",
stringDelimiterRight:"}",
preInit: null,
preBind: null,
postInit: null,
preInitDialog: null,
postInitDialog: null
}, options);
return this.each(function() {
new WYMeditor.editor(jQuery(this),options);
});
};
/* @name extend
* @description Returns the WYMeditor instance based on its index
*/
jQuery.extend({
wymeditors: function(i) {
return (WYMeditor.INSTANCES[i]);
}
});
/********** WYMeditor **********/
/* @name Wymeditor
* @description WYMeditor class
*/
/* @name init
* @description Initializes a WYMeditor instance
*/
WYMeditor.editor.prototype.init = function() {
//load subclass - browser specific
//unsupported browsers: do nothing
if (jQuery.browser.msie) {
var WymClass = new WYMeditor.WymClassExplorer(this);
}
else if (jQuery.browser.mozilla) {
var WymClass = new WYMeditor.WymClassMozilla(this);
}
else if (jQuery.browser.opera) {
var WymClass = new WYMeditor.WymClassOpera(this);
}
else if (jQuery.browser.safari) {
var WymClass = new WYMeditor.WymClassSafari(this);
}
if(WymClass) {
if(jQuery.isFunction(this._options.preInit)) this._options.preInit(this);
var SaxListener = new WYMeditor.XhtmlSaxListener();
jQuery.extend(SaxListener, WymClass);
this.parser = new WYMeditor.XhtmlParser(SaxListener);
if(this._options.styles || this._options.stylesheet){
this.configureEditorUsingRawCss();
}
this.helper = new WYMeditor.XmlHelper();
//extend the Wymeditor object
//don't use jQuery.extend since 1.1.4
//jQuery.extend(this, WymClass);
for (var prop in WymClass) { this[prop] = WymClass[prop]; }
//load wymbox
this._box = jQuery(this._element).hide().after(this._options.boxHtml).next();
//store the instance index in the wymbox element
//but keep it compatible with jQuery < 1.2.3, see #122
if( jQuery.isFunction( jQuery.fn.data ) )
jQuery.data(this._box.get(0), WYMeditor.WYM_INDEX, this._index);
var h = WYMeditor.Helper;
//construct the iframe
var iframeHtml = this._options.iframeHtml;
iframeHtml = h.replaceAll(iframeHtml, WYMeditor.INDEX, this._index);
iframeHtml = h.replaceAll(iframeHtml, WYMeditor.IFRAME_BASE_PATH, this._options.iframeBasePath);
//construct wymbox
var boxHtml = jQuery(this._box).html();
boxHtml = h.replaceAll(boxHtml, WYMeditor.LOGO, this._options.logoHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS, this._options.toolsHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS,this._options.containersHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES, this._options.classesHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.HTML, this._options.htmlHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.IFRAME, iframeHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.STATUS, this._options.statusHtml);
//construct tools list
var aTools = eval(this._options.toolsItems);
var sTools = "";
for(var i = 0; i < aTools.length; i++) {
var oTool = aTools[i];
if(oTool.name && oTool.title)
var sTool = this._options.toolsItemHtml;
var sTool = h.replaceAll(sTool, WYMeditor.TOOL_NAME, oTool.name);
sTool = h.replaceAll(sTool, WYMeditor.TOOL_TITLE, this._options.stringDelimiterLeft
+ oTool.title
+ this._options.stringDelimiterRight);
sTool = h.replaceAll(sTool, WYMeditor.TOOL_CLASS, oTool.css);
sTools += sTool;
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS_ITEMS, sTools);
//construct classes list
var aClasses = eval(this._options.classesItems);
var sClasses = "";
for(var i = 0; i < aClasses.length; i++) {
var oClass = aClasses[i];
if(oClass.name) {
if (oClass.rules && oClass.rules.length > 0) {
var sRules = "";
oClass.rules.each(function(rule){
sClass = this._options.classesItemHtml;
sClass = h.replaceAll(sClass, WYMeditor.CLASS_NAME, oClass.name + (oClass.join || "") + rule);
sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, rule.title || titleize(rule));
sRules += sClass;
}.bind(this)); // need to bind 'this' or else it will think 'this' is the window.
var sClassMultiple = this._options.classesItemHtmlMultiple;
sClassMultiple = h.replaceAll(sClassMultiple, WYMeditor.CLASS_TITLE, oClass.title || titleize(oClass.name));
sClassMultiple = h.replaceAll(sClassMultiple, '{classesItemHtml}', sRules);
sClasses += sClassMultiple;
}
else {
sClass = this._options.classesItemHtml;
sClass = h.replaceAll(sClass, WYMeditor.CLASS_NAME, oClass.name);
sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, oClass.title || titleize(oClass.name));
sClasses += sClass;
}
}
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES_ITEMS, sClasses);
//construct containers list
var aContainers = eval(this._options.containersItems);
var sContainers = "";
for(var i = 0; i < aContainers.length; i++) {
var oContainer = aContainers[i];
if(oContainer.name && oContainer.title)
var sContainer = this._options.containersItemHtml;
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_NAME, oContainer.name);
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_TITLE,
this._options.stringDelimiterLeft
+ oContainer.title
+ this._options.stringDelimiterRight);
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_CLASS, oContainer.css);
sContainers += sContainer;
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS_ITEMS, sContainers);
//l10n
boxHtml = this.replaceStrings(boxHtml);
//load html in wymbox
jQuery(this._box).html(boxHtml);
//hide the html value
jQuery(this._box).find(this._options.htmlSelector).hide();
//enable the skin
this.loadSkin();
}
};
WYMeditor.editor.prototype.bindEvents = function() {
//copy the instance
var wym = this;
//handle click event on tools buttons
jQuery(this._box).find(this._options.toolSelector).click(function() {
wym.exec(jQuery(this).attr(WYMeditor.NAME));
return(false);
});
//handle click event on containers buttons
jQuery(this._box).find(this._options.containerSelector).click(function() {
wym.container(jQuery(this).attr(WYMeditor.NAME));
return(false);
});
//handle keyup event on html value: set the editor value
jQuery(this._box).find(this._options.htmlValSelector).keyup(function() {
jQuery(wym._doc.body).html(jQuery(this).val());
});
//handle click event on classes buttons
jQuery(this._box).find(this._options.classSelector).click(function() {
var aClasses = eval(wym._options.classesItems);
var sName = jQuery(this).attr(WYMeditor.NAME);
var oClass = WYMeditor.Helper.findByName(aClasses, sName);
var replacers = [];
if (oClass == null) {
aClasses.each(function(classRule){
if (oClass == null && classRule.rules && classRule.rules.length > 0){
indexOf = classRule.rules.indexOf(sName.gsub(classRule.name + (classRule.join || ""), ""));
if (indexOf > -1) {
for (i=0;i<classRule.rules.length;i++){
if (i != indexOf){
replacers.push(classRule.name + (classRule.join || "") + classRule.rules[i]);
}
}
oClass = {expr: (classRule.rules[indexOf].expr || null)}
}
}
}.bind(this));
}
if(oClass) {
var jqexpr = oClass.expr;
// remove all related classes.
replacers.each(function(removable_class){
wym.removeClass(removable_class, jqexpr);
});
wym.toggleClass(sName, jqexpr);
}
// now hide the menu
wym.exec(WYMeditor.APPLY_CLASS);
return(false);
});
//handle event on update element
jQuery(this._options.updateSelector).bind(this._options.updateEvent, function() {
wym.update();
});
};
WYMeditor.editor.prototype.ready = function() {
return(this._doc != null);
};
/********** METHODS **********/
/* @name box
* @description Returns the WYMeditor container
*/
WYMeditor.editor.prototype.box = function() {
return(this._box);
};
/* @name html
* @description Get/Set the html value
*/
WYMeditor.editor.prototype.html = function(html) {
if(typeof html === 'string') jQuery(this._doc.body).html(html);
else return(jQuery(this._doc.body).html());
};
/* @name xhtml
* @description Cleans up the HTML
*/
WYMeditor.editor.prototype.xhtml = function() {
return this.parser.parse(this.html());
};
/* @name exec
* @description Executes a button command
*/
WYMeditor.editor.prototype.exec = function(cmd) {
//base function for execCommand
//open a dialog or exec
switch(cmd) {
case WYMeditor.CREATE_LINK:
var container = this.container();
if(container || this._selected_image) this.dialog(WYMeditor.DIALOG_LINK);
break;
case WYMeditor.INSERT_IMAGE:
this.dialog(WYMeditor.DIALOG_IMAGE);
break;
case WYMeditor.INSERT_TABLE:
this.dialog(WYMeditor.DIALOG_TABLE);
break;
case WYMeditor.PASTE:
this.dialog(WYMeditor.DIALOG_PASTE);
break;
case WYMeditor.TOGGLE_HTML:
this.update();
this.toggleHtml();
//partially fixes #121 when the user manually inserts an image
if(!jQuery(this._box).find(this._options.htmlSelector).is(':visible'))
this.listen();
break;
case WYMeditor.PREVIEW:
this.dialog(WYMeditor.PREVIEW);
break;
case WYMeditor.APPLY_CLASS:
jQuery(this._box).find(this._options.classUnhiddenSelector).toggleClass(this._options.classHiddenSelector.substring(1)); // substring(1) to remove the . at the start
jQuery(this._box).find("a[name=" + WYMeditor.APPLY_CLASS +"]").toggleClass('selected');
//this.dialog(WYMeditor.DIALOG_CLASS);
break;
default:
this._exec(cmd);
break;
}
};
/* @name container
* @description Get/Set the selected container
*/
WYMeditor.editor.prototype.container = function(sType) {
if(sType) {
var container = null;
if(sType.toLowerCase() == WYMeditor.TH) {
container = this.container();
//find the TD or TH container
switch(container.tagName.toLowerCase()) {
case WYMeditor.TD: case WYMeditor.TH:
break;
default:
var aTypes = new Array(WYMeditor.TD,WYMeditor.TH);
container = this.findUp(this.container(), aTypes);
break;
}
//if it exists, switch
if(container!=null) {
sType = (container.tagName.toLowerCase() == WYMeditor.TD)? WYMeditor.TH: WYMeditor.TD;
this.switchTo(container,sType);
this.update();
}
} else {
//set the container type
var aTypes=new Array(WYMeditor.P,WYMeditor.H1,WYMeditor.H2,WYMeditor.H3,WYMeditor.H4,WYMeditor.H5,
WYMeditor.H6,WYMeditor.PRE,WYMeditor.BLOCKQUOTE);
container = this.findUp(this.container(), aTypes);
if(container) {
var newNode = null;
//blockquotes must contain a block level element
if(sType.toLowerCase() == WYMeditor.BLOCKQUOTE) {
var blockquote = this.findUp(this.container(), WYMeditor.BLOCKQUOTE);
if(blockquote == null) {
newNode = this._doc.createElement(sType);
container.parentNode.insertBefore(newNode,container);
newNode.appendChild(container);
this.setFocusToNode(newNode.firstChild);
} else {
var nodes = blockquote.childNodes;
var lgt = nodes.length;
var firstNode = null;
if(lgt > 0) firstNode = nodes.item(0);
for(var x=0; x<lgt; x++) {
blockquote.parentNode.insertBefore(nodes.item(0),blockquote);
}
blockquote.parentNode.removeChild(blockquote);
if(firstNode) this.setFocusToNode(firstNode);
}
}
else this.switchTo(container,sType);
this.update();
}
}
}
else return(this.selected());
};
/* @name toggleClass
* @description Toggles class on selected element, or one of its parents
*/
WYMeditor.editor.prototype.toggleClass = function(sClass, jqexpr) {
var container = jQuery((this._selected_image ? this._selected_image : this.selected(true)));
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.toggleClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
};
/* @name removeClass
* @description Removes class on selected element, or one of its parents
*/
WYMeditor.editor.prototype.removeClass = function(sClass, jqexpr) {
var container = jQuery((this._selected_image ? this._selected_image : jQuery(this.selected(true))));
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.removeClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
}
/* @name findUp
* @description Returns the first parent or self container, based on its type
*/
WYMeditor.editor.prototype.findUp = function(node, filter) {
//filter is a string or an array of strings
if(node) {
var tagname = node.tagName.toLowerCase();
if(typeof(filter) == WYMeditor.STRING) {
while(tagname != filter && tagname != WYMeditor.BODY) {
node = node.parentNode;
tagname = node.tagName.toLowerCase();
}
} else {
var bFound = false;
while(!bFound && tagname != WYMeditor.BODY) {
for(var i = 0; i < filter.length; i++) {
if(tagname == filter[i]) {
bFound = true;
break;
}
}
if(!bFound) {
node = node.parentNode;
tagname = node.tagName.toLowerCase();
}
}
}
if(tagname != WYMeditor.BODY) return(node);
else return(null);
} else return(null);
};
/* @name switchTo
* @description Switch the node's type
*/
WYMeditor.editor.prototype.switchTo = function(selectionOrNode,sType) {
if (selectionOrNode.getRangeAt) {
// We have a selection object so we need to create a temporary node around it (bold is easy). This node will be replaced anyway.
this.exec(WYMeditor.BOLD);
selectionOrNode = selectionOrNode.focusNode.parentNode;
}
// we have a node.
var html = jQuery(selectionOrNode).html();
var newNode = this._doc.createElement(sType);
selectionOrNode.parentNode.replaceChild(newNode,selectionOrNode);
jQuery(newNode).html(html);
this.setFocusToNode(newNode);
return newNode;
};
WYMeditor.editor.prototype.replaceStrings = function(sVal) {
//check if the language file has already been loaded
//if not, get it via a synchronous ajax call
if(!WYMeditor.STRINGS[this._options.lang]) {
try {
eval(jQuery.ajax({url:this._options.langPath
+ this._options.lang + '.js', async:false}).responseText);
} catch(e) {
if (WYMeditor.console) {
WYMeditor.console.error("WYMeditor: error while parsing language file.");
}
return sVal;
}
}
//replace all the strings in sVal and return it
for (var key in WYMeditor.STRINGS[this._options.lang]) {
sVal = WYMeditor.Helper.replaceAll(sVal, this._options.stringDelimiterLeft + key
+ this._options.stringDelimiterRight,
WYMeditor.STRINGS[this._options.lang][key]);
};
return(sVal);
};
WYMeditor.editor.prototype.encloseString = function(sVal) {
return(this._options.stringDelimiterLeft
+ sVal
+ this._options.stringDelimiterRight);
};
/* @name status
* @description Prints a status message
*/
WYMeditor.editor.prototype.status = function(sMessage) {
//print status message
jQuery(this._box).find(this._options.statusSelector).html(sMessage);
};
/* @name update
* @description Updates the element and textarea values
*/
WYMeditor.editor.prototype.update = function() {
var html = this.xhtml().gsub(/<\/([A-Za-z0-9]*)></, function(m){return "</" + m[1] +">\n<"}).gsub(/src=\"system\/images/, 'src="/system/images'); // make system/images calls absolute.
jQuery(this._element).val(html);
jQuery(this._box).find(this._options.htmlValSelector).val(html);
};
/* @name dialog
* @description Opens a dialog box
*/
WYMeditor.editor.prototype.dialog = function( dialogType ) {
var path = this._wym._options.dialogPath + dialogType + this._wym._options.dialogFeatures;
this._current_unique_stamp = this.uniqueStamp();
// change undo or redo on cancel to true to have this happen when a user closes (cancels) a dialogue
this._undo_on_cancel = false;
this._redo_on_cancel = false;
//set to P if parent = BODY
if (![WYMeditor.DIALOG_TABLE, WYMeditor.DIALOG_PASTE].include(dialogType))
{
var container = this.selected();
if (container != null){
if(container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
}
else {
// somehow select the wymeditor textarea or simulate a click or a keydown on it.
}
}
selected = this.selected();
if (dialogType == WYMeditor.DIALOG_LINK && jQuery.browser.mozilla) {
selection = this._iframe.contentWindow.getSelection();
matches = selected.innerHTML.match(new RegExp(RegExp.escape(selection.anchorNode.textContent) + "(.*)" + RegExp.escape(selection.focusNode.textContent)));
if (matches != null && matches.length > 0 && (possible_anchor_tag = matches.last()) != null) {
if (((href_matches = possible_anchor_tag.match(/href="([^"]*)"/)) != null) && (href = href_matches.last()) != null) {
possible_anchors = this._iframe.document().getElementsByTagName('a');
for (i=0;i<possible_anchors.length;i++) {
if ((possible_match = possible_anchors[i]).innerHTML == selection) {
selected = possible_match;
}
}
}
}
}
// set up handlers.
imageGroup = null;
ajax_loaded_callback = function(){this.dialog_ajax_callback(selected)}.bind(this, selected);
var parent_node = null;
if (this._selected_image) {
parent_node = this._selected_image.parentNode;
}
else {
parent_node = selected;
}
if (parent_node != null && parent_node.tagName.toLowerCase() != WYMeditor.A)
{
// wrap the current selection with a funky span (not required for safari)
if (!this._selected_image && !jQuery.browser.safari)
{
this.wrap("<span id='replace_me_with_" + this._current_unique_stamp + "'>", "</span>");
}
}
else {
if (!this._selected_image) {
parent_node._id_before_replaceable = parent.id;
parent_node.id = 'replace_me_with_' + this._current_unique_stamp;
}
path += (this._wym._options.dialogFeatures.length == 0) ? "?" : "&"
port = (window.location.port.length > 0 ? (":" + window.location.port) : "")
path += "current_link=" + parent_node.href.gsub(window.location.protocol + "//" + window.location.hostname + port, "");
path += "&target_blank=" + (parent_node.target == "_blank" ? "true" : "false")
}
// launch thickbox
dialog_title = this.replaceStrings(this.encloseString( dialogType ));
switch(dialogType) {
case WYMeditor.DIALOG_TABLE: {
dialog_container = document.createElement("div");
dialog_container.id = 'inline_dialog_container';
dialog_container.innerHTML = this.replaceStrings(this._options.dialogTableHtml);
jQuery(document.body).after(dialog_container);
tb_show(dialog_title, "#" + this._options.dialogInlineFeatures + "&inlineId=inline_dialog_container&TB_inline=true&modal=true", imageGroup);
ajax_loaded_callback();
break;
}
case WYMeditor.DIALOG_PASTE: {
dialog_container = document.createElement("div");
dialog_container.id = 'inline_dialog_container';
dialog_container.innerHTML = this.replaceStrings(this._options.dialogPasteHtml);
jQuery(document.body).after(dialog_container);
tb_show(dialog_title, "#" + this._options.dialogInlineFeatures + "&inlineId=inline_dialog_container&TB_inline=true&modal=true", imageGroup);
ajax_loaded_callback();
break;
}
default:
{
tb_show(dialog_title, path, imageGroup, ajax_loaded_callback);
break;
}
}
};
WYMeditor.editor.prototype.dialog_ajax_callback = function(selected) {
// look for iframes
if ((iframes = $(this._options.dialogId).select('iframe')).length > 0 && (iframe = $(iframes[0])) != null)
{
iframe.observe('load', function(selected, e)
{
WYMeditor.INIT_DIALOG(this, selected);
iframe.stopObserving('load');
}.bind(this, selected));
}
else
{
WYMeditor.INIT_DIALOG(this, selected);
}
};
/* @name toggleHtml
* @description Shows/Hides the HTML
*/
WYMeditor.editor.prototype.toggleHtml = function() {
jQuery(this._box).find(this._options.htmlSelector).toggle();
};
WYMeditor.editor.prototype.uniqueStamp = function() {
return("wym-" + new Date().getTime());
};
WYMeditor.editor.prototype.paste = function(sData) {
console.log('pasting..');
var sTmp;
var container = this.selected();
//split the data, using double newlines as the separator
var aP = sData.split(this._newLine + this._newLine);
var rExp = new RegExp(this._newLine, "g");
//add a P for each item
if(container && container.tagName.toLowerCase() != WYMeditor.BODY) {
for(x = aP.length - 1; x >= 0; x--) {
sTmp = aP[x];
//simple newlines are replaced by a break
sTmp = sTmp.replace(rExp, "<br />");
jQuery(container).after("<p>" + sTmp + "</p>");
}
} else {
for(x = 0; x < aP.length; x++) {
sTmp = aP[x];
//simple newlines are replaced by a break
sTmp = sTmp.replace(rExp, "<br />");
jQuery(this._doc.body).append("<p>" + sTmp + "</p>");
}
}
};
WYMeditor.editor.prototype.insert = function(html) {
// Do we have a selection?
if (this._iframe.contentWindow.getSelection().focusNode != null) {
// Overwrite selection with provided html
this._exec( WYMeditor.INSERT_HTML, html);
} else {
// Fall back to the internal paste function if there's no selection
this.paste(html);
}
};
WYMeditor.editor.prototype.wrap = function(left, right, selection) {
// Do we have a selection?
if (selection == null) { selection = this._iframe.contentWindow.getSelection();}
if (selection.focusNode != null) {
// Wrap selection with provided html
this._exec( WYMeditor.INSERT_HTML, left + selection.toString() + right);
}
};
WYMeditor.editor.prototype.unwrap = function(selection) {
// Do we have a selection?
if (selection == null) { selection = this._iframe.contentWindow.getSelection();}
if (selection.focusNode != null) {
// Unwrap selection
this._exec( WYMeditor.INSERT_HTML, selection.toString() );
}
};
WYMeditor.editor.prototype.addCssRules = function(doc, aCss) {
var styles = doc.styleSheets[0];
if(styles) {
for(var i = 0; i < aCss.length; i++) {
var oCss = aCss[i];
if(oCss.name && oCss.css) this.addCssRule(styles, oCss);
}
}
};
/********** CONFIGURATION **********/
WYMeditor.editor.prototype.computeBasePath = function() {
if ((script_path = this.computeWymPath()) != null) {
if ((src_parts = script_path.split('/')).length > 1) { src_parts.pop(); }
return src_parts.join('/') + "/";
}
else {
return null;
}
};
WYMeditor.editor.prototype.computeWymPath = function() {
return jQuery('script[src*=jquery.refinery.wymeditor]').attr('src');
};
WYMeditor.editor.prototype.computeJqueryPath = function() {
return jQuery(jQuery.grep(jQuery('script'), function(s){
return (s.src && s.src.match(/jquery(-(.*)){0,1}(\.pack|\.min|\.packed)?\.js(\?.*)?$/ ))
})).attr('src');
};
WYMeditor.editor.prototype.computeCssPath = function() {
return jQuery(jQuery.grep(jQuery('link'), function(s){
return (s.href && s.href.match(/wymeditor\/skins\/(.*)screen\.css(\?.*)?$/ ))
})).attr('href');
};
WYMeditor.editor.prototype.configureEditorUsingRawCss = function() {
var CssParser = new WYMeditor.WymCssParser();
if(this._options.stylesheet){
CssParser.parse(jQuery.ajax({url: this._options.stylesheet,async:false}).responseText);
}else{
CssParser.parse(this._options.styles, false);
}
if(this._options.classesItems.length == 0) {
this._options.classesItems = CssParser.css_settings.classesItems;
}
if(this._options.editorStyles.length == 0) {
this._options.editorStyles = CssParser.css_settings.editorStyles;
}
if(this._options.dialogStyles.length == 0) {
this._options.dialogStyles = CssParser.css_settings.dialogStyles;
}
};
/********** EVENTS **********/
WYMeditor.editor.prototype.listen = function() {
//don't use jQuery.find() on the iframe body
//because of MSIE + jQuery + expando issue (#JQ1143)
//jQuery(this._doc.body).find("*").bind("mouseup", this.mouseup);
jQuery(this._doc.body).bind("mousedown", this.mousedown);
var images = this._doc.body.getElementsByTagName("img");
for(var i=0; i < images.length; i++) {
jQuery(images[i]).bind("mousedown", this.mousedown);
}
};
WYMeditor.editor.prototype.mousedown = function(evt) {
var wym = WYMeditor.INSTANCES[this.ownerDocument.title];
wym._selected_image = (this.tagName.toLowerCase() == WYMeditor.IMG) ? this : null;
evt.stopPropagation();
};
/********** SKINS **********/
/*
* Function: WYMeditor.loadCss
* Loads a stylesheet in the document.
*
* Parameters:
* href - The CSS path.
*/
WYMeditor.loadCss = function(href) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
var head = jQuery('head').get(0);
head.appendChild(link);
};
/*
* Function: WYMeditor.editor.loadSkin
* Loads the skin CSS and initialization script (if needed).
*/
WYMeditor.editor.prototype.loadSkin = function() {
//does the user want to automatically load the CSS (default: yes)?
//we also test if it hasn't been already loaded by another instance
//see below for a better (second) test
if(this._options.loadSkin && !WYMeditor.SKINS[this._options.skin]) {
//check if it hasn't been already loaded
//so we don't load it more than once
//(we check the existing <link> elements)
var found = false;
var rExp = new RegExp(this._options.skin
+ '\/' + WYMeditor.SKINS_DEFAULT_CSS + '$');
jQuery('link').each( function() {
if(this.href.match(rExp)) found = true;
});
//load it, using the skin path
if(!found) WYMeditor.loadCss( this._options.cssSkinPath
+ WYMeditor.SKINS_DEFAULT_CSS );
}
//put the classname (ex. wym_skin_default) on wym_box
jQuery(this._box).addClass( "wym_skin_" + this._options.skin );
//does the user want to use some JS to initialize the skin (default: yes)?
//also check if it hasn't already been loaded by another instance
if(this._options.initSkin && !WYMeditor.SKINS[this._options.skin]) {
eval(jQuery.ajax({url:this._options.jsSkinPath
+ WYMeditor.SKINS_DEFAULT_JS, async:false}).responseText);
}
//init the skin, if needed
if(WYMeditor.SKINS[this._options.skin] && WYMeditor.SKINS[this._options.skin].init)
WYMeditor.SKINS[this._options.skin].init(this);
};
/********** DIALOGS **********/
WYMeditor.INIT_DIALOG = function(wym, selected, isIframe) {
var selected = selected || wym.selected();
var dialog = $(wym._options.dialogId);
var doc = (isIframe ? dialog.select('iframe')[0].document() : document);
var dialogType = doc.getElementById('wym_dialog_type').value;
var replaceable = wym._selected_image ? jQuery(wym._selected_image) : jQuery(wym._doc.body).find('#replace_me_with_' + wym._current_unique_stamp);
[dialog.select("#TB_window .close_dialog"), $(doc.body).select("#TB_window .close_dialog")].flatten().uniq().each(function(button)
{
button.observe('click', function(e){this.close_dialog(e, true)}.bind(wym));
});
/*
switch(dialogType) {
case WYMeditor.DIALOG_LINK:
//ensure that we select the link to populate the fields
if (replaceable[0] != null && replaceable[0].tagName.toLowerCase() == WYMeditor.A)
{
jQuery(wym._options.hrefSelector).val(jQuery(replaceable).attr(WYMeditor.HREF));
jQuery(wym._options.hrefSelector);
}
//fix MSIE selection if link image has been clicked
if(!selected && wym._selected_image)
selected = jQuery(wym._selected_image).parentsOrSelf(WYMeditor.A);
break;
}
*/
//pre-init functions
if(jQuery.isFunction(wym._options.preInitDialog))
wym._options.preInitDialog(wym,window);
/*
//auto populate fields if selected container (e.g. A)
if(selected) {
jQuery(wym._options.hrefSelector).val(jQuery(selected).attr(WYMeditor.HREF));
jQuery(wym._options.srcSelector).val(jQuery(selected).attr(WYMeditor.SRC));
jQuery(wym._options.titleSelector).val(jQuery(selected).attr(WYMeditor.TITLE));
jQuery(wym._options.altSelector).val(jQuery(selected).attr(WYMeditor.ALT));
}*/
//auto populate image fields if selected image
if(wym._selected_image) {
jQuery(wym._options.dialogImageSelector + " " + wym._options.srcSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.SRC));
jQuery(wym._options.dialogImageSelector + " " + wym._options.titleSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.TITLE));
jQuery(wym._options.dialogImageSelector + " " + wym._options.altSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.ALT));
}
jQuery(wym._options.dialogLinkSelector + " " + wym._options.submitSelector).click(function()
{
var sUrl = jQuery(wym._options.hrefSelector).val();
if(sUrl.length > 0)
{
if (replaceable[0] != null) {
link = wym._doc.createElement("a");
link.href = sUrl;
link.title = jQuery(wym._options.titleSelector).val();
target = jQuery(wym._options.targetSelector).val();
if (target != null && target.length > 0) {
link.target = target;
}
// now grab what was selected in the editor and chuck it inside the link.
if (!wym._selected_image)
{
replaceable.after(link);
link.innerHTML = replaceable.html();
replaceable.remove();
}
else
{
if ((parent = replaceable[0].parentNode) != null && parent.tagName.toUpperCase() == "A") {
parent.href = link.href;
parent.title = jQuery(wym._options.titleSelector).val();
parent.target = target;
}
else {
replaceable.before(link);
jQuery(link).append(replaceable[0]);
}
}
}
else {
wym._exec(WYMeditor.CREATE_LINK, wym._current_unique_stamp);
jQuery("a[href=" + wym._current_unique_stamp + "]", wym._doc.body)
.attr(WYMeditor.HREF, sUrl)
.attr(WYMeditor.TITLE, jQuery(wym._options.titleSelector).val())
.attr(WYMeditor.TARGET, jQuery(wym._options.targetSelector).val());
}
}
// fire a click event on the dialogs close button
wym.close_dialog()
});
jQuery(wym._options.dialogImageSelector + " " + wym._options.submitSelector).click(function() {
form = jQuery(this.form);
var sUrl = form.find(wym._options.srcSelector).val();
var sTitle = form.find(wym._options.titleSelector).val();
var sAlt = form.find(wym._options.altSelector).val();
if (sUrl != null && sUrl.length > 0) {
wym._exec(WYMeditor.INSERT_IMAGE, wym._current_unique_stamp, selected);
//don't use jQuery.find() see #JQ1143
//var image = jQuery(wym._doc.body).find("img[@src=" + sStamp + "]");
var image = null;
var nodes = wym._doc.body.getElementsByTagName(WYMeditor.IMG);
for(var i=0; i < nodes.length; i++)
{
if(jQuery(nodes[i]).attr(WYMeditor.SRC) == wym._current_unique_stamp)
{
image = jQuery(nodes[i]);
break;
}
}
if(image) {
image.attr(WYMeditor.SRC, sUrl);
image.attr(WYMeditor.TITLE, sTitle);
image.attr(WYMeditor.ALT, sAlt);
if (!jQuery.browser.safari)
{
if (replaceable != null)
{
if (this._selected_image == null || (this._selected_image != null && replaceable.parentNode != null))
{
replaceable.after(image);
replaceable.remove();
}
}
}
}
// fire a click event on the dialogs close button
wym.close_dialog();
}
});
jQuery(wym._options.dialogTableSelector + " " + wym._options.submitSelector).click(function() {
var iRows = jQuery(wym._options.rowsSelector).val();
var iCols = jQuery(wym._options.colsSelector).val();
if(iRows > 0 && iCols > 0)
{
var table = wym._doc.createElement(WYMeditor.TABLE);
var newRow = null;
var newCol = null;
var sCaption = jQuery(wym._options.captionSelector).val();
//we create the caption
var newCaption = table.createCaption();
newCaption.innerHTML = sCaption;
//we create the rows and cells
for(x=0; x<iRows; x++) {
newRow = table.insertRow(x);
for(y=0; y<iCols; y++) {newRow.insertCell(y);}
}
//append the table after the selected container
var node = jQuery(wym.findUp(wym.container(),
WYMeditor.MAIN_CONTAINERS)).get(0);
if(!node || !node.parentNode) jQuery(wym._doc.body).append(table);
else jQuery(node).after(table);
}
// fire a click event on the dialogs close button
wym.close_dialog();
});
jQuery(wym._options.dialogPasteSelector + " " + wym._options.submitSelector).click(function() {
var sText = jQuery(wym._options.textSelector).val();
wym.paste(sText);
// fire a click event on the dialogs close button
wym.close_dialog();
});
jQuery(wym._options.dialogPreviewSelector + " "
+ wym._options.previewSelector)
.html(wym.xhtml());
//post-init functions
if(jQuery.isFunction(wym._options.postInitDialog))
wym._options.postInitDialog(wym,window);
};
WYMeditor.editor.prototype.close_dialog = function(e, cancelled) {
if (cancelled)
{
// if span exists, repalce it with its own html contents.
replaceable = jQuery(this._doc.body).find('#replace_me_with_' + this._current_unique_stamp);
if (replaceable[0] != null) {
if (replaceable[0].tagName.toLowerCase() != WYMeditor.A) {
replaceable.replaceWith(replaceable.html());
}
else {
replaceable[0].id = replaceable[0]._id_before_replaceable;
}
}
if (this._undo_on_cancel == true) {
this._exec("undo");
}
else if (this._redo_on_cancel == true) {
this._exec("redo");
}
}
if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8)
{
this._iframe.contentWindow.focus();
}
if ((inline_dialog_container = $('inline_dialog_container')) != null)
{
inline_dialog_container.remove();
}
tb_remove();
if (e) {
e.stop();
}
}
/********** XHTML LEXER/PARSER **********/
/*
* @name xml
* @description Use these methods to generate XML and XHTML compliant tags and
* escape tag attributes correctly
* @author Bermi Ferrer - http://bermi.org
* @author David Heinemeier Hansson http://loudthinking.com
*/
WYMeditor.XmlHelper = function()
{
this._entitiesDiv = document.createElement('div');
return this;
};
/*
* @name tag
* @description
* Returns an empty HTML tag of type *name* which by default is XHTML
* compliant. Setting *open* to true will create an open tag compatible
* with HTML 4.0 and below. Add HTML attributes by passing an attributes
* array to *options*. For attributes with no value like (disabled and
* readonly), give it a value of true in the *options* array.
*
* Examples:
*
* this.tag('br')
* # => <br />
* this.tag ('br', false, true)
* # => <br>
* this.tag ('input', jQuery({type:'text',disabled:true }) )
* # => <input type="text" disabled="disabled" />
*/
WYMeditor.XmlHelper.prototype.tag = function(name, options, open)
{
options = options || false;
open = open || false;
return '<'+name+(options ? this.tagOptions(options) : '')+(open ? '>' : ' />');
};
/*
* @name contentTag
* @description
* Returns a XML block tag of type *name* surrounding the *content*. Add
* XML attributes by passing an attributes array to *options*. For attributes
* with no value like (disabled and readonly), give it a value of true in
* the *options* array. You can use symbols or strings for the attribute names.
*
* this.contentTag ('p', 'Hello world!' )
* # => <p>Hello world!</p>
* this.contentTag('div', this.contentTag('p', "Hello world!"), jQuery({class : "strong"}))
* # => <div class="strong"><p>Hello world!</p></div>
* this.contentTag("select", options, jQuery({multiple : true}))
* # => <select multiple="multiple">...options...</select>
*/
WYMeditor.XmlHelper.prototype.contentTag = function(name, content, options)
{
options = options || false;
return '<'+name+(options ? this.tagOptions(options) : '')+'>'+content+'</'+name+'>';
};
/*
* @name cdataSection
* @description
* Returns a CDATA section for the given +content+. CDATA sections
* are used to escape blocks of text containing characters which would
* otherwise be recognized as markup. CDATA sections begin with the string
* <tt><![CDATA[</tt> and } with (and may not contain) the string
* <tt>]]></tt>.
*/
WYMeditor.XmlHelper.prototype.cdataSection = function(content)
{
return '<![CDATA['+content+']]>';
};
/*
* @name escapeOnce
* @description
* Returns the escaped +xml+ without affecting existing escaped entities.
*
* this.escapeOnce( "1 > 2 & 3")
* # => "1 > 2 & 3"
*/
WYMeditor.XmlHelper.prototype.escapeOnce = function(xml)
{
return this._fixDoubleEscape(this.escapeEntities(xml));
};
/*
* @name _fixDoubleEscape
* @description
* Fix double-escaped entities, such as &amp;, &#123;, etc.
*/
WYMeditor.XmlHelper.prototype._fixDoubleEscape = function(escaped)
{
return escaped.replace(/&([a-z]+|(#\d+));/ig, "&$1;");
};
/*
* @name tagOptions
* @description
* Takes an array like the one generated by Tag.parseAttributes
* [["src", "http://www.editam.com/?a=b&c=d&f=g"], ["title", "Editam, <Simplified> CMS"]]
* or an object like {src:"http://www.editam.com/?a=b&c=d&f=g", title:"Editam, <Simplified> CMS"}
* and returns a string properly escaped like
* ' src = "http://www.editam.com/?a=b&c=d&f=g" title = "Editam, <Simplified> CMS"'
* which is valid for strict XHTML
*/
WYMeditor.XmlHelper.prototype.tagOptions = function(options)
{
var xml = this;
xml._formated_options = '';
for (var key in options) {
var formated_options = '';
var value = options[key];
if(typeof value != 'function' && value.length > 0) {
if(parseInt(key) == key && typeof value == 'object'){
key = value.shift();
value = value.pop();
}
if(key != '' && value != ''){
xml._formated_options += ' '+key+'="'+xml.escapeOnce(value)+'"';
}
}
}
return xml._formated_options;
};
/*
* @name escapeEntities
* @description
* Escapes XML/HTML entities <, >, & and ". If seccond parameter is set to false it
* will not escape ". If set to true it will also escape '
*/
WYMeditor.XmlHelper.prototype.escapeEntities = function(string, escape_quotes)
{
this._entitiesDiv.innerHTML = string;
this._entitiesDiv.textContent = string;
var result = this._entitiesDiv.innerHTML;
if(typeof escape_quotes == 'undefined'){
if(escape_quotes != false) result = result.replace('"', '"');
if(escape_quotes == true) result = result.replace('"', ''');
}
return result;
};
/*
* Parses a string conatining tag attributes and values an returns an array formated like
* [["src", "http://www.editam.com"], ["title", "Editam, Simplified CMS"]]
*/
WYMeditor.XmlHelper.prototype.parseAttributes = function(tag_attributes)
{
// Use a compounded regex to match single quoted, double quoted and unquoted attribute pairs
var result = [];
var matches = tag_attributes.split(/((=\s*")(")("))|((=\s*\')(\')(\'))|((=\s*[^>\s]*))/g);
if(matches.toString() != tag_attributes){
for (var k in matches) {
var v = matches[k];
if(typeof v != 'function' && v.length != 0){
var re = new RegExp('(\\w+)\\s*'+v);
if(match = tag_attributes.match(re) ){
var value = v.replace(/^[\s=]+/, "");
var delimiter = value.charAt(0);
delimiter = delimiter == '"' ? '"' : (delimiter=="'"?"'":'');
if(delimiter != ''){
value = delimiter == '"' ? value.replace(/^"|"+$/g, '') : value.replace(/^'|'+$/g, '');
}
tag_attributes = tag_attributes.replace(match[0],'');
result.push([match[1] , value]);
}
}
}
}
return result;
};
/**
* XhtmlValidator for validating tag attributes
*
* @author Bermi Ferrer - http://bermi.org
*/
WYMeditor.XhtmlValidator = {
"_attributes":
{
"core":
{
"except":[
"base",
"head",
"html",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"class",
"id",
"style",
"title",
"accesskey",
"tabindex"
]
},
"language":
{
"except":[
"base",
"br",
"hr",
"iframe",
"param",
"script"
],
"attributes":
{
"dir":[
"ltr",
"rtl"
],
"0":"lang",
"1":"xml:lang"
}
},
"keyboard":
{
"attributes":
{
"accesskey":/^(\w){1}$/,
"tabindex":/^(\d)+$/
}
}
},
"_events":
{
"window":
{
"only":[
"body"
],
"attributes":[
"onload",
"onunload"
]
},
"form":
{
"only":[
"form",
"input",
"textarea",
"select",
"a",
"label",
"button"
],
"attributes":[
"onchange",
"onsubmit",
"onreset",
"onselect",
"onblur",
"onfocus"
]
},
"keyboard":
{
"except":[
"base",
"bdo",
"br",
"frame",
"frameset",
"head",
"html",
"iframe",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"onkeydown",
"onkeypress",
"onkeyup"
]
},
"mouse":
{
"except":[
"base",
"bdo",
"br",
"head",
"html",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"onclick",
"ondblclick",
"onmousedown",
"onmousemove",
"onmouseover",
"onmouseout",
"onmouseup"
]
}
},
"_tags":
{
"a":
{
"attributes":
{
"0":"charset",
"1":"coords",
"2":"href",
"3":"hreflang",
"4":"name",
"rel":/^(alternate|designates|stylesheet|start|next|prev|contents|index|glossary|copyright|chapter|section|subsection|appendix|help|bookmark| |shortcut|icon|moodalbox)+$/,
"rev":/^(alternate|designates|stylesheet|start|next|prev|contents|index|glossary|copyright|chapter|section|subsection|appendix|help|bookmark| |shortcut|icon|moodalbox)+$/,
"shape":/^(rect|rectangle|circ|circle|poly|polygon)$/,
"5":"type",
"target":/^(_blank)+$/
}
},
"0":"abbr",
"1":"acronym",
"2":"address",
"area":
{
"attributes":
{
"0":"alt",
"1":"coords",
"2":"href",
"nohref":/^(true|false)$/,
"shape":/^(rect|rectangle|circ|circle|poly|polygon)$/
},
"required":[
"alt"
]
},
"3":"b",
"base":
{
"attributes":[
"href"
],
"required":[
"href"
]
},
"bdo":
{
"attributes":
{
"dir":/^(ltr|rtl)$/
},
"required":[
"dir"
]
},
"4":"big",
"blockquote":
{
"attributes":[
"cite"
]
},
"5":"body",
"6":"br",
"button":
{
"attributes":
{
"disabled":/^(disabled)$/,
"type":/^(button|reset|submit)$/,
"0":"value"
},
"inside":"form"
},
"7":"caption",
"8":"cite",
"9":"code",
"col":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"span":/^(\d)+$/,
"valign":/^(top|middle|bottom|baseline)$/,
"2":"width"
},
"inside":"colgroup"
},
"colgroup":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"span":/^(\d)+$/,
"valign":/^(top|middle|bottom|baseline)$/,
"2":"width"
}
},
"10":"dd",
"del":
{
"attributes":
{
"0":"cite",
"datetime":/^([0-9]){8}/
}
},
"11":"div",
"12":"dfn",
"13":"dl",
"14":"dt",
"15":"em",
"fieldset":
{
"inside":"form"
},
"form":
{
"attributes":
{
"0":"action",
"1":"accept",
"2":"accept-charset",
"3":"enctype",
"method":/^(get|post)$/
},
"required":[
"action"
]
},
"head":
{
"attributes":[
"profile"
]
},
"16":"h1",
"17":"h2",
"18":"h3",
"19":"h4",
"20":"h5",
"21":"h6",
"22":"hr",
"html":
{
"attributes":[
"xmlns"
]
},
"23":"i",
"iframe":
{
"attributes":[
"src",
"width",
"height",
"frameborder",
"scrolling",
"marginheight",
"marginwidth"
],
"required":[
"src"
]
},
"img":
{
"attributes":{
"align":/^(right|left|center|justify)$/,
"0":"alt",
"1":"src",
"2":"height",
"3":"ismap",
"4":"longdesc",
"5":"usemap",
"6":"width"
},
"required":[
"alt",
"src"
]
},
"input":
{
"attributes":
{
"0":"accept",
"1":"alt",
"checked":/^(checked)$/,
"disabled":/^(disabled)$/,
"maxlength":/^(\d)+$/,
"2":"name",
"readonly":/^(readonly)$/,
"size":/^(\d)+$/,
"3":"src",
"type":/^(button|checkbox|file|hidden|image|password|radio|reset|submit|text)$/,
"4":"value"
},
"inside":"form"
},
"ins":
{
"attributes":
{
"0":"cite",
"datetime":/^([0-9]){8}/
}
},
"24":"kbd",
"label":
{
"attributes":[
"for"
],
"inside":"form"
},
"25":"legend",
"26":"li",
"link":
{
"attributes":
{
"0":"charset",
"1":"href",
"2":"hreflang",
"media":/^(all|braille|print|projection|screen|speech|,|;| )+$/i,
//next comment line required by Opera!
/*"rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,*/
"rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
"rev":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
"3":"type"
},
"inside":"head"
},
"map":
{
"attributes":[
"id",
"name"
],
"required":[
"id"
]
},
"meta":
{
"attributes":
{
"0":"content",
"http-equiv":/^(content\-type|expires|refresh|set\-cookie)$/i,
"1":"name",
"2":"scheme"
},
"required":[
"content"
]
},
"27":"noscript",
"28":"ol",
"optgroup":
{
"attributes":
{
"0":"label",
"disabled": /^(disabled)$/
},
"required":[
"label"
]
},
"option":
{
"attributes":
{
"0":"label",
"disabled":/^(disabled)$/,
"selected":/^(selected)$/,
"1":"value"
},
"inside":"select"
},
"29":"p",
"param":
{
"attributes":
[
"type",
"value",
"name"
],
"required":[
"name"
],
"inside":"object"
},
"embed":
{
"attributes":
[
"width",
"height",
"allowfullscreen",
"allowscriptaccess",
"wmode",
"type",
"src"
],
"inside":"object"
},
"object":
{
"attributes":[
"archive",
"classid",
"codebase",
"codetype",
"data",
"declare",
"height",
"name",
"standby",
"type",
"usemap",
"width"
]
},
"30":"pre",
"q":
{
"attributes":[
"cite"
]
},
"31":"samp",
"script":
{
"attributes":
{
"type":/^(text\/ecmascript|text\/javascript|text\/jscript|text\/vbscript|text\/vbs|text\/xml)$/,
"0":"charset",
"defer":/^(defer)$/,
"1":"src"
},
"required":[
"type"
]
},
"select":
{
"attributes":
{
"disabled":/^(disabled)$/,
"multiple":/^(multiple)$/,
"0":"name",
"1":"size"
},
"inside":"form"
},
"32":"small",
"33":"span",
"34":"strong",
"style":
{
"attributes":
{
"0":"type",
"media":/^(screen|tty|tv|projection|handheld|print|braille|aural|all)$/
},
"required":[
"type"
]
},
"35":"sub",
"36":"sup",
"table":
{
"attributes":
{
"0":"border",
"1":"cellpadding",
"2":"cellspacing",
"frame":/^(void|above|below|hsides|lhs|rhs|vsides|box|border)$/,
"rules":/^(none|groups|rows|cols|all)$/,
"3":"summary",
"4":"width"
}
},
"tbody":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"td":
{
"attributes":
{
"0":"abbr",
"align":/^(left|right|center|justify|char)$/,
"1":"axis",
"2":"char",
"3":"charoff",
"colspan":/^(\d)+$/,
"4":"headers",
"rowspan":/^(\d)+$/,
"scope":/^(col|colgroup|row|rowgroup)$/,
"valign":/^(top|middle|bottom|baseline)$/
}
},
"textarea":
{
"attributes":[
"cols",
"rows",
"disabled",
"name",
"readonly"
],
"required":[
"cols",
"rows"
],
"inside":"form"
},
"tfoot":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom)$/,
"2":"baseline"
}
},
"th":
{
"attributes":
{
"0":"abbr",
"align":/^(left|right|center|justify|char)$/,
"1":"axis",
"2":"char",
"3":"charoff",
"colspan":/^(\d)+$/,
"4":"headers",
"rowspan":/^(\d)+$/,
"scope":/^(col|colgroup|row|rowgroup)$/,
"valign":/^(top|middle|bottom|baseline)$/
}
},
"thead":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"37":"title",
"tr":
{
"attributes":
{
"align":/^(right|left|center|justify|char)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"38":"tt",
"39":"ul",
"40":"var"
},
// Temporary skiped attributes
skiped_attributes : [],
skiped_attribute_values : [],
getValidTagAttributes: function(tag, attributes)
{
var valid_attributes = {};
var possible_attributes = this.getPossibleTagAttributes(tag);
for(var attribute in attributes) {
var value = attributes[attribute];
var h = WYMeditor.Helper;
if(!h.contains(this.skiped_attributes, attribute) && !h.contains(this.skiped_attribute_values, value)){
if (typeof value != 'function' && h.contains(possible_attributes, attribute)) {
if (this.doesAttributeNeedsValidation(tag, attribute)) {
if(this.validateAttribute(tag, attribute, value)){
valid_attributes[attribute] = value;
}
}else{
valid_attributes[attribute] = value;
}
}
}
}
return valid_attributes;
},
getUniqueAttributesAndEventsForTag : function(tag)
{
var result = [];
if (this._tags[tag] && this._tags[tag]['attributes']) {
for (k in this._tags[tag]['attributes']) {
result.push(parseInt(k) == k ? this._tags[tag]['attributes'][k] : k);
}
}
return result;
},
getDefaultAttributesAndEventsForTags : function()
{
var result = [];
for (var key in this._events){
result.push(this._events[key]);
}
for (var key in this._attributes){
result.push(this._attributes[key]);
}
return result;
},
isValidTag : function(tag)
{
if(this._tags[tag]){
return true;
}
for(var key in this._tags){
if(this._tags[key] == tag){
return true;
}
}
return false;
},
getDefaultAttributesAndEventsForTag : function(tag)
{
var default_attributes = [];
if (this.isValidTag(tag)) {
var default_attributes_and_events = this.getDefaultAttributesAndEventsForTags();
for(var key in default_attributes_and_events) {
var defaults = default_attributes_and_events[key];
if(typeof defaults == 'object'){
var h = WYMeditor.Helper;
if ((defaults['except'] && h.contains(defaults['except'], tag)) || (defaults['only'] && !h.contains(defaults['only'], tag))) {
continue;
}
var tag_defaults = defaults['attributes'] ? defaults['attributes'] : defaults['events'];
for(var k in tag_defaults) {
default_attributes.push(typeof tag_defaults[k] != 'string' ? k : tag_defaults[k]);
}
}
}
}
return default_attributes;
},
doesAttributeNeedsValidation: function(tag, attribute)
{
return this._tags[tag] && ((this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute]) || (this._tags[tag]['required'] &&
WYMeditor.Helper.contains(this._tags[tag]['required'], attribute)));
},
validateAttribute : function(tag, attribute, value)
{
if ( this._tags[tag] &&
(this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute] && value.length > 0 && !value.match(this._tags[tag]['attributes'][attribute])) || // invalid format
(this._tags[tag] && this._tags[tag]['required'] && WYMeditor.Helper.contains(this._tags[tag]['required'], attribute) && value.length == 0) // required attribute
) {
return false;
}
return typeof this._tags[tag] != 'undefined';
},
getPossibleTagAttributes : function(tag)
{
if (!this._possible_tag_attributes) {
this._possible_tag_attributes = {};
}
if (!this._possible_tag_attributes[tag]) {
this._possible_tag_attributes[tag] = this.getUniqueAttributesAndEventsForTag(tag).concat(this.getDefaultAttributesAndEventsForTag(tag));
}
return this._possible_tag_attributes[tag];
}
};
/**
* Compounded regular expression. Any of
* the contained patterns could match and
* when one does, it's label is returned.
*
* Constructor. Starts with no patterns.
* @param boolean case True for case sensitive, false
* for insensitive.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.ParallelRegex = function(case_sensitive)
{
this._case = case_sensitive;
this._patterns = [];
this._labels = [];
this._regex = null;
return this;
};
/**
* Adds a pattern with an optional label.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string label Label of regex to be returned
* on a match.
* @access public
*/
WYMeditor.ParallelRegex.prototype.addPattern = function(pattern, label)
{
label = label || true;
var count = this._patterns.length;
this._patterns[count] = pattern;
this._labels[count] = label;
this._regex = null;
};
/**
* Attempts to match all patterns at once against
* a string.
* @param string subject String to match against.
*
* @return boolean True on success.
* @return string match First matched portion of
* subject.
* @access public
*/
WYMeditor.ParallelRegex.prototype.match = function(subject)
{
if (this._patterns.length == 0) {
return [false, ''];
}
var matches = subject.match(this._getCompoundedRegex());
if(!matches){
return [false, ''];
}
var match = matches[0];
for (var i = 1; i < matches.length; i++) {
if (matches[i]) {
return [this._labels[i-1], match];
}
}
return [true, matches[0]];
};
/**
* Compounds the patterns into a single
* regular expression separated with the
* "or" operator. Caches the regex.
* Will automatically escape (, ) and / tokens.
* @param array patterns List of patterns in order.
* @access private
*/
WYMeditor.ParallelRegex.prototype._getCompoundedRegex = function()
{
if (this._regex == null) {
for (var i = 0, count = this._patterns.length; i < count; i++) {
this._patterns[i] = '(' + this._untokenizeRegex(this._tokenizeRegex(this._patterns[i]).replace(/([\/\(\)])/g,'\\$1')) + ')';
}
this._regex = new RegExp(this._patterns.join("|") ,this._getPerlMatchingFlags());
}
return this._regex;
};
/**
* Escape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._tokenizeRegex = function(regex)
{
return regex.
replace(/\(\?(i|m|s|x|U)\)/, '~~~~~~Tk1\$1~~~~~~').
replace(/\(\?(\-[i|m|s|x|U])\)/, '~~~~~~Tk2\$1~~~~~~').
replace(/\(\?\=(.*)\)/, '~~~~~~Tk3\$1~~~~~~').
replace(/\(\?\!(.*)\)/, '~~~~~~Tk4\$1~~~~~~').
replace(/\(\?\<\=(.*)\)/, '~~~~~~Tk5\$1~~~~~~').
replace(/\(\?\<\!(.*)\)/, '~~~~~~Tk6\$1~~~~~~').
replace(/\(\?\:(.*)\)/, '~~~~~~Tk7\$1~~~~~~');
};
/**
* Unscape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._untokenizeRegex = function(regex)
{
return regex.
replace(/~~~~~~Tk1(.{1})~~~~~~/, "(?\$1)").
replace(/~~~~~~Tk2(.{2})~~~~~~/, "(?\$1)").
replace(/~~~~~~Tk3(.*)~~~~~~/, "(?=\$1)").
replace(/~~~~~~Tk4(.*)~~~~~~/, "(?!\$1)").
replace(/~~~~~~Tk5(.*)~~~~~~/, "(?<=\$1)").
replace(/~~~~~~Tk6(.*)~~~~~~/, "(?<!\$1)").
replace(/~~~~~~Tk7(.*)~~~~~~/, "(?:\$1)");
};
/**
* Accessor for perl regex mode flags to use.
* @return string Perl regex flags.
* @access private
*/
WYMeditor.ParallelRegex.prototype._getPerlMatchingFlags = function()
{
return (this._case ? "m" : "mi");
};
/**
* States for a stack machine.
*
* Constructor. Starts in named state.
* @param string start Starting state name.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.StateStack = function(start)
{
this._stack = [start];
return this;
};
/**
* Accessor for current state.
* @return string State.
* @access public
*/
WYMeditor.StateStack.prototype.getCurrent = function()
{
return this._stack[this._stack.length - 1];
};
/**
* Adds a state to the stack and sets it
* to be the current state.
* @param string state New state.
* @access public
*/
WYMeditor.StateStack.prototype.enter = function(state)
{
this._stack.push(state);
};
/**
* Leaves the current state and reverts
* to the previous one.
* @return boolean False if we drop off
* the bottom of the list.
* @access public
*/
WYMeditor.StateStack.prototype.leave = function()
{
if (this._stack.length == 1) {
return false;
}
this._stack.pop();
return true;
};
// GLOBALS
WYMeditor.LEXER_ENTER = 1;
WYMeditor.LEXER_MATCHED = 2;
WYMeditor.LEXER_UNMATCHED = 3;
WYMeditor.LEXER_EXIT = 4;
WYMeditor.LEXER_SPECIAL = 5;
/**
* Accepts text and breaks it into tokens.
* Some optimisation to make the sure the
* content is only scanned by the PHP regex
* parser once. Lexer modes must not start
* with leading underscores.
*
* Sets up the lexer in case insensitive matching
* by default.
* @param Parser parser Handling strategy by reference.
* @param string start Starting handler.
* @param boolean case True for case sensitive.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.Lexer = function(parser, start, case_sensitive)
{
start = start || 'accept';
this._case = case_sensitive || false;
this._regexes = {};
this._parser = parser;
this._mode = new WYMeditor.StateStack(start);
this._mode_handlers = {};
this._mode_handlers[start] = start;
return this;
};
/**
* Adds a token search pattern for a particular
* parsing mode. The pattern does not change the
* current mode.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @access public
*/
WYMeditor.Lexer.prototype.addPattern = function(pattern, mode)
{
var mode = mode || "accept";
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern);
if (typeof this._mode_handlers[mode] == 'undefined') {
this._mode_handlers[mode] = mode;
}
};
/**
* Adds a pattern that will enter a new parsing
* mode. Useful for entering parenthesis, strings,
* tags, etc.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @param string new_mode Change parsing to this new
* nested mode.
* @access public
*/
WYMeditor.Lexer.prototype.addEntryPattern = function(pattern, mode, new_mode)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, new_mode);
if (typeof this._mode_handlers[new_mode] == 'undefined') {
this._mode_handlers[new_mode] = new_mode;
}
};
/**
* Adds a pattern that will exit the current mode
* and re-enter the previous one.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Mode to leave.
* @access public
*/
WYMeditor.Lexer.prototype.addExitPattern = function(pattern, mode)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, "__exit");
if (typeof this._mode_handlers[mode] == 'undefined') {
this._mode_handlers[mode] = mode;
}
};
/**
* Adds a pattern that has a special mode. Acts as an entry
* and exit pattern in one go, effectively calling a special
* parser handler for this token only.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @param string special Use this mode for this one token.
* @access public
*/
WYMeditor.Lexer.prototype.addSpecialPattern = function(pattern, mode, special)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, '_'+special);
if (typeof this._mode_handlers[special] == 'undefined') {
this._mode_handlers[special] = special;
}
};
/**
* Adds a mapping from a mode to another handler.
* @param string mode Mode to be remapped.
* @param string handler New target handler.
* @access public
*/
WYMeditor.Lexer.prototype.mapHandler = function(mode, handler)
{
this._mode_handlers[mode] = handler;
};
/**
* Splits the page text into tokens. Will fail
* if the handlers report an error or if no
* content is consumed. If successful then each
* unparsed and parsed token invokes a call to the
* held listener.
* @param string raw Raw HTML text.
* @return boolean True on success, else false.
* @access public
*/
WYMeditor.Lexer.prototype.parse = function(raw)
{
if (typeof this._parser == 'undefined') {
return false;
}
var length = raw.length;
var parsed;
while (typeof (parsed = this._reduce(raw)) == 'object') {
var raw = parsed[0];
var unmatched = parsed[1];
var matched = parsed[2];
var mode = parsed[3];
if (! this._dispatchTokens(unmatched, matched, mode)) {
return false;
}
if (raw == '') {
return true;
}
if (raw.length == length) {
return false;
}
length = raw.length;
}
if (! parsed ) {
return false;
}
return this._invokeParser(raw, WYMeditor.LEXER_UNMATCHED);
};
/**
* Sends the matched token and any leading unmatched
* text to the parser changing the lexer to a new
* mode if one is listed.
* @param string unmatched Unmatched leading portion.
* @param string matched Actual token match.
* @param string mode Mode after match. A boolean
* false mode causes no change.
* @return boolean False if there was any error
* from the parser.
* @access private
*/
WYMeditor.Lexer.prototype._dispatchTokens = function(unmatched, matched, mode)
{
mode = mode || false;
if (! this._invokeParser(unmatched, WYMeditor.LEXER_UNMATCHED)) {
return false;
}
if (typeof mode == 'boolean') {
return this._invokeParser(matched, WYMeditor.LEXER_MATCHED);
}
if (this._isModeEnd(mode)) {
if (! this._invokeParser(matched, WYMeditor.LEXER_EXIT)) {
return false;
}
return this._mode.leave();
}
if (this._isSpecialMode(mode)) {
this._mode.enter(this._decodeSpecial(mode));
if (! this._invokeParser(matched, WYMeditor.LEXER_SPECIAL)) {
return false;
}
return this._mode.leave();
}
this._mode.enter(mode);
return this._invokeParser(matched, WYMeditor.LEXER_ENTER);
};
/**
* Tests to see if the new mode is actually to leave
* the current mode and pop an item from the matching
* mode stack.
* @param string mode Mode to test.
* @return boolean True if this is the exit mode.
* @access private
*/
WYMeditor.Lexer.prototype._isModeEnd = function(mode)
{
return (mode === "__exit");
};
/**
* Test to see if the mode is one where this mode
* is entered for this token only and automatically
* leaves immediately afterwoods.
* @param string mode Mode to test.
* @return boolean True if this is the exit mode.
* @access private
*/
WYMeditor.Lexer.prototype._isSpecialMode = function(mode)
{
return (mode.substring(0,1) == "_");
};
/**
* Strips the magic underscore marking single token
* modes.
* @param string mode Mode to decode.
* @return string Underlying mode name.
* @access private
*/
WYMeditor.Lexer.prototype._decodeSpecial = function(mode)
{
return mode.substring(1);
};
/**
* Calls the parser method named after the current
* mode. Empty content will be ignored. The lexer
* has a parser handler for each mode in the lexer.
* @param string content Text parsed.
* @param boolean is_match Token is recognised rather
* than unparsed data.
* @access private
*/
WYMeditor.Lexer.prototype._invokeParser = function(content, is_match)
{
if (!/ +/.test(content) && ((content === '') || (content === false))) {
return true;
}
var current = this._mode.getCurrent();
var handler = this._mode_handlers[current];
var result;
eval('result = this._parser.' + handler + '(content, is_match);');
return result;
};
/**
* Tries to match a chunk of text and if successful
* removes the recognised chunk and any leading
* unparsed data. Empty strings will not be matched.
* @param string raw The subject to parse. This is the
* content that will be eaten.
* @return array/boolean Three item list of unparsed
* content followed by the
* recognised token and finally the
* action the parser is to take.
* True if no match, false if there
* is a parsing error.
* @access private
*/
WYMeditor.Lexer.prototype._reduce = function(raw)
{
var matched = this._regexes[this._mode.getCurrent()].match(raw);
var match = matched[1];
var action = matched[0];
if (action) {
var unparsed_character_count = raw.indexOf(match);
var unparsed = raw.substr(0, unparsed_character_count);
raw = raw.substring(unparsed_character_count + match.length);
return [raw, unparsed, match, action];
}
return true;
};
/**
* This are the rules for breaking the XHTML code into events
* handled by the provided parser.
*
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlLexer = function(parser)
{
jQuery.extend(this, new WYMeditor.Lexer(parser, 'Text'));
this.mapHandler('Text', 'Text');
this.addTokens();
this.init();
return this;
};
WYMeditor.XhtmlLexer.prototype.init = function()
{
};
WYMeditor.XhtmlLexer.prototype.addTokens = function()
{
this.addCommentTokens('Text');
this.addScriptTokens('Text');
this.addCssTokens('Text');
this.addTagTokens('Text');
};
WYMeditor.XhtmlLexer.prototype.addCommentTokens = function(scope)
{
this.addEntryPattern("<!--", scope, 'Comment');
this.addExitPattern("-->", 'Comment');
};
WYMeditor.XhtmlLexer.prototype.addScriptTokens = function(scope)
{
this.addEntryPattern("<script", scope, 'Script');
this.addExitPattern("</script>", 'Script');
};
WYMeditor.XhtmlLexer.prototype.addCssTokens = function(scope)
{
this.addEntryPattern("<style", scope, 'Css');
this.addExitPattern("</style>", 'Css');
};
WYMeditor.XhtmlLexer.prototype.addTagTokens = function(scope)
{
this.addSpecialPattern("<\\s*[a-z0-9:\-]+\\s*>", scope, 'OpeningTag');
this.addEntryPattern("<[a-z0-9:\-]+"+'[\\\/ \\\>]+', scope, 'OpeningTag');
this.addInTagDeclarationTokens('OpeningTag');
this.addSpecialPattern("</\\s*[a-z0-9:\-]+\\s*>", scope, 'ClosingTag');
};
WYMeditor.XhtmlLexer.prototype.addInTagDeclarationTokens = function(scope)
{
this.addSpecialPattern('\\s+', scope, 'Ignore');
this.addAttributeTokens(scope);
this.addExitPattern('/>', scope);
this.addExitPattern('>', scope);
};
WYMeditor.XhtmlLexer.prototype.addAttributeTokens = function(scope)
{
this.addSpecialPattern("\\s*[a-z-_0-9]*:?[a-z-_0-9]+\\s*(?=\=)\\s*", scope, 'TagAttributes');
this.addEntryPattern('=\\s*"', scope, 'DoubleQuotedAttribute');
this.addPattern("\\\\\"", 'DoubleQuotedAttribute');
this.addExitPattern('"', 'DoubleQuotedAttribute');
this.addEntryPattern("=\\s*'", scope, 'SingleQuotedAttribute');
this.addPattern("\\\\'", 'SingleQuotedAttribute');
this.addExitPattern("'", 'SingleQuotedAttribute');
this.addSpecialPattern('=\\s*[^>\\s]*', scope, 'UnquotedAttribute');
};
/**
* XHTML Parser.
*
* This XHTML parser will trigger the events available on on
* current SaxListener
*
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlParser = function(Listener, mode)
{
var mode = mode || 'Text';
this._Lexer = new WYMeditor.XhtmlLexer(this);
this._Listener = Listener;
this._mode = mode;
this._matches = [];
this._last_match = '';
this._current_match = '';
return this;
};
WYMeditor.XhtmlParser.prototype.parse = function(raw)
{
this._Lexer.parse(this.beforeParsing(raw));
return this.afterParsing(this._Listener.getResult());
};
WYMeditor.XhtmlParser.prototype.beforeParsing = function(raw)
{
if(raw.match(/class="MsoNormal"/) || raw.match(/ns = "urn:schemas-microsoft-com/)){
// Useful for cleaning up content pasted from other sources (MSWord)
this._Listener.avoidStylingTagsAndAttributes();
}
return this._Listener.beforeParsing(raw);
};
WYMeditor.XhtmlParser.prototype.afterParsing = function(parsed)
{
if(this._Listener._avoiding_tags_implicitly){
this._Listener.allowStylingTagsAndAttributes();
}
return this._Listener.afterParsing(parsed);
};
WYMeditor.XhtmlParser.prototype.Ignore = function(match, state)
{
return true;
};
WYMeditor.XhtmlParser.prototype.Text = function(text)
{
this._Listener.addContent(text);
return true;
};
WYMeditor.XhtmlParser.prototype.Comment = function(match, status)
{
return this._addNonTagBlock(match, status, 'addComment');
};
WYMeditor.XhtmlParser.prototype.Script = function(match, status)
{
return this._addNonTagBlock(match, status, 'addScript');
};
WYMeditor.XhtmlParser.prototype.Css = function(match, status)
{
return this._addNonTagBlock(match, status, 'addCss');
};
WYMeditor.XhtmlParser.prototype._addNonTagBlock = function(match, state, type)
{
switch (state){
case WYMeditor.LEXER_ENTER:
this._non_tag = match;
break;
case WYMeditor.LEXER_UNMATCHED:
this._non_tag += match;
break;
case WYMeditor.LEXER_EXIT:
switch(type) {
case 'addComment':
this._Listener.addComment(this._non_tag+match);
break;
case 'addScript':
this._Listener.addScript(this._non_tag+match);
break;
case 'addCss':
this._Listener.addCss(this._non_tag+match);
break;
}
}
return true;
};
WYMeditor.XhtmlParser.prototype.OpeningTag = function(match, state)
{
switch (state){
case WYMeditor.LEXER_ENTER:
this._tag = this.normalizeTag(match);
this._tag_attributes = {};
break;
case WYMeditor.LEXER_SPECIAL:
this._callOpenTagListener(this.normalizeTag(match));
break;
case WYMeditor.LEXER_EXIT:
this._callOpenTagListener(this._tag, this._tag_attributes);
}
return true;
};
WYMeditor.XhtmlParser.prototype.ClosingTag = function(match, state)
{
this._callCloseTagListener(this.normalizeTag(match));
return true;
};
WYMeditor.XhtmlParser.prototype._callOpenTagListener = function(tag, attributes)
{
var attributes = attributes || {};
this.autoCloseUnclosedBeforeNewOpening(tag);
if(this._Listener.isBlockTag(tag)){
this._Listener._tag_stack.push(tag);
this._Listener.fixNestingBeforeOpeningBlockTag(tag, attributes);
this._Listener.openBlockTag(tag, attributes);
this._increaseOpenTagCounter(tag);
}else if(this._Listener.isInlineTag(tag)){
this._Listener.inlineTag(tag, attributes);
}else{
this._Listener.openUnknownTag(tag, attributes);
this._increaseOpenTagCounter(tag);
}
this._Listener.last_tag = tag;
this._Listener.last_tag_opened = true;
this._Listener.last_tag_attributes = attributes;
};
WYMeditor.XhtmlParser.prototype._callCloseTagListener = function(tag)
{
if(this._decreaseOpenTagCounter(tag)){
this.autoCloseUnclosedBeforeTagClosing(tag);
if(this._Listener.isBlockTag(tag)){
var expected_tag = this._Listener._tag_stack.pop();
if(expected_tag == false){
return;
}else if(expected_tag != tag){
tag = expected_tag;
}
this._Listener.closeBlockTag(tag);
}else{
this._Listener.closeUnknownTag(tag);
}
}else{
this._Listener.closeUnopenedTag(tag);
}
this._Listener.last_tag = tag;
this._Listener.last_tag_opened = false;
};
WYMeditor.XhtmlParser.prototype._increaseOpenTagCounter = function(tag)
{
this._Listener._open_tags[tag] = this._Listener._open_tags[tag] || 0;
this._Listener._open_tags[tag]++;
};
WYMeditor.XhtmlParser.prototype._decreaseOpenTagCounter = function(tag)
{
if(this._Listener._open_tags[tag]){
this._Listener._open_tags[tag]--;
if(this._Listener._open_tags[tag] == 0){
this._Listener._open_tags[tag] = undefined;
}
return true;
}
return false;
};
WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeNewOpening = function(new_tag)
{
this._autoCloseUnclosed(new_tag, false);
};
WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeTagClosing = function(tag)
{
this._autoCloseUnclosed(tag, true);
};
WYMeditor.XhtmlParser.prototype._autoCloseUnclosed = function(new_tag, closing)
{
var closing = closing || false;
if(this._Listener._open_tags){
for (var tag in this._Listener._open_tags) {
var counter = this._Listener._open_tags[tag];
if(counter > 0 && this._Listener.shouldCloseTagAutomatically(tag, new_tag, closing)){
this._callCloseTagListener(tag, true);
}
}
}
};
WYMeditor.XhtmlParser.prototype.getTagReplacements = function()
{
return this._Listener.getTagReplacements();
};
WYMeditor.XhtmlParser.prototype.normalizeTag = function(tag)
{
tag = tag.replace(/^([\s<\/>]*)|([\s<\/>]*)$/gm,'').toLowerCase();
var tags = this._Listener.getTagReplacements();
if(tags[tag]){
return tags[tag];
}
return tag;
};
WYMeditor.XhtmlParser.prototype.TagAttributes = function(match, state)
{
if(WYMeditor.LEXER_SPECIAL == state){
this._current_attribute = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.DoubleQuotedAttribute = function(match, state)
{
if(WYMeditor.LEXER_UNMATCHED == state){
this._tag_attributes[this._current_attribute] = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.SingleQuotedAttribute = function(match, state)
{
if(WYMeditor.LEXER_UNMATCHED == state){
this._tag_attributes[this._current_attribute] = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.UnquotedAttribute = function(match, state)
{
this._tag_attributes[this._current_attribute] = match.replace(/^=/,'');
return true;
};
/**
* XHTML Sax parser.
*
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlSaxListener = function()
{
this.output = '';
this.helper = new WYMeditor.XmlHelper();
this._open_tags = {};
this.validator = WYMeditor.XhtmlValidator;
this._tag_stack = [];
this.avoided_tags = [];
this.entities = {
' ':' ','¡':'¡','¢':'¢',
'£':'£','¤':'¤','¥':'¥',
'¦':'¦','§':'§','¨':'¨',
'©':'©','ª':'ª','«':'«',
'¬':'¬','­':'­','®':'®',
'¯':'¯','°':'°','±':'±',
'²':'²','³':'³','´':'´',
'µ':'µ','¶':'¶','·':'·',
'¸':'¸','¹':'¹','º':'º',
'»':'»','¼':'¼','½':'½',
'¾':'¾','¿':'¿','À':'À',
'Á':'Á','Â':'Â','Ã':'Ã',
'Ä':'Ä','Å':'Å','Æ':'Æ',
'Ç':'Ç','È':'È','É':'É',
'Ê':'Ê','Ë':'Ë','Ì':'Ì',
'Í':'Í','Î':'Î','Ï':'Ï',
'Ð':'Ð','Ñ':'Ñ','Ò':'Ò',
'Ó':'Ó','Ô':'Ô','Õ':'Õ',
'Ö':'Ö','×':'×','Ø':'Ø',
'Ù':'Ù','Ú':'Ú','Û':'Û',
'Ü':'Ü','Ý':'Ý','Þ':'Þ',
'ß':'ß','à':'à','á':'á',
'â':'â','ã':'ã','ä':'ä',
'å':'å','æ':'æ','ç':'ç',
'è':'è','é':'é','ê':'ê',
'ë':'ë','ì':'ì','í':'í',
'î':'î','ï':'ï','ð':'ð',
'ñ':'ñ','ò':'ò','ó':'ó',
'ô':'ô','õ':'õ','ö':'ö',
'÷':'÷','ø':'ø','ù':'ù',
'ú':'ú','û':'û','ü':'ü',
'ý':'ý','þ':'þ','ÿ':'ÿ',
'Œ':'Œ','œ':'œ','Š':'Š',
'š':'š','Ÿ':'Ÿ','ƒ':'ƒ',
'ˆ':'ˆ','˜':'˜','Α':'Α',
'Β':'Β','Γ':'Γ','Δ':'Δ',
'Ε':'Ε','Ζ':'Ζ','Η':'Η',
'Θ':'Θ','Ι':'Ι','Κ':'Κ',
'Λ':'Λ','Μ':'Μ','Ν':'Ν',
'Ξ':'Ξ','Ο':'Ο','Π':'Π',
'Ρ':'Ρ','Σ':'Σ','Τ':'Τ',
'Υ':'Υ','Φ':'Φ','Χ':'Χ',
'Ψ':'Ψ','Ω':'Ω','α':'α',
'β':'β','γ':'γ','δ':'δ',
'ε':'ε','ζ':'ζ','η':'η',
'θ':'θ','ι':'ι','κ':'κ',
'λ':'λ','μ':'μ','ν':'ν',
'ξ':'ξ','ο':'ο','π':'π',
'ρ':'ρ','ς':'ς','σ':'σ',
'τ':'τ','υ':'υ','φ':'φ',
'χ':'χ','ψ':'ψ','ω':'ω',
'ϑ':'ϑ','ϒ':'ϒ','ϖ':'ϖ',
' ':' ',' ':' ',' ':' ',
'‌':'‌','‍':'‍','‎':'‎',
'‏':'‏','–':'–','—':'—',
'‘':'‘','’':'’','‚':'‚',
'“':'“','”':'”','„':'„',
'†':'†','‡':'‡','•':'•',
'…':'…','‰':'‰','′':'′',
'″':'″','‹':'‹','›':'›',
'‾':'‾','⁄':'⁄','€':'€',
'ℑ':'ℑ','℘':'℘','ℜ':'ℜ',
'™':'™','ℵ':'ℵ','←':'←',
'↑':'↑','→':'→','↓':'↓',
'↔':'↔','↵':'↵','⇐':'⇐',
'⇑':'⇑','⇒':'⇒','⇓':'⇓',
'⇔':'⇔','∀':'∀','∂':'∂',
'∃':'∃','∅':'∅','∇':'∇',
'∈':'∈','∉':'∉','∋':'∋',
'∏':'∏','∑':'∑','−':'−',
'∗':'∗','√':'√','∝':'∝',
'∞':'∞','∠':'∠','∧':'∧',
'∨':'∨','∩':'∩','∪':'∪',
'∫':'∫','∴':'∴','∼':'∼',
'≅':'≅','≈':'≈','≠':'≠',
'≡':'≡','≤':'≤','≥':'≥',
'⊂':'⊂','⊃':'⊃','⊄':'⊄',
'⊆':'⊆','⊇':'⊇','⊕':'⊕',
'⊗':'⊗','⊥':'⊥','⋅':'⋅',
'⌈':'⌈','⌉':'⌉','⌊':'⌊',
'⌋':'⌋','⟨':'〈','⟩':'〉',
'◊':'◊','♠':'♠','♣':'♣',
'♥':'♥','♦':'♦'};
this.block_tags = ["a", "abbr", "acronym", "address", "area", "b",
"base", "bdo", "big", "blockquote", "body", "button",
"caption", "cite", "code", "col", "colgroup", "dd", "del", "div",
"dfn", "dl", "dt", "em", "fieldset", "form", "head", "h1", "h2",
"h3", "h4", "h5", "h6", "html", "i", "iframe", "ins",
"kbd", "label", "legend", "li", "map", "noscript",
"object", "ol", "optgroup", "option", "p", "pre", "q",
"samp", "script", "select", "small", "span", "strong", "style",
"sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th",
"thead", "title", "tr", "tt", "ul", "var", "extends"];
this.inline_tags = ["br", "embed", "hr", "img", "input", "param"];
return this;
};
WYMeditor.XhtmlSaxListener.prototype.shouldCloseTagAutomatically = function(tag, now_on_tag, closing)
{
var closing = closing || false;
if(tag == 'td'){
if((closing && now_on_tag == 'tr') || (!closing && now_on_tag == 'td')){
return true;
}
}
if(tag == 'option'){
if((closing && now_on_tag == 'select') || (!closing && now_on_tag == 'option')){
return true;
}
}
return false;
};
WYMeditor.XhtmlSaxListener.prototype.beforeParsing = function(raw)
{
this.output = '';
return raw;
};
WYMeditor.XhtmlSaxListener.prototype.afterParsing = function(xhtml)
{
xhtml = this.replaceNamedEntities(xhtml);
xhtml = this.joinRepeatedEntities(xhtml);
xhtml = this.removeEmptyTags(xhtml);
return xhtml;
};
WYMeditor.XhtmlSaxListener.prototype.replaceNamedEntities = function(xhtml)
{
for (var entity in this.entities) {
xhtml = xhtml.replace(entity, this.entities[entity]);
}
return xhtml;
};
WYMeditor.XhtmlSaxListener.prototype.joinRepeatedEntities = function(xhtml)
{
var tags = 'em|strong|sub|sup|acronym|pre|del|address';
return xhtml.replace(new RegExp('<\/('+tags+')><\\1>' ,''),'').
replace(new RegExp('(\s*<('+tags+')>\s*){2}(.*)(\s*<\/\\2>\s*){2}' ,''),'<\$2>\$3<\$2>');
};
WYMeditor.XhtmlSaxListener.prototype.removeEmptyTags = function(xhtml)
{
return xhtml.replace(new RegExp('<('+this.block_tags.join("|").replace(/\|td/,'')+')>(<br \/>| | |\\s)*<\/\\1>' ,'g'),'');
};
WYMeditor.XhtmlSaxListener.prototype.getResult = function()
{
return this.output;
};
WYMeditor.XhtmlSaxListener.prototype.getTagReplacements = function()
{
return {'b':'strong', 'i':'em'};
};
WYMeditor.XhtmlSaxListener.prototype.addContent = function(text)
{
this.output += text;
};
WYMeditor.XhtmlSaxListener.prototype.addComment = function(text)
{
if(this.remove_comments){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.addScript = function(text)
{
if(!this.remove_scripts){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.addCss = function(text)
{
if(!this.remove_embeded_styles){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.openBlockTag = function(tag, attributes)
{
this.output += this.helper.tag(tag, this.validator.getValidTagAttributes(tag, attributes), true);
};
WYMeditor.XhtmlSaxListener.prototype.inlineTag = function(tag, attributes)
{
this.output += this.helper.tag(tag, this.validator.getValidTagAttributes(tag, attributes));
};
WYMeditor.XhtmlSaxListener.prototype.openUnknownTag = function(tag, attributes)
{
//this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.XhtmlSaxListener.prototype.closeBlockTag = function(tag)
{
this.output = this.output.replace(/<br \/>$/, '')+this._getClosingTagContent('before', tag)+"</"+tag+">"+this._getClosingTagContent('after', tag);
};
WYMeditor.XhtmlSaxListener.prototype.closeUnknownTag = function(tag)
{
//this.output += "</"+tag+">";
};
WYMeditor.XhtmlSaxListener.prototype.closeUnopenedTag = function(tag)
{
this.output += "</"+tag+">";
};
WYMeditor.XhtmlSaxListener.prototype.avoidStylingTagsAndAttributes = function()
{
this.avoided_tags = ['div','span'];
this.validator.skiped_attributes = ['style'];
this.validator.skiped_attribute_values = ['MsoNormal','main1']; // MS Word attributes for class
this._avoiding_tags_implicitly = true;
};
WYMeditor.XhtmlSaxListener.prototype.allowStylingTagsAndAttributes = function()
{
this.avoided_tags = [];
this.validator.skiped_attributes = [];
this.validator.skiped_attribute_values = [];
this._avoiding_tags_implicitly = false;
};
WYMeditor.XhtmlSaxListener.prototype.isBlockTag = function(tag)
{
return !WYMeditor.Helper.contains(this.avoided_tags, tag) && WYMeditor.Helper.contains(this.block_tags, tag);
};
WYMeditor.XhtmlSaxListener.prototype.isInlineTag = function(tag)
{
return !WYMeditor.Helper.contains(this.avoided_tags, tag) && WYMeditor.Helper.contains(this.inline_tags, tag);
};
WYMeditor.XhtmlSaxListener.prototype.insertContentAfterClosingTag = function(tag, content)
{
this._insertContentWhenClosingTag('after', tag, content);
};
WYMeditor.XhtmlSaxListener.prototype.insertContentBeforeClosingTag = function(tag, content)
{
this._insertContentWhenClosingTag('before', tag, content);
};
WYMeditor.XhtmlSaxListener.prototype.fixNestingBeforeOpeningBlockTag = function(tag, attributes)
{
if(tag != 'li' && (tag == 'ul' || tag == 'ol') && this.last_tag && !this.last_tag_opened && this.last_tag == 'li'){
this.output = this.output.replace(/<\/li>$/, '');
this.insertContentAfterClosingTag(tag, '</li>');
}
};
WYMeditor.XhtmlSaxListener.prototype._insertContentWhenClosingTag = function(position, tag, content)
{
if(!this['_insert_'+position+'_closing']){
this['_insert_'+position+'_closing'] = [];
}
if(!this['_insert_'+position+'_closing'][tag]){
this['_insert_'+position+'_closing'][tag] = [];
}
this['_insert_'+position+'_closing'][tag].push(content);
};
WYMeditor.XhtmlSaxListener.prototype._getClosingTagContent = function(position, tag)
{
if( this['_insert_'+position+'_closing'] &&
this['_insert_'+position+'_closing'][tag] &&
this['_insert_'+position+'_closing'][tag].length > 0){
return this['_insert_'+position+'_closing'][tag].pop();
}
return '';
};
/********** CSS PARSER **********/
WYMeditor.WymCssLexer = function(parser, only_wym_blocks)
{
var only_wym_blocks = (typeof only_wym_blocks == 'undefined' ? true : only_wym_blocks);
jQuery.extend(this, new WYMeditor.Lexer(parser, (only_wym_blocks?'Ignore':'WymCss')));
this.mapHandler('WymCss', 'Ignore');
if(only_wym_blocks == true){
this.addEntryPattern("/\\\x2a[<\\s]*WYMeditor[>\\s]*\\\x2a/", 'Ignore', 'WymCss');
this.addExitPattern("/\\\x2a[<\/\\s]*WYMeditor[>\\s]*\\\x2a/", 'WymCss');
}
this.addSpecialPattern("\\\x2e[a-z-_0-9]+[\\sa-z1-6]*", 'WymCss', 'WymCssStyleDeclaration');
this.addEntryPattern("/\\\x2a", 'WymCss', 'WymCssComment');
this.addExitPattern("\\\x2a/", 'WymCssComment');
this.addEntryPattern("\x7b", 'WymCss', 'WymCssStyle');
this.addExitPattern("\x7d", 'WymCssStyle');
this.addEntryPattern("/\\\x2a", 'WymCssStyle', 'WymCssFeddbackStyle');
this.addExitPattern("\\\x2a/", 'WymCssFeddbackStyle');
return this;
};
WYMeditor.WymCssParser = function()
{
this._in_style = false;
this._has_title = false;
this.only_wym_blocks = true;
this.css_settings = {'classesItems':[], 'editorStyles':[], 'dialogStyles':[]};
return this;
};
WYMeditor.WymCssParser.prototype.parse = function(raw, only_wym_blocks)
{
var only_wym_blocks = (typeof only_wym_blocks == 'undefined' ? this.only_wym_blocks : only_wym_blocks);
this._Lexer = new WYMeditor.WymCssLexer(this, only_wym_blocks);
this._Lexer.parse(raw);
};
WYMeditor.WymCssParser.prototype.Ignore = function(match, state)
{
return true;
};
WYMeditor.WymCssParser.prototype.WymCssComment = function(text, status)
{
if(text.match(/end[a-z0-9\s]*wym[a-z0-9\s]*/mi)){
return false;
}
if(status == WYMeditor.LEXER_UNMATCHED){
if(!this._in_style){
this._has_title = true;
this._current_item = {'title':WYMeditor.Helper.trim(text)};
}else{
if(this._current_item[this._current_element]){
if(!this._current_item[this._current_element].expressions){
this._current_item[this._current_element].expressions = [text];
}else{
this._current_item[this._current_element].expressions.push(text);
}
}
}
this._in_style = true;
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssStyle = function(match, status)
{
if(status == WYMeditor.LEXER_UNMATCHED){
match = WYMeditor.Helper.trim(match);
if(match != ''){
this._current_item[this._current_element].style = match;
}
}else if (status == WYMeditor.LEXER_EXIT){
this._in_style = false;
this._has_title = false;
this.addStyleSetting(this._current_item);
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssFeddbackStyle = function(match, status)
{
if(status == WYMeditor.LEXER_UNMATCHED){
this._current_item[this._current_element].feedback_style = match.replace(/^([\s\/\*]*)|([\s\/\*]*)$/gm,'');
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssStyleDeclaration = function(match)
{
match = match.replace(/^([\s\.]*)|([\s\.*]*)$/gm, '');
var tag = '';
if(match.indexOf(' ') > 0){
var parts = match.split(' ');
this._current_element = parts[0];
var tag = parts[1];
}else{
this._current_element = match;
}
if(!this._has_title){
this._current_item = {'title':(!tag?'':tag.toUpperCase()+': ')+this._current_element};
this._has_title = true;
}
if(!this._current_item[this._current_element]){
this._current_item[this._current_element] = {'name':this._current_element};
}
if(tag){
if(!this._current_item[this._current_element].tags){
this._current_item[this._current_element].tags = [tag];
}else{
this._current_item[this._current_element].tags.push(tag);
}
}
return true;
};
WYMeditor.WymCssParser.prototype.addStyleSetting = function(style_details)
{
for (var name in style_details){
var details = style_details[name];
if(typeof details == 'object' && name != 'title'){
this.css_settings.classesItems.push({
'name': WYMeditor.Helper.trim(details.name),
'title': style_details.title,
'expr' : WYMeditor.Helper.trim((details.expressions||details.tags).join(', '))
});
if(details.feedback_style){
this.css_settings.editorStyles.push({
'name': '.'+ WYMeditor.Helper.trim(details.name),
'css': details.feedback_style
});
}
if(details.style){
this.css_settings.dialogStyles.push({
'name': '.'+ WYMeditor.Helper.trim(details.name),
'css': details.style
});
}
}
}
};
/********** HELPERS **********/
// Returns true if it is a text node with whitespaces only
jQuery.fn.isPhantomNode = function() {
if (this[0].nodeType == 3)
return !(/[^\t\n\r ]/.test(this[0].data));
return false;
};
WYMeditor.isPhantomNode = function(n) {
if (n.nodeType == 3)
return !(/[^\t\n\r ]/.test(n.data));
return false;
};
WYMeditor.isPhantomString = function(str) {
return !(/[^\t\n\r ]/.test(str));
};
// Returns the Parents or the node itself
// jqexpr = a jQuery expression
jQuery.fn.parentsOrSelf = function(jqexpr) {
var n = this;
if (n[0].nodeType == 3)
n = n.parents().slice(0,1);
// if (n.is(jqexpr)) // XXX should work, but doesn't (probably a jQuery bug)
if (n.filter(jqexpr).size() == 1)
return n;
else
return n.parents(jqexpr).slice(0,1);
};
// String & array helpers
WYMeditor.Helper = {
//replace all instances of 'old' by 'rep' in 'str' string
replaceAll: function(str, old, rep) {
var rExp = new RegExp(old, "g");
return(str.replace(rExp, rep));
},
//insert 'inserted' at position 'pos' in 'str' string
insertAt: function(str, inserted, pos) {
return(str.substr(0,pos) + inserted + str.substring(pos));
},
//trim 'str' string
trim: function(str) {
return str.replace(/^(\s*)|(\s*)$/gm,'');
},
//return true if 'arr' array contains 'elem', or false
contains: function(arr, elem) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === elem) return true;
}
return false;
},
//return 'item' position in 'arr' array, or -1
indexOf: function(arr, item) {
var ret=-1;
for(var i = 0; i < arr.length; i++) {
if (arr[i] == item) {
ret = i;
break;
}
}
return(ret);
},
//return 'item' object in 'arr' array, checking its 'name' property, or null
findByName: function(arr, name) {
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(item.name == name) return(item);
}
return(null);
}
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.explorer.js
* MSIE specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
* Jonatan Lundin (jonatan.lundin _at_ gmail.com)
*/
WYMeditor.WymClassExplorer = function(wym) {
this._wym = wym;
this._class = "className";
this._newLine = "\r\n";
};
WYMeditor.WymClassExplorer.prototype.initIframe = function(iframe) {
//This function is executed twice, though it is called once!
//But MSIE needs that, otherwise designMode won't work.
//Weird.
this._iframe = iframe;
this._doc = iframe.contentWindow.document;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init html value
jQuery(this._doc.body).html(this._wym._html);
//handle events
var wym = this;
this._doc.body.onfocus = function()
{wym._doc.designMode = "on"; wym._doc = iframe.contentWindow.document;};
this._doc.onbeforedeactivate = function() {wym.saveCaret();};
this._doc.onkeyup = function() {
wym.saveCaret();
wym.keyup();
};
this._doc.onclick = function() {wym.saveCaret();};
this._doc.body.onbeforepaste = function() {
wym._iframe.contentWindow.event.returnValue = false;
};
this._doc.body.onpaste = function() {
wym._iframe.contentWindow.event.returnValue = false;
wym.paste(window.clipboardData.getData("Text"));
};
//callback can't be executed twice, so we check
if(this._initialized) {
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
}
this._initialized = true;
//init designMode
this._doc.designMode="on";
try{
// (bermi's note) noticed when running unit tests on IE6
// Is this really needed, it trigger an unexisting property on IE6
this._doc = iframe.contentWindow.document;
}catch(e){}
};
WYMeditor.WymClassExplorer.prototype._exec = function(cmd,param) {
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var container = this.findUp(this.container(), WYMeditor.LI);
if(container)
this._doc.execCommand(cmd);
break;
default:
if(param) this._doc.execCommand(cmd,false,param);
else this._doc.execCommand(cmd);
break;
}
this.listen();
};
WYMeditor.WymClassExplorer.prototype.selected = function() {
var caretPos = this._iframe.contentWindow.document.caretPos;
if(caretPos!=null) {
if(caretPos.parentElement!=undefined)
return(caretPos.parentElement());
}
};
WYMeditor.WymClassExplorer.prototype.saveCaret = function() {
this._doc.caretPos = this._doc.selection.createRange();
};
WYMeditor.WymClassExplorer.prototype.addCssRule = function(styles, oCss) {
styles.addRule(oCss.name, oCss.css);
};
WYMeditor.WymClassExplorer.prototype.insert = function(html) {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Overwrite selection with provided html
range.pasteHTML(html);
} catch (e) { }
} else {
// Fall back to the internal paste function if there's no selection
this.paste(html);
}
};
WYMeditor.WymClassExplorer.prototype.wrap = function(left, right) {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Overwrite selection with provided html
range.pasteHTML(left + range.text + right);
} catch (e) { }
}
};
WYMeditor.WymClassExplorer.prototype.unwrap = function() {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Unwrap selection
var text = range.text;
this._exec( 'Cut' );
range.pasteHTML( text );
} catch (e) { }
}
};
//keyup handler
WYMeditor.WymClassExplorer.prototype.keyup = function() {
this._selected_image = null;
};
WYMeditor.WymClassExplorer.prototype.setFocusToNode = function(node) {
try{
var range = this._doc.selection.createRange();
range.moveToElementText(node);
range.collapse(false);
range.move('character',-1);
range.select();
node.focus();
}
catch($e){this._iframe.contentWindow.focus()}
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.mozilla.js
* Gecko specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Volker Mische (vmx a-t gmx dotde)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
*/
WYMeditor.WymClassMozilla = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\n";
};
WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentDocument;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init html value
this.html(this._wym._html);
//init designMode
this.enableDesignMode();
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor keyup events
jQuery(this._doc).bind("keyup", this.keyup);
//bind editor paste events
jQuery(this._doc).bind("paste", this.paste);
//bind editor focus events (used to reset designmode - Gecko bug)
jQuery(this._doc).bind("focus", this.enableDesignMode);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
/* @name html
* @description Get/Set the html value
*/
WYMeditor.WymClassMozilla.prototype.html = function(html) {
if(typeof html === 'string') {
//disable designMode
try { this._doc.designMode = "off"; } catch(e) { };
//replace em by i and strong by bold
//(designMode issue)
html = html.replace(/<em(\b[^>]*)>/gi, "<i$1>")
.replace(/<\/em>/gi, "</i>")
.replace(/<strong(\b[^>]*)>/gi, "<b$1>")
.replace(/<\/strong>/gi, "</b>");
//update the html body
jQuery(this._doc.body).html(html);
//re-init designMode
this.enableDesignMode();
}
else return(jQuery(this._doc.body).html());
};
WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {
if(!this.selected()) return(false);
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var focusNode = this.selected();
var sel = this._iframe.contentWindow.getSelection();
var anchorNode = sel.anchorNode;
if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
if(focusNode && focusNode == anchorNode && focusNode.tagName.toLowerCase() == WYMeditor.LI) {
var ancestor = focusNode.parentNode.parentNode;
if(focusNode.parentNode.childNodes.length>1
|| ancestor.tagName.toLowerCase() == WYMeditor.OL
|| ancestor.tagName.toLowerCase() == WYMeditor.UL)
this._doc.execCommand(cmd,'',null);
}
break;
default:
if(param) this._doc.execCommand(cmd,'',param);
else this._doc.execCommand(cmd,'',null);
}
//set to P if parent = BODY
var container = this.selected();
if(container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
//add event handlers on doc elements
this.listen();
};
/* @name selected
* @description Returns the selected container
*/
WYMeditor.WymClassMozilla.prototype.selected = function(upgrade_text_nodes) {
if (upgrade_text_nodes == null || upgrade_text_nodes.toString() != "true") { upgrade_text_nodes = false; }
var sel = this._iframe.contentWindow.getSelection();
var node = sel.focusNode;
if(node) {
if(node.nodeName == "#text"){
if (upgrade_text_nodes && sel.toString().length > 0) {
actual_node = null;
parent_node = sel.focusNode.parentNode;
if (parent_node != null) {
for (i=0;i<parent_node.childNodes.length;i++){
child_node = parent_node.childNodes[i];
if (child_node.nodeName != "#text" && child_node.innerHTML == sel.toString()){
actual_node = child_node;
}
}
}
if (actual_node == null) {
return this.switchTo(sel, 'span');
} else {
return actual_node;
}
}
else {
return node.parentNode;
}
}
else return(node);
}
else return(null);
};
WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}", styles.cssRules.length);
};
//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
if(evt.ctrlKey){
if(evt.keyCode == 66){
//CTRL+b => STRONG
wym._exec(WYMeditor.BOLD);
return false;
}
if(evt.keyCode == 73){
//CTRL+i => EMPHASIS
wym._exec(WYMeditor.ITALIC);
return false;
}
}
};
//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
var container = null;
if(evt.keyCode == 13 && !evt.shiftKey) {
//RETURN key
//cleanup <br><br> between paragraphs
jQuery(wym._doc.body).children(WYMeditor.BR).remove();
//fix PRE bug #73
container = wym.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
}
else if(evt.keyCode != 8
&& evt.keyCode != 17
&& evt.keyCode != 46
&& evt.keyCode != 224
&& !evt.metaKey
&& !evt.ctrlKey) {
//NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
//text nodes replaced by P
wym.format_block();
}
};
WYMeditor.WymClassMozilla.prototype.paste = function(evt) {
var wym = WYMeditor.INSTANCES[this.title];
wym.format_block();
};
WYMeditor.WymClassMozilla.prototype.format_block = function(selected) {
//'this' should be the wymeditor instance.
var wym = this;
selected = selected || wym.selected();
wym._selected_image = null;
var container = null;
container = wym.selected();
var name = container.tagName.toLowerCase();
//fix forbidden main containers
if(
name == "strong" ||
name == "b" ||
name == "em" ||
name == "i" ||
name == "sub" ||
name == "sup" ||
name == "a"
) name = container.parentNode.tagName.toLowerCase();
if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
}
WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
if(this.designMode == "off") {
try {
this.designMode = "on";
this.execCommand("styleWithCSS", '', false);
} catch(e) { }
}
};
WYMeditor.WymClassMozilla.prototype.setFocusToNode = function(node) {
var range = document.createRange();
range.selectNode(node);
var selected = this._iframe.contentWindow.getSelection();
selected.addRange(range);
selected.collapse(node, node.childNodes.length);
this._iframe.contentWindow.focus();
};
WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
var attributes = this.validator.getValidTagAttributes(tag, attributes);
// Handle Mozilla styled spans
if(tag == 'span' && attributes.style){
var new_tag = this.getTagForStyle(attributes.style);
if(new_tag){
this._tag_stack.pop();
var tag = new_tag;
this._tag_stack.push(new_tag);
attributes.style = '';
}else{
return;
}
}
this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {
if(/bold/.test(style)) return 'strong';
if(/italic/.test(style)) return 'em';
if(/sub/.test(style)) return 'sub';
if(/sub/.test(style)) return 'super';
return false;
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.opera.js
* Opera specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
*/
WYMeditor.WymClassOpera = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\r\n";
};
WYMeditor.WymClassOpera.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentWindow.document;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init designMode
this._doc.designMode = "on";
//init html value
this.html(this._wym._html);
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor events
jQuery(this._doc).bind("keyup", this.keyup);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
WYMeditor.WymClassOpera.prototype._exec = function(cmd,param) {
if(param) this._doc.execCommand(cmd,false,param);
else this._doc.execCommand(cmd);
this.listen();
};
WYMeditor.WymClassOpera.prototype.selected = function() {
var sel=this._iframe.contentWindow.getSelection();
var node=sel.focusNode;
if(node) {
if(node.nodeName=="#text")return(node.parentNode);
else return(node);
} else return(null);
};
WYMeditor.WymClassOpera.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}",
styles.cssRules.length);
};
//keydown handler
WYMeditor.WymClassOpera.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
var sel = wym._iframe.contentWindow.getSelection();
startNode = sel.getRangeAt(0).startContainer;
//Get a P instead of no container
if(!jQuery(startNode).parentsOrSelf(
WYMeditor.MAIN_CONTAINERS.join(","))[0]
&& !jQuery(startNode).parentsOrSelf('li')
&& evt.keyCode != WYMeditor.KEY.ENTER
&& evt.keyCode != WYMeditor.KEY.LEFT
&& evt.keyCode != WYMeditor.KEY.UP
&& evt.keyCode != WYMeditor.KEY.RIGHT
&& evt.keyCode != WYMeditor.KEY.DOWN
&& evt.keyCode != WYMeditor.KEY.BACKSPACE
&& evt.keyCode != WYMeditor.KEY.DELETE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
};
//keyup handler
WYMeditor.WymClassOpera.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
};
// TODO: implement me
WYMeditor.WymClassOpera.prototype.setFocusToNode = function(node) {
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.safari.js
* Safari specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Scott Lewis (lewiscot a-t gmail dotcom)
*/
WYMeditor.WymClassSafari = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\n";
};
WYMeditor.WymClassSafari.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentDocument;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init designMode
this._doc.designMode = "on";
//init html value
this.html(this._wym._html);
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor keyup events
jQuery(this._doc).bind("keyup", this.keyup);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
WYMeditor.WymClassSafari.prototype._exec = function(cmd,param) {
if(!this.selected()) return(false);
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var focusNode = this.selected();
var sel = this._iframe.contentWindow.getSelection();
var anchorNode = sel.anchorNode;
if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
if(focusNode && focusNode == anchorNode
&& focusNode.tagName.toLowerCase() == WYMeditor.LI) {
var ancestor = focusNode.parentNode.parentNode;
if(focusNode.parentNode.childNodes.length>1
|| ancestor.tagName.toLowerCase() == WYMeditor.OL
|| ancestor.tagName.toLowerCase() == WYMeditor.UL)
this._doc.execCommand(cmd,'',null);
}
break;
case WYMeditor.INSERT_ORDEREDLIST: case WYMeditor.INSERT_UNORDEREDLIST:
this._doc.execCommand(cmd,'',null);
//Safari creates lists in e.g. paragraphs.
//Find the container, and remove it.
var focusNode = this.selected();
var container = this.findUp(focusNode, WYMeditor.MAIN_CONTAINERS);
if(container) jQuery(container).replaceWith(jQuery(container).html());
break;
default:
if(param) this._doc.execCommand(cmd,'',param);
else this._doc.execCommand(cmd,'',null);
}
//set to P if parent = BODY
var container = this.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
//add event handlers on doc elements
this.listen();
};
/* @name selected
* @description Returns the selected container
*/
WYMeditor.WymClassSafari.prototype.selected = function(upgrade_text_nodes) {
if (upgrade_text_nodes == null || upgrade_text_nodes.toString() != "true") { upgrade_text_nodes = false; }
var sel = this._iframe.contentWindow.getSelection();
var node = sel.focusNode;
if(node) {
if(node.nodeName == "#text"){
if (upgrade_text_nodes && sel.toString().length > 0) {
actual_node = null;
parent_node = sel.focusNode.parentNode;
if (parent_node != null) {
for (i=0;i<parent_node.childNodes.length;i++){
child_node = parent_node.childNodes[i];
if (child_node.textContent == sel.toString()){
actual_node = child_node.parentNode;
}
}
}
if (actual_node == null) {
this._selected_item = this.switchTo(sel, 'span');
return this._selected_item;
} else {
return actual_node;
}
}
else {
return node.parentNode;
}
}
else return(node);
}
else return(null);
};
/* @name toggleClass
* @description Toggles class on selected element, or one of its parents
*/
WYMeditor.WymClassSafari.prototype.toggleClass = function(sClass, jqexpr) {
var container = null;
if (this._selected_image) {
container = jQuery(this._selected_image);
}
else {
container = jQuery(this.selected(true) || this._selected_item);
}
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.toggleClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
};
WYMeditor.WymClassSafari.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}",
styles.cssRules.length);
};
//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassSafari.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
if(evt.ctrlKey){
if(evt.keyCode == 66){
//CTRL+b => STRONG
wym._exec(WYMeditor.BOLD);
return false;
}
if(evt.keyCode == 73){
//CTRL+i => EMPHASIS
wym._exec(WYMeditor.ITALIC);
return false;
}
}
};
//keyup handler, mainly used for cleanups
WYMeditor.WymClassSafari.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
var container = null;
if(evt.keyCode == 13 && !evt.shiftKey) {
//RETURN key
//cleanup <br><br> between paragraphs
jQuery(wym._doc.body).children(WYMeditor.BR).remove();
//fix PRE bug #73
container = wym.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
}
//fix #112
if(evt.keyCode == 13 && evt.shiftKey) {
wym._exec('InsertLineBreak');
}
if(evt.keyCode != 8
&& evt.keyCode != 17
&& evt.keyCode != 46
&& evt.keyCode != 224
&& !evt.metaKey
&& !evt.ctrlKey) {
//NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
//text nodes replaced by P
container = wym.selected();
var name = container.tagName.toLowerCase();
//fix forbidden main containers
if(
name == "strong" ||
name == "b" ||
name == "em" ||
name == "i" ||
name == "sub" ||
name == "sup" ||
name == "a" ||
name == "span" //fix #110
) name = container.parentNode.tagName.toLowerCase();
if(name == WYMeditor.BODY || name == WYMeditor.DIV) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //fix #110 for DIV
}
};
//TODO
WYMeditor.WymClassSafari.prototype.setFocusToNode = function(node) {
/*var range = document.createRange();
range.selectNode(node);
var selected = this._iframe.contentWindow.getSelection();
selected.addRange(range);
selected.collapse(node, node.childNodes.length);
this._iframe.contentWindow.focus();*/
};
WYMeditor.WymClassSafari.prototype.openBlockTag = function(tag, attributes)
{
var attributes = this.validator.getValidTagAttributes(tag, attributes);
// Handle Safari styled spans
if(tag == 'span' && attributes.style) {
var new_tag = this.getTagForStyle(attributes.style);
if(new_tag){
this._tag_stack.pop();
var tag = new_tag;
this._tag_stack.push(new_tag);
attributes.style = '';
//should fix #125 - also removed the xhtml() override
if(typeof attributes['class'] == 'string')
attributes['class'] = attributes['class'].replace(/apple-style-span/gi, '');
} else {
return;
}
}
this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.WymClassSafari.prototype.getTagForStyle = function(style) {
if(/bold/.test(style)) return 'strong';
if(/italic/.test(style)) return 'em';
if(/sub/.test(style)) return 'sub';
if(/super/.test(style)) return 'sup';
return false;
};
function titleize(words) {
parts = [];
words.gsub(/\./, '').gsub(/[-_]/, ' ').split(' ').each(function(part){
parts.push(part[0].toUpperCase() + part.substring(1));
});
return parts.join(" ");
} | public/javascripts/wymeditor/jquery.refinery.wymeditor.js | /*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File: jquery.refinery.wymeditor.js
*
* Main JS file with core classes and functions.
* See the documentation for more info.
*
* About: authors
*
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Volker Mische (vmx a-t gmx dotde)
* Scott Lewis (lewiscot a-t gmail dotcom)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Daniel Reszka (d.reszka a-t wymeditor dotorg)
* Jonatan Lundin (jonatan.lundin _at_ gmail.com)
*/
/*
Namespace: WYMeditor
Global WYMeditor namespace.
*/
if(!WYMeditor) var WYMeditor = {};
//Wrap the Firebug console in WYMeditor.console
(function() {
if ( !window.console || !console.firebug ) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
WYMeditor.console = {};
for (var i = 0; i < names.length; ++i)
WYMeditor.console[names[i]] = function() {}
} else WYMeditor.console = window.console;
})();
jQuery.extend(WYMeditor, {
/*
Constants: Global WYMeditor constants.
VERSION - Defines WYMeditor version.
INSTANCES - An array of loaded WYMeditor.editor instances.
STRINGS - An array of loaded WYMeditor language pairs/values.
SKINS - An array of loaded WYMeditor skins.
NAME - The "name" attribute.
INDEX - A string replaced by the instance index.
WYM_INDEX - A string used to get/set the instance index.
BASE_PATH - A string replaced by WYMeditor's base path.
SKIN_PATH - A string replaced by WYMeditor's skin path.
WYM_PATH - A string replaced by WYMeditor's main JS file path.
SKINS_DEFAULT_PATH - The skins default base path.
SKINS_DEFAULT_CSS - The skins default CSS file.
LANG_DEFAULT_PATH - The language files default path.
IFRAME_BASE_PATH - A string replaced by the designmode iframe's base path.
IFRAME_DEFAULT - The iframe's default base path.
JQUERY_PATH - A string replaced by the computed jQuery path.
DIRECTION - A string replaced by the text direction (rtl or ltr).
LOGO - A string replaced by WYMeditor logo.
TOOLS - A string replaced by the toolbar's HTML.
TOOLS_ITEMS - A string replaced by the toolbar items.
TOOL_NAME - A string replaced by a toolbar item's name.
TOOL_TITLE - A string replaced by a toolbar item's title.
TOOL_CLASS - A string replaced by a toolbar item's class.
CLASSES - A string replaced by the classes panel's HTML.
CLASSES_ITEMS - A string replaced by the classes items.
CLASS_NAME - A string replaced by a class item's name.
CLASS_TITLE - A string replaced by a class item's title.
CONTAINERS - A string replaced by the containers panel's HTML.
CONTAINERS_ITEMS - A string replaced by the containers items.
CONTAINER_NAME - A string replaced by a container item's name.
CONTAINER_TITLE - A string replaced by a container item's title.
CONTAINER_CLASS - A string replaced by a container item's class.
HTML - A string replaced by the HTML view panel's HTML.
IFRAME - A string replaced by the designmode iframe.
STATUS - A string replaced by the status panel's HTML.
DIALOG_TITLE - A string replaced by a dialog's title.
DIALOG_BODY - A string replaced by a dialog's HTML body.
BODY - The BODY element.
STRING - The "string" type.
BODY,DIV,P,
H1,H2,H3,H4,H5,H6,
PRE,BLOCKQUOTE,
A,BR,IMG,
TABLE,TD,TH,
UL,OL,LI - HTML elements string representation.
CLASS,HREF,SRC,
TITLE,ALT - HTML attributes string representation.
DIALOG_LINK - A link dialog type.
DIALOG_IMAGE - An image dialog type.
DIALOG_TABLE - A table dialog type.
DIALOG_PASTE - A 'Paste from Word' dialog type.
BOLD - Command: (un)set selection to <strong>.
ITALIC - Command: (un)set selection to <em>.
CREATE_LINK - Command: open the link dialog or (un)set link.
INSERT_IMAGE - Command: open the image dialog or insert an image.
INSERT_TABLE - Command: open the table dialog.
PASTE - Command: open the paste dialog.
INDENT - Command: nest a list item.
OUTDENT - Command: unnest a list item.
TOGGLE_HTML - Command: display/hide the HTML view.
FORMAT_BLOCK - Command: set a block element to another type.
PREVIEW - Command: open the preview dialog.
UNLINK - Command: unset a link.
INSERT_UNORDEREDLIST- Command: insert an unordered list.
INSERT_ORDEREDLIST - Command: insert an ordered list.
MAIN_CONTAINERS - An array of the main HTML containers used in WYMeditor.
BLOCKS - An array of the HTML block elements.
KEY - Standard key codes.
NODE - Node types.
*/
VERSION : "0.5-b2-refinery",
INSTANCES : [],
STRINGS : [],
SKINS : [],
NAME : "name",
INDEX : "{Wym_Index}",
WYM_INDEX : "wym_index",
BASE_PATH : "{Wym_Base_Path}",
CSS_PATH : "{Wym_Css_Path}",
WYM_PATH : "{Wym_Wym_Path}",
SKINS_DEFAULT_PATH : "/images/wymeditor/skins/",
SKINS_DEFAULT_CSS : "skin.css",
SKINS_DEFAULT_JS : "skin.js",
LANG_DEFAULT_PATH : "lang/",
IFRAME_BASE_PATH : "{Wym_Iframe_Base_Path}",
IFRAME_DEFAULT : "iframe/default/",
JQUERY_PATH : "{Wym_Jquery_Path}",
DIRECTION : "{Wym_Direction}",
LOGO : "{Wym_Logo}",
TOOLS : "{Wym_Tools}",
TOOLS_ITEMS : "{Wym_Tools_Items}",
TOOL_NAME : "{Wym_Tool_Name}",
TOOL_TITLE : "{Wym_Tool_Title}",
TOOL_CLASS : "{Wym_Tool_Class}",
CLASSES : "{Wym_Classes}",
CLASSES_ITEMS : "{Wym_Classes_Items}",
CLASS_NAME : "{Wym_Class_Name}",
CLASS_TITLE : "{Wym_Class_Title}",
CONTAINERS : "{Wym_Containers}",
CONTAINERS_ITEMS : "{Wym_Containers_Items}",
CONTAINER_NAME : "{Wym_Container_Name}",
CONTAINER_TITLE : "{Wym_Containers_Title}",
CONTAINER_CLASS : "{Wym_Container_Class}",
HTML : "{Wym_Html}",
IFRAME : "{Wym_Iframe}",
STATUS : "{Wym_Status}",
DIALOG_TITLE : "{Wym_Dialog_Title}",
DIALOG_BODY : "{Wym_Dialog_Body}",
STRING : "string",
BODY : "body",
DIV : "div",
P : "p",
H1 : "h1",
H2 : "h2",
H3 : "h3",
H4 : "h4",
H5 : "h5",
H6 : "h6",
PRE : "pre",
BLOCKQUOTE : "blockquote",
A : "a",
BR : "br",
IMG : "img",
TABLE : "table",
TD : "td",
TH : "th",
UL : "ul",
OL : "ol",
LI : "li",
CLASS : "class",
HREF : "href",
SRC : "src",
TITLE : "title",
TARGET : "target",
ALT : "alt",
DIALOG_LINK : "Link",
DIALOG_IMAGE : "Image",
DIALOG_TABLE : "Table",
DIALOG_PASTE : "Paste_From_Word",
DIALOG_CLASS : "Css_Class",
BOLD : "Bold",
ITALIC : "Italic",
CREATE_LINK : "CreateLink",
INSERT_IMAGE : "InsertImage",
INSERT_TABLE : "InsertTable",
INSERT_HTML : "InsertHTML",
APPLY_CLASS : "Apply_Style",
PASTE : "Paste",
INDENT : "Indent",
OUTDENT : "Outdent",
TOGGLE_HTML : "ToggleHtml",
FORMAT_BLOCK : "FormatBlock",
PREVIEW : "Preview",
UNLINK : "Unlink",
INSERT_UNORDEREDLIST : "InsertUnorderedList",
INSERT_ORDEREDLIST : "InsertOrderedList",
MAIN_CONTAINERS : new Array("p","h1","h2","h3","h4","h5","h6","pre","blockquote"),
BLOCKS : new Array("address", "blockquote", "div", "dl",
"fieldset", "form", "h1", "h2", "h3", "h4", "h5", "h6", "hr",
"noscript", "ol", "p", "pre", "table", "ul", "dd", "dt",
"li", "tbody", "td", "tfoot", "th", "thead", "tr"),
KEY : {
BACKSPACE: 8,
ENTER: 13,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
CURSOR: new Array(37, 38, 39, 40),
DELETE: 46
},
NODE : {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3
},
/*
Class: WYMeditor.editor
WYMeditor editor main class, instanciated for each editor occurrence.
*/
editor : function(elem, options) {
/*
Constructor: WYMeditor.editor
Initializes main values (index, elements, paths, ...)
and call WYMeditor.editor.init which initializes the editor.
Parameters:
elem - The HTML element to be replaced by the editor.
options - The hash of options.
Returns:
Nothing.
See Also:
<WYMeditor.editor.init>
*/
//store the instance in the INSTANCES array and store the index
this._index = WYMeditor.INSTANCES.push(this) - 1;
//store the element replaced by the editor
this._element = elem;
//store the options
this._options = options;
//store the element's inner value
this._html = jQuery(elem).val();
//store the HTML option, if any
if(this._options.html) this._html = this._options.html;
//get or compute the base path (where the main JS file is located)
this._options.basePath = this._options.basePath || this.computeBasePath();
//get or set the skin path (where the skin files are located)
this._options.skinPath = this._options.skinPath || this._options.basePath + WYMeditor.SKINS_DEFAULT_PATH + this._options.skin + '/';
// set css and js skin paths
this._options.cssSkinPath = (this._options.cssSkinPath || this._options.skinPath) + this._options.skin + "/";
this._options.jsSkinPath = (this._options.jsSkinPath || this._options.skinPath) + this._options.skin + "/";
//get or compute the main JS file location
this._options.wymPath = this._options.wymPath || this.computeWymPath();
//get or set the language files path
this._options.langPath = this._options.langPath || this._options.basePath + WYMeditor.LANG_DEFAULT_PATH;
//get or set the designmode iframe's base path
this._options.iframeBasePath = this._options.iframeBasePath || this._options.basePath + WYMeditor.IFRAME_DEFAULT;
//get or compute the jQuery JS file location
this._options.jQueryPath = this._options.jQueryPath || this.computeJqueryPath();
//initialize the editor instance
this.init();
}
});
/********** JQUERY **********/
/**
* Replace an HTML element by WYMeditor
*
* @example jQuery(".wymeditor").wymeditor(
* {
*
* }
* );
* @desc Example description here
*
* @name WYMeditor
* @description WYMeditor is a web-based WYSIWYM XHTML editor
* @param Hash hash A hash of parameters
* @option Integer iExample Description here
* @option String sExample Description here
*
* @type jQuery
* @cat Plugins/WYMeditor
* @author Jean-Francois Hovinne
*/
jQuery.fn.wymeditor = function(options) {
options = jQuery.extend({
html: "",
basePath: false,
skinPath: false,
jsSkinPath: false,
cssSkinPath: false,
wymPath: false,
iframeBasePath: false,
jQueryPath: false,
styles: false,
stylesheet: false,
skin: "default",
initSkin: true,
loadSkin: true,
lang: "en",
direction: "ltr",
boxHtml: "<div class='wym_box'>"
+ "<div class='wym_area_top'>"
+ WYMeditor.TOOLS
+ "</div>"
+ "<div class='wym_area_left'></div>"
+ "<div class='wym_area_right'>"
+ WYMeditor.CONTAINERS
+ WYMeditor.CLASSES
+ "</div>"
+ "<div class='wym_area_main'>"
+ WYMeditor.HTML
+ WYMeditor.IFRAME
+ WYMeditor.STATUS
+ "</div>"
+ "<div class='wym_area_bottom'>"
+ WYMeditor.LOGO
+ "</div>"
+ "</div>",
logoHtml: "<a class='wym_wymeditor_link' "
+ "href='http://www.wymeditor.org/'>WYMeditor</a>",
iframeHtml:"<div class='wym_iframe wym_section'>"
+ "<iframe "
+ "src='"
+ WYMeditor.IFRAME_BASE_PATH
+ "wymiframe.html' "
+ "onload='this.contentWindow.parent.WYMeditor.INSTANCES["
+ WYMeditor.INDEX + "].initIframe(this)'"
+ "></iframe>"
+ "</div>",
editorStyles: [],
toolsHtml: "<div class='wym_tools wym_section'>"
+ "<h2>{Tools}</h2>"
+ "<ul>"
+ WYMeditor.TOOLS_ITEMS
+ "</ul>"
+ "</div>",
toolsItemHtml: "<li class='"
+ WYMeditor.TOOL_CLASS
+ "'><a href='#' name='"
+ WYMeditor.TOOL_NAME
+ "' title='"
+ WYMeditor.TOOL_TITLE
+ "'>"
+ WYMeditor.TOOL_TITLE
+ "</a></li>",
toolsItems: [
{'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'},
{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
{'name': 'Superscript', 'title': 'Superscript',
'css': 'wym_tools_superscript'},
{'name': 'Subscript', 'title': 'Subscript',
'css': 'wym_tools_subscript'},
{'name': 'InsertOrderedList', 'title': 'Ordered_List',
'css': 'wym_tools_ordered_list'},
{'name': 'InsertUnorderedList', 'title': 'Unordered_List',
'css': 'wym_tools_unordered_list'},
{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'},
{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'},
{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'},
{'name': 'Paste', 'title': 'Paste_From_Word',
'css': 'wym_tools_paste'},
{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},
{'name': 'Preview', 'title': 'Preview', 'css': 'wym_tools_preview'}
],
containersHtml: "<div class='wym_containers wym_section'>"
+ "<h2>{Containers}</h2>"
+ "<ul>"
+ WYMeditor.CONTAINERS_ITEMS
+ "</ul>"
+ "</div>",
containersItemHtml:"<li class='"
+ WYMeditor.CONTAINER_CLASS
+ "'>"
+ "<a href='#' name='"
+ WYMeditor.CONTAINER_NAME
+ "'>"
+ WYMeditor.CONTAINER_TITLE
+ "</a></li>",
containersItems: [
{'name': 'P', 'title': 'Paragraph', 'css': 'wym_containers_p'},
{'name': 'H1', 'title': 'Heading_1', 'css': 'wym_containers_h1'},
{'name': 'H2', 'title': 'Heading_2', 'css': 'wym_containers_h2'},
{'name': 'H3', 'title': 'Heading_3', 'css': 'wym_containers_h3'},
{'name': 'H4', 'title': 'Heading_4', 'css': 'wym_containers_h4'},
{'name': 'H5', 'title': 'Heading_5', 'css': 'wym_containers_h5'},
{'name': 'H6', 'title': 'Heading_6', 'css': 'wym_containers_h6'},
{'name': 'PRE', 'title': 'Preformatted', 'css': 'wym_containers_pre'},
{'name': 'BLOCKQUOTE', 'title': 'Blockquote',
'css': 'wym_containers_blockquote'},
{'name': 'TH', 'title': 'Table_Header', 'css': 'wym_containers_th'}
],
classesHtml: "<div class='wym_classes wym_section'>"
+ "<h2>{Classes}</h2><ul>"
+ WYMeditor.CLASSES_ITEMS
+ "</ul></div>",
classesItemHtml: "<li><a href='#' name='"
+ WYMeditor.CLASS_NAME
+ "'>"
+ WYMeditor.CLASS_TITLE
+ "</a></li>",
classesItems: [],
statusHtml: "<div class='wym_status wym_section'>"
+ "<h2>{Status}</h2>"
+ "</div>",
htmlHtml: "<div class='wym_html wym_section'>"
+ "<h2>{Source_Code}</h2>"
+ "<textarea class='wym_html_val'></textarea>"
+ "</div>",
boxSelector: ".wym_box",
toolsSelector: ".wym_tools",
toolsListSelector: " ul",
containersSelector:".wym_containers",
classesSelector: ".wym_classes",
htmlSelector: ".wym_html",
iframeSelector: ".wym_iframe iframe",
iframeBodySelector:".wym_iframe",
statusSelector: ".wym_status",
toolSelector: ".wym_tools a",
containerSelector: ".wym_containers a",
classSelector: ".wym_classes a",
classUnhiddenSelector: ".wym_classes",
classHiddenSelector: ".wym_classes_hidden",
htmlValSelector: ".wym_html_val",
hrefSelector: ".wym_href",
srcSelector: ".wym_src",
titleSelector: ".wym_title",
targetSelector: ".wym_target",
altSelector: ".wym_alt",
textSelector: ".wym_text",
rowsSelector: ".wym_rows",
colsSelector: ".wym_cols",
captionSelector: ".wym_caption",
summarySelector: ".wym_summary",
submitSelector: ".wym_submit",
cancelSelector: ".wym_cancel",
previewSelector: "",
dialogTypeSelector: ".wym_dialog_type",
dialogLinkSelector: ".wym_dialog_link",
dialogImageSelector: ".wym_dialog_image",
dialogTableSelector: ".wym_dialog_table",
dialogPasteSelector: ".wym_dialog_paste",
dialogPreviewSelector: ".wym_dialog_preview",
updateSelector: ".wymupdate",
updateEvent: "click",
dialogFeatures: "menubar=no,titlebar=no,toolbar=no,resizable=no"
+ ",width=560,height=300,top=0,left=0",
dialogHtml: "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'"
+ " 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
+ "<html dir='"
+ WYMeditor.DIRECTION
+ "'><head>"
+ "<link rel='stylesheet' type='text/css' media='screen'"
+ " href='"
+ WYMeditor.CSS_PATH
+ "' />"
+ "<title>"
+ WYMeditor.DIALOG_TITLE
+ "</title>"
+ "<script type='text/javascript'"
+ " src='"
+ WYMeditor.JQUERY_PATH
+ "'></script>"
+ "<script type='text/javascript'"
+ " src='"
+ WYMeditor.WYM_PATH
+ "'></script>"
+ "</head>"
+ WYMeditor.DIALOG_BODY
+ "</html>",
dialogLinkHtml: "<div class='wym_dialog wym_dialog_link'>"
+ "<form>"
+ "<fieldset>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_LINK
+ "' />"
+ "<legend>{Link}</legend>"
+ "<div class='row'>"
+ "<label>{URL}</label>"
+ "<input type='text' class='wym_href' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Title}</label>"
+ "<input type='text' class='wym_title' value='' size='40' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogImageHtml: "<div class='wym_dialog wym_dialog_image'>"
+ "<form>"
+ "<fieldset>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_IMAGE
+ "' />"
+ "<legend>{Image}</legend>"
+ "<div class='row'>"
+ "<label>{URL}</label>"
+ "<input type='text' class='wym_src' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Alternative_Text}</label>"
+ "<input type='text' class='wym_alt' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Title}</label>"
+ "<input type='text' class='wym_title' value='' size='40' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogTableHtml: "<div class='wym_dialog wym_dialog_table'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_TABLE
+ "' />"
+ "<div class='row'>"
+ "<label>{Caption}</label>"
+ "<input type='text' class='wym_caption' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Summary}</label>"
+ "<input type='text' class='wym_summary' value='' size='40' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Number_Of_Rows}</label>"
+ "<input type='text' class='wym_rows' value='3' size='3' />"
+ "</div>"
+ "<div class='row'>"
+ "<label>{Number_Of_Cols}</label>"
+ "<input type='text' class='wym_cols' value='2' size='3' />"
+ "</div>"
+ "<div class='row row-indent'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</form>"
+ "</div>",
dialogPasteHtml: "<div class='wym_dialog wym_dialog_paste'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
+ WYMeditor.DIALOG_PASTE
+ "' />"
+ "<fieldset>"
+ "<legend>{Paste_From_Word}</legend>"
+ "<div class='row'>"
+ "<textarea class='wym_text' rows='10' cols='50'></textarea>"
+ "</div>"
+ "<div class='row'>"
+ "<input class='wym_submit' type='button'"
+ " value='{Submit}' />"
+ "<input class='wym_cancel' type='button'"
+ "value='{Cancel}' />"
+ "</div>"
+ "</fieldset>"
+ "</form>"
+ "</div>",
dialogPreviewHtml: "<div class='wym_dialog wym_dialog_preview'></div>",
dialogStyles: [],
stringDelimiterLeft: "{",
stringDelimiterRight:"}",
preInit: null,
preBind: null,
postInit: null,
preInitDialog: null,
postInitDialog: null
}, options);
return this.each(function() {
new WYMeditor.editor(jQuery(this),options);
});
};
/* @name extend
* @description Returns the WYMeditor instance based on its index
*/
jQuery.extend({
wymeditors: function(i) {
return (WYMeditor.INSTANCES[i]);
}
});
/********** WYMeditor **********/
/* @name Wymeditor
* @description WYMeditor class
*/
/* @name init
* @description Initializes a WYMeditor instance
*/
WYMeditor.editor.prototype.init = function() {
//load subclass - browser specific
//unsupported browsers: do nothing
if (jQuery.browser.msie) {
var WymClass = new WYMeditor.WymClassExplorer(this);
}
else if (jQuery.browser.mozilla) {
var WymClass = new WYMeditor.WymClassMozilla(this);
}
else if (jQuery.browser.opera) {
var WymClass = new WYMeditor.WymClassOpera(this);
}
else if (jQuery.browser.safari) {
var WymClass = new WYMeditor.WymClassSafari(this);
}
if(WymClass) {
if(jQuery.isFunction(this._options.preInit)) this._options.preInit(this);
var SaxListener = new WYMeditor.XhtmlSaxListener();
jQuery.extend(SaxListener, WymClass);
this.parser = new WYMeditor.XhtmlParser(SaxListener);
if(this._options.styles || this._options.stylesheet){
this.configureEditorUsingRawCss();
}
this.helper = new WYMeditor.XmlHelper();
//extend the Wymeditor object
//don't use jQuery.extend since 1.1.4
//jQuery.extend(this, WymClass);
for (var prop in WymClass) { this[prop] = WymClass[prop]; }
//load wymbox
this._box = jQuery(this._element).hide().after(this._options.boxHtml).next();
//store the instance index in the wymbox element
//but keep it compatible with jQuery < 1.2.3, see #122
if( jQuery.isFunction( jQuery.fn.data ) )
jQuery.data(this._box.get(0), WYMeditor.WYM_INDEX, this._index);
var h = WYMeditor.Helper;
//construct the iframe
var iframeHtml = this._options.iframeHtml;
iframeHtml = h.replaceAll(iframeHtml, WYMeditor.INDEX, this._index);
iframeHtml = h.replaceAll(iframeHtml, WYMeditor.IFRAME_BASE_PATH, this._options.iframeBasePath);
//construct wymbox
var boxHtml = jQuery(this._box).html();
boxHtml = h.replaceAll(boxHtml, WYMeditor.LOGO, this._options.logoHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS, this._options.toolsHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS,this._options.containersHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES, this._options.classesHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.HTML, this._options.htmlHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.IFRAME, iframeHtml);
boxHtml = h.replaceAll(boxHtml, WYMeditor.STATUS, this._options.statusHtml);
//construct tools list
var aTools = eval(this._options.toolsItems);
var sTools = "";
for(var i = 0; i < aTools.length; i++) {
var oTool = aTools[i];
if(oTool.name && oTool.title)
var sTool = this._options.toolsItemHtml;
var sTool = h.replaceAll(sTool, WYMeditor.TOOL_NAME, oTool.name);
sTool = h.replaceAll(sTool, WYMeditor.TOOL_TITLE, this._options.stringDelimiterLeft
+ oTool.title
+ this._options.stringDelimiterRight);
sTool = h.replaceAll(sTool, WYMeditor.TOOL_CLASS, oTool.css);
sTools += sTool;
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS_ITEMS, sTools);
//construct classes list
var aClasses = eval(this._options.classesItems);
var sClasses = "";
for(var i = 0; i < aClasses.length; i++) {
var oClass = aClasses[i];
if(oClass.name) {
if (oClass.rules && oClass.rules.length > 0) {
var sRules = "";
oClass.rules.each(function(rule){
sClass = this._options.classesItemHtml;
sClass = h.replaceAll(sClass, WYMeditor.CLASS_NAME, oClass.name + (oClass.join || "") + rule);
sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, rule.title || titleize(rule));
sRules += sClass;
}.bind(this)); // need to bind 'this' or else it will think 'this' is the window.
var sClassMultiple = this._options.classesItemHtmlMultiple;
sClassMultiple = h.replaceAll(sClassMultiple, WYMeditor.CLASS_TITLE, oClass.title || titleize(oClass.name));
sClassMultiple = h.replaceAll(sClassMultiple, '{classesItemHtml}', sRules);
sClasses += sClassMultiple;
}
else {
sClass = this._options.classesItemHtml;
sClass = h.replaceAll(sClass, WYMeditor.CLASS_NAME, oClass.name);
sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, oClass.title || titleize(oClass.name));
sClasses += sClass;
}
}
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES_ITEMS, sClasses);
//construct containers list
var aContainers = eval(this._options.containersItems);
var sContainers = "";
for(var i = 0; i < aContainers.length; i++) {
var oContainer = aContainers[i];
if(oContainer.name && oContainer.title)
var sContainer = this._options.containersItemHtml;
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_NAME, oContainer.name);
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_TITLE,
this._options.stringDelimiterLeft
+ oContainer.title
+ this._options.stringDelimiterRight);
sContainer = h.replaceAll(sContainer, WYMeditor.CONTAINER_CLASS, oContainer.css);
sContainers += sContainer;
}
boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS_ITEMS, sContainers);
//l10n
boxHtml = this.replaceStrings(boxHtml);
//load html in wymbox
jQuery(this._box).html(boxHtml);
//hide the html value
jQuery(this._box).find(this._options.htmlSelector).hide();
//enable the skin
this.loadSkin();
}
};
WYMeditor.editor.prototype.bindEvents = function() {
//copy the instance
var wym = this;
//handle click event on tools buttons
jQuery(this._box).find(this._options.toolSelector).click(function() {
wym.exec(jQuery(this).attr(WYMeditor.NAME));
return(false);
});
//handle click event on containers buttons
jQuery(this._box).find(this._options.containerSelector).click(function() {
wym.container(jQuery(this).attr(WYMeditor.NAME));
return(false);
});
//handle keyup event on html value: set the editor value
jQuery(this._box).find(this._options.htmlValSelector).keyup(function() {
jQuery(wym._doc.body).html(jQuery(this).val());
});
//handle click event on classes buttons
jQuery(this._box).find(this._options.classSelector).click(function() {
var aClasses = eval(wym._options.classesItems);
var sName = jQuery(this).attr(WYMeditor.NAME);
var oClass = WYMeditor.Helper.findByName(aClasses, sName);
var replacers = [];
if (oClass == null) {
aClasses.each(function(classRule){
if (oClass == null && classRule.rules && classRule.rules.length > 0){
indexOf = classRule.rules.indexOf(sName.gsub(classRule.name + (classRule.join || ""), ""));
if (indexOf > -1) {
for (i=0;i<classRule.rules.length;i++){
if (i != indexOf){
replacers.push(classRule.name + (classRule.join || "") + classRule.rules[i]);
}
}
oClass = {expr: (classRule.rules[indexOf].expr || null)}
}
}
}.bind(this));
}
if(oClass) {
var jqexpr = oClass.expr;
// remove all related classes.
replacers.each(function(removable_class){
wym.removeClass(removable_class, jqexpr);
});
wym.toggleClass(sName, jqexpr);
}
// now hide the menu
wym.exec(WYMeditor.APPLY_CLASS);
return(false);
});
//handle event on update element
jQuery(this._options.updateSelector).bind(this._options.updateEvent, function() {
wym.update();
});
};
WYMeditor.editor.prototype.ready = function() {
return(this._doc != null);
};
/********** METHODS **********/
/* @name box
* @description Returns the WYMeditor container
*/
WYMeditor.editor.prototype.box = function() {
return(this._box);
};
/* @name html
* @description Get/Set the html value
*/
WYMeditor.editor.prototype.html = function(html) {
if(typeof html === 'string') jQuery(this._doc.body).html(html);
else return(jQuery(this._doc.body).html());
};
/* @name xhtml
* @description Cleans up the HTML
*/
WYMeditor.editor.prototype.xhtml = function() {
return this.parser.parse(this.html());
};
/* @name exec
* @description Executes a button command
*/
WYMeditor.editor.prototype.exec = function(cmd) {
//base function for execCommand
//open a dialog or exec
switch(cmd) {
case WYMeditor.CREATE_LINK:
var container = this.container();
if(container || this._selected_image) this.dialog(WYMeditor.DIALOG_LINK);
break;
case WYMeditor.INSERT_IMAGE:
this.dialog(WYMeditor.DIALOG_IMAGE);
break;
case WYMeditor.INSERT_TABLE:
this.dialog(WYMeditor.DIALOG_TABLE);
break;
case WYMeditor.PASTE:
this.dialog(WYMeditor.DIALOG_PASTE);
break;
case WYMeditor.TOGGLE_HTML:
this.update();
this.toggleHtml();
//partially fixes #121 when the user manually inserts an image
if(!jQuery(this._box).find(this._options.htmlSelector).is(':visible'))
this.listen();
break;
case WYMeditor.PREVIEW:
this.dialog(WYMeditor.PREVIEW);
break;
case WYMeditor.APPLY_CLASS:
jQuery(this._box).find(this._options.classUnhiddenSelector).toggleClass(this._options.classHiddenSelector.substring(1)); // substring(1) to remove the . at the start
jQuery(this._box).find("a[name=" + WYMeditor.APPLY_CLASS +"]").toggleClass('selected');
//this.dialog(WYMeditor.DIALOG_CLASS);
break;
default:
this._exec(cmd);
break;
}
};
/* @name container
* @description Get/Set the selected container
*/
WYMeditor.editor.prototype.container = function(sType) {
if(sType) {
var container = null;
if(sType.toLowerCase() == WYMeditor.TH) {
container = this.container();
//find the TD or TH container
switch(container.tagName.toLowerCase()) {
case WYMeditor.TD: case WYMeditor.TH:
break;
default:
var aTypes = new Array(WYMeditor.TD,WYMeditor.TH);
container = this.findUp(this.container(), aTypes);
break;
}
//if it exists, switch
if(container!=null) {
sType = (container.tagName.toLowerCase() == WYMeditor.TD)? WYMeditor.TH: WYMeditor.TD;
this.switchTo(container,sType);
this.update();
}
} else {
//set the container type
var aTypes=new Array(WYMeditor.P,WYMeditor.H1,WYMeditor.H2,WYMeditor.H3,WYMeditor.H4,WYMeditor.H5,
WYMeditor.H6,WYMeditor.PRE,WYMeditor.BLOCKQUOTE);
container = this.findUp(this.container(), aTypes);
if(container) {
var newNode = null;
//blockquotes must contain a block level element
if(sType.toLowerCase() == WYMeditor.BLOCKQUOTE) {
var blockquote = this.findUp(this.container(), WYMeditor.BLOCKQUOTE);
if(blockquote == null) {
newNode = this._doc.createElement(sType);
container.parentNode.insertBefore(newNode,container);
newNode.appendChild(container);
this.setFocusToNode(newNode.firstChild);
} else {
var nodes = blockquote.childNodes;
var lgt = nodes.length;
var firstNode = null;
if(lgt > 0) firstNode = nodes.item(0);
for(var x=0; x<lgt; x++) {
blockquote.parentNode.insertBefore(nodes.item(0),blockquote);
}
blockquote.parentNode.removeChild(blockquote);
if(firstNode) this.setFocusToNode(firstNode);
}
}
else this.switchTo(container,sType);
this.update();
}
}
}
else return(this.selected());
};
/* @name toggleClass
* @description Toggles class on selected element, or one of its parents
*/
WYMeditor.editor.prototype.toggleClass = function(sClass, jqexpr) {
var container = jQuery((this._selected_image ? this._selected_image : this.selected(true)));
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.toggleClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
};
/* @name removeClass
* @description Removes class on selected element, or one of its parents
*/
WYMeditor.editor.prototype.removeClass = function(sClass, jqexpr) {
var container = jQuery((this._selected_image ? this._selected_image : jQuery(this.selected(true))));
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.removeClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
}
/* @name findUp
* @description Returns the first parent or self container, based on its type
*/
WYMeditor.editor.prototype.findUp = function(node, filter) {
//filter is a string or an array of strings
if(node) {
var tagname = node.tagName.toLowerCase();
if(typeof(filter) == WYMeditor.STRING) {
while(tagname != filter && tagname != WYMeditor.BODY) {
node = node.parentNode;
tagname = node.tagName.toLowerCase();
}
} else {
var bFound = false;
while(!bFound && tagname != WYMeditor.BODY) {
for(var i = 0; i < filter.length; i++) {
if(tagname == filter[i]) {
bFound = true;
break;
}
}
if(!bFound) {
node = node.parentNode;
tagname = node.tagName.toLowerCase();
}
}
}
if(tagname != WYMeditor.BODY) return(node);
else return(null);
} else return(null);
};
/* @name switchTo
* @description Switch the node's type
*/
WYMeditor.editor.prototype.switchTo = function(selectionOrNode,sType) {
if (selectionOrNode.getRangeAt) {
// We have a selection object so we need to create a temporary node around it (bold is easy). This node will be replaced anyway.
this.exec(WYMeditor.BOLD);
selectionOrNode = selectionOrNode.focusNode.parentNode;
}
// we have a node.
var html = jQuery(selectionOrNode).html();
var newNode = this._doc.createElement(sType);
selectionOrNode.parentNode.replaceChild(newNode,selectionOrNode);
jQuery(newNode).html(html);
this.setFocusToNode(newNode);
return newNode;
};
WYMeditor.editor.prototype.replaceStrings = function(sVal) {
//check if the language file has already been loaded
//if not, get it via a synchronous ajax call
if(!WYMeditor.STRINGS[this._options.lang]) {
try {
eval(jQuery.ajax({url:this._options.langPath
+ this._options.lang + '.js', async:false}).responseText);
} catch(e) {
if (WYMeditor.console) {
WYMeditor.console.error("WYMeditor: error while parsing language file.");
}
return sVal;
}
}
//replace all the strings in sVal and return it
for (var key in WYMeditor.STRINGS[this._options.lang]) {
sVal = WYMeditor.Helper.replaceAll(sVal, this._options.stringDelimiterLeft + key
+ this._options.stringDelimiterRight,
WYMeditor.STRINGS[this._options.lang][key]);
};
return(sVal);
};
WYMeditor.editor.prototype.encloseString = function(sVal) {
return(this._options.stringDelimiterLeft
+ sVal
+ this._options.stringDelimiterRight);
};
/* @name status
* @description Prints a status message
*/
WYMeditor.editor.prototype.status = function(sMessage) {
//print status message
jQuery(this._box).find(this._options.statusSelector).html(sMessage);
};
/* @name update
* @description Updates the element and textarea values
*/
WYMeditor.editor.prototype.update = function() {
var html = this.xhtml().gsub(/<\/([A-Za-z0-9]*)></, function(m){return "</" + m[1] +">\n<"}).gsub(/src=\"system\/images/, 'src="/system/images'); // make system/images calls absolute.
jQuery(this._element).val(html);
jQuery(this._box).find(this._options.htmlValSelector).val(html);
};
/* @name dialog
* @description Opens a dialog box
*/
WYMeditor.editor.prototype.dialog = function( dialogType ) {
var path = this._wym._options.dialogPath + dialogType + this._wym._options.dialogFeatures;
this._current_unique_stamp = this.uniqueStamp();
// change undo or redo on cancel to true to have this happen when a user closes (cancels) a dialogue
this._undo_on_cancel = false;
this._redo_on_cancel = false;
//set to P if parent = BODY
if (![WYMeditor.DIALOG_TABLE, WYMeditor.DIALOG_PASTE].include(dialogType))
{
var container = this.selected();
if (container != null){
if(container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
}
else {
// somehow select the wymeditor textarea or simulate a click or a keydown on it.
}
}
selected = this.selected();
if (dialogType == WYMeditor.DIALOG_LINK && jQuery.browser.mozilla) {
selection = this._iframe.contentWindow.getSelection();
matches = selected.innerHTML.match(new RegExp(RegExp.escape(selection.anchorNode.textContent) + "(.*)" + RegExp.escape(selection.focusNode.textContent)));
if (matches != null && matches.length > 0 && (possible_anchor_tag = matches.last()) != null) {
if (((href_matches = possible_anchor_tag.match(/href="([^"]*)"/)) != null) && (href = href_matches.last()) != null) {
possible_anchors = this._iframe.document().getElementsByTagName('a');
for (i=0;i<possible_anchors.length;i++) {
if ((possible_match = possible_anchors[i]).innerHTML == selection) {
selected = possible_match;
}
}
}
}
}
// set up handlers.
imageGroup = null;
ajax_loaded_callback = function(){this.dialog_ajax_callback(selected)}.bind(this, selected);
var parent_node = null;
if (this._selected_image) {
parent_node = this._selected_image.parentNode;
}
else {
parent_node = selected;
}
if (parent_node != null && parent_node.tagName.toLowerCase() != WYMeditor.A)
{
// wrap the current selection with a funky span (not required for safari)
if (!this._selected_image && !jQuery.browser.safari)
{
this.wrap("<span id='replace_me_with_" + this._current_unique_stamp + "'>", "</span>");
}
}
else {
if (!this._selected_image) {
parent_node._id_before_replaceable = parent.id;
parent_node.id = 'replace_me_with_' + this._current_unique_stamp;
}
path += (this._wym._options.dialogFeatures.length == 0) ? "?" : "&"
port = (window.location.port.length > 0 ? (":" + window.location.port) : "")
path += "current_link=" + parent_node.href.gsub(window.location.protocol + "//" + window.location.hostname + port, "");
path += "&target_blank=" + (parent_node.target == "_blank" ? "true" : "false")
}
// launch thickbox
dialog_title = this.replaceStrings(this.encloseString( dialogType ));
switch(dialogType) {
case WYMeditor.DIALOG_TABLE: {
dialog_container = document.createElement("div");
dialog_container.id = 'inline_dialog_container';
dialog_container.innerHTML = this.replaceStrings(this._options.dialogTableHtml);
jQuery(document.body).after(dialog_container);
tb_show(dialog_title, "#" + this._options.dialogInlineFeatures + "&inlineId=inline_dialog_container&TB_inline=true&modal=true", imageGroup);
ajax_loaded_callback();
break;
}
case WYMeditor.DIALOG_PASTE: {
dialog_container = document.createElement("div");
dialog_container.id = 'inline_dialog_container';
dialog_container.innerHTML = this.replaceStrings(this._options.dialogPasteHtml);
jQuery(document.body).after(dialog_container);
tb_show(dialog_title, "#" + this._options.dialogInlineFeatures + "&inlineId=inline_dialog_container&TB_inline=true&modal=true", imageGroup);
ajax_loaded_callback();
break;
}
default:
{
tb_show(dialog_title, path, imageGroup, ajax_loaded_callback);
break;
}
}
};
WYMeditor.editor.prototype.dialog_ajax_callback = function(selected) {
// look for iframes
if ((iframes = $(this._options.dialogId).select('iframe')).length > 0 && (iframe = $(iframes[0])) != null)
{
iframe.observe('load', function(selected, e)
{
WYMeditor.INIT_DIALOG(this, selected);
iframe.stopObserving('load');
}.bind(this, selected));
}
else
{
WYMeditor.INIT_DIALOG(this, selected);
}
};
/* @name toggleHtml
* @description Shows/Hides the HTML
*/
WYMeditor.editor.prototype.toggleHtml = function() {
jQuery(this._box).find(this._options.htmlSelector).toggle();
};
WYMeditor.editor.prototype.uniqueStamp = function() {
return("wym-" + new Date().getTime());
};
WYMeditor.editor.prototype.paste = function(sData) {
console.log('pasting..');
var sTmp;
var container = this.selected();
//split the data, using double newlines as the separator
var aP = sData.split(this._newLine + this._newLine);
var rExp = new RegExp(this._newLine, "g");
//add a P for each item
if(container && container.tagName.toLowerCase() != WYMeditor.BODY) {
for(x = aP.length - 1; x >= 0; x--) {
sTmp = aP[x];
//simple newlines are replaced by a break
sTmp = sTmp.replace(rExp, "<br />");
jQuery(container).after("<p>" + sTmp + "</p>");
}
} else {
for(x = 0; x < aP.length; x++) {
sTmp = aP[x];
//simple newlines are replaced by a break
sTmp = sTmp.replace(rExp, "<br />");
jQuery(this._doc.body).append("<p>" + sTmp + "</p>");
}
}
};
WYMeditor.editor.prototype.insert = function(html) {
// Do we have a selection?
if (this._iframe.contentWindow.getSelection().focusNode != null) {
// Overwrite selection with provided html
this._exec( WYMeditor.INSERT_HTML, html);
} else {
// Fall back to the internal paste function if there's no selection
this.paste(html);
}
};
WYMeditor.editor.prototype.wrap = function(left, right, selection) {
// Do we have a selection?
if (selection == null) { selection = this._iframe.contentWindow.getSelection();}
if (selection.focusNode != null) {
// Wrap selection with provided html
this._exec( WYMeditor.INSERT_HTML, left + selection.toString() + right);
}
};
WYMeditor.editor.prototype.unwrap = function(selection) {
// Do we have a selection?
if (selection == null) { selection = this._iframe.contentWindow.getSelection();}
if (selection.focusNode != null) {
// Unwrap selection
this._exec( WYMeditor.INSERT_HTML, selection.toString() );
}
};
WYMeditor.editor.prototype.addCssRules = function(doc, aCss) {
var styles = doc.styleSheets[0];
if(styles) {
for(var i = 0; i < aCss.length; i++) {
var oCss = aCss[i];
if(oCss.name && oCss.css) this.addCssRule(styles, oCss);
}
}
};
/********** CONFIGURATION **********/
WYMeditor.editor.prototype.computeBasePath = function() {
if ((script_path = this.computeWymPath()) != null) {
if ((src_parts = script_path.split('/')).length > 1) { src_parts.pop(); }
return src_parts.join('/') + "/";
}
else {
return null;
}
};
WYMeditor.editor.prototype.computeWymPath = function() {
return jQuery('script[src*=jquery.refinery.wymeditor]').attr('src');
};
WYMeditor.editor.prototype.computeJqueryPath = function() {
return jQuery(jQuery.grep(jQuery('script'), function(s){
return (s.src && s.src.match(/jquery(-(.*)){0,1}(\.pack|\.min|\.packed)?\.js(\?.*)?$/ ))
})).attr('src');
};
WYMeditor.editor.prototype.computeCssPath = function() {
return jQuery(jQuery.grep(jQuery('link'), function(s){
return (s.href && s.href.match(/wymeditor\/skins\/(.*)screen\.css(\?.*)?$/ ))
})).attr('href');
};
WYMeditor.editor.prototype.configureEditorUsingRawCss = function() {
var CssParser = new WYMeditor.WymCssParser();
if(this._options.stylesheet){
CssParser.parse(jQuery.ajax({url: this._options.stylesheet,async:false}).responseText);
}else{
CssParser.parse(this._options.styles, false);
}
if(this._options.classesItems.length == 0) {
this._options.classesItems = CssParser.css_settings.classesItems;
}
if(this._options.editorStyles.length == 0) {
this._options.editorStyles = CssParser.css_settings.editorStyles;
}
if(this._options.dialogStyles.length == 0) {
this._options.dialogStyles = CssParser.css_settings.dialogStyles;
}
};
/********** EVENTS **********/
WYMeditor.editor.prototype.listen = function() {
//don't use jQuery.find() on the iframe body
//because of MSIE + jQuery + expando issue (#JQ1143)
//jQuery(this._doc.body).find("*").bind("mouseup", this.mouseup);
jQuery(this._doc.body).bind("mousedown", this.mousedown);
var images = this._doc.body.getElementsByTagName("img");
for(var i=0; i < images.length; i++) {
jQuery(images[i]).bind("mousedown", this.mousedown);
}
};
WYMeditor.editor.prototype.mousedown = function(evt) {
var wym = WYMeditor.INSTANCES[this.ownerDocument.title];
wym._selected_image = (this.tagName.toLowerCase() == WYMeditor.IMG) ? this : null;
evt.stopPropagation();
};
/********** SKINS **********/
/*
* Function: WYMeditor.loadCss
* Loads a stylesheet in the document.
*
* Parameters:
* href - The CSS path.
*/
WYMeditor.loadCss = function(href) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
var head = jQuery('head').get(0);
head.appendChild(link);
};
/*
* Function: WYMeditor.editor.loadSkin
* Loads the skin CSS and initialization script (if needed).
*/
WYMeditor.editor.prototype.loadSkin = function() {
//does the user want to automatically load the CSS (default: yes)?
//we also test if it hasn't been already loaded by another instance
//see below for a better (second) test
if(this._options.loadSkin && !WYMeditor.SKINS[this._options.skin]) {
//check if it hasn't been already loaded
//so we don't load it more than once
//(we check the existing <link> elements)
var found = false;
var rExp = new RegExp(this._options.skin
+ '\/' + WYMeditor.SKINS_DEFAULT_CSS + '$');
jQuery('link').each( function() {
if(this.href.match(rExp)) found = true;
});
//load it, using the skin path
if(!found) WYMeditor.loadCss( this._options.cssSkinPath
+ WYMeditor.SKINS_DEFAULT_CSS );
}
//put the classname (ex. wym_skin_default) on wym_box
jQuery(this._box).addClass( "wym_skin_" + this._options.skin );
//does the user want to use some JS to initialize the skin (default: yes)?
//also check if it hasn't already been loaded by another instance
if(this._options.initSkin && !WYMeditor.SKINS[this._options.skin]) {
eval(jQuery.ajax({url:this._options.jsSkinPath
+ WYMeditor.SKINS_DEFAULT_JS, async:false}).responseText);
}
//init the skin, if needed
if(WYMeditor.SKINS[this._options.skin] && WYMeditor.SKINS[this._options.skin].init)
WYMeditor.SKINS[this._options.skin].init(this);
};
/********** DIALOGS **********/
WYMeditor.INIT_DIALOG = function(wym, selected, isIframe) {
var selected = selected || wym.selected();
var dialog = $(wym._options.dialogId);
var doc = (isIframe ? dialog.select('iframe')[0].document() : document);
var dialogType = doc.getElementById('wym_dialog_type').value;
var replaceable = wym._selected_image ? jQuery(wym._selected_image) : jQuery(wym._doc.body).find('#replace_me_with_' + wym._current_unique_stamp);
[dialog.select("#TB_window .close_dialog"), $(doc.body).select("#TB_window .close_dialog")].flatten().uniq().each(function(button)
{
button.observe('click', function(e){this.close_dialog(e, true)}.bind(wym));
});
/*
switch(dialogType) {
case WYMeditor.DIALOG_LINK:
//ensure that we select the link to populate the fields
if (replaceable[0] != null && replaceable[0].tagName.toLowerCase() == WYMeditor.A)
{
jQuery(wym._options.hrefSelector).val(jQuery(replaceable).attr(WYMeditor.HREF));
jQuery(wym._options.hrefSelector);
}
//fix MSIE selection if link image has been clicked
if(!selected && wym._selected_image)
selected = jQuery(wym._selected_image).parentsOrSelf(WYMeditor.A);
break;
}
*/
//pre-init functions
if(jQuery.isFunction(wym._options.preInitDialog))
wym._options.preInitDialog(wym,window);
/*
//auto populate fields if selected container (e.g. A)
if(selected) {
jQuery(wym._options.hrefSelector).val(jQuery(selected).attr(WYMeditor.HREF));
jQuery(wym._options.srcSelector).val(jQuery(selected).attr(WYMeditor.SRC));
jQuery(wym._options.titleSelector).val(jQuery(selected).attr(WYMeditor.TITLE));
jQuery(wym._options.altSelector).val(jQuery(selected).attr(WYMeditor.ALT));
}*/
//auto populate image fields if selected image
if(wym._selected_image) {
jQuery(wym._options.dialogImageSelector + " " + wym._options.srcSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.SRC));
jQuery(wym._options.dialogImageSelector + " " + wym._options.titleSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.TITLE));
jQuery(wym._options.dialogImageSelector + " " + wym._options.altSelector)
.val(jQuery(wym._selected_image).attr(WYMeditor.ALT));
}
jQuery(wym._options.dialogLinkSelector + " " + wym._options.submitSelector).click(function()
{
var sUrl = jQuery(wym._options.hrefSelector).val();
if(sUrl.length > 0)
{
if (replaceable[0] != null) {
link = wym._doc.createElement("a");
link.href = sUrl;
link.title = jQuery(wym._options.titleSelector).val();
target = jQuery(wym._options.targetSelector).val();
if (target != null && target.length > 0) {
link.target = target;
}
// now grab what was selected in the editor and chuck it inside the link.
if (!wym._selected_image)
{
replaceable.after(link);
link.innerHTML = replaceable.html();
replaceable.remove();
}
else
{
if ((parent = replaceable[0].parentNode) != null && parent.tagName.toUpperCase() == "A") {
parent.href = link.href;
parent.title = jQuery(wym._options.titleSelector).val();
parent.target = target;
}
else {
replaceable.before(link);
jQuery(link).append(replaceable[0]);
}
}
}
else {
wym._exec(WYMeditor.CREATE_LINK, wym._current_unique_stamp);
jQuery("a[href=" + wym._current_unique_stamp + "]", wym._doc.body)
.attr(WYMeditor.HREF, sUrl)
.attr(WYMeditor.TITLE, jQuery(wym._options.titleSelector).val())
.attr(WYMeditor.TARGET, jQuery(wym._options.targetSelector).val());
}
}
// fire a click event on the dialogs close button
wym.close_dialog()
});
jQuery(wym._options.dialogImageSelector + " " + wym._options.submitSelector).click(function() {
form = jQuery(this.form);
var sUrl = form.find(wym._options.srcSelector).val();
var sTitle = form.find(wym._options.titleSelector).val();
var sAlt = form.find(wym._options.altSelector).val();
if (sUrl != null && sUrl.length > 0) {
wym._exec(WYMeditor.INSERT_IMAGE, wym._current_unique_stamp, selected);
//don't use jQuery.find() see #JQ1143
//var image = jQuery(wym._doc.body).find("img[@src=" + sStamp + "]");
var image = null;
var nodes = wym._doc.body.getElementsByTagName(WYMeditor.IMG);
for(var i=0; i < nodes.length; i++)
{
if(jQuery(nodes[i]).attr(WYMeditor.SRC) == wym._current_unique_stamp)
{
image = jQuery(nodes[i]);
break;
}
}
if(image) {
image.attr(WYMeditor.SRC, sUrl);
image.attr(WYMeditor.TITLE, sTitle);
image.attr(WYMeditor.ALT, sAlt);
if (!jQuery.browser.safari)
{
if (replaceable != null)
{
if (this._selected_image == null || (this._selected_image != null && replaceable.parentNode != null))
{
replaceable.after(image);
replaceable.remove();
}
}
}
}
// fire a click event on the dialogs close button
wym.close_dialog();
}
});
jQuery(wym._options.dialogTableSelector + " " + wym._options.submitSelector).click(function() {
var iRows = jQuery(wym._options.rowsSelector).val();
var iCols = jQuery(wym._options.colsSelector).val();
if(iRows > 0 && iCols > 0)
{
var table = wym._doc.createElement(WYMeditor.TABLE);
var newRow = null;
var newCol = null;
var sCaption = jQuery(wym._options.captionSelector).val();
//we create the caption
var newCaption = table.createCaption();
newCaption.innerHTML = sCaption;
//we create the rows and cells
for(x=0; x<iRows; x++) {
newRow = table.insertRow(x);
for(y=0; y<iCols; y++) {newRow.insertCell(y);}
}
//append the table after the selected container
var node = jQuery(wym.findUp(wym.container(),
WYMeditor.MAIN_CONTAINERS)).get(0);
if(!node || !node.parentNode) jQuery(wym._doc.body).append(table);
else jQuery(node).after(table);
}
// fire a click event on the dialogs close button
wym.close_dialog();
});
jQuery(wym._options.dialogPasteSelector + " " + wym._options.submitSelector).click(function() {
var sText = jQuery(wym._options.textSelector).val();
wym.paste(sText);
// fire a click event on the dialogs close button
wym.close_dialog();
});
jQuery(wym._options.dialogPreviewSelector + " "
+ wym._options.previewSelector)
.html(wym.xhtml());
//post-init functions
if(jQuery.isFunction(wym._options.postInitDialog))
wym._options.postInitDialog(wym,window);
};
WYMeditor.editor.prototype.close_dialog = function(e, cancelled) {
if (cancelled)
{
// if span exists, repalce it with its own html contents.
replaceable = jQuery(this._doc.body).find('#replace_me_with_' + this._current_unique_stamp);
if (replaceable[0] != null) {
if (replaceable[0].tagName.toLowerCase() != WYMeditor.A) {
replaceable.replaceWith(replaceable.html());
}
else {
replaceable[0].id = replaceable[0]._id_before_replaceable;
}
}
if (this._undo_on_cancel == true) {
this._exec("undo");
}
else if (this._redo_on_cancel == true) {
this._exec("redo");
}
}
if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8)
{
this._iframe.contentWindow.focus();
}
if ((inline_dialog_container = $('inline_dialog_container')) != null)
{
inline_dialog_container.remove();
}
tb_remove();
if (e) {
e.stop();
}
}
/********** XHTML LEXER/PARSER **********/
/*
* @name xml
* @description Use these methods to generate XML and XHTML compliant tags and
* escape tag attributes correctly
* @author Bermi Ferrer - http://bermi.org
* @author David Heinemeier Hansson http://loudthinking.com
*/
WYMeditor.XmlHelper = function()
{
this._entitiesDiv = document.createElement('div');
return this;
};
/*
* @name tag
* @description
* Returns an empty HTML tag of type *name* which by default is XHTML
* compliant. Setting *open* to true will create an open tag compatible
* with HTML 4.0 and below. Add HTML attributes by passing an attributes
* array to *options*. For attributes with no value like (disabled and
* readonly), give it a value of true in the *options* array.
*
* Examples:
*
* this.tag('br')
* # => <br />
* this.tag ('br', false, true)
* # => <br>
* this.tag ('input', jQuery({type:'text',disabled:true }) )
* # => <input type="text" disabled="disabled" />
*/
WYMeditor.XmlHelper.prototype.tag = function(name, options, open)
{
options = options || false;
open = open || false;
return '<'+name+(options ? this.tagOptions(options) : '')+(open ? '>' : ' />');
};
/*
* @name contentTag
* @description
* Returns a XML block tag of type *name* surrounding the *content*. Add
* XML attributes by passing an attributes array to *options*. For attributes
* with no value like (disabled and readonly), give it a value of true in
* the *options* array. You can use symbols or strings for the attribute names.
*
* this.contentTag ('p', 'Hello world!' )
* # => <p>Hello world!</p>
* this.contentTag('div', this.contentTag('p', "Hello world!"), jQuery({class : "strong"}))
* # => <div class="strong"><p>Hello world!</p></div>
* this.contentTag("select", options, jQuery({multiple : true}))
* # => <select multiple="multiple">...options...</select>
*/
WYMeditor.XmlHelper.prototype.contentTag = function(name, content, options)
{
options = options || false;
return '<'+name+(options ? this.tagOptions(options) : '')+'>'+content+'</'+name+'>';
};
/*
* @name cdataSection
* @description
* Returns a CDATA section for the given +content+. CDATA sections
* are used to escape blocks of text containing characters which would
* otherwise be recognized as markup. CDATA sections begin with the string
* <tt><![CDATA[</tt> and } with (and may not contain) the string
* <tt>]]></tt>.
*/
WYMeditor.XmlHelper.prototype.cdataSection = function(content)
{
return '<![CDATA['+content+']]>';
};
/*
* @name escapeOnce
* @description
* Returns the escaped +xml+ without affecting existing escaped entities.
*
* this.escapeOnce( "1 > 2 & 3")
* # => "1 > 2 & 3"
*/
WYMeditor.XmlHelper.prototype.escapeOnce = function(xml)
{
return this._fixDoubleEscape(this.escapeEntities(xml));
};
/*
* @name _fixDoubleEscape
* @description
* Fix double-escaped entities, such as &amp;, &#123;, etc.
*/
WYMeditor.XmlHelper.prototype._fixDoubleEscape = function(escaped)
{
return escaped.replace(/&([a-z]+|(#\d+));/ig, "&$1;");
};
/*
* @name tagOptions
* @description
* Takes an array like the one generated by Tag.parseAttributes
* [["src", "http://www.editam.com/?a=b&c=d&f=g"], ["title", "Editam, <Simplified> CMS"]]
* or an object like {src:"http://www.editam.com/?a=b&c=d&f=g", title:"Editam, <Simplified> CMS"}
* and returns a string properly escaped like
* ' src = "http://www.editam.com/?a=b&c=d&f=g" title = "Editam, <Simplified> CMS"'
* which is valid for strict XHTML
*/
WYMeditor.XmlHelper.prototype.tagOptions = function(options)
{
var xml = this;
xml._formated_options = '';
for (var key in options) {
var formated_options = '';
var value = options[key];
if(typeof value != 'function' && value.length > 0) {
if(parseInt(key) == key && typeof value == 'object'){
key = value.shift();
value = value.pop();
}
if(key != '' && value != ''){
xml._formated_options += ' '+key+'="'+xml.escapeOnce(value)+'"';
}
}
}
return xml._formated_options;
};
/*
* @name escapeEntities
* @description
* Escapes XML/HTML entities <, >, & and ". If seccond parameter is set to false it
* will not escape ". If set to true it will also escape '
*/
WYMeditor.XmlHelper.prototype.escapeEntities = function(string, escape_quotes)
{
this._entitiesDiv.innerHTML = string;
this._entitiesDiv.textContent = string;
var result = this._entitiesDiv.innerHTML;
if(typeof escape_quotes == 'undefined'){
if(escape_quotes != false) result = result.replace('"', '"');
if(escape_quotes == true) result = result.replace('"', ''');
}
return result;
};
/*
* Parses a string conatining tag attributes and values an returns an array formated like
* [["src", "http://www.editam.com"], ["title", "Editam, Simplified CMS"]]
*/
WYMeditor.XmlHelper.prototype.parseAttributes = function(tag_attributes)
{
// Use a compounded regex to match single quoted, double quoted and unquoted attribute pairs
var result = [];
var matches = tag_attributes.split(/((=\s*")(")("))|((=\s*\')(\')(\'))|((=\s*[^>\s]*))/g);
if(matches.toString() != tag_attributes){
for (var k in matches) {
var v = matches[k];
if(typeof v != 'function' && v.length != 0){
var re = new RegExp('(\\w+)\\s*'+v);
if(match = tag_attributes.match(re) ){
var value = v.replace(/^[\s=]+/, "");
var delimiter = value.charAt(0);
delimiter = delimiter == '"' ? '"' : (delimiter=="'"?"'":'');
if(delimiter != ''){
value = delimiter == '"' ? value.replace(/^"|"+$/g, '') : value.replace(/^'|'+$/g, '');
}
tag_attributes = tag_attributes.replace(match[0],'');
result.push([match[1] , value]);
}
}
}
}
return result;
};
/**
* XhtmlValidator for validating tag attributes
*
* @author Bermi Ferrer - http://bermi.org
*/
WYMeditor.XhtmlValidator = {
"_attributes":
{
"core":
{
"except":[
"base",
"head",
"html",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"class",
"id",
"style",
"title",
"accesskey",
"tabindex"
]
},
"language":
{
"except":[
"base",
"br",
"hr",
"iframe",
"param",
"script"
],
"attributes":
{
"dir":[
"ltr",
"rtl"
],
"0":"lang",
"1":"xml:lang"
}
},
"keyboard":
{
"attributes":
{
"accesskey":/^(\w){1}$/,
"tabindex":/^(\d)+$/
}
}
},
"_events":
{
"window":
{
"only":[
"body"
],
"attributes":[
"onload",
"onunload"
]
},
"form":
{
"only":[
"form",
"input",
"textarea",
"select",
"a",
"label",
"button"
],
"attributes":[
"onchange",
"onsubmit",
"onreset",
"onselect",
"onblur",
"onfocus"
]
},
"keyboard":
{
"except":[
"base",
"bdo",
"br",
"frame",
"frameset",
"head",
"html",
"iframe",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"onkeydown",
"onkeypress",
"onkeyup"
]
},
"mouse":
{
"except":[
"base",
"bdo",
"br",
"head",
"html",
"meta",
"param",
"script",
"style",
"title"
],
"attributes":[
"onclick",
"ondblclick",
"onmousedown",
"onmousemove",
"onmouseover",
"onmouseout",
"onmouseup"
]
}
},
"_tags":
{
"a":
{
"attributes":
{
"0":"charset",
"1":"coords",
"2":"href",
"3":"hreflang",
"4":"name",
"rel":/^(alternate|designates|stylesheet|start|next|prev|contents|index|glossary|copyright|chapter|section|subsection|appendix|help|bookmark| |shortcut|icon|moodalbox)+$/,
"rev":/^(alternate|designates|stylesheet|start|next|prev|contents|index|glossary|copyright|chapter|section|subsection|appendix|help|bookmark| |shortcut|icon|moodalbox)+$/,
"shape":/^(rect|rectangle|circ|circle|poly|polygon)$/,
"5":"type",
"target":/^(_blank)+$/
}
},
"0":"abbr",
"1":"acronym",
"2":"address",
"area":
{
"attributes":
{
"0":"alt",
"1":"coords",
"2":"href",
"nohref":/^(true|false)$/,
"shape":/^(rect|rectangle|circ|circle|poly|polygon)$/
},
"required":[
"alt"
]
},
"3":"b",
"base":
{
"attributes":[
"href"
],
"required":[
"href"
]
},
"bdo":
{
"attributes":
{
"dir":/^(ltr|rtl)$/
},
"required":[
"dir"
]
},
"4":"big",
"blockquote":
{
"attributes":[
"cite"
]
},
"5":"body",
"6":"br",
"button":
{
"attributes":
{
"disabled":/^(disabled)$/,
"type":/^(button|reset|submit)$/,
"0":"value"
},
"inside":"form"
},
"7":"caption",
"8":"cite",
"9":"code",
"col":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"span":/^(\d)+$/,
"valign":/^(top|middle|bottom|baseline)$/,
"2":"width"
},
"inside":"colgroup"
},
"colgroup":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"span":/^(\d)+$/,
"valign":/^(top|middle|bottom|baseline)$/,
"2":"width"
}
},
"10":"dd",
"del":
{
"attributes":
{
"0":"cite",
"datetime":/^([0-9]){8}/
}
},
"11":"div",
"12":"dfn",
"13":"dl",
"14":"dt",
"15":"em",
"fieldset":
{
"inside":"form"
},
"form":
{
"attributes":
{
"0":"action",
"1":"accept",
"2":"accept-charset",
"3":"enctype",
"method":/^(get|post)$/
},
"required":[
"action"
]
},
"head":
{
"attributes":[
"profile"
]
},
"16":"h1",
"17":"h2",
"18":"h3",
"19":"h4",
"20":"h5",
"21":"h6",
"22":"hr",
"html":
{
"attributes":[
"xmlns"
]
},
"23":"i",
"iframe":
{
"attributes":[
"src",
"width",
"height",
"frameborder",
"scrolling",
"marginheight",
"marginwidth"
],
"required":[
"src"
]
},
"img":
{
"attributes":{
"align":/^(right|left|center|justify)$/,
"0":"alt",
"1":"src",
"2":"height",
"3":"ismap",
"4":"longdesc",
"5":"usemap",
"6":"width"
},
"required":[
"alt",
"src"
]
},
"input":
{
"attributes":
{
"0":"accept",
"1":"alt",
"checked":/^(checked)$/,
"disabled":/^(disabled)$/,
"maxlength":/^(\d)+$/,
"2":"name",
"readonly":/^(readonly)$/,
"size":/^(\d)+$/,
"3":"src",
"type":/^(button|checkbox|file|hidden|image|password|radio|reset|submit|text)$/,
"4":"value"
},
"inside":"form"
},
"ins":
{
"attributes":
{
"0":"cite",
"datetime":/^([0-9]){8}/
}
},
"24":"kbd",
"label":
{
"attributes":[
"for"
],
"inside":"form"
},
"25":"legend",
"26":"li",
"link":
{
"attributes":
{
"0":"charset",
"1":"href",
"2":"hreflang",
"media":/^(all|braille|print|projection|screen|speech|,|;| )+$/i,
//next comment line required by Opera!
/*"rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,*/
"rel":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
"rev":/^(alternate|appendix|bookmark|chapter|contents|copyright|glossary|help|home|index|next|prev|section|start|stylesheet|subsection| |shortcut|icon)+$/i,
"3":"type"
},
"inside":"head"
},
"map":
{
"attributes":[
"id",
"name"
],
"required":[
"id"
]
},
"meta":
{
"attributes":
{
"0":"content",
"http-equiv":/^(content\-type|expires|refresh|set\-cookie)$/i,
"1":"name",
"2":"scheme"
},
"required":[
"content"
]
},
"27":"noscript",
"28":"ol",
"optgroup":
{
"attributes":
{
"0":"label",
"disabled": /^(disabled)$/
},
"required":[
"label"
]
},
"option":
{
"attributes":
{
"0":"label",
"disabled":/^(disabled)$/,
"selected":/^(selected)$/,
"1":"value"
},
"inside":"select"
},
"29":"p",
"param":
{
"attributes":
[
"type",
"value",
"name"
],
"required":[
"name"
],
"inside":"object"
},
"embed":
{
"attributes":
[
"width",
"height",
"allowfullscreen",
"allowscriptaccess",
"wmode",
"type",
"src"
],
"inside":"object"
},
"object":
{
"attributes":[
"archive",
"classid",
"codebase",
"codetype",
"data",
"declare",
"height",
"name",
"standby",
"type",
"usemap",
"width"
]
},
"30":"pre",
"q":
{
"attributes":[
"cite"
]
},
"31":"samp",
"script":
{
"attributes":
{
"type":/^(text\/ecmascript|text\/javascript|text\/jscript|text\/vbscript|text\/vbs|text\/xml)$/,
"0":"charset",
"defer":/^(defer)$/,
"1":"src"
},
"required":[
"type"
]
},
"select":
{
"attributes":
{
"disabled":/^(disabled)$/,
"multiple":/^(multiple)$/,
"0":"name",
"1":"size"
},
"inside":"form"
},
"32":"small",
"33":"span",
"34":"strong",
"style":
{
"attributes":
{
"0":"type",
"media":/^(screen|tty|tv|projection|handheld|print|braille|aural|all)$/
},
"required":[
"type"
]
},
"35":"sub",
"36":"sup",
"table":
{
"attributes":
{
"0":"border",
"1":"cellpadding",
"2":"cellspacing",
"frame":/^(void|above|below|hsides|lhs|rhs|vsides|box|border)$/,
"rules":/^(none|groups|rows|cols|all)$/,
"3":"summary",
"4":"width"
}
},
"tbody":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"td":
{
"attributes":
{
"0":"abbr",
"align":/^(left|right|center|justify|char)$/,
"1":"axis",
"2":"char",
"3":"charoff",
"colspan":/^(\d)+$/,
"4":"headers",
"rowspan":/^(\d)+$/,
"scope":/^(col|colgroup|row|rowgroup)$/,
"valign":/^(top|middle|bottom|baseline)$/
}
},
"textarea":
{
"attributes":[
"cols",
"rows",
"disabled",
"name",
"readonly"
],
"required":[
"cols",
"rows"
],
"inside":"form"
},
"tfoot":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom)$/,
"2":"baseline"
}
},
"th":
{
"attributes":
{
"0":"abbr",
"align":/^(left|right|center|justify|char)$/,
"1":"axis",
"2":"char",
"3":"charoff",
"colspan":/^(\d)+$/,
"4":"headers",
"rowspan":/^(\d)+$/,
"scope":/^(col|colgroup|row|rowgroup)$/,
"valign":/^(top|middle|bottom|baseline)$/
}
},
"thead":
{
"attributes":
{
"align":/^(right|left|center|justify)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"37":"title",
"tr":
{
"attributes":
{
"align":/^(right|left|center|justify|char)$/,
"0":"char",
"1":"charoff",
"valign":/^(top|middle|bottom|baseline)$/
}
},
"38":"tt",
"39":"ul",
"40":"var"
},
// Temporary skiped attributes
skiped_attributes : [],
skiped_attribute_values : [],
getValidTagAttributes: function(tag, attributes)
{
var valid_attributes = {};
var possible_attributes = this.getPossibleTagAttributes(tag);
for(var attribute in attributes) {
var value = attributes[attribute];
var h = WYMeditor.Helper;
if(!h.contains(this.skiped_attributes, attribute) && !h.contains(this.skiped_attribute_values, value)){
if (typeof value != 'function' && h.contains(possible_attributes, attribute)) {
if (this.doesAttributeNeedsValidation(tag, attribute)) {
if(this.validateAttribute(tag, attribute, value)){
valid_attributes[attribute] = value;
}
}else{
valid_attributes[attribute] = value;
}
}
}
}
return valid_attributes;
},
getUniqueAttributesAndEventsForTag : function(tag)
{
var result = [];
if (this._tags[tag] && this._tags[tag]['attributes']) {
for (k in this._tags[tag]['attributes']) {
result.push(parseInt(k) == k ? this._tags[tag]['attributes'][k] : k);
}
}
return result;
},
getDefaultAttributesAndEventsForTags : function()
{
var result = [];
for (var key in this._events){
result.push(this._events[key]);
}
for (var key in this._attributes){
result.push(this._attributes[key]);
}
return result;
},
isValidTag : function(tag)
{
if(this._tags[tag]){
return true;
}
for(var key in this._tags){
if(this._tags[key] == tag){
return true;
}
}
return false;
},
getDefaultAttributesAndEventsForTag : function(tag)
{
var default_attributes = [];
if (this.isValidTag(tag)) {
var default_attributes_and_events = this.getDefaultAttributesAndEventsForTags();
for(var key in default_attributes_and_events) {
var defaults = default_attributes_and_events[key];
if(typeof defaults == 'object'){
var h = WYMeditor.Helper;
if ((defaults['except'] && h.contains(defaults['except'], tag)) || (defaults['only'] && !h.contains(defaults['only'], tag))) {
continue;
}
var tag_defaults = defaults['attributes'] ? defaults['attributes'] : defaults['events'];
for(var k in tag_defaults) {
default_attributes.push(typeof tag_defaults[k] != 'string' ? k : tag_defaults[k]);
}
}
}
}
return default_attributes;
},
doesAttributeNeedsValidation: function(tag, attribute)
{
return this._tags[tag] && ((this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute]) || (this._tags[tag]['required'] &&
WYMeditor.Helper.contains(this._tags[tag]['required'], attribute)));
},
validateAttribute : function(tag, attribute, value)
{
if ( this._tags[tag] &&
(this._tags[tag]['attributes'] && this._tags[tag]['attributes'][attribute] && value.length > 0 && !value.match(this._tags[tag]['attributes'][attribute])) || // invalid format
(this._tags[tag] && this._tags[tag]['required'] && WYMeditor.Helper.contains(this._tags[tag]['required'], attribute) && value.length == 0) // required attribute
) {
return false;
}
return typeof this._tags[tag] != 'undefined';
},
getPossibleTagAttributes : function(tag)
{
if (!this._possible_tag_attributes) {
this._possible_tag_attributes = {};
}
if (!this._possible_tag_attributes[tag]) {
this._possible_tag_attributes[tag] = this.getUniqueAttributesAndEventsForTag(tag).concat(this.getDefaultAttributesAndEventsForTag(tag));
}
return this._possible_tag_attributes[tag];
}
};
/**
* Compounded regular expression. Any of
* the contained patterns could match and
* when one does, it's label is returned.
*
* Constructor. Starts with no patterns.
* @param boolean case True for case sensitive, false
* for insensitive.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.ParallelRegex = function(case_sensitive)
{
this._case = case_sensitive;
this._patterns = [];
this._labels = [];
this._regex = null;
return this;
};
/**
* Adds a pattern with an optional label.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string label Label of regex to be returned
* on a match.
* @access public
*/
WYMeditor.ParallelRegex.prototype.addPattern = function(pattern, label)
{
label = label || true;
var count = this._patterns.length;
this._patterns[count] = pattern;
this._labels[count] = label;
this._regex = null;
};
/**
* Attempts to match all patterns at once against
* a string.
* @param string subject String to match against.
*
* @return boolean True on success.
* @return string match First matched portion of
* subject.
* @access public
*/
WYMeditor.ParallelRegex.prototype.match = function(subject)
{
if (this._patterns.length == 0) {
return [false, ''];
}
var matches = subject.match(this._getCompoundedRegex());
if(!matches){
return [false, ''];
}
var match = matches[0];
for (var i = 1; i < matches.length; i++) {
if (matches[i]) {
return [this._labels[i-1], match];
}
}
return [true, matches[0]];
};
/**
* Compounds the patterns into a single
* regular expression separated with the
* "or" operator. Caches the regex.
* Will automatically escape (, ) and / tokens.
* @param array patterns List of patterns in order.
* @access private
*/
WYMeditor.ParallelRegex.prototype._getCompoundedRegex = function()
{
if (this._regex == null) {
for (var i = 0, count = this._patterns.length; i < count; i++) {
this._patterns[i] = '(' + this._untokenizeRegex(this._tokenizeRegex(this._patterns[i]).replace(/([\/\(\)])/g,'\\$1')) + ')';
}
this._regex = new RegExp(this._patterns.join("|") ,this._getPerlMatchingFlags());
}
return this._regex;
};
/**
* Escape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._tokenizeRegex = function(regex)
{
return regex.
replace(/\(\?(i|m|s|x|U)\)/, '~~~~~~Tk1\$1~~~~~~').
replace(/\(\?(\-[i|m|s|x|U])\)/, '~~~~~~Tk2\$1~~~~~~').
replace(/\(\?\=(.*)\)/, '~~~~~~Tk3\$1~~~~~~').
replace(/\(\?\!(.*)\)/, '~~~~~~Tk4\$1~~~~~~').
replace(/\(\?\<\=(.*)\)/, '~~~~~~Tk5\$1~~~~~~').
replace(/\(\?\<\!(.*)\)/, '~~~~~~Tk6\$1~~~~~~').
replace(/\(\?\:(.*)\)/, '~~~~~~Tk7\$1~~~~~~');
};
/**
* Unscape lookahead/lookbehind blocks
*/
WYMeditor.ParallelRegex.prototype._untokenizeRegex = function(regex)
{
return regex.
replace(/~~~~~~Tk1(.{1})~~~~~~/, "(?\$1)").
replace(/~~~~~~Tk2(.{2})~~~~~~/, "(?\$1)").
replace(/~~~~~~Tk3(.*)~~~~~~/, "(?=\$1)").
replace(/~~~~~~Tk4(.*)~~~~~~/, "(?!\$1)").
replace(/~~~~~~Tk5(.*)~~~~~~/, "(?<=\$1)").
replace(/~~~~~~Tk6(.*)~~~~~~/, "(?<!\$1)").
replace(/~~~~~~Tk7(.*)~~~~~~/, "(?:\$1)");
};
/**
* Accessor for perl regex mode flags to use.
* @return string Perl regex flags.
* @access private
*/
WYMeditor.ParallelRegex.prototype._getPerlMatchingFlags = function()
{
return (this._case ? "m" : "mi");
};
/**
* States for a stack machine.
*
* Constructor. Starts in named state.
* @param string start Starting state name.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.StateStack = function(start)
{
this._stack = [start];
return this;
};
/**
* Accessor for current state.
* @return string State.
* @access public
*/
WYMeditor.StateStack.prototype.getCurrent = function()
{
return this._stack[this._stack.length - 1];
};
/**
* Adds a state to the stack and sets it
* to be the current state.
* @param string state New state.
* @access public
*/
WYMeditor.StateStack.prototype.enter = function(state)
{
this._stack.push(state);
};
/**
* Leaves the current state and reverts
* to the previous one.
* @return boolean False if we drop off
* the bottom of the list.
* @access public
*/
WYMeditor.StateStack.prototype.leave = function()
{
if (this._stack.length == 1) {
return false;
}
this._stack.pop();
return true;
};
// GLOBALS
WYMeditor.LEXER_ENTER = 1;
WYMeditor.LEXER_MATCHED = 2;
WYMeditor.LEXER_UNMATCHED = 3;
WYMeditor.LEXER_EXIT = 4;
WYMeditor.LEXER_SPECIAL = 5;
/**
* Accepts text and breaks it into tokens.
* Some optimisation to make the sure the
* content is only scanned by the PHP regex
* parser once. Lexer modes must not start
* with leading underscores.
*
* Sets up the lexer in case insensitive matching
* by default.
* @param Parser parser Handling strategy by reference.
* @param string start Starting handler.
* @param boolean case True for case sensitive.
* @access public
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.Lexer = function(parser, start, case_sensitive)
{
start = start || 'accept';
this._case = case_sensitive || false;
this._regexes = {};
this._parser = parser;
this._mode = new WYMeditor.StateStack(start);
this._mode_handlers = {};
this._mode_handlers[start] = start;
return this;
};
/**
* Adds a token search pattern for a particular
* parsing mode. The pattern does not change the
* current mode.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @access public
*/
WYMeditor.Lexer.prototype.addPattern = function(pattern, mode)
{
var mode = mode || "accept";
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern);
if (typeof this._mode_handlers[mode] == 'undefined') {
this._mode_handlers[mode] = mode;
}
};
/**
* Adds a pattern that will enter a new parsing
* mode. Useful for entering parenthesis, strings,
* tags, etc.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @param string new_mode Change parsing to this new
* nested mode.
* @access public
*/
WYMeditor.Lexer.prototype.addEntryPattern = function(pattern, mode, new_mode)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, new_mode);
if (typeof this._mode_handlers[new_mode] == 'undefined') {
this._mode_handlers[new_mode] = new_mode;
}
};
/**
* Adds a pattern that will exit the current mode
* and re-enter the previous one.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Mode to leave.
* @access public
*/
WYMeditor.Lexer.prototype.addExitPattern = function(pattern, mode)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, "__exit");
if (typeof this._mode_handlers[mode] == 'undefined') {
this._mode_handlers[mode] = mode;
}
};
/**
* Adds a pattern that has a special mode. Acts as an entry
* and exit pattern in one go, effectively calling a special
* parser handler for this token only.
* @param string pattern Perl style regex, but ( and )
* lose the usual meaning.
* @param string mode Should only apply this
* pattern when dealing with
* this type of input.
* @param string special Use this mode for this one token.
* @access public
*/
WYMeditor.Lexer.prototype.addSpecialPattern = function(pattern, mode, special)
{
if (typeof this._regexes[mode] == 'undefined') {
this._regexes[mode] = new WYMeditor.ParallelRegex(this._case);
}
this._regexes[mode].addPattern(pattern, '_'+special);
if (typeof this._mode_handlers[special] == 'undefined') {
this._mode_handlers[special] = special;
}
};
/**
* Adds a mapping from a mode to another handler.
* @param string mode Mode to be remapped.
* @param string handler New target handler.
* @access public
*/
WYMeditor.Lexer.prototype.mapHandler = function(mode, handler)
{
this._mode_handlers[mode] = handler;
};
/**
* Splits the page text into tokens. Will fail
* if the handlers report an error or if no
* content is consumed. If successful then each
* unparsed and parsed token invokes a call to the
* held listener.
* @param string raw Raw HTML text.
* @return boolean True on success, else false.
* @access public
*/
WYMeditor.Lexer.prototype.parse = function(raw)
{
if (typeof this._parser == 'undefined') {
return false;
}
var length = raw.length;
var parsed;
while (typeof (parsed = this._reduce(raw)) == 'object') {
var raw = parsed[0];
var unmatched = parsed[1];
var matched = parsed[2];
var mode = parsed[3];
if (! this._dispatchTokens(unmatched, matched, mode)) {
return false;
}
if (raw == '') {
return true;
}
if (raw.length == length) {
return false;
}
length = raw.length;
}
if (! parsed ) {
return false;
}
return this._invokeParser(raw, WYMeditor.LEXER_UNMATCHED);
};
/**
* Sends the matched token and any leading unmatched
* text to the parser changing the lexer to a new
* mode if one is listed.
* @param string unmatched Unmatched leading portion.
* @param string matched Actual token match.
* @param string mode Mode after match. A boolean
* false mode causes no change.
* @return boolean False if there was any error
* from the parser.
* @access private
*/
WYMeditor.Lexer.prototype._dispatchTokens = function(unmatched, matched, mode)
{
mode = mode || false;
if (! this._invokeParser(unmatched, WYMeditor.LEXER_UNMATCHED)) {
return false;
}
if (typeof mode == 'boolean') {
return this._invokeParser(matched, WYMeditor.LEXER_MATCHED);
}
if (this._isModeEnd(mode)) {
if (! this._invokeParser(matched, WYMeditor.LEXER_EXIT)) {
return false;
}
return this._mode.leave();
}
if (this._isSpecialMode(mode)) {
this._mode.enter(this._decodeSpecial(mode));
if (! this._invokeParser(matched, WYMeditor.LEXER_SPECIAL)) {
return false;
}
return this._mode.leave();
}
this._mode.enter(mode);
return this._invokeParser(matched, WYMeditor.LEXER_ENTER);
};
/**
* Tests to see if the new mode is actually to leave
* the current mode and pop an item from the matching
* mode stack.
* @param string mode Mode to test.
* @return boolean True if this is the exit mode.
* @access private
*/
WYMeditor.Lexer.prototype._isModeEnd = function(mode)
{
return (mode === "__exit");
};
/**
* Test to see if the mode is one where this mode
* is entered for this token only and automatically
* leaves immediately afterwoods.
* @param string mode Mode to test.
* @return boolean True if this is the exit mode.
* @access private
*/
WYMeditor.Lexer.prototype._isSpecialMode = function(mode)
{
return (mode.substring(0,1) == "_");
};
/**
* Strips the magic underscore marking single token
* modes.
* @param string mode Mode to decode.
* @return string Underlying mode name.
* @access private
*/
WYMeditor.Lexer.prototype._decodeSpecial = function(mode)
{
return mode.substring(1);
};
/**
* Calls the parser method named after the current
* mode. Empty content will be ignored. The lexer
* has a parser handler for each mode in the lexer.
* @param string content Text parsed.
* @param boolean is_match Token is recognised rather
* than unparsed data.
* @access private
*/
WYMeditor.Lexer.prototype._invokeParser = function(content, is_match)
{
if (!/ +/.test(content) && ((content === '') || (content === false))) {
return true;
}
var current = this._mode.getCurrent();
var handler = this._mode_handlers[current];
var result;
eval('result = this._parser.' + handler + '(content, is_match);');
return result;
};
/**
* Tries to match a chunk of text and if successful
* removes the recognised chunk and any leading
* unparsed data. Empty strings will not be matched.
* @param string raw The subject to parse. This is the
* content that will be eaten.
* @return array/boolean Three item list of unparsed
* content followed by the
* recognised token and finally the
* action the parser is to take.
* True if no match, false if there
* is a parsing error.
* @access private
*/
WYMeditor.Lexer.prototype._reduce = function(raw)
{
var matched = this._regexes[this._mode.getCurrent()].match(raw);
var match = matched[1];
var action = matched[0];
if (action) {
var unparsed_character_count = raw.indexOf(match);
var unparsed = raw.substr(0, unparsed_character_count);
raw = raw.substring(unparsed_character_count + match.length);
return [raw, unparsed, match, action];
}
return true;
};
/**
* This are the rules for breaking the XHTML code into events
* handled by the provided parser.
*
* @author Marcus Baker (http://lastcraft.com)
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlLexer = function(parser)
{
jQuery.extend(this, new WYMeditor.Lexer(parser, 'Text'));
this.mapHandler('Text', 'Text');
this.addTokens();
this.init();
return this;
};
WYMeditor.XhtmlLexer.prototype.init = function()
{
};
WYMeditor.XhtmlLexer.prototype.addTokens = function()
{
this.addCommentTokens('Text');
this.addScriptTokens('Text');
this.addCssTokens('Text');
this.addTagTokens('Text');
};
WYMeditor.XhtmlLexer.prototype.addCommentTokens = function(scope)
{
this.addEntryPattern("<!--", scope, 'Comment');
this.addExitPattern("-->", 'Comment');
};
WYMeditor.XhtmlLexer.prototype.addScriptTokens = function(scope)
{
this.addEntryPattern("<script", scope, 'Script');
this.addExitPattern("</script>", 'Script');
};
WYMeditor.XhtmlLexer.prototype.addCssTokens = function(scope)
{
this.addEntryPattern("<style", scope, 'Css');
this.addExitPattern("</style>", 'Css');
};
WYMeditor.XhtmlLexer.prototype.addTagTokens = function(scope)
{
this.addSpecialPattern("<\\s*[a-z0-9:\-]+\\s*>", scope, 'OpeningTag');
this.addEntryPattern("<[a-z0-9:\-]+"+'[\\\/ \\\>]+', scope, 'OpeningTag');
this.addInTagDeclarationTokens('OpeningTag');
this.addSpecialPattern("</\\s*[a-z0-9:\-]+\\s*>", scope, 'ClosingTag');
};
WYMeditor.XhtmlLexer.prototype.addInTagDeclarationTokens = function(scope)
{
this.addSpecialPattern('\\s+', scope, 'Ignore');
this.addAttributeTokens(scope);
this.addExitPattern('/>', scope);
this.addExitPattern('>', scope);
};
WYMeditor.XhtmlLexer.prototype.addAttributeTokens = function(scope)
{
this.addSpecialPattern("\\s*[a-z-_0-9]*:?[a-z-_0-9]+\\s*(?=\=)\\s*", scope, 'TagAttributes');
this.addEntryPattern('=\\s*"', scope, 'DoubleQuotedAttribute');
this.addPattern("\\\\\"", 'DoubleQuotedAttribute');
this.addExitPattern('"', 'DoubleQuotedAttribute');
this.addEntryPattern("=\\s*'", scope, 'SingleQuotedAttribute');
this.addPattern("\\\\'", 'SingleQuotedAttribute');
this.addExitPattern("'", 'SingleQuotedAttribute');
this.addSpecialPattern('=\\s*[^>\\s]*', scope, 'UnquotedAttribute');
};
/**
* XHTML Parser.
*
* This XHTML parser will trigger the events available on on
* current SaxListener
*
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlParser = function(Listener, mode)
{
var mode = mode || 'Text';
this._Lexer = new WYMeditor.XhtmlLexer(this);
this._Listener = Listener;
this._mode = mode;
this._matches = [];
this._last_match = '';
this._current_match = '';
return this;
};
WYMeditor.XhtmlParser.prototype.parse = function(raw)
{
this._Lexer.parse(this.beforeParsing(raw));
return this.afterParsing(this._Listener.getResult());
};
WYMeditor.XhtmlParser.prototype.beforeParsing = function(raw)
{
if(raw.match(/class="MsoNormal"/) || raw.match(/ns = "urn:schemas-microsoft-com/)){
// Useful for cleaning up content pasted from other sources (MSWord)
this._Listener.avoidStylingTagsAndAttributes();
}
return this._Listener.beforeParsing(raw);
};
WYMeditor.XhtmlParser.prototype.afterParsing = function(parsed)
{
if(this._Listener._avoiding_tags_implicitly){
this._Listener.allowStylingTagsAndAttributes();
}
return this._Listener.afterParsing(parsed);
};
WYMeditor.XhtmlParser.prototype.Ignore = function(match, state)
{
return true;
};
WYMeditor.XhtmlParser.prototype.Text = function(text)
{
this._Listener.addContent(text);
return true;
};
WYMeditor.XhtmlParser.prototype.Comment = function(match, status)
{
return this._addNonTagBlock(match, status, 'addComment');
};
WYMeditor.XhtmlParser.prototype.Script = function(match, status)
{
return this._addNonTagBlock(match, status, 'addScript');
};
WYMeditor.XhtmlParser.prototype.Css = function(match, status)
{
return this._addNonTagBlock(match, status, 'addCss');
};
WYMeditor.XhtmlParser.prototype._addNonTagBlock = function(match, state, type)
{
switch (state){
case WYMeditor.LEXER_ENTER:
this._non_tag = match;
break;
case WYMeditor.LEXER_UNMATCHED:
this._non_tag += match;
break;
case WYMeditor.LEXER_EXIT:
switch(type) {
case 'addComment':
this._Listener.addComment(this._non_tag+match);
break;
case 'addScript':
this._Listener.addScript(this._non_tag+match);
break;
case 'addCss':
this._Listener.addCss(this._non_tag+match);
break;
}
}
return true;
};
WYMeditor.XhtmlParser.prototype.OpeningTag = function(match, state)
{
switch (state){
case WYMeditor.LEXER_ENTER:
this._tag = this.normalizeTag(match);
this._tag_attributes = {};
break;
case WYMeditor.LEXER_SPECIAL:
this._callOpenTagListener(this.normalizeTag(match));
break;
case WYMeditor.LEXER_EXIT:
this._callOpenTagListener(this._tag, this._tag_attributes);
}
return true;
};
WYMeditor.XhtmlParser.prototype.ClosingTag = function(match, state)
{
this._callCloseTagListener(this.normalizeTag(match));
return true;
};
WYMeditor.XhtmlParser.prototype._callOpenTagListener = function(tag, attributes)
{
var attributes = attributes || {};
this.autoCloseUnclosedBeforeNewOpening(tag);
if(this._Listener.isBlockTag(tag)){
this._Listener._tag_stack.push(tag);
this._Listener.fixNestingBeforeOpeningBlockTag(tag, attributes);
this._Listener.openBlockTag(tag, attributes);
this._increaseOpenTagCounter(tag);
}else if(this._Listener.isInlineTag(tag)){
this._Listener.inlineTag(tag, attributes);
}else{
this._Listener.openUnknownTag(tag, attributes);
this._increaseOpenTagCounter(tag);
}
this._Listener.last_tag = tag;
this._Listener.last_tag_opened = true;
this._Listener.last_tag_attributes = attributes;
};
WYMeditor.XhtmlParser.prototype._callCloseTagListener = function(tag)
{
if(this._decreaseOpenTagCounter(tag)){
this.autoCloseUnclosedBeforeTagClosing(tag);
if(this._Listener.isBlockTag(tag)){
var expected_tag = this._Listener._tag_stack.pop();
if(expected_tag == false){
return;
}else if(expected_tag != tag){
tag = expected_tag;
}
this._Listener.closeBlockTag(tag);
}else{
this._Listener.closeUnknownTag(tag);
}
}else{
this._Listener.closeUnopenedTag(tag);
}
this._Listener.last_tag = tag;
this._Listener.last_tag_opened = false;
};
WYMeditor.XhtmlParser.prototype._increaseOpenTagCounter = function(tag)
{
this._Listener._open_tags[tag] = this._Listener._open_tags[tag] || 0;
this._Listener._open_tags[tag]++;
};
WYMeditor.XhtmlParser.prototype._decreaseOpenTagCounter = function(tag)
{
if(this._Listener._open_tags[tag]){
this._Listener._open_tags[tag]--;
if(this._Listener._open_tags[tag] == 0){
this._Listener._open_tags[tag] = undefined;
}
return true;
}
return false;
};
WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeNewOpening = function(new_tag)
{
this._autoCloseUnclosed(new_tag, false);
};
WYMeditor.XhtmlParser.prototype.autoCloseUnclosedBeforeTagClosing = function(tag)
{
this._autoCloseUnclosed(tag, true);
};
WYMeditor.XhtmlParser.prototype._autoCloseUnclosed = function(new_tag, closing)
{
var closing = closing || false;
if(this._Listener._open_tags){
for (var tag in this._Listener._open_tags) {
var counter = this._Listener._open_tags[tag];
if(counter > 0 && this._Listener.shouldCloseTagAutomatically(tag, new_tag, closing)){
this._callCloseTagListener(tag, true);
}
}
}
};
WYMeditor.XhtmlParser.prototype.getTagReplacements = function()
{
return this._Listener.getTagReplacements();
};
WYMeditor.XhtmlParser.prototype.normalizeTag = function(tag)
{
tag = tag.replace(/^([\s<\/>]*)|([\s<\/>]*)$/gm,'').toLowerCase();
var tags = this._Listener.getTagReplacements();
if(tags[tag]){
return tags[tag];
}
return tag;
};
WYMeditor.XhtmlParser.prototype.TagAttributes = function(match, state)
{
if(WYMeditor.LEXER_SPECIAL == state){
this._current_attribute = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.DoubleQuotedAttribute = function(match, state)
{
if(WYMeditor.LEXER_UNMATCHED == state){
this._tag_attributes[this._current_attribute] = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.SingleQuotedAttribute = function(match, state)
{
if(WYMeditor.LEXER_UNMATCHED == state){
this._tag_attributes[this._current_attribute] = match;
}
return true;
};
WYMeditor.XhtmlParser.prototype.UnquotedAttribute = function(match, state)
{
this._tag_attributes[this._current_attribute] = match.replace(/^=/,'');
return true;
};
/**
* XHTML Sax parser.
*
* @author Bermi Ferrer (http://bermi.org)
*/
WYMeditor.XhtmlSaxListener = function()
{
this.output = '';
this.helper = new WYMeditor.XmlHelper();
this._open_tags = {};
this.validator = WYMeditor.XhtmlValidator;
this._tag_stack = [];
this.avoided_tags = [];
this.entities = {
' ':' ','¡':'¡','¢':'¢',
'£':'£','¤':'¤','¥':'¥',
'¦':'¦','§':'§','¨':'¨',
'©':'©','ª':'ª','«':'«',
'¬':'¬','­':'­','®':'®',
'¯':'¯','°':'°','±':'±',
'²':'²','³':'³','´':'´',
'µ':'µ','¶':'¶','·':'·',
'¸':'¸','¹':'¹','º':'º',
'»':'»','¼':'¼','½':'½',
'¾':'¾','¿':'¿','À':'À',
'Á':'Á','Â':'Â','Ã':'Ã',
'Ä':'Ä','Å':'Å','Æ':'Æ',
'Ç':'Ç','È':'È','É':'É',
'Ê':'Ê','Ë':'Ë','Ì':'Ì',
'Í':'Í','Î':'Î','Ï':'Ï',
'Ð':'Ð','Ñ':'Ñ','Ò':'Ò',
'Ó':'Ó','Ô':'Ô','Õ':'Õ',
'Ö':'Ö','×':'×','Ø':'Ø',
'Ù':'Ù','Ú':'Ú','Û':'Û',
'Ü':'Ü','Ý':'Ý','Þ':'Þ',
'ß':'ß','à':'à','á':'á',
'â':'â','ã':'ã','ä':'ä',
'å':'å','æ':'æ','ç':'ç',
'è':'è','é':'é','ê':'ê',
'ë':'ë','ì':'ì','í':'í',
'î':'î','ï':'ï','ð':'ð',
'ñ':'ñ','ò':'ò','ó':'ó',
'ô':'ô','õ':'õ','ö':'ö',
'÷':'÷','ø':'ø','ù':'ù',
'ú':'ú','û':'û','ü':'ü',
'ý':'ý','þ':'þ','ÿ':'ÿ',
'Œ':'Œ','œ':'œ','Š':'Š',
'š':'š','Ÿ':'Ÿ','ƒ':'ƒ',
'ˆ':'ˆ','˜':'˜','Α':'Α',
'Β':'Β','Γ':'Γ','Δ':'Δ',
'Ε':'Ε','Ζ':'Ζ','Η':'Η',
'Θ':'Θ','Ι':'Ι','Κ':'Κ',
'Λ':'Λ','Μ':'Μ','Ν':'Ν',
'Ξ':'Ξ','Ο':'Ο','Π':'Π',
'Ρ':'Ρ','Σ':'Σ','Τ':'Τ',
'Υ':'Υ','Φ':'Φ','Χ':'Χ',
'Ψ':'Ψ','Ω':'Ω','α':'α',
'β':'β','γ':'γ','δ':'δ',
'ε':'ε','ζ':'ζ','η':'η',
'θ':'θ','ι':'ι','κ':'κ',
'λ':'λ','μ':'μ','ν':'ν',
'ξ':'ξ','ο':'ο','π':'π',
'ρ':'ρ','ς':'ς','σ':'σ',
'τ':'τ','υ':'υ','φ':'φ',
'χ':'χ','ψ':'ψ','ω':'ω',
'ϑ':'ϑ','ϒ':'ϒ','ϖ':'ϖ',
' ':' ',' ':' ',' ':' ',
'‌':'‌','‍':'‍','‎':'‎',
'‏':'‏','–':'–','—':'—',
'‘':'‘','’':'’','‚':'‚',
'“':'“','”':'”','„':'„',
'†':'†','‡':'‡','•':'•',
'…':'…','‰':'‰','′':'′',
'″':'″','‹':'‹','›':'›',
'‾':'‾','⁄':'⁄','€':'€',
'ℑ':'ℑ','℘':'℘','ℜ':'ℜ',
'™':'™','ℵ':'ℵ','←':'←',
'↑':'↑','→':'→','↓':'↓',
'↔':'↔','↵':'↵','⇐':'⇐',
'⇑':'⇑','⇒':'⇒','⇓':'⇓',
'⇔':'⇔','∀':'∀','∂':'∂',
'∃':'∃','∅':'∅','∇':'∇',
'∈':'∈','∉':'∉','∋':'∋',
'∏':'∏','∑':'∑','−':'−',
'∗':'∗','√':'√','∝':'∝',
'∞':'∞','∠':'∠','∧':'∧',
'∨':'∨','∩':'∩','∪':'∪',
'∫':'∫','∴':'∴','∼':'∼',
'≅':'≅','≈':'≈','≠':'≠',
'≡':'≡','≤':'≤','≥':'≥',
'⊂':'⊂','⊃':'⊃','⊄':'⊄',
'⊆':'⊆','⊇':'⊇','⊕':'⊕',
'⊗':'⊗','⊥':'⊥','⋅':'⋅',
'⌈':'⌈','⌉':'⌉','⌊':'⌊',
'⌋':'⌋','⟨':'〈','⟩':'〉',
'◊':'◊','♠':'♠','♣':'♣',
'♥':'♥','♦':'♦'};
this.block_tags = ["a", "abbr", "acronym", "address", "area", "b",
"base", "bdo", "big", "blockquote", "body", "button",
"caption", "cite", "code", "col", "colgroup", "dd", "del", "div",
"dfn", "dl", "dt", "em", "fieldset", "form", "head", "h1", "h2",
"h3", "h4", "h5", "h6", "html", "i", "iframe", "ins",
"kbd", "label", "legend", "li", "map", "noscript",
"object", "ol", "optgroup", "option", "p", "pre", "q",
"samp", "script", "select", "small", "span", "strong", "style",
"sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th",
"thead", "title", "tr", "tt", "ul", "var", "extends"];
this.inline_tags = ["br", "embed", "hr", "img", "input", "param"];
return this;
};
WYMeditor.XhtmlSaxListener.prototype.shouldCloseTagAutomatically = function(tag, now_on_tag, closing)
{
var closing = closing || false;
if(tag == 'td'){
if((closing && now_on_tag == 'tr') || (!closing && now_on_tag == 'td')){
return true;
}
}
if(tag == 'option'){
if((closing && now_on_tag == 'select') || (!closing && now_on_tag == 'option')){
return true;
}
}
return false;
};
WYMeditor.XhtmlSaxListener.prototype.beforeParsing = function(raw)
{
this.output = '';
return raw;
};
WYMeditor.XhtmlSaxListener.prototype.afterParsing = function(xhtml)
{
xhtml = this.replaceNamedEntities(xhtml);
xhtml = this.joinRepeatedEntities(xhtml);
xhtml = this.removeEmptyTags(xhtml);
return xhtml;
};
WYMeditor.XhtmlSaxListener.prototype.replaceNamedEntities = function(xhtml)
{
for (var entity in this.entities) {
xhtml = xhtml.replace(entity, this.entities[entity]);
}
return xhtml;
};
WYMeditor.XhtmlSaxListener.prototype.joinRepeatedEntities = function(xhtml)
{
var tags = 'em|strong|sub|sup|acronym|pre|del|address';
return xhtml.replace(new RegExp('<\/('+tags+')><\\1>' ,''),'').
replace(new RegExp('(\s*<('+tags+')>\s*){2}(.*)(\s*<\/\\2>\s*){2}' ,''),'<\$2>\$3<\$2>');
};
WYMeditor.XhtmlSaxListener.prototype.removeEmptyTags = function(xhtml)
{
return xhtml.replace(new RegExp('<('+this.block_tags.join("|").replace(/\|td/,'')+')>(<br \/>| | |\\s)*<\/\\1>' ,'g'),'');
};
WYMeditor.XhtmlSaxListener.prototype.getResult = function()
{
return this.output;
};
WYMeditor.XhtmlSaxListener.prototype.getTagReplacements = function()
{
return {'b':'strong', 'i':'em'};
};
WYMeditor.XhtmlSaxListener.prototype.addContent = function(text)
{
this.output += text;
};
WYMeditor.XhtmlSaxListener.prototype.addComment = function(text)
{
if(this.remove_comments){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.addScript = function(text)
{
if(!this.remove_scripts){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.addCss = function(text)
{
if(!this.remove_embeded_styles){
this.output += text;
}
};
WYMeditor.XhtmlSaxListener.prototype.openBlockTag = function(tag, attributes)
{
this.output += this.helper.tag(tag, this.validator.getValidTagAttributes(tag, attributes), true);
};
WYMeditor.XhtmlSaxListener.prototype.inlineTag = function(tag, attributes)
{
this.output += this.helper.tag(tag, this.validator.getValidTagAttributes(tag, attributes));
};
WYMeditor.XhtmlSaxListener.prototype.openUnknownTag = function(tag, attributes)
{
//this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.XhtmlSaxListener.prototype.closeBlockTag = function(tag)
{
this.output = this.output.replace(/<br \/>$/, '')+this._getClosingTagContent('before', tag)+"</"+tag+">"+this._getClosingTagContent('after', tag);
};
WYMeditor.XhtmlSaxListener.prototype.closeUnknownTag = function(tag)
{
//this.output += "</"+tag+">";
};
WYMeditor.XhtmlSaxListener.prototype.closeUnopenedTag = function(tag)
{
this.output += "</"+tag+">";
};
WYMeditor.XhtmlSaxListener.prototype.avoidStylingTagsAndAttributes = function()
{
this.avoided_tags = ['div','span'];
this.validator.skiped_attributes = ['style'];
this.validator.skiped_attribute_values = ['MsoNormal','main1']; // MS Word attributes for class
this._avoiding_tags_implicitly = true;
};
WYMeditor.XhtmlSaxListener.prototype.allowStylingTagsAndAttributes = function()
{
this.avoided_tags = [];
this.validator.skiped_attributes = [];
this.validator.skiped_attribute_values = [];
this._avoiding_tags_implicitly = false;
};
WYMeditor.XhtmlSaxListener.prototype.isBlockTag = function(tag)
{
return !WYMeditor.Helper.contains(this.avoided_tags, tag) && WYMeditor.Helper.contains(this.block_tags, tag);
};
WYMeditor.XhtmlSaxListener.prototype.isInlineTag = function(tag)
{
return !WYMeditor.Helper.contains(this.avoided_tags, tag) && WYMeditor.Helper.contains(this.inline_tags, tag);
};
WYMeditor.XhtmlSaxListener.prototype.insertContentAfterClosingTag = function(tag, content)
{
this._insertContentWhenClosingTag('after', tag, content);
};
WYMeditor.XhtmlSaxListener.prototype.insertContentBeforeClosingTag = function(tag, content)
{
this._insertContentWhenClosingTag('before', tag, content);
};
WYMeditor.XhtmlSaxListener.prototype.fixNestingBeforeOpeningBlockTag = function(tag, attributes)
{
if(tag != 'li' && (tag == 'ul' || tag == 'ol') && this.last_tag && !this.last_tag_opened && this.last_tag == 'li'){
this.output = this.output.replace(/<\/li>$/, '');
this.insertContentAfterClosingTag(tag, '</li>');
}
};
WYMeditor.XhtmlSaxListener.prototype._insertContentWhenClosingTag = function(position, tag, content)
{
if(!this['_insert_'+position+'_closing']){
this['_insert_'+position+'_closing'] = [];
}
if(!this['_insert_'+position+'_closing'][tag]){
this['_insert_'+position+'_closing'][tag] = [];
}
this['_insert_'+position+'_closing'][tag].push(content);
};
WYMeditor.XhtmlSaxListener.prototype._getClosingTagContent = function(position, tag)
{
if( this['_insert_'+position+'_closing'] &&
this['_insert_'+position+'_closing'][tag] &&
this['_insert_'+position+'_closing'][tag].length > 0){
return this['_insert_'+position+'_closing'][tag].pop();
}
return '';
};
/********** CSS PARSER **********/
WYMeditor.WymCssLexer = function(parser, only_wym_blocks)
{
var only_wym_blocks = (typeof only_wym_blocks == 'undefined' ? true : only_wym_blocks);
jQuery.extend(this, new WYMeditor.Lexer(parser, (only_wym_blocks?'Ignore':'WymCss')));
this.mapHandler('WymCss', 'Ignore');
if(only_wym_blocks == true){
this.addEntryPattern("/\\\x2a[<\\s]*WYMeditor[>\\s]*\\\x2a/", 'Ignore', 'WymCss');
this.addExitPattern("/\\\x2a[<\/\\s]*WYMeditor[>\\s]*\\\x2a/", 'WymCss');
}
this.addSpecialPattern("\\\x2e[a-z-_0-9]+[\\sa-z1-6]*", 'WymCss', 'WymCssStyleDeclaration');
this.addEntryPattern("/\\\x2a", 'WymCss', 'WymCssComment');
this.addExitPattern("\\\x2a/", 'WymCssComment');
this.addEntryPattern("\x7b", 'WymCss', 'WymCssStyle');
this.addExitPattern("\x7d", 'WymCssStyle');
this.addEntryPattern("/\\\x2a", 'WymCssStyle', 'WymCssFeddbackStyle');
this.addExitPattern("\\\x2a/", 'WymCssFeddbackStyle');
return this;
};
WYMeditor.WymCssParser = function()
{
this._in_style = false;
this._has_title = false;
this.only_wym_blocks = true;
this.css_settings = {'classesItems':[], 'editorStyles':[], 'dialogStyles':[]};
return this;
};
WYMeditor.WymCssParser.prototype.parse = function(raw, only_wym_blocks)
{
var only_wym_blocks = (typeof only_wym_blocks == 'undefined' ? this.only_wym_blocks : only_wym_blocks);
this._Lexer = new WYMeditor.WymCssLexer(this, only_wym_blocks);
this._Lexer.parse(raw);
};
WYMeditor.WymCssParser.prototype.Ignore = function(match, state)
{
return true;
};
WYMeditor.WymCssParser.prototype.WymCssComment = function(text, status)
{
if(text.match(/end[a-z0-9\s]*wym[a-z0-9\s]*/mi)){
return false;
}
if(status == WYMeditor.LEXER_UNMATCHED){
if(!this._in_style){
this._has_title = true;
this._current_item = {'title':WYMeditor.Helper.trim(text)};
}else{
if(this._current_item[this._current_element]){
if(!this._current_item[this._current_element].expressions){
this._current_item[this._current_element].expressions = [text];
}else{
this._current_item[this._current_element].expressions.push(text);
}
}
}
this._in_style = true;
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssStyle = function(match, status)
{
if(status == WYMeditor.LEXER_UNMATCHED){
match = WYMeditor.Helper.trim(match);
if(match != ''){
this._current_item[this._current_element].style = match;
}
}else if (status == WYMeditor.LEXER_EXIT){
this._in_style = false;
this._has_title = false;
this.addStyleSetting(this._current_item);
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssFeddbackStyle = function(match, status)
{
if(status == WYMeditor.LEXER_UNMATCHED){
this._current_item[this._current_element].feedback_style = match.replace(/^([\s\/\*]*)|([\s\/\*]*)$/gm,'');
}
return true;
};
WYMeditor.WymCssParser.prototype.WymCssStyleDeclaration = function(match)
{
match = match.replace(/^([\s\.]*)|([\s\.*]*)$/gm, '');
var tag = '';
if(match.indexOf(' ') > 0){
var parts = match.split(' ');
this._current_element = parts[0];
var tag = parts[1];
}else{
this._current_element = match;
}
if(!this._has_title){
this._current_item = {'title':(!tag?'':tag.toUpperCase()+': ')+this._current_element};
this._has_title = true;
}
if(!this._current_item[this._current_element]){
this._current_item[this._current_element] = {'name':this._current_element};
}
if(tag){
if(!this._current_item[this._current_element].tags){
this._current_item[this._current_element].tags = [tag];
}else{
this._current_item[this._current_element].tags.push(tag);
}
}
return true;
};
WYMeditor.WymCssParser.prototype.addStyleSetting = function(style_details)
{
for (var name in style_details){
var details = style_details[name];
if(typeof details == 'object' && name != 'title'){
this.css_settings.classesItems.push({
'name': WYMeditor.Helper.trim(details.name),
'title': style_details.title,
'expr' : WYMeditor.Helper.trim((details.expressions||details.tags).join(', '))
});
if(details.feedback_style){
this.css_settings.editorStyles.push({
'name': '.'+ WYMeditor.Helper.trim(details.name),
'css': details.feedback_style
});
}
if(details.style){
this.css_settings.dialogStyles.push({
'name': '.'+ WYMeditor.Helper.trim(details.name),
'css': details.style
});
}
}
}
};
/********** HELPERS **********/
// Returns true if it is a text node with whitespaces only
jQuery.fn.isPhantomNode = function() {
if (this[0].nodeType == 3)
return !(/[^\t\n\r ]/.test(this[0].data));
return false;
};
WYMeditor.isPhantomNode = function(n) {
if (n.nodeType == 3)
return !(/[^\t\n\r ]/.test(n.data));
return false;
};
WYMeditor.isPhantomString = function(str) {
return !(/[^\t\n\r ]/.test(str));
};
// Returns the Parents or the node itself
// jqexpr = a jQuery expression
jQuery.fn.parentsOrSelf = function(jqexpr) {
var n = this;
if (n[0].nodeType == 3)
n = n.parents().slice(0,1);
// if (n.is(jqexpr)) // XXX should work, but doesn't (probably a jQuery bug)
if (n.filter(jqexpr).size() == 1)
return n;
else
return n.parents(jqexpr).slice(0,1);
};
// String & array helpers
WYMeditor.Helper = {
//replace all instances of 'old' by 'rep' in 'str' string
replaceAll: function(str, old, rep) {
var rExp = new RegExp(old, "g");
return(str.replace(rExp, rep));
},
//insert 'inserted' at position 'pos' in 'str' string
insertAt: function(str, inserted, pos) {
return(str.substr(0,pos) + inserted + str.substring(pos));
},
//trim 'str' string
trim: function(str) {
return str.replace(/^(\s*)|(\s*)$/gm,'');
},
//return true if 'arr' array contains 'elem', or false
contains: function(arr, elem) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === elem) return true;
}
return false;
},
//return 'item' position in 'arr' array, or -1
indexOf: function(arr, item) {
var ret=-1;
for(var i = 0; i < arr.length; i++) {
if (arr[i] == item) {
ret = i;
break;
}
}
return(ret);
},
//return 'item' object in 'arr' array, checking its 'name' property, or null
findByName: function(arr, name) {
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(item.name == name) return(item);
}
return(null);
}
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.explorer.js
* MSIE specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
* Jonatan Lundin (jonatan.lundin _at_ gmail.com)
*/
WYMeditor.WymClassExplorer = function(wym) {
this._wym = wym;
this._class = "className";
this._newLine = "\r\n";
};
WYMeditor.WymClassExplorer.prototype.initIframe = function(iframe) {
//This function is executed twice, though it is called once!
//But MSIE needs that, otherwise designMode won't work.
//Weird.
this._iframe = iframe;
this._doc = iframe.contentWindow.document;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init html value
jQuery(this._doc.body).html(this._wym._html);
//handle events
var wym = this;
this._doc.body.onfocus = function()
{wym._doc.designMode = "on"; wym._doc = iframe.contentWindow.document;};
this._doc.onbeforedeactivate = function() {wym.saveCaret();};
this._doc.onkeyup = function() {
wym.saveCaret();
wym.keyup();
};
this._doc.onclick = function() {wym.saveCaret();};
this._doc.body.onbeforepaste = function() {
wym._iframe.contentWindow.event.returnValue = false;
};
this._doc.body.onpaste = function() {
wym._iframe.contentWindow.event.returnValue = false;
wym.paste(window.clipboardData.getData("Text"));
};
//callback can't be executed twice, so we check
if(this._initialized) {
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
}
this._initialized = true;
//init designMode
this._doc.designMode="on";
try{
// (bermi's note) noticed when running unit tests on IE6
// Is this really needed, it trigger an unexisting property on IE6
this._doc = iframe.contentWindow.document;
}catch(e){}
};
WYMeditor.WymClassExplorer.prototype._exec = function(cmd,param) {
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var container = this.findUp(this.container(), WYMeditor.LI);
if(container)
this._doc.execCommand(cmd);
break;
default:
if(param) this._doc.execCommand(cmd,false,param);
else this._doc.execCommand(cmd);
break;
}
this.listen();
};
WYMeditor.WymClassExplorer.prototype.selected = function() {
var caretPos = this._iframe.contentWindow.document.caretPos;
if(caretPos!=null) {
if(caretPos.parentElement!=undefined)
return(caretPos.parentElement());
}
};
WYMeditor.WymClassExplorer.prototype.saveCaret = function() {
this._doc.caretPos = this._doc.selection.createRange();
};
WYMeditor.WymClassExplorer.prototype.addCssRule = function(styles, oCss) {
styles.addRule(oCss.name, oCss.css);
};
WYMeditor.WymClassExplorer.prototype.insert = function(html) {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Overwrite selection with provided html
range.pasteHTML(html);
} catch (e) { }
} else {
// Fall back to the internal paste function if there's no selection
this.paste(html);
}
};
WYMeditor.WymClassExplorer.prototype.wrap = function(left, right) {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Overwrite selection with provided html
range.pasteHTML(left + range.text + right);
} catch (e) { }
}
};
WYMeditor.WymClassExplorer.prototype.unwrap = function() {
// Get the current selection
var range = this._doc.selection.createRange();
// Check if the current selection is inside the editor
if ( jQuery(range.parentElement()).parents( this._options.iframeBodySelector ).is('*') ) {
try {
// Unwrap selection
var text = range.text;
this._exec( 'Cut' );
range.pasteHTML( text );
} catch (e) { }
}
};
//keyup handler
WYMeditor.WymClassExplorer.prototype.keyup = function() {
this._selected_image = null;
};
WYMeditor.WymClassExplorer.prototype.setFocusToNode = function(node) {
try{
var range = this._doc.selection.createRange();
range.moveToElementText(node);
range.collapse(false);
range.move('character',-1);
range.select();
node.focus();
}
catch($e){this._iframe.contentWindow.focus()}
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.mozilla.js
* Gecko specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Volker Mische (vmx a-t gmx dotde)
* Bermi Ferrer (wymeditor a-t bermi dotorg)
* Frédéric Palluel-Lafleur (fpalluel a-t gmail dotcom)
*/
WYMeditor.WymClassMozilla = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\n";
};
WYMeditor.WymClassMozilla.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentDocument;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init html value
this.html(this._wym._html);
//init designMode
this.enableDesignMode();
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor keyup events
jQuery(this._doc).bind("keyup", this.keyup);
//bind editor focus events (used to reset designmode - Gecko bug)
jQuery(this._doc).bind("focus", this.enableDesignMode);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
/* @name html
* @description Get/Set the html value
*/
WYMeditor.WymClassMozilla.prototype.html = function(html) {
if(typeof html === 'string') {
//disable designMode
try { this._doc.designMode = "off"; } catch(e) { };
//replace em by i and strong by bold
//(designMode issue)
html = html.replace(/<em(\b[^>]*)>/gi, "<i$1>")
.replace(/<\/em>/gi, "</i>")
.replace(/<strong(\b[^>]*)>/gi, "<b$1>")
.replace(/<\/strong>/gi, "</b>");
//update the html body
jQuery(this._doc.body).html(html);
//re-init designMode
this.enableDesignMode();
}
else return(jQuery(this._doc.body).html());
};
WYMeditor.WymClassMozilla.prototype._exec = function(cmd,param) {
if(!this.selected()) return(false);
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var focusNode = this.selected();
var sel = this._iframe.contentWindow.getSelection();
var anchorNode = sel.anchorNode;
if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
if(focusNode && focusNode == anchorNode && focusNode.tagName.toLowerCase() == WYMeditor.LI) {
var ancestor = focusNode.parentNode.parentNode;
if(focusNode.parentNode.childNodes.length>1
|| ancestor.tagName.toLowerCase() == WYMeditor.OL
|| ancestor.tagName.toLowerCase() == WYMeditor.UL)
this._doc.execCommand(cmd,'',null);
}
break;
default:
if(param) this._doc.execCommand(cmd,'',param);
else this._doc.execCommand(cmd,'',null);
}
//set to P if parent = BODY
var container = this.selected();
if(container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
//add event handlers on doc elements
this.listen();
};
/* @name selected
* @description Returns the selected container
*/
WYMeditor.WymClassMozilla.prototype.selected = function(upgrade_text_nodes) {
if (upgrade_text_nodes == null || upgrade_text_nodes.toString() != "true") { upgrade_text_nodes = false; }
var sel = this._iframe.contentWindow.getSelection();
var node = sel.focusNode;
if(node) {
if(node.nodeName == "#text"){
if (upgrade_text_nodes && sel.toString().length > 0) {
actual_node = null;
parent_node = sel.focusNode.parentNode;
if (parent_node != null) {
for (i=0;i<parent_node.childNodes.length;i++){
child_node = parent_node.childNodes[i];
if (child_node.nodeName != "#text" && child_node.innerHTML == sel.toString()){
actual_node = child_node;
}
}
}
if (actual_node == null) {
return this.switchTo(sel, 'span');
} else {
return actual_node;
}
}
else {
return node.parentNode;
}
}
else return(node);
}
else return(null);
};
WYMeditor.WymClassMozilla.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}", styles.cssRules.length);
};
//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
if(evt.ctrlKey){
if(evt.keyCode == 66){
//CTRL+b => STRONG
wym._exec(WYMeditor.BOLD);
return false;
}
if(evt.keyCode == 73){
//CTRL+i => EMPHASIS
wym._exec(WYMeditor.ITALIC);
return false;
}
}
};
//keyup handler, mainly used for cleanups
WYMeditor.WymClassMozilla.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
var container = null;
if(evt.keyCode == 13 && !evt.shiftKey) {
//RETURN key
//cleanup <br><br> between paragraphs
jQuery(wym._doc.body).children(WYMeditor.BR).remove();
//fix PRE bug #73
container = wym.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
}
else if(evt.keyCode != 8
&& evt.keyCode != 17
&& evt.keyCode != 46
&& evt.keyCode != 224
&& !evt.metaKey
&& !evt.ctrlKey) {
//NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
//text nodes replaced by P
container = wym.selected();
var name = container.tagName.toLowerCase();
//fix forbidden main containers
if(
name == "strong" ||
name == "b" ||
name == "em" ||
name == "i" ||
name == "sub" ||
name == "sup" ||
name == "a"
) name = container.parentNode.tagName.toLowerCase();
if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
}
};
WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
if(this.designMode == "off") {
try {
this.designMode = "on";
this.execCommand("styleWithCSS", '', false);
} catch(e) { }
}
};
WYMeditor.WymClassMozilla.prototype.setFocusToNode = function(node) {
var range = document.createRange();
range.selectNode(node);
var selected = this._iframe.contentWindow.getSelection();
selected.addRange(range);
selected.collapse(node, node.childNodes.length);
this._iframe.contentWindow.focus();
};
WYMeditor.WymClassMozilla.prototype.openBlockTag = function(tag, attributes)
{
var attributes = this.validator.getValidTagAttributes(tag, attributes);
// Handle Mozilla styled spans
if(tag == 'span' && attributes.style){
var new_tag = this.getTagForStyle(attributes.style);
if(new_tag){
this._tag_stack.pop();
var tag = new_tag;
this._tag_stack.push(new_tag);
attributes.style = '';
}else{
return;
}
}
this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.WymClassMozilla.prototype.getTagForStyle = function(style) {
if(/bold/.test(style)) return 'strong';
if(/italic/.test(style)) return 'em';
if(/sub/.test(style)) return 'sub';
if(/sub/.test(style)) return 'super';
return false;
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.opera.js
* Opera specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
*/
WYMeditor.WymClassOpera = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\r\n";
};
WYMeditor.WymClassOpera.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentWindow.document;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init designMode
this._doc.designMode = "on";
//init html value
this.html(this._wym._html);
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor events
jQuery(this._doc).bind("keyup", this.keyup);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
WYMeditor.WymClassOpera.prototype._exec = function(cmd,param) {
if(param) this._doc.execCommand(cmd,false,param);
else this._doc.execCommand(cmd);
this.listen();
};
WYMeditor.WymClassOpera.prototype.selected = function() {
var sel=this._iframe.contentWindow.getSelection();
var node=sel.focusNode;
if(node) {
if(node.nodeName=="#text")return(node.parentNode);
else return(node);
} else return(null);
};
WYMeditor.WymClassOpera.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}",
styles.cssRules.length);
};
//keydown handler
WYMeditor.WymClassOpera.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
var sel = wym._iframe.contentWindow.getSelection();
startNode = sel.getRangeAt(0).startContainer;
//Get a P instead of no container
if(!jQuery(startNode).parentsOrSelf(
WYMeditor.MAIN_CONTAINERS.join(","))[0]
&& !jQuery(startNode).parentsOrSelf('li')
&& evt.keyCode != WYMeditor.KEY.ENTER
&& evt.keyCode != WYMeditor.KEY.LEFT
&& evt.keyCode != WYMeditor.KEY.UP
&& evt.keyCode != WYMeditor.KEY.RIGHT
&& evt.keyCode != WYMeditor.KEY.DOWN
&& evt.keyCode != WYMeditor.KEY.BACKSPACE
&& evt.keyCode != WYMeditor.KEY.DELETE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
};
//keyup handler
WYMeditor.WymClassOpera.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
};
// TODO: implement me
WYMeditor.WymClassOpera.prototype.setFocusToNode = function(node) {
};
/*
* WYMeditor : what you see is What You Mean web-based editor
* Copyright (c) 2008 Jean-Francois Hovinne, http://www.wymeditor.org/
* Dual licensed under the MIT (MIT-license.txt)
* and GPL (GPL-license.txt) licenses.
*
* For further information visit:
* http://www.wymeditor.org/
*
* File Name:
* jquery.wymeditor.safari.js
* Safari specific class and functions.
* See the documentation for more info.
*
* File Authors:
* Jean-Francois Hovinne (jf.hovinne a-t wymeditor dotorg)
* Scott Lewis (lewiscot a-t gmail dotcom)
*/
WYMeditor.WymClassSafari = function(wym) {
this._wym = wym;
this._class = "class";
this._newLine = "\n";
};
WYMeditor.WymClassSafari.prototype.initIframe = function(iframe) {
this._iframe = iframe;
this._doc = iframe.contentDocument;
//add css rules from options
var styles = this._doc.styleSheets[0];
var aCss = eval(this._options.editorStyles);
this.addCssRules(this._doc, aCss);
this._doc.title = this._wym._index;
//set the text direction
jQuery('html', this._doc).attr('dir', this._options.direction);
//init designMode
this._doc.designMode = "on";
//init html value
this.html(this._wym._html);
//pre-bind functions
if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
//bind external events
this._wym.bindEvents();
//bind editor keydown events
jQuery(this._doc).bind("keydown", this.keydown);
//bind editor keyup events
jQuery(this._doc).bind("keyup", this.keyup);
//post-init functions
if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
//add event listeners to doc elements, e.g. images
this.listen();
};
WYMeditor.WymClassSafari.prototype._exec = function(cmd,param) {
if(!this.selected()) return(false);
switch(cmd) {
case WYMeditor.INDENT: case WYMeditor.OUTDENT:
var focusNode = this.selected();
var sel = this._iframe.contentWindow.getSelection();
var anchorNode = sel.anchorNode;
if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
if(focusNode && focusNode == anchorNode
&& focusNode.tagName.toLowerCase() == WYMeditor.LI) {
var ancestor = focusNode.parentNode.parentNode;
if(focusNode.parentNode.childNodes.length>1
|| ancestor.tagName.toLowerCase() == WYMeditor.OL
|| ancestor.tagName.toLowerCase() == WYMeditor.UL)
this._doc.execCommand(cmd,'',null);
}
break;
case WYMeditor.INSERT_ORDEREDLIST: case WYMeditor.INSERT_UNORDEREDLIST:
this._doc.execCommand(cmd,'',null);
//Safari creates lists in e.g. paragraphs.
//Find the container, and remove it.
var focusNode = this.selected();
var container = this.findUp(focusNode, WYMeditor.MAIN_CONTAINERS);
if(container) jQuery(container).replaceWith(jQuery(container).html());
break;
default:
if(param) this._doc.execCommand(cmd,'',param);
else this._doc.execCommand(cmd,'',null);
}
//set to P if parent = BODY
var container = this.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.BODY)
this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
//add event handlers on doc elements
this.listen();
};
/* @name selected
* @description Returns the selected container
*/
WYMeditor.WymClassSafari.prototype.selected = function(upgrade_text_nodes) {
if (upgrade_text_nodes == null || upgrade_text_nodes.toString() != "true") { upgrade_text_nodes = false; }
var sel = this._iframe.contentWindow.getSelection();
var node = sel.focusNode;
if(node) {
if(node.nodeName == "#text"){
if (upgrade_text_nodes && sel.toString().length > 0) {
actual_node = null;
parent_node = sel.focusNode.parentNode;
if (parent_node != null) {
for (i=0;i<parent_node.childNodes.length;i++){
child_node = parent_node.childNodes[i];
if (child_node.textContent == sel.toString()){
actual_node = child_node.parentNode;
}
}
}
if (actual_node == null) {
this._selected_item = this.switchTo(sel, 'span');
return this._selected_item;
} else {
return actual_node;
}
}
else {
return node.parentNode;
}
}
else return(node);
}
else return(null);
};
/* @name toggleClass
* @description Toggles class on selected element, or one of its parents
*/
WYMeditor.WymClassSafari.prototype.toggleClass = function(sClass, jqexpr) {
var container = null;
if (this._selected_image) {
container = jQuery(this._selected_image);
}
else {
container = jQuery(this.selected(true) || this._selected_item);
}
if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
container.toggleClass(sClass);
if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
};
WYMeditor.WymClassSafari.prototype.addCssRule = function(styles, oCss) {
styles.insertRule(oCss.name + " {" + oCss.css + "}",
styles.cssRules.length);
};
//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassSafari.prototype.keydown = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
if(evt.ctrlKey){
if(evt.keyCode == 66){
//CTRL+b => STRONG
wym._exec(WYMeditor.BOLD);
return false;
}
if(evt.keyCode == 73){
//CTRL+i => EMPHASIS
wym._exec(WYMeditor.ITALIC);
return false;
}
}
};
//keyup handler, mainly used for cleanups
WYMeditor.WymClassSafari.prototype.keyup = function(evt) {
//'this' is the doc
var wym = WYMeditor.INSTANCES[this.title];
wym._selected_image = null;
var container = null;
if(evt.keyCode == 13 && !evt.shiftKey) {
//RETURN key
//cleanup <br><br> between paragraphs
jQuery(wym._doc.body).children(WYMeditor.BR).remove();
//fix PRE bug #73
container = wym.selected();
if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
}
//fix #112
if(evt.keyCode == 13 && evt.shiftKey) {
wym._exec('InsertLineBreak');
}
if(evt.keyCode != 8
&& evt.keyCode != 17
&& evt.keyCode != 46
&& evt.keyCode != 224
&& !evt.metaKey
&& !evt.ctrlKey) {
//NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
//text nodes replaced by P
container = wym.selected();
var name = container.tagName.toLowerCase();
//fix forbidden main containers
if(
name == "strong" ||
name == "b" ||
name == "em" ||
name == "i" ||
name == "sub" ||
name == "sup" ||
name == "a" ||
name == "span" //fix #110
) name = container.parentNode.tagName.toLowerCase();
if(name == WYMeditor.BODY || name == WYMeditor.DIV) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //fix #110 for DIV
}
};
//TODO
WYMeditor.WymClassSafari.prototype.setFocusToNode = function(node) {
/*var range = document.createRange();
range.selectNode(node);
var selected = this._iframe.contentWindow.getSelection();
selected.addRange(range);
selected.collapse(node, node.childNodes.length);
this._iframe.contentWindow.focus();*/
};
WYMeditor.WymClassSafari.prototype.openBlockTag = function(tag, attributes)
{
var attributes = this.validator.getValidTagAttributes(tag, attributes);
// Handle Safari styled spans
if(tag == 'span' && attributes.style) {
var new_tag = this.getTagForStyle(attributes.style);
if(new_tag){
this._tag_stack.pop();
var tag = new_tag;
this._tag_stack.push(new_tag);
attributes.style = '';
//should fix #125 - also removed the xhtml() override
if(typeof attributes['class'] == 'string')
attributes['class'] = attributes['class'].replace(/apple-style-span/gi, '');
} else {
return;
}
}
this.output += this.helper.tag(tag, attributes, true);
};
WYMeditor.WymClassSafari.prototype.getTagForStyle = function(style) {
if(/bold/.test(style)) return 'strong';
if(/italic/.test(style)) return 'em';
if(/sub/.test(style)) return 'sub';
if(/super/.test(style)) return 'sup';
return false;
};
function titleize(words) {
parts = [];
words.gsub(/\./, '').gsub(/[-_]/, ' ').split(' ').each(function(part){
parts.push(part[0].toUpperCase() + part.substring(1));
});
return parts.join(" ");
} | Support onpaste for firefox and make it format a block if content is pasted like it does already on keyup
| public/javascripts/wymeditor/jquery.refinery.wymeditor.js | Support onpaste for firefox and make it format a block if content is pasted like it does already on keyup | <ide><path>ublic/javascripts/wymeditor/jquery.refinery.wymeditor.js
<ide> TOGGLE_HTML : "ToggleHtml",
<ide> FORMAT_BLOCK : "FormatBlock",
<ide> PREVIEW : "Preview",
<del>
<add>
<ide> UNLINK : "Unlink",
<ide> INSERT_UNORDEREDLIST : "InsertUnorderedList",
<ide> INSERT_ORDEREDLIST : "InsertOrderedList",
<ide> ATTRIBUTE: 2,
<ide> TEXT: 3
<ide> },
<del>
<add>
<ide> /*
<ide> Class: WYMeditor.editor
<ide> WYMeditor editor main class, instanciated for each editor occurrence.
<ide> * }
<ide> * );
<ide> * @desc Example description here
<del> *
<add> *
<ide> * @name WYMeditor
<ide> * @description WYMeditor is a web-based WYSIWYM XHTML editor
<ide> * @param Hash hash A hash of parameters
<ide> options = jQuery.extend({
<ide>
<ide> html: "",
<del>
<add>
<ide> basePath: false,
<del>
<add>
<ide> skinPath: false,
<ide> jsSkinPath: false,
<ide> cssSkinPath: false,
<del>
<add>
<ide> wymPath: false,
<del>
<add>
<ide> iframeBasePath: false,
<del>
<add>
<ide> jQueryPath: false,
<del>
<add>
<ide> styles: false,
<del>
<add>
<ide> stylesheet: false,
<del>
<add>
<ide> skin: "default",
<ide> initSkin: true,
<ide> loadSkin: true,
<ide> direction: "ltr",
<ide>
<ide> boxHtml: "<div class='wym_box'>"
<del> + "<div class='wym_area_top'>"
<add> + "<div class='wym_area_top'>"
<ide> + WYMeditor.TOOLS
<ide> + "</div>"
<ide> + "<div class='wym_area_left'></div>"
<ide> + WYMeditor.INDEX + "].initIframe(this)'"
<ide> + "></iframe>"
<ide> + "</div>",
<del>
<add>
<ide> editorStyles: [],
<ide>
<ide> toolsHtml: "<div class='wym_tools wym_section'>"
<ide> + WYMeditor.TOOLS_ITEMS
<ide> + "</ul>"
<ide> + "</div>",
<del>
<add>
<ide> toolsItemHtml: "<li class='"
<ide> + WYMeditor.TOOL_CLASS
<ide> + "'><a href='#' name='"
<ide> + "</a></li>",
<ide>
<ide> toolsItems: [
<del> {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'},
<add> {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'},
<ide> {'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
<ide> {'name': 'Superscript', 'title': 'Superscript',
<ide> 'css': 'wym_tools_superscript'},
<ide> + WYMeditor.CONTAINERS_ITEMS
<ide> + "</ul>"
<ide> + "</div>",
<del>
<add>
<ide> containersItemHtml:"<li class='"
<ide> + WYMeditor.CONTAINER_CLASS
<ide> + "'>"
<ide> + "'>"
<ide> + WYMeditor.CONTAINER_TITLE
<ide> + "</a></li>",
<del>
<add>
<ide> containersItems: [
<ide> {'name': 'P', 'title': 'Paragraph', 'css': 'wym_containers_p'},
<ide> {'name': 'H1', 'title': 'Heading_1', 'css': 'wym_containers_h1'},
<ide> classUnhiddenSelector: ".wym_classes",
<ide> classHiddenSelector: ".wym_classes_hidden",
<ide> htmlValSelector: ".wym_html_val",
<del>
<add>
<ide> hrefSelector: ".wym_href",
<ide> srcSelector: ".wym_src",
<ide> titleSelector: ".wym_title",
<ide> targetSelector: ".wym_target",
<ide> altSelector: ".wym_alt",
<ide> textSelector: ".wym_text",
<del>
<add>
<ide> rowsSelector: ".wym_rows",
<ide> colsSelector: ".wym_cols",
<ide> captionSelector: ".wym_caption",
<ide> summarySelector: ".wym_summary",
<del>
<add>
<ide> submitSelector: ".wym_submit",
<ide> cancelSelector: ".wym_cancel",
<ide> previewSelector: "",
<del>
<add>
<ide> dialogTypeSelector: ".wym_dialog_type",
<ide> dialogLinkSelector: ".wym_dialog_link",
<ide> dialogImageSelector: ".wym_dialog_image",
<ide> dialogTableSelector: ".wym_dialog_table",
<ide> dialogPasteSelector: ".wym_dialog_paste",
<ide> dialogPreviewSelector: ".wym_dialog_preview",
<del>
<add>
<ide> updateSelector: ".wymupdate",
<ide> updateEvent: "click",
<del>
<add>
<ide> dialogFeatures: "menubar=no,titlebar=no,toolbar=no,resizable=no"
<ide> + ",width=560,height=300,top=0,left=0",
<ide>
<ide> + "</head>"
<ide> + WYMeditor.DIALOG_BODY
<ide> + "</html>",
<del>
<add>
<ide> dialogLinkHtml: "<div class='wym_dialog wym_dialog_link'>"
<ide> + "<form>"
<ide> + "<fieldset>"
<ide> + "</fieldset>"
<ide> + "</form>"
<ide> + "</div>",
<del>
<add>
<ide> dialogImageHtml: "<div class='wym_dialog wym_dialog_image'>"
<ide> + "<form>"
<ide> + "<fieldset>"
<ide> + "</fieldset>"
<ide> + "</form>"
<ide> + "</div>",
<del>
<add>
<ide> dialogTableHtml: "<div class='wym_dialog wym_dialog_table'>"
<ide> + "<form>"
<ide> + "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"
<ide> + "</div>",
<ide>
<ide> dialogPreviewHtml: "<div class='wym_dialog wym_dialog_preview'></div>",
<del>
<add>
<ide> dialogStyles: [],
<ide>
<ide> stringDelimiterLeft: "{",
<ide> stringDelimiterRight:"}",
<del>
<add>
<ide> preInit: null,
<ide> preBind: null,
<ide> postInit: null,
<del>
<add>
<ide> preInitDialog: null,
<ide> postInitDialog: null
<ide>
<ide> else if (jQuery.browser.safari) {
<ide> var WymClass = new WYMeditor.WymClassSafari(this);
<ide> }
<del>
<add>
<ide> if(WymClass) {
<del>
<add>
<ide> if(jQuery.isFunction(this._options.preInit)) this._options.preInit(this);
<ide>
<ide> var SaxListener = new WYMeditor.XhtmlSaxListener();
<ide> jQuery.extend(SaxListener, WymClass);
<ide> this.parser = new WYMeditor.XhtmlParser(SaxListener);
<del>
<add>
<ide> if(this._options.styles || this._options.stylesheet){
<ide> this.configureEditorUsingRawCss();
<ide> }
<del>
<add>
<ide> this.helper = new WYMeditor.XmlHelper();
<del>
<add>
<ide> //extend the Wymeditor object
<ide> //don't use jQuery.extend since 1.1.4
<ide> //jQuery.extend(this, WymClass);
<ide> //but keep it compatible with jQuery < 1.2.3, see #122
<ide> if( jQuery.isFunction( jQuery.fn.data ) )
<ide> jQuery.data(this._box.get(0), WYMeditor.WYM_INDEX, this._index);
<del>
<add>
<ide> var h = WYMeditor.Helper;
<ide>
<ide> //construct the iframe
<ide> var iframeHtml = this._options.iframeHtml;
<ide> iframeHtml = h.replaceAll(iframeHtml, WYMeditor.INDEX, this._index);
<ide> iframeHtml = h.replaceAll(iframeHtml, WYMeditor.IFRAME_BASE_PATH, this._options.iframeBasePath);
<del>
<add>
<ide> //construct wymbox
<ide> var boxHtml = jQuery(this._box).html();
<del>
<add>
<ide> boxHtml = h.replaceAll(boxHtml, WYMeditor.LOGO, this._options.logoHtml);
<ide> boxHtml = h.replaceAll(boxHtml, WYMeditor.TOOLS, this._options.toolsHtml);
<ide> boxHtml = h.replaceAll(boxHtml, WYMeditor.CONTAINERS,this._options.containersHtml);
<ide> boxHtml = h.replaceAll(boxHtml, WYMeditor.HTML, this._options.htmlHtml);
<ide> boxHtml = h.replaceAll(boxHtml, WYMeditor.IFRAME, iframeHtml);
<ide> boxHtml = h.replaceAll(boxHtml, WYMeditor.STATUS, this._options.statusHtml);
<del>
<add>
<ide> //construct tools list
<ide> var aTools = eval(this._options.toolsItems);
<ide> var sTools = "";
<ide> //construct classes list
<ide> var aClasses = eval(this._options.classesItems);
<ide> var sClasses = "";
<del>
<add>
<ide> for(var i = 0; i < aClasses.length; i++) {
<ide> var oClass = aClasses[i];
<ide> if(oClass.name) {
<ide> sClass = h.replaceAll(sClass, WYMeditor.CLASS_TITLE, rule.title || titleize(rule));
<ide> sRules += sClass;
<ide> }.bind(this)); // need to bind 'this' or else it will think 'this' is the window.
<del>
<add>
<ide> var sClassMultiple = this._options.classesItemHtmlMultiple;
<ide> sClassMultiple = h.replaceAll(sClassMultiple, WYMeditor.CLASS_TITLE, oClass.title || titleize(oClass.name));
<ide> sClassMultiple = h.replaceAll(sClassMultiple, '{classesItemHtml}', sRules);
<ide> }
<ide>
<ide> boxHtml = h.replaceAll(boxHtml, WYMeditor.CLASSES_ITEMS, sClasses);
<del>
<add>
<ide> //construct containers list
<ide> var aContainers = eval(this._options.containersItems);
<ide> var sContainers = "";
<ide>
<ide> //l10n
<ide> boxHtml = this.replaceStrings(boxHtml);
<del>
<add>
<ide> //load html in wymbox
<ide> jQuery(this._box).html(boxHtml);
<del>
<add>
<ide> //hide the html value
<ide> jQuery(this._box).find(this._options.htmlSelector).hide();
<del>
<add>
<ide> //enable the skin
<ide> this.loadSkin();
<del>
<add>
<ide> }
<ide> };
<ide>
<ide>
<ide> //copy the instance
<ide> var wym = this;
<del>
<add>
<ide> //handle click event on tools buttons
<ide> jQuery(this._box).find(this._options.toolSelector).click(function() {
<ide> wym.exec(jQuery(this).attr(WYMeditor.NAME));
<ide> return(false);
<ide> });
<del>
<add>
<ide> //handle click event on containers buttons
<ide> jQuery(this._box).find(this._options.containerSelector).click(function() {
<ide> wym.container(jQuery(this).attr(WYMeditor.NAME));
<ide> return(false);
<ide> });
<del>
<add>
<ide> //handle keyup event on html value: set the editor value
<ide> jQuery(this._box).find(this._options.htmlValSelector).keyup(function() {
<ide> jQuery(wym._doc.body).html(jQuery(this).val());
<ide> replacers.push(classRule.name + (classRule.join || "") + classRule.rules[i]);
<ide> }
<ide> }
<del>
<add>
<ide> oClass = {expr: (classRule.rules[indexOf].expr || null)}
<ide> }
<ide> }
<ide> }.bind(this));
<ide> }
<del>
<add>
<ide> if(oClass) {
<ide> var jqexpr = oClass.expr;
<ide> // remove all related classes.
<ide> replacers.each(function(removable_class){
<ide> wym.removeClass(removable_class, jqexpr);
<ide> });
<del>
<add>
<ide> wym.toggleClass(sName, jqexpr);
<ide> }
<del>
<add>
<ide> // now hide the menu
<ide> wym.exec(WYMeditor.APPLY_CLASS);
<del>
<add>
<ide> return(false);
<ide> });
<del>
<add>
<ide> //handle event on update element
<ide> jQuery(this._options.updateSelector).bind(this._options.updateEvent, function() {
<ide> wym.update();
<ide> * @description Executes a button command
<ide> */
<ide> WYMeditor.editor.prototype.exec = function(cmd) {
<del>
<add>
<ide> //base function for execCommand
<ide> //open a dialog or exec
<ide> switch(cmd) {
<ide> var container = this.container();
<ide> if(container || this._selected_image) this.dialog(WYMeditor.DIALOG_LINK);
<ide> break;
<del>
<add>
<ide> case WYMeditor.INSERT_IMAGE:
<ide> this.dialog(WYMeditor.DIALOG_IMAGE);
<ide> break;
<del>
<add>
<ide> case WYMeditor.INSERT_TABLE:
<ide> this.dialog(WYMeditor.DIALOG_TABLE);
<ide> break;
<del>
<add>
<ide> case WYMeditor.PASTE:
<ide> this.dialog(WYMeditor.DIALOG_PASTE);
<ide> break;
<del>
<add>
<ide> case WYMeditor.TOGGLE_HTML:
<ide> this.update();
<ide> this.toggleHtml();
<ide> if(!jQuery(this._box).find(this._options.htmlSelector).is(':visible'))
<ide> this.listen();
<ide> break;
<del>
<add>
<ide> case WYMeditor.PREVIEW:
<ide> this.dialog(WYMeditor.PREVIEW);
<ide> break;
<del>
<add>
<ide> case WYMeditor.APPLY_CLASS:
<ide> jQuery(this._box).find(this._options.classUnhiddenSelector).toggleClass(this._options.classHiddenSelector.substring(1)); // substring(1) to remove the . at the start
<ide> jQuery(this._box).find("a[name=" + WYMeditor.APPLY_CLASS +"]").toggleClass('selected');
<ide> //this.dialog(WYMeditor.DIALOG_CLASS);
<ide> break;
<del>
<add>
<ide> default:
<ide> this._exec(cmd);
<ide> break;
<ide> WYMeditor.editor.prototype.container = function(sType) {
<ide>
<ide> if(sType) {
<del>
<add>
<ide> var container = null;
<del>
<add>
<ide> if(sType.toLowerCase() == WYMeditor.TH) {
<del>
<add>
<ide> container = this.container();
<del>
<add>
<ide> //find the TD or TH container
<ide> switch(container.tagName.toLowerCase()) {
<del>
<add>
<ide> case WYMeditor.TD: case WYMeditor.TH:
<ide> break;
<ide> default:
<ide> container = this.findUp(this.container(), aTypes);
<ide> break;
<ide> }
<del>
<add>
<ide> //if it exists, switch
<ide> if(container!=null) {
<del>
<add>
<ide> sType = (container.tagName.toLowerCase() == WYMeditor.TD)? WYMeditor.TH: WYMeditor.TD;
<ide> this.switchTo(container,sType);
<ide> this.update();
<ide> }
<ide> } else {
<del>
<add>
<ide> //set the container type
<ide> var aTypes=new Array(WYMeditor.P,WYMeditor.H1,WYMeditor.H2,WYMeditor.H3,WYMeditor.H4,WYMeditor.H5,
<ide> WYMeditor.H6,WYMeditor.PRE,WYMeditor.BLOCKQUOTE);
<ide>
<ide> container = this.findUp(this.container(), aTypes);
<del>
<add>
<ide> if(container) {
<del>
<add>
<ide> var newNode = null;
<del>
<add>
<ide> //blockquotes must contain a block level element
<ide> if(sType.toLowerCase() == WYMeditor.BLOCKQUOTE) {
<del>
<add>
<ide> var blockquote = this.findUp(this.container(), WYMeditor.BLOCKQUOTE);
<del>
<add>
<ide> if(blockquote == null) {
<del>
<add>
<ide> newNode = this._doc.createElement(sType);
<ide> container.parentNode.insertBefore(newNode,container);
<ide> newNode.appendChild(container);
<ide> this.setFocusToNode(newNode.firstChild);
<del>
<add>
<ide> } else {
<del>
<add>
<ide> var nodes = blockquote.childNodes;
<ide> var lgt = nodes.length;
<ide> var firstNode = null;
<del>
<add>
<ide> if(lgt > 0) firstNode = nodes.item(0);
<ide> for(var x=0; x<lgt; x++) {
<ide> blockquote.parentNode.insertBefore(nodes.item(0),blockquote);
<ide> if(firstNode) this.setFocusToNode(firstNode);
<ide> }
<ide> }
<del>
<add>
<ide> else this.switchTo(container,sType);
<del>
<add>
<ide> this.update();
<ide> }
<ide> }
<ide> * @description Toggles class on selected element, or one of its parents
<ide> */
<ide> WYMeditor.editor.prototype.toggleClass = function(sClass, jqexpr) {
<del>
<add>
<ide> var container = jQuery((this._selected_image ? this._selected_image : this.selected(true)));
<ide> if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
<ide> container.toggleClass(sClass);
<ide> * @description Removes class on selected element, or one of its parents
<ide> */
<ide> WYMeditor.editor.prototype.removeClass = function(sClass, jqexpr) {
<del>
<add>
<ide> var container = jQuery((this._selected_image ? this._selected_image : jQuery(this.selected(true))));
<ide> if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
<ide> container.removeClass(sClass);
<ide>
<ide> if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
<del>
<add>
<ide> }
<ide>
<ide> /* @name findUp
<ide> if(node) {
<ide>
<ide> var tagname = node.tagName.toLowerCase();
<del>
<add>
<ide> if(typeof(filter) == WYMeditor.STRING) {
<del>
<add>
<ide> while(tagname != filter && tagname != WYMeditor.BODY) {
<del>
<add>
<ide> node = node.parentNode;
<ide> tagname = node.tagName.toLowerCase();
<ide> }
<del>
<add>
<ide> } else {
<del>
<add>
<ide> var bFound = false;
<del>
<add>
<ide> while(!bFound && tagname != WYMeditor.BODY) {
<ide> for(var i = 0; i < filter.length; i++) {
<ide> if(tagname == filter[i]) {
<ide> }
<ide> }
<ide> }
<del>
<add>
<ide> if(tagname != WYMeditor.BODY) return(node);
<ide> else return(null);
<del>
<add>
<ide> } else return(null);
<ide> };
<ide>
<ide> if (selectionOrNode.getRangeAt) {
<ide> // We have a selection object so we need to create a temporary node around it (bold is easy). This node will be replaced anyway.
<ide> this.exec(WYMeditor.BOLD);
<del> selectionOrNode = selectionOrNode.focusNode.parentNode;
<del> }
<del>
<add> selectionOrNode = selectionOrNode.focusNode.parentNode;
<add> }
<add>
<ide> // we have a node.
<ide> var html = jQuery(selectionOrNode).html();
<ide> var newNode = this._doc.createElement(sType);
<ide> selectionOrNode.parentNode.replaceChild(newNode,selectionOrNode);
<del>
<add>
<ide> jQuery(newNode).html(html);
<ide> this.setFocusToNode(newNode);
<del>
<add>
<ide> return newNode;
<ide> };
<ide>
<ide>
<ide> //replace all the strings in sVal and return it
<ide> for (var key in WYMeditor.STRINGS[this._options.lang]) {
<del> sVal = WYMeditor.Helper.replaceAll(sVal, this._options.stringDelimiterLeft + key
<add> sVal = WYMeditor.Helper.replaceAll(sVal, this._options.stringDelimiterLeft + key
<ide> + this._options.stringDelimiterRight,
<ide> WYMeditor.STRINGS[this._options.lang][key]);
<ide> };
<ide> // change undo or redo on cancel to true to have this happen when a user closes (cancels) a dialogue
<ide> this._undo_on_cancel = false;
<ide> this._redo_on_cancel = false;
<del>
<add>
<ide> //set to P if parent = BODY
<ide> if (![WYMeditor.DIALOG_TABLE, WYMeditor.DIALOG_PASTE].include(dialogType))
<ide> {
<ide> // somehow select the wymeditor textarea or simulate a click or a keydown on it.
<ide> }
<ide> }
<del>
<add>
<ide> selected = this.selected();
<ide> if (dialogType == WYMeditor.DIALOG_LINK && jQuery.browser.mozilla) {
<ide> selection = this._iframe.contentWindow.getSelection();
<ide> // set up handlers.
<ide> imageGroup = null;
<ide> ajax_loaded_callback = function(){this.dialog_ajax_callback(selected)}.bind(this, selected);
<del>
<add>
<ide> var parent_node = null;
<ide> if (this._selected_image) {
<ide> parent_node = this._selected_image.parentNode;
<ide> parent_node._id_before_replaceable = parent.id;
<ide> parent_node.id = 'replace_me_with_' + this._current_unique_stamp;
<ide> }
<del>
<add>
<ide> path += (this._wym._options.dialogFeatures.length == 0) ? "?" : "&"
<ide> port = (window.location.port.length > 0 ? (":" + window.location.port) : "")
<ide> path += "current_link=" + parent_node.href.gsub(window.location.protocol + "//" + window.location.hostname + port, "");
<ide> };
<ide>
<ide> WYMeditor.editor.prototype.dialog_ajax_callback = function(selected) {
<del>
<add>
<ide> // look for iframes
<ide> if ((iframes = $(this._options.dialogId).select('iframe')).length > 0 && (iframe = $(iframes[0])) != null)
<ide> {
<ide> console.log('pasting..');
<ide> var sTmp;
<ide> var container = this.selected();
<del>
<add>
<ide> //split the data, using double newlines as the separator
<ide> var aP = sData.split(this._newLine + this._newLine);
<ide> var rExp = new RegExp(this._newLine, "g");
<ide> sTmp = sTmp.replace(rExp, "<br />");
<ide> jQuery(this._doc.body).append("<p>" + sTmp + "</p>");
<ide> }
<del>
<add>
<ide> }
<ide> };
<ide>
<ide> //don't use jQuery.find() on the iframe body
<ide> //because of MSIE + jQuery + expando issue (#JQ1143)
<ide> //jQuery(this._doc.body).find("*").bind("mouseup", this.mouseup);
<del>
<add>
<ide> jQuery(this._doc.body).bind("mousedown", this.mousedown);
<ide> var images = this._doc.body.getElementsByTagName("img");
<ide> for(var i=0; i < images.length; i++) {
<ide> };
<ide>
<ide> WYMeditor.editor.prototype.mousedown = function(evt) {
<del>
<add>
<ide> var wym = WYMeditor.INSTANCES[this.ownerDocument.title];
<ide> wym._selected_image = (this.tagName.toLowerCase() == WYMeditor.IMG) ? this : null;
<ide> evt.stopPropagation();
<ide> * href - The CSS path.
<ide> */
<ide> WYMeditor.loadCss = function(href) {
<del>
<add>
<ide> var link = document.createElement('link');
<ide> link.rel = 'stylesheet';
<ide> link.href = href;
<ide> button.observe('click', function(e){this.close_dialog(e, true)}.bind(wym));
<ide> });
<ide> /*
<del> switch(dialogType) {
<add> switch(dialogType) {
<ide> case WYMeditor.DIALOG_LINK:
<ide> //ensure that we select the link to populate the fields
<ide> if (replaceable[0] != null && replaceable[0].tagName.toLowerCase() == WYMeditor.A)
<ide> .val(jQuery(wym._selected_image).attr(WYMeditor.ALT));
<ide> }
<ide>
<del> jQuery(wym._options.dialogLinkSelector + " " + wym._options.submitSelector).click(function()
<add> jQuery(wym._options.dialogLinkSelector + " " + wym._options.submitSelector).click(function()
<ide> {
<ide> var sUrl = jQuery(wym._options.hrefSelector).val();
<del> if(sUrl.length > 0)
<add> if(sUrl.length > 0)
<ide> {
<ide> if (replaceable[0] != null) {
<ide> link = wym._doc.createElement("a");
<ide> jQuery("a[href=" + wym._current_unique_stamp + "]", wym._doc.body)
<ide> .attr(WYMeditor.HREF, sUrl)
<ide> .attr(WYMeditor.TITLE, jQuery(wym._options.titleSelector).val())
<del> .attr(WYMeditor.TARGET, jQuery(wym._options.targetSelector).val());
<add> .attr(WYMeditor.TARGET, jQuery(wym._options.targetSelector).val());
<ide> }
<ide> }
<ide> // fire a click event on the dialogs close button
<ide> //var image = jQuery(wym._doc.body).find("img[@src=" + sStamp + "]");
<ide> var image = null;
<ide> var nodes = wym._doc.body.getElementsByTagName(WYMeditor.IMG);
<del> for(var i=0; i < nodes.length; i++)
<add> for(var i=0; i < nodes.length; i++)
<ide> {
<del> if(jQuery(nodes[i]).attr(WYMeditor.SRC) == wym._current_unique_stamp)
<add> if(jQuery(nodes[i]).attr(WYMeditor.SRC) == wym._current_unique_stamp)
<ide> {
<ide> image = jQuery(nodes[i]);
<ide> break;
<ide> }
<ide> }
<del>
<add>
<ide> if(image) {
<ide> image.attr(WYMeditor.SRC, sUrl);
<ide> image.attr(WYMeditor.TITLE, sTitle);
<ide> image.attr(WYMeditor.ALT, sAlt);
<del>
<add>
<ide> if (!jQuery.browser.safari)
<ide> {
<ide> if (replaceable != null)
<ide> }
<ide> }
<ide> }
<del>
<add>
<ide> // fire a click event on the dialogs close button
<ide> wym.close_dialog();
<ide> }
<ide> var iRows = jQuery(wym._options.rowsSelector).val();
<ide> var iCols = jQuery(wym._options.colsSelector).val();
<ide>
<del> if(iRows > 0 && iCols > 0)
<add> if(iRows > 0 && iCols > 0)
<ide> {
<ide> var table = wym._doc.createElement(WYMeditor.TABLE);
<ide> var newRow = null;
<ide> replaceable[0].id = replaceable[0]._id_before_replaceable;
<ide> }
<ide> }
<del>
<add>
<ide> if (this._undo_on_cancel == true) {
<ide> this._exec("undo");
<ide> }
<ide> this._exec("redo");
<ide> }
<ide> }
<del>
<add>
<ide> if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8)
<ide> {
<ide> this._iframe.contentWindow.focus();
<ide> }
<del>
<add>
<ide> if ((inline_dialog_container = $('inline_dialog_container')) != null)
<ide> {
<ide> inline_dialog_container.remove();
<ide> }
<del>
<add>
<ide> tb_remove();
<del>
<add>
<ide> if (e) {
<ide> e.stop();
<ide> }
<ide> //This function is executed twice, though it is called once!
<ide> //But MSIE needs that, otherwise designMode won't work.
<ide> //Weird.
<del>
<add>
<ide> this._iframe = iframe;
<ide> this._doc = iframe.contentWindow.document;
<del>
<add>
<ide> //add css rules from options
<ide> var styles = this._doc.styleSheets[0];
<ide> var aCss = eval(this._options.editorStyles);
<ide>
<ide> //set the text direction
<ide> jQuery('html', this._doc).attr('dir', this._options.direction);
<del>
<add>
<ide> //init html value
<ide> jQuery(this._doc.body).html(this._wym._html);
<del>
<add>
<ide> //handle events
<ide> var wym = this;
<del>
<add>
<ide> this._doc.body.onfocus = function()
<ide> {wym._doc.designMode = "on"; wym._doc = iframe.contentWindow.document;};
<ide> this._doc.onbeforedeactivate = function() {wym.saveCaret();};
<ide> wym.keyup();
<ide> };
<ide> this._doc.onclick = function() {wym.saveCaret();};
<del>
<add>
<ide> this._doc.body.onbeforepaste = function() {
<ide> wym._iframe.contentWindow.event.returnValue = false;
<ide> };
<del>
<add>
<ide> this._doc.body.onpaste = function() {
<ide> wym._iframe.contentWindow.event.returnValue = false;
<ide> wym.paste(window.clipboardData.getData("Text"));
<ide> };
<del>
<add>
<ide> //callback can't be executed twice, so we check
<ide> if(this._initialized) {
<del>
<add>
<ide> //pre-bind functions
<ide> if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
<del>
<add>
<ide> //bind external events
<ide> this._wym.bindEvents();
<del>
<add>
<ide> //post-init functions
<ide> if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
<del>
<add>
<ide> //add event listeners to doc elements, e.g. images
<ide> this.listen();
<ide> }
<del>
<add>
<ide> this._initialized = true;
<del>
<add>
<ide> //init designMode
<ide> this._doc.designMode="on";
<ide> try{
<ide> // (bermi's note) noticed when running unit tests on IE6
<ide> // Is this really needed, it trigger an unexisting property on IE6
<del> this._doc = iframe.contentWindow.document;
<add> this._doc = iframe.contentWindow.document;
<ide> }catch(e){}
<ide> };
<ide>
<ide> WYMeditor.WymClassExplorer.prototype._exec = function(cmd,param) {
<ide>
<ide> switch(cmd) {
<del>
<add>
<ide> case WYMeditor.INDENT: case WYMeditor.OUTDENT:
<del>
<add>
<ide> var container = this.findUp(this.container(), WYMeditor.LI);
<ide> if(container)
<ide> this._doc.execCommand(cmd);
<ide> else this._doc.execCommand(cmd);
<ide> break;
<ide> }
<del>
<add>
<ide> this.listen();
<ide> };
<ide>
<ide>
<ide> this._iframe = iframe;
<ide> this._doc = iframe.contentDocument;
<del>
<add>
<ide> //add css rules from options
<del>
<del> var styles = this._doc.styleSheets[0];
<add>
<add> var styles = this._doc.styleSheets[0];
<ide> var aCss = eval(this._options.editorStyles);
<del>
<add>
<ide> this.addCssRules(this._doc, aCss);
<ide>
<ide> this._doc.title = this._wym._index;
<ide>
<ide> //set the text direction
<ide> jQuery('html', this._doc).attr('dir', this._options.direction);
<del>
<add>
<ide> //init html value
<ide> this.html(this._wym._html);
<del>
<add>
<ide> //init designMode
<ide> this.enableDesignMode();
<del>
<add>
<ide> //pre-bind functions
<ide> if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
<del>
<add>
<ide> //bind external events
<ide> this._wym.bindEvents();
<del>
<add>
<ide> //bind editor keydown events
<ide> jQuery(this._doc).bind("keydown", this.keydown);
<del>
<add>
<ide> //bind editor keyup events
<ide> jQuery(this._doc).bind("keyup", this.keyup);
<del>
<add>
<add> //bind editor paste events
<add> jQuery(this._doc).bind("paste", this.paste);
<add>
<ide> //bind editor focus events (used to reset designmode - Gecko bug)
<ide> jQuery(this._doc).bind("focus", this.enableDesignMode);
<del>
<add>
<ide> //post-init functions
<ide> if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
<del>
<add>
<ide> //add event listeners to doc elements, e.g. images
<ide> this.listen();
<ide> };
<ide> WYMeditor.WymClassMozilla.prototype.html = function(html) {
<ide>
<ide> if(typeof html === 'string') {
<del>
<add>
<ide> //disable designMode
<ide> try { this._doc.designMode = "off"; } catch(e) { };
<del>
<add>
<ide> //replace em by i and strong by bold
<ide> //(designMode issue)
<ide> html = html.replace(/<em(\b[^>]*)>/gi, "<i$1>")
<ide> .replace(/<\/em>/gi, "</i>")
<ide> .replace(/<strong(\b[^>]*)>/gi, "<b$1>")
<ide> .replace(/<\/strong>/gi, "</b>");
<del>
<add>
<ide> //update the html body
<ide> jQuery(this._doc.body).html(html);
<del>
<add>
<ide> //re-init designMode
<ide> this.enableDesignMode();
<ide> }
<ide> if(!this.selected()) return(false);
<ide>
<ide> switch(cmd) {
<del>
<add>
<ide> case WYMeditor.INDENT: case WYMeditor.OUTDENT:
<del> var focusNode = this.selected();
<add> var focusNode = this.selected();
<ide> var sel = this._iframe.contentWindow.getSelection();
<ide> var anchorNode = sel.anchorNode;
<ide> if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
<ide> this._doc.execCommand(cmd,'',null);
<ide> }
<ide> break;
<del>
<add>
<ide> default:
<ide> if(param) this._doc.execCommand(cmd,'',param);
<ide> else this._doc.execCommand(cmd,'',null);
<ide> }
<del>
<add>
<ide> //set to P if parent = BODY
<ide> var container = this.selected();
<ide> if(container.tagName.toLowerCase() == WYMeditor.BODY)
<ide> this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
<del>
<add>
<ide> //add event handlers on doc elements
<ide>
<ide> this.listen();
<ide> * @description Returns the selected container
<ide> */
<ide> WYMeditor.WymClassMozilla.prototype.selected = function(upgrade_text_nodes) {
<del>
<add>
<ide> if (upgrade_text_nodes == null || upgrade_text_nodes.toString() != "true") { upgrade_text_nodes = false; }
<ide> var sel = this._iframe.contentWindow.getSelection();
<ide> var node = sel.focusNode;
<ide> }
<ide> }
<ide> else return(node);
<del> }
<add> }
<ide> else return(null);
<ide> };
<ide>
<ide>
<ide> //keydown handler, mainly used for keyboard shortcuts
<ide> WYMeditor.WymClassMozilla.prototype.keydown = function(evt) {
<del>
<add>
<ide> //'this' is the doc
<ide> var wym = WYMeditor.INSTANCES[this.title];
<del>
<add>
<ide> if(evt.ctrlKey){
<ide> if(evt.keyCode == 66){
<ide> //CTRL+b => STRONG
<ide>
<ide> //'this' is the doc
<ide> var wym = WYMeditor.INSTANCES[this.title];
<del>
<add>
<ide> wym._selected_image = null;
<ide> var container = null;
<ide>
<ide> if(evt.keyCode == 13 && !evt.shiftKey) {
<del>
<add>
<ide> //RETURN key
<ide> //cleanup <br><br> between paragraphs
<ide> jQuery(wym._doc.body).children(WYMeditor.BR).remove();
<del>
<add>
<ide> //fix PRE bug #73
<ide> container = wym.selected();
<ide> if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
<ide> wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
<ide> }
<del>
<add>
<ide> else if(evt.keyCode != 8
<ide> && evt.keyCode != 17
<ide> && evt.keyCode != 46
<ide> && !evt.ctrlKey) {
<ide> //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
<ide> //text nodes replaced by P
<del>
<del> container = wym.selected();
<del> var name = container.tagName.toLowerCase();
<del>
<del> //fix forbidden main containers
<del> if(
<del> name == "strong" ||
<del> name == "b" ||
<del> name == "em" ||
<del> name == "i" ||
<del> name == "sub" ||
<del> name == "sup" ||
<del> name == "a"
<del>
<del> ) name = container.parentNode.tagName.toLowerCase();
<del>
<del> if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
<del> }
<del>};
<add>
<add> wym.format_block();
<add> }
<add>};
<add>
<add>WYMeditor.WymClassMozilla.prototype.paste = function(evt) {
<add>
<add> var wym = WYMeditor.INSTANCES[this.title];
<add>
<add> wym.format_block();
<add>
<add>};
<add>
<add>WYMeditor.WymClassMozilla.prototype.format_block = function(selected) {
<add>
<add> //'this' should be the wymeditor instance.
<add> var wym = this;
<add>
<add> selected = selected || wym.selected();
<add>
<add> wym._selected_image = null;
<add> var container = null;
<add>
<add> container = wym.selected();
<add> var name = container.tagName.toLowerCase();
<add>
<add> //fix forbidden main containers
<add> if(
<add> name == "strong" ||
<add> name == "b" ||
<add> name == "em" ||
<add> name == "i" ||
<add> name == "sub" ||
<add> name == "sup" ||
<add> name == "a"
<add>
<add> ) name = container.parentNode.tagName.toLowerCase();
<add>
<add> if(name == WYMeditor.BODY) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);
<add>}
<ide>
<ide> WYMeditor.WymClassMozilla.prototype.enableDesignMode = function() {
<ide> if(this.designMode == "off") {
<ide> return;
<ide> }
<ide> }
<del>
<add>
<ide> this.output += this.helper.tag(tag, attributes, true);
<ide> };
<ide>
<ide>
<ide> this._iframe = iframe;
<ide> this._doc = iframe.contentWindow.document;
<del>
<add>
<ide> //add css rules from options
<del> var styles = this._doc.styleSheets[0];
<add> var styles = this._doc.styleSheets[0];
<ide> var aCss = eval(this._options.editorStyles);
<ide>
<ide> this.addCssRules(this._doc, aCss);
<ide>
<ide> //set the text direction
<ide> jQuery('html', this._doc).attr('dir', this._options.direction);
<del>
<add>
<ide> //init designMode
<ide> this._doc.designMode = "on";
<ide>
<ide> //init html value
<ide> this.html(this._wym._html);
<del>
<add>
<ide> //pre-bind functions
<ide> if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
<del>
<add>
<ide> //bind external events
<ide> this._wym.bindEvents();
<del>
<add>
<ide> //bind editor keydown events
<ide> jQuery(this._doc).bind("keydown", this.keydown);
<del>
<add>
<ide> //bind editor events
<ide> jQuery(this._doc).bind("keyup", this.keyup);
<del>
<add>
<ide> //post-init functions
<ide> if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
<del>
<add>
<ide> //add event listeners to doc elements, e.g. images
<ide> this.listen();
<ide> };
<ide>
<ide> if(param) this._doc.execCommand(cmd,false,param);
<ide> else this._doc.execCommand(cmd);
<del>
<add>
<ide> this.listen();
<ide> };
<ide>
<ide>
<ide> //keydown handler
<ide> WYMeditor.WymClassOpera.prototype.keydown = function(evt) {
<del>
<add>
<ide> //'this' is the doc
<ide> var wym = WYMeditor.INSTANCES[this.title];
<ide> var sel = wym._iframe.contentWindow.getSelection();
<ide>
<ide> this._iframe = iframe;
<ide> this._doc = iframe.contentDocument;
<del>
<add>
<ide> //add css rules from options
<del>
<del> var styles = this._doc.styleSheets[0];
<add>
<add> var styles = this._doc.styleSheets[0];
<ide> var aCss = eval(this._options.editorStyles);
<del>
<add>
<ide> this.addCssRules(this._doc, aCss);
<ide>
<ide> this._doc.title = this._wym._index;
<ide>
<ide> //init designMode
<ide> this._doc.designMode = "on";
<del>
<add>
<ide> //init html value
<ide> this.html(this._wym._html);
<del>
<add>
<ide> //pre-bind functions
<ide> if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);
<del>
<add>
<ide> //bind external events
<ide> this._wym.bindEvents();
<del>
<add>
<ide> //bind editor keydown events
<ide> jQuery(this._doc).bind("keydown", this.keydown);
<del>
<add>
<ide> //bind editor keyup events
<ide> jQuery(this._doc).bind("keyup", this.keyup);
<del>
<add>
<ide> //post-init functions
<ide> if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);
<del>
<add>
<ide> //add event listeners to doc elements, e.g. images
<ide> this.listen();
<ide> };
<ide> if(!this.selected()) return(false);
<ide>
<ide> switch(cmd) {
<del>
<add>
<ide> case WYMeditor.INDENT: case WYMeditor.OUTDENT:
<del>
<del> var focusNode = this.selected();
<add>
<add> var focusNode = this.selected();
<ide> var sel = this._iframe.contentWindow.getSelection();
<ide> var anchorNode = sel.anchorNode;
<ide> if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;
<del>
<add>
<ide> focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
<ide> anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);
<del>
<add>
<ide> if(focusNode && focusNode == anchorNode
<ide> && focusNode.tagName.toLowerCase() == WYMeditor.LI) {
<ide>
<ide> if(container) jQuery(container).replaceWith(jQuery(container).html());
<ide>
<ide> break;
<del>
<add>
<ide> default:
<ide>
<ide> if(param) this._doc.execCommand(cmd,'',param);
<ide> else this._doc.execCommand(cmd,'',null);
<ide> }
<del>
<add>
<ide> //set to P if parent = BODY
<ide> var container = this.selected();
<ide> if(container && container.tagName.toLowerCase() == WYMeditor.BODY)
<ide> }
<ide> }
<ide> else return(node);
<del> }
<add> }
<ide> else return(null);
<ide> };
<ide>
<ide> * @description Toggles class on selected element, or one of its parents
<ide> */
<ide> WYMeditor.WymClassSafari.prototype.toggleClass = function(sClass, jqexpr) {
<del>
<add>
<ide> var container = null;
<ide> if (this._selected_image) {
<ide> container = jQuery(this._selected_image);
<ide> else {
<ide> container = jQuery(this.selected(true) || this._selected_item);
<ide> }
<del>
<add>
<ide> if (jqexpr != null) { container = jQuery(container.parentsOrSelf(jqexpr)); }
<ide> container.toggleClass(sClass);
<ide> if(!container.attr(WYMeditor.CLASS)) container.removeAttr(this._class);
<ide>
<ide> //keydown handler, mainly used for keyboard shortcuts
<ide> WYMeditor.WymClassSafari.prototype.keydown = function(evt) {
<del>
<add>
<ide> //'this' is the doc
<ide> var wym = WYMeditor.INSTANCES[this.title];
<del>
<add>
<ide> if(evt.ctrlKey){
<ide> if(evt.keyCode == 66){
<ide> //CTRL+b => STRONG
<ide>
<ide> //'this' is the doc
<ide> var wym = WYMeditor.INSTANCES[this.title];
<del>
<add>
<ide> wym._selected_image = null;
<ide> var container = null;
<ide>
<ide> if(evt.keyCode == 13 && !evt.shiftKey) {
<del>
<add>
<ide> //RETURN key
<ide> //cleanup <br><br> between paragraphs
<ide> jQuery(wym._doc.body).children(WYMeditor.BR).remove();
<del>
<add>
<ide> //fix PRE bug #73
<ide> container = wym.selected();
<ide> if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
<ide> if(evt.keyCode == 13 && evt.shiftKey) {
<ide> wym._exec('InsertLineBreak');
<ide> }
<del>
<add>
<ide> if(evt.keyCode != 8
<ide> && evt.keyCode != 17
<ide> && evt.keyCode != 46
<ide> && evt.keyCode != 224
<ide> && !evt.metaKey
<ide> && !evt.ctrlKey) {
<del>
<add>
<ide> //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
<ide> //text nodes replaced by P
<del>
<add>
<ide> container = wym.selected();
<ide> var name = container.tagName.toLowerCase();
<ide>
<ide> var tag = new_tag;
<ide> this._tag_stack.push(new_tag);
<ide> attributes.style = '';
<del>
<add>
<ide> //should fix #125 - also removed the xhtml() override
<ide> if(typeof attributes['class'] == 'string')
<ide> attributes['class'] = attributes['class'].replace(/apple-style-span/gi, '');
<del>
<add>
<ide> } else {
<ide> return;
<ide> }
<ide> }
<del>
<add>
<ide> this.output += this.helper.tag(tag, attributes, true);
<ide> };
<ide>
<ide> };
<ide>
<ide> function titleize(words) {
<del> parts = [];
<add> parts = [];
<ide> words.gsub(/\./, '').gsub(/[-_]/, ' ').split(' ').each(function(part){
<ide> parts.push(part[0].toUpperCase() + part.substring(1));
<del> });
<del>
<add> });
<add>
<ide> return parts.join(" ");
<ide> } |
|
JavaScript | apache-2.0 | 2ccf73eec1e617d2e867eabfe3b5c6e180eb247c | 0 | EchoAppsTeam/EchoConversations | (function($) {
"use strict";
/**
* @class Echo.StreamServer.Controls.Stream.Plugins.CardUIShim
* Extends Stream control to look like Card-based app.
*/
var plugin = Echo.Plugin.manifest("CardUIShim", "Echo.StreamServer.Controls.Stream");
plugin.config = {
"displayEmptyStream": true
};
plugin.init = function() {
// Stream should trigger 'onActivitiesComplete' event to start items liveUpdate animation
this.component._executeNextActivity = function() {
var acts = this.activities;
if (!acts.queue.length && this.config.get("state.layout") === "full") {
acts.state = "paused";
}
if (!acts.queue.length) {
this.events.publish({
"topic": "onActivitiesComplete"
});
}
if (acts.animations > 0 || !this.itemsRenderingComplete ||
!acts.queue.length ||
this.config.get("liveUpdates.enabled") &&
acts.state === "paused" &&
acts.queue[0].action !== "replace" &&
!acts.queue[0].byCurrentUser) {
return;
}
acts.queue.shift().handler();
};
// disable 'fade' animation
this.component._spotUpdates.animate.fade = function(item) {
this.activities.animations--;
this._executeNextActivity();
};
};
plugin.component.renderers.header = function(element) {
return element.hide();
};
plugin.component.renderers.container = function(element) {
var items = $.grep(this.component.get("threads"), function(item) {
return !item.deleted;
});
return (items.length || this.config.get("displayEmptyStream"))
? element.show()
: element.hide();
};
plugin.css =
'.{plugin.cass} .{class:more} { border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{plugin.cass} .{class:messageText} { border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{plugin.class:caption} { line-height: 18px; }' +
'.{plugin.class} .{class:header} { padding: 5px 0px 5px 0px; margin: 0px; font-size: 14px; }' +
'.{plugin.class} .{class:body} .echo-control-message { margin: 0px 0px 10px; border: 1px solid #d2d2d2; box-shadow: 0px 1px 1px #d2d2d2; border-radius: 3px; color: #c6c6c6; padding: 30px 0px 30px 0px; text-align: left;}' +
'.{plugin.class} .{class:body} .echo-control-message .echo-control-message-info { height: 35px; display: block; font-size: 14px; line-height: 16px; font-weight: normal; font-style: normal; background-image: url({%= baseURL %}/images/info.png); padding-left: 40px; width: 180px; margin: 0px auto; }' +
'.{plugin.class} .echo-control-message-info { background: url({%= baseURL %}/images/info.png) no-repeat; }' +
'.{plugin.class} .{class:item} { margin: 0px 0px 10px 0px; padding: 0px; border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; background: #ffffff; }' +
'.{plugin.class} .{class:item-children} .{class:item} { margin: 0px; padding: 0px; box-shadow: 0 0 0; border: 0px; background: #f8f8f8; }';
Echo.Plugin.create(plugin);
})(Echo.jQuery);
(function($) {
"use strict";
/**
* @class Echo.StreamServer.Controls.Stream.Item.Plugins.CardUIShim
* Extends Item control to look like Card-based app.
*/
var plugin = Echo.Plugin.manifest("CardUIShim", "Echo.StreamServer.Controls.Stream.Item");
plugin.events = {
"Echo.StreamServer.Controls.Stream.onActivitiesComplete": function() {
var self = this;
var container = this.component.view.get("container");
if (this.get("isLiveUpdate") && container) {
var fade = function() {
if ($.inviewport(container, {"threshold": 0})) {
self.set("isLiveUpdate", false);
if (self._transitionSupported()) {
container.removeClass(self.cssPrefix + "liveUpdate");
} else {
setTimeout(function() {
// IE 8-9 doesn't support transition, so we just remove the highlighting.
// Maybe we should use jquery.animate (animating colors requires jQuery UI) ?
container.removeClass(self.cssPrefix + "liveUpdate");
}, self.config.get("fadeTimeout"));
}
$(document).off("scroll", fade).off("resize", fade);
return true;
} else {
return false;
}
};
if (!fade()) {
$(document).on("scroll", fade).on("resize", fade);
}
}
}
};
plugin.labels = {
"topPostIndicatorTitle": "Top Post"
};
plugin.config = {
"fadeTimeout": 10000, // 10 seconds
"displayTopPostHighlight": true
};
plugin.init = function() {
this.set("isLiveUpdate", this.component.config.get("live"));
this.extendTemplate("replace", "header", plugin.templates.header);
this.extendTemplate("insertBefore", "frame", plugin.templates.topPostMarker);
this.extendTemplate("insertAfter", "authorName", plugin.templates.date);
this.extendTemplate("insertAsLastChild", "expandChildren", plugin.templates.chevron);
this.extendTemplate("remove", "date");
};
plugin.templates.date =
'<div class="{plugin.class:date}"></div>';
plugin.templates.wrapper =
'<div class="{plugin.class:wrapper}"></div>';
plugin.templates.chevron =
'<span class="{plugin.class:chevron} icon-chevron-down"></span>';
plugin.templates.button =
'<a class="{class:button} {class:button}-{data:name}">' +
'<i class="{plugin.class:buttonIcon} {data:icon}"></i>' +
'<span class="echo-primaryFont {class:buttonCaption}">{data:label}</span>' +
'</a>';
plugin.templates.topPostMarker =
'<i class="icon-bookmark {plugin.class:topPostMarker}" title="{plugin.label:topPostIndicatorTitle}"></i>';
plugin.renderers.topPostMarker = function(element) {
var item = this.component;
var itemMarkers = item.get("data.object.markers", []);
var visible = !!this.config.get("displayTopPostHighlight") &&
!item.get("depth") &&
~$.inArray("Conversations.TopPost", itemMarkers);
return visible
? element.show()
: element.hide();
};
plugin.renderers.date = function(element) {
// TODO: use parentRenderer here
this.age = this.component.getRelativeTime(this.component.timestamp);
return element.html(this.age);
};
plugin.component.renderers.tags = function(element) {
return element.hide();
};
plugin.component.renderers.markers = function(element) {
return element.hide();
};
plugin.component.renderers.container = function(element) {
if (this.get("isLiveUpdate")) {
element.addClass(this.cssPrefix + "liveUpdate");
var transition = "border-left " + this.config.get("fadeTimeout") + "ms linear";
element.css({
"transition": transition,
"-o-transition": transition,
"-ms-transition": transition,
"-moz-transition": transition,
"-webkit-transition": transition
});
}
element = this.parentRenderer("container", arguments);
return this.component.view.rendered()
? element
: element.wrap(this.substitute({
"template": plugin.templates.wrapper
}));
};
plugin.component.renderers._button = function(element, extra) {
var template = extra.template || plugin.templates.button;
var data = {
"label": extra.label || "",
"name": extra.name,
"icon": extra.icon || "icon-comment"
};
var button = $(this.substitute({"template": template, "data": data}));
if (!extra.clickable) return element.append(button);
var clickables = $(".echo-clickable", button);
if (extra.element) {
button.find("span").empty().append(extra.element);
}
if (!clickables.length) {
clickables = button;
button.addClass("echo-clickable");
}
clickables[extra.once ? "one" : "on"]({
"click": function(event) {
event.stopPropagation();
if (extra.callback) extra.callback();
}
});
var _data = this.component.get("buttons." + extra.plugin + "." + extra.name);
_data.element = button;
_data.clickableElements = clickables;
if (Echo.Utils.isMobileDevice()) {
clickables.addClass("echo-linkColor");
}
return element.append(button);
};
var cache = {};
plugin.methods._transitionSupported = function() {
if (!cache.transitionSupported) {
var s = document.createElement('p').style;
cache.transitionSupported = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
}
return cache.transitionSupported;
};
var itemDepthRules = [];
// 100 is a maximum level of children in query, but we can apply styles for ~20
for (var i = 0; i <= 20; i++) {
itemDepthRules.push('.{plugin.class} .{class:depth}-' + i + ' { margin-left: 0px; padding-left: ' + (i ? 8 + (i - 1) * 39 : 16) + 'px; }');
}
plugin.css =
'.{plugin.class:topPostMarker} { float: right; position: relative; top: -19px; right: 0px; }' +
'.{plugin.class} .{plugin.class:wrapper} { background: #ffffff; border-bottom: 1px solid #e5e5e5; border-radius: 3px 3px 0px 0px; }' +
'.{plugin.class} .{class:container} { border-left: 8px solid transparent; background: #ffffff; }' +
'.{plugin.class} .{class:container}.{class:depth-0} { border-radius: 2px 3px 0px 0px; }' +
'.{plugin.class} .{class:container}.{plugin.class:liveUpdate} { border-left: 8px solid #f5ba47; }' +
'.{plugin.class} .echo-trinaryBackgroundColor { background-color: #f8f8f8; }' +
'.{plugin.class:date} { float: left; color: #d3d3d3; margin-left: 5px; line-height: 18px; }' +
'.{plugin.class} .{class:blocker-backdrop} { background-color: transparent; }' +
'.{plugin.class} .{class:avatar} { height: 28px; width: 28px; margin-left: 3px; }' +
'.{plugin.class} .{class:avatar} img { height: 28px; width: 28px; border-radius: 50%;}' +
'.{plugin.class} .{class:content} { background: #f8f8f8; border-radius: 3px; }' +
'.{plugin.class} .{class:buttons} { margin-left: 0px; white-space: nowrap; }' +
'.{plugin.class} .{class:metadata} { margin-bottom: 8px; }' +
'.{plugin.class} .{class:body} { padding-top: 0px; margin-bottom: 8px; }' +
'.{plugin.class} .{class:body} .{class:text} { color: #42474A; font-size: 15px; line-height: 21px; }' +
'.{plugin.class} .{class:authorName} { color: #595959; font-weight: normal; font-size: 14px; line-height: 16px; }' +
'.{plugin.class} .{class:children} .{class:avatar-wrapper} { margin-top: 5px; }' +
'.{plugin.class} .{class:children} .{class:frame} { margin-left: 5px; }' +
'.{plugin.class} .{class:children} .{class:data} { margin-top: 2px; padding-top: 0px; }' +
'.{plugin.class} .{class:children} .{plugin.class:wrapper} { padding-top: 0px; background: none; border: none; }' +
'.{plugin.class} .{class:container-child} { padding: 20px 0px 0px 16px; margin: 0px 15px 2px 0px; }' +
'.{plugin.class} .{class:content} .{class:container-child-thread} { padding: 20px 0px 0px 8px; margin: 0px 15px 2px 0px; }' +
'.{plugin.class} .{class:button} { margin-right: 10px; }' +
'.{plugin.class} .{class:button-delim} { display: none; }' +
'.echo-sdk-ui .{plugin.class:buttonIcon}[class*=" icon-"] { margin-right: 4px; margin-top: 0px; }' +
'.{plugin.class} .{plugin.class:buttonIcon} { opacity: 0.3; }' +
'.{plugin.class} .{class:buttonCaption} { vertical-align: middle; font-size: 12px; }' +
'.{plugin.class} .{class:buttons} a.{class:button}.echo-linkColor, .{class:buttons} a.{class:button}:hover { color: #262626; text-decoration: none; }' +
'.{plugin.class} .{class:buttons} a.{class:button}.echo-linkColor .{plugin.class:buttonIcon},' +
'.{class:buttons} a.{class:button}:hover .{plugin.class:buttonIcon} { opacity: 0.8; }' +
'.{plugin.class} .{class:depth-0} .{plugin.class:date} { line-height: 40px; }' +
'.{plugin.class} .{plugin.class:chevron} { margin-top: 0px !important; }' +
'.{plugin.class} .{class:expandChildrenLabel} { margin-right: 5px; }' +
'.{plugin.class} .{class:expandChildren} .{class:expandChildrenLabel} { color: #D3D3D3; }' +
'.{plugin.class} .{class:expandChildren}:hover .{class:expandChildrenLabel} { color: #262626; }' +
'.{plugin.class} .{class:expandChildren} .{plugin.class:chevron} { opacity: 0.3; }' +
'.{plugin.class} .{class:expandChildren}:hover .{plugin.class:chevron} { opacity: 0.8; }' +
'.{plugin.class} .{class:expandChildren} .echo-message-icon { padding-left: 0px; background: none; }' +
'.{plugin.class} .{class:expandChildren} .{class:message-loading} { background: none; }' +
'.{plugin.class} .{class:depth-0} .{class:footer} { padding: 8px 0px 10px; }' +
'.{plugin.class} .{class:depth-0} .{class:body} { padding-top: 0px; }' +
'.{plugin.class} .{class:depth-0} .{class:avatar} { height: 36px; width: 36px; }' +
'.{plugin.class} .{class:depth-0} .{class:avatar} img { height: 36px; width: 36px; border-radius: 50%;}' +
'.{plugin.class} .{class:depth-0} .{class:authorName} { font-weight: normal; font-size: 17px; line-height: 38px; margin-left: 45px;}' +
'.{plugin.class} .{class:depth-0} .{class:subwrapper} { margin-left: 0px; }' +
'.{plugin.class} .{class:depth-0} .{class:childrenMarker} { display: none; }' +
'.{plugin.class} .{class:data} { padding: 7px 0px 0px 0px; }' +
'.{plugin.class} .{class:content} .{class:depth-0} { padding: 15px 16px 0px 8px; }' +
itemDepthRules.join("\n");
Echo.Plugin.create(plugin);
})(Echo.jQuery);
(function($) {
"use strict";
/**
* @class Echo.StreamServer.Controls.Submit.Plugins.CardUIShim
* Extends Submit control to look like Card-based app.
*/
var plugin = Echo.Plugin.manifest("CardUIShim", "Echo.StreamServer.Controls.Submit");
plugin.config = {
"submitPermissions": "forceLogin",
"buttons": ["login"],
"displaySharingOnPost": true
};
plugin.events = {
"Echo.UserSession.onInvalidate": {
"context": "global",
"handler": function() {
if (this.deferredActivity) {
this.deferredActivity();
delete this.deferredActivity;
// clearing up saved text...
var targetURL = this.component.config.get("targetURL");
Echo.Utils.set(Echo.Variables, targetURL, "");
}
}
},
"Echo.StreamServer.Controls.Submit.onSharingOnPostChange": {
"context": "global",
"handler": function() {
this.view.render({"name": "postButton"});
}
}
};
plugin.labels = {
"post": "Post",
"postAndShare": "Post and Share"
};
plugin.templates.attach = '<div class="{plugin.class:attach}"><img class="{plugin.class:attachPic}" src="{%= baseURL %}/images/attach.png" /></div>';
plugin.templates.auth = '<div class="{plugin.class:auth}"></div>';
plugin.templates.postButton =
'<div class="btn-group">' +
'<button class="btn btn-primary {plugin.class:postButton}"></button>' +
'<button class="btn btn-primary dropdown-toggle {plugin.class:switchSharing}" data-toggle="dropdown"><span class="caret"></span></button>' +
'<ul class="dropdown-menu pull-right">' +
'<li><a href="#" class="{plugin.class:switchToPost}">{plugin.label:post}</a></li>' +
'<li><a href="#" class="{plugin.class:switchToPostAndShare}">{plugin.label:postAndShare}</a></li>' +
'</ul>' +
'</div>';
plugin.init = function() {
var self = this, submit = this.component;
this.extendTemplate("remove", "postButton");
this.extendTemplate("insertAsFirstChild", "postContainer", plugin.templates.postButton);
this.extendTemplate("insertBefore", "header", plugin.templates.auth);
// drop all validators
submit.validators = [];
submit.addPostValidator(function() {
var areFieldsValid = true;
var isGuestAllowed = self.config.get("submitPermissions") === "allowGuest";
$.each(isGuestAllowed ? ["name", "text"] : ["text"], function (i, field) {
areFieldsValid = !submit.highlightMandatory(submit.view.get(field));
return areFieldsValid;
});
// exit in case some required fields are empty
if (!areFieldsValid) return false;
if (!isGuestAllowed && !submit.user.is("logged")) {
self.deferredActivity = function() {
self.component.post();
};
self._requestLoginPrompt();
return false;
}
return true;
});
// Note: let's keep the "attach" icon hidden for now,
// as there is no functionality associated with it..
//
// this.extendTemplate("insertAsFirstChild", "controls", plugin.templates.attach);
};
plugin.methods._requestLoginPrompt = function() {
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "identity/login/request",
"payload": this.component.user.data || {}
}
}]);
};
plugin.renderers.postButton = function(element) {
var self = this;
var submit = this.component;
var states = {
"normal": {
"target": element,
"icon": false,
"disabled": false,
"label": this.labels.get(this._sharingOnPost() ? "postAndShare" : "post")
},
"posting": {
"target": element,
"icon": submit.config.get("cdnBaseURL.sdk-assets") + "/images/loading.gif",
"disabled": true,
"label": submit.labels.get("posting")
}
};
var postButton = new Echo.GUI.Button(states.normal);
submit.posting = submit.posting || {};
submit.posting.subscriptions = submit.posting.subscriptions || [];
var subscribe = function(phase, state, callback) {
var topic = "Echo.StreamServer.Controls.Submit.onPost" + phase;
var subscriptions = submit.posting.subscriptions;
if (subscriptions[topic]) {
submit.events.unsubscribe({
"topic": topic,
"handlerId": subscriptions[topic]
});
}
subscriptions[topic] = submit.events.subscribe({
"topic": topic,
"handler": function(topic, params) {
postButton.setState(state);
if (callback) callback(params);
}
});
};
subscribe("Init", states.posting);
subscribe("Complete", states.normal, function(data) {
if (self._sharingOnPost()) {
self._share(data);
}
submit.view.get("text").val("").trigger("blur");
submit.view.render({"name": "tags"});
submit.view.render({"name": "markers"});
});
subscribe("Error", states.normal, function(params) {
var request = params.request || {};
if (request.state && request.state.critical) {
submit._showError(params);
}
});
submit.posting.action = submit.posting.action || function() {
if (submit._isPostValid()) {
submit.post();
}
};
element.off("click", submit.posting.action).on("click", submit.posting.action);
return element;
};
plugin.renderers.switchSharing = function(element) {
if (!this.config.get("displaySharingOnPost")) {
// it should looks like single button, not buttons group
element.parent().removeClass("btn-group");
element.hide();
}
return element;
};
plugin.renderers.switchToPost = function(element) {
var self = this;
return element.on("click", function(e) {
self._sharingOnPost(false);
e.preventDefault();
});
};
plugin.renderers.switchToPostAndShare = function(element) {
var self = this;
return element.on("click", function(e) {
self._sharingOnPost(true);
e.preventDefault();
});
};
plugin.component.renderers.header = function(element) {
var plugin = this, status = plugin._userStatus();
if (status === "logged" || status === "forcedLogin") {
return element.empty();
}
return plugin.parentRenderer("header", arguments);
};
plugin.component.renderers.container = function(element) {
var plugin = this;
plugin.parentRenderer("container", arguments);
var _class = function(postfix) {
return plugin.cssPrefix + postfix;
};
return element
.removeClass($.map(["logged", "anonymous", "forcedLogin"], _class).join(" "))
.addClass(_class(plugin._userStatus()));
};
plugin.renderers.auth = function(element) {
var config = this.config.assemble($.extend(true, {"target": element}, this.config.get("auth")));
new Echo.StreamServer.Controls.CardUIAuth(config);
return element;
};
plugin.methods._share = function(data) {
var item = data.postData.content[0];
var payload = {
"origin": "item",
"actor": {
"id": this.component.user.get("identityUrl"),
"name": item.actor.name,
"avatar": item.actor.avatar
},
"object": {
"id": data.request.response.objectID,
"content": item.object.content
},
"source": item.source,
"target": item.targets[0].id
};
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "content/share/request",
"payload": payload
}
}]);
};
plugin.methods._sharingOnPost = function(enabled) {
if (typeof enabled !== "undefined") {
Echo.Cookie.set("sharingOnPost", !!enabled);
this.component.events.publish({
"topic": "onSharingOnPostChange",
"contenxt": "global"
});
}
return this.config.get("displaySharingOnPost")
&& Echo.Cookie.get("sharingOnPost") === "true";
};
plugin.methods._userStatus = function() {
return this.component.user.is("logged")
? "logged"
: this.config.get("submitPermissions") === "forceLogin"
? "forcedLogin"
: "anonymous";
};
plugin.css =
'.{plugin.class} .{class:urlContainer} { display: none; }' +
'.{plugin.class} .{class:avatar} { display: none; }' +
'.{plugin.class} .{class:fieldsWrapper} { margin-left: 0px; }' +
'.{plugin.class} .{class:plugin-JanrainAuth-forcedLogin} .{class:header} { display: none; }' +
'.{plugin.class} .{class:fieldsWrapper} input { font-weight: normal; }' +
'.{plugin.class} .{class:nameContainer} { padding: 3px 2px 3px 5px; }' +
'.{plugin.class} .{class:tagsContainer} { display: none !important; }' +
'.{plugin.class} .{class:markersContainer} { display: none !important; }' +
'.{plugin.class} .{class:content} textarea.{class:textArea} { height: 75px; }' +
'.{plugin.class} .{class:controls} { margin: 0px; padding: 5px; border: 1px solid #d8d8d8; border-top: 0px; background: #ffffff;}' +
'.{plugin.class} .{class:container} { padding: 20px 20px 20px; border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{plugin.class} .{class:header} { margin-top: 10px; }' +
'.{plugin.class} .{class:postContainer} .dropdown-menu { min-width: 100px; }' +
'.{plugin.class} .btn.{plugin.class:postButton} { padding: 3px 12px 5px 12px; }' +
'.{plugin.class:attach} { margin: 5px; float: left; }';
Echo.Plugin.create(plugin);
})(Echo.jQuery);
| plugins/card-ui-shim.js | (function($) {
"use strict";
/**
* @class Echo.StreamServer.Controls.Stream.Plugins.CardUIShim
* Extends Stream control to look like Card-based app.
*/
var plugin = Echo.Plugin.manifest("CardUIShim", "Echo.StreamServer.Controls.Stream");
plugin.config = {
"displayEmptyStream": true
};
plugin.init = function() {
// Stream should trigger 'onActivitiesComplete' event to start items liveUpdate animation
this.component._executeNextActivity = function() {
var acts = this.activities;
if (!acts.queue.length && this.config.get("state.layout") === "full") {
acts.state = "paused";
}
if (!acts.queue.length) {
this.events.publish({
"topic": "onActivitiesComplete"
});
}
if (acts.animations > 0 || !this.itemsRenderingComplete ||
!acts.queue.length ||
this.config.get("liveUpdates.enabled") &&
acts.state === "paused" &&
acts.queue[0].action !== "replace" &&
!acts.queue[0].byCurrentUser) {
return;
}
acts.queue.shift().handler();
};
// disable 'fade' animation
this.component._spotUpdates.animate.fade = function(item) {
this.activities.animations--;
this._executeNextActivity();
};
};
plugin.component.renderers.header = function(element) {
return element.hide();
};
plugin.component.renderers.container = function(element) {
var items = $.grep(this.component.get("threads"), function(item) {
return !item.deleted;
});
return (items.length || this.config.get("displayEmptyStream"))
? element.show()
: element.hide();
};
plugin.css =
'.{plugin.cass} .{class:more} { border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{plugin.cass} .{class:messageText} { border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{plugin.class:caption} { line-height: 18px; }' +
'.{plugin.class} .{class:header} { padding: 5px 0px 5px 0px; margin: 0px; font-size: 14px; }' +
'.{plugin.class} .{class:body} .echo-control-message { margin: 0px 0px 10px; border: 1px solid #d2d2d2; box-shadow: 0px 1px 1px #d2d2d2; border-radius: 3px; color: #c6c6c6; padding: 30px 0px 30px 0px; text-align: left;}' +
'.{plugin.class} .{class:body} .echo-control-message .echo-control-message-info { height: 35px; display: block; font-size: 14px; line-height: 16px; font-weight: normal; font-style: normal; background-image: url({%= baseURL %}/images/info.png); padding-left: 40px; width: 180px; margin: 0px auto; }' +
'.{plugin.class} .echo-control-message-info { background: url({%= baseURL %}/images/info.png) no-repeat; }' +
'.{plugin.class} .{class:item} { margin: 0px 0px 10px 0px; padding: 0px; border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; background: #ffffff; }' +
'.{plugin.class} .{class:item-children} .{class:item} { margin: 0px; padding: 0px; box-shadow: 0 0 0; border: 0px; background: #f8f8f8; }';
Echo.Plugin.create(plugin);
})(Echo.jQuery);
(function($) {
"use strict";
/**
* @class Echo.StreamServer.Controls.Stream.Item.Plugins.CardUIShim
* Extends Item control to look like Card-based app.
*/
var plugin = Echo.Plugin.manifest("CardUIShim", "Echo.StreamServer.Controls.Stream.Item");
plugin.events = {
"Echo.StreamServer.Controls.Stream.onActivitiesComplete": function() {
var self = this;
var container = this.component.view.get("container");
if (this.get("isLiveUpdate") && container) {
var fade = function() {
if ($.inviewport(container, {"threshold": 0})) {
self.set("isLiveUpdate", false);
if (self._transitionSupported()) {
container.removeClass(self.cssPrefix + "liveUpdate");
} else {
setTimeout(function() {
// IE 8-9 doesn't support transition, so we just remove the highlighting.
// Maybe we should use jquery.animate (animating colors requires jQuery UI) ?
container.removeClass(self.cssPrefix + "liveUpdate");
}, self.config.get("fadeTimeout"));
}
$(document).off("scroll", fade).off("resize", fade);
return true;
} else {
return false;
}
};
if (!fade()) {
$(document).on("scroll", fade).on("resize", fade);
}
}
}
};
plugin.labels = {
"topPostIndicatorTitle": "Top Post"
};
plugin.config = {
"fadeTimeout": 10000, // 10 seconds
"displayTopPostHighlight": true
};
plugin.init = function() {
this.set("isLiveUpdate", this.component.config.get("live"));
this.extendTemplate("replace", "header", plugin.templates.header);
this.extendTemplate("insertBefore", "frame", plugin.templates.topPostMarker);
this.extendTemplate("insertAfter", "authorName", plugin.templates.date);
this.extendTemplate("insertAsLastChild", "expandChildren", plugin.templates.chevron);
this.extendTemplate("remove", "date");
};
plugin.templates.date =
'<div class="{plugin.class:date}"></div>';
plugin.templates.wrapper =
'<div class="{plugin.class:wrapper}"></div>';
plugin.templates.chevron =
'<span class="{plugin.class:chevron} icon-chevron-down"></span>';
plugin.templates.button =
'<a class="{class:button} {class:button}-{data:name}">' +
'<i class="{plugin.class:buttonIcon} {data:icon}"></i>' +
'<span class="echo-primaryFont {class:buttonCaption}">{data:label}</span>' +
'</a>';
plugin.templates.topPostMarker =
'<i class="icon-bookmark {plugin.class:topPostMarker}" title="{plugin.label:topPostIndicatorTitle}"></i>';
plugin.renderers.topPostMarker = function(element) {
var item = this.component;
var itemMarkers = item.get("data.object.markers", []);
var visible = !!this.config.get("displayTopPostHighlight") &&
!item.get("depth") &&
~$.inArray("Conversations.TopPost", itemMarkers);
return visible
? element.show()
: element.hide();
};
plugin.renderers.date = function(element) {
// TODO: use parentRenderer here
this.age = this.component.getRelativeTime(this.component.timestamp);
return element.html(this.age);
};
plugin.component.renderers.tags = function(element) {
return element.hide();
};
plugin.component.renderers.markers = function(element) {
return element.hide();
};
plugin.component.renderers.container = function(element) {
if (this.get("isLiveUpdate")) {
element.addClass(this.cssPrefix + "liveUpdate");
var transition = "border-left " + this.config.get("fadeTimeout") + "ms linear";
element.css({
"transition": transition,
"-o-transition": transition,
"-ms-transition": transition,
"-moz-transition": transition,
"-webkit-transition": transition
});
}
element = this.parentRenderer("container", arguments);
return this.component.view.rendered()
? element
: element.wrap(this.substitute({
"template": plugin.templates.wrapper
}));
};
plugin.component.renderers._button = function(element, extra) {
var template = extra.template || plugin.templates.button;
var data = {
"label": extra.label || "",
"name": extra.name,
"icon": extra.icon || "icon-comment"
};
var button = $(this.substitute({"template": template, "data": data}));
if (!extra.clickable) return element.append(button);
var clickables = $(".echo-clickable", button);
if (extra.element) {
button.find("span").empty().append(extra.element);
}
if (!clickables.length) {
clickables = button;
button.addClass("echo-clickable");
}
clickables[extra.once ? "one" : "on"]({
"click": function(event) {
event.stopPropagation();
if (extra.callback) extra.callback();
}
});
var _data = this.component.get("buttons." + extra.plugin + "." + extra.name);
_data.element = button;
_data.clickableElements = clickables;
if (Echo.Utils.isMobileDevice()) {
clickables.addClass("echo-linkColor");
}
return element.append(button);
};
var cache = {};
plugin.methods._transitionSupported = function() {
if (!cache.transitionSupported) {
var s = document.createElement('p').style;
cache.transitionSupported = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
}
return cache.transitionSupported;
};
var itemDepthRules = [];
// 100 is a maximum level of children in query, but we can apply styles for ~20
for (var i = 0; i <= 20; i++) {
itemDepthRules.push('.{plugin.class} .{class:depth}-' + i + ' { margin-left: 0px; padding-left: ' + (i ? 8 + (i - 1) * 39 : 16) + 'px; }');
}
plugin.css =
'.{plugin.class:topPostMarker} { float: right; position: relative; top: -19px; right: 0px; }' +
'.{plugin.class} .{plugin.class:wrapper} { background: #ffffff; border-bottom: 1px solid #e5e5e5; border-radius: 3px 3px 0px 0px; }' +
'.{plugin.class} .{class:container} { border-left: 8px solid transparent; background: #ffffff; }' +
'.{plugin.class} .{class:container}.{class:depth-0} { border-radius: 2px 3px 0px 0px; }' +
'.{plugin.class} .{class:container}.{plugin.class:liveUpdate} { border-left: 8px solid #f5ba47; }' +
'.{plugin.class} .echo-trinaryBackgroundColor { background-color: #f8f8f8; }' +
'.{plugin.class:date} { float: left; color: #d3d3d3; margin-left: 5px; line-height: 18px; }' +
'.{plugin.class} .{class:avatar} { height: 28px; width: 28px; margin-left: 3px; }' +
'.{plugin.class} .{class:avatar} img { height: 28px; width: 28px; border-radius: 50%;}' +
'.{plugin.class} .{class:content} { background: #f8f8f8; border-radius: 3px; }' +
'.{plugin.class} .{class:buttons} { margin-left: 0px; white-space: nowrap; }' +
'.{plugin.class} .{class:metadata} { margin-bottom: 8px; }' +
'.{plugin.class} .{class:body} { padding-top: 0px; margin-bottom: 8px; }' +
'.{plugin.class} .{class:body} .{class:text} { color: #42474A; font-size: 15px; line-height: 21px; }' +
'.{plugin.class} .{class:authorName} { color: #595959; font-weight: normal; font-size: 14px; line-height: 16px; }' +
'.{plugin.class} .{class:children} .{class:avatar-wrapper} { margin-top: 5px; }' +
'.{plugin.class} .{class:children} .{class:frame} { margin-left: 5px; }' +
'.{plugin.class} .{class:children} .{class:data} { margin-top: 2px; padding-top: 0px; }' +
'.{plugin.class} .{class:children} .{plugin.class:wrapper} { padding-top: 0px; background: none; border: none; }' +
'.{plugin.class} .{class:container-child} { padding: 20px 0px 0px 16px; margin: 0px 15px 2px 0px; }' +
'.{plugin.class} .{class:content} .{class:container-child-thread} { padding: 20px 0px 0px 8px; margin: 0px 15px 2px 0px; }' +
'.{plugin.class} .{class:button} { margin-right: 10px; }' +
'.{plugin.class} .{class:button-delim} { display: none; }' +
'.echo-sdk-ui .{plugin.class:buttonIcon}[class*=" icon-"] { margin-right: 4px; margin-top: 0px; }' +
'.{plugin.class} .{plugin.class:buttonIcon} { opacity: 0.3; }' +
'.{plugin.class} .{class:buttonCaption} { vertical-align: middle; font-size: 12px; }' +
'.{plugin.class} .{class:buttons} a.{class:button}.echo-linkColor, .{class:buttons} a.{class:button}:hover { color: #262626; text-decoration: none; }' +
'.{plugin.class} .{class:buttons} a.{class:button}.echo-linkColor .{plugin.class:buttonIcon},' +
'.{class:buttons} a.{class:button}:hover .{plugin.class:buttonIcon} { opacity: 0.8; }' +
'.{plugin.class} .{class:depth-0} .{plugin.class:date} { line-height: 40px; }' +
'.{plugin.class} .{plugin.class:chevron} { margin-top: 0px !important; }' +
'.{plugin.class} .{class:expandChildrenLabel} { margin-right: 5px; }' +
'.{plugin.class} .{class:expandChildren} .{class:expandChildrenLabel} { color: #D3D3D3; }' +
'.{plugin.class} .{class:expandChildren}:hover .{class:expandChildrenLabel} { color: #262626; }' +
'.{plugin.class} .{class:expandChildren} .{plugin.class:chevron} { opacity: 0.3; }' +
'.{plugin.class} .{class:expandChildren}:hover .{plugin.class:chevron} { opacity: 0.8; }' +
'.{plugin.class} .{class:expandChildren} .echo-message-icon { padding-left: 0px; background: none; }' +
'.{plugin.class} .{class:expandChildren} .{class:message-loading} { background: none; }' +
'.{plugin.class} .{class:depth-0} .{class:footer} { padding: 8px 0px 10px; }' +
'.{plugin.class} .{class:depth-0} .{class:body} { padding-top: 0px; }' +
'.{plugin.class} .{class:depth-0} .{class:avatar} { height: 36px; width: 36px; }' +
'.{plugin.class} .{class:depth-0} .{class:avatar} img { height: 36px; width: 36px; border-radius: 50%;}' +
'.{plugin.class} .{class:depth-0} .{class:authorName} { font-weight: normal; font-size: 17px; line-height: 38px; margin-left: 45px;}' +
'.{plugin.class} .{class:depth-0} .{class:subwrapper} { margin-left: 0px; }' +
'.{plugin.class} .{class:depth-0} .{class:childrenMarker} { display: none; }' +
'.{plugin.class} .{class:data} { padding: 7px 0px 0px 0px; }' +
'.{plugin.class} .{class:content} .{class:depth-0} { padding: 15px 16px 0px 8px; }' +
itemDepthRules.join("\n");
Echo.Plugin.create(plugin);
})(Echo.jQuery);
(function($) {
"use strict";
/**
* @class Echo.StreamServer.Controls.Submit.Plugins.CardUIShim
* Extends Submit control to look like Card-based app.
*/
var plugin = Echo.Plugin.manifest("CardUIShim", "Echo.StreamServer.Controls.Submit");
plugin.config = {
"submitPermissions": "forceLogin",
"buttons": ["login"],
"displaySharingOnPost": true
};
plugin.events = {
"Echo.UserSession.onInvalidate": {
"context": "global",
"handler": function() {
if (this.deferredActivity) {
this.deferredActivity();
delete this.deferredActivity;
// clearing up saved text...
var targetURL = this.component.config.get("targetURL");
Echo.Utils.set(Echo.Variables, targetURL, "");
}
}
},
"Echo.StreamServer.Controls.Submit.onSharingOnPostChange": {
"context": "global",
"handler": function() {
this.view.render({"name": "postButton"});
}
}
};
plugin.labels = {
"post": "Post",
"postAndShare": "Post and Share"
};
plugin.templates.attach = '<div class="{plugin.class:attach}"><img class="{plugin.class:attachPic}" src="{%= baseURL %}/images/attach.png" /></div>';
plugin.templates.auth = '<div class="{plugin.class:auth}"></div>';
plugin.templates.postButton =
'<div class="btn-group">' +
'<button class="btn btn-primary {plugin.class:postButton}"></button>' +
'<button class="btn btn-primary dropdown-toggle {plugin.class:switchSharing}" data-toggle="dropdown"><span class="caret"></span></button>' +
'<ul class="dropdown-menu pull-right">' +
'<li><a href="#" class="{plugin.class:switchToPost}">{plugin.label:post}</a></li>' +
'<li><a href="#" class="{plugin.class:switchToPostAndShare}">{plugin.label:postAndShare}</a></li>' +
'</ul>' +
'</div>';
plugin.init = function() {
var self = this, submit = this.component;
this.extendTemplate("remove", "postButton");
this.extendTemplate("insertAsFirstChild", "postContainer", plugin.templates.postButton);
this.extendTemplate("insertBefore", "header", plugin.templates.auth);
// drop all validators
submit.validators = [];
submit.addPostValidator(function() {
var areFieldsValid = true;
var isGuestAllowed = self.config.get("submitPermissions") === "allowGuest";
$.each(isGuestAllowed ? ["name", "text"] : ["text"], function (i, field) {
areFieldsValid = !submit.highlightMandatory(submit.view.get(field));
return areFieldsValid;
});
// exit in case some required fields are empty
if (!areFieldsValid) return false;
if (!isGuestAllowed && !submit.user.is("logged")) {
self.deferredActivity = function() {
self.component.post();
};
self._requestLoginPrompt();
return false;
}
return true;
});
// Note: let's keep the "attach" icon hidden for now,
// as there is no functionality associated with it..
//
// this.extendTemplate("insertAsFirstChild", "controls", plugin.templates.attach);
};
plugin.methods._requestLoginPrompt = function() {
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "identity/login/request",
"payload": this.component.user.data || {}
}
}]);
};
plugin.renderers.postButton = function(element) {
var self = this;
var submit = this.component;
var states = {
"normal": {
"target": element,
"icon": false,
"disabled": false,
"label": this.labels.get(this._sharingOnPost() ? "postAndShare" : "post")
},
"posting": {
"target": element,
"icon": submit.config.get("cdnBaseURL.sdk-assets") + "/images/loading.gif",
"disabled": true,
"label": submit.labels.get("posting")
}
};
var postButton = new Echo.GUI.Button(states.normal);
submit.posting = submit.posting || {};
submit.posting.subscriptions = submit.posting.subscriptions || [];
var subscribe = function(phase, state, callback) {
var topic = "Echo.StreamServer.Controls.Submit.onPost" + phase;
var subscriptions = submit.posting.subscriptions;
if (subscriptions[topic]) {
submit.events.unsubscribe({
"topic": topic,
"handlerId": subscriptions[topic]
});
}
subscriptions[topic] = submit.events.subscribe({
"topic": topic,
"handler": function(topic, params) {
postButton.setState(state);
if (callback) callback(params);
}
});
};
subscribe("Init", states.posting);
subscribe("Complete", states.normal, function(data) {
if (self._sharingOnPost()) {
self._share(data);
}
submit.view.get("text").val("").trigger("blur");
submit.view.render({"name": "tags"});
submit.view.render({"name": "markers"});
});
subscribe("Error", states.normal, function(params) {
var request = params.request || {};
if (request.state && request.state.critical) {
submit._showError(params);
}
});
submit.posting.action = submit.posting.action || function() {
if (submit._isPostValid()) {
submit.post();
}
};
element.off("click", submit.posting.action).on("click", submit.posting.action);
return element;
};
plugin.renderers.switchSharing = function(element) {
if (!this.config.get("displaySharingOnPost")) {
// it should looks like single button, not buttons group
element.parent().removeClass("btn-group");
element.hide();
}
return element;
};
plugin.renderers.switchToPost = function(element) {
var self = this;
return element.on("click", function(e) {
self._sharingOnPost(false);
e.preventDefault();
});
};
plugin.renderers.switchToPostAndShare = function(element) {
var self = this;
return element.on("click", function(e) {
self._sharingOnPost(true);
e.preventDefault();
});
};
plugin.component.renderers.header = function(element) {
var plugin = this, status = plugin._userStatus();
if (status === "logged" || status === "forcedLogin") {
return element.empty();
}
return plugin.parentRenderer("header", arguments);
};
plugin.component.renderers.container = function(element) {
var plugin = this;
plugin.parentRenderer("container", arguments);
var _class = function(postfix) {
return plugin.cssPrefix + postfix;
};
return element
.removeClass($.map(["logged", "anonymous", "forcedLogin"], _class).join(" "))
.addClass(_class(plugin._userStatus()));
};
plugin.renderers.auth = function(element) {
var config = this.config.assemble($.extend(true, {"target": element}, this.config.get("auth")));
new Echo.StreamServer.Controls.CardUIAuth(config);
return element;
};
plugin.methods._share = function(data) {
var item = data.postData.content[0];
var payload = {
"origin": "item",
"actor": {
"id": this.component.user.get("identityUrl"),
"name": item.actor.name,
"avatar": item.actor.avatar
},
"object": {
"id": data.request.response.objectID,
"content": item.object.content
},
"source": item.source,
"target": item.targets[0].id
};
Backplane.response([{
// IMPORTANT: we use ID of the last received message
// from the server-side to avoid same messages re-processing
// because of the "since" parameter cleanup...
"id": Backplane.since,
"channel_name": Backplane.getChannelName(),
"message": {
"type": "content/share/request",
"payload": payload
}
}]);
};
plugin.methods._sharingOnPost = function(enabled) {
if (typeof enabled !== "undefined") {
Echo.Cookie.set("sharingOnPost", !!enabled);
this.component.events.publish({
"topic": "onSharingOnPostChange",
"contenxt": "global"
});
}
return this.config.get("displaySharingOnPost")
&& Echo.Cookie.get("sharingOnPost") === "true";
};
plugin.methods._userStatus = function() {
return this.component.user.is("logged")
? "logged"
: this.config.get("submitPermissions") === "forceLogin"
? "forcedLogin"
: "anonymous";
};
plugin.css =
'.{plugin.class} .{class:urlContainer} { display: none; }' +
'.{plugin.class} .{class:avatar} { display: none; }' +
'.{plugin.class} .{class:fieldsWrapper} { margin-left: 0px; }' +
'.{plugin.class} .{class:plugin-JanrainAuth-forcedLogin} .{class:header} { display: none; }' +
'.{plugin.class} .{class:fieldsWrapper} input { font-weight: normal; }' +
'.{plugin.class} .{class:nameContainer} { padding: 3px 2px 3px 5px; }' +
'.{plugin.class} .{class:tagsContainer} { display: none !important; }' +
'.{plugin.class} .{class:markersContainer} { display: none !important; }' +
'.{plugin.class} .{class:content} textarea.{class:textArea} { height: 75px; }' +
'.{plugin.class} .{class:controls} { margin: 0px; padding: 5px; border: 1px solid #d8d8d8; border-top: 0px; background: #ffffff;}' +
'.{plugin.class} .{class:container} { padding: 20px 20px 20px; border: 1px solid #d8d8d8; border-bottom-width: 2px; border-radius: 3px; }' +
'.{plugin.class} .{class:header} { margin-top: 10px; }' +
'.{plugin.class} .{class:postContainer} .dropdown-menu { min-width: 100px; }' +
'.{plugin.class} .btn.{plugin.class:postButton} { padding: 3px 12px 5px 12px; }' +
'.{plugin.class:attach} { margin: 5px; float: left; }';
Echo.Plugin.create(plugin);
})(Echo.jQuery);
| Changed background-color of blocking backdrop to transparent one
| plugins/card-ui-shim.js | Changed background-color of blocking backdrop to transparent one | <ide><path>lugins/card-ui-shim.js
<ide> '.{plugin.class} .echo-trinaryBackgroundColor { background-color: #f8f8f8; }' +
<ide> '.{plugin.class:date} { float: left; color: #d3d3d3; margin-left: 5px; line-height: 18px; }' +
<ide>
<add> '.{plugin.class} .{class:blocker-backdrop} { background-color: transparent; }' +
<ide> '.{plugin.class} .{class:avatar} { height: 28px; width: 28px; margin-left: 3px; }' +
<ide> '.{plugin.class} .{class:avatar} img { height: 28px; width: 28px; border-radius: 50%;}' +
<ide> |
|
Java | apache-2.0 | 523fe31f92d9166bacf70fd00b7a7b6154d30511 | 0 | RavenB/lumify,TeamUDS/lumify,TeamUDS/lumify,Steimel/lumify,TeamUDS/lumify,j-bernardo/lumify,Steimel/lumify,dvdnglnd/lumify,Steimel/lumify,Steimel/lumify,dvdnglnd/lumify,j-bernardo/lumify,RavenB/lumify,bings/lumify,bings/lumify,dvdnglnd/lumify,Steimel/lumify,TeamUDS/lumify,dvdnglnd/lumify,j-bernardo/lumify,j-bernardo/lumify,bings/lumify,lumifyio/lumify,lumifyio/lumify,RavenB/lumify,TeamUDS/lumify,lumifyio/lumify,bings/lumify,j-bernardo/lumify,RavenB/lumify,dvdnglnd/lumify,lumifyio/lumify,RavenB/lumify,bings/lumify,lumifyio/lumify | package io.lumify.tools;
import io.lumify.core.cmdline.CommandLineBase;
import io.lumify.core.user.Privilege;
import io.lumify.core.user.User;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import java.util.Date;
import java.util.List;
import java.util.Set;
public class UserAdmin extends CommandLineBase {
private static final String CMD_OPT_USERNAME = "username";
private static final String CMD_OPT_USERID = "userid";
private static final String CMD_OPT_PRIVILEGES = "privileges";
private static final String CMD_OPT_AS_TABLE = "as-table";
private static final String CMD_ACTION_LIST = "list";
private static final String CMD_ACTION_DELETE = "delete";
private static final String CMD_ACTION_SET_PRIVILEGES = "set-privileges";
public static void main(String[] args) throws Exception {
int res = new UserAdmin().run(args);
if (res != 0) {
System.exit(res);
}
}
@Override
protected Options getOptions() {
Options opts = super.getOptions();
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_USERID)
.withDescription("The user id of the user you would like to view or edit")
.hasArg()
.create("i")
);
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_USERNAME)
.withDescription("The username of the user you would like to view or edit")
.hasArg()
.create("u")
);
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_PRIVILEGES)
.withDescription("Comma separated list of privileges " + privilegesAsString(Privilege.ALL))
.hasArg()
.create("p")
);
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_AS_TABLE)
.withDescription("List users in a table")
.create("t")
);
return opts;
}
@Override
protected int run(CommandLine cmd) throws Exception {
List args = cmd.getArgList();
if (args.contains(CMD_ACTION_LIST)) {
return list(cmd);
}
if (args.contains(CMD_ACTION_DELETE)) {
return delete(cmd);
}
if (args.contains(CMD_ACTION_SET_PRIVILEGES)) {
return setPrivileges(cmd);
}
System.out.println(cmd.toString());
return 0;
}
private int delete(CommandLine cmd) {
User user = findUser(cmd);
if (user == null) {
printUserNotFoundError(cmd);
return 2;
}
getUserRepository().delete(user);
System.out.println("Deleted user " + user.getUserId());
return 0;
}
private int list(CommandLine cmd) {
Iterable<User> users = getUserRepository().findAll();
if (cmd.hasOption(CMD_OPT_AS_TABLE)) {
printUsers(users);
} else {
for (User user : users) {
printUser(user);
}
}
return 0;
}
private int setPrivileges(CommandLine cmd) {
String privilegesString = cmd.getOptionValue(CMD_OPT_PRIVILEGES);
Set<Privilege> privileges = null;
if (privilegesString != null) {
privileges = Privilege.stringToPrivileges(privilegesString);
}
User user = findUser(cmd);
if (user == null) {
printUserNotFoundError(cmd);
return 2;
}
if (privileges != null) {
System.out.println("Assigning privileges " + privileges + " to user " + user.getUserId());
getUserRepository().setPrivileges(user, privileges);
user = getUserRepository().findById(user.getUserId());
}
printUser(user);
return 0;
}
private User findUser(CommandLine cmd) {
String username = cmd.getOptionValue(CMD_OPT_USERNAME);
String userid = cmd.getOptionValue(CMD_OPT_USERID);
User user = null;
if (username != null) {
user = getUserRepository().findByUsername(username);
} else if (userid != null) {
user = getUserRepository().findById(userid);
}
return user;
}
private void printUser(User user) {
System.out.println(" ID: " + user.getUserId());
System.out.println(" Username: " + user.getUsername());
System.out.println(" E-Mail Address: " + valueOrBlank(user.getEmailAddress()));
System.out.println(" Display Name: " + user.getDisplayName());
System.out.println(" Create Date: " + user.getCreateDate());
System.out.println(" Current Login Date: " + valueOrBlank(user.getCurrentLoginDate()));
System.out.println(" Current Login Remote Addr: " + valueOrBlank(user.getCurrentLoginRemoteAddr()));
System.out.println(" Previous Login Date: " + valueOrBlank(user.getPreviousLoginDate()));
System.out.println("Previous Login Remote Addr: " + valueOrBlank(user.getPreviousLoginRemoteAddr()));
System.out.println(" Login Count: " + user.getLoginCount());
System.out.println(" Privileges: " + privilegesAsString(getUserRepository().getPrivileges(user)));
System.out.println("");
}
private void printUsers(Iterable<User> users) {
if (users != null) {
int maxIdWidth = 1;
int maxUsernameWidth = 1;
int maxEmailAddressWidth = 1;
int maxDisplayNameWidth = 1;
int maxLoginCountWidth = 1;
int maxPrivilegesWidth = privilegesAsString(Privilege.ALL).length();
for (User user : users) {
maxIdWidth = maxWidth(user.getUserId(), maxIdWidth);
maxUsernameWidth = maxWidth(user.getUsername(), maxUsernameWidth);
maxEmailAddressWidth = maxWidth(user.getEmailAddress(), maxEmailAddressWidth);
maxDisplayNameWidth = maxWidth(user.getDisplayName(), maxDisplayNameWidth);
maxLoginCountWidth = maxWidth(Integer.toString(user.getLoginCount()), maxLoginCountWidth);
}
String format = String.format("%%%ds %%%ds %%%ds %%%ds %%%dd %%%ds%%n", -1 * maxIdWidth, -1 * maxUsernameWidth, -1 * maxEmailAddressWidth, -1 * maxDisplayNameWidth, maxLoginCountWidth, -1 * maxPrivilegesWidth);
for (User user : users) {
String emailAddress = user.getEmailAddress();
emailAddress = emailAddress != null ? emailAddress : "";
System.out.printf(format,
user.getUserId(),
user.getUsername(),
emailAddress,
user.getDisplayName(),
user.getLoginCount(),
privilegesAsString(getUserRepository().getPrivileges(user))
);
}
} else {
System.out.println("No users");
}
}
private String privilegesAsString(Set<Privilege> privileges) {
return privileges.toString().replaceAll(" ", "");
}
private void printUserNotFoundError(CommandLine cmd) {
String username = cmd.getOptionValue(CMD_OPT_USERNAME);
if (username != null) {
System.out.println("No user found with username: " + username);
return;
}
String userid = cmd.getOptionValue(CMD_OPT_USERID);
if (userid != null) {
System.out.println("No user found with userid: " + userid);
return;
}
}
private String valueOrBlank(Object o) {
return o != null ? o.toString() : "";
}
private int maxWidth(Object o, int max) {
int width = valueOrBlank(o).length();
return width > max ? width : max;
}
}
| lumify-tools/lumify-user-admin/src/main/java/io/lumify/tools/UserAdmin.java | package io.lumify.tools;
import io.lumify.core.cmdline.CommandLineBase;
import io.lumify.core.user.Privilege;
import io.lumify.core.user.User;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import java.util.Date;
import java.util.List;
import java.util.Set;
public class UserAdmin extends CommandLineBase {
private static final String CMD_OPT_USERNAME = "username";
private static final String CMD_OPT_USERID = "userid";
private static final String CMD_OPT_PRIVILEGES = "privileges";
private static final String CMD_OPT_AS_TABLE = "as-table";
private static final String CMD_ACTION_LIST = "list";
private static final String CMD_ACTION_DELETE = "delete";
private static final String CMD_ACTION_SET_PRIVILEGES = "set-privileges";
public static void main(String[] args) throws Exception {
int res = new UserAdmin().run(args);
if (res != 0) {
System.exit(res);
}
}
@Override
protected Options getOptions() {
Options opts = super.getOptions();
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_USERID)
.withDescription("The user id of the user you would like to view or edit")
.hasArg()
.create("i")
);
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_USERNAME)
.withDescription("The username of the user you would like to view or edit")
.hasArg()
.create("u")
);
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_PRIVILEGES)
.withDescription("Comma separated list of privileges " + privilegesAsString(Privilege.ALL))
.hasArg()
.create("p")
);
opts.addOption(
OptionBuilder
.withLongOpt(CMD_OPT_AS_TABLE)
.withDescription("List users in a table")
.create("t")
);
return opts;
}
@Override
protected int run(CommandLine cmd) throws Exception {
List args = cmd.getArgList();
if (args.contains(CMD_ACTION_LIST)) {
return list(cmd);
}
if (args.contains(CMD_ACTION_DELETE)) {
return delete(cmd);
}
if (args.contains(CMD_ACTION_SET_PRIVILEGES)) {
return setPrivileges(cmd);
}
System.out.println(cmd.toString());
return 0;
}
private int delete(CommandLine cmd) {
User user = findUser(cmd);
if (user == null) {
printUserNotFoundError(cmd);
return 2;
}
getUserRepository().delete(user);
System.out.println("Deleted user " + user.getUserId());
return 0;
}
private int list(CommandLine cmd) {
Iterable<User> users = getUserRepository().findAll();
if (cmd.hasOption(CMD_OPT_AS_TABLE)) {
printUsers(users);
} else {
for (User user : users) {
printUser(user);
}
}
return 0;
}
private int setPrivileges(CommandLine cmd) {
String privilegesString = cmd.getOptionValue(CMD_OPT_PRIVILEGES);
Set<Privilege> privileges = null;
if (privilegesString != null) {
privileges = Privilege.stringToPrivileges(privilegesString);
}
User user = findUser(cmd);
if (user == null) {
printUserNotFoundError(cmd);
return 2;
}
if (privileges != null) {
System.out.println("Assigning privileges " + privileges + " to user " + user.getUserId());
getUserRepository().setPrivileges(user, privileges);
user = getUserRepository().findById(user.getUserId());
}
printUser(user);
return 0;
}
private User findUser(CommandLine cmd) {
String username = cmd.getOptionValue(CMD_OPT_USERNAME);
String userid = cmd.getOptionValue(CMD_OPT_USERID);
User user = null;
if (username != null) {
user = getUserRepository().findByUsername(username);
} else if (userid != null) {
user = getUserRepository().findById(userid);
}
return user;
}
private void printUser(User user) {
String emailAddress = user.getEmailAddress();
emailAddress = emailAddress != null ? emailAddress : "";
Date currentLoginDate = user.getCurrentLoginDate();
String currentLoginDateString = currentLoginDate != null ? currentLoginDate.toString() : "";
String currentLoginRemoteAddr = user.getCurrentLoginRemoteAddr();
currentLoginRemoteAddr = currentLoginRemoteAddr != null ? currentLoginRemoteAddr : "";
Date previousLoginDate = user.getPreviousLoginDate();
String previousLoginDateString = previousLoginDate != null ? previousLoginDate.toString() : "";
String previousLoginRemoteAddr = user.getPreviousLoginRemoteAddr();
previousLoginRemoteAddr = previousLoginRemoteAddr != null ? previousLoginRemoteAddr : "";
System.out.println(" ID: " + user.getUserId());
System.out.println(" Username: " + user.getUsername());
System.out.println(" E-Mail Address: " + emailAddress);
System.out.println(" Display Name: " + user.getDisplayName());
System.out.println(" Current Login Date: " + currentLoginDateString);
System.out.println(" Current Login Remote Addr: " + currentLoginRemoteAddr);
System.out.println(" Previous Login Date: " + previousLoginDateString);
System.out.println("Previous Login Remote Addr: " + previousLoginRemoteAddr);
System.out.println(" Login Count: " + user.getLoginCount());
System.out.println(" Privileges: " + privilegesAsString(getUserRepository().getPrivileges(user)));
System.out.println("");
}
private void printUsers(Iterable<User> users) {
if (users != null) {
int maxIdWidth = 1;
int maxUsernameWidth = 1;
int maxEmailAddressWidth = 1;
int maxDisplayNameWidth = 1;
int maxLoginCountWidth = 1;
int maxPrivilegesWith = privilegesAsString(Privilege.ALL).length();
for (User user : users) {
String id = user.getUserId();
int idWidth = id != null ? id.length() : 0;
maxIdWidth = idWidth > maxIdWidth ? idWidth : maxIdWidth;
String username = user.getUsername();
int usernameWidth = username != null ? username.length() : 0;
maxUsernameWidth = usernameWidth > maxUsernameWidth ? usernameWidth : maxUsernameWidth;
String emailAddress = user.getEmailAddress();
int emailAddressWidth = emailAddress != null ? emailAddress.length() : 0;
maxEmailAddressWidth = emailAddressWidth > maxEmailAddressWidth ? emailAddressWidth : maxEmailAddressWidth;
String displayName = user.getDisplayName();
int displayNameWidth = displayName != null ? displayName.length() : 0;
maxDisplayNameWidth = displayNameWidth > maxDisplayNameWidth ? displayNameWidth : maxDisplayNameWidth;
int loginCount = user.getLoginCount();
int loginCountWidth = Integer.toString(loginCount).length();
maxLoginCountWidth = loginCountWidth > maxLoginCountWidth ? loginCountWidth : maxLoginCountWidth;
}
String format = String.format("%%%ds %%%ds %%%ds %%%ds %%%dd %%%ds%%n", -1 * maxIdWidth, -1 * maxUsernameWidth, -1 * maxEmailAddressWidth, -1 * maxDisplayNameWidth, maxLoginCountWidth, -1 * maxPrivilegesWith);
for (User user : users) {
String emailAddress = user.getEmailAddress();
emailAddress = emailAddress != null ? emailAddress : "";
System.out.printf(format,
user.getUserId(),
user.getUsername(),
emailAddress,
user.getDisplayName(),
user.getLoginCount(),
privilegesAsString(getUserRepository().getPrivileges(user))
);
}
} else {
System.out.println("No users");
}
}
private String privilegesAsString(Set<Privilege> privileges) {
return privileges.toString().replaceAll(" ", "");
}
private void printUserNotFoundError(CommandLine cmd) {
String username = cmd.getOptionValue(CMD_OPT_USERNAME);
if (username != null) {
System.out.println("No user found with username: " + username);
return;
}
String userid = cmd.getOptionValue(CMD_OPT_USERID);
if (userid != null) {
System.out.println("No user found with userid: " + userid);
return;
}
}
}
| clean up, display create date
| lumify-tools/lumify-user-admin/src/main/java/io/lumify/tools/UserAdmin.java | clean up, display create date | <ide><path>umify-tools/lumify-user-admin/src/main/java/io/lumify/tools/UserAdmin.java
<ide> }
<ide>
<ide> private void printUser(User user) {
<del> String emailAddress = user.getEmailAddress();
<del> emailAddress = emailAddress != null ? emailAddress : "";
<del> Date currentLoginDate = user.getCurrentLoginDate();
<del> String currentLoginDateString = currentLoginDate != null ? currentLoginDate.toString() : "";
<del> String currentLoginRemoteAddr = user.getCurrentLoginRemoteAddr();
<del> currentLoginRemoteAddr = currentLoginRemoteAddr != null ? currentLoginRemoteAddr : "";
<del> Date previousLoginDate = user.getPreviousLoginDate();
<del> String previousLoginDateString = previousLoginDate != null ? previousLoginDate.toString() : "";
<del> String previousLoginRemoteAddr = user.getPreviousLoginRemoteAddr();
<del> previousLoginRemoteAddr = previousLoginRemoteAddr != null ? previousLoginRemoteAddr : "";
<del>
<ide> System.out.println(" ID: " + user.getUserId());
<ide> System.out.println(" Username: " + user.getUsername());
<del> System.out.println(" E-Mail Address: " + emailAddress);
<add> System.out.println(" E-Mail Address: " + valueOrBlank(user.getEmailAddress()));
<ide> System.out.println(" Display Name: " + user.getDisplayName());
<del> System.out.println(" Current Login Date: " + currentLoginDateString);
<del> System.out.println(" Current Login Remote Addr: " + currentLoginRemoteAddr);
<del> System.out.println(" Previous Login Date: " + previousLoginDateString);
<del> System.out.println("Previous Login Remote Addr: " + previousLoginRemoteAddr);
<add> System.out.println(" Create Date: " + user.getCreateDate());
<add> System.out.println(" Current Login Date: " + valueOrBlank(user.getCurrentLoginDate()));
<add> System.out.println(" Current Login Remote Addr: " + valueOrBlank(user.getCurrentLoginRemoteAddr()));
<add> System.out.println(" Previous Login Date: " + valueOrBlank(user.getPreviousLoginDate()));
<add> System.out.println("Previous Login Remote Addr: " + valueOrBlank(user.getPreviousLoginRemoteAddr()));
<ide> System.out.println(" Login Count: " + user.getLoginCount());
<ide> System.out.println(" Privileges: " + privilegesAsString(getUserRepository().getPrivileges(user)));
<ide> System.out.println("");
<ide> int maxEmailAddressWidth = 1;
<ide> int maxDisplayNameWidth = 1;
<ide> int maxLoginCountWidth = 1;
<del> int maxPrivilegesWith = privilegesAsString(Privilege.ALL).length();
<add> int maxPrivilegesWidth = privilegesAsString(Privilege.ALL).length();
<ide> for (User user : users) {
<del> String id = user.getUserId();
<del> int idWidth = id != null ? id.length() : 0;
<del> maxIdWidth = idWidth > maxIdWidth ? idWidth : maxIdWidth;
<del> String username = user.getUsername();
<del> int usernameWidth = username != null ? username.length() : 0;
<del> maxUsernameWidth = usernameWidth > maxUsernameWidth ? usernameWidth : maxUsernameWidth;
<del> String emailAddress = user.getEmailAddress();
<del> int emailAddressWidth = emailAddress != null ? emailAddress.length() : 0;
<del> maxEmailAddressWidth = emailAddressWidth > maxEmailAddressWidth ? emailAddressWidth : maxEmailAddressWidth;
<del> String displayName = user.getDisplayName();
<del> int displayNameWidth = displayName != null ? displayName.length() : 0;
<del> maxDisplayNameWidth = displayNameWidth > maxDisplayNameWidth ? displayNameWidth : maxDisplayNameWidth;
<del> int loginCount = user.getLoginCount();
<del> int loginCountWidth = Integer.toString(loginCount).length();
<del> maxLoginCountWidth = loginCountWidth > maxLoginCountWidth ? loginCountWidth : maxLoginCountWidth;
<add> maxIdWidth = maxWidth(user.getUserId(), maxIdWidth);
<add> maxUsernameWidth = maxWidth(user.getUsername(), maxUsernameWidth);
<add> maxEmailAddressWidth = maxWidth(user.getEmailAddress(), maxEmailAddressWidth);
<add> maxDisplayNameWidth = maxWidth(user.getDisplayName(), maxDisplayNameWidth);
<add> maxLoginCountWidth = maxWidth(Integer.toString(user.getLoginCount()), maxLoginCountWidth);
<ide> }
<del> String format = String.format("%%%ds %%%ds %%%ds %%%ds %%%dd %%%ds%%n", -1 * maxIdWidth, -1 * maxUsernameWidth, -1 * maxEmailAddressWidth, -1 * maxDisplayNameWidth, maxLoginCountWidth, -1 * maxPrivilegesWith);
<add> String format = String.format("%%%ds %%%ds %%%ds %%%ds %%%dd %%%ds%%n", -1 * maxIdWidth, -1 * maxUsernameWidth, -1 * maxEmailAddressWidth, -1 * maxDisplayNameWidth, maxLoginCountWidth, -1 * maxPrivilegesWidth);
<ide> for (User user : users) {
<ide> String emailAddress = user.getEmailAddress();
<ide> emailAddress = emailAddress != null ? emailAddress : "";
<ide> }
<ide> }
<ide>
<add> private String valueOrBlank(Object o) {
<add> return o != null ? o.toString() : "";
<add> }
<add>
<add> private int maxWidth(Object o, int max) {
<add> int width = valueOrBlank(o).length();
<add> return width > max ? width : max;
<add> }
<ide> } |
|
Java | lgpl-2.1 | a28ffe0139ef81731182449688816f2700adc783 | 0 | skyvers/wildcat,skyvers/wildcat,skyvers/skyve,skyvers/wildcat,skyvers/skyve,skyvers/skyve,skyvers/skyve,skyvers/skyve,skyvers/skyve,skyvers/wildcat,skyvers/wildcat,skyvers/skyve | package modules.admin.ControlPanel;
import java.util.Date;
import java.util.List;
import org.skyve.CORE;
import org.skyve.EXT;
import org.skyve.domain.PersistentBean;
import org.skyve.domain.messages.MessageSeverity;
import org.skyve.job.CancellableJob;
import org.skyve.metadata.customer.Customer;
import org.skyve.metadata.model.document.Document;
import org.skyve.metadata.module.Module;
import org.skyve.persistence.DocumentQuery;
import org.skyve.persistence.Persistence;
import org.skyve.util.Binder;
import org.skyve.util.DataBuilder;
import org.skyve.util.PushMessage;
import org.skyve.util.test.SkyveFixture.FixtureType;
import modules.admin.domain.ModuleDocument;
import modules.admin.domain.Tag;
public class GenerateTestDataJob extends CancellableJob {
private static final long serialVersionUID = -3430408494450224782L;
private DataBuilder db;
@Override
public void execute() throws Exception {
List<String> log = getLog();
Customer customer = CORE.getCustomer();
Persistence pers = CORE.getPersistence();
ControlPanelExtension bean = (ControlPanelExtension) getBean();
Tag tag = createOrRetrieveTag(pers, bean);
// create a DataBuilder which will also populate optional references
db = new DataBuilder()
.fixture(FixtureType.crud)
.optional(true, true)
.depth(10);
int failed = 0;
int size = bean.getTestDocumentNames().size() * bean.getTestNumberToGenerate().intValue();
for (ModuleDocument docName : bean.getTestDocumentNames()) {
for (int i = 0; i < bean.getTestNumberToGenerate().intValue(); i++) {
try {
Module module = customer.getModule(docName.getModuleName());
Document document = module.getDocument(customer, docName.getDocumentName());
PersistentBean newTestDataItem = db.build(module, document);
pers.save(document, newTestDataItem);
if (Boolean.TRUE.equals(bean.getTestTagGeneratedData())) {
EXT.tag(tag.getBizId(), module.getName(), document.getName(), newTestDataItem.getBizId());
}
log.add(Binder.formatMessage(customer, "Succesfully created {moduleName}.{documentName} ", docName)
+ newTestDataItem.getBizKey());
pers.commit(false);
pers.evictCached(newTestDataItem);
pers.begin();
} catch (Exception e) {
failed++;
log.add(String.format("Error creating instance of %s - %s", docName.getDocumentName(), e.getMessage()));
e.printStackTrace();
}
setPercentComplete((int) (((float) i) / ((float) size) * 100F));
}
log.add("");
}
setPercentComplete(100);
int successful = (bean.getTestNumberToGenerate().intValue() * bean.getTestDocumentNames().size()) - failed;
log.add("Finished Generate Test Data job at " + new Date());
log.add(successful + " Documents successfully created, " + failed + " failed.");
EXT.push(new PushMessage().user(CORE.getUser()).growl(MessageSeverity.info,
String.format("%d Documents successfully created", new Integer(successful))));
}
private static Tag createOrRetrieveTag(Persistence pers, ControlPanelExtension bean) {
Tag tag = null;
if (Boolean.TRUE.equals(bean.getTestTagGeneratedData())) {
DocumentQuery q = pers.newDocumentQuery(Tag.MODULE_NAME, Tag.DOCUMENT_NAME);
q.getFilter().addEquals(Tag.namePropertyName, bean.getTestTagName());
tag = q.beanResult();
// create a new tag if it does not exist
if (tag == null) {
tag = Tag.newInstance();
tag.setName(bean.getTestTagName());
tag.setVisible(Boolean.TRUE);
tag = pers.save(tag);
}
}
return tag;
}
}
| skyve-ee/src/skyve/modules/admin/ControlPanel/GenerateTestDataJob.java | package modules.admin.ControlPanel;
import java.util.Date;
import java.util.List;
import org.skyve.CORE;
import org.skyve.EXT;
import org.skyve.domain.PersistentBean;
import org.skyve.domain.messages.MessageSeverity;
import org.skyve.job.CancellableJob;
import org.skyve.metadata.customer.Customer;
import org.skyve.metadata.model.document.Document;
import org.skyve.metadata.module.Module;
import org.skyve.persistence.DocumentQuery;
import org.skyve.persistence.Persistence;
import org.skyve.util.Binder;
import org.skyve.util.DataBuilder;
import org.skyve.util.PushMessage;
import org.skyve.util.test.SkyveFixture.FixtureType;
import modules.admin.domain.ModuleDocument;
import modules.admin.domain.Tag;
public class GenerateTestDataJob extends CancellableJob {
private static final long serialVersionUID = -3430408494450224782L;
private DataBuilder db;
@Override
public void execute() throws Exception {
List<String> log = getLog();
Customer customer = CORE.getCustomer();
Persistence pers = CORE.getPersistence();
ControlPanelExtension bean = (ControlPanelExtension) getBean();
Tag tag = createOrRetrieveTag(pers, bean);
db = new DataBuilder().fixture(FixtureType.crud);
int failed = 0;
int size = bean.getTestDocumentNames().size() * bean.getTestNumberToGenerate().intValue();
for (ModuleDocument docName : bean.getTestDocumentNames()) {
for (int i = 0; i < bean.getTestNumberToGenerate().intValue(); i++) {
try {
Module module = customer.getModule(docName.getModuleName());
Document document = module.getDocument(customer, docName.getDocumentName());
PersistentBean newTestDataItem = db.build(module, document);
pers.save(document, newTestDataItem);
if (Boolean.TRUE.equals(bean.getTestTagGeneratedData())) {
EXT.tag(tag.getBizId(), module.getName(), document.getName(), newTestDataItem.getBizId());
}
log.add(Binder.formatMessage(customer, "Succesfully created {moduleName}.{documentName} ", docName)
+ newTestDataItem.getBizKey());
pers.commit(false);
pers.evictCached(newTestDataItem);
pers.begin();
} catch (Exception e) {
failed++;
log.add(String.format("Error creating instance of %s - %s", docName.getDocumentName(), e.getMessage()));
e.printStackTrace();
}
setPercentComplete((int) (((float) i) / ((float) size) * 100F));
}
log.add("");
}
setPercentComplete(100);
int successful = (bean.getTestNumberToGenerate().intValue() * bean.getTestDocumentNames().size()) - failed;
log.add("Finished Generate Test Data job at " + new Date());
log.add(successful + " Documents successfully created, " + failed + " failed.");
EXT.push(new PushMessage().user(CORE.getUser()).growl(MessageSeverity.info,
String.format("%d Documents successfully created", new Integer(successful))));
}
private static Tag createOrRetrieveTag(Persistence pers, ControlPanelExtension bean) {
Tag tag = null;
if (Boolean.TRUE.equals(bean.getTestTagGeneratedData())) {
DocumentQuery q = pers.newDocumentQuery(Tag.MODULE_NAME, Tag.DOCUMENT_NAME);
q.getFilter().addEquals(Tag.namePropertyName, bean.getTestTagName());
tag = q.beanResult();
// create a new tag if it does not exist
if (tag == null) {
tag = Tag.newInstance();
tag.setName(bean.getTestTagName());
tag.setVisible(Boolean.TRUE);
tag = pers.save(tag);
}
}
return tag;
}
}
| Update GenerateTestDataJob to populate optional references when generating test data
| skyve-ee/src/skyve/modules/admin/ControlPanel/GenerateTestDataJob.java | Update GenerateTestDataJob to populate optional references when generating test data | <ide><path>kyve-ee/src/skyve/modules/admin/ControlPanel/GenerateTestDataJob.java
<ide> Persistence pers = CORE.getPersistence();
<ide> ControlPanelExtension bean = (ControlPanelExtension) getBean();
<ide> Tag tag = createOrRetrieveTag(pers, bean);
<del> db = new DataBuilder().fixture(FixtureType.crud);
<ide>
<add> // create a DataBuilder which will also populate optional references
<add> db = new DataBuilder()
<add> .fixture(FixtureType.crud)
<add> .optional(true, true)
<add> .depth(10);
<add>
<ide> int failed = 0;
<ide> int size = bean.getTestDocumentNames().size() * bean.getTestNumberToGenerate().intValue();
<ide> |
|
Java | mit | 1bbf499d83a710e1b8690a0cf31d26a91eaccc6d | 0 | ncomet/javaone2017-bytebuddy,ncomet/javaone2017-bytebuddy | package memoization;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import static net.bytebuddy.implementation.MethodDelegation.to;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class Memoization {
private static Map<Integer, Long> cache;
public Memoization() {
this.cache = new HashMap<>();
}
public <T> T of(Class<T> type) {
try {
return new ByteBuddy()
.subclass(type)
.method(named("compute"))
.intercept(to(this))
.make()
.load(type.getClassLoader())
.getLoaded()
.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public long intercept(int arg, @SuperCall Callable<Long> superMethod) throws Exception {
return cache.computeIfAbsent(arg, o -> {
try {
return superMethod.call();
} catch (Exception e) {
e.printStackTrace();
}
return 0L;
});
}
}
| projects/fibonacci-bytebuddy/src/main/java/memoization/Memoization.java | package memoization;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import static net.bytebuddy.implementation.MethodDelegation.to;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class Memoization {
private Map<Integer, Long> cache;
public Memoization() {
this.cache = new HashMap<>();
}
public <T> T of(Class<T> type) {
try {
return new ByteBuddy()
.subclass(type)
.method(named("compute"))
.intercept(to(this))
.make()
.load(type.getClassLoader())
.getLoaded()
.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public long intercept(int arg, @SuperCall Callable<Long> superMethod) throws Exception {
return cache.computeIfAbsent(arg, o -> {
try {
return superMethod.call();
} catch (Exception e) {
e.printStackTrace();
}
return 0L;
});
}
}
| static cache
| projects/fibonacci-bytebuddy/src/main/java/memoization/Memoization.java | static cache | <ide><path>rojects/fibonacci-bytebuddy/src/main/java/memoization/Memoization.java
<ide>
<ide> public class Memoization {
<ide>
<del> private Map<Integer, Long> cache;
<add> private static Map<Integer, Long> cache;
<ide>
<ide> public Memoization() {
<ide> this.cache = new HashMap<>(); |
|
Java | bsd-3-clause | ef233526ee623b75cbe3974cac7bf67f1f6f7758 | 0 | decorators-squad/camel,decorators-squad/camel | /**
* Copyright (c) 2016-2020, Mihai Emil Andronache
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package com.amihaiemil.eoyaml;
import static org.hamcrest.CoreMatchers.is;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Unit tests for {@link PlainStringScalar}.
* @author Mihai Andronache ([email protected])
* @version $Id$
* @since 1.0.0
*
*/
public final class PlainStringScalarTest {
/**
* Scalar can return its own value.
*/
@Test
public void returnsValue() {
final String val = "test scalar value";
final PlainStringScalar scl = new PlainStringScalar(val);
MatcherAssert.assertThat(scl.value(), Matchers.equalTo(val));
}
/**
* Scalar can return its comment.
*/
@Test
public void returnsComment() {
final String val = "test scalar value";
final PlainStringScalar scl = new PlainStringScalar(val, "comment");
MatcherAssert.assertThat(
scl.comment().value(),
Matchers.equalTo("comment")
);
MatcherAssert.assertThat(
scl.comment().yamlNode(),
Matchers.is(scl)
);
}
/**
* Make sure that equals and hash code are reflexive
* and symmetric.
*/
@Test
public void equalsAndHashCode() {
final String val = "test scalar value";
final PlainStringScalar firstScalar = new PlainStringScalar(val);
final PlainStringScalar secondScalar = new PlainStringScalar(val);
MatcherAssert.assertThat(firstScalar, Matchers.equalTo(secondScalar));
MatcherAssert.assertThat(secondScalar, Matchers.equalTo(firstScalar));
MatcherAssert.assertThat(firstScalar, Matchers.equalTo(firstScalar));
MatcherAssert.assertThat(firstScalar,
Matchers.not(Matchers.equalTo(null)));
MatcherAssert.assertThat(
firstScalar.hashCode() == secondScalar.hashCode(), is(true)
);
}
/**
* Scalar can compare itself to another Scalar.
*/
@Test
public void comparesToScalar() {
PlainStringScalar first = new PlainStringScalar("java");
PlainStringScalar second = new PlainStringScalar("java");
PlainStringScalar digits = new PlainStringScalar("123");
PlainStringScalar otherDigits = new PlainStringScalar("124");
PlainStringScalar nullScalar = new PlainStringScalar(null);
MatcherAssert.assertThat(first.compareTo(first), Matchers.equalTo(0));
MatcherAssert.assertThat(first.compareTo(second), Matchers.equalTo(0));
MatcherAssert.assertThat(
first.compareTo(digits), Matchers.greaterThan(0)
);
MatcherAssert.assertThat(
first.compareTo(null), Matchers.greaterThan(0)
);
MatcherAssert.assertThat(
digits.compareTo(otherDigits), Matchers.lessThan(0)
);
MatcherAssert.assertThat(
first.compareTo(nullScalar), Matchers.greaterThan(0)
);
MatcherAssert.assertThat(
nullScalar.compareTo(first), Matchers.lessThan(0)
);
}
/**
* Scalar can compare itself to a Mapping.
*/
@Test
public void comparesToMapping() {
PlainStringScalar first = new PlainStringScalar("java");
RtYamlMapping map = new RtYamlMapping(new LinkedHashMap<>());
MatcherAssert.assertThat(first.compareTo(map), Matchers.lessThan(0));
}
/**
* Scalar can compare itself to a Sequence.
*/
@Test
public void comparesToSequence() {
PlainStringScalar first = new PlainStringScalar("java");
RtYamlSequence seq = new RtYamlSequence(new LinkedList<YamlNode>());
MatcherAssert.assertThat(first.compareTo(seq), Matchers.lessThan(0));
}
/**
* Method toString should print it as a valid YAML document.
*/
@Test
public void toStringPrintsYaml() {
final Scalar scalar = new PlainStringScalar("value");
MatcherAssert.assertThat(
scalar.toString(),
Matchers.equalTo(
"---"
+ System.lineSeparator()
+ "value"
+ System.lineSeparator()
+ "..."
)
);
}
}
| src/test/java/com/amihaiemil/eoyaml/PlainStringScalarTest.java | /**
* Copyright (c) 2016-2020, Mihai Emil Andronache
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package com.amihaiemil.eoyaml;
import static org.hamcrest.CoreMatchers.is;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Unit tests for {@link PlainStringScalar}.
* @author Mihai Andronache ([email protected])
* @version $Id$
* @since 1.0.0
*
*/
public final class PlainStringScalarTest {
/**
* Scalar can return its own value.
*/
@Test
public void returnsValue() {
final String val = "test scalar value";
final PlainStringScalar scl = new PlainStringScalar(val);
MatcherAssert.assertThat(scl.value(), Matchers.equalTo(val));
}
/**
* Scalar can return its comment.
*/
@Test
public void returnsComment() {
final String val = "test scalar value";
final PlainStringScalar scl = new PlainStringScalar(val, "comment");
MatcherAssert.assertThat(
scl.comment().value(),
Matchers.equalTo("comment")
);
MatcherAssert.assertThat(
scl.comment().yamlNode(),
Matchers.is(scl)
);
}
/**
* Make sure that equals and hash code are reflexive
* and symmetric.
*/
@Test
public void equalsAndHashCode() {
final String val = "test scalar value";
final PlainStringScalar firstScalar = new PlainStringScalar(val);
final PlainStringScalar secondScalar = new PlainStringScalar(val);
MatcherAssert.assertThat(firstScalar, Matchers.equalTo(secondScalar));
MatcherAssert.assertThat(secondScalar, Matchers.equalTo(firstScalar));
MatcherAssert.assertThat(firstScalar, Matchers.equalTo(firstScalar));
MatcherAssert.assertThat(firstScalar,
Matchers.not(Matchers.equalTo(null)));
MatcherAssert.assertThat(
firstScalar.hashCode() == secondScalar.hashCode(), is(true)
);
}
/**
* Scalar can compare itself to another Scalar.
*/
@Test
public void comparesToScalar() {
PlainStringScalar first = new PlainStringScalar("java");
PlainStringScalar second = new PlainStringScalar("java");
PlainStringScalar digits = new PlainStringScalar("123");
PlainStringScalar otherDigits = new PlainStringScalar("124");
MatcherAssert.assertThat(first.compareTo(first), Matchers.equalTo(0));
MatcherAssert.assertThat(first.compareTo(second), Matchers.equalTo(0));
MatcherAssert.assertThat(
first.compareTo(digits), Matchers.greaterThan(0)
);
MatcherAssert.assertThat(
first.compareTo(null), Matchers.greaterThan(0)
);
MatcherAssert.assertThat(
digits.compareTo(otherDigits), Matchers.lessThan(0)
);
}
/**
* Scalar can compare itself to a Mapping.
*/
@Test
public void comparesToMapping() {
PlainStringScalar first = new PlainStringScalar("java");
RtYamlMapping map = new RtYamlMapping(new LinkedHashMap<>());
MatcherAssert.assertThat(first.compareTo(map), Matchers.lessThan(0));
}
/**
* Scalar can compare itself to a Sequence.
*/
@Test
public void comparesToSequence() {
PlainStringScalar first = new PlainStringScalar("java");
RtYamlSequence seq = new RtYamlSequence(new LinkedList<YamlNode>());
MatcherAssert.assertThat(first.compareTo(seq), Matchers.lessThan(0));
}
/**
* Method toString should print it as a valid YAML document.
*/
@Test
public void toStringPrintsYaml() {
final Scalar scalar = new PlainStringScalar("value");
MatcherAssert.assertThat(
scalar.toString(),
Matchers.equalTo(
"---"
+ System.lineSeparator()
+ "value"
+ System.lineSeparator()
+ "..."
)
);
}
}
| Add checks for null value in scalar.
| src/test/java/com/amihaiemil/eoyaml/PlainStringScalarTest.java | Add checks for null value in scalar. | <ide><path>rc/test/java/com/amihaiemil/eoyaml/PlainStringScalarTest.java
<ide> PlainStringScalar second = new PlainStringScalar("java");
<ide> PlainStringScalar digits = new PlainStringScalar("123");
<ide> PlainStringScalar otherDigits = new PlainStringScalar("124");
<add> PlainStringScalar nullScalar = new PlainStringScalar(null);
<ide> MatcherAssert.assertThat(first.compareTo(first), Matchers.equalTo(0));
<ide> MatcherAssert.assertThat(first.compareTo(second), Matchers.equalTo(0));
<ide> MatcherAssert.assertThat(
<ide> );
<ide> MatcherAssert.assertThat(
<ide> digits.compareTo(otherDigits), Matchers.lessThan(0)
<add> );
<add> MatcherAssert.assertThat(
<add> first.compareTo(nullScalar), Matchers.greaterThan(0)
<add> );
<add> MatcherAssert.assertThat(
<add> nullScalar.compareTo(first), Matchers.lessThan(0)
<ide> );
<ide> }
<ide> |
|
Java | apache-2.0 | 246cf13de04f1af67004d4322f9755828c101e85 | 0 | CMPUT301W14T05/Team5GeoTopics | package ca.ualberta.cs.team5geotopics.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import android.graphics.Bitmap;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import ca.ualberta.cs.team5geotopics.BitmapJsonConverter;
import ca.ualberta.cs.team5geotopics.BrowseActivity;
import ca.ualberta.cs.team5geotopics.Cache;
import ca.ualberta.cs.team5geotopics.CommentModel;
import ca.ualberta.cs.team5geotopics.TopLevelActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class CacheTests extends
ActivityInstrumentationTestCase2<TopLevelActivity> {
BrowseActivity activity;
public CacheTests() {
super(TopLevelActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
activity = getActivity();
}
public void testFileIO(){
//this has the "hard to test" smell
Cache cache = Cache.getInstance();
String filename = "testFile";
Bitmap pic = Bitmap.createBitmap(10,10 ,Bitmap.Config.ARGB_8888);
ArrayList<CommentModel> acm = new ArrayList<CommentModel>();
CommentModel comment1 = new CommentModel("1.2", "1.111", "Body-test body", "Author", null, "Title");
CommentModel comment2 = new CommentModel("2", "2", "Body2", "Author2", pic, "Title2");
acm.add(comment1);
acm.add(comment2); //make a list of 2 comments
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Bitmap.class, new BitmapJsonConverter());
Gson gson = builder.create();
String jsonString = gson.toJson(acm);
cache.replaceFileHistory(jsonString, filename); //store to file
acm.clear();
acm = cache.loadFromCache(filename, activity);
assertTrue(!acm.isEmpty());
assertTrue(acm.get(0).getmBody().equals(comment1.getmBody()));
assertTrue(acm.get(0).getmAuthor().equals(comment1.getmAuthor()));
assertTrue(acm.get(0).getmTitle().equals(comment1.getmTitle()));
assertTrue(acm.get(0).getmPicture() == null);
assertTrue(acm.get(0).getLat().equals(comment1.getLat()));
assertTrue(acm.get(0).getLon().equals(comment1.getLon()));
assertTrue(acm.get(1).getmBody().equals(comment2.getmBody()));
assertTrue(acm.get(1).getmAuthor().equals(comment2.getmAuthor()));
assertTrue(acm.get(1).getmTitle().equals(comment2.getmTitle()));
assertTrue(acm.get(1).getLat().equals(comment2.getLat()));
assertTrue(acm.get(1).getLon().equals(comment2.getLon()));
//Log.w("filterlogstest", acm.get(1).getmPicture().toString());
//Log.w("filterlogstest", comment2.getmPicture().toString()); //references change but the picture still makes it.
assertTrue(acm.get(1).getmPicture().describeContents() == comment2.getmPicture().describeContents());
}
}
| GeoTopicsTests/src/ca/ualberta/cs/team5geotopics/test/CacheTests.java | package ca.ualberta.cs.team5geotopics.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import android.graphics.Bitmap;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import ca.ualberta.cs.team5geotopics.BitmapJsonConverter;
import ca.ualberta.cs.team5geotopics.BrowseActivity;
import ca.ualberta.cs.team5geotopics.Cache;
import ca.ualberta.cs.team5geotopics.CommentModel;
import ca.ualberta.cs.team5geotopics.TopLevelActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class CacheTests extends
ActivityInstrumentationTestCase2<TopLevelActivity> {
BrowseActivity activity;
public CacheTests() {
super(TopLevelActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
activity = getActivity();
}
public void testFileIO(){
//this has the "hard to test" smell
Cache cache = Cache.getInstance();
String filename = "testFile";
Bitmap pic = Bitmap.createBitmap(10,10 ,Bitmap.Config.ARGB_8888);
ArrayList<CommentModel> acm = new ArrayList<CommentModel>();
CommentModel comment1 = new CommentModel("1.2", "1.111", "Body", "Author", null, "Title");
CommentModel comment2 = new CommentModel("2", "2", "Body2", "Author2", pic, "Title2");
acm.add(comment1);
acm.add(comment2); //make a list of 2 comments
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Bitmap.class, new BitmapJsonConverter());
Gson gson = builder.create();
String jsonString = gson.toJson(acm);
cache.replaceFileHistory(jsonString, filename); //store to file
acm.clear();
acm = cache.loadFromCache(filename, activity);
assertTrue(!acm.isEmpty()); //so there is something here. What else can it be (how can I view it's contents)
assertTrue(acm.contains(comment1));
assertTrue(acm.contains(comment2));
}
}
| created test for cache IO
| GeoTopicsTests/src/ca/ualberta/cs/team5geotopics/test/CacheTests.java | created test for cache IO | <ide><path>eoTopicsTests/src/ca/ualberta/cs/team5geotopics/test/CacheTests.java
<ide> Bitmap pic = Bitmap.createBitmap(10,10 ,Bitmap.Config.ARGB_8888);
<ide>
<ide> ArrayList<CommentModel> acm = new ArrayList<CommentModel>();
<del> CommentModel comment1 = new CommentModel("1.2", "1.111", "Body", "Author", null, "Title");
<add> CommentModel comment1 = new CommentModel("1.2", "1.111", "Body-test body", "Author", null, "Title");
<ide> CommentModel comment2 = new CommentModel("2", "2", "Body2", "Author2", pic, "Title2");
<ide>
<ide> acm.add(comment1);
<ide> acm.clear();
<ide>
<ide> acm = cache.loadFromCache(filename, activity);
<del> assertTrue(!acm.isEmpty()); //so there is something here. What else can it be (how can I view it's contents)
<del> assertTrue(acm.contains(comment1));
<del> assertTrue(acm.contains(comment2));
<add> assertTrue(!acm.isEmpty());
<ide>
<add> assertTrue(acm.get(0).getmBody().equals(comment1.getmBody()));
<add> assertTrue(acm.get(0).getmAuthor().equals(comment1.getmAuthor()));
<add> assertTrue(acm.get(0).getmTitle().equals(comment1.getmTitle()));
<add> assertTrue(acm.get(0).getmPicture() == null);
<add> assertTrue(acm.get(0).getLat().equals(comment1.getLat()));
<add> assertTrue(acm.get(0).getLon().equals(comment1.getLon()));
<add>
<add> assertTrue(acm.get(1).getmBody().equals(comment2.getmBody()));
<add> assertTrue(acm.get(1).getmAuthor().equals(comment2.getmAuthor()));
<add> assertTrue(acm.get(1).getmTitle().equals(comment2.getmTitle()));
<add> assertTrue(acm.get(1).getLat().equals(comment2.getLat()));
<add> assertTrue(acm.get(1).getLon().equals(comment2.getLon()));
<add>
<add> //Log.w("filterlogstest", acm.get(1).getmPicture().toString());
<add> //Log.w("filterlogstest", comment2.getmPicture().toString()); //references change but the picture still makes it.
<add> assertTrue(acm.get(1).getmPicture().describeContents() == comment2.getmPicture().describeContents());
<ide>
<ide>
<ide> } |
|
Java | mit | cee9835a0d071e7e3719693b1af93178e47ac88c | 0 | algoliareadmebot/algoliasearch-client-java-2,algolia/algoliasearch-client-java,algoliareadmebot/algoliasearch-client-java,algolia/algoliasearch-client-java,algoliareadmebot/algoliasearch-client-java-2,algoliareadmebot/algoliasearch-client-java | package com.algolia.search.saas;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
/*
* Copyright (c) 2015 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
public class Query {
public enum QueryType {
// / all query words are interpreted as prefixes.
PREFIX_ALL,
// / only the last word is interpreted as a prefix (default behavior).
PREFIX_LAST,
// / no query word is interpreted as a prefix. This option is not
// recommended.
PREFIX_NONE,
// The parameter isn't set
PREFIX_NOTSET
}
public enum RemoveWordsType {
// / when a query does not return any result, the final word will be
// removed until there is results. This option is particulary useful on
// e-commerce websites
REMOVE_LAST_WORDS,
// / when a query does not return any result, the first word will be
// removed until there is results. This option is useful on adress
// search.
REMOVE_FIRST_WORDS,
// / No specific processing is done when a query does not return any
// result.
REMOVE_NONE,
// / When a query does not return any result, a second trial will be
// made with all words as optional (which is equivalent to transforming
// the AND operand between query terms in a OR operand)
REMOVE_ALLOPTIONAL,
// The parameter isn't set
REMOVE_NOTSET
}
public enum TypoTolerance {
// / the typotolerance is enabled and all typos are retrieved. (Default
// behavior)
TYPO_TRUE,
// / the typotolerance is disabled.
TYPO_FALSE,
// / only keep results with the minimum number of typos.
TYPO_MIN,
// / the typotolerance with a distance=2 is disabled if the results
// contain hits without typo.
TYPO_STRICT,
// The parameter isn't set
TYPO_NOTSET
}
protected List<String> attributes;
protected List<String> attributesToHighlight;
protected List<String> attributesToSnippet;
protected List<String> noTypoToleranceOn;
protected Integer minWordSizeForApprox1;
protected Integer minWordSizeForApprox2;
protected Boolean getRankingInfo;
protected Boolean ignorePlural;
protected Integer distinct;
protected Boolean advancedSyntax;
protected Integer page;
protected Integer hitsPerPage;
protected String restrictSearchableAttributes;
protected String tags;
protected String filters;
protected String highlightPreTag;
protected String highlightPostTag;
protected String snippetEllipsisText;
protected Integer minProximity;
protected String numerics;
protected String insideBoundingBox;
protected String insidePolygon;
protected String aroundLatLong;
protected Boolean aroundLatLongViaIP;
protected String query;
protected String similarQuery;
protected QueryType queryType;
protected String optionalWords;
protected String facets;
protected String facetFilters;
protected Integer maxNumberOfFacets;
protected Boolean analytics;
protected Boolean synonyms;
protected Boolean replaceSynonyms;
protected Boolean allowTyposOnNumericTokens;
protected RemoveWordsType removeWordsIfNoResult;
protected TypoTolerance typoTolerance;
protected String analyticsTags;
protected int aroundPrecision;
protected int aroundRadius;
protected Boolean removeStopWords;
protected String userToken;
protected String referers;
protected Integer validUntil;
protected String restrictIndices;
public Query(String query) {
minWordSizeForApprox1 = null;
minWordSizeForApprox2 = null;
getRankingInfo = null;
ignorePlural = null;
distinct = null;
page = null;
minProximity = null;
hitsPerPage = null;
this.query = query;
this.similarQuery = null;
queryType = QueryType.PREFIX_NOTSET;
maxNumberOfFacets = null;
advancedSyntax = null;
removeStopWords = null;
analytics = synonyms = replaceSynonyms = allowTyposOnNumericTokens = null;
analyticsTags = null;
typoTolerance = TypoTolerance.TYPO_NOTSET;
removeWordsIfNoResult = RemoveWordsType.REMOVE_NOTSET;
aroundPrecision = aroundRadius = 0;
userToken = referers = null;
validUntil = null;
restrictIndices = null;
}
public Query() {
this((String) null);
}
public Query(Query other) {
if (other.noTypoToleranceOn != null) {
noTypoToleranceOn = new ArrayList<String>(other.noTypoToleranceOn);
}
if (other.attributesToHighlight != null) {
attributesToHighlight = new ArrayList<String>(other.attributesToHighlight);
}
if (other.attributes != null) {
attributes = new ArrayList<String>(other.attributes);
}
if (other.attributesToSnippet != null) {
attributesToSnippet = new ArrayList<String>(other.attributesToSnippet);
}
minWordSizeForApprox1 = other.minWordSizeForApprox1;
minWordSizeForApprox2 = other.minWordSizeForApprox2;
getRankingInfo = other.getRankingInfo;
ignorePlural = other.ignorePlural;
minProximity = other.minProximity;
highlightPreTag = other.highlightPreTag;
highlightPostTag = other.highlightPostTag;
snippetEllipsisText = other.snippetEllipsisText;
distinct = other.distinct;
advancedSyntax = other.advancedSyntax;
removeStopWords = other.removeStopWords;
page = other.page;
hitsPerPage = other.hitsPerPage;
restrictSearchableAttributes = other.restrictSearchableAttributes;
tags = other.tags;
numerics = other.numerics;
insideBoundingBox = other.insideBoundingBox;
insidePolygon = other.insidePolygon;
aroundRadius = other.aroundRadius;
aroundPrecision = other.aroundPrecision;
aroundLatLong = other.aroundLatLong;
aroundLatLongViaIP = other.aroundLatLongViaIP;
query = other.query;
similarQuery = other.similarQuery;
queryType = other.queryType;
optionalWords = other.optionalWords;
facets = other.facets;
facetFilters = other.facetFilters;
filters = other.filters;
maxNumberOfFacets = other.maxNumberOfFacets;
analytics = other.analytics;
analyticsTags = other.analyticsTags;
synonyms = other.synonyms;
replaceSynonyms = other.replaceSynonyms;
typoTolerance = other.typoTolerance;
allowTyposOnNumericTokens = other.allowTyposOnNumericTokens;
removeWordsIfNoResult = other.removeWordsIfNoResult;
referers = other.referers;
userToken = other.userToken;
validUntil = other.validUntil;
restrictIndices = other.restrictIndices;
}
/**
* Select the strategy to adopt when a query does not return any result.
*/
public Query removeWordsIfNoResult(RemoveWordsType type) {
this.removeWordsIfNoResult = type;
return this;
}
/**
* List of object attributes you want to use for textual search (must be a
* subset of the attributesToIndex index setting). Attributes are separated
* with a comma (for example @"name,address"). You can also use a JSON
* string array encoding (for example
* encodeURIComponent("[\"name\",\"address\"]")). By default, all attributes
* specified in attributesToIndex settings are used to search.
*/
public Query restrictSearchableAttributes(String attributes) {
this.restrictSearchableAttributes = attributes;
return this;
}
/**
* Select how the query words are interpreted:
*/
public Query setQueryType(QueryType type) {
this.queryType = type;
return this;
}
/**
* Set the full text query
*/
public Query setQueryString(String query) {
this.query = query;
return this;
}
/**
* Set the full text similar query string
*/
public Query setSimilarQueryString(String query) {
this.similarQuery = query;
return this;
}
/**
* Specify the list of attribute names to retrieve. By default all
* attributes are retrieved.
*/
public Query setAttributesToRetrieve(List<String> attributes) {
this.attributes = attributes;
return this;
}
/**
* Specify the list of attribute names to highlight. By default indexed
* attributes are highlighted.
*/
public Query setAttributesToHighlight(List<String> attributes) {
this.attributesToHighlight = attributes;
return this;
}
/*
* List of attributes on which you want to disable typo tolerance (must be a subset of the attributesToIndex index setting).
*/
public Query disableTypoToleranceOnAttributes(List<String> attributes) {
this.noTypoToleranceOn = attributes;
return this;
}
/**
* Specify the list of attribute names to Snippet alongside the number of
* words to return (syntax is 'attributeName:nbWords'). By default no
* snippet is computed.
*/
public Query setAttributesToSnippet(List<String> attributes) {
this.attributesToSnippet = attributes;
return this;
}
/**
* @param distinct set to true, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set. This feature
* is similar to the SQL "distinct" keyword: when enabled in a
* query with the distinct=1 parameter, all hits containing a
* duplicate value for the attributeForDistinct attribute are
* removed from results. For example, if the chosen attribute is
* show_name and several hits have the same value for show_name,
* then only the best one is kept and others are removed.
*/
public Query enableDistinct(boolean distinct) {
this.distinct = distinct ? 1 : 0;
return this;
}
/**
* This feature is similar to the distinct just before but instead of
* keeping the best value per value of attributeForDistinct, it allows to
* keep N values.
*
* @param nbHitsToKeep Specify the maximum number of hits to keep for each distinct
* value
*/
public Query enableDistinct(int nbHitsToKeep) {
this.distinct = nbHitsToKeep;
return this;
}
/**
* @param enabled set to false, this query will not be taken into account in
* analytics feature. Default to true.
*/
public Query enableAnalytics(boolean enabled) {
this.analytics = enabled;
return this;
}
/**
* @param analyticsTags the analytics tags identifying the query
*/
public Query setAnalyticsTags(String analyticsTags) {
this.analyticsTags = analyticsTags;
return this;
}
/**
* @param enabled set to false, this query will not use synonyms defined in
* configuration. Default to true.
*/
public Query enableSynonyms(boolean enabled) {
this.synonyms = enabled;
return this;
}
/**
* @param enabled set to false, words matched via synonyms expansion will not be
* replaced by the matched synonym in highlight result. Default
* to true.
*/
public Query enableReplaceSynonymsInHighlight(boolean enabled) {
this.replaceSynonyms = enabled;
return this;
}
/**
* @param enabled set to false, disable typo-tolerance. Default to true.
*/
public Query enableTypoTolerance(boolean enabled) {
if (enabled) {
this.typoTolerance = TypoTolerance.TYPO_TRUE;
} else {
this.typoTolerance = TypoTolerance.TYPO_FALSE;
}
return this;
}
/**
* @param typoTolerance option allow to control the number of typo in the results set.
*/
public Query setTypoTolerance(TypoTolerance typoTolerance) {
this.typoTolerance = typoTolerance;
return this;
}
/**
* Specify the minimum number of characters in a query word to accept one
* typo in this word. Defaults to 3.
*/
public Query setMinWordSizeToAllowOneTypo(int nbChars) {
minWordSizeForApprox1 = nbChars;
return this;
}
/*
* Configure the precision of the proximity ranking criterion. By default,
* the minimum (and best) proximity value distance between 2 matching words
* is 1. Setting it to 2 (or 3) would allow 1 (or 2) words to be found
* between the matching words without degrading the proximity ranking value.
*
* Considering the query "javascript framework", if you set minProximity=2
* the records "JavaScript framework" and "JavaScript charting framework"
* will get the same proximity score, even if the second one contains a word
* between the 2 matching words. Default to 1.
*/
public Query setMinProximity(int value) {
this.minProximity = value;
return this;
}
/*
* Specify the string that is inserted before/after the highlighted parts in
* the query result (default to "<em>" / "</em>").
*/
public Query setHighlightingTags(String preTag, String postTag) {
this.highlightPreTag = preTag;
this.highlightPostTag = postTag;
return this;
}
/**
* Specify the string that is used as an ellipsis indicator when a snippet
* is truncated (defaults to the empty string).
*/
public Query setSnippetEllipsisText(String snippetEllipsisText) {
this.snippetEllipsisText = snippetEllipsisText;
return this;
}
/**
* Specify the minimum number of characters in a query word to accept two
* typos in this word. Defaults to 7.
*/
public Query setMinWordSizeToAllowTwoTypos(int nbChars) {
minWordSizeForApprox2 = nbChars;
return this;
}
/**
* @param enabled set to false, disable typo-tolerance on numeric tokens.
* Default to true.
*/
public Query enableTyposOnNumericTokens(boolean enabled) {
this.allowTyposOnNumericTokens = enabled;
return this;
}
/**
* if set, the result hits will contain ranking information in _rankingInfo
* attribute.
*/
public Query getRankingInfo(boolean enabled) {
getRankingInfo = enabled;
return this;
}
/**
* If set to true, plural won't be considered as a typo (for example
* car/cars will be considered as equals). Default to false.
*/
public Query ignorePlural(boolean enabled) {
ignorePlural = enabled;
return this;
}
/**
* Set the page to retrieve (zero base). Defaults to 0.
*/
public Query setPage(int page) {
this.page = page;
return this;
}
/**
* Set the number of hits per page. Defaults to 10.
*/
public Query setHitsPerPage(int nbHitsPerPage) {
this.hitsPerPage = nbHitsPerPage;
return this;
}
/**
* Set the number of hits per page. Defaults to 10.
*
* @deprecated Use {@code setHitsPerPage}
*/
@Deprecated
public Query setNbHitsPerPage(int nbHitsPerPage) {
return setHitsPerPage(nbHitsPerPage);
}
/**
* Set the userToken used as identifier for the ratelimit
*/
public Query setUserToken(String userToken) {
this.userToken = userToken;
return this;
}
/**
* Set the referers used to restrict the query from a specific website. Works only on HTTP.
*/
public Query setReferers(String referers) {
this.referers = referers;
return this;
}
/**
* Search for entries around a given latitude/longitude with an automatic radius computed depending of the density of the area.
*/
public Query aroundLatitudeLongitude(float latitude, float longitude) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude;
return this;
}
/**
* Search for entries around a given latitude/longitude.
*
* @param radius set the maximum distance in meters. Note: at indexing, geoloc
* of an object should be set with _geoloc attribute containing
* lat and lng attributes (for example
* {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude;
aroundRadius = radius;
return this;
}
/**
* Change the radius or around latitude/longitude query
*/
public Query setAroundRadius(int radius) {
aroundRadius = radius;
return this;
}
/**
* Change the precision or around latitude/longitude query
*/
public Query setAroundPrecision(int precision) {
aroundPrecision = precision;
return this;
}
/**
* Search for entries around a given latitude/longitude.
*
* @param radius set the maximum distance in meters (manually defined)
* @param precision set the precision for ranking (for example if you set
* precision=100, two objects that are distant of less than 100m
* will be considered as identical for "geo" ranking parameter).
* Note: at indexing, geoloc of an object should be set with
* _geoloc attribute containing lat and lng attributes (for
* example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius, int precision) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude;
aroundRadius = radius;
aroundPrecision = precision;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP
* geolocation) with an automatic radius depending on area density
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled) {
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP
* geolocation)
*
* @param radius set the maximum distance in meters manually
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius) {
aroundRadius = radius;
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP
* geolocation)
*
* @param radius set the maximum distance in meters.
* @param precision set the precision for ranking (for example if you set
* precision=100, two objects that are distant of less than 100m
* will be considered as identical for "geo" ranking parameter).
* Note: at indexing, geoloc of an object should be set with
* _geoloc attribute containing lat and lng attributes (for
* example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius, int precision) {
aroundRadius = radius;
aroundPrecision = precision;
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries inside a given area defined by the two extreme points of a rectangle.
* At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form "_geoloc":{"lat":48.853409, "lng":2.348800} or
* "_geoloc":[{"lat":48.853409, "lng":2.348800},{"lat":48.547456, "lng":2.972075}] if you have several geo-locations in your record).
* <p>
* You can use several bounding boxes (OR) by calling this method several times.
*/
public Query insideBoundingBox(float latitudeP1, float longitudeP1, float latitudeP2, float longitudeP2) {
if (insideBoundingBox == null) {
insideBoundingBox = "insideBoundingBox=" + latitudeP1 + "," + longitudeP1 + "," + latitudeP2 + "," + longitudeP2;
} else if (insideBoundingBox.length() > 18) {
insideBoundingBox += "," + latitudeP1 + "," + longitudeP1 + "," + latitudeP2 + "," + longitudeP2;
}
return this;
}
/**
* Add a point to the polygon of geo-search (requires a minimum of three points to define a valid polygon)
* At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form "_geoloc":{"lat":48.853409, "lng":2.348800} or
* "_geoloc":[{"lat":48.853409, "lng":2.348800},{"lat":48.547456, "lng":2.972075}] if you have several geo-locations in your record).
*/
public Query addInsidePolygon(float latitude, float longitude) {
if (insidePolygon == null) {
insidePolygon = "insidePolygon=" + latitude + "," + longitude;
} else if (insidePolygon.length() > 14) {
insidePolygon += "," + latitude + "," + longitude;
}
return this;
}
/**
* Set the list of words that should be considered as optional when found in
* the query.
*
* @param words The list of optional words, comma separated.
*/
public Query setOptionalWords(String words) {
this.optionalWords = words;
return this;
}
/**
* Set the list of words that should be considered as optional when found in
* the query.
*
* @param words The list of optional words.
*/
public Query setOptionalWords(List<String> words) {
StringBuilder builder = new StringBuilder();
for (String word : words) {
builder.append(word);
builder.append(",");
}
this.optionalWords = builder.toString();
return this;
}
/**
* Filter the query with numeric, facet or/and tag filters.
* The syntax is a SQL like syntax, you can use the OR and AND keywords.
* The syntax for the underlying numeric, facet and tag filters is the same than in the other filters:
* available=1 AND (category:Book OR NOT category:Ebook) AND public
* date: 1441745506 TO 1441755506 AND inStock > 0 AND author:"John Doe"
* The list of keywords is:
* OR: create a disjunctive filter between two filters.
* AND: create a conjunctive filter between two filters.
* TO: used to specify a range for a numeric filter.
* NOT: used to negate a filter. The syntax with the ‘-‘ isn’t allowed.
*/
public Query setFilters(String filters) {
this.filters = filters;
return this;
}
/**
* Filter the query by a list of facets. Each filter is encoded as
* `attributeName:value`.
*/
public Query setFacetFilters(List<String> facets) {
JSONArray obj = new JSONArray();
for (String facet : facets) {
obj.put(facet);
}
this.facetFilters = obj.toString();
return this;
}
/**
* Filter the query by a list of facets. Filters are separated by commas and
* each facet is encoded as `attributeName:value`. To OR facets, you must
* add parentheses. For example:
* `(category:Book,category:Movie),author:John%20Doe`. You can also use a
* JSON string array encoding, for example
* `[[\"category:Book\",\"category:Movie\"],\"author:John Doe\"]`.
*/
public Query setFacetFilters(String facetFilters) {
this.facetFilters = facetFilters;
return this;
}
/**
* List of object attributes that you want to use for faceting. <br/>
* Only attributes that have been added in **attributesForFaceting** index
* setting can be used in this parameter. You can also use `*` to perform
* faceting on all attributes specified in **attributesForFaceting**.
*/
public Query setFacets(List<String> facets) {
JSONArray obj = new JSONArray();
for (String facet : facets) {
obj.put(facet);
}
this.facets = obj.toString();
return this;
}
/**
* Limit the number of facet values returned for each facet.
*/
public Query setMaxNumberOfFacets(int n) {
this.maxNumberOfFacets = n;
return this;
}
/**
* Filter the query by a set of tags. You can AND tags by separating them by
* commas. To OR tags, you must add parentheses. For example
* tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). At indexing, tags should
* be added in the _tags attribute of objects (for example
* {"_tags":["tag1","tag2"]} )
*/
public Query setTagFilters(String tags) {
this.tags = tags;
return this;
}
/**
* Add a list of numeric filters separated by a comma. The syntax of one
* filter is `attributeName` followed by `operand` followed by `value.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`. You can have
* multiple conditions on one attribute like for example
* `numerics=price>100,price<1000`.
*/
public Query setNumericFilters(String numerics) {
this.numerics = numerics;
return this;
}
/**
* Add a list of numeric filters separated by a comma. The syntax of one
* filter is `attributeName` followed by `operand` followed by `value.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`. You can have
* multiple conditions on one attribute like for example
* `numerics=price>100,price<1000`.
*/
public Query setNumericFilters(List<String> numerics) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String n : numerics) {
if (!first)
builder.append(",");
builder.append(n);
first = false;
}
this.numerics = builder.toString();
return this;
}
/**
* Enable the removal of stop words. Defaults to false
*/
public Query enableRemoveStopWords(boolean removeStopWords) {
this.removeStopWords = removeStopWords;
return this;
}
/**
* Enable the advanced query syntax. Defaults to false. - Phrase query: a
* phrase query defines a particular sequence of terms. A phrase query is
* build by Algolia's query parser for words surrounded by ". For example,
* "search engine" will retrieve records having search next to engine only.
* Typo-tolerance is disabled on phrase queries. - Prohibit operator: The
* prohibit operator excludes records that contain the term after the -
* symbol. For example search -engine will retrieve records containing
* search but not engine.
*/
public Query enableAvancedSyntax(boolean advancedSyntax) {
this.advancedSyntax = advancedSyntax;
return this;
}
public Query setValidUntil(Integer timestamp) {
this.validUntil = timestamp;
return this;
}
public Query setRestrictIndicies(String indices) {
this.restrictIndices = indices;
return this;
}
private StringBuilder append(StringBuilder stringBuilder, String key, List<String> values) throws UnsupportedEncodingException {
if (values != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(key).append("=");
boolean first = true;
for (String attr : values) {
if (!first) {
stringBuilder.append(',');
}
stringBuilder.append(URLEncoder.encode(attr, "UTF-8"));
first = false;
}
}
return stringBuilder;
}
private StringBuilder append(StringBuilder stringBuilder, String key, String value) {
if (value != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(key).append("=").append(value);
}
return stringBuilder;
}
private StringBuilder appendWithEncoding(StringBuilder stringBuilder, String key, String value) throws UnsupportedEncodingException {
if (value != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
}
return stringBuilder;
}
private StringBuilder append(StringBuilder stringBuilder, String key, Integer value) {
if (value != null && value > 0) {
return append(stringBuilder, key, value.toString());
}
return stringBuilder;
}
private StringBuilder append(StringBuilder stringBuilder, String key, Boolean value) {
if (value != null) {
return append(stringBuilder, key, value ? "1" : "0");
}
return stringBuilder;
}
protected String getQueryString() {
StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder = append(stringBuilder, "attributes", attributes);
stringBuilder = append(stringBuilder, "disableTypoToleranceOnAttributes", noTypoToleranceOn);
stringBuilder = append(stringBuilder, "attributesToHighlight", attributesToHighlight);
stringBuilder = append(stringBuilder, "attributesToSnippet", attributesToSnippet);
if (typoTolerance != TypoTolerance.TYPO_NOTSET) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("typoTolerance=");
switch (typoTolerance) {
case TYPO_FALSE:
stringBuilder.append("false");
break;
case TYPO_MIN:
stringBuilder.append("min");
break;
case TYPO_STRICT:
stringBuilder.append("strict");
break;
case TYPO_TRUE:
stringBuilder.append("true");
break;
case TYPO_NOTSET:
throw new IllegalStateException("code not reachable");
}
}
stringBuilder = append(stringBuilder, "allowTyposOnNumericTokens", allowTyposOnNumericTokens);
stringBuilder = append(stringBuilder, "minWordSizefor1Typo", minWordSizeForApprox1);
stringBuilder = append(stringBuilder, "minWordSizefor2Typos", minWordSizeForApprox2);
switch (removeWordsIfNoResult) {
case REMOVE_LAST_WORDS:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=LastWords");
break;
case REMOVE_FIRST_WORDS:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=FirstWords");
break;
case REMOVE_ALLOPTIONAL:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=allOptional");
break;
case REMOVE_NONE:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=none");
break;
case REMOVE_NOTSET:
// Nothing to do
break;
}
stringBuilder = append(stringBuilder, "getRankingInfo", getRankingInfo);
stringBuilder = append(stringBuilder, "ignorePlural", ignorePlural);
stringBuilder = append(stringBuilder, "analytics", analytics);
stringBuilder = append(stringBuilder, "analyticsTags", analyticsTags);
stringBuilder = append(stringBuilder, "synonyms", synonyms);
stringBuilder = append(stringBuilder, "replaceSynonymsInHighlight", replaceSynonyms);
stringBuilder = append(stringBuilder, "distinct", distinct);
stringBuilder = append(stringBuilder, "removeStopWords", removeStopWords);
stringBuilder = append(stringBuilder, "advancedSyntax", advancedSyntax);
stringBuilder = append(stringBuilder, "page", page);
stringBuilder = append(stringBuilder, "minProximity", minProximity);
if (highlightPreTag != null && highlightPostTag != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("highlightPreTag=");
stringBuilder.append(highlightPreTag);
stringBuilder.append("&highlightPostTag=");
stringBuilder.append(highlightPostTag);
}
if (snippetEllipsisText != null) {
appendWithEncoding(stringBuilder, "snippetEllipsisText", snippetEllipsisText);
}
stringBuilder = append(stringBuilder, "hitsPerPage", hitsPerPage);
stringBuilder = appendWithEncoding(stringBuilder, "tagFilters", tags);
stringBuilder = appendWithEncoding(stringBuilder, "numericFilters", numerics);
if (insideBoundingBox != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(insideBoundingBox);
} else if (aroundLatLong != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(aroundLatLong);
} else if (insidePolygon != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(insidePolygon);
}
stringBuilder = append(stringBuilder, "aroundLatLongViaIP", aroundLatLongViaIP);
stringBuilder = append(stringBuilder, "aroundRadius", aroundRadius);
stringBuilder = append(stringBuilder, "aroundPrecision", aroundPrecision);
stringBuilder = appendWithEncoding(stringBuilder, "query", query);
stringBuilder = appendWithEncoding(stringBuilder, "similarQuery", similarQuery);
stringBuilder = appendWithEncoding(stringBuilder, "facets", facets);
stringBuilder = appendWithEncoding(stringBuilder, "filters", filters);
stringBuilder = appendWithEncoding(stringBuilder, "facetFilters", facetFilters);
stringBuilder = append(stringBuilder, "maxNumberOfFacets", maxNumberOfFacets);
stringBuilder = appendWithEncoding(stringBuilder, "optionalWords", optionalWords);
stringBuilder = appendWithEncoding(stringBuilder, "restrictSearchableAttributes", restrictSearchableAttributes);
switch (queryType) {
case PREFIX_ALL:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("queryType=prefixAll");
break;
case PREFIX_LAST:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("queryType=prefixLast");
break;
case PREFIX_NONE:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("queryType=prefixNone");
break;
default:
//Do nothing
break;
}
stringBuilder = appendWithEncoding(stringBuilder, "referer", referers);
stringBuilder = appendWithEncoding(stringBuilder, "userToken", userToken);
stringBuilder = append(stringBuilder, "validUntil", validUntil);
stringBuilder = appendWithEncoding(stringBuilder, "restrictIndices", restrictIndices);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return stringBuilder.toString();
}
/**
* @return the attributes
*/
public List<String> getAttributes() {
return attributes;
}
/**
* @return the attributesToHighlight
*/
public List<String> getAttributesToHighlight() {
return attributesToHighlight;
}
/**
* @return the attributesToSnippet
*/
public List<String> getAttributesToSnippet() {
return attributesToSnippet;
}
/**
* @return the minWordSizeForApprox1
*/
public Integer getMinWordSizeForApprox1() {
return minWordSizeForApprox1;
}
/**
* @return the minWordSizeForApprox2
*/
public Integer getMinWordSizeForApprox2() {
return minWordSizeForApprox2;
}
/**
* @return the getRankingInfo
*/
public Boolean isGetRankingInfo() {
return getRankingInfo;
}
/**
* @return the ignorePlural
*/
public Boolean isIgnorePlural() {
return ignorePlural;
}
/**
* @return the distinct
*/
public Boolean isDistinct() {
return distinct > 0;
}
/**
* @return the distinct
*/
public Integer getDistinct() {
return distinct;
}
/**
* @return the advancedSyntax
*/
public Boolean isAdvancedSyntax() {
return advancedSyntax;
}
/**
* @return the page
*/
public Integer getPage() {
return page;
}
/**
* @return the hitsPerPage
*/
public Integer getHitsPerPage() {
return hitsPerPage;
}
/**
* @return the restrictSearchableAttributes
*/
public String getRestrictSearchableAttributes() {
return restrictSearchableAttributes;
}
/**
* @return the tags
*/
public String getTags() {
return tags;
}
/**
* @return the numerics
*/
public String getNumerics() {
return numerics;
}
/**
* @return the insideBoundingBox
*/
public String getInsideBoundingBox() {
return insideBoundingBox;
}
/**
* @return the aroundLatLong
*/
public String getAroundLatLong() {
return aroundLatLong;
}
/**
* @return the aroundLatLongViaIP
*/
public Boolean isAroundLatLongViaIP() {
return aroundLatLongViaIP;
}
/**
* @return the query
*/
public String getQuery() {
return query;
}
/**
* @return the similar query
*/
public String getSimilarQuery() {
return similarQuery;
}
/**
* @return the queryType
*/
public QueryType getQueryType() {
return queryType;
}
/**
* @return the optionalWords
*/
public String getOptionalWords() {
return optionalWords;
}
/**
* @return the facets
*/
public String getFacets() {
return facets;
}
/**
* @return the filters
*/
public String getFilters() {
return filters;
}
/**
* @return the facetFilters
*/
public String getFacetFilters() {
return facetFilters;
}
/**
* @return the maxNumberOfFacets
*/
public Integer getMaxNumberOfFacets() {
return maxNumberOfFacets;
}
/**
* @return the analytics
*/
public Boolean isAnalytics() {
return analytics;
}
/**
* @return the analytics tags
*/
public String getAnalyticsTags() {
return analyticsTags;
}
/**
* @return the synonyms
*/
public Boolean isSynonyms() {
return synonyms;
}
/**
* @return the replaceSynonyms
*/
public Boolean isReplaceSynonyms() {
return replaceSynonyms;
}
/**
* @return the allowTyposOnNumericTokens
*/
public Boolean isAllowTyposOnNumericTokens() {
return allowTyposOnNumericTokens;
}
/**
* @return the removeWordsIfNoResult
*/
public RemoveWordsType getRemoveWordsIfNoResult() {
return removeWordsIfNoResult;
}
/**
* @return the typoTolerance
*/
public TypoTolerance getTypoTolerance() {
return typoTolerance;
}
/**
* @return the validity used for ephemeral API Keys
*/
public Integer getValidUntil() {
return validUntil;
}
/**
* @return The list of indices allowed
*/
public String getRestrictIndices() {
return restrictIndices;
}
}
| src/main/java/com/algolia/search/saas/Query.java | package com.algolia.search.saas;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
/*
* Copyright (c) 2015 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
public class Query {
public enum QueryType {
// / all query words are interpreted as prefixes.
PREFIX_ALL,
// / only the last word is interpreted as a prefix (default behavior).
PREFIX_LAST,
// / no query word is interpreted as a prefix. This option is not
// recommended.
PREFIX_NONE,
// The parameter isn't set
PREFIX_NOTSET
}
public enum RemoveWordsType {
// / when a query does not return any result, the final word will be
// removed until there is results. This option is particulary useful on
// e-commerce websites
REMOVE_LAST_WORDS,
// / when a query does not return any result, the first word will be
// removed until there is results. This option is useful on adress
// search.
REMOVE_FIRST_WORDS,
// / No specific processing is done when a query does not return any
// result.
REMOVE_NONE,
// / When a query does not return any result, a second trial will be
// made with all words as optional (which is equivalent to transforming
// the AND operand between query terms in a OR operand)
REMOVE_ALLOPTIONAL,
// The parameter isn't set
REMOVE_NOTSET
}
public enum TypoTolerance {
// / the typotolerance is enabled and all typos are retrieved. (Default
// behavior)
TYPO_TRUE,
// / the typotolerance is disabled.
TYPO_FALSE,
// / only keep results with the minimum number of typos.
TYPO_MIN,
// / the typotolerance with a distance=2 is disabled if the results
// contain hits without typo.
TYPO_STRICT,
// The parameter isn't set
TYPO_NOTSET
}
protected List<String> attributes;
protected List<String> attributesToHighlight;
protected List<String> attributesToSnippet;
protected List<String> noTypoToleranceOn;
protected Integer minWordSizeForApprox1;
protected Integer minWordSizeForApprox2;
protected Boolean getRankingInfo;
protected Boolean ignorePlural;
protected Integer distinct;
protected Boolean advancedSyntax;
protected Integer page;
protected Integer hitsPerPage;
protected String restrictSearchableAttributes;
protected String tags;
protected String filters;
protected String highlightPreTag;
protected String highlightPostTag;
protected String snippetEllipsisText;
protected Integer minProximity;
protected String numerics;
protected String insideBoundingBox;
protected String insidePolygon;
protected String aroundLatLong;
protected Boolean aroundLatLongViaIP;
protected String query;
protected String similarQuery;
protected QueryType queryType;
protected String optionalWords;
protected String facets;
protected String facetFilters;
protected Integer maxNumberOfFacets;
protected Boolean analytics;
protected Boolean synonyms;
protected Boolean replaceSynonyms;
protected Boolean allowTyposOnNumericTokens;
protected RemoveWordsType removeWordsIfNoResult;
protected TypoTolerance typoTolerance;
protected String analyticsTags;
protected int aroundPrecision;
protected int aroundRadius;
protected Boolean removeStopWords;
protected String userToken;
protected String referers;
public Query(String query) {
minWordSizeForApprox1 = null;
minWordSizeForApprox2 = null;
getRankingInfo = null;
ignorePlural = null;
distinct = null;
page = null;
minProximity = null;
hitsPerPage = null;
this.query = query;
this.similarQuery = null;
queryType = QueryType.PREFIX_NOTSET;
maxNumberOfFacets = null;
advancedSyntax = null;
removeStopWords = null;
analytics = synonyms = replaceSynonyms = allowTyposOnNumericTokens = null;
analyticsTags = null;
typoTolerance = TypoTolerance.TYPO_NOTSET;
removeWordsIfNoResult = RemoveWordsType.REMOVE_NOTSET;
aroundPrecision = aroundRadius = 0;
userToken = referers = null;
}
public Query() {
this((String) null);
}
public Query(Query other) {
if (other.noTypoToleranceOn != null) {
noTypoToleranceOn = new ArrayList<String>(other.noTypoToleranceOn);
}
if (other.attributesToHighlight != null) {
attributesToHighlight = new ArrayList<String>(other.attributesToHighlight);
}
if (other.attributes != null) {
attributes = new ArrayList<String>(other.attributes);
}
if (other.attributesToSnippet != null) {
attributesToSnippet = new ArrayList<String>(other.attributesToSnippet);
}
minWordSizeForApprox1 = other.minWordSizeForApprox1;
minWordSizeForApprox2 = other.minWordSizeForApprox2;
getRankingInfo = other.getRankingInfo;
ignorePlural = other.ignorePlural;
minProximity = other.minProximity;
highlightPreTag = other.highlightPreTag;
highlightPostTag = other.highlightPostTag;
snippetEllipsisText = other.snippetEllipsisText;
distinct = other.distinct;
advancedSyntax = other.advancedSyntax;
removeStopWords = other.removeStopWords;
page = other.page;
hitsPerPage = other.hitsPerPage;
restrictSearchableAttributes = other.restrictSearchableAttributes;
tags = other.tags;
numerics = other.numerics;
insideBoundingBox = other.insideBoundingBox;
insidePolygon = other.insidePolygon;
aroundRadius = other.aroundRadius;
aroundPrecision = other.aroundPrecision;
aroundLatLong = other.aroundLatLong;
aroundLatLongViaIP = other.aroundLatLongViaIP;
query = other.query;
similarQuery = other.similarQuery;
queryType = other.queryType;
optionalWords = other.optionalWords;
facets = other.facets;
facetFilters = other.facetFilters;
filters = other.filters;
maxNumberOfFacets = other.maxNumberOfFacets;
analytics = other.analytics;
analyticsTags = other.analyticsTags;
synonyms = other.synonyms;
replaceSynonyms = other.replaceSynonyms;
typoTolerance = other.typoTolerance;
allowTyposOnNumericTokens = other.allowTyposOnNumericTokens;
removeWordsIfNoResult = other.removeWordsIfNoResult;
referers = other.referers;
userToken = other.userToken;
}
/**
* Select the strategy to adopt when a query does not return any result.
*/
public Query removeWordsIfNoResult(RemoveWordsType type) {
this.removeWordsIfNoResult = type;
return this;
}
/**
* List of object attributes you want to use for textual search (must be a
* subset of the attributesToIndex index setting). Attributes are separated
* with a comma (for example @"name,address"). You can also use a JSON
* string array encoding (for example
* encodeURIComponent("[\"name\",\"address\"]")). By default, all attributes
* specified in attributesToIndex settings are used to search.
*/
public Query restrictSearchableAttributes(String attributes) {
this.restrictSearchableAttributes = attributes;
return this;
}
/**
* Select how the query words are interpreted:
*/
public Query setQueryType(QueryType type) {
this.queryType = type;
return this;
}
/**
* Set the full text query
*/
public Query setQueryString(String query) {
this.query = query;
return this;
}
/**
* Set the full text similar query string
*/
public Query setSimilarQueryString(String query) {
this.similarQuery = query;
return this;
}
/**
* Specify the list of attribute names to retrieve. By default all
* attributes are retrieved.
*/
public Query setAttributesToRetrieve(List<String> attributes) {
this.attributes = attributes;
return this;
}
/**
* Specify the list of attribute names to highlight. By default indexed
* attributes are highlighted.
*/
public Query setAttributesToHighlight(List<String> attributes) {
this.attributesToHighlight = attributes;
return this;
}
/*
* List of attributes on which you want to disable typo tolerance (must be a subset of the attributesToIndex index setting).
*/
public Query disableTypoToleranceOnAttributes(List<String> attributes) {
this.noTypoToleranceOn = attributes;
return this;
}
/**
* Specify the list of attribute names to Snippet alongside the number of
* words to return (syntax is 'attributeName:nbWords'). By default no
* snippet is computed.
*/
public Query setAttributesToSnippet(List<String> attributes) {
this.attributesToSnippet = attributes;
return this;
}
/**
* @param distinct set to true, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set. This feature
* is similar to the SQL "distinct" keyword: when enabled in a
* query with the distinct=1 parameter, all hits containing a
* duplicate value for the attributeForDistinct attribute are
* removed from results. For example, if the chosen attribute is
* show_name and several hits have the same value for show_name,
* then only the best one is kept and others are removed.
*/
public Query enableDistinct(boolean distinct) {
this.distinct = distinct ? 1 : 0;
return this;
}
/**
* This feature is similar to the distinct just before but instead of
* keeping the best value per value of attributeForDistinct, it allows to
* keep N values.
*
* @param nbHitsToKeep Specify the maximum number of hits to keep for each distinct
* value
*/
public Query enableDistinct(int nbHitsToKeep) {
this.distinct = nbHitsToKeep;
return this;
}
/**
* @param enabled set to false, this query will not be taken into account in
* analytics feature. Default to true.
*/
public Query enableAnalytics(boolean enabled) {
this.analytics = enabled;
return this;
}
/**
* @param analyticsTags the analytics tags identifying the query
*/
public Query setAnalyticsTags(String analyticsTags) {
this.analyticsTags = analyticsTags;
return this;
}
/**
* @param enabled set to false, this query will not use synonyms defined in
* configuration. Default to true.
*/
public Query enableSynonyms(boolean enabled) {
this.synonyms = enabled;
return this;
}
/**
* @param enabled set to false, words matched via synonyms expansion will not be
* replaced by the matched synonym in highlight result. Default
* to true.
*/
public Query enableReplaceSynonymsInHighlight(boolean enabled) {
this.replaceSynonyms = enabled;
return this;
}
/**
* @param enabled set to false, disable typo-tolerance. Default to true.
*/
public Query enableTypoTolerance(boolean enabled) {
if (enabled) {
this.typoTolerance = TypoTolerance.TYPO_TRUE;
} else {
this.typoTolerance = TypoTolerance.TYPO_FALSE;
}
return this;
}
/**
* @param typoTolerance option allow to control the number of typo in the results set.
*/
public Query setTypoTolerance(TypoTolerance typoTolerance) {
this.typoTolerance = typoTolerance;
return this;
}
/**
* Specify the minimum number of characters in a query word to accept one
* typo in this word. Defaults to 3.
*/
public Query setMinWordSizeToAllowOneTypo(int nbChars) {
minWordSizeForApprox1 = nbChars;
return this;
}
/*
* Configure the precision of the proximity ranking criterion. By default,
* the minimum (and best) proximity value distance between 2 matching words
* is 1. Setting it to 2 (or 3) would allow 1 (or 2) words to be found
* between the matching words without degrading the proximity ranking value.
*
* Considering the query "javascript framework", if you set minProximity=2
* the records "JavaScript framework" and "JavaScript charting framework"
* will get the same proximity score, even if the second one contains a word
* between the 2 matching words. Default to 1.
*/
public Query setMinProximity(int value) {
this.minProximity = value;
return this;
}
/*
* Specify the string that is inserted before/after the highlighted parts in
* the query result (default to "<em>" / "</em>").
*/
public Query setHighlightingTags(String preTag, String postTag) {
this.highlightPreTag = preTag;
this.highlightPostTag = postTag;
return this;
}
/**
* Specify the string that is used as an ellipsis indicator when a snippet
* is truncated (defaults to the empty string).
*/
public Query setSnippetEllipsisText(String snippetEllipsisText) {
this.snippetEllipsisText = snippetEllipsisText;
return this;
}
/**
* Specify the minimum number of characters in a query word to accept two
* typos in this word. Defaults to 7.
*/
public Query setMinWordSizeToAllowTwoTypos(int nbChars) {
minWordSizeForApprox2 = nbChars;
return this;
}
/**
* @param enabled set to false, disable typo-tolerance on numeric tokens.
* Default to true.
*/
public Query enableTyposOnNumericTokens(boolean enabled) {
this.allowTyposOnNumericTokens = enabled;
return this;
}
/**
* if set, the result hits will contain ranking information in _rankingInfo
* attribute.
*/
public Query getRankingInfo(boolean enabled) {
getRankingInfo = enabled;
return this;
}
/**
* If set to true, plural won't be considered as a typo (for example
* car/cars will be considered as equals). Default to false.
*/
public Query ignorePlural(boolean enabled) {
ignorePlural = enabled;
return this;
}
/**
* Set the page to retrieve (zero base). Defaults to 0.
*/
public Query setPage(int page) {
this.page = page;
return this;
}
/**
* Set the number of hits per page. Defaults to 10.
*/
public Query setHitsPerPage(int nbHitsPerPage) {
this.hitsPerPage = nbHitsPerPage;
return this;
}
/**
* Set the number of hits per page. Defaults to 10.
*
* @deprecated Use {@code setHitsPerPage}
*/
@Deprecated
public Query setNbHitsPerPage(int nbHitsPerPage) {
return setHitsPerPage(nbHitsPerPage);
}
/**
* Set the userToken used as identifier for the ratelimit
*/
public Query setUserToken(String userToken) {
this.userToken = userToken;
return this;
}
/**
* Set the referers used to restrict the query from a specific website. Works only on HTTP.
*/
public Query setReferers(String referers) {
this.referers = referers;
return this;
}
/**
* Search for entries around a given latitude/longitude with an automatic radius computed depending of the density of the area.
*/
public Query aroundLatitudeLongitude(float latitude, float longitude) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude;
return this;
}
/**
* Search for entries around a given latitude/longitude.
*
* @param radius set the maximum distance in meters. Note: at indexing, geoloc
* of an object should be set with _geoloc attribute containing
* lat and lng attributes (for example
* {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude;
aroundRadius = radius;
return this;
}
/**
* Change the radius or around latitude/longitude query
*/
public Query setAroundRadius(int radius) {
aroundRadius = radius;
return this;
}
/**
* Change the precision or around latitude/longitude query
*/
public Query setAroundPrecision(int precision) {
aroundPrecision = precision;
return this;
}
/**
* Search for entries around a given latitude/longitude.
*
* @param radius set the maximum distance in meters (manually defined)
* @param precision set the precision for ranking (for example if you set
* precision=100, two objects that are distant of less than 100m
* will be considered as identical for "geo" ranking parameter).
* Note: at indexing, geoloc of an object should be set with
* _geoloc attribute containing lat and lng attributes (for
* example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius, int precision) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude;
aroundRadius = radius;
aroundPrecision = precision;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP
* geolocation) with an automatic radius depending on area density
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled) {
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP
* geolocation)
*
* @param radius set the maximum distance in meters manually
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius) {
aroundRadius = radius;
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP
* geolocation)
*
* @param radius set the maximum distance in meters.
* @param precision set the precision for ranking (for example if you set
* precision=100, two objects that are distant of less than 100m
* will be considered as identical for "geo" ranking parameter).
* Note: at indexing, geoloc of an object should be set with
* _geoloc attribute containing lat and lng attributes (for
* example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius, int precision) {
aroundRadius = radius;
aroundPrecision = precision;
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries inside a given area defined by the two extreme points of a rectangle.
* At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form "_geoloc":{"lat":48.853409, "lng":2.348800} or
* "_geoloc":[{"lat":48.853409, "lng":2.348800},{"lat":48.547456, "lng":2.972075}] if you have several geo-locations in your record).
* <p>
* You can use several bounding boxes (OR) by calling this method several times.
*/
public Query insideBoundingBox(float latitudeP1, float longitudeP1, float latitudeP2, float longitudeP2) {
if (insideBoundingBox == null) {
insideBoundingBox = "insideBoundingBox=" + latitudeP1 + "," + longitudeP1 + "," + latitudeP2 + "," + longitudeP2;
} else if (insideBoundingBox.length() > 18) {
insideBoundingBox += "," + latitudeP1 + "," + longitudeP1 + "," + latitudeP2 + "," + longitudeP2;
}
return this;
}
/**
* Add a point to the polygon of geo-search (requires a minimum of three points to define a valid polygon)
* At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form "_geoloc":{"lat":48.853409, "lng":2.348800} or
* "_geoloc":[{"lat":48.853409, "lng":2.348800},{"lat":48.547456, "lng":2.972075}] if you have several geo-locations in your record).
*/
public Query addInsidePolygon(float latitude, float longitude) {
if (insidePolygon == null) {
insidePolygon = "insidePolygon=" + latitude + "," + longitude;
} else if (insidePolygon.length() > 14) {
insidePolygon += "," + latitude + "," + longitude;
}
return this;
}
/**
* Set the list of words that should be considered as optional when found in
* the query.
*
* @param words The list of optional words, comma separated.
*/
public Query setOptionalWords(String words) {
this.optionalWords = words;
return this;
}
/**
* Set the list of words that should be considered as optional when found in
* the query.
*
* @param words The list of optional words.
*/
public Query setOptionalWords(List<String> words) {
StringBuilder builder = new StringBuilder();
for (String word : words) {
builder.append(word);
builder.append(",");
}
this.optionalWords = builder.toString();
return this;
}
/**
* Filter the query with numeric, facet or/and tag filters.
* The syntax is a SQL like syntax, you can use the OR and AND keywords.
* The syntax for the underlying numeric, facet and tag filters is the same than in the other filters:
* available=1 AND (category:Book OR NOT category:Ebook) AND public
* date: 1441745506 TO 1441755506 AND inStock > 0 AND author:"John Doe"
* The list of keywords is:
* OR: create a disjunctive filter between two filters.
* AND: create a conjunctive filter between two filters.
* TO: used to specify a range for a numeric filter.
* NOT: used to negate a filter. The syntax with the ‘-‘ isn’t allowed.
*/
public Query setFilters(String filters) {
this.filters = filters;
return this;
}
/**
* Filter the query by a list of facets. Each filter is encoded as
* `attributeName:value`.
*/
public Query setFacetFilters(List<String> facets) {
JSONArray obj = new JSONArray();
for (String facet : facets) {
obj.put(facet);
}
this.facetFilters = obj.toString();
return this;
}
/**
* Filter the query by a list of facets. Filters are separated by commas and
* each facet is encoded as `attributeName:value`. To OR facets, you must
* add parentheses. For example:
* `(category:Book,category:Movie),author:John%20Doe`. You can also use a
* JSON string array encoding, for example
* `[[\"category:Book\",\"category:Movie\"],\"author:John Doe\"]`.
*/
public Query setFacetFilters(String facetFilters) {
this.facetFilters = facetFilters;
return this;
}
/**
* List of object attributes that you want to use for faceting. <br/>
* Only attributes that have been added in **attributesForFaceting** index
* setting can be used in this parameter. You can also use `*` to perform
* faceting on all attributes specified in **attributesForFaceting**.
*/
public Query setFacets(List<String> facets) {
JSONArray obj = new JSONArray();
for (String facet : facets) {
obj.put(facet);
}
this.facets = obj.toString();
return this;
}
/**
* Limit the number of facet values returned for each facet.
*/
public Query setMaxNumberOfFacets(int n) {
this.maxNumberOfFacets = n;
return this;
}
/**
* Filter the query by a set of tags. You can AND tags by separating them by
* commas. To OR tags, you must add parentheses. For example
* tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). At indexing, tags should
* be added in the _tags attribute of objects (for example
* {"_tags":["tag1","tag2"]} )
*/
public Query setTagFilters(String tags) {
this.tags = tags;
return this;
}
/**
* Add a list of numeric filters separated by a comma. The syntax of one
* filter is `attributeName` followed by `operand` followed by `value.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`. You can have
* multiple conditions on one attribute like for example
* `numerics=price>100,price<1000`.
*/
public Query setNumericFilters(String numerics) {
this.numerics = numerics;
return this;
}
/**
* Add a list of numeric filters separated by a comma. The syntax of one
* filter is `attributeName` followed by `operand` followed by `value.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`. You can have
* multiple conditions on one attribute like for example
* `numerics=price>100,price<1000`.
*/
public Query setNumericFilters(List<String> numerics) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String n : numerics) {
if (!first)
builder.append(",");
builder.append(n);
first = false;
}
this.numerics = builder.toString();
return this;
}
/**
* Enable the removal of stop words. Defaults to false
*/
public Query enableRemoveStopWords(boolean removeStopWords) {
this.removeStopWords = removeStopWords;
return this;
}
/**
* Enable the advanced query syntax. Defaults to false. - Phrase query: a
* phrase query defines a particular sequence of terms. A phrase query is
* build by Algolia's query parser for words surrounded by ". For example,
* "search engine" will retrieve records having search next to engine only.
* Typo-tolerance is disabled on phrase queries. - Prohibit operator: The
* prohibit operator excludes records that contain the term after the -
* symbol. For example search -engine will retrieve records containing
* search but not engine.
*/
public Query enableAvancedSyntax(boolean advancedSyntax) {
this.advancedSyntax = advancedSyntax;
return this;
}
private StringBuilder append(StringBuilder stringBuilder, String key, List<String> values) throws UnsupportedEncodingException {
if (values != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(key).append("=");
boolean first = true;
for (String attr : values) {
if (!first) {
stringBuilder.append(',');
}
stringBuilder.append(URLEncoder.encode(attr, "UTF-8"));
first = false;
}
}
return stringBuilder;
}
private StringBuilder append(StringBuilder stringBuilder, String key, String value) {
if (value != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(key).append("=").append(value);
}
return stringBuilder;
}
private StringBuilder appendWithEncoding(StringBuilder stringBuilder, String key, String value) throws UnsupportedEncodingException {
if (value != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
}
return stringBuilder;
}
private StringBuilder append(StringBuilder stringBuilder, String key, Integer value) {
if (value != null && value > 0) {
return append(stringBuilder, key, value.toString());
}
return stringBuilder;
}
private StringBuilder append(StringBuilder stringBuilder, String key, Boolean value) {
if (value != null) {
return append(stringBuilder, key, value ? "1" : "0");
}
return stringBuilder;
}
protected String getQueryString() {
StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder = append(stringBuilder, "attributes", attributes);
stringBuilder = append(stringBuilder, "disableTypoToleranceOnAttributes", noTypoToleranceOn);
stringBuilder = append(stringBuilder, "attributesToHighlight", attributesToHighlight);
stringBuilder = append(stringBuilder, "attributesToSnippet", attributesToSnippet);
if (typoTolerance != TypoTolerance.TYPO_NOTSET) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("typoTolerance=");
switch (typoTolerance) {
case TYPO_FALSE:
stringBuilder.append("false");
break;
case TYPO_MIN:
stringBuilder.append("min");
break;
case TYPO_STRICT:
stringBuilder.append("strict");
break;
case TYPO_TRUE:
stringBuilder.append("true");
break;
case TYPO_NOTSET:
throw new IllegalStateException("code not reachable");
}
}
stringBuilder = append(stringBuilder, "allowTyposOnNumericTokens", allowTyposOnNumericTokens);
stringBuilder = append(stringBuilder, "minWordSizefor1Typo", minWordSizeForApprox1);
stringBuilder = append(stringBuilder, "minWordSizefor2Typos", minWordSizeForApprox2);
switch (removeWordsIfNoResult) {
case REMOVE_LAST_WORDS:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=LastWords");
break;
case REMOVE_FIRST_WORDS:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=FirstWords");
break;
case REMOVE_ALLOPTIONAL:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=allOptional");
break;
case REMOVE_NONE:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("removeWordsIfNoResult=none");
break;
case REMOVE_NOTSET:
// Nothing to do
break;
}
stringBuilder = append(stringBuilder, "getRankingInfo", getRankingInfo);
stringBuilder = append(stringBuilder, "ignorePlural", ignorePlural);
stringBuilder = append(stringBuilder, "analytics", analytics);
stringBuilder = append(stringBuilder, "analyticsTags", analyticsTags);
stringBuilder = append(stringBuilder, "synonyms", synonyms);
stringBuilder = append(stringBuilder, "replaceSynonymsInHighlight", replaceSynonyms);
stringBuilder = append(stringBuilder, "distinct", distinct);
stringBuilder = append(stringBuilder, "removeStopWords", removeStopWords);
stringBuilder = append(stringBuilder, "advancedSyntax", advancedSyntax);
stringBuilder = append(stringBuilder, "page", page);
stringBuilder = append(stringBuilder, "minProximity", minProximity);
if (highlightPreTag != null && highlightPostTag != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("highlightPreTag=");
stringBuilder.append(highlightPreTag);
stringBuilder.append("&highlightPostTag=");
stringBuilder.append(highlightPostTag);
}
if (snippetEllipsisText != null) {
appendWithEncoding(stringBuilder, "snippetEllipsisText", snippetEllipsisText);
}
stringBuilder = append(stringBuilder, "hitsPerPage", hitsPerPage);
stringBuilder = appendWithEncoding(stringBuilder, "tagFilters", tags);
stringBuilder = appendWithEncoding(stringBuilder, "numericFilters", numerics);
if (insideBoundingBox != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(insideBoundingBox);
} else if (aroundLatLong != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(aroundLatLong);
} else if (insidePolygon != null) {
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append(insidePolygon);
}
stringBuilder = append(stringBuilder, "aroundLatLongViaIP", aroundLatLongViaIP);
stringBuilder = append(stringBuilder, "aroundRadius", aroundRadius);
stringBuilder = append(stringBuilder, "aroundPrecision", aroundPrecision);
stringBuilder = appendWithEncoding(stringBuilder, "query", query);
stringBuilder = appendWithEncoding(stringBuilder, "similarQuery", similarQuery);
stringBuilder = appendWithEncoding(stringBuilder, "facets", facets);
stringBuilder = appendWithEncoding(stringBuilder, "filters", filters);
stringBuilder = appendWithEncoding(stringBuilder, "facetFilters", facetFilters);
stringBuilder = append(stringBuilder, "maxNumberOfFacets", maxNumberOfFacets);
stringBuilder = appendWithEncoding(stringBuilder, "optionalWords", optionalWords);
stringBuilder = appendWithEncoding(stringBuilder, "restrictSearchableAttributes", restrictSearchableAttributes);
switch (queryType) {
case PREFIX_ALL:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("queryType=prefixAll");
break;
case PREFIX_LAST:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("queryType=prefixLast");
break;
case PREFIX_NONE:
if (stringBuilder.length() > 0) {
stringBuilder.append('&');
}
stringBuilder.append("queryType=prefixNone");
break;
default:
//Do nothing
break;
}
stringBuilder = appendWithEncoding(stringBuilder, "referer", referers);
stringBuilder = appendWithEncoding(stringBuilder, "userToken", userToken);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return stringBuilder.toString();
}
/**
* @return the attributes
*/
public List<String> getAttributes() {
return attributes;
}
/**
* @return the attributesToHighlight
*/
public List<String> getAttributesToHighlight() {
return attributesToHighlight;
}
/**
* @return the attributesToSnippet
*/
public List<String> getAttributesToSnippet() {
return attributesToSnippet;
}
/**
* @return the minWordSizeForApprox1
*/
public Integer getMinWordSizeForApprox1() {
return minWordSizeForApprox1;
}
/**
* @return the minWordSizeForApprox2
*/
public Integer getMinWordSizeForApprox2() {
return minWordSizeForApprox2;
}
/**
* @return the getRankingInfo
*/
public Boolean isGetRankingInfo() {
return getRankingInfo;
}
/**
* @return the ignorePlural
*/
public Boolean isIgnorePlural() {
return ignorePlural;
}
/**
* @return the distinct
*/
public Boolean isDistinct() {
return distinct > 0;
}
/**
* @return the distinct
*/
public Integer getDistinct() {
return distinct;
}
/**
* @return the advancedSyntax
*/
public Boolean isAdvancedSyntax() {
return advancedSyntax;
}
/**
* @return the page
*/
public Integer getPage() {
return page;
}
/**
* @return the hitsPerPage
*/
public Integer getHitsPerPage() {
return hitsPerPage;
}
/**
* @return the restrictSearchableAttributes
*/
public String getRestrictSearchableAttributes() {
return restrictSearchableAttributes;
}
/**
* @return the tags
*/
public String getTags() {
return tags;
}
/**
* @return the numerics
*/
public String getNumerics() {
return numerics;
}
/**
* @return the insideBoundingBox
*/
public String getInsideBoundingBox() {
return insideBoundingBox;
}
/**
* @return the aroundLatLong
*/
public String getAroundLatLong() {
return aroundLatLong;
}
/**
* @return the aroundLatLongViaIP
*/
public Boolean isAroundLatLongViaIP() {
return aroundLatLongViaIP;
}
/**
* @return the query
*/
public String getQuery() {
return query;
}
/**
* @return the similar query
*/
public String getSimilarQuery() {
return similarQuery;
}
/**
* @return the queryType
*/
public QueryType getQueryType() {
return queryType;
}
/**
* @return the optionalWords
*/
public String getOptionalWords() {
return optionalWords;
}
/**
* @return the facets
*/
public String getFacets() {
return facets;
}
/**
* @return the filters
*/
public String getFilters() {
return filters;
}
/**
* @return the facetFilters
*/
public String getFacetFilters() {
return facetFilters;
}
/**
* @return the maxNumberOfFacets
*/
public Integer getMaxNumberOfFacets() {
return maxNumberOfFacets;
}
/**
* @return the analytics
*/
public Boolean isAnalytics() {
return analytics;
}
/**
* @return the analytics tags
*/
public String getAnalyticsTags() {
return analyticsTags;
}
/**
* @return the synonyms
*/
public Boolean isSynonyms() {
return synonyms;
}
/**
* @return the replaceSynonyms
*/
public Boolean isReplaceSynonyms() {
return replaceSynonyms;
}
/**
* @return the allowTyposOnNumericTokens
*/
public Boolean isAllowTyposOnNumericTokens() {
return allowTyposOnNumericTokens;
}
/**
* @return the removeWordsIfNoResult
*/
public RemoveWordsType getRemoveWordsIfNoResult() {
return removeWordsIfNoResult;
}
/**
* @return the typoTolerance
*/
public TypoTolerance getTypoTolerance() {
return typoTolerance;
}
}
| Add new secured parameters
| src/main/java/com/algolia/search/saas/Query.java | Add new secured parameters | <ide><path>rc/main/java/com/algolia/search/saas/Query.java
<ide> protected Boolean removeStopWords;
<ide> protected String userToken;
<ide> protected String referers;
<add> protected Integer validUntil;
<add> protected String restrictIndices;
<ide>
<ide> public Query(String query) {
<ide> minWordSizeForApprox1 = null;
<ide> removeWordsIfNoResult = RemoveWordsType.REMOVE_NOTSET;
<ide> aroundPrecision = aroundRadius = 0;
<ide> userToken = referers = null;
<add> validUntil = null;
<add> restrictIndices = null;
<ide> }
<ide>
<ide> public Query() {
<ide> removeWordsIfNoResult = other.removeWordsIfNoResult;
<ide> referers = other.referers;
<ide> userToken = other.userToken;
<add> validUntil = other.validUntil;
<add> restrictIndices = other.restrictIndices;
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public Query enableAvancedSyntax(boolean advancedSyntax) {
<ide> this.advancedSyntax = advancedSyntax;
<add> return this;
<add> }
<add>
<add> public Query setValidUntil(Integer timestamp) {
<add> this.validUntil = timestamp;
<add> return this;
<add> }
<add>
<add> public Query setRestrictIndicies(String indices) {
<add> this.restrictIndices = indices;
<ide> return this;
<ide> }
<ide>
<ide>
<ide> stringBuilder = appendWithEncoding(stringBuilder, "referer", referers);
<ide> stringBuilder = appendWithEncoding(stringBuilder, "userToken", userToken);
<add> stringBuilder = append(stringBuilder, "validUntil", validUntil);
<add> stringBuilder = appendWithEncoding(stringBuilder, "restrictIndices", restrictIndices);
<ide> } catch (UnsupportedEncodingException e) {
<ide> throw new RuntimeException(e);
<ide> }
<ide> public TypoTolerance getTypoTolerance() {
<ide> return typoTolerance;
<ide> }
<add>
<add> /**
<add> * @return the validity used for ephemeral API Keys
<add> */
<add> public Integer getValidUntil() {
<add> return validUntil;
<add> }
<add>
<add> /**
<add> * @return The list of indices allowed
<add> */
<add> public String getRestrictIndices() {
<add> return restrictIndices;
<add> }
<ide> } |
|
Java | apache-2.0 | 52ba6263cda086f8cd324c0fd4431affcb49c828 | 0 | youdonghai/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,apixandru/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,apixandru/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,signed/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,kdwink/intellij-community,apixandru/intellij-community,fitermay/intellij-community,xfournet/intellij-community,allotria/intellij-community,retomerz/intellij-community,clumsy/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,allotria/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,semonte/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,vladmm/intellij-community,retomerz/intellij-community,FHannes/intellij-community,allotria/intellij-community,kdwink/intellij-community,signed/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,FHannes/intellij-community,hurricup/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,apixandru/intellij-community,apixandru/intellij-community,signed/intellij-community,kdwink/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,signed/intellij-community,da1z/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,asedunov/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,fitermay/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,fitermay/intellij-community,clumsy/intellij-community,xfournet/intellij-community,da1z/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,xfournet/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,retomerz/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,blademainer/intellij-community,signed/intellij-community,allotria/intellij-community,vladmm/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,retomerz/intellij-community,vladmm/intellij-community,vladmm/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,blademainer/intellij-community,fitermay/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ibinti/intellij-community,retomerz/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,semonte/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,hurricup/intellij-community,asedunov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,hurricup/intellij-community,blademainer/intellij-community,signed/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,FHannes/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,signed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fitermay/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,vladmm/intellij-community,da1z/intellij-community,da1z/intellij-community,asedunov/intellij-community,blademainer/intellij-community,xfournet/intellij-community,da1z/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,ibinti/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,blademainer/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui.customization;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.Separator;
import com.intellij.openapi.keymap.impl.ui.ActionsTreeUtil;
import com.intellij.openapi.keymap.impl.ui.Group;
import com.intellij.openapi.util.*;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
/**
* User: anna
* Date: Mar 18, 2005
*/
public class ActionUrl implements JDOMExternalizable {
public static final int ADDED = 1;
public static final int DELETED = -1;
//temp action only
public static final int MOVE = 2;
private ArrayList<String> myGroupPath;
private Object myComponent;
private int myActionType;
private int myAbsolutePosition;
public int myInitialPosition = -1;
@NonNls private static final String IS_GROUP = "is_group";
@NonNls private static final String SEPARATOR = "seperator";
@NonNls private static final String IS_ACTION = "is_action";
@NonNls private static final String VALUE = "value";
@NonNls private static final String PATH = "path";
@NonNls private static final String ACTION_TYPE = "action_type";
@NonNls private static final String POSITION = "position";
public ActionUrl() {
myGroupPath = new ArrayList<String>();
}
public ActionUrl(final ArrayList<String> groupPath,
final Object component,
final int actionType,
final int position) {
myGroupPath = groupPath;
myComponent = component;
myActionType = actionType;
myAbsolutePosition = position;
}
public ArrayList<String> getGroupPath() {
return myGroupPath;
}
public String getParentGroup(){
return myGroupPath.get(myGroupPath.size() - 1);
}
public String getRootGroup() {
return myGroupPath.size() >= 1 ? myGroupPath.get(1) : "";
}
public Object getComponent() {
return myComponent;
}
@Nullable
public AnAction getComponentAction(){
if (myComponent instanceof Separator){
return Separator.getInstance();
}
if (myComponent instanceof String){
return ActionManager.getInstance().getAction((String)myComponent);
}
if (myComponent instanceof Group){
final String id = ((Group)myComponent).getId();
if (id == null || id.length() == 0){
return ((Group)myComponent).constructActionGroup(true);
}
return ActionManager.getInstance().getAction(id);
}
return null;
}
public int getActionType() {
return myActionType;
}
public void setActionType(final int actionType) {
myActionType = actionType;
}
public int getAbsolutePosition() {
return myAbsolutePosition;
}
public void setAbsolutePosition(final int absolutePosition) {
myAbsolutePosition = absolutePosition;
}
public int getInitialPosition() {
return myInitialPosition;
}
public void setInitialPosition(final int initialPosition) {
myInitialPosition = initialPosition;
}
@Override
public void readExternal(Element element) throws InvalidDataException {
myGroupPath = new ArrayList<String>();
for (Object o : element.getChildren(PATH)) {
myGroupPath.add(((Element)o).getAttributeValue(VALUE));
}
final String attributeValue = element.getAttributeValue(VALUE);
if (element.getAttributeValue(IS_ACTION) != null) {
myComponent = attributeValue;
}
else if (element.getAttributeValue(SEPARATOR) != null) {
myComponent = Separator.getInstance();
}
else if (element.getAttributeValue(IS_GROUP) != null) {
final AnAction action = ActionManager.getInstance().getAction(attributeValue);
myComponent = action instanceof ActionGroup
? ActionsTreeUtil.createGroup((ActionGroup)action, true, null)
: new Group(attributeValue, attributeValue, null);
}
myActionType = Integer.parseInt(element.getAttributeValue(ACTION_TYPE));
myAbsolutePosition = Integer.parseInt(element.getAttributeValue(POSITION));
DefaultJDOMExternalizer.readExternal(this, element);
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
for (String s : myGroupPath) {
Element path = new Element(PATH);
path.setAttribute(VALUE, s);
element.addContent(path);
}
if (myComponent instanceof String) {
element.setAttribute(VALUE, (String)myComponent);
element.setAttribute(IS_ACTION, Boolean.TRUE.toString());
}
else if (myComponent instanceof Separator) {
element.setAttribute(SEPARATOR, Boolean.TRUE.toString());
}
else if (myComponent instanceof Group) {
final String groupId = ((Group)myComponent).getId() != null && ((Group)myComponent).getId().length() != 0
? ((Group)myComponent).getId()
: ((Group)myComponent).getName();
element.setAttribute(VALUE, groupId != null ? groupId : "");
element.setAttribute(IS_GROUP, Boolean.TRUE.toString());
}
element.setAttribute(ACTION_TYPE, Integer.toString(myActionType));
element.setAttribute(POSITION, Integer.toString(myAbsolutePosition));
DefaultJDOMExternalizer.writeExternal(this, element);
}
public boolean isGroupContainsInPath(ActionGroup group){
for (String s : myGroupPath) {
if (s.equals(group.getTemplatePresentation().getText())) {
return true;
}
}
return false;
}
public static void changePathInActionsTree(JTree tree, ActionUrl url){
if (url.myActionType == ADDED){
addPathToActionsTree(tree, url);
} else if (url.myActionType == DELETED) {
removePathFromActionsTree(tree, url);
} else if (url.myActionType == MOVE){
movePathInActionsTree(tree, url);
}
}
private static void addPathToActionsTree(JTree tree, ActionUrl url) {
final TreePath treePath = CustomizationUtil.getTreePath(tree, url);
if (treePath == null) return;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
final int absolutePosition = url.getAbsolutePosition();
if (node.getChildCount() >= absolutePosition && absolutePosition >= 0) {
if (url.getComponent() instanceof Group){
node.insert(ActionsTreeUtil.createNode((Group)url.getComponent()), absolutePosition);
} else {
node.insert(new DefaultMutableTreeNode(url.getComponent()), absolutePosition);
}
}
}
private static void removePathFromActionsTree(JTree tree, ActionUrl url) {
if (url.myComponent == null) return;
final TreePath treePath = CustomizationUtil.getTreePath(tree, url);
if (treePath == null) return;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
final int absolutePosition = url.getAbsolutePosition();
if (node.getChildCount() > absolutePosition && absolutePosition >= 0) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(absolutePosition);
if (child.getUserObject().equals(url.getComponent())) {
node.remove(child);
}
}
}
private static void movePathInActionsTree(JTree tree, ActionUrl url){
final TreePath treePath = CustomizationUtil.getTreePath(tree, url);
if (treePath != null){
if (treePath.getLastPathComponent() != null){
final DefaultMutableTreeNode parent = ((DefaultMutableTreeNode)treePath.getLastPathComponent());
final int absolutePosition = url.getAbsolutePosition();
final int initialPosition = url.getInitialPosition();
if (parent.getChildCount() > absolutePosition && absolutePosition >= 0) {
if (parent.getChildCount() > initialPosition && initialPosition >= 0) {
final DefaultMutableTreeNode child = (DefaultMutableTreeNode)parent.getChildAt(initialPosition);
if (child.getUserObject().equals(url.getComponent())){
parent.remove(child);
parent.insert(child, absolutePosition);
}
}
}
}
}
}
public static ArrayList<String> getGroupPath(final TreePath treePath){
final ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < treePath.getPath().length - 1; i++) {
Object o = ((DefaultMutableTreeNode)treePath.getPath()[i]).getUserObject();
if (o instanceof Group){
result.add(((Group)o).getName());
}
}
return result;
}
public boolean equals(Object object){
if (!(object instanceof ActionUrl)){
return false;
}
ActionUrl url = (ActionUrl)object;
Object comp = myComponent instanceof Pair ? ((Pair)myComponent).first : myComponent;
Object thatComp = url.myComponent instanceof Pair ? ((Pair)url.myComponent).first : url.myComponent;
return Comparing.equal(comp, thatComp) && myGroupPath.equals(url.myGroupPath) && myAbsolutePosition == url.getAbsolutePosition();
}
public int hashCode() {
int result = myComponent != null ? myComponent.hashCode() : 0;
result += 29 * myGroupPath.hashCode();
return result;
}
public void setComponent(final Object object) {
myComponent = object;
}
public void setGroupPath(final ArrayList<String> groupPath) {
myGroupPath = groupPath;
}
@Override
public String toString() {
return "ActionUrl{" +
"myGroupPath=" + myGroupPath +
", myComponent=" + myComponent +
", myActionType=" + myActionType +
", myAbsolutePosition=" + myAbsolutePosition +
", myInitialPosition=" + myInitialPosition +
'}';
}
}
| platform/platform-impl/src/com/intellij/ide/ui/customization/ActionUrl.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.ui.customization;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.Separator;
import com.intellij.openapi.keymap.impl.ui.ActionsTreeUtil;
import com.intellij.openapi.keymap.impl.ui.Group;
import com.intellij.openapi.util.*;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.util.ArrayList;
/**
* User: anna
* Date: Mar 18, 2005
*/
public class ActionUrl implements JDOMExternalizable {
public static final int ADDED = 1;
public static final int DELETED = -1;
//temp action only
public static final int MOVE = 2;
private ArrayList<String> myGroupPath;
private Object myComponent;
private int myActionType;
private int myAbsolutePosition;
public int myInitialPosition = -1;
@NonNls private static final String IS_GROUP = "is_group";
@NonNls private static final String SEPARATOR = "seperator";
@NonNls private static final String IS_ACTION = "is_action";
@NonNls private static final String VALUE = "value";
@NonNls private static final String PATH = "path";
@NonNls private static final String ACTION_TYPE = "action_type";
@NonNls private static final String POSITION = "position";
public ActionUrl() {
myGroupPath = new ArrayList<String>();
}
public ActionUrl(final ArrayList<String> groupPath,
final Object component,
final int actionType,
final int position) {
myGroupPath = groupPath;
myComponent = component;
myActionType = actionType;
myAbsolutePosition = position;
}
public ArrayList<String> getGroupPath() {
return myGroupPath;
}
public String getParentGroup(){
return myGroupPath.get(myGroupPath.size() - 1);
}
public String getRootGroup() {
return myGroupPath.size() >= 1 ? myGroupPath.get(1) : "";
}
public Object getComponent() {
return myComponent;
}
@Nullable
public AnAction getComponentAction(){
if (myComponent instanceof Separator){
return Separator.getInstance();
}
if (myComponent instanceof String){
return ActionManager.getInstance().getAction((String)myComponent);
}
if (myComponent instanceof Group){
final String id = ((Group)myComponent).getId();
if (id == null || id.length() == 0){
return ((Group)myComponent).constructActionGroup(true);
}
return ActionManager.getInstance().getAction(id);
}
return null;
}
public int getActionType() {
return myActionType;
}
public void setActionType(final int actionType) {
myActionType = actionType;
}
public int getAbsolutePosition() {
return myAbsolutePosition;
}
public void setAbsolutePosition(final int absolutePosition) {
myAbsolutePosition = absolutePosition;
}
public int getInitialPosition() {
return myInitialPosition;
}
public void setInitialPosition(final int initialPosition) {
myInitialPosition = initialPosition;
}
public void readExternal(Element element) throws InvalidDataException {
myGroupPath = new ArrayList<String>();
for (Object o : element.getChildren(PATH)) {
myGroupPath.add(((Element)o).getAttributeValue(VALUE));
}
final String attributeValue = element.getAttributeValue(VALUE);
if (element.getAttributeValue(IS_ACTION) != null) {
myComponent = attributeValue;
}
else if (element.getAttributeValue(SEPARATOR) != null) {
myComponent = Separator.getInstance();
}
else if (element.getAttributeValue(IS_GROUP) != null) {
final AnAction action = ActionManager.getInstance().getAction(attributeValue);
myComponent = action instanceof ActionGroup
? ActionsTreeUtil.createGroup((ActionGroup)action, true, null)
: new Group(attributeValue, attributeValue, null);
}
myActionType = Integer.parseInt(element.getAttributeValue(ACTION_TYPE));
myAbsolutePosition = Integer.parseInt(element.getAttributeValue(POSITION));
DefaultJDOMExternalizer.readExternal(this, element);
}
public void writeExternal(Element element) throws WriteExternalException {
for (String s : myGroupPath) {
Element path = new Element(PATH);
path.setAttribute(VALUE, s);
element.addContent(path);
}
if (myComponent instanceof String) {
element.setAttribute(VALUE, (String)myComponent);
element.setAttribute(IS_ACTION, Boolean.TRUE.toString());
}
else if (myComponent instanceof Separator) {
element.setAttribute(SEPARATOR, Boolean.TRUE.toString());
}
else if (myComponent instanceof Group) {
final String groupId = ((Group)myComponent).getId() != null && ((Group)myComponent).getId().length() != 0
? ((Group)myComponent).getId()
: ((Group)myComponent).getName();
element.setAttribute(VALUE, groupId != null ? groupId : "");
element.setAttribute(IS_GROUP, Boolean.TRUE.toString());
}
element.setAttribute(ACTION_TYPE, Integer.toString(myActionType));
element.setAttribute(POSITION, Integer.toString(myAbsolutePosition));
DefaultJDOMExternalizer.writeExternal(this, element);
}
public boolean isGroupContainsInPath(ActionGroup group){
for (String s : myGroupPath) {
if (s.equals(group.getTemplatePresentation().getText())) {
return true;
}
}
return false;
}
public static void changePathInActionsTree(JTree tree, ActionUrl url){
if (url.myActionType == ADDED){
addPathToActionsTree(tree, url);
} else if (url.myActionType == DELETED) {
removePathFromActionsTree(tree, url);
} else if (url.myActionType == MOVE){
movePathInActionsTree(tree, url);
}
}
private static void addPathToActionsTree(JTree tree, ActionUrl url) {
final TreePath treePath = CustomizationUtil.getTreePath(tree, url);
if (treePath == null) return;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
final int absolutePosition = url.getAbsolutePosition();
if (node.getChildCount() >= absolutePosition && absolutePosition >= 0) {
if (url.getComponent() instanceof Group){
node.insert(ActionsTreeUtil.createNode((Group)url.getComponent()), absolutePosition);
} else {
node.insert(new DefaultMutableTreeNode(url.getComponent()), absolutePosition);
}
}
}
private static void removePathFromActionsTree(JTree tree, ActionUrl url) {
if (url.myComponent == null) return;
final TreePath treePath = CustomizationUtil.getTreePath(tree, url);
if (treePath == null) return;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
final int absolutePosition = url.getAbsolutePosition();
if (node.getChildCount() > absolutePosition && absolutePosition >= 0) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(absolutePosition);
if (child.getUserObject().equals(url.getComponent())) {
node.remove(child);
}
}
}
private static void movePathInActionsTree(JTree tree, ActionUrl url){
final TreePath treePath = CustomizationUtil.getTreePath(tree, url);
if (treePath != null){
if (treePath.getLastPathComponent() != null){
final DefaultMutableTreeNode parent = ((DefaultMutableTreeNode)treePath.getLastPathComponent());
final int absolutePosition = url.getAbsolutePosition();
final int initialPosition = url.getInitialPosition();
if (parent.getChildCount() > absolutePosition && absolutePosition >= 0) {
if (parent.getChildCount() > initialPosition && initialPosition >= 0) {
final DefaultMutableTreeNode child = (DefaultMutableTreeNode)parent.getChildAt(initialPosition);
if (child.getUserObject().equals(url.getComponent())){
parent.remove(child);
parent.insert(child, absolutePosition);
}
}
}
}
}
}
public static ArrayList<String> getGroupPath(final TreePath treePath){
final ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < treePath.getPath().length - 1; i++) {
Object o = ((DefaultMutableTreeNode)treePath.getPath()[i]).getUserObject();
if (o instanceof Group){
result.add(((Group)o).getName());
}
}
return result;
}
public boolean equals(Object object){
if (!(object instanceof ActionUrl)){
return false;
}
ActionUrl url = (ActionUrl)object;
Object comp = myComponent instanceof Pair ? ((Pair)myComponent).first : myComponent;
Object thatComp = url.myComponent instanceof Pair ? ((Pair)url.myComponent).first : url.myComponent;
return Comparing.equal(comp, thatComp) && myGroupPath.equals(url.myGroupPath) && myAbsolutePosition == url.getAbsolutePosition();
}
public int hashCode() {
int result = myComponent != null ? myComponent.hashCode() : 0;
result += 29 * myGroupPath.hashCode();
return result;
}
public void setComponent(final Object object) {
myComponent = object;
}
public void setGroupPath(final ArrayList<String> groupPath) {
myGroupPath = groupPath;
}
@Override
public String toString() {
return "ActionUrl{" +
"myGroupPath=" + myGroupPath +
", myComponent=" + myComponent +
", myActionType=" + myActionType +
", myAbsolutePosition=" + myAbsolutePosition +
", myInitialPosition=" + myInitialPosition +
'}';
}
}
| cleanup
| platform/platform-impl/src/com/intellij/ide/ui/customization/ActionUrl.java | cleanup | <ide><path>latform/platform-impl/src/com/intellij/ide/ui/customization/ActionUrl.java
<ide> /*
<del> * Copyright 2000-2009 JetBrains s.r.o.
<add> * Copyright 2000-2015 JetBrains s.r.o.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> myInitialPosition = initialPosition;
<ide> }
<ide>
<add> @Override
<ide> public void readExternal(Element element) throws InvalidDataException {
<ide> myGroupPath = new ArrayList<String>();
<ide> for (Object o : element.getChildren(PATH)) {
<ide> DefaultJDOMExternalizer.readExternal(this, element);
<ide> }
<ide>
<add> @Override
<ide> public void writeExternal(Element element) throws WriteExternalException {
<ide> for (String s : myGroupPath) {
<ide> Element path = new Element(PATH); |
|
Java | agpl-3.0 | 4b36650bdeb4a3507c5d0228a2c1bf6253bd44c2 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | b91f27a2-2e61-11e5-9284-b827eb9e62be | hello.java | b919a8e0-2e61-11e5-9284-b827eb9e62be | b91f27a2-2e61-11e5-9284-b827eb9e62be | hello.java | b91f27a2-2e61-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>b919a8e0-2e61-11e5-9284-b827eb9e62be
<add>b91f27a2-2e61-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | 420ea30a407de4a8f828c759306e9f1eb4d09800 | 0 | blue-systems-group/project.maybe.polyglot,xcv58/polyglot,liujed/polyglot-eclipse,liujed/polyglot-eclipse,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse,xcv58/polyglot,xcv58/polyglot,xcv58/polyglot,blue-systems-group/project.maybe.polyglot,blue-systems-group/project.maybe.polyglot,liujed/polyglot-eclipse | /*******************************************************************************
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2012 Polyglot project group, Cornell University
* Copyright (c) 2006-2012 IBM Corporation
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program and the accompanying materials are made available under
* the terms of the Lesser GNU Public License v2.0 which accompanies this
* distribution.
*
* The development of the Polyglot project has been supported by a
* number of funding sources, including DARPA Contract F30602-99-1-0533,
* monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and
* N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302,
* and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan
* Research Fellowship, and an Intel Research Ph.D. Fellowship.
*
* See README for contributors.
******************************************************************************/
package polyglot.visit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import polyglot.ast.Block;
import polyglot.ast.Branch;
import polyglot.ast.Catch;
import polyglot.ast.CodeNode;
import polyglot.ast.CompoundStmt;
import polyglot.ast.Labeled;
import polyglot.ast.Loop;
import polyglot.ast.Return;
import polyglot.ast.Stmt;
import polyglot.ast.Switch;
import polyglot.ast.Term;
import polyglot.ast.Try;
import polyglot.main.Report;
import polyglot.types.MemberInstance;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.util.CollectionUtil;
import polyglot.util.Copy;
import polyglot.util.InternalCompilerError;
import polyglot.util.StringUtil;
import polyglot.visit.FlowGraph.Edge;
import polyglot.visit.FlowGraph.EdgeKey;
import polyglot.visit.FlowGraph.Peer;
/**
* Class used to construct a CFG.
*/
public class CFGBuilder<FlowItem extends DataFlow.Item> implements Copy {
/** The flowgraph under construction. */
protected FlowGraph<FlowItem> graph;
/** The type system. */
protected TypeSystem ts;
/**
* The outer CFGBuilder. We create a new inner CFGBuilder when entering a
* loop or try-block and when entering a finally block.
*/
protected CFGBuilder<FlowItem> outer;
/**
* The innermost loop or try-block in lexical scope. We maintain a stack
* of loops and try-blocks in order to add edges for break and continue
* statements and for exception throws. When such a jump is encountered we
* traverse the stack, searching for the target of the jump.
*/
protected Stmt innermostTarget;
/**
* Nodes in finally blocks need to be analyzed multiple times, once for each
* possible way to reach the finally block. The path_to_finally is used to
* distinguish these different "copies" of nodes in the finally block, and is
* a list of terms that attempted to complete normally that caused the finally
* block to be reached. If this CFGBuilder is for an AST that is not nested inside
* a finallyBlock, then path_to_finally will be empty.
*
* To explain by example, consider the following code (which is assumed to not
* be nested inside a finally block, and assume that S1 does not contain any
* try-finally block).
* <code>try { S1 } finally { S2 }</code>
* Assume that term t1 in S1 may complete abruptly. The code for S2 will be
* analyzed (at least) twice: once for normal termination of S1 (and so
* path_to_finally will be empty) and once for the abrupt completion of t1
* (and so path_to_finally will be [t1]).
*
* Consider the following code:
* <code>try { try { S1 } finally { S2 } } finally { S3 }</code>
* Assume that terms t1 in S1 and t2 in S2 may complete abruptly.
* Nodes in S2 will be analyzed (at least) twice, with path_to_finally empty
* (for normal termination of S1) and with path_to_empty equals [t1] (for
* abrupt completion of t1). S3 will be analyzed (at least) 3 times:
* once with path_to_finally empty (for normal termination of S1 and S2)
* once with path_to_finally equals [t1] (for abrupt completion of t1 and normal termination of S2), and
* once with path_to_finally equals [t1, t2] (for (attempted) abrupt completion of t1 and subsequent
* abrupt completion of t2).
*
* Consider the following code:
* <code>try { S1 } finally { try { S2 } finally { S3 } }</code>
* Assume that terms t1 in S1 and t2 in S2 may complete abruptly.
* Nodes in S2 will be analyzed (at least) twice, with path_to_finally empty
* (for normal termination of S1) and with path_to_empty equals [t1] (for
* abrupt completion of t1). S3 will be analyzed (at least) 3 times:
* once with path_to_finally empty (for normal termination of S1 and S2)
* once with path_to_finally equals [t1] (for abrupt completion of t1 and normal termination of S2), and
* once with path_to_finally equals [t1, t2] (for (attempted) abrupt completion of t1 and subsequent
* abrupt completion of t2).
*
*/
protected List<Term> path_to_finally;
/** The data flow analysis for which we are constructing the graph. */
protected DataFlow<FlowItem> df;
/**
* True if we should skip the catch blocks for the innermost try when
* building edges for an exception throw.
*/
protected boolean skipInnermostCatches;
/**
* True if we should skip dead if branches, such as S in "if (false) { S }".
* Different dataflow analyses have different requirements.
*/
protected boolean skipDeadIfBranches = false;
/**
* True if we should skip dead loop bodies, such as S in "while (false) { S }".
* Different dataflow analyses have different requirements.
*/
protected boolean skipDeadLoopBodies = false;
/**
* True if we should add edges for uncaught Errors to the exit node of the
* graph. By default, we do not, but subclasses can change this behavior
* if needed.
*/
protected boolean errorEdgesToExitNode;
/**
* Should we add exception edges into finally blocks? If true, then the edge from
* an AST node that throws an exception to a finally block will be labeled with the
* appropriate exception; if false, then the edge will be labeled OTHER.
* For backwards compatibility, the default value is false.
*/
protected boolean exceptionEdgesToFinally;
public CFGBuilder(TypeSystem ts, FlowGraph<FlowItem> graph,
DataFlow<FlowItem> df) {
this.ts = ts;
this.graph = graph;
this.df = df;
this.path_to_finally = Collections.emptyList();
this.outer = null;
this.innermostTarget = null;
this.skipInnermostCatches = false;
this.errorEdgesToExitNode = false;
this.exceptionEdgesToFinally = false;
}
public FlowGraph<FlowItem> graph() {
return graph;
}
public DataFlow<FlowItem> dataflow() {
return df;
}
public CFGBuilder<FlowItem> outer() {
return outer;
}
public Stmt innermostTarget() {
return innermostTarget;
}
public boolean skipInnermostCatches() {
return skipInnermostCatches;
}
/** Get the type system. */
public TypeSystem typeSystem() {
return ts;
}
/** Copy the CFGBuilder. */
@Override
public CFGBuilder<FlowItem> copy() {
try {
@SuppressWarnings("unchecked")
CFGBuilder<FlowItem> clone = (CFGBuilder<FlowItem>) super.clone();
return clone;
}
catch (CloneNotSupportedException e) {
throw new InternalCompilerError("Java clone() weirdness.");
}
}
/**
* Construct a new CFGBuilder with the a new innermost loop or
* try-block <code>n</code>.
*/
public CFGBuilder<FlowItem> push(Stmt n) {
return push(n, false);
}
/**
* Construct a new CFGBuilder with the a new innermost loop or
* try-block <code>n</code>, optionally skipping innermost catch blocks.
*/
public CFGBuilder<FlowItem> push(Stmt n, boolean skipInnermostCatches) {
CFGBuilder<FlowItem> v = copy();
v.outer = this;
v.innermostTarget = n;
v.skipInnermostCatches = skipInnermostCatches;
return v;
}
/**
* Visit edges from a branch. Simulate breaking/continuing out of
* the loop, visiting any finally blocks encountered.
*/
public void visitBranchTarget(Branch b) {
Peer<FlowItem> last_peer =
graph.peer(b, this.path_to_finally, Term.EXIT);
for (CFGBuilder<FlowItem> v = this; v != null; v = v.outer) {
Term c = v.innermostTarget;
if (c instanceof Try) {
Try tr = (Try) c;
if (tr.finallyBlock() != null) {
last_peer =
tryFinally(v,
last_peer,
last_peer.node == b,
tr.finallyBlock());
}
}
if (b.label() != null) {
if (c instanceof Labeled) {
Labeled l = (Labeled) c;
if (l.label().equals(b.label())) {
if (b.kind() == Branch.BREAK) {
edge(last_peer,
this.graph().peer(l,
this.path_to_finally,
Term.EXIT),
FlowGraph.EDGE_KEY_OTHER);
}
else {
Stmt s = l.statement();
if (s instanceof Loop) {
Loop loop = (Loop) s;
edge(last_peer,
this.graph().peer(loop.continueTarget(),
this.path_to_finally,
Term.ENTRY),
FlowGraph.EDGE_KEY_OTHER);
}
else {
throw new CFGBuildError("Target of continue statement must "
+ "be a loop.",
l.position());
}
}
return;
}
}
}
else {
if (c instanceof Loop) {
Loop l = (Loop) c;
if (b.kind() == Branch.CONTINUE) {
edge(last_peer,
this.graph().peer(l.continueTarget(),
this.path_to_finally,
Term.ENTRY),
FlowGraph.EDGE_KEY_OTHER);
}
else {
edge(last_peer,
this.graph().peer(l,
this.path_to_finally,
Term.EXIT),
FlowGraph.EDGE_KEY_OTHER);
}
return;
}
else if (c instanceof Switch && b.kind() == Branch.BREAK) {
edge(last_peer,
this.graph().peer(c, this.path_to_finally, Term.EXIT),
FlowGraph.EDGE_KEY_OTHER);
return;
}
}
}
throw new CFGBuildError("Target of branch statement not found.",
b.position());
}
/**
* Visit edges for a return statement. Simulate the return, visiting any
* finally blocks encountered.
*/
public void visitReturn(Return r) {
Peer<FlowItem> last_peer =
this.graph().peer(r, this.path_to_finally, Term.EXIT);
for (CFGBuilder<FlowItem> v = this; v != null; v = v.outer) {
Term c = v.innermostTarget;
if (c instanceof Try) {
Try tr = (Try) c;
if (tr.finallyBlock() != null) {
last_peer =
tryFinally(v,
last_peer,
last_peer.node == r,
tr.finallyBlock());
}
}
}
// Add an edge to the exit node.
edge(last_peer, exitPeer(), FlowGraph.EDGE_KEY_OTHER);
}
protected static int counter = 0;
/** Visit the AST, constructing the CFG. */
public void visitGraph() {
String name = StringUtil.getShortNameComponent(df.getClass().getName());
name += counter++;
if (Report.should_report(Report.cfg, 2)) {
String rootName = "";
if (graph.root() instanceof CodeNode) {
CodeNode cd = (CodeNode) graph.root();
rootName = cd.codeInstance().toString();
if (cd.codeInstance() instanceof MemberInstance) {
rootName +=
" in "
+ ((MemberInstance) cd.codeInstance()).container()
.toString();
}
}
Report.report(2, "digraph CFGBuild" + name + " {");
Report.report(2,
" label=\"CFGBuilder: "
+ name
+ "\\n"
+ rootName
+ "\"; fontsize=20; center=true; ratio=auto; size = \"8.5,11\";");
}
// create peers for the entry and exit nodes.
entryPeer();
exitPeer();
this.visitCFG(graph.root(), Collections.<EdgeKeyTermPair> emptyList());
if (Report.should_report(Report.cfg, 2)) Report.report(2, "}");
}
/**
* Utility method to get the peer for the entry of the flow graph.
*/
protected Peer<FlowItem> entryPeer() {
return graph.peer(graph.root(),
Collections.<Term> emptyList(),
Term.ENTRY);
}
/**
* Utility method to get the peer for the exit of the flow graph.
*/
protected Peer<FlowItem> exitPeer() {
return graph.peer(graph.root(),
Collections.<Term> emptyList(),
Term.EXIT);
}
/**
* Utility function to visit all edges in a list.
*
* If <code>entry</code> is Term.ENTRY, the final successor is
* <code>after</code>'s entry node; if it's Term.EXIT, it's
* <code>after</code>'s exit.
*/
public void visitCFGList(List<? extends Term> elements, Term after,
int entry) {
Term prev = null;
for (Term c : elements) {
if (prev != null) {
visitCFG(prev, c, Term.ENTRY);
}
prev = c;
}
if (prev != null) {
visitCFG(prev, after, entry);
}
}
/**
* Create an edge for a node <code>a</code> with a single successor
* <code>succ</code>.
*
* The EdgeKey used for the edge from <code>a</code> to <code>succ</code>
* will be FlowGraph.EDGE_KEY_OTHER.
*
* If <code>entry</code> is Term.ENTRY, the successor is <code>succ</code>'s
* entry node; if it's Term.EXIT, it's <code>succ</code>'s exit.
*/
public void visitCFG(Term a, Term succ, int entry) {
visitCFG(a, FlowGraph.EDGE_KEY_OTHER, succ, entry);
}
/**
* Create an edge for a node <code>a</code> with a single successor
* <code>succ</code>, and EdgeKey <code>edgeKey</code>.
*
* If <code>entry</code> is Term.ENTRY, the successor is <code>succ</code>'s
* entry node; if it's Term.EXIT, it's <code>succ</code>'s exit.
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey, Term succ, int entry) {
visitCFG(a,
CollectionUtil.list(new EdgeKeyTermPair(edgeKey, succ, entry)));
}
/**
* Create edges from node <code>a</code> to successors <code>succ1</code>
* and <code>succ2</code> with EdgeKeys <code>edgeKey1</code> and
* <code>edgeKey2</code> respecitvely.
*
* <code>entry1</code> and <code>entry2</code> determine whether the
* successors are entry or exit nodes. They can be Term.ENTRY or Term.EXIT.
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey1, Term succ1,
int entry1, FlowGraph.EdgeKey edgeKey2, Term succ2, int entry2) {
visitCFG(a, CollectionUtil.list(new EdgeKeyTermPair(edgeKey1,
succ1,
entry1),
new EdgeKeyTermPair(edgeKey2,
succ2,
entry2)));
}
/**
* Create edges from node <code>a</code> to all successors <code>succ</code>
* with the EdgeKey <code>edgeKey</code> for all edges created.
*
* If <code>entry</code> is Term.ENTRY, all terms in <code>succ</code> are
* treated as entry nodes; if it's Term.EXIT, they are treated as exit
* nodes.
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey, List<Term> succ,
int entry) {
List<EdgeKeyTermPair> l = new ArrayList<EdgeKeyTermPair>(succ.size());
for (Term t : succ) {
l.add(new EdgeKeyTermPair(edgeKey, t, entry));
}
visitCFG(a, l);
}
/**
* Create edges from node <code>a</code> to all successors
* <code>succ</code> with the EdgeKey <code>edgeKey</code> for all edges
* created.
*
* The <code>entry</code> list must have the same size as
* <code>succ</code>, and each corresponding element determines whether a
* successor is an entry or exit node (using Term.ENTRY or Term.EXIT).
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey, List<Term> succ,
List<Integer> entry) {
if (succ.size() != entry.size()) {
throw new IllegalArgumentException();
}
List<EdgeKeyTermPair> l = new ArrayList<EdgeKeyTermPair>(succ.size());
for (int i = 0; i < succ.size(); i++) {
Term t = succ.get(i);
l.add(new EdgeKeyTermPair(edgeKey, t, entry.get(i).intValue()));
}
visitCFG(a, l);
}
protected static class EdgeKeyTermPair {
public final FlowGraph.EdgeKey edgeKey;
public final Term term;
public final int entry;
public EdgeKeyTermPair(FlowGraph.EdgeKey edgeKey, Term term, int entry) {
this.edgeKey = edgeKey;
this.term = term;
this.entry = entry;
}
@Override
public String toString() {
return "{edgeKey=" + edgeKey + ",term=" + term + ","
+ (entry == Term.ENTRY ? "entry" : "exit") + "}";
}
}
/**
* Create edges for a node <code>a</code> with successors
* <code>succs</code>.
*
* @param a the source node for the edges.
* @param succs a list of <code>EdgeKeyTermPair</code>s
*/
protected void visitCFG(Term a, List<EdgeKeyTermPair> succs) {
Term child = a.firstChild();
if (child == null) {
edge(this, a, Term.ENTRY, a, Term.EXIT, FlowGraph.EDGE_KEY_OTHER);
}
else {
edge(this,
a,
Term.ENTRY,
child,
Term.ENTRY,
FlowGraph.EDGE_KEY_OTHER);
}
if (Report.should_report(Report.cfg, 2))
Report.report(2, "// node " + a + " -> " + succs);
succs = a.acceptCFG(this, succs);
for (EdgeKeyTermPair s : succs) {
edge(a, s.term, s.entry, s.edgeKey);
}
visitThrow(a);
}
public void visitThrow(Term a) {
for (Type type : a.del().throwTypes(ts)) {
visitThrow(a, Term.EXIT, type);
}
// Every statement can throw an error.
// This is probably too inefficient.
if ((a instanceof Stmt && !(a instanceof CompoundStmt))
|| (a instanceof Block && ((Block) a).statements().isEmpty())) {
visitThrow(a, Term.EXIT, ts.Error());
}
}
/**
* Create edges for an exception thrown from term <code>t</code>.
*/
public void visitThrow(Term t, int entry, Type type) {
Peer<FlowItem> last_peer =
this.graph.peer(t, this.path_to_finally, entry);
for (CFGBuilder<FlowItem> v = this; v != null; v = v.outer) {
Term c = v.innermostTarget;
if (c instanceof Try) {
Try tr = (Try) c;
if (!v.skipInnermostCatches) {
boolean definiteCatch = false;
for (Catch cb : tr.catchBlocks()) {
// definite catch
if (type.isImplicitCastValid(cb.catchType())) {
edge(last_peer,
this.graph.peer(cb,
this.path_to_finally,
Term.ENTRY),
new FlowGraph.ExceptionEdgeKey(type));
definiteCatch = true;
}
// possible catch
else if (cb.catchType().isImplicitCastValid(type)) {
edge(last_peer,
this.graph.peer(cb,
this.path_to_finally,
Term.ENTRY),
new FlowGraph.ExceptionEdgeKey(cb.catchType()));
}
}
if (definiteCatch) {
// the exception has definitely been caught.
// we can stop recursing to outer try-catch blocks
return;
}
}
if (tr.finallyBlock() != null) {
if (exceptionEdgesToFinally) {
last_peer =
tryFinally(v,
last_peer,
last_peer.node == t,
new FlowGraph.ExceptionEdgeKey(type),
tr.finallyBlock());
}
else {
last_peer =
tryFinally(v,
last_peer,
last_peer.node == t,
tr.finallyBlock());
}
}
}
}
// If not caught, insert a node from the thrower to exit.
if (errorEdgesToExitNode || !type.isSubtype(ts.Error())) {
edge(last_peer, exitPeer(), new FlowGraph.ExceptionEdgeKey(type));
}
}
/**
* Create edges for the finally block of a try-finally construct.
*
* @param v v.innermostTarget is the Try term that the finallyBlock is assoicated with.
* @param last is the last peer visited before the finally block is entered.
* @param abruptCompletion is true if and only if the finally block is being entered
* due to the (attempted) abrupt completion of the term <code>last.node</code>.
* @param edgeKeyToFinally the EdgeKey to use for the edge going to the entry of the finally block. If null, then FlowGraph.EDGE_KEY_OTHER will be used.
* @param finallyBlock the finally block associated with a try finally block.
*/
protected static <FlowItem extends DataFlow.Item> Peer<FlowItem> tryFinally(
CFGBuilder<FlowItem> v, Peer<FlowItem> last,
boolean abruptCompletion, EdgeKey edgeKeyToFinally,
Block finallyBlock) {
CFGBuilder<FlowItem> v_ = v.outer.enterFinally(last, abruptCompletion);
Peer<FlowItem> finallyBlockEntryPeer =
v_.graph.peer(finallyBlock, v_.path_to_finally, Term.ENTRY);
if (edgeKeyToFinally == null) {
edgeKeyToFinally = FlowGraph.EDGE_KEY_OTHER;
}
v_.edge(last, finallyBlockEntryPeer, edgeKeyToFinally);
// visit the finally block.
v_.visitCFG(finallyBlock, Collections.<EdgeKeyTermPair> emptyList());
// the exit peer for the finally block.
Peer<FlowItem> finallyBlockExitPeer =
v_.graph.peer(finallyBlock, v_.path_to_finally, Term.EXIT);
return finallyBlockExitPeer;
}
/**
* Create edges for the finally block of a try-finally construct.
*
* @param v v.innermostTarget is the Try term that the finallyBlock is assoicated with.
* @param last is the last peer visited before the finally block is entered.
* @param abruptCompletion is true if and only if the finally block is being entered
* due to the (attempted) abrupt completion of the term <code>last.node</code>.
* @param finallyBlock the finally block associated with a try finally block.
*/
protected static <FlowItem extends DataFlow.Item> Peer<FlowItem> tryFinally(
CFGBuilder<FlowItem> v, Peer<FlowItem> last,
boolean abruptCompletion, Block finallyBlock) {
return tryFinally(v,
last,
abruptCompletion,
FlowGraph.EDGE_KEY_OTHER,
finallyBlock);
}
/**
* Enter a finally block. This method returns a new CFGBuilder
* with the path_to_finally set appropriately.
* If we are entering the finally block because peer <code>from</code> is
* (attempting to) complete abruptly, then the path_to_finally will have
* Term <code>from</code> appended to the path_to_finally list
* of <code>from</code>. Otherwise, <code>from</code> is not attempting
* to complete abruptly, and the path_to_finally will be the same as
* <code>from.path_to_finally</code>.
*
*/
protected CFGBuilder<FlowItem> enterFinally(Peer<FlowItem> from,
boolean abruptCompletion) {
if (abruptCompletion) {
CFGBuilder<FlowItem> v = this.copy();
v.path_to_finally =
new ArrayList<Term>(from.path_to_finally.size() + 1);
v.path_to_finally.addAll(from.path_to_finally);
v.path_to_finally.add(from.node);
return v;
}
else {
if (CollectionUtil.equals(this.path_to_finally,
from.path_to_finally)) {
return this;
}
CFGBuilder<FlowItem> v = this.copy();
v.path_to_finally = new ArrayList<Term>(from.path_to_finally);
return v;
}
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to either the
* entry or exit of <code>q</code>.
*/
public void edge(Term p, Term q, int qEntry) {
edge(this, p, q, qEntry, FlowGraph.EDGE_KEY_OTHER);
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to either the
* entry or exit of <code>q</code>.
*/
public void edge(Term p, Term q, int qEntry, FlowGraph.EdgeKey edgeKey) {
edge(this, p, q, qEntry, edgeKey);
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to either the
* entry or exit of <code>q</code>.
*/
public void edge(CFGBuilder<FlowItem> p_visitor, Term p, Term q,
int qEntry, FlowGraph.EdgeKey edgeKey) {
edge(p_visitor, p, Term.EXIT, q, qEntry, edgeKey);
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to peer pq.
*/
public void edge(CFGBuilder<FlowItem> p_visitor, Term p, Peer<FlowItem> pq,
FlowGraph.EdgeKey edgeKey) {
Peer<FlowItem> pp = graph.peer(p, p_visitor.path_to_finally, Term.EXIT);
edge(pp, pq, edgeKey);
}
/**
* @param p_visitor The visitor used to create p ("this" is the visitor
* that created q)
* @param p The predecessor node in the forward graph
* @param pEntry whether we are working with the entry or exit of p. Can be
* Term.ENTRY or Term.EXIT.
* @param q The successor node in the forward graph
* @param qEntry whether we are working with the entry or exit of q. Can be
* Term.ENTRY or Term.EXIT.
*/
public void edge(CFGBuilder<FlowItem> p_visitor, Term p, int pEntry,
Term q, int qEntry, FlowGraph.EdgeKey edgeKey) {
Peer<FlowItem> pp = graph.peer(p, p_visitor.path_to_finally, pEntry);
Peer<FlowItem> pq = graph.peer(q, path_to_finally, qEntry);
edge(pp, pq, edgeKey);
}
protected void edge(Peer<FlowItem> pp, Peer<FlowItem> pq,
FlowGraph.EdgeKey edgeKey) {
if (Report.should_report(Report.cfg, 2))
Report.report(2, "// edge " + pp.node() + " -> " + pq.node());
if (Report.should_report(Report.cfg, 3)) {
// at level 3, use Peer.toString() as the label for the nodes
Report.report(2,
pp.hashCode() + " [ label = \""
+ StringUtil.escape(pp.toString()) + "\" ];");
Report.report(2,
pq.hashCode() + " [ label = \""
+ StringUtil.escape(pq.toString()) + "\" ];");
}
else if (Report.should_report(Report.cfg, 2)) {
// at level 2, use Node.toString() as the label for the nodes
// which is more readable than Peer.toString(), but not as unique.
Report.report(2,
pp.hashCode() + " [ label = \""
+ StringUtil.escape(pp.node.toString())
+ "\" ];");
Report.report(2,
pq.hashCode() + " [ label = \""
+ StringUtil.escape(pq.node.toString())
+ "\" ];");
}
if (graph.forward()) {
if (Report.should_report(Report.cfg, 2)) {
Report.report(2, pp.hashCode() + " -> " + pq.hashCode()
+ " [label=\"" + edgeKey + "\"];");
}
pp.succs.add(new Edge<FlowItem>(edgeKey, pq));
pq.preds.add(new Edge<FlowItem>(edgeKey, pp));
}
else {
if (Report.should_report(Report.cfg, 2)) {
Report.report(2, pq.hashCode() + " -> " + pp.hashCode()
+ " [label=\"" + edgeKey + "\"];");
}
pq.succs.add(new Edge<FlowItem>(edgeKey, pp));
pp.preds.add(new Edge<FlowItem>(edgeKey, pq));
}
}
/**
* Should the CFG construction skip dead if branches? (e.g., should statement s be
* skipped in the following: if (false) { S } ). Different dataflow analyses require
* different behavior.
*/
public boolean skipDeadIfBranches() {
return this.skipDeadIfBranches;
}
public CFGBuilder<FlowItem> skipDeadIfBranches(boolean b) {
if (b == this.skipDeadIfBranches) {
return this;
}
CFGBuilder<FlowItem> v = copy();
v.skipDeadIfBranches = b;
return v;
}
/**
* Should the CFG construction skip dead loop bodies? (e.g., should statement s be
* skipped in the following: while (false) { S } ). Different dataflow analyses require
* different behavior.
*/
public boolean skipDeadLoopBodies() {
return this.skipDeadLoopBodies;
}
public CFGBuilder<FlowItem> skipDeadLoopBodies(boolean b) {
if (b == this.skipDeadLoopBodies) {
return this;
}
CFGBuilder<FlowItem> v = copy();
v.skipDeadLoopBodies = b;
return v;
}
}
| src/polyglot/visit/CFGBuilder.java | /*******************************************************************************
* This file is part of the Polyglot extensible compiler framework.
*
* Copyright (c) 2000-2012 Polyglot project group, Cornell University
* Copyright (c) 2006-2012 IBM Corporation
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This program and the accompanying materials are made available under
* the terms of the Lesser GNU Public License v2.0 which accompanies this
* distribution.
*
* The development of the Polyglot project has been supported by a
* number of funding sources, including DARPA Contract F30602-99-1-0533,
* monitored by USAF Rome Laboratory, ONR Grants N00014-01-1-0968 and
* N00014-09-1-0652, NSF Grants CNS-0208642, CNS-0430161, CCF-0133302,
* and CCF-1054172, AFRL Contract FA8650-10-C-7022, an Alfred P. Sloan
* Research Fellowship, and an Intel Research Ph.D. Fellowship.
*
* See README for contributors.
******************************************************************************/
package polyglot.visit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import polyglot.ast.Block;
import polyglot.ast.Branch;
import polyglot.ast.Catch;
import polyglot.ast.CodeNode;
import polyglot.ast.CompoundStmt;
import polyglot.ast.Labeled;
import polyglot.ast.Loop;
import polyglot.ast.Return;
import polyglot.ast.Stmt;
import polyglot.ast.Switch;
import polyglot.ast.Term;
import polyglot.ast.Try;
import polyglot.main.Report;
import polyglot.types.MemberInstance;
import polyglot.types.Type;
import polyglot.types.TypeSystem;
import polyglot.util.CollectionUtil;
import polyglot.util.Copy;
import polyglot.util.InternalCompilerError;
import polyglot.util.StringUtil;
import polyglot.visit.FlowGraph.Edge;
import polyglot.visit.FlowGraph.Peer;
/**
* Class used to construct a CFG.
*/
public class CFGBuilder<FlowItem extends DataFlow.Item> implements Copy {
/** The flowgraph under construction. */
protected FlowGraph<FlowItem> graph;
/** The type system. */
protected TypeSystem ts;
/**
* The outer CFGBuilder. We create a new inner CFGBuilder when entering a
* loop or try-block and when entering a finally block.
*/
protected CFGBuilder<FlowItem> outer;
/**
* The innermost loop or try-block in lexical scope. We maintain a stack
* of loops and try-blocks in order to add edges for break and continue
* statements and for exception throws. When such a jump is encountered we
* traverse the stack, searching for the target of the jump.
*/
protected Stmt innermostTarget;
/**
* Nodes in finally blocks need to be analyzed multiple times, once for each
* possible way to reach the finally block. The path_to_finally is used to
* distinguish these different "copies" of nodes in the finally block, and is
* a list of terms that attempted to complete normally that caused the finally
* block to be reached. If this CFGBuilder is for an AST that is not nested inside
* a finallyBlock, then path_to_finally will be empty.
*
* To explain by example, consider the following code (which is assumed to not
* be nested inside a finally block, and assume that S1 does not contain any
* try-finally block).
* <code>try { S1 } finally { S2 }</code>
* Assume that term t1 in S1 may complete abruptly. The code for S2 will be
* analyzed (at least) twice: once for normal termination of S1 (and so
* path_to_finally will be empty) and once for the abrupt completion of t1
* (and so path_to_finally will be [t1]).
*
* Consider the following code:
* <code>try { try { S1 } finally { S2 } } finally { S3 }</code>
* Assume that terms t1 in S1 and t2 in S2 may complete abruptly.
* Nodes in S2 will be analyzed (at least) twice, with path_to_finally empty
* (for normal termination of S1) and with path_to_empty equals [t1] (for
* abrupt completion of t1). S3 will be analyzed (at least) 3 times:
* once with path_to_finally empty (for normal termination of S1 and S2)
* once with path_to_finally equals [t1] (for abrupt completion of t1 and normal termination of S2), and
* once with path_to_finally equals [t1, t2] (for (attempted) abrupt completion of t1 and subsequent
* abrupt completion of t2).
*
* Consider the following code:
* <code>try { S1 } finally { try { S2 } finally { S3 } }</code>
* Assume that terms t1 in S1 and t2 in S2 may complete abruptly.
* Nodes in S2 will be analyzed (at least) twice, with path_to_finally empty
* (for normal termination of S1) and with path_to_empty equals [t1] (for
* abrupt completion of t1). S3 will be analyzed (at least) 3 times:
* once with path_to_finally empty (for normal termination of S1 and S2)
* once with path_to_finally equals [t1] (for abrupt completion of t1 and normal termination of S2), and
* once with path_to_finally equals [t1, t2] (for (attempted) abrupt completion of t1 and subsequent
* abrupt completion of t2).
*
*/
protected List<Term> path_to_finally;
/** The data flow analysis for which we are constructing the graph. */
protected DataFlow<FlowItem> df;
/**
* True if we should skip the catch blocks for the innermost try when
* building edges for an exception throw.
*/
protected boolean skipInnermostCatches;
/**
* True if we should skip dead if branches, such as S in "if (false) { S }".
* Different dataflow analyses have different requirements.
*/
protected boolean skipDeadIfBranches = false;
/**
* True if we should skip dead loop bodies, such as S in "while (false) { S }".
* Different dataflow analyses have different requirements.
*/
protected boolean skipDeadLoopBodies = false;
/**
* True if we should add edges for uncaught Errors to the exit node of the
* graph. By default, we do not, but subclasses can change this behavior
* if needed.
*/
protected boolean errorEdgesToExitNode;
public CFGBuilder(TypeSystem ts, FlowGraph<FlowItem> graph,
DataFlow<FlowItem> df) {
this.ts = ts;
this.graph = graph;
this.df = df;
this.path_to_finally = Collections.emptyList();
this.outer = null;
this.innermostTarget = null;
this.skipInnermostCatches = false;
this.errorEdgesToExitNode = false;
}
public FlowGraph<FlowItem> graph() {
return graph;
}
public DataFlow<FlowItem> dataflow() {
return df;
}
public CFGBuilder<FlowItem> outer() {
return outer;
}
public Stmt innermostTarget() {
return innermostTarget;
}
public boolean skipInnermostCatches() {
return skipInnermostCatches;
}
/** Get the type system. */
public TypeSystem typeSystem() {
return ts;
}
/** Copy the CFGBuilder. */
@Override
public CFGBuilder<FlowItem> copy() {
try {
@SuppressWarnings("unchecked")
CFGBuilder<FlowItem> clone = (CFGBuilder<FlowItem>) super.clone();
return clone;
}
catch (CloneNotSupportedException e) {
throw new InternalCompilerError("Java clone() weirdness.");
}
}
/**
* Construct a new CFGBuilder with the a new innermost loop or
* try-block <code>n</code>.
*/
public CFGBuilder<FlowItem> push(Stmt n) {
return push(n, false);
}
/**
* Construct a new CFGBuilder with the a new innermost loop or
* try-block <code>n</code>, optionally skipping innermost catch blocks.
*/
public CFGBuilder<FlowItem> push(Stmt n, boolean skipInnermostCatches) {
CFGBuilder<FlowItem> v = copy();
v.outer = this;
v.innermostTarget = n;
v.skipInnermostCatches = skipInnermostCatches;
return v;
}
/**
* Visit edges from a branch. Simulate breaking/continuing out of
* the loop, visiting any finally blocks encountered.
*/
public void visitBranchTarget(Branch b) {
Peer<FlowItem> last_peer =
graph.peer(b, this.path_to_finally, Term.EXIT);
for (CFGBuilder<FlowItem> v = this; v != null; v = v.outer) {
Term c = v.innermostTarget;
if (c instanceof Try) {
Try tr = (Try) c;
if (tr.finallyBlock() != null) {
last_peer =
tryFinally(v,
last_peer,
last_peer.node == b,
tr.finallyBlock());
}
}
if (b.label() != null) {
if (c instanceof Labeled) {
Labeled l = (Labeled) c;
if (l.label().equals(b.label())) {
if (b.kind() == Branch.BREAK) {
edge(last_peer,
this.graph().peer(l,
this.path_to_finally,
Term.EXIT),
FlowGraph.EDGE_KEY_OTHER);
}
else {
Stmt s = l.statement();
if (s instanceof Loop) {
Loop loop = (Loop) s;
edge(last_peer,
this.graph().peer(loop.continueTarget(),
this.path_to_finally,
Term.ENTRY),
FlowGraph.EDGE_KEY_OTHER);
}
else {
throw new CFGBuildError("Target of continue statement must "
+ "be a loop.",
l.position());
}
}
return;
}
}
}
else {
if (c instanceof Loop) {
Loop l = (Loop) c;
if (b.kind() == Branch.CONTINUE) {
edge(last_peer,
this.graph().peer(l.continueTarget(),
this.path_to_finally,
Term.ENTRY),
FlowGraph.EDGE_KEY_OTHER);
}
else {
edge(last_peer,
this.graph().peer(l,
this.path_to_finally,
Term.EXIT),
FlowGraph.EDGE_KEY_OTHER);
}
return;
}
else if (c instanceof Switch && b.kind() == Branch.BREAK) {
edge(last_peer,
this.graph().peer(c, this.path_to_finally, Term.EXIT),
FlowGraph.EDGE_KEY_OTHER);
return;
}
}
}
throw new CFGBuildError("Target of branch statement not found.",
b.position());
}
/**
* Visit edges for a return statement. Simulate the return, visiting any
* finally blocks encountered.
*/
public void visitReturn(Return r) {
Peer<FlowItem> last_peer =
this.graph().peer(r, this.path_to_finally, Term.EXIT);
for (CFGBuilder<FlowItem> v = this; v != null; v = v.outer) {
Term c = v.innermostTarget;
if (c instanceof Try) {
Try tr = (Try) c;
if (tr.finallyBlock() != null) {
last_peer =
tryFinally(v,
last_peer,
last_peer.node == r,
tr.finallyBlock());
}
}
}
// Add an edge to the exit node.
edge(last_peer, exitPeer(), FlowGraph.EDGE_KEY_OTHER);
}
protected static int counter = 0;
/** Visit the AST, constructing the CFG. */
public void visitGraph() {
String name = StringUtil.getShortNameComponent(df.getClass().getName());
name += counter++;
if (Report.should_report(Report.cfg, 2)) {
String rootName = "";
if (graph.root() instanceof CodeNode) {
CodeNode cd = (CodeNode) graph.root();
rootName = cd.codeInstance().toString();
if (cd.codeInstance() instanceof MemberInstance) {
rootName +=
" in "
+ ((MemberInstance) cd.codeInstance()).container()
.toString();
}
}
Report.report(2, "digraph CFGBuild" + name + " {");
Report.report(2,
" label=\"CFGBuilder: "
+ name
+ "\\n"
+ rootName
+ "\"; fontsize=20; center=true; ratio=auto; size = \"8.5,11\";");
}
// create peers for the entry and exit nodes.
entryPeer();
exitPeer();
this.visitCFG(graph.root(), Collections.<EdgeKeyTermPair> emptyList());
if (Report.should_report(Report.cfg, 2)) Report.report(2, "}");
}
/**
* Utility method to get the peer for the entry of the flow graph.
*/
protected Peer<FlowItem> entryPeer() {
return graph.peer(graph.root(),
Collections.<Term> emptyList(),
Term.ENTRY);
}
/**
* Utility method to get the peer for the exit of the flow graph.
*/
protected Peer<FlowItem> exitPeer() {
return graph.peer(graph.root(),
Collections.<Term> emptyList(),
Term.EXIT);
}
/**
* Utility function to visit all edges in a list.
*
* If <code>entry</code> is Term.ENTRY, the final successor is
* <code>after</code>'s entry node; if it's Term.EXIT, it's
* <code>after</code>'s exit.
*/
public void visitCFGList(List<? extends Term> elements, Term after,
int entry) {
Term prev = null;
for (Term c : elements) {
if (prev != null) {
visitCFG(prev, c, Term.ENTRY);
}
prev = c;
}
if (prev != null) {
visitCFG(prev, after, entry);
}
}
/**
* Create an edge for a node <code>a</code> with a single successor
* <code>succ</code>.
*
* The EdgeKey used for the edge from <code>a</code> to <code>succ</code>
* will be FlowGraph.EDGE_KEY_OTHER.
*
* If <code>entry</code> is Term.ENTRY, the successor is <code>succ</code>'s
* entry node; if it's Term.EXIT, it's <code>succ</code>'s exit.
*/
public void visitCFG(Term a, Term succ, int entry) {
visitCFG(a, FlowGraph.EDGE_KEY_OTHER, succ, entry);
}
/**
* Create an edge for a node <code>a</code> with a single successor
* <code>succ</code>, and EdgeKey <code>edgeKey</code>.
*
* If <code>entry</code> is Term.ENTRY, the successor is <code>succ</code>'s
* entry node; if it's Term.EXIT, it's <code>succ</code>'s exit.
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey, Term succ, int entry) {
visitCFG(a,
CollectionUtil.list(new EdgeKeyTermPair(edgeKey, succ, entry)));
}
/**
* Create edges from node <code>a</code> to successors <code>succ1</code>
* and <code>succ2</code> with EdgeKeys <code>edgeKey1</code> and
* <code>edgeKey2</code> respecitvely.
*
* <code>entry1</code> and <code>entry2</code> determine whether the
* successors are entry or exit nodes. They can be Term.ENTRY or Term.EXIT.
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey1, Term succ1,
int entry1, FlowGraph.EdgeKey edgeKey2, Term succ2, int entry2) {
visitCFG(a, CollectionUtil.list(new EdgeKeyTermPair(edgeKey1,
succ1,
entry1),
new EdgeKeyTermPair(edgeKey2,
succ2,
entry2)));
}
/**
* Create edges from node <code>a</code> to all successors <code>succ</code>
* with the EdgeKey <code>edgeKey</code> for all edges created.
*
* If <code>entry</code> is Term.ENTRY, all terms in <code>succ</code> are
* treated as entry nodes; if it's Term.EXIT, they are treated as exit
* nodes.
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey, List<Term> succ,
int entry) {
List<EdgeKeyTermPair> l = new ArrayList<EdgeKeyTermPair>(succ.size());
for (Term t : succ) {
l.add(new EdgeKeyTermPair(edgeKey, t, entry));
}
visitCFG(a, l);
}
/**
* Create edges from node <code>a</code> to all successors
* <code>succ</code> with the EdgeKey <code>edgeKey</code> for all edges
* created.
*
* The <code>entry</code> list must have the same size as
* <code>succ</code>, and each corresponding element determines whether a
* successor is an entry or exit node (using Term.ENTRY or Term.EXIT).
*/
public void visitCFG(Term a, FlowGraph.EdgeKey edgeKey, List<Term> succ,
List<Integer> entry) {
if (succ.size() != entry.size()) {
throw new IllegalArgumentException();
}
List<EdgeKeyTermPair> l = new ArrayList<EdgeKeyTermPair>(succ.size());
for (int i = 0; i < succ.size(); i++) {
Term t = succ.get(i);
l.add(new EdgeKeyTermPair(edgeKey, t, entry.get(i).intValue()));
}
visitCFG(a, l);
}
protected static class EdgeKeyTermPair {
public final FlowGraph.EdgeKey edgeKey;
public final Term term;
public final int entry;
public EdgeKeyTermPair(FlowGraph.EdgeKey edgeKey, Term term, int entry) {
this.edgeKey = edgeKey;
this.term = term;
this.entry = entry;
}
@Override
public String toString() {
return "{edgeKey=" + edgeKey + ",term=" + term + ","
+ (entry == Term.ENTRY ? "entry" : "exit") + "}";
}
}
/**
* Create edges for a node <code>a</code> with successors
* <code>succs</code>.
*
* @param a the source node for the edges.
* @param succs a list of <code>EdgeKeyTermPair</code>s
*/
protected void visitCFG(Term a, List<EdgeKeyTermPair> succs) {
Term child = a.firstChild();
if (child == null) {
edge(this, a, Term.ENTRY, a, Term.EXIT, FlowGraph.EDGE_KEY_OTHER);
}
else {
edge(this,
a,
Term.ENTRY,
child,
Term.ENTRY,
FlowGraph.EDGE_KEY_OTHER);
}
if (Report.should_report(Report.cfg, 2))
Report.report(2, "// node " + a + " -> " + succs);
succs = a.acceptCFG(this, succs);
for (EdgeKeyTermPair s : succs) {
edge(a, s.term, s.entry, s.edgeKey);
}
visitThrow(a);
}
public void visitThrow(Term a) {
for (Type type : a.del().throwTypes(ts)) {
visitThrow(a, Term.EXIT, type);
}
// Every statement can throw an error.
// This is probably too inefficient.
if ((a instanceof Stmt && !(a instanceof CompoundStmt))
|| (a instanceof Block && ((Block) a).statements().isEmpty())) {
visitThrow(a, Term.EXIT, ts.Error());
}
}
/**
* Create edges for an exception thrown from term <code>t</code>.
*/
public void visitThrow(Term t, int entry, Type type) {
Peer<FlowItem> last_peer =
this.graph.peer(t, this.path_to_finally, entry);
for (CFGBuilder<FlowItem> v = this; v != null; v = v.outer) {
Term c = v.innermostTarget;
if (c instanceof Try) {
Try tr = (Try) c;
if (!v.skipInnermostCatches) {
boolean definiteCatch = false;
for (Catch cb : tr.catchBlocks()) {
// definite catch
if (type.isImplicitCastValid(cb.catchType())) {
edge(last_peer,
this.graph.peer(cb,
this.path_to_finally,
Term.ENTRY),
new FlowGraph.ExceptionEdgeKey(type));
definiteCatch = true;
}
// possible catch
else if (cb.catchType().isImplicitCastValid(type)) {
edge(last_peer,
this.graph.peer(cb,
this.path_to_finally,
Term.ENTRY),
new FlowGraph.ExceptionEdgeKey(cb.catchType()));
}
}
if (definiteCatch) {
// the exception has definitely been caught.
// we can stop recursing to outer try-catch blocks
return;
}
}
if (tr.finallyBlock() != null) {
last_peer =
tryFinally(v,
last_peer,
last_peer.node == t,
tr.finallyBlock());
}
}
}
// If not caught, insert a node from the thrower to exit.
if (errorEdgesToExitNode || !type.isSubtype(ts.Error())) {
edge(last_peer, exitPeer(), new FlowGraph.ExceptionEdgeKey(type));
}
}
/**
* Create edges for the finally block of a try-finally construct.
*
* @param v v.innermostTarget is the Try term that the finallyBlock is assoicated with.
* @param last is the last peer visited before the finally block is entered.
* @param abruptCompletion is true if and only if the finally block is being entered
* due to the (attempted) abrupt completion of the term <code>last.node</code>.
* @param finallyBlock the finally block associated with a try finally block.
*/
protected static <FlowItem extends DataFlow.Item> Peer<FlowItem> tryFinally(
CFGBuilder<FlowItem> v, Peer<FlowItem> last,
boolean abruptCompletion, Block finallyBlock) {
CFGBuilder<FlowItem> v_ = v.outer.enterFinally(last, abruptCompletion);
Peer<FlowItem> finallyBlockEntryPeer =
v_.graph.peer(finallyBlock, v_.path_to_finally, Term.ENTRY);
v_.edge(last, finallyBlockEntryPeer, FlowGraph.EDGE_KEY_OTHER);
// visit the finally block.
v_.visitCFG(finallyBlock, Collections.<EdgeKeyTermPair> emptyList());
// the ext peer for the finally block.
Peer<FlowItem> finallyBlockExitPeer =
v_.graph.peer(finallyBlock, v_.path_to_finally, Term.EXIT);
return finallyBlockExitPeer;
}
/**
* Enter a finally block. This method returns a new CFGBuilder
* with the path_to_finally set appropriately.
* If we are entering the finally block because peer <code>from</code> is
* (attempting to) complete abruptly, then the path_to_finally will have
* Term <code>from</code> appended to the path_to_finally list
* of <code>from</code>. Otherwise, <code>from</code> is not attempting
* to complete abruptly, and the path_to_finally will be the same as
* <code>from.path_to_finally</code>.
*
*/
protected CFGBuilder<FlowItem> enterFinally(Peer<FlowItem> from,
boolean abruptCompletion) {
if (abruptCompletion) {
CFGBuilder<FlowItem> v = this.copy();
v.path_to_finally =
new ArrayList<Term>(from.path_to_finally.size() + 1);
v.path_to_finally.addAll(from.path_to_finally);
v.path_to_finally.add(from.node);
return v;
}
else {
if (CollectionUtil.equals(this.path_to_finally,
from.path_to_finally)) {
return this;
}
CFGBuilder<FlowItem> v = this.copy();
v.path_to_finally = new ArrayList<Term>(from.path_to_finally);
return v;
}
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to either the
* entry or exit of <code>q</code>.
*/
public void edge(Term p, Term q, int qEntry) {
edge(this, p, q, qEntry, FlowGraph.EDGE_KEY_OTHER);
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to either the
* entry or exit of <code>q</code>.
*/
public void edge(Term p, Term q, int qEntry, FlowGraph.EdgeKey edgeKey) {
edge(this, p, q, qEntry, edgeKey);
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to either the
* entry or exit of <code>q</code>.
*/
public void edge(CFGBuilder<FlowItem> p_visitor, Term p, Term q,
int qEntry, FlowGraph.EdgeKey edgeKey) {
edge(p_visitor, p, Term.EXIT, q, qEntry, edgeKey);
}
/**
* Add an edge to the CFG from the exit of <code>p</code> to peer pq.
*/
public void edge(CFGBuilder<FlowItem> p_visitor, Term p, Peer<FlowItem> pq,
FlowGraph.EdgeKey edgeKey) {
Peer<FlowItem> pp = graph.peer(p, p_visitor.path_to_finally, Term.EXIT);
edge(pp, pq, edgeKey);
}
/**
* @param p_visitor The visitor used to create p ("this" is the visitor
* that created q)
* @param p The predecessor node in the forward graph
* @param pEntry whether we are working with the entry or exit of p. Can be
* Term.ENTRY or Term.EXIT.
* @param q The successor node in the forward graph
* @param qEntry whether we are working with the entry or exit of q. Can be
* Term.ENTRY or Term.EXIT.
*/
public void edge(CFGBuilder<FlowItem> p_visitor, Term p, int pEntry,
Term q, int qEntry, FlowGraph.EdgeKey edgeKey) {
Peer<FlowItem> pp = graph.peer(p, p_visitor.path_to_finally, pEntry);
Peer<FlowItem> pq = graph.peer(q, path_to_finally, qEntry);
edge(pp, pq, edgeKey);
}
protected void edge(Peer<FlowItem> pp, Peer<FlowItem> pq,
FlowGraph.EdgeKey edgeKey) {
if (Report.should_report(Report.cfg, 2))
Report.report(2, "// edge " + pp.node() + " -> " + pq.node());
if (Report.should_report(Report.cfg, 3)) {
// at level 3, use Peer.toString() as the label for the nodes
Report.report(2,
pp.hashCode() + " [ label = \""
+ StringUtil.escape(pp.toString()) + "\" ];");
Report.report(2,
pq.hashCode() + " [ label = \""
+ StringUtil.escape(pq.toString()) + "\" ];");
}
else if (Report.should_report(Report.cfg, 2)) {
// at level 2, use Node.toString() as the label for the nodes
// which is more readable than Peer.toString(), but not as unique.
Report.report(2,
pp.hashCode() + " [ label = \""
+ StringUtil.escape(pp.node.toString())
+ "\" ];");
Report.report(2,
pq.hashCode() + " [ label = \""
+ StringUtil.escape(pq.node.toString())
+ "\" ];");
}
if (graph.forward()) {
if (Report.should_report(Report.cfg, 2)) {
Report.report(2, pp.hashCode() + " -> " + pq.hashCode()
+ " [label=\"" + edgeKey + "\"];");
}
pp.succs.add(new Edge<FlowItem>(edgeKey, pq));
pq.preds.add(new Edge<FlowItem>(edgeKey, pp));
}
else {
if (Report.should_report(Report.cfg, 2)) {
Report.report(2, pq.hashCode() + " -> " + pp.hashCode()
+ " [label=\"" + edgeKey + "\"];");
}
pq.succs.add(new Edge<FlowItem>(edgeKey, pp));
pp.preds.add(new Edge<FlowItem>(edgeKey, pq));
}
}
/**
* Should the CFG construction skip dead if branches? (e.g., should statement s be
* skipped in the following: if (false) { S } ). Different dataflow analyses require
* different behavior.
*/
public boolean skipDeadIfBranches() {
return this.skipDeadIfBranches;
}
public CFGBuilder<FlowItem> skipDeadIfBranches(boolean b) {
if (b == this.skipDeadIfBranches) {
return this;
}
CFGBuilder<FlowItem> v = copy();
v.skipDeadIfBranches = b;
return v;
}
/**
* Should the CFG construction skip dead loop bodies? (e.g., should statement s be
* skipped in the following: while (false) { S } ). Different dataflow analyses require
* different behavior.
*/
public boolean skipDeadLoopBodies() {
return this.skipDeadLoopBodies;
}
public CFGBuilder<FlowItem> skipDeadLoopBodies(boolean b) {
if (b == this.skipDeadLoopBodies) {
return this;
}
CFGBuilder<FlowItem> v = copy();
v.skipDeadLoopBodies = b;
return v;
}
}
| Allow edges to finally blocks to be labelled with the exception that caused them. Set by a flag, and needed by subclasses in order to implement required functionality in dataflow analyses.
| src/polyglot/visit/CFGBuilder.java | Allow edges to finally blocks to be labelled with the exception that caused them. Set by a flag, and needed by subclasses in order to implement required functionality in dataflow analyses. | <ide><path>rc/polyglot/visit/CFGBuilder.java
<ide> import polyglot.util.InternalCompilerError;
<ide> import polyglot.util.StringUtil;
<ide> import polyglot.visit.FlowGraph.Edge;
<add>import polyglot.visit.FlowGraph.EdgeKey;
<ide> import polyglot.visit.FlowGraph.Peer;
<ide>
<ide> /**
<ide> */
<ide> protected boolean errorEdgesToExitNode;
<ide>
<add> /**
<add> * Should we add exception edges into finally blocks? If true, then the edge from
<add> * an AST node that throws an exception to a finally block will be labeled with the
<add> * appropriate exception; if false, then the edge will be labeled OTHER.
<add> * For backwards compatibility, the default value is false.
<add> */
<add> protected boolean exceptionEdgesToFinally;
<add>
<ide> public CFGBuilder(TypeSystem ts, FlowGraph<FlowItem> graph,
<ide> DataFlow<FlowItem> df) {
<ide> this.ts = ts;
<ide> this.innermostTarget = null;
<ide> this.skipInnermostCatches = false;
<ide> this.errorEdgesToExitNode = false;
<add> this.exceptionEdgesToFinally = false;
<ide> }
<ide>
<ide> public FlowGraph<FlowItem> graph() {
<ide> }
<ide>
<ide> if (tr.finallyBlock() != null) {
<del> last_peer =
<del> tryFinally(v,
<del> last_peer,
<del> last_peer.node == t,
<del> tr.finallyBlock());
<add> if (exceptionEdgesToFinally) {
<add> last_peer =
<add> tryFinally(v,
<add> last_peer,
<add> last_peer.node == t,
<add> new FlowGraph.ExceptionEdgeKey(type),
<add> tr.finallyBlock());
<add> }
<add> else {
<add> last_peer =
<add> tryFinally(v,
<add> last_peer,
<add> last_peer.node == t,
<add> tr.finallyBlock());
<add> }
<ide> }
<ide> }
<ide> }
<ide> if (errorEdgesToExitNode || !type.isSubtype(ts.Error())) {
<ide> edge(last_peer, exitPeer(), new FlowGraph.ExceptionEdgeKey(type));
<ide> }
<add> }
<add>
<add> /**
<add> * Create edges for the finally block of a try-finally construct.
<add> *
<add> * @param v v.innermostTarget is the Try term that the finallyBlock is assoicated with.
<add> * @param last is the last peer visited before the finally block is entered.
<add> * @param abruptCompletion is true if and only if the finally block is being entered
<add> * due to the (attempted) abrupt completion of the term <code>last.node</code>.
<add> * @param edgeKeyToFinally the EdgeKey to use for the edge going to the entry of the finally block. If null, then FlowGraph.EDGE_KEY_OTHER will be used.
<add> * @param finallyBlock the finally block associated with a try finally block.
<add> */
<add> protected static <FlowItem extends DataFlow.Item> Peer<FlowItem> tryFinally(
<add> CFGBuilder<FlowItem> v, Peer<FlowItem> last,
<add> boolean abruptCompletion, EdgeKey edgeKeyToFinally,
<add> Block finallyBlock) {
<add> CFGBuilder<FlowItem> v_ = v.outer.enterFinally(last, abruptCompletion);
<add>
<add> Peer<FlowItem> finallyBlockEntryPeer =
<add> v_.graph.peer(finallyBlock, v_.path_to_finally, Term.ENTRY);
<add>
<add> if (edgeKeyToFinally == null) {
<add> edgeKeyToFinally = FlowGraph.EDGE_KEY_OTHER;
<add> }
<add> v_.edge(last, finallyBlockEntryPeer, edgeKeyToFinally);
<add>
<add> // visit the finally block.
<add> v_.visitCFG(finallyBlock, Collections.<EdgeKeyTermPair> emptyList());
<add>
<add> // the exit peer for the finally block.
<add> Peer<FlowItem> finallyBlockExitPeer =
<add> v_.graph.peer(finallyBlock, v_.path_to_finally, Term.EXIT);
<add> return finallyBlockExitPeer;
<ide> }
<ide>
<ide> /**
<ide> protected static <FlowItem extends DataFlow.Item> Peer<FlowItem> tryFinally(
<ide> CFGBuilder<FlowItem> v, Peer<FlowItem> last,
<ide> boolean abruptCompletion, Block finallyBlock) {
<del> CFGBuilder<FlowItem> v_ = v.outer.enterFinally(last, abruptCompletion);
<del>
<del> Peer<FlowItem> finallyBlockEntryPeer =
<del> v_.graph.peer(finallyBlock, v_.path_to_finally, Term.ENTRY);
<del> v_.edge(last, finallyBlockEntryPeer, FlowGraph.EDGE_KEY_OTHER);
<del>
<del> // visit the finally block.
<del> v_.visitCFG(finallyBlock, Collections.<EdgeKeyTermPair> emptyList());
<del>
<del> // the ext peer for the finally block.
<del> Peer<FlowItem> finallyBlockExitPeer =
<del> v_.graph.peer(finallyBlock, v_.path_to_finally, Term.EXIT);
<del> return finallyBlockExitPeer;
<add> return tryFinally(v,
<add> last,
<add> abruptCompletion,
<add> FlowGraph.EDGE_KEY_OTHER,
<add> finallyBlock);
<ide> }
<ide>
<ide> /** |
|
Java | mit | 7b428f26cdc68287280dcd5c158555ccb3cccf99 | 0 | davidcarboni/Cryptolite | package com.github.davidcarboni.cryptolite;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
/**
*
* This class provides the ability to convert a byte array to Base-64 and back,
* or to a hexadecimal string for printing out.
* <p>
* It also provides for converting text String objects to and from a byte array.
*
* @author David Carboni
*
*/
public class Codec {
/**
* The encoding to use for string operations.
*/
public static final String ENCODING = "UTF8";
/**
* Renders the given byte array as a hex String. This is a convenience
* method useful for checking values during development.
* <p>
* Internally, this checks for null and then calls the Apache commons-codec
* method {@link Hex#encodeHexString(byte[])}.
*
* @param bytes
* The array to be rendered.
* @return A string representation of the byte array.
*/
public static String toHexString(byte[] bytes) {
if (bytes == null) {
return null;
}
return Hex.encodeHexString(bytes);
}
/**
* Encodes the given byte array as a base-64 String.
*
* Internally, this checks for null and then calls the Apache commons-codec
* method {@link Base64#encodeBase64String(byte[])}.
*
* @param bytes
* The array to be encoded.
* @return The byte array encoded using base-64.
*/
public static String toBase64String(byte[] bytes) {
if (bytes == null) {
return null;
}
return Base64.encodeBase64String(bytes);
}
/**
* Decodes the given base-64 string into a byte array.
*
* @param base64
* A base-64 encoded string.
* @return The decoded byte array.
*/
public static byte[] fromBase64String(String base64) {
return Base64.decodeBase64(base64);
}
/**
* Converts the given String to a byte array using {@value #ENCODING}.
*
* @param string
* The String to be converted to a byte array.
* @return A byte array representing the String.
*/
public static byte[] toByteArray(String string) {
if (string == null) {
return null;
}
try {
return string.getBytes(ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error converting String to byte array using encoding " + ENCODING);
}
}
/**
* Converts the given byte array to a String using {@value #ENCODING}.
*
* @param bytes
* The byte array to be converted to a String.
* @return The String represented by the given bytes.
*/
public static String fromByteArray(byte[] bytes) {
if (bytes == null) {
return null;
}
try {
return new String(bytes, ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error converting byte array to String using encoding " + ENCODING);
}
}
}
| src/main/java/com/github/davidcarboni/cryptolite/Codec.java | package com.github.davidcarboni.cryptolite;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
/**
*
* This class provides the ability to convert a byte array to Base-64 and back, or to a hexadecimal
* string for printing out.
* <p>
* It also provides for converting text String objects to and from a byte array.
*
* @author David Carboni
*
*/
public class Codec {
/**
* The encoding to use for string operations.
*/
public static final String ENCODING = "UTF8";
/**
* Renders the given byte array as a hex String. This is a convenience method useful for
* checking values during development.
* <p>
* Internally, this checks for null and then calls the Apache commons-codec method
* {@link Hex#encodeHexString(byte[])}.
*
* @param bytes
* The array to be rendered.
* @return A string representation of the byte array.
*/
public static String toHexString(byte[] bytes) {
if (bytes == null) {
return null;
}
return Hex.encodeHexString(bytes);
}
/**
* Encodes the given byte array as a base-64 String.
*
* @param bytes
* The array to be encoded.
* @return The byte array encoded using base-64.
*/
public static String toBase64String(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
/**
* Decodes the given base-64 string into a byte array.
*
* @param base64
* A base-64 encoded string.
* @return The decoded byte array.
*/
public static byte[] fromBase64String(String base64) {
return Base64.decodeBase64(base64);
}
/**
* Converts the given String to a byte array using {@value #ENCODING}.
*
* @param string
* The String to be converted to a byte array.
* @return A byte array representing the String.
*/
public static byte[] toByteArray(String string) {
if (string == null) {
return null;
}
try {
return string.getBytes(ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error converting String to byte array using encoding " + ENCODING);
}
}
/**
* Converts the given byte array to a String using {@value #ENCODING}.
*
* @param bytes
* The byte array to be converted to a String.
* @return A byte array representing the String.
*/
public static String fromByteArray(byte[] bytes) {
if (bytes == null) {
return null;
}
try {
return new String(bytes, ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error converting byte array to String using encoding " + ENCODING);
}
}
}
| Added a null check to toBase64String and cleaned up Javadoc. | src/main/java/com/github/davidcarboni/cryptolite/Codec.java | Added a null check to toBase64String and cleaned up Javadoc. | <ide><path>rc/main/java/com/github/davidcarboni/cryptolite/Codec.java
<ide>
<ide> /**
<ide> *
<del> * This class provides the ability to convert a byte array to Base-64 and back, or to a hexadecimal
<del> * string for printing out.
<add> * This class provides the ability to convert a byte array to Base-64 and back,
<add> * or to a hexadecimal string for printing out.
<ide> * <p>
<ide> * It also provides for converting text String objects to and from a byte array.
<ide> *
<ide> public static final String ENCODING = "UTF8";
<ide>
<ide> /**
<del> * Renders the given byte array as a hex String. This is a convenience method useful for
<del> * checking values during development.
<add> * Renders the given byte array as a hex String. This is a convenience
<add> * method useful for checking values during development.
<ide> * <p>
<del> * Internally, this checks for null and then calls the Apache commons-codec method
<del> * {@link Hex#encodeHexString(byte[])}.
<add> * Internally, this checks for null and then calls the Apache commons-codec
<add> * method {@link Hex#encodeHexString(byte[])}.
<ide> *
<ide> * @param bytes
<ide> * The array to be rendered.
<ide> /**
<ide> * Encodes the given byte array as a base-64 String.
<ide> *
<add> * Internally, this checks for null and then calls the Apache commons-codec
<add> * method {@link Base64#encodeBase64String(byte[])}.
<add> *
<ide> * @param bytes
<ide> * The array to be encoded.
<ide> * @return The byte array encoded using base-64.
<ide> */
<ide> public static String toBase64String(byte[] bytes) {
<add>
<add> if (bytes == null) {
<add> return null;
<add> }
<add>
<ide> return Base64.encodeBase64String(bytes);
<ide> }
<ide>
<ide> *
<ide> * @param bytes
<ide> * The byte array to be converted to a String.
<del> * @return A byte array representing the String.
<add> * @return The String represented by the given bytes.
<ide> */
<ide> public static String fromByteArray(byte[] bytes) {
<ide> |
|
Java | apache-2.0 | 47a90af4c2bcf55083b1441bfacebae8d69cfd5d | 0 | junkerm/specmate,junkerm/specmate,junkerm/specmate,junkerm/specmate,junkerm/specmate | package com.specmate.uitests;
import org.junit.*;
import org.junit.rules.TestName;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.model.Statement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
//import com.saucelabs.junit.SauceOnDemandTestWatcher;
import com.specmate.uitests.pagemodel.LoginElements;
import java.net.URL;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import com.saucelabs.common.SauceOnDemandSessionIdProvider;
@Ignore
@RunWith(Parameterized.class)
public class TestBase implements SauceOnDemandSessionIdProvider {
public static String username = System.getenv("SAUCE_USERNAME");
public static String accesskey = System.getenv("SAUCE_ACCESS_KEY");
public static String seleniumURI;
public static String buildTag;
public static final String tunnelidentifier = System.getenv("TRAVIS_JOB_NUMBER");
private static boolean result;
@Rule
public final TestWatcher watcher = new TestWatcher() {
@Override
public Statement apply(Statement base, Description description) {
return super.apply(base, description);
}
@Override
protected void failed(Throwable e, Description description) {
result = false;
}
@Override
protected void succeeded(Description description) {
result = true;
}
};
@Rule
public TestName name = new TestName() {
public String getMethodName() {
return String.format("%s", super.getMethodName());
}
};
protected String browser;
protected String os;
protected String version;
protected String deviceName;
protected String deviceOrientation;
protected String sessionId;
protected WebDriver driver;
/**Constructor for test instances*/
public TestBase(String os, String version, String browser, String deviceName, String deviceOrientation) {
super();
this.os = os;
this.version = version;
this.browser = browser;
this.deviceName = deviceName;
this.deviceOrientation = deviceOrientation;
}
/**Browser configurations*/
@Parameters
public static LinkedList<String[]> browsersStrings() {
LinkedList<String[]> browsers = new LinkedList<String[]>();
browsers.add(new String[]{"Windows 10", "59.0", "Chrome", null, null});
//browsers.add(new String[]{"Windows 10", "14.14393", "MicrosoftEdge", null, null});
//browsers.add(new String[]{"Windows 10", "11.0", "internet explorer", null, null});
return browsers;
}
@Before
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
capabilities.setCapability(CapabilityType.VERSION, version);
capabilities.setCapability("deviceName", deviceName);
capabilities.setCapability("device-orientation", deviceOrientation);
capabilities.setCapability("platform", os);
capabilities.setCapability("tunnel-identifier", tunnelidentifier);
String methodName = name.getMethodName();
capabilities.setCapability("name", methodName);
if (buildTag != null) {
capabilities.setCapability("build", buildTag);
}
this.driver = new RemoteWebDriver(new URL("https://" + username+ ":" + accesskey + seleniumURI +"/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
this.sessionId = (((RemoteWebDriver) driver).getSessionId()).toString();
}
@After
public void tearDown() throws Exception {
((JavascriptExecutor)driver).executeScript("sauce:job-result=" + (result ? "passed" : "failed"));
driver.quit();
}
public String getSessionId() {
return sessionId;
}
@BeforeClass
public static void setupClass() {
// Get the uri to send the commands to
seleniumURI = "@ondemand.saucelabs.com:443";
// Set the buildTag to the Travis Build number
buildTag = System.getenv("TRAVIS_BUILD_NUMBER");
if (buildTag == null) {
buildTag = System.getenv("SAUCE_BUILD_NAME");
}
}
public void performLogin(LoginElements login) {
login.username("username");
login.password("password");
login.changeToEnglish();
login.changeToGerman();
login.changeToProject("test-data");
login.login();
}
}
| ui-tests/src/test/java/com/specmate/uitests/TestBase.java | package com.specmate.uitests;
import com.saucelabs.common.SauceOnDemandAuthentication;
import org.junit.*;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
//import com.saucelabs.junit.SauceOnDemandTestWatcher;
import com.specmate.uitests.pagemodel.LoginElements;
import java.net.URL;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import com.saucelabs.common.SauceOnDemandSessionIdProvider;
@Ignore
@RunWith(Parameterized.class)
public class TestBase implements SauceOnDemandSessionIdProvider {
public static String username = System.getenv("SAUCE_USERNAME");
public static String accesskey = System.getenv("SAUCE_ACCESS_KEY");
public static String seleniumURI;
public static String buildTag;
public static final String tunnelidentifier = System.getenv("TRAVIS_JOB_NUMBER");
//public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication();
/**Mark the Sauce Job as passed/failed when the test succeeds or fails*/
//@Rule
//public SauceOnDemandTestWatcher resultReportingTestWatcher = new SauceOnDemandTestWatcher(this, authentication);
@Rule
public TestName name = new TestName() {
public String getMethodName() {
return String.format("%s", super.getMethodName());
}
};
protected String browser;
protected String os;
protected String version;
protected String deviceName;
protected String deviceOrientation;
protected String sessionId;
protected WebDriver driver;
/**Constructor for test instances*/
public TestBase(String os, String version, String browser, String deviceName, String deviceOrientation) {
super();
this.os = os;
this.version = version;
this.browser = browser;
this.deviceName = deviceName;
this.deviceOrientation = deviceOrientation;
}
/**Browser configurations*/
@Parameters
public static LinkedList<String[]> browsersStrings() {
LinkedList<String[]> browsers = new LinkedList<String[]>();
browsers.add(new String[]{"Windows 10", "59.0", "Chrome", null, null});
//browsers.add(new String[]{"Windows 10", "14.14393", "MicrosoftEdge", null, null});
//browsers.add(new String[]{"Windows 10", "11.0", "internet explorer", null, null});
return browsers;
}
@Before
public void setUp() throws Exception {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
capabilities.setCapability(CapabilityType.VERSION, version);
capabilities.setCapability("deviceName", deviceName);
capabilities.setCapability("device-orientation", deviceOrientation);
capabilities.setCapability("platform", os);
capabilities.setCapability("tunnel-identifier", tunnelidentifier);
String methodName = name.getMethodName();
capabilities.setCapability("name", methodName);
if (buildTag != null) {
capabilities.setCapability("build", buildTag);
}
this.driver = new RemoteWebDriver(new URL("https://" + username+ ":" + accesskey + seleniumURI +"/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
this.sessionId = (((RemoteWebDriver) driver).getSessionId()).toString();
}
@After
public void tearDown() throws Exception {
((JavascriptExecutor)driver).executeScript("sauce:job-result=passed");
driver.quit();
}
public String getSessionId() {
return sessionId;
}
@BeforeClass
public static void setupClass() {
// Get the uri to send the commands to
seleniumURI = "@ondemand.saucelabs.com:443";
// Set the buildTag to the Travis Build number
buildTag = System.getenv("TRAVIS_BUILD_NUMBER");
if (buildTag == null) {
buildTag = System.getenv("SAUCE_BUILD_NAME");
}
}
public void performLogin(LoginElements login) {
login.username("username");
login.password("password");
login.changeToEnglish();
login.changeToGerman();
login.changeToProject("test-data");
login.login();
}
}
| Add: Test Watcher
| ui-tests/src/test/java/com/specmate/uitests/TestBase.java | Add: Test Watcher | <ide><path>i-tests/src/test/java/com/specmate/uitests/TestBase.java
<ide> package com.specmate.uitests;
<ide>
<del>import com.saucelabs.common.SauceOnDemandAuthentication;
<ide>
<ide> import org.junit.*;
<ide> import org.junit.rules.TestName;
<add>import org.junit.rules.TestWatcher;
<add>import org.junit.runner.Description;
<ide> import org.junit.runner.RunWith;
<ide> import org.junit.runners.Parameterized;
<ide> import org.junit.runners.Parameterized.Parameters;
<add>import org.junit.runners.model.Statement;
<ide> import org.openqa.selenium.JavascriptExecutor;
<ide> import org.openqa.selenium.WebDriver;
<ide> import org.openqa.selenium.remote.CapabilityType;
<ide> public static String seleniumURI;
<ide> public static String buildTag;
<ide> public static final String tunnelidentifier = System.getenv("TRAVIS_JOB_NUMBER");
<del>
<del> //public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication();
<add> private static boolean result;
<ide>
<del> /**Mark the Sauce Job as passed/failed when the test succeeds or fails*/
<del> //@Rule
<del> //public SauceOnDemandTestWatcher resultReportingTestWatcher = new SauceOnDemandTestWatcher(this, authentication);
<add>
<add> @Rule
<add> public final TestWatcher watcher = new TestWatcher() {
<add> @Override
<add> public Statement apply(Statement base, Description description) {
<add> return super.apply(base, description);
<add> }
<add>
<add> @Override
<add> protected void failed(Throwable e, Description description) {
<add> result = false;
<add> }
<add>
<add> @Override
<add> protected void succeeded(Description description) {
<add> result = true;
<add> }
<add> };
<ide>
<ide> @Rule
<ide> public TestName name = new TestName() {
<ide>
<ide> @After
<ide> public void tearDown() throws Exception {
<del> ((JavascriptExecutor)driver).executeScript("sauce:job-result=passed");
<add> ((JavascriptExecutor)driver).executeScript("sauce:job-result=" + (result ? "passed" : "failed"));
<add>
<ide> driver.quit();
<ide> }
<ide> |
|
Java | apache-2.0 | 5e7ed1c7302915da18a4437b4096a26df3e9cd50 | 0 | kierarad/gocd,varshavaradarajan/gocd,GaneshSPatil/gocd,jyotisingh/gocd,ibnc/gocd,gocd/gocd,arvindsv/gocd,GaneshSPatil/gocd,varshavaradarajan/gocd,tomzo/gocd,tomzo/gocd,marques-work/gocd,gocd/gocd,arvindsv/gocd,Skarlso/gocd,bdpiparva/gocd,gocd/gocd,ketan/gocd,ibnc/gocd,varshavaradarajan/gocd,naveenbhaskar/gocd,GaneshSPatil/gocd,jyotisingh/gocd,kierarad/gocd,marques-work/gocd,ketan/gocd,arvindsv/gocd,marques-work/gocd,gocd/gocd,jyotisingh/gocd,ketan/gocd,marques-work/gocd,ind9/gocd,tomzo/gocd,GaneshSPatil/gocd,ketan/gocd,bdpiparva/gocd,ind9/gocd,arvindsv/gocd,kierarad/gocd,GaneshSPatil/gocd,Skarlso/gocd,bdpiparva/gocd,ibnc/gocd,bdpiparva/gocd,bdpiparva/gocd,ketan/gocd,naveenbhaskar/gocd,gocd/gocd,marques-work/gocd,marques-work/gocd,jyotisingh/gocd,gocd/gocd,ibnc/gocd,ind9/gocd,arvindsv/gocd,kierarad/gocd,Skarlso/gocd,jyotisingh/gocd,bdpiparva/gocd,varshavaradarajan/gocd,kierarad/gocd,varshavaradarajan/gocd,tomzo/gocd,tomzo/gocd,Skarlso/gocd,ind9/gocd,naveenbhaskar/gocd,jyotisingh/gocd,GaneshSPatil/gocd,naveenbhaskar/gocd,Skarlso/gocd,naveenbhaskar/gocd,Skarlso/gocd,kierarad/gocd,ibnc/gocd,tomzo/gocd,naveenbhaskar/gocd,ketan/gocd,arvindsv/gocd,ind9/gocd,varshavaradarajan/gocd,ibnc/gocd | /*
* Copyright 2018 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.work;
import com.thoughtworks.go.config.RunIfConfig;
import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.domain.JobResult;
import com.thoughtworks.go.domain.JobState;
import com.thoughtworks.go.domain.Property;
import com.thoughtworks.go.domain.builder.FetchArtifactBuilder;
import com.thoughtworks.go.publishers.GoArtifactsManipulator;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.BuildRepositoryRemote;
import com.thoughtworks.go.remote.work.ConsoleOutputTransmitter;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.util.GoConstants;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.SystemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static com.thoughtworks.go.domain.JobState.*;
import static java.lang.String.format;
public class DefaultGoPublisher implements GoPublisher {
private static final Logger LOG = LoggerFactory.getLogger(DefaultGoPublisher.class);
private final AgentRuntimeInfo agentRuntimeInfo;
private final String consoleLogCharset;
private GoArtifactsManipulator manipulator;
private JobIdentifier jobIdentifier;
private AgentIdentifier agentIdentifier;
private BuildRepositoryRemote remoteBuildRepository;
private ConsoleOutputTransmitter consoleOutputTransmitter;
private String currentWorkingDirectory = SystemUtil.currentWorkingDirectory();
public DefaultGoPublisher(GoArtifactsManipulator manipulator, JobIdentifier jobIdentifier,
BuildRepositoryRemote remoteBuildRepository,
AgentRuntimeInfo agentRuntimeInfo, String consoleLogCharset) {
this.manipulator = manipulator;
this.jobIdentifier = jobIdentifier;
this.agentIdentifier = agentRuntimeInfo.getIdentifier();
this.remoteBuildRepository = remoteBuildRepository;
this.agentRuntimeInfo = agentRuntimeInfo;
this.consoleLogCharset = consoleLogCharset;
init();
}
//do not put the logic into the constructor it is really hard to stub.
protected void init() {
consoleOutputTransmitter = manipulator.createConsoleOutputTransmitter(jobIdentifier, agentIdentifier, consoleLogCharset);
}
@Override
public void setProperty(Property property) {
manipulator.setProperty(jobIdentifier, property);
}
@Override
public void upload(File fileToUpload, String destPath) {
manipulator.publish(this, destPath, fileToUpload, jobIdentifier);
}
public void fetch(FetchArtifactBuilder fetchArtifact) {
manipulator.fetch(this, fetchArtifact);
}
@Override
public void consumeLine(String line) {
taggedConsumeLine(null, line);
}
public void stop() {
LOG.info("Stopping Transmission for {}", jobIdentifier.toFullString());
consoleOutputTransmitter.stop();
}
private void reportCurrentStatus(JobState state) {
consoleOutputTransmitter.flushToServer();
LOG.info("{} is reporting status [{}] to Go Server for {}", agentIdentifier, state, jobIdentifier.toFullString());
remoteBuildRepository.reportCurrentStatus(agentRuntimeInfo, jobIdentifier, state);
}
public void reportCompleting(JobResult result) {
consoleOutputTransmitter.flushToServer();
LOG.info("{} is reporting build result [{}] to Go Server for {}", agentIdentifier, result, jobIdentifier.toFullString());
remoteBuildRepository.reportCompleting(agentRuntimeInfo, jobIdentifier, result);
}
public void reportCompleted(JobResult result) {
if (result != null) {
LOG.info("{} is reporting build result [{}] to Go Server for {}", agentIdentifier, result, jobIdentifier.toFullString());
reportCompletedAction();
consoleOutputTransmitter.flushToServer();
remoteBuildRepository.reportCompleted(agentRuntimeInfo, jobIdentifier, result);
} else {
reportCompletedAction();
reportCurrentStatus(Completed);
}
}
private void reportCompletedAction() {
reportAction(COMPLETED, "Job completed");
}
public boolean isIgnored() {
return remoteBuildRepository.isIgnored(jobIdentifier);
}
private void reportAction(String tag, String action) {
String message = String.format("[%s] %s %s on %s [%s]", GoConstants.PRODUCT_NAME, action, jobIdentifier.buildLocatorForDisplay(),
agentIdentifier.getHostName(), currentWorkingDirectory);
LOG.debug(message);
taggedConsumeLine(tag, message);
}
@Override
public void consumeLineWithPrefix(String message) {
taggedConsumeLineWithPrefix(NOTICE, message);
}
@Override
public void taggedConsumeLineWithPrefix(String tag, String message) {
taggedConsumeLine(tag, String.format("[%s] %s", GoConstants.PRODUCT_NAME, message));
}
@Override
public void reportErrorMessage(String message, Exception e) {
LOG.error(message, e);
taggedConsumeLine(ERR, message);
}
@Override
public void taggedConsumeLine(String tag, String line) {
SystemEnvironment env = new SystemEnvironment();
if (env.isWebsocketsForAgentsEnabled() && env.isConsoleLogsThroughWebsocketEnabled()) {
remoteBuildRepository.taggedConsumeLine(tag, line, jobIdentifier);
} else {
consoleOutputTransmitter.taggedConsumeLine(tag, line);
}
}
public void reportPreparing() {
reportAction(PREP, "Start to prepare");
reportCurrentStatus(Preparing);
}
public void reportStartingToBuild() {
reportAction(NOTICE, "Start to build");
reportCurrentStatus(Building);
}
public void reportCompleting(JobResult result, String tag) {
taggedConsumeLineWithPrefix(tag, format("Current job status: %s", RunIfConfig.fromJobResult(result.toLowerCase())));
reportCurrentStatus(Completing);
}
public void reportJobCancelled() {
reportAction(NOTICE, "Job is cancelled");
consoleOutputTransmitter.flushToServer();
}
public void reportBeginToPublishArtifacts() {
reportAction(PUBLISH, "Start to upload");
}
public void reportCreatingProperties() {
reportAction(NOTICE, "Start to create properties");
}
}
| common/src/main/java/com/thoughtworks/go/work/DefaultGoPublisher.java | /*
* Copyright 2018 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.work;
import com.thoughtworks.go.config.RunIfConfig;
import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.domain.JobResult;
import com.thoughtworks.go.domain.JobState;
import com.thoughtworks.go.domain.Property;
import com.thoughtworks.go.domain.builder.FetchArtifactBuilder;
import com.thoughtworks.go.publishers.GoArtifactsManipulator;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.BuildRepositoryRemote;
import com.thoughtworks.go.remote.work.ConsoleOutputTransmitter;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.util.GoConstants;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.SystemUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static com.thoughtworks.go.domain.JobState.*;
import static java.lang.String.format;
public class DefaultGoPublisher implements GoPublisher {
private static final Logger LOG = LoggerFactory.getLogger(DefaultGoPublisher.class);
private final AgentRuntimeInfo agentRuntimeInfo;
private final String consoleLogCharset;
private GoArtifactsManipulator manipulator;
private JobIdentifier jobIdentifier;
private AgentIdentifier agentIdentifier;
private BuildRepositoryRemote remoteBuildRepository;
private ConsoleOutputTransmitter consoleOutputTransmitter;
private String currentWorkingDirectory = SystemUtil.currentWorkingDirectory();
public DefaultGoPublisher(GoArtifactsManipulator manipulator, JobIdentifier jobIdentifier,
BuildRepositoryRemote remoteBuildRepository,
AgentRuntimeInfo agentRuntimeInfo, String consoleLogCharset) {
this.manipulator = manipulator;
this.jobIdentifier = jobIdentifier;
this.agentIdentifier = agentRuntimeInfo.getIdentifier();
this.remoteBuildRepository = remoteBuildRepository;
this.agentRuntimeInfo = agentRuntimeInfo;
this.consoleLogCharset = consoleLogCharset;
init();
}
//do not put the logic into the constructor it is really hard to stub.
protected void init() {
consoleOutputTransmitter = manipulator.createConsoleOutputTransmitter(jobIdentifier, agentIdentifier, consoleLogCharset);
}
@Override
public void setProperty(Property property) {
manipulator.setProperty(jobIdentifier, property);
}
@Override
public void upload(File fileToUpload, String destPath) {
manipulator.publish(this, destPath, fileToUpload, jobIdentifier);
}
public void fetch(FetchArtifactBuilder fetchArtifact) {
manipulator.fetch(this, fetchArtifact);
}
@Override
public void consumeLine(String line) {
taggedConsumeLine(null, line);
}
public void stop() {
LOG.info("Stopping Transmission for {}", jobIdentifier.toFullString());
consoleOutputTransmitter.stop();
}
private void reportCurrentStatus(JobState state) {
consoleOutputTransmitter.flushToServer();
LOG.info("{} is reporting status [{}] to Go Server for {}", agentIdentifier, state, jobIdentifier.toFullString());
remoteBuildRepository.reportCurrentStatus(agentRuntimeInfo, jobIdentifier, state);
}
public void reportCompleting(JobResult result) {
consoleOutputTransmitter.flushToServer();
LOG.info("{} is reporting build result [{}] to Go Server for {}", agentIdentifier, result, jobIdentifier.toFullString());
remoteBuildRepository.reportCompleting(agentRuntimeInfo, jobIdentifier, result);
}
public void reportCompleted(JobResult result) {
if (result != null) {
LOG.info("{} is reporting build result [{}] to Go Server for {}", agentIdentifier, result, jobIdentifier.toFullString());
consoleOutputTransmitter.flushToServer();
remoteBuildRepository.reportCompleted(agentRuntimeInfo, jobIdentifier, result);
}
reportCompletedAction();
}
private void reportCompletedAction() {
reportAction(COMPLETED, "Job completed");
reportCurrentStatus(Completed);
}
public boolean isIgnored() {
return remoteBuildRepository.isIgnored(jobIdentifier);
}
private void reportAction(String tag, String action) {
String message = String.format("[%s] %s %s on %s [%s]", GoConstants.PRODUCT_NAME, action, jobIdentifier.buildLocatorForDisplay(),
agentIdentifier.getHostName(), currentWorkingDirectory);
LOG.debug(message);
taggedConsumeLine(tag, message);
}
@Override
public void consumeLineWithPrefix(String message) {
taggedConsumeLineWithPrefix(NOTICE, message);
}
@Override
public void taggedConsumeLineWithPrefix(String tag, String message) {
taggedConsumeLine(tag, String.format("[%s] %s", GoConstants.PRODUCT_NAME, message));
}
@Override
public void reportErrorMessage(String message, Exception e) {
LOG.error(message, e);
taggedConsumeLine(ERR, message);
}
@Override
public void taggedConsumeLine(String tag, String line) {
SystemEnvironment env = new SystemEnvironment();
if (env.isWebsocketsForAgentsEnabled() && env.isConsoleLogsThroughWebsocketEnabled()) {
remoteBuildRepository.taggedConsumeLine(tag, line, jobIdentifier);
} else {
consoleOutputTransmitter.taggedConsumeLine(tag, line);
}
}
public void reportPreparing() {
reportAction(PREP, "Start to prepare");
reportCurrentStatus(Preparing);
}
public void reportStartingToBuild() {
reportAction(NOTICE, "Start to build");
reportCurrentStatus(Building);
}
public void reportCompleting(JobResult result, String tag) {
taggedConsumeLineWithPrefix(tag, format("Current job status: %s", RunIfConfig.fromJobResult(result.toLowerCase())));
reportCurrentStatus(Completing);
}
public void reportJobCancelled() {
reportAction(NOTICE, "Job is cancelled");
consoleOutputTransmitter.flushToServer();
}
public void reportBeginToPublishArtifacts() {
reportAction(PUBLISH, "Start to upload");
}
public void reportCreatingProperties() {
reportAction(NOTICE, "Start to create properties");
}
}
| Fix agent reposting job completion twice
* This fixes an issue where agent happened to report job
completion twice. This issue was introduced while fixing an
issue with console logs being swallowed #5335
| common/src/main/java/com/thoughtworks/go/work/DefaultGoPublisher.java | Fix agent reposting job completion twice | <ide><path>ommon/src/main/java/com/thoughtworks/go/work/DefaultGoPublisher.java
<ide> public void reportCompleted(JobResult result) {
<ide> if (result != null) {
<ide> LOG.info("{} is reporting build result [{}] to Go Server for {}", agentIdentifier, result, jobIdentifier.toFullString());
<add> reportCompletedAction();
<ide> consoleOutputTransmitter.flushToServer();
<ide> remoteBuildRepository.reportCompleted(agentRuntimeInfo, jobIdentifier, result);
<add> } else {
<add> reportCompletedAction();
<add> reportCurrentStatus(Completed);
<ide> }
<del>
<del> reportCompletedAction();
<ide> }
<ide>
<ide> private void reportCompletedAction() {
<ide> reportAction(COMPLETED, "Job completed");
<del> reportCurrentStatus(Completed);
<ide> }
<ide>
<ide> public boolean isIgnored() { |
|
Java | bsd-3-clause | b293c68c9a0c7de8a920fb37b0867ef1eb1379c4 | 0 | NCIP/cab2b,NCIP/cab2b,NCIP/cab2b | package edu.wustl.cab2b.client.ui;
/**
* The main RHS panel from the choose category tab, comprising the
* {@link ChooseCategorySearchPanel}. Other components would be added in
* future.
*
* @author mahesh_iyer
*
*/
public class ChooseCategoryCategorySearchPanel extends AbstractCategorySearchPanel {
/**
* constructor
*
* @param Panel
* The reference to the parent content panel to be propogated
* through the child heirarchy to cause the parent to be
* refreshed for the appropritate event.
*/
public ChooseCategoryCategorySearchPanel(ContentPanel panel) {
super(panel);
}
/**
* The abstract method implementation from the base class returns an
* instance of {@link ChooseCategorySearchPanel} to be added to this panel.
* Sub-classes might be required to over-ride this method.
*
* @param addLimitPanel
* The reference to the parent content panel to be propogated
* through the child heirarchy to cause the parent to be
* refreshed for the appropritate event.
*/
public AbstractSearchPanel getSearchPanel(ContentPanel chooseCategoryPanel) {
return new ChooseCategorySearchPanel(chooseCategoryPanel);
}
}
| source/client/main/edu/wustl/cab2b/client/ui/ChooseCategoryCategorySearchPanel.java | package edu.wustl.cab2b.client.ui;
import org.jdesktop.swingx.JXPanel;
/**
* The main RHS panel from the choose category tab, comprising the
* {@link ChooseCategorySearchPanel}. Other components would be added in
* future.
*
* @author mahesh_iyer
*
*/
public class ChooseCategoryCategorySearchPanel extends AbstractCategorySearchPanel
{
/**
* constructor
*
* @param Panel
* The reference to the parent content panel to be propogated
* through the child heirarchy to cause the parent to be
* refreshed for the appropritate event.
*/
public ChooseCategoryCategorySearchPanel(ContentPanel panel)
{
super(panel);
}
/**
* The abstract method implementation from the base class returns an
* instance of {@link ChooseCategorySearchPanel} to be added to this panel.
* Sub-classes might be required to over-ride this method.
*
* @param addLimitPanel
* The reference to the parent content panel to be propogated
* through the child heirarchy to cause the parent to be
* refreshed for the appropritate event.
*/
public AbstractSearchPanel getSearchPanel(ContentPanel chooseCategoryPanel)
{
return new ChooseCategorySearchPanel(chooseCategoryPanel);
}
}
| Formatted
| source/client/main/edu/wustl/cab2b/client/ui/ChooseCategoryCategorySearchPanel.java | Formatted | <ide><path>ource/client/main/edu/wustl/cab2b/client/ui/ChooseCategoryCategorySearchPanel.java
<ide> package edu.wustl.cab2b.client.ui;
<del>
<del>import org.jdesktop.swingx.JXPanel;
<ide>
<ide> /**
<ide> * The main RHS panel from the choose category tab, comprising the
<ide> *
<ide> */
<ide>
<del>public class ChooseCategoryCategorySearchPanel extends AbstractCategorySearchPanel
<del>{
<del>
<del> /**
<del> * constructor
<del> *
<del> * @param Panel
<del> * The reference to the parent content panel to be propogated
<del> * through the child heirarchy to cause the parent to be
<del> * refreshed for the appropritate event.
<del> */
<del>
<del> public ChooseCategoryCategorySearchPanel(ContentPanel panel)
<del> {
<del> super(panel);
<del> }
<add>public class ChooseCategoryCategorySearchPanel extends AbstractCategorySearchPanel {
<add> /**
<add> * constructor
<add> *
<add> * @param Panel
<add> * The reference to the parent content panel to be propogated
<add> * through the child heirarchy to cause the parent to be
<add> * refreshed for the appropritate event.
<add> */
<ide>
<del> /**
<del> * The abstract method implementation from the base class returns an
<del> * instance of {@link ChooseCategorySearchPanel} to be added to this panel.
<del> * Sub-classes might be required to over-ride this method.
<del> *
<del> * @param addLimitPanel
<del> * The reference to the parent content panel to be propogated
<del> * through the child heirarchy to cause the parent to be
<del> * refreshed for the appropritate event.
<del> */
<del> public AbstractSearchPanel getSearchPanel(ContentPanel chooseCategoryPanel)
<del> {
<del> return new ChooseCategorySearchPanel(chooseCategoryPanel);
<del> }
<del>
<add> public ChooseCategoryCategorySearchPanel(ContentPanel panel) {
<add> super(panel);
<add> }
<add>
<add> /**
<add> * The abstract method implementation from the base class returns an
<add> * instance of {@link ChooseCategorySearchPanel} to be added to this panel.
<add> * Sub-classes might be required to over-ride this method.
<add> *
<add> * @param addLimitPanel
<add> * The reference to the parent content panel to be propogated
<add> * through the child heirarchy to cause the parent to be
<add> * refreshed for the appropritate event.
<add> */
<add> public AbstractSearchPanel getSearchPanel(ContentPanel chooseCategoryPanel) {
<add> return new ChooseCategorySearchPanel(chooseCategoryPanel);
<add> }
<add>
<ide> } |
|
JavaScript | mit | 904b762dede55dc1d3dc70c9f72eb02ace3048c1 | 0 | namlook/eureka-widget-application-menu,namlook/eureka-widget-application-menu | import Ember from 'ember';
import WidgetApplication from 'ember-eureka/widget-application';
export default WidgetApplication.extend({
menuItems: function() {
var currentRouteName = this.get('currentRouteName');
var items = this.get('config.items');
if (!items) {
items = Ember.A();
var models = this.get('currentController.appConfig.structure.models');
var item, isActive, dasherizedModelType;
Ember.keys(models).forEach(function(modelType) {
// if the model has no view, skip it
if (!Ember.get(models, modelType+'.views.collection.index')) {
return;
}
dasherizedModelType = modelType.dasherize();
isActive = currentRouteName.split('.')[1] === dasherizedModelType;
item = Ember.Object.create({
label: modelType,
route: 'eureka.'+dasherizedModelType,
isActive: isActive
});
items.pushObject(item);
});
} else {
items = items.map(function(item) {
item.isActive = currentRouteName === item.route;
return item;
});
}
return items;
}.property('config.items.[]', 'currentRouteName')
});
| addon/index.js | import Ember from 'ember';
import WidgetApplication from 'ember-eureka/widget-application';
export default WidgetApplication.extend({
currentRouteName: Ember.computed.alias('application.currentRouteName'),
menuItems: function() {
var items = this.get('config.items');
if (!items) {
var application = this.get('application');
var modelTypesList = Ember.keys(Ember.get(application.config, 'structure.models'));
items = Ember.A();
var currentRouteName = this.get('currentRouteName');
var item, route, isActive;
modelTypesList.forEach(function(modelType) {
route = modelType.dasherize();
isActive = currentRouteName.split('.')[0] === route;
item = Ember.Object.create({
label: modelType,
route: modelType.dasherize(),
isActive: isActive
});
items.pushObject(item);
});
}
return items;
}.property('config.items.[]', 'application', 'currentRouteName')
});
| keep up with new eureka
| addon/index.js | keep up with new eureka | <ide><path>ddon/index.js
<ide> import WidgetApplication from 'ember-eureka/widget-application';
<ide>
<ide> export default WidgetApplication.extend({
<del> currentRouteName: Ember.computed.alias('application.currentRouteName'),
<ide>
<ide> menuItems: function() {
<add>
<add> var currentRouteName = this.get('currentRouteName');
<add>
<ide> var items = this.get('config.items');
<ide> if (!items) {
<ide>
<del> var application = this.get('application');
<del> var modelTypesList = Ember.keys(Ember.get(application.config, 'structure.models'));
<ide> items = Ember.A();
<del> var currentRouteName = this.get('currentRouteName');
<del> var item, route, isActive;
<add> var models = this.get('currentController.appConfig.structure.models');
<ide>
<del> modelTypesList.forEach(function(modelType) {
<del> route = modelType.dasherize();
<del> isActive = currentRouteName.split('.')[0] === route;
<add> var item, isActive, dasherizedModelType;
<add> Ember.keys(models).forEach(function(modelType) {
<add>
<add> // if the model has no view, skip it
<add> if (!Ember.get(models, modelType+'.views.collection.index')) {
<add> return;
<add> }
<add>
<add> dasherizedModelType = modelType.dasherize();
<add> isActive = currentRouteName.split('.')[1] === dasherizedModelType;
<ide>
<ide> item = Ember.Object.create({
<ide> label: modelType,
<del> route: modelType.dasherize(),
<add> route: 'eureka.'+dasherizedModelType,
<ide> isActive: isActive
<ide> });
<ide>
<ide> items.pushObject(item);
<ide> });
<add>
<add> } else {
<add> items = items.map(function(item) {
<add> item.isActive = currentRouteName === item.route;
<add> return item;
<add> });
<ide> }
<add>
<ide> return items;
<del> }.property('config.items.[]', 'application', 'currentRouteName')
<add> }.property('config.items.[]', 'currentRouteName')
<ide> }); |
|
Java | apache-2.0 | 867b041bc86fcc2920798248ec7958ca230478e3 | 0 | rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy | /*
* Central Repository
*
* Copyright 2021 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.centralrepository.contentviewer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.swing.SwingWorker;
import org.openide.nodes.Node;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.application.NodeData;
import org.sleuthkit.autopsy.centralrepository.application.OtherOccurrences;
import org.sleuthkit.autopsy.centralrepository.contentviewer.OtherOccurrencesNodeWorker.OtherOccurrencesData;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepository;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeUtil;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.datamodel.TskContentItem;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifactTag;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.OsAccount;
import org.sleuthkit.datamodel.TskException;
/**
* A SwingWorker that gathers data for the OtherOccurencesPanel which appears in
* the dataContentViewerOtherCases panel.
*/
class OtherOccurrencesNodeWorker extends SwingWorker<OtherOccurrencesData, Void> {
private static final Logger logger = Logger.getLogger(OtherOccurrencesNodeWorker.class.getName());
private final Node node;
/**
* Constructs a new instance for the given node.
*
* @param node
*/
OtherOccurrencesNodeWorker(Node node) {
this.node = node;
}
@Override
protected OtherOccurrencesData doInBackground() throws Exception {
OtherOccurrencesData data = null;
if (CentralRepository.isEnabled()) {
OsAccount osAccount = node.getLookup().lookup(OsAccount.class);
String deviceId = "";
String dataSourceName = "";
Map<String, CorrelationCase> caseNames = new HashMap<>();
Case currentCase = Case.getCurrentCaseThrows();
Collection<CorrelationAttributeInstance> correlationAttributes = new ArrayList<>();
Content content = null;
if (osAccount != null) {
content = osAccount;
correlationAttributes.addAll(OtherOccurrences.getCorrelationAttributeFromOsAccount(node, osAccount));
} else {
TskContentItem<?> contentItem = node.getLookup().lookup(TskContentItem.class);
if (contentItem != null) {
content = contentItem.getTskContent();
} else { //fallback and check ContentTags
ContentTag nodeContentTag = node.getLookup().lookup(ContentTag.class);
BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
if (nodeBbArtifactTag != null) {
content = nodeBbArtifactTag.getContent();
} else if (nodeContentTag != null) {
content = nodeContentTag.getContent();
}
}
if (content != null) {
correlationAttributes.addAll(CorrelationAttributeUtil.makeCorrAttrsForSearch(content));
}
}
try {
if (content != null) {
Content dataSource = file.getDataSource();
deviceId = currentCase.getSleuthkitCase().getDataSource(dataSource.getId()).getDeviceId();
dataSourceName = dataSource.getName();
}
} catch (TskException ex) {
logger.log(Level.WARNING, "Exception occurred while trying to get the data source, current case, and device id for an AbstractFile in the other occurrences viewer", ex);
return data;
}
int totalCount = 0;
Set<String> dataSources = new HashSet<>();
for (CorrelationAttributeInstance corAttr : correlationAttributes) {
for (NodeData nodeData : OtherOccurrences.getCorrelatedInstances(deviceId, dataSourceName, corAttr).values()) {
try {
dataSources.add(OtherOccurrences.makeDataSourceString(nodeData.getCorrelationAttributeInstance().getCorrelationCase().getCaseUUID(), nodeData.getDeviceID(), nodeData.getDataSourceName()));
caseNames.put(nodeData.getCorrelationAttributeInstance().getCorrelationCase().getCaseUUID(), nodeData.getCorrelationAttributeInstance().getCorrelationCase());
} catch (CentralRepoException ex) {
logger.log(Level.WARNING, "Unable to get correlation case for displaying other occurrence for case: " + nodeData.getCaseName(), ex);
}
totalCount++;
if (isCancelled()) {
break;
}
}
}
if (!isCancelled()) {
data = new OtherOccurrencesData(correlationAttributes, file, dataSourceName, deviceId, caseNames, totalCount, dataSources.size(), OtherOccurrences.getEarliestCaseDate());
}
}
return data;
}
/**
* Object to store all of the data gathered in the OtherOccurrencesWorker
* doInBackground method.
*/
static class OtherOccurrencesData {
private final String deviceId;
private final AbstractFile file;
private final String dataSourceName;
private final Map<String, CorrelationCase> caseMap;
private final int instanceDataCount;
private final int dataSourceCount;
private final String earliestCaseDate;
private final Collection<CorrelationAttributeInstance> correlationAttributes;
private OtherOccurrencesData(Collection<CorrelationAttributeInstance> correlationAttributes, AbstractFile file, String dataSourceName, String deviceId, Map<String, CorrelationCase> caseMap, int instanceCount, int dataSourceCount, String earliestCaseDate) {
this.file = file;
this.deviceId = deviceId;
this.dataSourceName = dataSourceName;
this.caseMap = caseMap;
this.instanceDataCount = instanceCount;
this.dataSourceCount = dataSourceCount;
this.earliestCaseDate = earliestCaseDate;
this.correlationAttributes = correlationAttributes;
}
public String getDeviceId() {
return deviceId;
}
public AbstractFile getFile() {
return file;
}
public String getDataSourceName() {
return dataSourceName;
}
public Map<String, CorrelationCase> getCaseMap() {
return caseMap;
}
public int getInstanceDataCount() {
return instanceDataCount;
}
public int getDataSourceCount() {
return dataSourceCount;
}
/**
* Returns the earliest date in the case.
*
* @return Formatted date string, or message that one was not found.
*/
public String getEarliestCaseDate() {
return earliestCaseDate;
}
public Collection<CorrelationAttributeInstance> getCorrelationAttributes() {
return correlationAttributes;
}
}
}
| Core/src/org/sleuthkit/autopsy/centralrepository/contentviewer/OtherOccurrencesNodeWorker.java | /*
* Central Repository
*
* Copyright 2021 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.centralrepository.contentviewer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.swing.SwingWorker;
import org.openide.nodes.Node;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.centralrepository.application.NodeData;
import org.sleuthkit.autopsy.centralrepository.application.OtherOccurrences;
import org.sleuthkit.autopsy.centralrepository.contentviewer.OtherOccurrencesNodeWorker.OtherOccurrencesData;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoException;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepository;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeInstance;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationAttributeUtil;
import org.sleuthkit.autopsy.centralrepository.datamodel.CorrelationCase;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.datamodel.TskContentItem;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifactTag;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.OsAccount;
import org.sleuthkit.datamodel.TskException;
/**
* A SwingWorker that gathers data for the OtherOccurencesPanel which appears in
* the dataContentViewerOtherCases panel.
*/
class OtherOccurrencesNodeWorker extends SwingWorker<OtherOccurrencesData, Void> {
private static final Logger logger = Logger.getLogger(OtherOccurrencesNodeWorker.class.getName());
private final Node node;
/**
* Constructs a new instance for the given node.
*
* @param node
*/
OtherOccurrencesNodeWorker(Node node) {
this.node = node;
}
@Override
protected OtherOccurrencesData doInBackground() throws Exception {
OtherOccurrencesData data = null;
if (CentralRepository.isEnabled()) {
OsAccount osAccount = node.getLookup().lookup(OsAccount.class);
String deviceId = "";
String dataSourceName = "";
Map<String, CorrelationCase> caseNames = new HashMap<>();
Case currentCase = Case.getCurrentCaseThrows();
//the file is used for determining a correlation instance is not the selected instance
AbstractFile file = node.getLookup().lookup(AbstractFile.class);
try {
if (file != null) {
Content dataSource = file.getDataSource();
deviceId = currentCase.getSleuthkitCase().getDataSource(dataSource.getId()).getDeviceId();
dataSourceName = dataSource.getName();
}
} catch (TskException ex) {
// do nothing.
// @@@ Review this behavior
return data;
}
Collection<CorrelationAttributeInstance> correlationAttributes = new ArrayList<>();
if (osAccount != null) {
correlationAttributes.addAll(OtherOccurrences.getCorrelationAttributeFromOsAccount(node, osAccount));
} else {
TskContentItem<?> contentItem = node.getLookup().lookup(TskContentItem.class);
Content content = null;
if (contentItem != null) {
content = contentItem.getTskContent();
} else { //fallback and check ContentTags
ContentTag nodeContentTag = node.getLookup().lookup(ContentTag.class);
BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
if (nodeBbArtifactTag != null) {
content = nodeBbArtifactTag.getArtifact();
} else if (nodeContentTag != null) {
content = nodeContentTag.getContent();
}
}
if (content != null) {
correlationAttributes.addAll(CorrelationAttributeUtil.makeCorrAttrsForSearch(content));
}
}
int totalCount = 0;
Set<String> dataSources = new HashSet<>();
for (CorrelationAttributeInstance corAttr : correlationAttributes) {
for (NodeData nodeData : OtherOccurrences.getCorrelatedInstances(deviceId, dataSourceName, corAttr).values()) {
try {
dataSources.add(OtherOccurrences.makeDataSourceString(nodeData.getCorrelationAttributeInstance().getCorrelationCase().getCaseUUID(), nodeData.getDeviceID(), nodeData.getDataSourceName()));
caseNames.put(nodeData.getCorrelationAttributeInstance().getCorrelationCase().getCaseUUID(), nodeData.getCorrelationAttributeInstance().getCorrelationCase());
} catch (CentralRepoException ex) {
logger.log(Level.WARNING, "Unable to get correlation case for displaying other occurrence for case: " + nodeData.getCaseName(), ex);
}
totalCount++;
if (isCancelled()) {
break;
}
}
}
if (!isCancelled()) {
data = new OtherOccurrencesData(correlationAttributes, file, dataSourceName, deviceId, caseNames, totalCount, dataSources.size(), OtherOccurrences.getEarliestCaseDate());
}
}
return data;
}
/**
* Object to store all of the data gathered in the OtherOccurrencesWorker
* doInBackground method.
*/
static class OtherOccurrencesData {
private final String deviceId;
private final AbstractFile file;
private final String dataSourceName;
private final Map<String, CorrelationCase> caseMap;
private final int instanceDataCount;
private final int dataSourceCount;
private final String earliestCaseDate;
private final Collection<CorrelationAttributeInstance> correlationAttributes;
private OtherOccurrencesData(Collection<CorrelationAttributeInstance> correlationAttributes, AbstractFile file, String dataSourceName, String deviceId, Map<String, CorrelationCase> caseMap, int instanceCount, int dataSourceCount, String earliestCaseDate) {
this.file = file;
this.deviceId = deviceId;
this.dataSourceName = dataSourceName;
this.caseMap = caseMap;
this.instanceDataCount = instanceCount;
this.dataSourceCount = dataSourceCount;
this.earliestCaseDate = earliestCaseDate;
this.correlationAttributes = correlationAttributes;
}
public String getDeviceId() {
return deviceId;
}
public AbstractFile getFile() {
return file;
}
public String getDataSourceName() {
return dataSourceName;
}
public Map<String, CorrelationCase> getCaseMap() {
return caseMap;
}
public int getInstanceDataCount() {
return instanceDataCount;
}
public int getDataSourceCount() {
return dataSourceCount;
}
/**
* Returns the earliest date in the case.
*
* @return Formatted date string, or message that one was not found.
*/
public String getEarliestCaseDate() {
return earliestCaseDate;
}
public Collection<CorrelationAttributeInstance> getCorrelationAttributes() {
return correlationAttributes;
}
}
}
| 7918 change to logging for failure to get ds info
| Core/src/org/sleuthkit/autopsy/centralrepository/contentviewer/OtherOccurrencesNodeWorker.java | 7918 change to logging for failure to get ds info | <ide><path>ore/src/org/sleuthkit/autopsy/centralrepository/contentviewer/OtherOccurrencesNodeWorker.java
<ide> String dataSourceName = "";
<ide> Map<String, CorrelationCase> caseNames = new HashMap<>();
<ide> Case currentCase = Case.getCurrentCaseThrows();
<del> //the file is used for determining a correlation instance is not the selected instance
<del> AbstractFile file = node.getLookup().lookup(AbstractFile.class);
<del> try {
<del> if (file != null) {
<del> Content dataSource = file.getDataSource();
<del> deviceId = currentCase.getSleuthkitCase().getDataSource(dataSource.getId()).getDeviceId();
<del> dataSourceName = dataSource.getName();
<del> }
<del> } catch (TskException ex) {
<del> // do nothing.
<del> // @@@ Review this behavior
<del> return data;
<del> }
<add>
<ide> Collection<CorrelationAttributeInstance> correlationAttributes = new ArrayList<>();
<del>
<add> Content content = null;
<ide> if (osAccount != null) {
<add> content = osAccount;
<ide> correlationAttributes.addAll(OtherOccurrences.getCorrelationAttributeFromOsAccount(node, osAccount));
<ide> } else {
<ide> TskContentItem<?> contentItem = node.getLookup().lookup(TskContentItem.class);
<del> Content content = null;
<ide> if (contentItem != null) {
<ide> content = contentItem.getTskContent();
<ide> } else { //fallback and check ContentTags
<ide> ContentTag nodeContentTag = node.getLookup().lookup(ContentTag.class);
<ide> BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
<ide> if (nodeBbArtifactTag != null) {
<del> content = nodeBbArtifactTag.getArtifact();
<add> content = nodeBbArtifactTag.getContent();
<ide> } else if (nodeContentTag != null) {
<ide> content = nodeContentTag.getContent();
<ide> }
<ide> correlationAttributes.addAll(CorrelationAttributeUtil.makeCorrAttrsForSearch(content));
<ide> }
<ide> }
<del>
<add> try {
<add> if (content != null) {
<add> Content dataSource = file.getDataSource();
<add> deviceId = currentCase.getSleuthkitCase().getDataSource(dataSource.getId()).getDeviceId();
<add> dataSourceName = dataSource.getName();
<add> }
<add> } catch (TskException ex) {
<add> logger.log(Level.WARNING, "Exception occurred while trying to get the data source, current case, and device id for an AbstractFile in the other occurrences viewer", ex);
<add> return data;
<add> }
<ide> int totalCount = 0;
<ide> Set<String> dataSources = new HashSet<>();
<ide> for (CorrelationAttributeInstance corAttr : correlationAttributes) { |
|
Java | apache-2.0 | 66281fec33aaebf1a3dad9955b1242ea14ddf90f | 0 | jembi/openxds,jembi/openxds,jembi/openxds | /**
* Copyright 2009 Misys plc, Sysnet International, Medem and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Contributors:
* Misys plc - Implementation
*/
package org.openhealthexchange.openxds;
import org.openhealthexchange.openpixpdq.ihe.configuration.IheConfigurationException;
import org.openhealthexchange.openxds.configuration.XdsConfigurationLoader;
/**
* This class manages the stand alone XDS server startup.
*
* @author <a href="mailto:[email protected]">Wenzhi Li</a>
*
*/
public class XdsServer {
/**
* The main method to start up XDS Registry or Repository server.
*
* @param args For server startup, it is expected to have 2 arguments.
* The first is "startup"; the second one is the full file
* path to IheActors.xml.
* <p>
*/
public static void main(String[] args) {
if (args.length != 2 ||
(args.length == 2 && !args[0].equalsIgnoreCase("startup")) ) {
printUsage();
return ;
}
if (args.length == 2 && args[0].equalsIgnoreCase("startup") ) {
//Start up the servers
XdsConfigurationLoader loader = XdsConfigurationLoader.getInstance();
String actorFile = args[1];
try {
loader.loadConfiguration(actorFile, true);
} catch (IheConfigurationException e) {
e.printStackTrace();
}
}
}
/**
* Prints the usage of how to start up this XDS server.
*/
private static void printUsage() {
System.out.println("*********************************************************");
System.out.println("WRONG USAGE: The XDS server expects 2 arguments.");
System.out.println("To start up the server: ");
System.out.println(" java XdsServer startup <full path of IheActors.xml>");
System.out.println("*********************************************************");
}
}
| openxds/openxds-core/src/main/java/org/openhealthexchange/openxds/XdsServer.java | /**
* Copyright 2009 Misys plc, Sysnet International, Medem and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Contributors:
* Misys plc - Implementation
*/
package org.openhealthexchange.openxds;
import org.openhealthexchange.openpixpdq.ihe.configuration.ConfigurationLoader;
import org.openhealthexchange.openpixpdq.ihe.configuration.IheConfigurationException;
import org.openhealthexchange.openxds.configuration.XdsConfigurationLoader;
/**
* This class manages the stand alone XDS server startup and shutdown.
*
* @author <a href="mailto:[email protected]">Wenzhi Li</a>
*
*/
public class XdsServer {
/**
* The main method to start up or shut down XDS Registry or Repository server.
*
* @param args For server startup, it is expected to have 2 arguments.
* The first is "startup"; the second one is the full file
* path to IheActors.xml.
* <p>
* For server shutdown, provide just one argument "shutdown".
*/
public static void main(String[] args) {
if (args.length < 1 || args.length > 2 ||
(args.length == 1 && !args[0].equalsIgnoreCase("shutdown")) ||
(args.length == 2 && !args[0].equalsIgnoreCase("startup")) ) {
printUsage();
return ;
}
if (args.length == 2 && args[0].equalsIgnoreCase("startup") ) {
//Start up the servers
XdsConfigurationLoader loader = XdsConfigurationLoader.getInstance();
String actorFile = args[1];
try {
loader.loadConfiguration(actorFile, true);
} catch (IheConfigurationException e) {
e.printStackTrace();
}
}
else if (args.length == 1 && args[0].equalsIgnoreCase("shutdown")) {
//Shut down all the active servers
XdsConfigurationLoader.getInstance().resetAllBrokers();
}
}
/**
* Prints the usage of how to start up or shutdown this XDS server.
*/
private static void printUsage() {
System.out.println("*********************************************************");
System.out.println("WRONG USAGE: The XDS server expects 2 arguments.");
System.out.println("To start up the server: ");
System.out.println(" java XdsServer startup <full path of IheActors.xml>");
System.out.println("To shut down the XDS server: ");
System.out.println(" java XdsServer shutdown");
System.out.println("*********************************************************");
}
}
| Removed shutdown option from XdsServer as it is not needed.
| openxds/openxds-core/src/main/java/org/openhealthexchange/openxds/XdsServer.java | Removed shutdown option from XdsServer as it is not needed. | <ide><path>penxds/openxds-core/src/main/java/org/openhealthexchange/openxds/XdsServer.java
<ide> */
<ide> package org.openhealthexchange.openxds;
<ide>
<del>import org.openhealthexchange.openpixpdq.ihe.configuration.ConfigurationLoader;
<ide> import org.openhealthexchange.openpixpdq.ihe.configuration.IheConfigurationException;
<ide> import org.openhealthexchange.openxds.configuration.XdsConfigurationLoader;
<ide>
<ide> /**
<del> * This class manages the stand alone XDS server startup and shutdown.
<add> * This class manages the stand alone XDS server startup.
<ide> *
<ide> * @author <a href="mailto:[email protected]">Wenzhi Li</a>
<ide> *
<ide> public class XdsServer {
<ide>
<ide> /**
<del> * The main method to start up or shut down XDS Registry or Repository server.
<add> * The main method to start up XDS Registry or Repository server.
<ide> *
<ide> * @param args For server startup, it is expected to have 2 arguments.
<ide> * The first is "startup"; the second one is the full file
<ide> * path to IheActors.xml.
<ide> * <p>
<del> * For server shutdown, provide just one argument "shutdown".
<ide> */
<ide> public static void main(String[] args) {
<del> if (args.length < 1 || args.length > 2 ||
<del> (args.length == 1 && !args[0].equalsIgnoreCase("shutdown")) ||
<add> if (args.length != 2 ||
<ide> (args.length == 2 && !args[0].equalsIgnoreCase("startup")) ) {
<ide> printUsage();
<ide> return ;
<ide> e.printStackTrace();
<ide> }
<ide> }
<del> else if (args.length == 1 && args[0].equalsIgnoreCase("shutdown")) {
<del> //Shut down all the active servers
<del> XdsConfigurationLoader.getInstance().resetAllBrokers();
<del> }
<ide>
<ide> }
<ide>
<ide> /**
<del> * Prints the usage of how to start up or shutdown this XDS server.
<add> * Prints the usage of how to start up this XDS server.
<ide> */
<ide> private static void printUsage() {
<ide> System.out.println("*********************************************************");
<ide> System.out.println("WRONG USAGE: The XDS server expects 2 arguments.");
<ide> System.out.println("To start up the server: ");
<ide> System.out.println(" java XdsServer startup <full path of IheActors.xml>");
<del> System.out.println("To shut down the XDS server: ");
<del> System.out.println(" java XdsServer shutdown");
<ide> System.out.println("*********************************************************");
<ide> }
<ide> } |
|
Java | apache-2.0 | 31eaf3ced7b6feb432c6fc12d714c466553ea6de | 0 | awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop,awylie/hadoop | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.Krb5AndCertsSslSocketConnector;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.util.StringUtils;
/**********************************************************
* The Secondary NameNode is a helper to the primary NameNode.
* The Secondary is responsible for supporting periodic checkpoints
* of the HDFS metadata. The current design allows only one Secondary
* NameNode per HDFs cluster.
*
* The Secondary NameNode is a daemon that periodically wakes
* up (determined by the schedule specified in the configuration),
* triggers a periodic checkpoint and then goes back to sleep.
* The Secondary NameNode uses the ClientProtocol to talk to the
* primary NameNode.
*
**********************************************************/
public class SecondaryNameNode implements Runnable {
static{
Configuration.addDefaultResource("hdfs-default.xml");
Configuration.addDefaultResource("hdfs-site.xml");
}
public static final Log LOG =
LogFactory.getLog(SecondaryNameNode.class.getName());
private String fsName;
private CheckpointStorage checkpointImage;
private NamenodeProtocol namenode;
private Configuration conf;
private InetSocketAddress nameNodeAddr;
private volatile boolean shouldRun;
private HttpServer infoServer;
private int infoPort;
private int imagePort;
private String infoBindAddress;
private Collection<File> checkpointDirs;
private Collection<File> checkpointEditsDirs;
private long checkpointPeriod; // in seconds
private long checkpointSize; // size (in MB) of current Edit Log
/**
* Utility class to facilitate junit test error simulation.
*/
static class ErrorSimulator {
private static boolean[] simulation = null; // error simulation events
static void initializeErrorSimulationEvent(int numberOfEvents) {
simulation = new boolean[numberOfEvents];
for (int i = 0; i < numberOfEvents; i++) {
simulation[i] = false;
}
}
static boolean getErrorSimulation(int index) {
if(simulation == null)
return false;
assert(index < simulation.length);
return simulation[index];
}
static void setErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = true;
}
static void clearErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = false;
}
}
FSImage getFSImage() {
return checkpointImage;
}
/**
* Create a connection to the primary namenode.
*/
public SecondaryNameNode(Configuration conf) throws IOException {
try {
initialize(conf);
} catch(IOException e) {
shutdown();
throw e;
}
}
@SuppressWarnings("deprecation")
public static InetSocketAddress getHttpAddress(Configuration conf) {
String infoAddr = NetUtils.getServerAddress(conf,
"dfs.secondary.info.bindAddress", "dfs.secondary.info.port",
"dfs.secondary.http.address");
return NetUtils.createSocketAddr(infoAddr);
}
/**
* Initialize SecondaryNameNode.
*/
private void initialize(final Configuration conf) throws IOException {
final InetSocketAddress infoSocAddr = getHttpAddress(conf);
infoBindAddress = infoSocAddr.getHostName();
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
}
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode =
(NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
NamenodeProtocol.versionID, nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
// Kerberized SSL servers must be run from the host principal...
UserGroupInformation httpUGI =
UserGroupInformation.loginUserFromKeytabAndReturnUGI(
SecurityUtil.getServerPrincipal(conf
.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
infoBindAddress),
conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY));
try {
infoServer = httpUGI.doAs(new PrivilegedExceptionAction<HttpServer>() {
@Override
public HttpServer run() throws IOException, InterruptedException {
LOG.info("Starting web server as: " +
UserGroupInformation.getCurrentUser().getUserName());
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
if(UserGroupInformation.isSecurityEnabled()) {
System.setProperty("https.cipherSuites",
Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0));
InetSocketAddress secInfoSocAddr =
NetUtils.createSocketAddr(infoBindAddress + ":"+ conf.get(
"dfs.secondary.https.port", infoBindAddress + ":" + 0));
imagePort = secInfoSocAddr.getPort();
infoServer.addSslListener(secInfoSocAddr, conf, false, true);
}
infoServer.setAttribute("name.system.image", checkpointImage);
infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class, true);
infoServer.start();
return infoServer;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
LOG.info("Web server init done");
// The web-server port can be ephemeral... ensure we have the correct info
infoPort = infoServer.getPort();
if(!UserGroupInformation.isSecurityEnabled())
imagePort = infoPort;
conf.set("dfs.secondary.http.address", infoBindAddress + ":" +infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" +infoPort);
LOG.info("Secondary image servlet up at: " + infoBindAddress + ":" + imagePort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " +
"(" + checkpointPeriod/60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " +
"(" + checkpointSize/1024 + " KB)");
}
/**
* Shut down this instance of the datanode.
* Returns only after shutdown is complete.
*/
public void shutdown() {
shouldRun = false;
try {
if (infoServer != null) infoServer.stop();
} catch (Exception e) {
LOG.warn("Exception shutting down SecondaryNameNode", e);
}
try {
if (checkpointImage != null) checkpointImage.close();
} catch(IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
public void run() {
if (UserGroupInformation.isSecurityEnabled()) {
UserGroupInformation ugi = null;
try {
ugi = UserGroupInformation.getLoginUser();
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
ugi.doAs(new PrivilegedAction<Object>() {
@Override
public Object run() {
doWork();
return null;
}
});
} else {
doWork();
}
}
//
// The main work loop
//
public void doWork() {
//
// Poll the Namenode (once every 5 minutes) to find the size of the
// pending edit log.
//
long period = 5 * 60; // 5 minutes
long lastCheckpointTime = 0;
if (checkpointPeriod < period) {
period = checkpointPeriod;
}
while (shouldRun) {
try {
Thread.sleep(1000 * period);
} catch (InterruptedException ie) {
// do nothing
}
if (!shouldRun) {
break;
}
try {
// We may have lost our ticket since last checkpoint, log in again, just in case
if(UserGroupInformation.isSecurityEnabled())
UserGroupInformation.getCurrentUser().reloginFromKeytab();
long now = System.currentTimeMillis();
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
now >= lastCheckpointTime + 1000 * checkpointPeriod) {
doCheckpoint();
lastCheckpointTime = now;
}
} catch (IOException e) {
LOG.error("Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
} catch (Throwable e) {
LOG.error("Throwable Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
}
}
/**
* Download <code>fsimage</code> and <code>edits</code>
* files from the name-node.
* @throws IOException
*/
private void downloadCheckpointFiles(final CheckpointSignature sig
) throws IOException {
try {
UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkpointImage.cTime = sig.cTime;
checkpointImage.checkpointTime = sig.checkpointTime;
// get fsimage
String fileid = "getimage=1";
File[] srcNames = checkpointImage.getImageFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
// get edits file
fileid = "getedit=1";
srcNames = checkpointImage.getEditsFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
checkpointImage.checkpointUploadDone();
return null;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Copy the new fsimage into the NameNode
*/
private void putFSImage(CheckpointSignature sig) throws IOException {
String fileid = "putimage=1&port=" + imagePort +
"&machine=" + infoBindAddress +
"&token=" + sig.toString();
LOG.info("Posted URL " + fsName + fileid);
TransferFsImage.getFileClient(fsName, fileid, (File[])null);
}
/**
* Returns the Jetty server that the Namenode is listening on.
*/
private String getInfoServer() throws IOException {
URI fsName = FileSystem.getDefaultUri(conf);
if (!"hdfs".equals(fsName.getScheme())) {
throw new IOException("This is not a DFS");
}
String infoAddr = NameNode.getInfoServer(conf);
LOG.debug("infoAddr = " + infoAddr);
return infoAddr;
}
/**
* Create a new checkpoint
*/
void doCheckpoint() throws IOException {
// Do the required initialization of the merge work area.
startCheckpoint();
// Tell the namenode to start logging transactions in a new edit file
// Retuns a token that would be used to upload the merged image.
CheckpointSignature sig = (CheckpointSignature)namenode.rollEditLog();
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(0)) {
throw new IOException("Simulating error0 " +
"after creating edits.new");
}
downloadCheckpointFiles(sig); // Fetch fsimage and edits
doMerge(sig); // Do the merge
//
// Upload the new image into the NameNode. Then tell the Namenode
// to make this new uploaded image as the most current image.
//
putFSImage(sig);
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(1)) {
throw new IOException("Simulating error1 " +
"after uploading new image to NameNode");
}
namenode.rollFsImage();
checkpointImage.endCheckpoint();
LOG.warn("Checkpoint done. New Image Size: "
+ checkpointImage.getFsImageName().length());
}
private void startCheckpoint() throws IOException {
checkpointImage.unlockAll();
checkpointImage.getEditLog().close();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
checkpointImage.startCheckpoint();
}
/**
* Merge downloaded image and edits and write the new image into
* current storage directory.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem =
new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
/**
* @param argv The parameters passed to this program.
* @exception Exception if the filesystem does not exist.
* @return 0 on success, non zero on error.
*/
private int processArgs(String[] argv) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-geteditsize".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-checkpoint".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
if (argv.length == 2 && !"force".equals(argv[i])) {
printUsage(cmd);
return exitCode;
}
}
exitCode = 0;
try {
if ("-checkpoint".equals(cmd)) {
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
argv.length == 2 && "force".equals(argv[i])) {
doCheckpoint();
} else {
System.err.println("EditLog size " + size + " bytes is " +
"smaller than configured checkpoint " +
"size " + checkpointSize + " bytes.");
System.err.println("Skipping checkpoint.");
}
} else if ("-geteditsize".equals(cmd)) {
long size = namenode.getEditLogSize();
System.out.println("EditLog size is " + size + " bytes");
} else {
exitCode = -1;
LOG.error(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
LOG.error(cmd.substring(1) + ": "
+ content[0]);
} catch (Exception ex) {
LOG.error(cmd.substring(1) + ": "
+ ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
LOG.error(cmd.substring(1) + ": "
+ e.getLocalizedMessage());
} finally {
// Does the RPC connection need to be closed?
}
return exitCode;
}
/**
* Displays format of commands.
* @param cmd The command that is being executed.
*/
private void printUsage(String cmd) {
if ("-geteditsize".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-geteditsize]");
} else if ("-checkpoint".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-checkpoint [force]]");
} else {
System.err.println("Usage: java SecondaryNameNode " +
"[-checkpoint [force]] " +
"[-geteditsize] ");
}
}
/**
* main() has some simple utility methods.
* @param argv Command line parameters.
* @exception Exception if the filesystem does not exist.
*/
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
// Create a never ending deamon
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
static class CheckpointStorage extends FSImage {
/**
*/
CheckpointStorage() throws IOException {
super();
}
@Override
public
boolean isConversionNeeded(StorageDirectory sd) {
return false;
}
/**
* Analyze checkpoint directories.
* Create directories if they do not exist.
* Recover from an unsuccessful checkpoint is necessary.
*
* @param dataDirs
* @param editsDirs
* @throws IOException
*/
void recoverCreate(Collection<File> dataDirs,
Collection<File> editsDirs) throws IOException {
Collection<File> tempDataDirs = new ArrayList<File>(dataDirs);
Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs);
this.storageDirs = new ArrayList<StorageDirectory>();
setStorageDirectories(tempDataDirs, tempEditsDirs);
for (Iterator<StorageDirectory> it =
dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
boolean isAccessible = true;
try { // create directories if don't exist yet
if(!sd.getRoot().mkdirs()) {
// do nothing, directory is already created
}
} catch(SecurityException se) {
isAccessible = false;
}
if(!isAccessible)
throw new InconsistentFSStateException(sd.getRoot(),
"cannot access checkpoint directory.");
StorageState curState;
try {
curState = sd.analyzeStorage(HdfsConstants.StartupOption.REGULAR);
// sd is locked but not opened
switch(curState) {
case NON_EXISTENT:
// fail if any of the configured checkpoint dirs are inaccessible
throw new InconsistentFSStateException(sd.getRoot(),
"checkpoint directory does not exist or is not accessible.");
case NOT_FORMATTED:
break; // it's ok since initially there is no current and VERSION
case NORMAL:
break;
default: // recovery is possible
sd.doRecover(curState);
}
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
}
}
/**
* Prepare directories for a new checkpoint.
* <p>
* Rename <code>current</code> to <code>lastcheckpoint.tmp</code>
* and recreate <code>current</code>.
* @throws IOException
*/
void startCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveCurrent(sd);
}
}
void endCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveLastCheckpoint(sd);
}
}
/**
* Merge image and edits, and verify consistency with the signature.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
getEditLog().open();
StorageDirectory sdName = null;
StorageDirectory sdEdits = null;
Iterator<StorageDirectory> it = null;
it = dirIterator(NameNodeDirType.IMAGE);
if (it.hasNext())
sdName = it.next();
it = dirIterator(NameNodeDirType.EDITS);
if (it.hasNext())
sdEdits = it.next();
if ((sdName == null) || (sdEdits == null))
throw new IOException("Could not locate checkpoint directories");
loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE));
loadFSEdits(sdEdits);
sig.validateStorageInfo(this);
saveNamespace(false);
}
}
}
| src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.Krb5AndCertsSslSocketConnector;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.util.StringUtils;
/**********************************************************
* The Secondary NameNode is a helper to the primary NameNode.
* The Secondary is responsible for supporting periodic checkpoints
* of the HDFS metadata. The current design allows only one Secondary
* NameNode per HDFs cluster.
*
* The Secondary NameNode is a daemon that periodically wakes
* up (determined by the schedule specified in the configuration),
* triggers a periodic checkpoint and then goes back to sleep.
* The Secondary NameNode uses the ClientProtocol to talk to the
* primary NameNode.
*
**********************************************************/
public class SecondaryNameNode implements Runnable {
static{
Configuration.addDefaultResource("hdfs-default.xml");
Configuration.addDefaultResource("hdfs-site.xml");
}
public static final Log LOG =
LogFactory.getLog(SecondaryNameNode.class.getName());
private String fsName;
private CheckpointStorage checkpointImage;
private NamenodeProtocol namenode;
private Configuration conf;
private InetSocketAddress nameNodeAddr;
private volatile boolean shouldRun;
private HttpServer infoServer;
private int infoPort;
private int imagePort;
private String infoBindAddress;
private Collection<File> checkpointDirs;
private Collection<File> checkpointEditsDirs;
private long checkpointPeriod; // in seconds
private long checkpointSize; // size (in MB) of current Edit Log
/**
* Utility class to facilitate junit test error simulation.
*/
static class ErrorSimulator {
private static boolean[] simulation = null; // error simulation events
static void initializeErrorSimulationEvent(int numberOfEvents) {
simulation = new boolean[numberOfEvents];
for (int i = 0; i < numberOfEvents; i++) {
simulation[i] = false;
}
}
static boolean getErrorSimulation(int index) {
if(simulation == null)
return false;
assert(index < simulation.length);
return simulation[index];
}
static void setErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = true;
}
static void clearErrorSimulation(int index) {
assert(index < simulation.length);
simulation[index] = false;
}
}
FSImage getFSImage() {
return checkpointImage;
}
/**
* Create a connection to the primary namenode.
*/
public SecondaryNameNode(Configuration conf) throws IOException {
try {
initialize(conf);
} catch(IOException e) {
shutdown();
throw e;
}
}
@SuppressWarnings("deprecation")
public static InetSocketAddress getHttpAddress(Configuration conf) {
String infoAddr = NetUtils.getServerAddress(conf,
"dfs.secondary.info.bindAddress", "dfs.secondary.info.port",
"dfs.secondary.http.address");
return NetUtils.createSocketAddr(infoAddr);
}
/**
* Initialize SecondaryNameNode.
*/
private void initialize(final Configuration conf) throws IOException {
final InetSocketAddress infoSocAddr = getHttpAddress(conf);
infoBindAddress = infoSocAddr.getHostName();
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
}
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode =
(NamenodeProtocol) RPC.waitForProxy(NamenodeProtocol.class,
NamenodeProtocol.versionID, nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
// Kerberized SSL servers must be run from the host principal...
if (UserGroupInformation.isSecurityEnabled()) {
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY,
infoBindAddress);
}
UserGroupInformation ugi = UserGroupInformation.getLoginUser();
try {
infoServer = ugi.doAs(new PrivilegedExceptionAction<HttpServer>() {
@Override
public HttpServer run() throws IOException, InterruptedException {
LOG.info("Starting web server as: " +
UserGroupInformation.getLoginUser().getUserName());
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
if(UserGroupInformation.isSecurityEnabled()) {
System.setProperty("https.cipherSuites",
Krb5AndCertsSslSocketConnector.KRB5_CIPHER_SUITES.get(0));
InetSocketAddress secInfoSocAddr =
NetUtils.createSocketAddr(infoBindAddress + ":"+ conf.get(
"dfs.secondary.https.port", infoBindAddress + ":" + 0));
imagePort = secInfoSocAddr.getPort();
infoServer.addSslListener(secInfoSocAddr, conf, false, true);
}
infoServer.setAttribute("name.system.image", checkpointImage);
infoServer.setAttribute(JspHelper.CURRENT_CONF, conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class, true);
infoServer.start();
return infoServer;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
if (UserGroupInformation.isSecurityEnabled()) {
// Go back to being the correct Namenode principal
SecurityUtil.login(conf,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
infoBindAddress);
LOG.info("Web server init done, returning to: " +
UserGroupInformation.getLoginUser().getUserName());
}
}
// The web-server port can be ephemeral... ensure we have the correct info
infoPort = infoServer.getPort();
if(!UserGroupInformation.isSecurityEnabled())
imagePort = infoPort;
conf.set("dfs.secondary.http.address", infoBindAddress + ":" +infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" +infoPort);
LOG.info("Secondary image servlet up at: " + infoBindAddress + ":" + imagePort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " +
"(" + checkpointPeriod/60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " +
"(" + checkpointSize/1024 + " KB)");
}
/**
* Shut down this instance of the datanode.
* Returns only after shutdown is complete.
*/
public void shutdown() {
shouldRun = false;
try {
if (infoServer != null) infoServer.stop();
} catch (Exception e) {
LOG.warn("Exception shutting down SecondaryNameNode", e);
}
try {
if (checkpointImage != null) checkpointImage.close();
} catch(IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
public void run() {
if (UserGroupInformation.isSecurityEnabled()) {
UserGroupInformation ugi = null;
try {
ugi = UserGroupInformation.getLoginUser();
} catch (IOException e) {
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
ugi.doAs(new PrivilegedAction<Object>() {
@Override
public Object run() {
doWork();
return null;
}
});
} else {
doWork();
}
}
//
// The main work loop
//
public void doWork() {
//
// Poll the Namenode (once every 5 minutes) to find the size of the
// pending edit log.
//
long period = 5 * 60; // 5 minutes
long lastCheckpointTime = 0;
if (checkpointPeriod < period) {
period = checkpointPeriod;
}
while (shouldRun) {
try {
Thread.sleep(1000 * period);
} catch (InterruptedException ie) {
// do nothing
}
if (!shouldRun) {
break;
}
try {
// We may have lost our ticket since last checkpoint, log in again, just in case
if(UserGroupInformation.isSecurityEnabled())
UserGroupInformation.getCurrentUser().reloginFromKeytab();
long now = System.currentTimeMillis();
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
now >= lastCheckpointTime + 1000 * checkpointPeriod) {
doCheckpoint();
lastCheckpointTime = now;
}
} catch (IOException e) {
LOG.error("Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
} catch (Throwable e) {
LOG.error("Throwable Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
}
}
/**
* Download <code>fsimage</code> and <code>edits</code>
* files from the name-node.
* @throws IOException
*/
private void downloadCheckpointFiles(final CheckpointSignature sig
) throws IOException {
try {
UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
checkpointImage.cTime = sig.cTime;
checkpointImage.checkpointTime = sig.checkpointTime;
// get fsimage
String fileid = "getimage=1";
File[] srcNames = checkpointImage.getImageFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
// get edits file
fileid = "getedit=1";
srcNames = checkpointImage.getEditsFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size " +
srcNames[0].length() + " bytes.");
checkpointImage.checkpointUploadDone();
return null;
}
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Copy the new fsimage into the NameNode
*/
private void putFSImage(CheckpointSignature sig) throws IOException {
String fileid = "putimage=1&port=" + imagePort +
"&machine=" + infoBindAddress +
"&token=" + sig.toString();
LOG.info("Posted URL " + fsName + fileid);
TransferFsImage.getFileClient(fsName, fileid, (File[])null);
}
/**
* Returns the Jetty server that the Namenode is listening on.
*/
private String getInfoServer() throws IOException {
URI fsName = FileSystem.getDefaultUri(conf);
if (!"hdfs".equals(fsName.getScheme())) {
throw new IOException("This is not a DFS");
}
String infoAddr = NameNode.getInfoServer(conf);
LOG.debug("infoAddr = " + infoAddr);
return infoAddr;
}
/**
* Create a new checkpoint
*/
void doCheckpoint() throws IOException {
// Do the required initialization of the merge work area.
startCheckpoint();
// Tell the namenode to start logging transactions in a new edit file
// Retuns a token that would be used to upload the merged image.
CheckpointSignature sig = (CheckpointSignature)namenode.rollEditLog();
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(0)) {
throw new IOException("Simulating error0 " +
"after creating edits.new");
}
downloadCheckpointFiles(sig); // Fetch fsimage and edits
doMerge(sig); // Do the merge
//
// Upload the new image into the NameNode. Then tell the Namenode
// to make this new uploaded image as the most current image.
//
putFSImage(sig);
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(1)) {
throw new IOException("Simulating error1 " +
"after uploading new image to NameNode");
}
namenode.rollFsImage();
checkpointImage.endCheckpoint();
LOG.warn("Checkpoint done. New Image Size: "
+ checkpointImage.getFsImageName().length());
}
private void startCheckpoint() throws IOException {
checkpointImage.unlockAll();
checkpointImage.getEditLog().close();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
checkpointImage.startCheckpoint();
}
/**
* Merge downloaded image and edits and write the new image into
* current storage directory.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem =
new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
/**
* @param argv The parameters passed to this program.
* @exception Exception if the filesystem does not exist.
* @return 0 on success, non zero on error.
*/
private int processArgs(String[] argv) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-geteditsize".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-checkpoint".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
if (argv.length == 2 && !"force".equals(argv[i])) {
printUsage(cmd);
return exitCode;
}
}
exitCode = 0;
try {
if ("-checkpoint".equals(cmd)) {
long size = namenode.getEditLogSize();
if (size >= checkpointSize ||
argv.length == 2 && "force".equals(argv[i])) {
doCheckpoint();
} else {
System.err.println("EditLog size " + size + " bytes is " +
"smaller than configured checkpoint " +
"size " + checkpointSize + " bytes.");
System.err.println("Skipping checkpoint.");
}
} else if ("-geteditsize".equals(cmd)) {
long size = namenode.getEditLogSize();
System.out.println("EditLog size is " + size + " bytes");
} else {
exitCode = -1;
LOG.error(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
LOG.error(cmd.substring(1) + ": "
+ content[0]);
} catch (Exception ex) {
LOG.error(cmd.substring(1) + ": "
+ ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
LOG.error(cmd.substring(1) + ": "
+ e.getLocalizedMessage());
} finally {
// Does the RPC connection need to be closed?
}
return exitCode;
}
/**
* Displays format of commands.
* @param cmd The command that is being executed.
*/
private void printUsage(String cmd) {
if ("-geteditsize".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-geteditsize]");
} else if ("-checkpoint".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-checkpoint [force]]");
} else {
System.err.println("Usage: java SecondaryNameNode " +
"[-checkpoint [force]] " +
"[-geteditsize] ");
}
}
/**
* main() has some simple utility methods.
* @param argv Command line parameters.
* @exception Exception if the filesystem does not exist.
*/
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
// Create a never ending deamon
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
static class CheckpointStorage extends FSImage {
/**
*/
CheckpointStorage() throws IOException {
super();
}
@Override
public
boolean isConversionNeeded(StorageDirectory sd) {
return false;
}
/**
* Analyze checkpoint directories.
* Create directories if they do not exist.
* Recover from an unsuccessful checkpoint is necessary.
*
* @param dataDirs
* @param editsDirs
* @throws IOException
*/
void recoverCreate(Collection<File> dataDirs,
Collection<File> editsDirs) throws IOException {
Collection<File> tempDataDirs = new ArrayList<File>(dataDirs);
Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs);
this.storageDirs = new ArrayList<StorageDirectory>();
setStorageDirectories(tempDataDirs, tempEditsDirs);
for (Iterator<StorageDirectory> it =
dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
boolean isAccessible = true;
try { // create directories if don't exist yet
if(!sd.getRoot().mkdirs()) {
// do nothing, directory is already created
}
} catch(SecurityException se) {
isAccessible = false;
}
if(!isAccessible)
throw new InconsistentFSStateException(sd.getRoot(),
"cannot access checkpoint directory.");
StorageState curState;
try {
curState = sd.analyzeStorage(HdfsConstants.StartupOption.REGULAR);
// sd is locked but not opened
switch(curState) {
case NON_EXISTENT:
// fail if any of the configured checkpoint dirs are inaccessible
throw new InconsistentFSStateException(sd.getRoot(),
"checkpoint directory does not exist or is not accessible.");
case NOT_FORMATTED:
break; // it's ok since initially there is no current and VERSION
case NORMAL:
break;
default: // recovery is possible
sd.doRecover(curState);
}
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
}
}
/**
* Prepare directories for a new checkpoint.
* <p>
* Rename <code>current</code> to <code>lastcheckpoint.tmp</code>
* and recreate <code>current</code>.
* @throws IOException
*/
void startCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveCurrent(sd);
}
}
void endCheckpoint() throws IOException {
for(StorageDirectory sd : storageDirs) {
moveLastCheckpoint(sd);
}
}
/**
* Merge image and edits, and verify consistency with the signature.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
getEditLog().open();
StorageDirectory sdName = null;
StorageDirectory sdEdits = null;
Iterator<StorageDirectory> it = null;
it = dirIterator(NameNodeDirType.IMAGE);
if (it.hasNext())
sdName = it.next();
it = dirIterator(NameNodeDirType.EDITS);
if (it.hasNext())
sdEdits = it.next();
if ((sdName == null) || (sdEdits == null))
throw new IOException("Could not locate checkpoint directories");
loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE));
loadFSEdits(sdEdits);
sig.validateStorageInfo(this);
saveNamespace(false);
}
}
}
| commit ebdc0709836b6ec9823d2a335c083a9ff411f72a
Author: Devaraj Das <[email protected]>
Date: Wed May 5 14:09:32 2010 -0700
HDFS:1006 from https://issues.apache.org/jira/secure/attachment/12443766/hdfs-1006-bugfix-1.patch
+++ b/YAHOO-CHANGES.txt
+ HDFS-1006. Removes unnecessary logins from the previous patch. (ddas)
+
+ HADOOP-6745. adding some java doc to Server.RpcMetrics, UGI (boryas)
+
git-svn-id: 7e7a2d564dde2945c3a26e08d1235fcc0cb7aba1@1077442 13f79535-47bb-0310-9956-ffa450edef68
| src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java | commit ebdc0709836b6ec9823d2a335c083a9ff411f72a Author: Devaraj Das <[email protected]> Date: Wed May 5 14:09:32 2010 -0700 | <ide><path>rc/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java
<ide>
<ide> // initialize the webserver for uploading files.
<ide> // Kerberized SSL servers must be run from the host principal...
<del> if (UserGroupInformation.isSecurityEnabled()) {
<del> SecurityUtil.login(conf,
<del> DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
<del> DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY,
<del> infoBindAddress);
<del> }
<del> UserGroupInformation ugi = UserGroupInformation.getLoginUser();
<add> UserGroupInformation httpUGI =
<add> UserGroupInformation.loginUserFromKeytabAndReturnUGI(
<add> SecurityUtil.getServerPrincipal(conf
<add> .get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KRB_HTTPS_USER_NAME_KEY),
<add> infoBindAddress),
<add> conf.get(DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY));
<ide> try {
<del> infoServer = ugi.doAs(new PrivilegedExceptionAction<HttpServer>() {
<add> infoServer = httpUGI.doAs(new PrivilegedExceptionAction<HttpServer>() {
<ide>
<ide> @Override
<ide> public HttpServer run() throws IOException, InterruptedException {
<ide> LOG.info("Starting web server as: " +
<del> UserGroupInformation.getLoginUser().getUserName());
<add> UserGroupInformation.getCurrentUser().getUserName());
<ide>
<ide> int tmpInfoPort = infoSocAddr.getPort();
<ide> infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
<ide> });
<ide> } catch (InterruptedException e) {
<ide> throw new RuntimeException(e);
<del> } finally {
<del> if (UserGroupInformation.isSecurityEnabled()) {
<del> // Go back to being the correct Namenode principal
<del> SecurityUtil.login(conf,
<del> DFSConfigKeys.DFS_SECONDARY_NAMENODE_KEYTAB_FILE_KEY,
<del> DFSConfigKeys.DFS_SECONDARY_NAMENODE_USER_NAME_KEY,
<del> infoBindAddress);
<del> LOG.info("Web server init done, returning to: " +
<del> UserGroupInformation.getLoginUser().getUserName());
<del> }
<del> }
<add> }
<add> LOG.info("Web server init done");
<ide> // The web-server port can be ephemeral... ensure we have the correct info
<ide>
<ide> infoPort = infoServer.getPort(); |
|
Java | apache-2.0 | aba6431ae8677446fea8508be17d9be019250edd | 0 | phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida | package ca.corefacility.bioinformatics.irida.ria.unit.web.oauth;
import java.util.*;
import java.util.function.Function;
import javax.validation.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import ca.corefacility.bioinformatics.irida.model.RemoteAPI;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.RemoteAPIAjaxController;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxCreateItemSuccessResponse;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxFormErrorResponse;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxResponse;
import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableRequest;
import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableResponse;
import ca.corefacility.bioinformatics.irida.ria.web.rempoteapi.dto.RemoteAPITableModel;
import ca.corefacility.bioinformatics.irida.ria.web.services.UIRemoteAPIService;
import ca.corefacility.bioinformatics.irida.service.RemoteAPIService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.*;
/**
* Testing for {@link RemoteAPIAjaxController}
*/
public class RemoteAPIAjaxControllerTest {
private RemoteAPIService remoteAPIService;
private UIRemoteAPIService uiRemoteAPIService;
private RemoteAPIAjaxController controller;
private MessageSource messageSource;
private final RemoteAPI REMOTE_API_01 = new RemoteAPI("Toronto", "http://toronto.nowhere", "", "toronto", "123456");
private final RemoteAPI REMOTE_API_02 = new RemoteAPI("Washington", "http://washington.nowhere", "", "washington",
"654321");
@Before
public void init() {
remoteAPIService = mock(RemoteAPIService.class);
uiRemoteAPIService = mock(UIRemoteAPIService.class);
messageSource = mock(MessageSource.class);
controller = new RemoteAPIAjaxController(remoteAPIService, uiRemoteAPIService, messageSource);
Page<RemoteAPI> remoteAPIPage = new Page<>() {
@Override
public int getTotalPages() {
return 10;
}
@Override
public long getTotalElements() {
return 104;
}
@Override
public <U> Page<U> map(Function<? super RemoteAPI, ? extends U> function) {
return null;
}
@Override
public int getNumber() {
return 0;
}
@Override
public int getSize() {
return 0;
}
@Override
public int getNumberOfElements() {
return 104;
}
@Override
public List<RemoteAPI> getContent() {
return List.of(REMOTE_API_01);
}
@Override
public boolean hasContent() {
return true;
}
@Override
public Sort getSort() {
return null;
}
@Override
public boolean isFirst() {
return false;
}
@Override
public boolean isLast() {
return false;
}
@Override
public boolean hasNext() {
return false;
}
@Override
public boolean hasPrevious() {
return false;
}
@Override
public Pageable nextPageable() {
return null;
}
@Override
public Pageable previousPageable() {
return null;
}
@Override
public Iterator<RemoteAPI> iterator() {
return null;
}
};
when(remoteAPIService.search(any(), anyInt(), anyInt(), any(Sort.Direction.class),
any(String[].class))).thenReturn(remoteAPIPage);
when(remoteAPIService.read(1L)).thenReturn(REMOTE_API_01);
when(remoteAPIService.read(2L)).thenReturn(REMOTE_API_02);
}
@Test
public void getAjaxAPIListTest() {
TableRequest request = new TableRequest();
request.setSortColumn("label");
request.setSortDirection("ascend");
request.setCurrent(0);
request.setPageSize(10);
TableResponse<RemoteAPITableModel> response = controller.getAjaxAPIList(request);
verify(remoteAPIService, times(1)).search(any(), anyInt(), anyInt(), any(Sort.Direction.class),
any(String[].class));
assertEquals("Should have 1 Remote API", 1, response.getDataSource()
.size());
}
@Test
public void testPostCreateRemoteAPI_goodRequest() {
RemoteAPI client = new RemoteAPI("NEW CLIENT", "http://example.com", "", "CLIENT_ID", "CLIENT_SECRET");
RemoteAPI createdClient = new RemoteAPI("NEW CLIENT", "http://example.com", "", "CLIENT_ID", "CLIENT_SECRET");
createdClient.setId(1L);
when(remoteAPIService.create(client)).thenReturn(createdClient);
ResponseEntity<AjaxResponse> response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
assertEquals("Should have a response status of 200", response.getStatusCode(), HttpStatus.OK);
AjaxCreateItemSuccessResponse ajaxCreateItemSuccessResponse = (AjaxCreateItemSuccessResponse) response.getBody();
assert ajaxCreateItemSuccessResponse != null;
assertEquals("Should return the id of the newly created remote api", 1L, ajaxCreateItemSuccessResponse.getId());
}
@Test
public void testPostCreateRemoteAPI_badRequest() {
RemoteAPI client = new RemoteAPI(null, null, "", "CLIENT_ID", "CLIENT_SECRET");
Configuration<?> configuration = Validation.byDefaultProvider().configure();
ValidatorFactory factory = configuration.buildValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<RemoteAPI>> violations = validator.validate(client);
HashSet<ConstraintViolation<?>> constraintViolations = new HashSet<>(violations);
when(remoteAPIService.create(client)).thenThrow(new ConstraintViolationException(constraintViolations));
ResponseEntity<AjaxResponse> response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
verify(remoteAPIService, times(1)).create(client);
assertEquals("Should return a 422 response", response.getStatusCode(), HttpStatus.UNPROCESSABLE_ENTITY);
AjaxFormErrorResponse formErrorsResponse = (AjaxFormErrorResponse)response.getBody();
assert formErrorsResponse != null;
Map<String, String> formErrors = formErrorsResponse.getErrors();
assertEquals("Form should have 3 errors", 3, formErrors.keySet()
.size());
assertTrue("Should have a serviceUri error", formErrors.containsKey("serviceURI"));
assertTrue("Should have a name error", formErrors.containsKey("name"));
assertTrue("Should have a label error", formErrors.containsKey("label"));
}
}
| src/test/java/ca/corefacility/bioinformatics/irida/ria/unit/web/oauth/RemoteAPIAjaxControllerTest.java | package ca.corefacility.bioinformatics.irida.ria.unit.web.oauth;
import java.util.*;
import java.util.function.Function;
import javax.validation.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import ca.corefacility.bioinformatics.irida.model.RemoteAPI;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.RemoteAPIAjaxController;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxCreateItemSuccessResponse;
import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableRequest;
import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableResponse;
import ca.corefacility.bioinformatics.irida.ria.web.rempoteapi.dto.RemoteAPITableModel;
import ca.corefacility.bioinformatics.irida.ria.web.services.UIRemoteAPIService;
import ca.corefacility.bioinformatics.irida.service.RemoteAPIService;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.*;
/**
* Testing for {@link RemoteAPIAjaxController}
*/
public class RemoteAPIAjaxControllerTest {
private RemoteAPIService remoteAPIService;
private UIRemoteAPIService uiRemoteAPIService;
private RemoteAPIAjaxController controller;
private MessageSource messageSource;
private final RemoteAPI REMOTE_API_01 = new RemoteAPI("Toronto", "http://toronto.nowhere", "", "toronto", "123456");
private final RemoteAPI REMOTE_API_02 = new RemoteAPI("Washington", "http://washington.nowhere", "", "washington",
"654321");
@Before
public void init() {
remoteAPIService = mock(RemoteAPIService.class);
uiRemoteAPIService = mock(UIRemoteAPIService.class);
messageSource = mock(MessageSource.class);
controller = new RemoteAPIAjaxController(remoteAPIService, uiRemoteAPIService, messageSource);
Page<RemoteAPI> remoteAPIPage = new Page<>() {
@Override
public int getTotalPages() {
return 10;
}
@Override
public long getTotalElements() {
return 104;
}
@Override
public <U> Page<U> map(Function<? super RemoteAPI, ? extends U> function) {
return null;
}
@Override
public int getNumber() {
return 0;
}
@Override
public int getSize() {
return 0;
}
@Override
public int getNumberOfElements() {
return 104;
}
@Override
public List<RemoteAPI> getContent() {
return List.of(REMOTE_API_01);
}
@Override
public boolean hasContent() {
return true;
}
@Override
public Sort getSort() {
return null;
}
@Override
public boolean isFirst() {
return false;
}
@Override
public boolean isLast() {
return false;
}
@Override
public boolean hasNext() {
return false;
}
@Override
public boolean hasPrevious() {
return false;
}
@Override
public Pageable nextPageable() {
return null;
}
@Override
public Pageable previousPageable() {
return null;
}
@Override
public Iterator<RemoteAPI> iterator() {
return null;
}
};
when(remoteAPIService.search(any(), anyInt(), anyInt(), any(Sort.Direction.class),
any(String[].class))).thenReturn(remoteAPIPage);
when(remoteAPIService.read(1L)).thenReturn(REMOTE_API_01);
when(remoteAPIService.read(2L)).thenReturn(REMOTE_API_02);
}
@Test
public void getAjaxAPIListTest() {
TableRequest request = new TableRequest();
request.setSortColumn("label");
request.setSortDirection("ascend");
request.setCurrent(0);
request.setPageSize(10);
TableResponse<RemoteAPITableModel> response = controller.getAjaxAPIList(request);
verify(remoteAPIService, times(1)).search(any(), anyInt(), anyInt(), any(Sort.Direction.class),
any(String[].class));
assertEquals("Should have 1 Remote API", 1, response.getDataSource()
.size());
}
@Test
public void testPostCreateRemoteAPI_goodRequest() {
RemoteAPI client = new RemoteAPI("NEW CLIENT", "http://example.com", "", "CLIENT_ID", "CLIENT_SECRET");
RemoteAPI createdClient = new RemoteAPI("NEW CLIENT", "http://example.com", "", "CLIENT_ID", "CLIENT_SECRET");
createdClient.setId(1L);
when(remoteAPIService.create(client)).thenReturn(createdClient);
ResponseEntity response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
assertEquals("Should have a response status of 200", response.getStatusCode(), HttpStatus.OK);
AjaxCreateItemSuccessResponse ajaxCreateItemSuccessResponse = (AjaxCreateItemSuccessResponse) response.getBody();
assertEquals("Should return the id of the newly created remote api", 1L, ajaxCreateItemSuccessResponse.getId());
String foobar = "baz";
}
@Test
public void testPostCreateRemoteAPI_badRequest() {
RemoteAPI client = new RemoteAPI(null, null, "", "CLIENT_ID", "CLIENT_SECRET");
RemoteAPI createdClient = new RemoteAPI(null, null, "", "CLIENT_ID", "CLIENT_SECRET");
createdClient.setId(1L);
Configuration<?> configuration = Validation.byDefaultProvider().configure();
ValidatorFactory factory = configuration.buildValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<RemoteAPI>> violations = validator.validate(client);
HashSet<ConstraintViolation<?>> constraintViolations = new HashSet<>(violations);
when(remoteAPIService.create(client)).thenThrow(new ConstraintViolationException(constraintViolations));
ResponseEntity response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
verify(remoteAPIService, times(1)).create(client);
}
}
| Updated testing for RemoteAPIAjaxController
| src/test/java/ca/corefacility/bioinformatics/irida/ria/unit/web/oauth/RemoteAPIAjaxControllerTest.java | Updated testing for RemoteAPIAjaxController | <ide><path>rc/test/java/ca/corefacility/bioinformatics/irida/ria/unit/web/oauth/RemoteAPIAjaxControllerTest.java
<ide> import ca.corefacility.bioinformatics.irida.model.RemoteAPI;
<ide> import ca.corefacility.bioinformatics.irida.ria.web.ajax.RemoteAPIAjaxController;
<ide> import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxCreateItemSuccessResponse;
<add>import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxFormErrorResponse;
<add>import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxResponse;
<ide> import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableRequest;
<ide> import ca.corefacility.bioinformatics.irida.ria.web.models.tables.TableResponse;
<ide> import ca.corefacility.bioinformatics.irida.ria.web.rempoteapi.dto.RemoteAPITableModel;
<ide> import ca.corefacility.bioinformatics.irida.service.RemoteAPIService;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertTrue;
<ide> import static org.mockito.Matchers.any;
<ide> import static org.mockito.Matchers.anyInt;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> when(remoteAPIService.create(client)).thenReturn(createdClient);
<ide>
<del> ResponseEntity response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
<add> ResponseEntity<AjaxResponse> response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
<ide> assertEquals("Should have a response status of 200", response.getStatusCode(), HttpStatus.OK);
<ide> AjaxCreateItemSuccessResponse ajaxCreateItemSuccessResponse = (AjaxCreateItemSuccessResponse) response.getBody();
<add> assert ajaxCreateItemSuccessResponse != null;
<ide> assertEquals("Should return the id of the newly created remote api", 1L, ajaxCreateItemSuccessResponse.getId());
<del> String foobar = "baz";
<ide> }
<ide>
<ide> @Test
<ide> public void testPostCreateRemoteAPI_badRequest() {
<ide> RemoteAPI client = new RemoteAPI(null, null, "", "CLIENT_ID", "CLIENT_SECRET");
<del> RemoteAPI createdClient = new RemoteAPI(null, null, "", "CLIENT_ID", "CLIENT_SECRET");
<del> createdClient.setId(1L);
<ide>
<ide> Configuration<?> configuration = Validation.byDefaultProvider().configure();
<ide> ValidatorFactory factory = configuration.buildValidatorFactory();
<ide>
<ide> when(remoteAPIService.create(client)).thenThrow(new ConstraintViolationException(constraintViolations));
<ide>
<del> ResponseEntity response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
<del>
<add> ResponseEntity<AjaxResponse> response = controller.postCreateRemoteAPI(client, Locale.ENGLISH);
<ide> verify(remoteAPIService, times(1)).create(client);
<add> assertEquals("Should return a 422 response", response.getStatusCode(), HttpStatus.UNPROCESSABLE_ENTITY);
<add> AjaxFormErrorResponse formErrorsResponse = (AjaxFormErrorResponse)response.getBody();
<add> assert formErrorsResponse != null;
<add> Map<String, String> formErrors = formErrorsResponse.getErrors();
<add> assertEquals("Form should have 3 errors", 3, formErrors.keySet()
<add> .size());
<add> assertTrue("Should have a serviceUri error", formErrors.containsKey("serviceURI"));
<add> assertTrue("Should have a name error", formErrors.containsKey("name"));
<add> assertTrue("Should have a label error", formErrors.containsKey("label"));
<ide> }
<ide> } |
|
Java | apache-2.0 | 24fe6423311af0bf686888c90516444c11622974 | 0 | habren/KafkaExample | package com.jasongj.kafka.connect;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Map;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.utils.AppInfoParser;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;
public class ConsoleSinkTask extends SinkTask {
private PrintStream printStream;
@Override
public String version() {
return AppInfoParser.getVersion();
}
@Override
public void flush(Map<TopicPartition, OffsetAndMetadata> offsets) {
if(printStream != null){
printStream.flush();
}
}
@Override
public void put(Collection<SinkRecord> records) {
records.forEach(printStream::println);
}
@Override
public void start(Map<String, String> config) {
this.printStream = System.out;
}
@Override
public void stop() {
if(printStream != null){
printStream.close();
}
}
}
| demokafka.0.10.1.0/src/main/java/com/jasongj/kafka/connect/ConsoleSinkTask.java | package com.jasongj.kafka.connect;
import java.util.Collection;
import java.util.Map;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;
public class ConsoleSinkTask extends SinkTask {
@Override
public String version() {
return null;
}
@Override
public void flush(Map<TopicPartition, OffsetAndMetadata> arg0) {
}
@Override
public void put(Collection<SinkRecord> arg0) {
}
@Override
public void start(Map<String, String> arg0) {
}
@Override
public void stop() {
}
}
| Implement ConsoleSinkTask
| demokafka.0.10.1.0/src/main/java/com/jasongj/kafka/connect/ConsoleSinkTask.java | Implement ConsoleSinkTask | <ide><path>emokafka.0.10.1.0/src/main/java/com/jasongj/kafka/connect/ConsoleSinkTask.java
<ide> package com.jasongj.kafka.connect;
<ide>
<add>import java.io.PrintStream;
<ide> import java.util.Collection;
<ide> import java.util.Map;
<ide>
<ide> import org.apache.kafka.clients.consumer.OffsetAndMetadata;
<ide> import org.apache.kafka.common.TopicPartition;
<add>import org.apache.kafka.common.utils.AppInfoParser;
<ide> import org.apache.kafka.connect.sink.SinkRecord;
<ide> import org.apache.kafka.connect.sink.SinkTask;
<ide>
<ide> public class ConsoleSinkTask extends SinkTask {
<ide>
<add> private PrintStream printStream;
<add>
<ide> @Override
<ide> public String version() {
<del> return null;
<add> return AppInfoParser.getVersion();
<ide> }
<ide>
<ide> @Override
<del> public void flush(Map<TopicPartition, OffsetAndMetadata> arg0) {
<del>
<add> public void flush(Map<TopicPartition, OffsetAndMetadata> offsets) {
<add> if(printStream != null){
<add> printStream.flush();
<add> }
<ide> }
<ide>
<ide> @Override
<del> public void put(Collection<SinkRecord> arg0) {
<del>
<add> public void put(Collection<SinkRecord> records) {
<add> records.forEach(printStream::println);
<ide> }
<ide>
<ide> @Override
<del> public void start(Map<String, String> arg0) {
<del>
<add> public void start(Map<String, String> config) {
<add> this.printStream = System.out;
<ide> }
<ide>
<ide> @Override
<ide> public void stop() {
<add> if(printStream != null){
<add> printStream.close();
<add> }
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | 5588273537130231e83b3029045087987ba88075 | 0 | tectronics/scalaris,seyyed/scalaris,tectronics/scalaris,seyyed/scalaris,seyyed/scalaris,digshock/scalaris,digshock/scalaris,seyyed/scalaris,seyyed/scalaris,tectronics/scalaris,tectronics/scalaris,digshock/scalaris,digshock/scalaris,seyyed/scalaris,digshock/scalaris,tectronics/scalaris,digshock/scalaris,digshock/scalaris,tectronics/scalaris,tectronics/scalaris,seyyed/scalaris | /**
* Copyright 2007-2011 Zuse Institute Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.zib.scalaris.examples.wikipedia.data.xml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import de.zib.scalaris.examples.wikipedia.data.Revision;
import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler.ReportAtShutDown;
/**
* Provides abilities to read an xml wiki dump file and write Wiki pages to
* Scalaris.
*
* @author Nico Kruber, [email protected]
*/
public class Main {
/**
* Default blacklist - pages with these names are not imported
*/
public final static Set<String> blacklist = new HashSet<String>();
/**
* The main function of the application. Some articles are blacklisted and
* will not be processed (see implementation for a list of them).
*
* @param args
* first argument should be the xml file to convert.
*/
public static void main(String[] args) {
try {
String filename = args[0];
if (args.length > 1) {
if (args[1].equals("filter")) {
doFilter(filename, Arrays.copyOfRange(args, 2, args.length));
} else if (args[1].equals("import")) {
doImport(filename, Arrays.copyOfRange(args, 2, args.length), false);
} else if (args[1].equals("prepare")) {
doImport(filename, Arrays.copyOfRange(args, 2, args.length), true);
}
}
} catch (SAXException e) {
System.err.println(e.getMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Imports all pages in the Wikipedia XML dump from the given file to Scalaris.
*
* @param filename
* @param args
* @param prepare
*
* @throws RuntimeException
* @throws IOException
* @throws SAXException
* @throws FileNotFoundException
*/
private static void doImport(String filename, String[] args, boolean prepare) throws RuntimeException, IOException,
SAXException, FileNotFoundException {
int i = 0;
int maxRevisions = -1;
if (args.length > i) {
try {
maxRevisions = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {
System.err.println("no number: " + args[i]);
System.exit(-1);
}
}
++i;
// a timestamp in ISO8601 format
Calendar minTime = null;
if (args.length > i && !args[i].isEmpty()) {
try {
minTime = Revision.stringToCalendar(args[i]);
} catch (IllegalArgumentException e) {
System.err.println("no date in ISO8601: " + args[i]);
System.exit(-1);
}
}
++i;
// a timestamp in ISO8601 format
Calendar maxTime = null;
if (args.length > i && !args[i].isEmpty()) {
try {
maxTime = Revision.stringToCalendar(args[i]);
} catch (IllegalArgumentException e) {
System.err.println("no date in ISO8601: " + args[i]);
System.exit(-1);
}
}
++i;
Set<String> whitelist = null;
String whitelistFile = "";
if (args.length > i && !args[i].isEmpty()) {
whitelistFile = args[i];
FileReader inFile = new FileReader(whitelistFile);
BufferedReader br = new BufferedReader(inFile);
whitelist = new HashSet<String>();
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
whitelist.add(line);
}
}
if (whitelist.isEmpty()) {
whitelist = null;
}
}
++i;
if (prepare) {
// only prepare the import to Scalaris, i.e. pre-process K/V pairs?
String dbFileName = "";
if (args.length > i && !args[i].isEmpty()) {
dbFileName = args[i];
} else {
System.err.println("need a DB file name for prepare; arguments given: " + Arrays.toString(args));
System.exit(-1);
}
++i;
WikiDumpHandler.println(System.out, "wiki prepare file " + dbFileName);
WikiDumpHandler.println(System.out, " wiki dump : " + filename);
WikiDumpHandler.println(System.out, " white list : " + whitelistFile);
WikiDumpHandler.println(System.out, " max revisions : " + maxRevisions);
WikiDumpHandler.println(System.out, " min time : " + (minTime == null ? "null" : minTime.toString()));
WikiDumpHandler.println(System.out, " max time : " + (maxTime == null ? "null" : maxTime.toString()));
WikiDumpHandler handler = new WikiDumpPrepareSQLiteForScalarisHandler(
blacklist, whitelist, maxRevisions, minTime, maxTime,
dbFileName);
InputSource file = getFileReader(filename);
runXmlHandler(handler, file);
} else {
if (filename.endsWith(".db")) {
WikiDumpHandler.println(System.out, "wiki import from " + filename);
WikiDumpPreparedSQLiteToScalaris handler =
new WikiDumpPreparedSQLiteToScalaris(filename);
handler.setUp();
WikiDumpPreparedSQLiteToScalaris.ReportAtShutDown shutdownHook = handler.new ReportAtShutDown();
Runtime.getRuntime().addShutdownHook(shutdownHook);
handler.writeToScalaris();
handler.tearDown();
shutdownHook.run();
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} else {
WikiDumpHandler.println(System.out, "wiki import from " + filename);
WikiDumpHandler.println(System.out, " white list : " + whitelistFile);
WikiDumpHandler.println(System.out, " max revisions : " + maxRevisions);
WikiDumpHandler.println(System.out, " min time : " + minTime);
WikiDumpHandler.println(System.out, " max time : " + maxTime);
WikiDumpHandler handler = new WikiDumpToScalarisHandler(
blacklist, whitelist, maxRevisions, minTime, maxTime);
InputSource file = getFileReader(filename);
runXmlHandler(handler, file);
}
}
}
/**
* @param handler
* @param file
* @throws SAXException
* @throws IOException
*/
static void runXmlHandler(WikiDumpHandler handler, InputSource file)
throws SAXException, IOException {
XMLReader reader = XMLReaderFactory.createXMLReader();
handler.setUp();
ReportAtShutDown shutdownHook = handler.new ReportAtShutDown();
Runtime.getRuntime().addShutdownHook(shutdownHook);
reader.setContentHandler(handler);
reader.parse(file);
handler.tearDown();
shutdownHook.run();
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
/**
* Filters all pages in the Wikipedia XML dump from the given file and
* creates a list of page names belonging to certain categories.
*
* @param filename
* @param args
*
* @throws RuntimeException
* @throws IOException
* @throws SAXException
* @throws FileNotFoundException
*/
private static void doFilter(String filename, String[] args) throws RuntimeException, IOException,
SAXException, FileNotFoundException {
int i = 0;
int recursionLvl = 1;
if (args.length > i) {
try {
recursionLvl = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {
System.err.println("no number: " + args[i]);
System.exit(-1);
}
}
++i;
// a timestamp in ISO8601 format
Calendar maxTime = null;
if (args.length > i && !args[i].isEmpty()) {
try {
maxTime = Revision.stringToCalendar(args[i]);
} catch (IllegalArgumentException e) {
System.err.println("no date in ISO8601: " + args[i]);
System.exit(-1);
}
}
++i;
String pageListFileName = "";
if (args.length > i && !args[i].isEmpty()) {
pageListFileName = args[i];
} else {
System.err.println("need a pagelist file name for filter; arguments given: " + Arrays.toString(args));
System.exit(-1);
}
++i;
Set<String> allowedPages = new HashSet<String>();
allowedPages.add("Main Page");
allowedPages.add("MediaWiki:Noarticletext");
String allowedPagesFileName = "";
if (args.length > i && !args[i].isEmpty()) {
allowedPagesFileName = args[i];
FileReader inFile = new FileReader(allowedPagesFileName);
BufferedReader br = new BufferedReader(inFile);
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
allowedPages.add(line);
}
}
}
++i;
LinkedList<String> rootCategories = new LinkedList<String>();
if (args.length > i) {
for (String rCat : Arrays.asList(args).subList(i, args.length)) {
if (!rCat.isEmpty()) {
rootCategories.add(rCat);
}
}
}
WikiDumpHandler.println(System.out, "filtering by categories " + rootCategories.toString() + " ...");
WikiDumpHandler.println(System.out, " wiki dump : " + filename);
WikiDumpHandler.println(System.out, " max time : " + maxTime);
WikiDumpHandler.println(System.out, " allowed pages : " + allowedPagesFileName);
WikiDumpHandler.println(System.out, " recursion lvl : " + recursionLvl);
SortedSet<String> pages = getPageList(filename, maxTime, allowedPages,
rootCategories, recursionLvl);
do {
FileWriter outFile = new FileWriter(pageListFileName);
PrintWriter out = new PrintWriter(outFile);
for (String page : pages) {
out.println(page);
}
out.close();
} while(false);
}
/**
* Extracts all allowed pages in the given root categories as well as those
* pages explicitly mentioned in a list of allowed pages.
*
* Gets the category and template trees from a file, i.e.
* <tt>filename + "-trees.db"</tt>, or if this does not exist, builds the
* trees and stores them to this file.
*
* @param filename
* the name of the xml wiki dump file
* @param maxTime
* the maximum time of a revision to use for category parsing
* @param allowedPages
* all allowed pages (un-normalised page titles)
* @param rootCategories
* all allowed categories (un-normalised page titles)
* @param recursionLvl
* recursion level to include pages linking to
*
* @return a set of (de-normalised) page titles
*
* @throws RuntimeException
* @throws FileNotFoundException
* @throws IOException
* @throws SAXException
*/
protected static SortedSet<String> getPageList(String filename, Calendar maxTime,
Set<String> allowedPages, LinkedList<String> rootCategories,
int recursionLvl) throws RuntimeException, FileNotFoundException,
IOException, SAXException {
Map<String, Set<String>> templateTree = new HashMap<String, Set<String>>();
Map<String, Set<String>> includeTree = new HashMap<String, Set<String>>();
Map<String, Set<String>> referenceTree = new HashMap<String, Set<String>>();
File trees = new File(filename + "-trees.db");
if (trees.exists()) {
// read trees from tree file
WikiDumpHandler.println(System.out, "reading category tree from " + trees.getAbsolutePath() + " ...");
WikiDumpGetCategoryTreeHandler.readTrees(trees.getAbsolutePath(),
templateTree, includeTree, referenceTree);
} else {
// build trees from xml file
// need to get all subcategories recursively, as they must be
// included as well
WikiDumpHandler.println(System.out, "building category tree from " + filename + " ...");
WikiDumpGetCategoryTreeHandler handler = new WikiDumpGetCategoryTreeHandler(
blacklist, null, maxTime, trees.getPath());
InputSource file = getFileReader(filename);
runXmlHandler(handler, file);
WikiDumpGetCategoryTreeHandler.readTrees(trees.getAbsolutePath(),
templateTree, includeTree, referenceTree);
}
WikiDumpHandler.println(System.out, "creating list of pages to import (recursion level: " + recursionLvl + ") ...");
Set<String> allowedCats = new HashSet<String>(rootCategories);
return WikiDumpGetCategoryTreeHandler.getPagesInCategories(
trees.getAbsolutePath(), allowedCats, allowedPages, recursionLvl,
templateTree, includeTree, referenceTree, System.out, false);
}
/**
* Gets an appropriate file reader for the given file.
*
* @param filename
* the name of the file
*
* @return a file reader
*
* @throws FileNotFoundException
* @throws IOException
*/
public static InputSource getFileReader(String filename) throws FileNotFoundException, IOException {
InputStream is;
if (filename.endsWith(".xml.gz")) {
is = new GZIPInputStream(new FileInputStream(filename));
} else if (filename.endsWith(".xml.bz2")) {
is = new BZip2CompressorInputStream(new FileInputStream(filename));
} else if (filename.endsWith(".xml")) {
is = new FileInputStream(filename);
} else {
System.err.println("Unsupported file: " + filename + ". Supported: *.xml.gz, *.xml.bz2, *.xml");
System.exit(-1);
return null; // will never be reached but is necessary to keep javac happy
}
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
return new InputSource(br);
}
}
| contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/Main.java | /**
* Copyright 2007-2011 Zuse Institute Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.zib.scalaris.examples.wikipedia.data.xml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import de.zib.scalaris.examples.wikipedia.data.Revision;
import de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler.ReportAtShutDown;
/**
* Provides abilities to read an xml wiki dump file and write Wiki pages to
* Scalaris.
*
* @author Nico Kruber, [email protected]
*/
public class Main {
/**
* Default blacklist - pages with these names are not imported
*/
public final static Set<String> blacklist = new HashSet<String>();
/**
* The main function of the application. Some articles are blacklisted and
* will not be processed (see implementation for a list of them).
*
* @param args
* first argument should be the xml file to convert.
*/
public static void main(String[] args) {
try {
String filename = args[0];
if (args.length > 1) {
if (args[1].equals("filter")) {
doFilter(filename, Arrays.copyOfRange(args, 2, args.length));
} else if (args[1].equals("import")) {
doImport(filename, Arrays.copyOfRange(args, 2, args.length), false);
} else if (args[1].equals("prepare")) {
doImport(filename, Arrays.copyOfRange(args, 2, args.length), true);
}
}
} catch (SAXException e) {
System.err.println(e.getMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Imports all pages in the Wikipedia XML dump from the given file to Scalaris.
*
* @param filename
* @param args
* @param prepare
*
* @throws RuntimeException
* @throws IOException
* @throws SAXException
* @throws FileNotFoundException
*/
private static void doImport(String filename, String[] args, boolean prepare) throws RuntimeException, IOException,
SAXException, FileNotFoundException {
int i = 0;
int maxRevisions = -1;
if (args.length > i) {
try {
maxRevisions = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {
System.err.println("no number: " + args[i]);
System.exit(-1);
}
}
++i;
// a timestamp in ISO8601 format
Calendar minTime = null;
if (args.length > i && !args[i].isEmpty()) {
try {
minTime = Revision.stringToCalendar(args[i]);
} catch (IllegalArgumentException e) {
System.err.println("no date in ISO8601: " + args[i]);
System.exit(-1);
}
}
++i;
// a timestamp in ISO8601 format
Calendar maxTime = null;
if (args.length > i && !args[i].isEmpty()) {
try {
maxTime = Revision.stringToCalendar(args[i]);
} catch (IllegalArgumentException e) {
System.err.println("no date in ISO8601: " + args[i]);
System.exit(-1);
}
}
++i;
Set<String> whitelist = null;
String whitelistFile = "";
if (args.length > i && !args[i].isEmpty()) {
whitelistFile = args[i];
FileReader inFile = new FileReader(whitelistFile);
BufferedReader br = new BufferedReader(inFile);
whitelist = new HashSet<String>();
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
whitelist.add(line);
}
}
if (whitelist.isEmpty()) {
whitelist = null;
}
}
++i;
if (prepare) {
// only prepare the import to Scalaris, i.e. pre-process K/V pairs?
String dbFileName = "";
if (args.length > i && !args[i].isEmpty()) {
dbFileName = args[i];
} else {
System.err.println("need a DB file name for prepare; arguments given: " + Arrays.toString(args));
System.exit(-1);
}
++i;
WikiDumpHandler.println(System.out, "wiki prepare file " + dbFileName);
WikiDumpHandler.println(System.out, " wiki dump : " + filename);
WikiDumpHandler.println(System.out, " white list : " + whitelistFile);
WikiDumpHandler.println(System.out, " max revisions : " + maxRevisions);
WikiDumpHandler.println(System.out, " min time : " + minTime);
WikiDumpHandler.println(System.out, " max time : " + maxTime);
WikiDumpHandler handler = new WikiDumpPrepareSQLiteForScalarisHandler(
blacklist, whitelist, maxRevisions, minTime, maxTime,
dbFileName);
InputSource file = getFileReader(filename);
runXmlHandler(handler, file);
} else {
if (filename.endsWith(".db")) {
WikiDumpHandler.println(System.out, "wiki import from " + filename);
WikiDumpPreparedSQLiteToScalaris handler =
new WikiDumpPreparedSQLiteToScalaris(filename);
handler.setUp();
WikiDumpPreparedSQLiteToScalaris.ReportAtShutDown shutdownHook = handler.new ReportAtShutDown();
Runtime.getRuntime().addShutdownHook(shutdownHook);
handler.writeToScalaris();
handler.tearDown();
shutdownHook.run();
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} else {
WikiDumpHandler.println(System.out, "wiki import from " + filename);
WikiDumpHandler.println(System.out, " white list : " + whitelistFile);
WikiDumpHandler.println(System.out, " max revisions : " + maxRevisions);
WikiDumpHandler.println(System.out, " min time : " + minTime);
WikiDumpHandler.println(System.out, " max time : " + maxTime);
WikiDumpHandler handler = new WikiDumpToScalarisHandler(
blacklist, whitelist, maxRevisions, minTime, maxTime);
InputSource file = getFileReader(filename);
runXmlHandler(handler, file);
}
}
}
/**
* @param handler
* @param file
* @throws SAXException
* @throws IOException
*/
static void runXmlHandler(WikiDumpHandler handler, InputSource file)
throws SAXException, IOException {
XMLReader reader = XMLReaderFactory.createXMLReader();
handler.setUp();
ReportAtShutDown shutdownHook = handler.new ReportAtShutDown();
Runtime.getRuntime().addShutdownHook(shutdownHook);
reader.setContentHandler(handler);
reader.parse(file);
handler.tearDown();
shutdownHook.run();
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
/**
* Filters all pages in the Wikipedia XML dump from the given file and
* creates a list of page names belonging to certain categories.
*
* @param filename
* @param args
*
* @throws RuntimeException
* @throws IOException
* @throws SAXException
* @throws FileNotFoundException
*/
private static void doFilter(String filename, String[] args) throws RuntimeException, IOException,
SAXException, FileNotFoundException {
int i = 0;
int recursionLvl = 1;
if (args.length > i) {
try {
recursionLvl = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {
System.err.println("no number: " + args[i]);
System.exit(-1);
}
}
++i;
// a timestamp in ISO8601 format
Calendar maxTime = null;
if (args.length > i && !args[i].isEmpty()) {
try {
maxTime = Revision.stringToCalendar(args[i]);
} catch (IllegalArgumentException e) {
System.err.println("no date in ISO8601: " + args[i]);
System.exit(-1);
}
}
++i;
String pageListFileName = "";
if (args.length > i && !args[i].isEmpty()) {
pageListFileName = args[i];
} else {
System.err.println("need a pagelist file name for filter; arguments given: " + Arrays.toString(args));
System.exit(-1);
}
++i;
Set<String> allowedPages = new HashSet<String>();
allowedPages.add("Main Page");
allowedPages.add("MediaWiki:Noarticletext");
String allowedPagesFileName = "";
if (args.length > i && !args[i].isEmpty()) {
allowedPagesFileName = args[i];
FileReader inFile = new FileReader(allowedPagesFileName);
BufferedReader br = new BufferedReader(inFile);
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
allowedPages.add(line);
}
}
}
++i;
LinkedList<String> rootCategories = new LinkedList<String>();
if (args.length > i) {
for (String rCat : Arrays.asList(args).subList(i, args.length)) {
if (!rCat.isEmpty()) {
rootCategories.add(rCat);
}
}
}
WikiDumpHandler.println(System.out, "filtering by categories " + rootCategories.toString() + " ...");
WikiDumpHandler.println(System.out, " wiki dump : " + filename);
WikiDumpHandler.println(System.out, " max time : " + maxTime);
WikiDumpHandler.println(System.out, " allowed pages : " + allowedPagesFileName);
WikiDumpHandler.println(System.out, " recursion lvl : " + recursionLvl);
SortedSet<String> pages = getPageList(filename, maxTime, allowedPages,
rootCategories, recursionLvl);
do {
FileWriter outFile = new FileWriter(pageListFileName);
PrintWriter out = new PrintWriter(outFile);
for (String page : pages) {
out.println(page);
}
out.close();
} while(false);
}
/**
* Extracts all allowed pages in the given root categories as well as those
* pages explicitly mentioned in a list of allowed pages.
*
* Gets the category and template trees from a file, i.e.
* <tt>filename + "-trees.db"</tt>, or if this does not exist, builds the
* trees and stores them to this file.
*
* @param filename
* the name of the xml wiki dump file
* @param maxTime
* the maximum time of a revision to use for category parsing
* @param allowedPages
* all allowed pages (un-normalised page titles)
* @param rootCategories
* all allowed categories (un-normalised page titles)
* @param recursionLvl
* recursion level to include pages linking to
*
* @return a set of (de-normalised) page titles
*
* @throws RuntimeException
* @throws FileNotFoundException
* @throws IOException
* @throws SAXException
*/
protected static SortedSet<String> getPageList(String filename, Calendar maxTime,
Set<String> allowedPages, LinkedList<String> rootCategories,
int recursionLvl) throws RuntimeException, FileNotFoundException,
IOException, SAXException {
Map<String, Set<String>> templateTree = new HashMap<String, Set<String>>();
Map<String, Set<String>> includeTree = new HashMap<String, Set<String>>();
Map<String, Set<String>> referenceTree = new HashMap<String, Set<String>>();
File trees = new File(filename + "-trees.db");
if (trees.exists()) {
// read trees from tree file
WikiDumpHandler.println(System.out, "reading category tree from " + trees.getAbsolutePath() + " ...");
WikiDumpGetCategoryTreeHandler.readTrees(trees.getAbsolutePath(),
templateTree, includeTree, referenceTree);
} else {
// build trees from xml file
// need to get all subcategories recursively, as they must be
// included as well
WikiDumpHandler.println(System.out, "building category tree from " + filename + " ...");
WikiDumpGetCategoryTreeHandler handler = new WikiDumpGetCategoryTreeHandler(
blacklist, null, maxTime, trees.getPath());
InputSource file = getFileReader(filename);
runXmlHandler(handler, file);
WikiDumpGetCategoryTreeHandler.readTrees(trees.getAbsolutePath(),
templateTree, includeTree, referenceTree);
}
WikiDumpHandler.println(System.out, "creating list of pages to import (recursion level: " + recursionLvl + ") ...");
Set<String> allowedCats = new HashSet<String>(rootCategories);
return WikiDumpGetCategoryTreeHandler.getPagesInCategories(
trees.getAbsolutePath(), allowedCats, allowedPages, recursionLvl,
templateTree, includeTree, referenceTree, System.out, false);
}
/**
* Gets an appropriate file reader for the given file.
*
* @param filename
* the name of the file
*
* @return a file reader
*
* @throws FileNotFoundException
* @throws IOException
*/
public static InputSource getFileReader(String filename) throws FileNotFoundException, IOException {
InputStream is;
if (filename.endsWith(".xml.gz")) {
is = new GZIPInputStream(new FileInputStream(filename));
} else if (filename.endsWith(".xml.bz2")) {
is = new BZip2CompressorInputStream(new FileInputStream(filename));
} else if (filename.endsWith(".xml")) {
is = new FileInputStream(filename);
} else {
System.err.println("Unsupported file: " + filename + ". Supported: *.xml.gz, *.xml.bz2, *.xml");
System.exit(-1);
return null; // will never be reached but is necessary to keep javac happy
}
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
return new InputSource(br);
}
}
| - Wiki on Scalaris: fixed debug output of minTime and maxTime | contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/Main.java | - Wiki on Scalaris: fixed debug output of minTime and maxTime | <ide><path>ontrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/Main.java
<ide> WikiDumpHandler.println(System.out, " wiki dump : " + filename);
<ide> WikiDumpHandler.println(System.out, " white list : " + whitelistFile);
<ide> WikiDumpHandler.println(System.out, " max revisions : " + maxRevisions);
<del> WikiDumpHandler.println(System.out, " min time : " + minTime);
<del> WikiDumpHandler.println(System.out, " max time : " + maxTime);
<add> WikiDumpHandler.println(System.out, " min time : " + (minTime == null ? "null" : minTime.toString()));
<add> WikiDumpHandler.println(System.out, " max time : " + (maxTime == null ? "null" : maxTime.toString()));
<ide> WikiDumpHandler handler = new WikiDumpPrepareSQLiteForScalarisHandler(
<ide> blacklist, whitelist, maxRevisions, minTime, maxTime,
<ide> dbFileName); |
|
JavaScript | mit | af0f3e22937b0c284b17e238ac055afd9a31819b | 0 | webgme/webgme,webgme/webgme,webgme/webgme | /*globals define, _, WebGMEGlobal*/
/*jshint browser: true */
/**
* @author rkereskenyi / https://github.com/rkereskenyi
*/
define(['js/logger',
'js/util',
'js/Constants',
'js/Utils/GMEConcepts',
'js/NodePropertyNames',
'js/RegistryKeys',
'js/Widgets/DiagramDesigner/DiagramDesignerWidget.Constants',
'./MetaEditorControl.DiagramDesignerWidgetEventHandlers',
'./MetaRelations',
'./MetaEditorConstants',
'js/Utils/PreferencesHelper',
'js/Controls/AlignMenu'
], function (Logger,
util,
CONSTANTS,
GMEConcepts,
nodePropertyNames,
REGISTRY_KEYS,
DiagramDesignerWidgetConstants,
MetaEditorControlDiagramDesignerWidgetEventHandlers,
MetaRelations,
MetaEditorConstants,
PreferencesHelper,
AlignMenu) {
'use strict';
var MetaEditorControl,
META_DECORATOR = 'MetaDecorator',
WIDGET_NAME = 'DiagramDesigner',
META_RULES_CONTAINER_NODE_ID = MetaEditorConstants.META_ASPECT_CONTAINER_ID;
MetaEditorControl = function (options) {
var self = this;
this.logger = options.logger || Logger.create(options.loggerName || 'gme:Panels:MetaEditor:MetaEditorControl',
WebGMEGlobal.gmeConfig.client.log);
this._client = options.client;
//initialize core collections and variables
this.diagramDesigner = options.widget;
this._alignMenu = new AlignMenu(this.diagramDesigner.CONSTANTS, {});
if (this._client === undefined) {
this.logger.error('MetaEditorControl\'s client is not specified...');
throw ('MetaEditorControl can not be created');
}
if (this.diagramDesigner === undefined) {
this.logger.error('MetaEditorControl\'s DiagramDesigner is not specified...');
throw ('MetaEditorControl can not be created');
}
//in METAEDITOR mode DRAG & COPY is not enabled
this.diagramDesigner.enableDragCopy(false);
this._metaAspectMemberPatterns = {};
this._filteredOutConnTypes = [];
this._filteredOutConnectionDescriptors = {};
//local variable holding info about the currently opened node
this.currentNodeInfo = {id: null, members: []};
this._metaAspectMembersAll = [];
this._metaAspectMembersPerSheet = {};
this._metaAspectMembersCoordinatesGlobal = {};
this._metaAspectMembersCoordinatesPerSheet = {};
this._selectedMetaAspectSheetMembers = [];
this._selectedSheetID = null;
//set default connection type to containment
this._setNewConnectionType(MetaRelations.META_RELATIONS.CONTAINMENT);
this._initFilterPanel();
//attach all the event handlers for event's coming from DiagramDesigner
this.attachDiagramDesignerWidgetEventHandlers();
//let the decorator-manager download the required decorator
this._client.decoratorManager.download([META_DECORATOR], WIDGET_NAME, function () {
self.logger.debug('MetaEditorControl ctor finished');
//load meta container node
//give the UI time to render first before start using it's features
setTimeout(function () {
self._loadMetaAspectContainerNode();
}, 10);
});
};
MetaEditorControl.prototype._loadMetaAspectContainerNode = function () {
var self = this;
this.metaAspectContainerNodeID = META_RULES_CONTAINER_NODE_ID;
this.logger.debug('_loadMetaAspectContainerNode: "' + this.metaAspectContainerNodeID + '"');
this._initializeSelectedSheet();
//remove current territory patterns
if (this._territoryId) {
this._client.removeUI(this._territoryId);
}
//put new node's info into territory rules
this._selfPatterns = {};
this._selfPatterns[this.metaAspectContainerNodeID] = {children: 0};
//create and set territory
this._territoryId = this._client.addUI(this, function (events) {
self._eventCallback(events);
});
this._client.updateTerritory(this._territoryId, this._selfPatterns);
};
/**********************************************************/
/* PUBLIC METHODS */
/**********************************************************/
MetaEditorControl.prototype._eventCallback = function (events) {
var i = events ? events.length : 0,
e;
this.logger.debug('_eventCallback "' + i + '" items');
this.diagramDesigner.beginUpdate();
while (i--) {
e = events[i];
switch (e.etype) {
case CONSTANTS.TERRITORY_EVENT_LOAD:
this._onLoad(e.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UPDATE:
this._onUpdate(e.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UNLOAD:
this._onUnload(e.eid);
break;
default:
break;
}
}
this.diagramDesigner.endUpdate();
this.diagramDesigner.hideProgressbar();
this.logger.debug('_eventCallback "' + events.length + '" items - DONE');
};
//might not be the best approach
MetaEditorControl.prototype.destroy = function () {
this._detachClientEventListeners();
this._client.removeUI(this._territoryId);
this._client.removeUI(this._metaAspectMembersTerritoryId);
this.diagramDesigner.clear();
};
/**********************************************************/
/* LOAD / UPDATE / UNLOAD HANDLER */
/**********************************************************/
MetaEditorControl.prototype._onLoad = function (gmeID) {
if (gmeID === this.metaAspectContainerNodeID) {
this._processMetaAspectContainerNode();
} else {
this._processNodeLoad(gmeID);
}
};
MetaEditorControl.prototype._onUpdate = function (gmeID) {
if (gmeID === this.metaAspectContainerNodeID) {
this._processMetaAspectContainerNode();
} else {
this._processNodeUpdate(gmeID);
}
};
MetaEditorControl.prototype._onUnload = function (gmeID) {
var self = this;
if (gmeID === this.metaAspectContainerNodeID) {
//the opened model has been deleted....
//most probably a project / branch / whatever change
this.logger.debug('The currently opened aspect has been deleted --- GMEID: "' +
this.metaAspectContainerNodeID + '"');
setTimeout(function () {
self._loadMetaAspectContainerNode();
}, 10);
} else {
this._processNodeUnload(gmeID);
}
};
/**********************************************************/
/* END OF --- LOAD / UPDATE / UNLOAD HANDLER */
/**********************************************************/
/**********************************************************/
/* CUSTOM BUTTON EVENT HANDLERS */
/**********************************************************/
MetaEditorControl.prototype._printNodeData = function () {
//TODO could be filled with meaningful info
};
/**********************************************************/
/* END OF --- CUSTOM BUTTON EVENT HANDLERS */
/**********************************************************/
/***********************************************************/
/* PROCESS CURRENT NODE TO HANDLE ADDED / REMOVED ELEMENT */
/***********************************************************/
MetaEditorControl.prototype._processMetaAspectContainerNode = function () {
var aspectNodeID = this.metaAspectContainerNodeID,
aspectNode = this._client.getNode(aspectNodeID),
len,
diff,
objDesc,
componentID,
gmeID,
metaAspectSetMembers = aspectNode.getMemberIds(MetaEditorConstants.META_ASPECT_SET_NAME),
territoryChanged = false,
selectedSheetMembers,
positionsUpdated;
//this._metaAspectMembersAll contains all the currently known members of the meta aspect
//update current member list
this._metaAspectMembersAll = metaAspectSetMembers.slice(0);
len = this._metaAspectMembersAll.length;
this._metaAspectMembersCoordinatesGlobal = {};
while (len--) {
gmeID = this._metaAspectMembersAll[len];
this._metaAspectMembersCoordinatesGlobal[gmeID] = aspectNode.getMemberRegistry(
MetaEditorConstants.META_ASPECT_SET_NAME,
gmeID,
REGISTRY_KEYS.POSITION);
}
//setSelected sheet
//this._selectedMetaAspectSet
//process the sheets
positionsUpdated = this._processMetaAspectSheetsRegistry();
this.logger.debug('_metaAspectMembersAll: \n' + JSON.stringify(this._metaAspectMembersAll));
this.logger.debug('_metaAspectMembersCoordinatesGlobal: \n' +
JSON.stringify(this._metaAspectMembersCoordinatesGlobal));
this.logger.debug('_metaAspectMembersPerSheet: \n' + JSON.stringify(this._metaAspectMembersPerSheet));
this.logger.debug('_metaAspectMembersCoordinatesPerSheet: \n' +
JSON.stringify(this._metaAspectMembersCoordinatesPerSheet));
//check to see if the territory needs to be changed
//the territory contains the nodes that are on the currently opened sheet
//this._selectedMetaAspectSheetMembers
selectedSheetMembers = this._metaAspectMembersPerSheet[this._selectedMetaAspectSet] || [];
//check deleted nodes
diff = _.difference(this._selectedMetaAspectSheetMembers, selectedSheetMembers);
len = diff.length;
while (len--) {
delete this._metaAspectMemberPatterns[diff[len]];
territoryChanged = true;
}
//check added nodes
diff = _.difference(selectedSheetMembers, this._selectedMetaAspectSheetMembers);
len = diff.length;
while (len--) {
this._metaAspectMemberPatterns[diff[len]] = {children: 0};
territoryChanged = true;
}
//check all other nodes for position change
//or any other change that could have happened (local registry modifications)
//diff = positionsUpdated;//_.intersection(this._selectedMetaAspectSheetMembers, selectedSheetMembers);
diff = _.intersection(this._selectedMetaAspectSheetMembers, selectedSheetMembers);
len = diff.length;
while (len--) {
gmeID = diff[len];
objDesc = {position: {x: 100, y: 100}};
if (this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID]) {
objDesc.position.x = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].x;
objDesc.position.y = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].y;
}
if (this._GMEID2ComponentID.hasOwnProperty(gmeID)) {
componentID = this._GMEID2ComponentID[gmeID];
this.diagramDesigner.updateDesignerItem(componentID, objDesc);
}
}
this._selectedMetaAspectSheetMembers = selectedSheetMembers.slice(0);
//there was change in the territory
if (territoryChanged === true) {
this._client.updateTerritory(this._metaAspectMembersTerritoryId, this._metaAspectMemberPatterns);
}
};
/**********************************************************************/
/* END OF --- PROCESS CURRENT NODE TO HANDLE ADDED / REMOVED ELEMENT */
/**********************************************************************/
/**************************************************************************/
/* HANDLE OBJECT LOAD --- DISPLAY IT WITH ALL THE POINTERS / SETS / ETC */
/**************************************************************************/
MetaEditorControl.prototype._processNodeLoad = function (gmeID) {
var uiComponent,
decClass,
objDesc;
//component loaded
if (this._GMENodes.indexOf(gmeID) === -1) {
//aspect's member has been loaded
objDesc = {position: {x: 100, y: 100}};
if (this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID]) {
objDesc.position.x = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].x;
objDesc.position.y = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].y;
}
decClass = this._client.decoratorManager.getDecoratorForWidget(META_DECORATOR, WIDGET_NAME);
objDesc.decoratorClass = decClass;
objDesc.control = this;
objDesc.metaInfo = {};
objDesc.metaInfo[CONSTANTS.GME_ID] = gmeID;
//each meta specific registry customization will be stored in the MetaContainer node's main META SET
// (MetaEditorConstants.META_ASPECT_SET_NAME)
objDesc.preferencesHelper = PreferencesHelper.getPreferences([{
containerID: this.metaAspectContainerNodeID,
setID: MetaEditorConstants.META_ASPECT_SET_NAME
}]);
uiComponent = this.diagramDesigner.createDesignerItem(objDesc);
this._GMENodes.push(gmeID);
this._GMEID2ComponentID[gmeID] = uiComponent.id;
this._ComponentID2GMEID[uiComponent.id] = gmeID;
//process new node to display containment / pointers / inheritance / sets as connections
this._processNodeMetaContainment(gmeID);
this._processNodeMetaPointers(gmeID, false);
this._processNodeMetaInheritance(gmeID);
this._processNodeMixins(gmeID);
this._processNodeMetaPointers(gmeID, true);
//check all the waiting pointers (whose SRC/DST is already displayed and waiting for the DST/SRC to show up)
//it might be this new node
this._processConnectionWaitingList(gmeID);
}
};
MetaEditorControl.prototype._processConnectionWaitingList = function (gmeID) {
var len,
gmeSrcID,
gmeDstID,
connType,
connTexts,
c = [];
//check for possible endpoint as gmeID
gmeDstID = gmeID;
if (this._connectionWaitingListByDstGMEID && this._connectionWaitingListByDstGMEID.hasOwnProperty(gmeDstID)) {
for (gmeSrcID in this._connectionWaitingListByDstGMEID[gmeDstID]) {
if (this._connectionWaitingListByDstGMEID[gmeDstID].hasOwnProperty(gmeSrcID)) {
len = this._connectionWaitingListByDstGMEID[gmeDstID][gmeSrcID].length;
while (len--) {
connType = this._connectionWaitingListByDstGMEID[gmeDstID][gmeSrcID][len][0];
connTexts = this._connectionWaitingListByDstGMEID[gmeDstID][gmeSrcID][len][1];
c.push({
gmeSrcID: gmeSrcID,
gmeDstID: gmeDstID,
connType: connType,
connTexts: connTexts
});
}
}
}
delete this._connectionWaitingListByDstGMEID[gmeDstID];
}
//check for possible source as gmeID
gmeSrcID = gmeID;
if (this._connectionWaitingListBySrcGMEID && this._connectionWaitingListBySrcGMEID.hasOwnProperty(gmeSrcID)) {
for (gmeDstID in this._connectionWaitingListBySrcGMEID[gmeSrcID]) {
if (this._connectionWaitingListBySrcGMEID[gmeSrcID].hasOwnProperty(gmeDstID)) {
len = this._connectionWaitingListBySrcGMEID[gmeSrcID][gmeDstID].length;
while (len--) {
connType = this._connectionWaitingListBySrcGMEID[gmeSrcID][gmeDstID][len][0];
connTexts = this._connectionWaitingListBySrcGMEID[gmeSrcID][gmeDstID][len][1];
c.push({
gmeSrcID: gmeSrcID,
gmeDstID: gmeDstID,
connType: connType,
connTexts: connTexts
});
}
}
}
delete this._connectionWaitingListBySrcGMEID[gmeSrcID];
}
len = c.length;
while (len--) {
gmeSrcID = c[len].gmeSrcID;
gmeDstID = c[len].gmeDstID;
connType = c[len].connType;
connTexts = c[len].connTexts;
this._createConnection(gmeSrcID, gmeDstID, connType, connTexts);
}
};
/**************************************************************************/
/* END OF --- HANDLE OBJECT LOAD DISPLAY IT WITH ALL THE POINTERS / ... */
/**************************************************************************/
/****************************************************************************/
/* HANDLE OBJECT UNLOAD --- DISPLAY IT WITH ALL THE POINTERS / SETS / ETC */
/****************************************************************************/
MetaEditorControl.prototype._processNodeUnload = function (gmeID) {
var componentID,
idx,
len,
i,
otherEnd,
pointerName,
aConns,
connectionID;
if (this._GMEID2ComponentID.hasOwnProperty(gmeID)) {
componentID = this._GMEID2ComponentID[gmeID];
//gather all the information that is stored in this node's META
//CONTAINMENT
len = this._nodeMetaContainment[gmeID].targets.length;
while (len--) {
otherEnd = this._nodeMetaContainment[gmeID].targets[len];
this._removeConnection(gmeID, otherEnd, MetaRelations.META_RELATIONS.CONTAINMENT);
}
//POINTERS
len = this._nodeMetaPointers[gmeID].combinedNames.length;
while (len--) {
pointerName = this._nodeMetaPointers[gmeID].combinedNames[len];
otherEnd = this._nodeMetaPointers[gmeID][pointerName].target;
pointerName = this._nodeMetaPointers[gmeID][pointerName].name;
this._removeConnection(gmeID, otherEnd, MetaRelations.META_RELATIONS.POINTER, pointerName);
}
//INHERITANCE
if (this._nodeMetaInheritance[gmeID] && !_.isEmpty(this._nodeMetaInheritance[gmeID])) {
this._removeConnection(this._nodeMetaInheritance[gmeID],
gmeID,
MetaRelations.META_RELATIONS.INHERITANCE);
}
//MIXINS
for (i = 0; i < this._nodeMixins[gmeID].length; i += 1) {
this._removeConnection(gmeID, this._nodeMixins[gmeID][i], MetaRelations.META_RELATIONS.MIXIN);
}
//POINTER LISTS
len = this._nodeMetaSets[gmeID].combinedNames.length;
while (len--) {
pointerName = this._nodeMetaSets[gmeID].combinedNames[len];
otherEnd = this._nodeMetaSets[gmeID][pointerName].target;
pointerName = this._nodeMetaSets[gmeID][pointerName].name;
this._removeConnection(gmeID, otherEnd, MetaRelations.META_RELATIONS.SET, pointerName);
}
//finally delete the guy from the screen
this.diagramDesigner.deleteComponent(componentID);
delete this._ComponentID2GMEID[componentID];
delete this._GMEID2ComponentID[gmeID];
idx = this._GMENodes.indexOf(gmeID);
this._GMENodes.splice(idx, 1);
//check if there is any more connection present that's associated with this object
//typically the connection end is this guy
//if so, remove but save to savedList
aConns = this._getAssociatedConnections(gmeID);
len = aConns.src.length;
while (len--) {
connectionID = aConns.src[len];
//save the connection to the waiting list, since the destination is still there
this._saveConnectionToWaitingList(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type,
this._connectionListByID[connectionID].connTexts);
this._removeConnection(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type);
}
len = aConns.dst.length;
while (len--) {
connectionID = aConns.dst[len];
if (this._connectionListByID[connectionID]) {
//save the connection to the waiting list, since the destination is still there
this._saveConnectionToWaitingList(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type,
this._connectionListByID[connectionID].connTexts);
this._removeConnection(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type);
}
}
//check the waiting list and remove any connection that was waiting and this end was present
for (otherEnd in this._connectionWaitingListBySrcGMEID) {
if (this._connectionWaitingListBySrcGMEID.hasOwnProperty(otherEnd)) {
delete this._connectionWaitingListBySrcGMEID[otherEnd][gmeID];
if (_.isEmpty(this._connectionWaitingListBySrcGMEID[otherEnd])) {
delete this._connectionWaitingListBySrcGMEID[otherEnd];
}
}
}
for (otherEnd in this._connectionWaitingListByDstGMEID) {
if (this._connectionWaitingListByDstGMEID.hasOwnProperty(otherEnd)) {
delete this._connectionWaitingListByDstGMEID[otherEnd][gmeID];
if (_.isEmpty(this._connectionWaitingListByDstGMEID[otherEnd])) {
delete this._connectionWaitingListByDstGMEID[otherEnd];
}
}
}
//keep up accounting
delete this._nodeMetaContainment[gmeID];
delete this._nodeMetaPointers[gmeID];
delete this._nodeMetaInheritance[gmeID];
delete this._nodeMixins[gmeID];
delete this._nodeMetaSets[gmeID];
}
};
/****************************************************************************/
/* END OF --- HANDLE OBJECT UNLOAD */
/****************************************************************************/
/****************************************************************************/
/* CREATE A SPECIFIC TYPE OF CONNECTION BETWEEN 2 GME OBJECTS */
/****************************************************************************/
MetaEditorControl.prototype._createConnection = function (gmeSrcId, gmeDstId, connType, connTexts) {
var connDesc,
connComponent,
metaInfo;
//need to check if the src and dst objects are displayed or not
//if YES, create connection
//if NO, store information in a waiting queue
if (this._GMENodes.indexOf(gmeSrcId) !== -1 && this._GMENodes.indexOf(gmeDstId) !== -1) {
//source and destination is displayed
if (this._filteredOutConnTypes.indexOf(connType) === -1) {
//connection type is not filtered out
connDesc = {
srcObjId: this._GMEID2ComponentID[gmeSrcId],
srcSubCompId: undefined,
dstObjId: this._GMEID2ComponentID[gmeDstId],
dstSubCompId: undefined,
reconnectable: false,
name: '',
nameEdit: false
};
//set visual properties
_.extend(connDesc, MetaRelations.getLineVisualDescriptor(connType));
//fill out texts
if (connTexts) {
_.extend(connDesc, connTexts);
}
connComponent = this.diagramDesigner.createConnection(connDesc);
//set connection metaInfo and store connection type
//the MetaDecorator uses this information when queried for connectionArea
metaInfo = {};
metaInfo[MetaRelations.CONNECTION_META_INFO.TYPE] = connType;
connComponent.setMetaInfo(metaInfo);
this._saveConnection(gmeSrcId, gmeDstId, connType, connComponent.id, connTexts);
} else {
//connection type is filtered out
this._filteredOutConnectionDescriptors[connType].push([gmeSrcId, gmeDstId, connTexts]);
}
} else {
//source or destination is not displayed, store it in a queue
this._saveConnectionToWaitingList(gmeSrcId, gmeDstId, connType, connTexts);
}
};
MetaEditorControl.prototype._saveConnectionToWaitingList = function (gmeSrcId, gmeDstId, connType, connTexts) {
if (this._GMENodes.indexOf(gmeSrcId) !== -1 && this._GMENodes.indexOf(gmeDstId) === -1) {
//#1 - the destination object is missing from the screen
this._connectionWaitingListByDstGMEID[gmeDstId] = this._connectionWaitingListByDstGMEID[gmeDstId] || {};
this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId] =
this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId] || [];
this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId].push([connType, connTexts]);
} else if (this._GMENodes.indexOf(gmeSrcId) === -1 && this._GMENodes.indexOf(gmeDstId) !== -1) {
//#2 - the source object is missing from the screen
this._connectionWaitingListBySrcGMEID[gmeSrcId] = this._connectionWaitingListBySrcGMEID[gmeSrcId] || {};
this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId] =
this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId] || [];
this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId].push([connType, connTexts]);
} else {
//#3 - both gmeSrcId and gmeDstId is missing from the screen
//NOTE: this should never happen!!!
this.logger.error('_saveConnectionToWaitingList both gmeSrcId and gmeDstId is undefined...');
}
};
MetaEditorControl.prototype._saveConnection = function (gmeSrcId, gmeDstId, connType, connComponentId, connTexts) {
//save by SRC
this._connectionListBySrcGMEID[gmeSrcId] = this._connectionListBySrcGMEID[gmeSrcId] || {};
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId] = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId] || {};
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType] =
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType] || [];
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].push(connComponentId);
//save by DST
this._connectionListByDstGMEID[gmeDstId] = this._connectionListByDstGMEID[gmeDstId] || {};
this._connectionListByDstGMEID[gmeDstId][gmeSrcId] = this._connectionListByDstGMEID[gmeDstId][gmeSrcId] || {};
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType] =
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType] || [];
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType].push(connComponentId);
//save by type
this._connectionListByType[connType] = this._connectionListByType[connType] || [];
this._connectionListByType[connType].push(connComponentId);
//save by connectionID
this._connectionListByID[connComponentId] = {
GMESrcId: gmeSrcId,
GMEDstId: gmeDstId,
type: connType,
name: (connTexts && connTexts.name) ? connTexts.name : undefined,
connTexts: connTexts
};
};
/****************************************************************************/
/* END OF --- CREATE A SPECIFIC TYPE OF CONNECTION BETWEEN 2 GME OBJECTS */
/****************************************************************************/
/****************************************************************************/
/* REMOVES A SPECIFIC TYPE OF CONNECTION FROM 2 GME OBJECTS */
/****************************************************************************/
MetaEditorControl.prototype._removeConnection = function (gmeSrcId, gmeDstId, connType, pointerName) {
var connectionID,
idx,
len,
connectionPresent = false;
//only bother if
//- both the source and destination is present on the screen
//the connection in question is drawn
if (this._connectionListBySrcGMEID[gmeSrcId] &&
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId] &&
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType]) {
connectionPresent = true;
}
if (!connectionPresent) {
return;
}
len = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].length;
while (len--) {
connectionID = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType][len];
//if a pointer with a specific name should be removed
//clear out the connectionID if this connection is not the representation of that pointer
if (connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
this._connectionListByID[connectionID].name !== pointerName) {
connectionID = undefined;
}
//if the connectionID is still valid
if (connectionID) {
this.diagramDesigner.deleteComponent(connectionID);
//clean up accounting
delete this._connectionListByID[connectionID];
idx = this._connectionListByType[connType].indexOf(connectionID);
this._connectionListByType[connType].splice(idx, 1);
idx = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].indexOf(connectionID);
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].splice(idx, 1);
idx = this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType].indexOf(connectionID);
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType].splice(idx, 1);
}
}
};
/****************************************************************************/
/* END OF --- REMOVES A SPECIFIC TYPE OF CONNECTION FROM 2 GME OBJECTS */
/****************************************************************************/
/*****************************************************************************/
/* UPDATE CONNECTION TEXT */
/*****************************************************************************/
MetaEditorControl.prototype._updateConnectionText = function (gmeSrcId, gmeDstId, connType, connTexts) {
var connectionID,
idx,
len = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].length,
pointerName = connTexts.name,
found = false,
connDesc;
while (len--) {
connectionID = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType][len];
//if a pointer with a specific name should be removed
//clear out the connectionID if this connection is not the representation of that pointer
if (connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
this._connectionListByID[connectionID].name !== pointerName) {
connectionID = undefined;
}
//if the connectionID is still valid
if (connectionID) {
this._connectionListByID[connectionID].name = connTexts.name;
this._connectionListByID[connectionID].connTexts = connTexts;
this.diagramDesigner.updateConnectionTexts(connectionID, connTexts);
found = true;
}
}
if (!found) {
//try to find it in the connection waiting list
if (this._GMENodes.indexOf(gmeSrcId) !== -1 && this._GMENodes.indexOf(gmeDstId) === -1) {
//#1 - the destination object is missing from the screen
len = this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId].length;
for (idx = 0; idx < len; idx += 1) {
connDesc = this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId][idx];
if (connDesc[0] === connType) {
if (connType !== MetaRelations.META_RELATIONS.POINTER ||
(connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
connDesc[1].name === pointerName)) {
connDesc[1] = connTexts;
}
}
}
} else if (this._GMENodes.indexOf(gmeSrcId) === -1 && this._GMENodes.indexOf(gmeDstId) !== -1) {
//#2 - the source object is missing from the screen
len = this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId].length;
for (idx = 0; idx < len; idx += 1) {
connDesc = this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId][idx];
if (connDesc[0] === connType) {
if (connType !== MetaRelations.META_RELATIONS.POINTER ||
(connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
connDesc[1].name === pointerName)) {
connDesc[1] = connTexts;
}
}
}
} else {
//#3 - both gmeSrcId and gmeDstId is missing from the screen
}
}
};
/*****************************************************************************/
/* END OF --- UPDATE CONNECTION TEXT */
/*****************************************************************************/
/**************************************************************************/
/* HANDLE OBJECT UPDATE --- DISPLAY IT WITH ALL THE POINTERS / SETS / ETC */
/**************************************************************************/
MetaEditorControl.prototype._processNodeUpdate = function (gmeID) {
var componentID,
decClass,
objDesc = {};
if (this._GMEID2ComponentID.hasOwnProperty(gmeID)) {
componentID = this._GMEID2ComponentID[gmeID];
decClass = this._client.decoratorManager.getDecoratorForWidget(META_DECORATOR, WIDGET_NAME);
objDesc.decoratorClass = decClass;
objDesc.preferencesHelper = PreferencesHelper.getPreferences([{
containerID: this.metaAspectContainerNodeID,
setID: MetaEditorConstants.META_ASPECT_SET_NAME
}]);
this.diagramDesigner.updateDesignerItem(componentID, objDesc);
//update set relations
this._processNodeMetaContainment(gmeID);
this._processNodeMetaPointers(gmeID, false);
this._processNodeMetaInheritance(gmeID);
this._processNodeMixins(gmeID);
this._processNodeMetaPointers(gmeID, true);
}
};
/**************************************************************************/
/* END OF --- HANDLE OBJECT UPDATE */
/**************************************************************************/
/***********************************************************************************/
/* DISPLAY META CONTAINMENT RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/***********************************************************************************/
MetaEditorControl.prototype._processNodeMetaContainment = function (gmeID) {
var containmentMetaDescriptor = this._client.getValidChildrenItems(gmeID) || [],
containmentOwnTypes = this._client.getOwnValidChildrenTypes(gmeID) || [],
len,
oldMetaContainment,
newMetaContainment = {targets: []},
diff,
containmentTarget,
idx;
this._nodeMetaContainment[gmeID] = this._nodeMetaContainment[gmeID] || {targets: []};
oldMetaContainment = this._nodeMetaContainment[gmeID];
len = containmentMetaDescriptor.length;
while (len--) {
if (containmentOwnTypes.indexOf(containmentMetaDescriptor[len].id) !== -1) {
newMetaContainment.targets.push(containmentMetaDescriptor[len].id);
newMetaContainment[containmentMetaDescriptor[len].id] = {
multiplicity: '' + (containmentMetaDescriptor[len].min || 0) + '..' +
(containmentMetaDescriptor[len].max || '*')
};
}
}
//compute updated connections
diff = _.intersection(oldMetaContainment.targets, newMetaContainment.targets);
len = diff.length;
while (len--) {
containmentTarget = diff[len];
if (oldMetaContainment[containmentTarget].multiplicity !==
newMetaContainment[containmentTarget].multiplicity) {
//update accounting
oldMetaContainment[containmentTarget].multiplicity = newMetaContainment[containmentTarget].multiplicity;
//update connection text
this._updateConnectionText(gmeID, containmentTarget, MetaRelations.META_RELATIONS.CONTAINMENT, {
dstText: newMetaContainment[containmentTarget].multiplicity,
dstTextEdit: true
});
}
}
//compute deleted pointers
diff = _.difference(oldMetaContainment.targets, newMetaContainment.targets);
len = diff.length;
while (len--) {
containmentTarget = diff[len];
this._removeConnection(gmeID, containmentTarget, MetaRelations.META_RELATIONS.CONTAINMENT);
idx = oldMetaContainment.targets.indexOf(containmentTarget);
oldMetaContainment.targets.splice(idx, 1);
delete oldMetaContainment[containmentTarget];
}
//compute added pointers
diff = _.difference(newMetaContainment.targets, oldMetaContainment.targets);
len = diff.length;
while (len--) {
containmentTarget = diff[len];
oldMetaContainment.targets.push(containmentTarget);
oldMetaContainment[containmentTarget] = {multiplicity: newMetaContainment[containmentTarget].multiplicity};
this._createConnection(gmeID, containmentTarget, MetaRelations.META_RELATIONS.CONTAINMENT, {
dstText: newMetaContainment[containmentTarget].multiplicity,
dstTextEdit: true
});
}
};
/**********************************************************************************************/
/* END OF --- DISPLAY META CONTAINMENT RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/**********************************************************************************************/
/*******************************************************************************/
/* DISPLAY META POINTER RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/*******************************************************************************/
MetaEditorControl.prototype._processNodeMetaPointers = function (gmeID, isSet) {
var node = this._client.getNode(gmeID),
pointerNames = isSet === true ? node.getValidSetNames() : node.getValidPointerNames(),
pointerMetaDescriptor,
pointerOwnMetaTypes,
len,
oldMetaPointers,
newMetaPointers = {names: [], combinedNames: []},
diff,
pointerTarget,
pointerName,
idx,
lenTargets,
combinedName,
ptrType = isSet === true ? MetaRelations.META_RELATIONS.SET : MetaRelations.META_RELATIONS.POINTER;
if (isSet !== true) {
this._nodeMetaPointers[gmeID] = this._nodeMetaPointers[gmeID] || {names: [], combinedNames: []};
oldMetaPointers = this._nodeMetaPointers[gmeID];
} else {
this._nodeMetaSets[gmeID] = this._nodeMetaSets[gmeID] || {names: [], combinedNames: []};
oldMetaPointers = this._nodeMetaSets[gmeID];
}
len = pointerNames.length;
while (len--) {
pointerMetaDescriptor = this._client.getValidTargetItems(gmeID, pointerNames[len]);
pointerOwnMetaTypes = this._client.getOwnValidTargetTypes(gmeID, pointerNames[len]);
if (pointerMetaDescriptor) {
lenTargets = pointerMetaDescriptor.length;
while (lenTargets--) {
if (pointerOwnMetaTypes.indexOf(pointerMetaDescriptor[lenTargets].id) !== -1) {
combinedName = pointerNames[len] + '_' + pointerMetaDescriptor[lenTargets].id;
newMetaPointers.names.push(pointerNames[len]);
newMetaPointers.combinedNames.push(combinedName);
newMetaPointers[combinedName] = {
name: pointerNames[len],
target: pointerMetaDescriptor[lenTargets].id
};
if (isSet) {
newMetaPointers[combinedName].multiplicity = '' +
(pointerMetaDescriptor[lenTargets].min || 0) +
'..' +
(pointerMetaDescriptor[lenTargets].max || '*');
}
}
}
}
}
//compute updated connections
diff = _.intersection(oldMetaPointers.combinedNames, newMetaPointers.combinedNames);
len = diff.length;
while (len--) {
combinedName = diff[len];
if (oldMetaPointers[combinedName].multiplicity !== newMetaPointers[combinedName].multiplicity) {
pointerName = oldMetaPointers[combinedName].name;
pointerTarget = oldMetaPointers[combinedName].target;
oldMetaPointers[combinedName].multiplicity = newMetaPointers[combinedName].multiplicity;
this._updateConnectionText(gmeID, pointerTarget, ptrType, {
name: pointerName,
dstText: newMetaPointers[combinedName].multiplicity,
dstTextEdit: true
});
}
}
//compute deleted pointers
diff = _.difference(oldMetaPointers.combinedNames, newMetaPointers.combinedNames);
len = diff.length;
while (len--) {
combinedName = diff[len];
pointerName = oldMetaPointers[combinedName].name;
pointerTarget = oldMetaPointers[combinedName].target;
this._removeConnection(gmeID, pointerTarget, ptrType, pointerName);
idx = oldMetaPointers.combinedNames.indexOf(combinedName);
oldMetaPointers.combinedNames.splice(idx, 1);
delete oldMetaPointers[combinedName];
}
//compute added pointers
diff = _.difference(newMetaPointers.combinedNames, oldMetaPointers.combinedNames);
len = diff.length;
while (len--) {
combinedName = diff[len];
pointerName = newMetaPointers[combinedName].name;
pointerTarget = newMetaPointers[combinedName].target;
oldMetaPointers.names.push(pointerName);
oldMetaPointers.combinedNames.push(combinedName);
oldMetaPointers[combinedName] = {
name: newMetaPointers[combinedName].name,
target: newMetaPointers[combinedName].target,
multiplicity: newMetaPointers[combinedName].multiplicity
};
this._createConnection(gmeID, pointerTarget, ptrType, {
name: pointerName,
dstText: newMetaPointers[combinedName].multiplicity,
dstTextEdit: true
});
}
};
/******************************************************************************************/
/* END OF --- DISPLAY META POINTER RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/******************************************************************************************/
/***********************************************************************************/
/* DISPLAY META INHERITANCE RELATIONS AS A CONNECTION FROM PARENT TO OBJECT */
/***********************************************************************************/
MetaEditorControl.prototype._processNodeMetaInheritance = function (gmeID) {
var node = this._client.getNode(gmeID),
oldMetaInheritance,
newMetaInheritance = node.getBaseId();
//if there was a valid old that's different than the current, delete the connection representing the old
oldMetaInheritance = this._nodeMetaInheritance[gmeID];
if (oldMetaInheritance && (oldMetaInheritance !== newMetaInheritance)) {
this._removeConnection(gmeID, oldMetaInheritance, MetaRelations.META_RELATIONS.INHERITANCE);
delete this._nodeMetaInheritance[gmeID];
}
if (newMetaInheritance && (oldMetaInheritance !== newMetaInheritance)) {
this._nodeMetaInheritance[gmeID] = newMetaInheritance;
this._createConnection(gmeID, newMetaInheritance, MetaRelations.META_RELATIONS.INHERITANCE, undefined);
}
};
/**********************************************************************************************/
/* END OF --- DISPLAY META CONTAINMENT RELATIONS AS A CONNECTION FROM PARENT TO OBJECT */
/**********************************************************************************************/
MetaEditorControl.prototype._processNodeMixins = function (gmeID) {
var node = this._client.getNode(gmeID),
oldMixins,
newMixins = node.getMixinPaths(),
i;
this.logger.debug('processing mixins for [' + gmeID + ']');
// If there was a valid old that's different than the current, delete the connection representing the old.
oldMixins = this._nodeMixins[gmeID] || [];
for (i = 0; i < oldMixins.length; i += 1) {
if (newMixins.indexOf(oldMixins[i]) === -1) {
this._removeConnection(gmeID, oldMixins[i], MetaRelations.META_RELATIONS.MIXIN);
}
}
for (i = 0; i < newMixins.length; i += 1) {
if (oldMixins.indexOf(newMixins[i]) === -1) {
this._createConnection(gmeID, newMixins[i], MetaRelations.META_RELATIONS.MIXIN, undefined);
}
}
this._nodeMixins[gmeID] = newMixins;
};
/****************************************************************************/
/* CREATE NEW CONNECTION BUTTONS AND THEIR EVENT HANDLERS */
/****************************************************************************/
MetaEditorControl.prototype._setNewConnectionType = function (connType) {
var connProps = MetaRelations.getLineVisualDescriptor(connType),
temp;
if (this._connType !== connType) {
this._connType = connType;
if (connType === MetaRelations.META_RELATIONS.CONTAINMENT) {
//for METACONTAINMENT AND INHERITANCE flip the visual end arrow style for drawing only
temp = connProps[DiagramDesignerWidgetConstants.LINE_START_ARROW];
connProps[DiagramDesignerWidgetConstants.LINE_START_ARROW] =
connProps[DiagramDesignerWidgetConstants.LINE_END_ARROW];
connProps[DiagramDesignerWidgetConstants.LINE_END_ARROW] = temp;
}
this.diagramDesigner.connectionDrawingManager.setConnectionInDrawProperties(connProps);
this.diagramDesigner.setFilterChecked(this._connType);
}
};
/****************************************************************************/
/* END OF --- CREATE NEW CONNECTION BUTTONS AND THEIR EVENT HANDLERS */
/****************************************************************************/
/****************************************************************************/
/* CREATE NEW CONNECTION BETWEEN TWO ITEMS */
/****************************************************************************/
MetaEditorControl.prototype._onCreateNewConnection = function (params) {
var sourceId = this._ComponentID2GMEID[params.src],
targetId = this._ComponentID2GMEID[params.dst];
switch (this._connType) {
case MetaRelations.META_RELATIONS.CONTAINMENT:
this._createContainmentRelationship(targetId, sourceId);
break;
case MetaRelations.META_RELATIONS.INHERITANCE:
this._createInheritanceRelationship(sourceId, targetId);
break;
case MetaRelations.META_RELATIONS.POINTER:
this._createPointerRelationship(sourceId, targetId, false);
break;
case MetaRelations.META_RELATIONS.SET:
this._createPointerRelationship(sourceId, targetId, true);
break;
case MetaRelations.META_RELATIONS.MIXIN:
this._createMixinRelationship(sourceId, targetId);
break;
default:
break;
}
};
MetaEditorControl.prototype._createContainmentRelationship = function (containerID, objectID) {
var containerNode = this._client.getNode(containerID),
objectNode = this._client.getNode(objectID);
if (containerNode && objectNode) {
this._client.updateValidChildrenItem(containerID, {id: objectID});
}
};
MetaEditorControl.prototype._deleteContainmentRelationship = function (containerID, objectID) {
var containerNode = this._client.getNode(containerID),
objectNode = this._client.getNode(objectID);
if (containerNode && objectNode) {
this._client.removeValidChildrenItem(containerID, objectID);
}
};
MetaEditorControl.prototype._createPointerRelationship = function (sourceID, targetID, isSet) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
pointerMetaDescriptor,
existingPointerNames,
notAllowedPointerNames,
self = this;
if (sourceNode && targetNode) {
notAllowedPointerNames = _.union(sourceNode.getSetNames(), sourceNode.getPointerNames());
if (isSet === true) {
//this is a pointer list
existingPointerNames = _.difference(sourceNode.getSetNames() || [],
this._client.getMetaAspectNames(sourceID));
} else {
//this is a single pointer
//get the list of existing pointers and show them in a dialog so the user can choose
existingPointerNames = sourceNode.getPointerNames() || [];
}
notAllowedPointerNames = _.difference(notAllowedPointerNames, existingPointerNames);
//handle RESERVED pointer names
existingPointerNames = _.difference(existingPointerNames, MetaEditorConstants.RESERVED_POINTER_NAMES);
notAllowedPointerNames = notAllowedPointerNames.concat(MetaEditorConstants.RESERVED_POINTER_NAMES);
//query pointer name from user
this.diagramDesigner.selectNewPointerName(existingPointerNames,
notAllowedPointerNames,
isSet,
function (userSelectedPointerName) {
self._client.startTransaction();
pointerMetaDescriptor = self._client.getOwnValidTargetItems(sourceID, userSelectedPointerName);
if (!pointerMetaDescriptor) {
if (isSet !== true) {
//single pointer
self._client.setPointerMeta(sourceID, userSelectedPointerName, {
min: 1,
max: 1,
items: [
{
id: targetID,
max: 1
}
]
});
self._client.makePointer(sourceID, userSelectedPointerName, null);
} else {
//pointer list
self._client.setPointerMeta(sourceID, userSelectedPointerName, {
items: [
{
id: targetID
}
]
});
self._client.createSet(sourceID, userSelectedPointerName);
}
} else {
if (isSet !== true) {
//single pointer
self._client.updateValidTargetItem(sourceID,
userSelectedPointerName,
{
id: targetID,
max: 1
});
} else {
//pointer list
self._client.updateValidTargetItem(sourceID, userSelectedPointerName, {id: targetID});
}
}
self._client.completeTransaction();
});
}
};
MetaEditorControl.prototype._deletePointerRelationship = function (sourceID, targetID, pointerName, isSet) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
pointerMetaDescriptor;
//NOTE: this method is called from inside a transaction, don't need to start/complete one
if (sourceNode && targetNode) {
this._client.removeValidTargetItem(sourceID, pointerName, targetID);
pointerMetaDescriptor = this._client.getValidTargetItems(sourceID, pointerName);
if (!pointerMetaDescriptor || pointerMetaDescriptor.length === 0) {
if (isSet === false) {
//single pointer
this._client.deleteMetaPointer(sourceID, pointerName);
this._client.delPointer(sourceID, pointerName);
} else {
//pointer list
this._client.deleteMetaPointer(sourceID, pointerName);
this._client.deleteSet(sourceID, pointerName);
}
}
}
};
MetaEditorControl.prototype._createInheritanceRelationship = function (objectID, newBaseID) {
var newBaseNode = this._client.getNode(newBaseID),
objectNode = this._client.getNode(objectID),
objectBase;
if (newBaseNode && objectNode) {
objectBase = objectNode.getBaseId();
if (objectBase && !_.isEmpty(objectBase)) {
this.logger.debug('InheritanceRelationship from "' +
objectNode.getAttribute(nodePropertyNames.Attributes.name) +
'" (' + objectID + ') to parent "' + objectBase + '" already exists, but overwriting to "' +
newBaseNode.getAttribute(nodePropertyNames.Attributes.name) + '" (' + newBaseID + ')"');
}
this._client.setBase(objectID, newBaseID);
}
};
MetaEditorControl.prototype._deleteInheritanceRelationship = function (parentID, objectID) {
var objectNode = this._client.getNode(objectID),
objectBaseId,
baseNode;
if (objectNode) {
objectBaseId = objectNode.getBaseId();
if (objectBaseId) {
baseNode = this._client.getNode(objectBaseId);
if (baseNode) {
objectBaseId = baseNode.getAttribute(nodePropertyNames.Attributes.name) + ' (' + objectBaseId + ')';
}
/*this.logger.debug('Deleting InheritanceRelationship from "' +
objectNode.getAttribute(nodePropertyNames.Attributes.name) + '" (' + objectID + ') to parent "' +
objectBaseId + '"');
this._client.delBase(objectID);*/
//TEMPORARILY DO NOT ALLOW DELETING INHERITANCE RELATIONSHIP
this.logger.error('Deleting InheritanceRelationship from "' +
objectNode.getAttribute(nodePropertyNames.Attributes.name) + '" (' + objectID +
') to parent "' + objectBaseId + '" is not allowed...');
}
}
};
MetaEditorControl.prototype._createMixinRelationship = function (objectId, newMixinId) {
var newBaseNode = this._client.getNode(newMixinId),
objectNode = this._client.getNode(objectId),
objectBase;
if (newBaseNode && objectNode) {
this._client.addMixin(objectId, newMixinId);
} else {
this.logger.error('cannot set [' + newMixinId + '] as mixin for [' + objectId +
'] because not all node are loaded');
}
};
MetaEditorControl.prototype._deleteMixinRelationship = function (objectId, mixinToRemoveId) {
var newBaseNode = this._client.getNode(mixinToRemoveId),
objectNode = this._client.getNode(objectId),
objectBase;
if (newBaseNode && objectNode) {
this._client.delMixin(objectId, mixinToRemoveId);
} else {
this.logger.error('cannot remove [' + newMixinId + '] mixin from [' + objectId +
'] because not all node are loaded');
}
};
/****************************************************************************/
/* END OF --- CREATE NEW CONNECTION BETWEEN TWO ITEMS */
/****************************************************************************/
/****************************************************************************/
/* POINTER FILTER PANEL AND EVENT HANDLERS */
/****************************************************************************/
MetaEditorControl.prototype._initFilterPanel = function () {
var filterIcon;
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.CONTAINMENT);
this.diagramDesigner.addFilterItem('Containment', MetaRelations.META_RELATIONS.CONTAINMENT, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.POINTER);
this.diagramDesigner.addFilterItem('Pointer', MetaRelations.META_RELATIONS.POINTER, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.INHERITANCE);
this.diagramDesigner.addFilterItem('Inheritance', MetaRelations.META_RELATIONS.INHERITANCE, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.MIXIN);
this.diagramDesigner.addFilterItem('Mixin', MetaRelations.META_RELATIONS.MIXIN, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.SET);
this.diagramDesigner.addFilterItem('Set', MetaRelations.META_RELATIONS.SET, filterIcon);
};
MetaEditorControl.prototype._onConnectionTypeFilterCheckChanged = function (value, isChecked) {
var idx;
if (isChecked === true) {
//type should be enabled
idx = this._filteredOutConnTypes.indexOf(value);
this._filteredOutConnTypes.splice(idx, 1);
this._unfilterConnType(value);
} else {
this._filteredOutConnTypes.push(value);
this._filterConnType(value);
}
};
MetaEditorControl.prototype._filterConnType = function (connType) {
var len = this._connectionListByType &&
this._connectionListByType.hasOwnProperty(connType) ? this._connectionListByType[connType].length : 0,
connComponentId,
gmeSrcId,
gmeDstId,
connTexts,
pointerName;
this._filteredOutConnectionDescriptors[connType] = [];
this.diagramDesigner.beginUpdate();
while (len--) {
connComponentId = this._connectionListByType[connType][len];
gmeSrcId = this._connectionListByID[connComponentId].GMESrcId;
gmeDstId = this._connectionListByID[connComponentId].GMEDstId;
connTexts = this._connectionListByID[connComponentId].connTexts;
if (connType === MetaRelations.META_RELATIONS.POINTER) {
pointerName = this._connectionListByID[connComponentId].name;
}
this._filteredOutConnectionDescriptors[connType].push([gmeSrcId, gmeDstId, connTexts]);
this._removeConnection(gmeSrcId, gmeDstId, connType, pointerName);
}
this.diagramDesigner.endUpdate();
};
MetaEditorControl.prototype._unfilterConnType = function (connType) {
//FIXME: What does this mean?
var len = this._filteredOutConnectionDescriptors &&
this._filteredOutConnectionDescriptors.hasOwnProperty(connType) ?
this._filteredOutConnectionDescriptors[connType].length : 0,
gmeSrcId,
gmeDstId,
connTexts;
this.diagramDesigner.beginUpdate();
while (len--) {
gmeSrcId = this._filteredOutConnectionDescriptors[connType][len][0];
gmeDstId = this._filteredOutConnectionDescriptors[connType][len][1];
connTexts = this._filteredOutConnectionDescriptors[connType][len][2];
this._createConnection(gmeSrcId, gmeDstId, connType, connTexts);
}
delete this._filteredOutConnectionDescriptors[connType];
this.diagramDesigner.endUpdate();
};
/****************************************************************************/
/* END OF --- POINTER FILTER PANEL AND EVENT HANDLERS */
/****************************************************************************/
/****************************************************************************/
/* CONNECTION DESTINATION TEXT CHANGE */
/****************************************************************************/
MetaEditorControl.prototype._onConnectionDstTextChanged = function (connectionID, oldValue, newValue) {
var connDesc = this._connectionListByID[connectionID];
if (connDesc.type === MetaRelations.META_RELATIONS.CONTAINMENT) {
this._containmentRelationshipMultiplicityUpdate(connDesc.GMESrcId, connDesc.GMEDstId, oldValue, newValue);
} else if (connDesc.type === MetaRelations.META_RELATIONS.POINTER) {
this._pointerRelationshipMultiplicityUpdate(connDesc.GMESrcId,
connDesc.GMEDstId,
connDesc.name,
oldValue,
newValue);
} else if (connDesc.type === MetaRelations.META_RELATIONS.INHERITANCE) {
//never can happen
} else if (connDesc.type === MetaRelations.META_RELATIONS.SET) {
this._setRelationshipMultiplicityUpdate(connDesc.GMESrcId,
connDesc.GMEDstId,
connDesc.name,
oldValue,
newValue);
}
};
MetaEditorControl.prototype._containmentRelationshipMultiplicityUpdate = function (containerID, objectID, oldValue,
newValue) {
var containerNode = this._client.getNode(containerID),
objectNode = this._client.getNode(objectID),
multiplicity,
multiplicityValid;
multiplicityValid = function (value) {
var result = null,
pattNum = /^\d+$/g,
pattMinToMax = /^\d+\.\.\d+$/g,
pattMinToMany = /^\d+\.\.\*$/g;
//valid values for containment are 1, x..*, x..y
if (pattNum.test(value)) {
//#1: single digit number
result = {
min: parseInt(value, 10),
max: parseInt(value, 10)
};
} else if (pattMinToMax.test(value)) {
//#2: x..y
result = {
min: parseInt(value, 10),
max: parseInt(value.substring(value.indexOf('..') + 2), 10)
};
} else if (pattMinToMany.test(value)) {
//#3: x..*
result = {
min: parseInt(value, 10),
max: -1
};
}
return result;
};
if (containerNode && objectNode) {
multiplicity = multiplicityValid(newValue);
if (multiplicity) {
multiplicity.id = objectID;
this._client.updateValidChildrenItem(containerID, multiplicity);
} else {
this._updateConnectionText(containerID, objectID, MetaRelations.META_RELATIONS.CONTAINMENT, {
dstText: oldValue,
dstTextEdit: true
});
}
}
};
MetaEditorControl.prototype._pointerRelationshipMultiplicityUpdate = function (sourceID, targetID, pointerName,
oldValue, newValue) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
multiplicityValid,
multiplicity;
multiplicityValid = function (value) {
var result,
pattOne = '1',
pattZeroOne = '0..1';
//valid values for pointer are: 1, 0..1
if (value === pattOne) {
//#1: single digit number
result = {
min: 1,
max: 1
};
} else if (value === pattZeroOne) {
result = {
min: 0,
max: 1
};
}
return result;
};
if (sourceNode && targetNode) {
multiplicity = multiplicityValid(newValue);
if (multiplicity) {
multiplicity.id = targetID;
this._client.updateValidTargetItem(sourceID, pointerName, multiplicity);
} else {
this._updateConnectionText(sourceID, targetID, MetaRelations.META_RELATIONS.POINTER, {
name: pointerName,
dstText: oldValue,
dstTextEdit: true
});
}
}
};
MetaEditorControl.prototype._setRelationshipMultiplicityUpdate = function (sourceID, targetID, pointerName,
oldValue, newValue) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
multiplicityValid,
multiplicity;
multiplicityValid = function (value) {
var result = null,
pattNum = /^\d+$/g,
pattMinToMax = /^\d+\.\.\d+$/g,
pattMinToMany = /^\d+\.\.\*$/g;
//valid value for pointer list are: 1, x..*, x..y
if (pattNum.test(value)) {
//#1: single digit number
result = {
min: parseInt(value, 10),
max: parseInt(value, 10)
};
} else if (pattMinToMax.test(value)) {
//#2: x..y
result = {
min: parseInt(value, 10),
max: parseInt(value.substring(value.indexOf('..') + 2), 10)
};
} else if (pattMinToMany.test(value)) {
//#3: x..*
result = {
min: parseInt(value, 10),
max: -1
};
}
return result;
};
if (sourceNode && targetNode) {
multiplicity = multiplicityValid(newValue);
if (multiplicity) {
multiplicity.id = targetID;
this._client.updateValidTargetItem(sourceID, pointerName, multiplicity);
} else {
this._updateConnectionText(sourceID, targetID, MetaRelations.META_RELATIONS.SET, {
name: pointerName,
dstText: oldValue,
dstTextEdit: true
});
}
}
};
/****************************************************************************/
/* END OF --- CONNECTION DESTINATION TEXT CHANGE */
/****************************************************************************/
MetaEditorControl.prototype._attachClientEventListeners = function () {
};
MetaEditorControl.prototype._detachClientEventListeners = function () {
};
MetaEditorControl.prototype.onActivate = function () {
if (this._selectedSheetID) {
WebGMEGlobal.State.registerActiveTab(this._selectedSheetID);
}
this._attachClientEventListeners();
this._displayToolbarItems();
};
MetaEditorControl.prototype.onDeactivate = function () {
this._detachClientEventListeners();
this._hideToolbarItems();
};
MetaEditorControl.prototype._displayToolbarItems = function () {
if (this._toolbarInitialized !== true) {
this._initializeToolbar();
} else {
for (var i = 0; i < this._toolbarItems.length; i++) {
this._toolbarItems[i].show();
}
}
};
MetaEditorControl.prototype._hideToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = 0; i < this._toolbarItems.length; i++) {
this._toolbarItems[i].hide();
}
}
};
MetaEditorControl.prototype._removeToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = 0; i < this._toolbarItems.length; i++) {
this._toolbarItems[i].destroy();
}
}
};
MetaEditorControl.prototype._initializeToolbar = function () {
var toolBar = WebGMEGlobal.Toolbar,
self = this;
this._toolbarItems = [];
/****************** ADD BUTTONS AND THEIR EVENT HANDLERS TO DIAGRAM DESIGNER ******************/
/************** CREATE META RELATION CONNECTION TYPES *****************/
this._radioButtonGroupMetaRelationType = toolBar.addRadioButtonGroup(function (data) {
self._setNewConnectionType(data.connType);
});
this._toolbarItems.push(this._radioButtonGroupMetaRelationType);
this._radioButtonGroupMetaRelationType.addButton({
title: 'Containment',
selected: true,
data: {connType: MetaRelations.META_RELATIONS.CONTAINMENT},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.CONTAINMENT)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Inheritance',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.INHERITANCE},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.INHERITANCE)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Mixin',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.MIXIN},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.MIXIN)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Pointer',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.POINTER},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.POINTER)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Set',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.SET},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.SET)
});
/************** END OF - CREATE META RELATION CONNECTION TYPES *****************/
/************** PRINT NODE DATA *****************/
// TODO removed, but could be reimplemented if needed such function
//this._btnPrintNodeMetaData = toolBar.addButton({ "title": "Print node META data",
// "icon": "glyphicon glyphicon-share",
// "clickFn": function (/*data*/){
// self._printNodeData();
// }});
//this._toolbarItems.push(this._btnPrintNodeMetaData);
/************** END OF - PRINT NODE DATA *****************/
/****************** END OF - ADD BUTTONS AND THEIR EVENT HANDLERS TO DESIGNER CANVAS ******************/
this._toolbarInitialized = true;
};
MetaEditorControl.prototype._getAssociatedConnections = function (objectID) {
var result = {src: [], dst: []},
len,
cID,
checkConnections;
checkConnections = function (cList, res) {
var otherID,
connType;
//check objectID as source
if (cList.hasOwnProperty(objectID)) {
for (otherID in cList[objectID]) {
if (cList[objectID].hasOwnProperty(otherID)) {
for (connType in cList[objectID][otherID]) {
if (cList[objectID][otherID].hasOwnProperty(connType)) {
len = cList[objectID][otherID][connType].length;
while (len--) {
cID = cList[objectID][otherID][connType][len];
if (res.indexOf(cID) === -1) {
res.push(cID);
}
}
}
}
}
}
}
};
checkConnections(this._connectionListBySrcGMEID, result.src);
checkConnections(this._connectionListByDstGMEID, result.dst);
return result;
};
MetaEditorControl.prototype._processMetaAspectSheetsRegistry = function () {
var aspectNode = this._client.getNode(this.metaAspectContainerNodeID),
metaAspectSheetsRegistry = aspectNode.getEditableRegistry(REGISTRY_KEYS.META_SHEETS) || [],
i,
len,
sheetID,
selectedSheetID,
setName,
j,
gmeID;
//save old positions
var oldMetaAspectMembersCoordinatesPerSheet = this._metaAspectMembersCoordinatesPerSheet;
this._sheets = {};
this._metaAspectMembersPerSheet = {};
this._metaAspectMembersCoordinatesPerSheet = {};
this.diagramDesigner.clearTabs();
this._metaAspectSheetsPerMember = {};
metaAspectSheetsRegistry.sort(function (a, b) {
if (a.order < b.order) {
return -1;
} else {
return 1;
}
});
//here we have the metaAspectRegistry ordered by user defined order
this.diagramDesigner.addMultipleTabsBegin();
len = metaAspectSheetsRegistry.length;
for (i = 0; i < len; i += 1) {
setName = metaAspectSheetsRegistry[i].SetID;
sheetID = this.diagramDesigner.addTab(metaAspectSheetsRegistry[i].title, true, true);
this._sheets[sheetID] = setName;
//get the most up-to-date member list for each set
this._metaAspectMembersPerSheet[setName] = aspectNode.getMemberIds(setName);
//TODO: debug check to see if root for any reason is present among the members list
//TODO: remove, not needed, just for DEGUG reasons...
//TODO: it should never happen because it leads to double refresh when ROOT changes
//TODO: when onOneEvent will be eliminated this will not be an issue anymore
if (this._metaAspectMembersPerSheet[setName].indexOf(CONSTANTS.PROJECT_ROOT_ID) > -1) {
this.logger.error('ROOT is in MetaSet: ' + setName);
}
//get the sheet coordinates
this._metaAspectMembersCoordinatesPerSheet[setName] = {};
j = this._metaAspectMembersPerSheet[setName].length;
while (j--) {
gmeID = this._metaAspectMembersPerSheet[setName][j];
this._metaAspectMembersCoordinatesPerSheet[setName][gmeID] = aspectNode.getMemberRegistry(setName,
gmeID,
REGISTRY_KEYS.POSITION);
this._metaAspectSheetsPerMember[gmeID] = this._metaAspectSheetsPerMember[gmeID] || [];
this._metaAspectSheetsPerMember[gmeID].push(setName);
}
if (this._selectedMetaAspectSet &&
this._selectedMetaAspectSet === metaAspectSheetsRegistry[i].SetID) {
selectedSheetID = sheetID;
}
}
this.diagramDesigner.addMultipleTabsEnd();
//figure out whose position has changed
var positionUpdated = [];
if (this._selectedMetaAspectSet) {
var oldPositions = oldMetaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet];
var newPositions = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet];
if (oldPositions && newPositions) {
for (var oldItemId in oldPositions) {
if (oldPositions.hasOwnProperty(oldItemId) && newPositions.hasOwnProperty(oldItemId)) {
if (oldPositions[oldItemId].x !== newPositions[oldItemId].x ||
oldPositions[oldItemId].y !== newPositions[oldItemId].y) {
positionUpdated.push(oldItemId);
}
}
}
}
}
//setting selectedSheetID from global STATE
if (WebGMEGlobal.State.getActiveTab() !== null && WebGMEGlobal.State.getActiveTab() !== undefined &&
metaAspectSheetsRegistry.length > WebGMEGlobal.State.getActiveTab()) {
//only the active panel should react to the global state
if (WebGMEGlobal.PanelManager._activePanel.control === this) {
selectedSheetID = WebGMEGlobal.State.getActiveTab().toString();
} else {
for (selectedSheetID in this._sheets || {}) {
if (this._sheets[selectedSheetID] === this._selectedMetaAspectSet) {
break;
}
}
}
}
if (!selectedSheetID) {
for (selectedSheetID in this._sheets) {
if (this._sheets.hasOwnProperty(selectedSheetID)) {
break;
}
}
}
this._selectedSheetID = selectedSheetID;
this.diagramDesigner.selectTab(selectedSheetID);
return positionUpdated;
};
MetaEditorControl.prototype._initializeSelectedSheet = function () {
var len,
self = this;
this.logger.debug('_initializeSelectedSheet');
//delete everything from model editor
this.diagramDesigner.clear();
//clean up local hash map
this._GMENodes = [];
this._GMEID2ComponentID = {};
this._ComponentID2GMEID = {};
this._connectionWaitingListByDstGMEID = {};
this._connectionWaitingListBySrcGMEID = {};
this._connectionListBySrcGMEID = {};
this._connectionListByDstGMEID = {};
this._connectionListByType = {};
this._connectionListByID = {};
this._nodeMetaContainment = {};
this._nodeMetaPointers = {};
this._nodeMetaSets = {};
this._nodeMetaInheritance = {};
this._nodeMixins = [];
this._selectedMetaAspectSheetMembers = [];
this._filteredOutConnectionDescriptors = {};
len = this._filteredOutConnTypes.length;
while (len--) {
this._filteredOutConnectionDescriptors[this._filteredOutConnTypes[len]] = [];
}
//remove current territory patterns
if (this._metaAspectMembersTerritoryId) {
this._client.removeUI(this._metaAspectMembersTerritoryId);
}
this._metaAspectMemberPatterns = {};
if (this._selectedMetaAspectSet && this._metaAspectMembersPerSheet[this._selectedMetaAspectSet]) {
len = this._metaAspectMembersPerSheet[this._selectedMetaAspectSet].length;
if (len > 0) {
this.diagramDesigner.showProgressbar();
}
while (len--) {
this._selectedMetaAspectSheetMembers.push(
this._metaAspectMembersPerSheet[this._selectedMetaAspectSet][len]);
this._metaAspectMemberPatterns[this._metaAspectMembersPerSheet[this._selectedMetaAspectSet][len]] =
{children: 0};
}
}
this._metaAspectMembersTerritoryId = this._client.addUI(this, function (events) {
self._eventCallback(events);
});
this._client.updateTerritory(this._metaAspectMembersTerritoryId, this._metaAspectMemberPatterns);
};
MetaEditorControl.prototype.setReadOnly = function (isReadOnly) {
this._radioButtonGroupMetaRelationType.enabled(!isReadOnly);
};
//attach MetaEditorControl - DiagramDesigner event handler functions
_.extend(MetaEditorControl.prototype, MetaEditorControlDiagramDesignerWidgetEventHandlers.prototype);
return MetaEditorControl;
});
| src/client/js/Panels/MetaEditor/MetaEditorControl.js | /*globals define, _, WebGMEGlobal*/
/*jshint browser: true */
/**
* @author rkereskenyi / https://github.com/rkereskenyi
*/
define(['js/logger',
'js/util',
'js/Constants',
'js/Utils/GMEConcepts',
'js/NodePropertyNames',
'js/RegistryKeys',
'js/Widgets/DiagramDesigner/DiagramDesignerWidget.Constants',
'./MetaEditorControl.DiagramDesignerWidgetEventHandlers',
'./MetaRelations',
'./MetaEditorConstants',
'js/Utils/PreferencesHelper',
'js/Controls/AlignMenu'
], function (Logger,
util,
CONSTANTS,
GMEConcepts,
nodePropertyNames,
REGISTRY_KEYS,
DiagramDesignerWidgetConstants,
MetaEditorControlDiagramDesignerWidgetEventHandlers,
MetaRelations,
MetaEditorConstants,
PreferencesHelper,
AlignMenu) {
'use strict';
var MetaEditorControl,
META_DECORATOR = 'MetaDecorator',
WIDGET_NAME = 'DiagramDesigner',
META_RULES_CONTAINER_NODE_ID = MetaEditorConstants.META_ASPECT_CONTAINER_ID;
MetaEditorControl = function (options) {
var self = this;
this.logger = options.logger || Logger.create(options.loggerName || 'gme:Panels:MetaEditor:MetaEditorControl',
WebGMEGlobal.gmeConfig.client.log);
this._client = options.client;
//initialize core collections and variables
this.diagramDesigner = options.widget;
this._alignMenu = new AlignMenu(this.diagramDesigner.CONSTANTS, {});
if (this._client === undefined) {
this.logger.error('MetaEditorControl\'s client is not specified...');
throw ('MetaEditorControl can not be created');
}
if (this.diagramDesigner === undefined) {
this.logger.error('MetaEditorControl\'s DiagramDesigner is not specified...');
throw ('MetaEditorControl can not be created');
}
//in METAEDITOR mode DRAG & COPY is not enabled
this.diagramDesigner.enableDragCopy(false);
this._metaAspectMemberPatterns = {};
this._filteredOutConnTypes = [];
this._filteredOutConnectionDescriptors = {};
//local variable holding info about the currently opened node
this.currentNodeInfo = {id: null, members: []};
this._metaAspectMembersAll = [];
this._metaAspectMembersPerSheet = {};
this._metaAspectMembersCoordinatesGlobal = {};
this._metaAspectMembersCoordinatesPerSheet = {};
this._selectedMetaAspectSheetMembers = [];
this._selectedSheetID = null;
//set default connection type to containment
this._setNewConnectionType(MetaRelations.META_RELATIONS.CONTAINMENT);
this._initFilterPanel();
//attach all the event handlers for event's coming from DiagramDesigner
this.attachDiagramDesignerWidgetEventHandlers();
//let the decorator-manager download the required decorator
this._client.decoratorManager.download([META_DECORATOR], WIDGET_NAME, function () {
self.logger.debug('MetaEditorControl ctor finished');
//load meta container node
//give the UI time to render first before start using it's features
setTimeout(function () {
self._loadMetaAspectContainerNode();
}, 10);
});
};
MetaEditorControl.prototype._loadMetaAspectContainerNode = function () {
var self = this;
this.metaAspectContainerNodeID = META_RULES_CONTAINER_NODE_ID;
this.logger.debug('_loadMetaAspectContainerNode: "' + this.metaAspectContainerNodeID + '"');
this._initializeSelectedSheet();
//remove current territory patterns
if (this._territoryId) {
this._client.removeUI(this._territoryId);
}
//put new node's info into territory rules
this._selfPatterns = {};
this._selfPatterns[this.metaAspectContainerNodeID] = {children: 0};
//create and set territory
this._territoryId = this._client.addUI(this, function (events) {
self._eventCallback(events);
});
this._client.updateTerritory(this._territoryId, this._selfPatterns);
};
/**********************************************************/
/* PUBLIC METHODS */
/**********************************************************/
MetaEditorControl.prototype._eventCallback = function (events) {
var i = events ? events.length : 0,
e;
this.logger.debug('_eventCallback "' + i + '" items');
this.diagramDesigner.beginUpdate();
while (i--) {
e = events[i];
switch (e.etype) {
case CONSTANTS.TERRITORY_EVENT_LOAD:
this._onLoad(e.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UPDATE:
this._onUpdate(e.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UNLOAD:
this._onUnload(e.eid);
break;
default:
break;
}
}
this.diagramDesigner.endUpdate();
this.diagramDesigner.hideProgressbar();
this.logger.debug('_eventCallback "' + events.length + '" items - DONE');
};
//might not be the best approach
MetaEditorControl.prototype.destroy = function () {
this._detachClientEventListeners();
this._client.removeUI(this._territoryId);
this._client.removeUI(this._metaAspectMembersTerritoryId);
this.diagramDesigner.clear();
};
/**********************************************************/
/* LOAD / UPDATE / UNLOAD HANDLER */
/**********************************************************/
MetaEditorControl.prototype._onLoad = function (gmeID) {
if (gmeID === this.metaAspectContainerNodeID) {
this._processMetaAspectContainerNode();
} else {
this._processNodeLoad(gmeID);
}
};
MetaEditorControl.prototype._onUpdate = function (gmeID) {
if (gmeID === this.metaAspectContainerNodeID) {
this._processMetaAspectContainerNode();
} else {
this._processNodeUpdate(gmeID);
}
};
MetaEditorControl.prototype._onUnload = function (gmeID) {
var self = this;
if (gmeID === this.metaAspectContainerNodeID) {
//the opened model has been deleted....
//most probably a project / branch / whatever change
this.logger.debug('The currently opened aspect has been deleted --- GMEID: "' +
this.metaAspectContainerNodeID + '"');
setTimeout(function () {
self._loadMetaAspectContainerNode();
}, 10);
} else {
this._processNodeUnload(gmeID);
}
};
/**********************************************************/
/* END OF --- LOAD / UPDATE / UNLOAD HANDLER */
/**********************************************************/
/**********************************************************/
/* CUSTOM BUTTON EVENT HANDLERS */
/**********************************************************/
MetaEditorControl.prototype._printNodeData = function () {
//TODO could be filled with meaningful info
};
/**********************************************************/
/* END OF --- CUSTOM BUTTON EVENT HANDLERS */
/**********************************************************/
/***********************************************************/
/* PROCESS CURRENT NODE TO HANDLE ADDED / REMOVED ELEMENT */
/***********************************************************/
MetaEditorControl.prototype._processMetaAspectContainerNode = function () {
var aspectNodeID = this.metaAspectContainerNodeID,
aspectNode = this._client.getNode(aspectNodeID),
len,
diff,
objDesc,
componentID,
gmeID,
metaAspectSetMembers = aspectNode.getMemberIds(MetaEditorConstants.META_ASPECT_SET_NAME),
territoryChanged = false,
selectedSheetMembers,
positionsUpdated;
//this._metaAspectMembersAll contains all the currently known members of the meta aspect
//update current member list
this._metaAspectMembersAll = metaAspectSetMembers.slice(0);
len = this._metaAspectMembersAll.length;
this._metaAspectMembersCoordinatesGlobal = {};
while (len--) {
gmeID = this._metaAspectMembersAll[len];
this._metaAspectMembersCoordinatesGlobal[gmeID] = aspectNode.getMemberRegistry(
MetaEditorConstants.META_ASPECT_SET_NAME,
gmeID,
REGISTRY_KEYS.POSITION);
}
//setSelected sheet
//this._selectedMetaAspectSet
//process the sheets
positionsUpdated = this._processMetaAspectSheetsRegistry();
this.logger.debug('_metaAspectMembersAll: \n' + JSON.stringify(this._metaAspectMembersAll));
this.logger.debug('_metaAspectMembersCoordinatesGlobal: \n' +
JSON.stringify(this._metaAspectMembersCoordinatesGlobal));
this.logger.debug('_metaAspectMembersPerSheet: \n' + JSON.stringify(this._metaAspectMembersPerSheet));
this.logger.debug('_metaAspectMembersCoordinatesPerSheet: \n' +
JSON.stringify(this._metaAspectMembersCoordinatesPerSheet));
//check to see if the territory needs to be changed
//the territory contains the nodes that are on the currently opened sheet
//this._selectedMetaAspectSheetMembers
selectedSheetMembers = this._metaAspectMembersPerSheet[this._selectedMetaAspectSet] || [];
//check deleted nodes
diff = _.difference(this._selectedMetaAspectSheetMembers, selectedSheetMembers);
len = diff.length;
while (len--) {
delete this._metaAspectMemberPatterns[diff[len]];
territoryChanged = true;
}
//check added nodes
diff = _.difference(selectedSheetMembers, this._selectedMetaAspectSheetMembers);
len = diff.length;
while (len--) {
this._metaAspectMemberPatterns[diff[len]] = {children: 0};
territoryChanged = true;
}
//check all other nodes for position change
//or any other change that could have happened (local registry modifications)
//diff = positionsUpdated;//_.intersection(this._selectedMetaAspectSheetMembers, selectedSheetMembers);
diff = _.intersection(this._selectedMetaAspectSheetMembers, selectedSheetMembers);
len = diff.length;
while (len--) {
gmeID = diff[len];
objDesc = {position: {x: 100, y: 100}};
if (this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID]) {
objDesc.position.x = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].x;
objDesc.position.y = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].y;
}
if (this._GMEID2ComponentID.hasOwnProperty(gmeID)) {
componentID = this._GMEID2ComponentID[gmeID];
this.diagramDesigner.updateDesignerItem(componentID, objDesc);
}
}
this._selectedMetaAspectSheetMembers = selectedSheetMembers.slice(0);
//there was change in the territory
if (territoryChanged === true) {
this._client.updateTerritory(this._metaAspectMembersTerritoryId, this._metaAspectMemberPatterns);
}
};
/**********************************************************************/
/* END OF --- PROCESS CURRENT NODE TO HANDLE ADDED / REMOVED ELEMENT */
/**********************************************************************/
/**************************************************************************/
/* HANDLE OBJECT LOAD --- DISPLAY IT WITH ALL THE POINTERS / SETS / ETC */
/**************************************************************************/
MetaEditorControl.prototype._processNodeLoad = function (gmeID) {
var uiComponent,
decClass,
objDesc;
//component loaded
if (this._GMENodes.indexOf(gmeID) === -1) {
//aspect's member has been loaded
objDesc = {position: {x: 100, y: 100}};
if (this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID]) {
objDesc.position.x = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].x;
objDesc.position.y = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet][gmeID].y;
}
decClass = this._client.decoratorManager.getDecoratorForWidget(META_DECORATOR, WIDGET_NAME);
objDesc.decoratorClass = decClass;
objDesc.control = this;
objDesc.metaInfo = {};
objDesc.metaInfo[CONSTANTS.GME_ID] = gmeID;
//each meta specific registry customization will be stored in the MetaContainer node's main META SET
// (MetaEditorConstants.META_ASPECT_SET_NAME)
objDesc.preferencesHelper = PreferencesHelper.getPreferences([{
containerID: this.metaAspectContainerNodeID,
setID: MetaEditorConstants.META_ASPECT_SET_NAME
}]);
uiComponent = this.diagramDesigner.createDesignerItem(objDesc);
this._GMENodes.push(gmeID);
this._GMEID2ComponentID[gmeID] = uiComponent.id;
this._ComponentID2GMEID[uiComponent.id] = gmeID;
//process new node to display containment / pointers / inheritance / sets as connections
this._processNodeMetaContainment(gmeID);
this._processNodeMetaPointers(gmeID, false);
this._processNodeMetaInheritance(gmeID);
this._processNodeMixins(gmeID);
this._processNodeMetaPointers(gmeID, true);
//check all the waiting pointers (whose SRC/DST is already displayed and waiting for the DST/SRC to show up)
//it might be this new node
this._processConnectionWaitingList(gmeID);
}
};
MetaEditorControl.prototype._processConnectionWaitingList = function (gmeID) {
var len,
gmeSrcID,
gmeDstID,
connType,
connTexts,
c = [];
//check for possible endpoint as gmeID
gmeDstID = gmeID;
if (this._connectionWaitingListByDstGMEID && this._connectionWaitingListByDstGMEID.hasOwnProperty(gmeDstID)) {
for (gmeSrcID in this._connectionWaitingListByDstGMEID[gmeDstID]) {
if (this._connectionWaitingListByDstGMEID[gmeDstID].hasOwnProperty(gmeSrcID)) {
len = this._connectionWaitingListByDstGMEID[gmeDstID][gmeSrcID].length;
while (len--) {
connType = this._connectionWaitingListByDstGMEID[gmeDstID][gmeSrcID][len][0];
connTexts = this._connectionWaitingListByDstGMEID[gmeDstID][gmeSrcID][len][1];
c.push({
gmeSrcID: gmeSrcID,
gmeDstID: gmeDstID,
connType: connType,
connTexts: connTexts
});
}
}
}
delete this._connectionWaitingListByDstGMEID[gmeDstID];
}
//check for possible source as gmeID
gmeSrcID = gmeID;
if (this._connectionWaitingListBySrcGMEID && this._connectionWaitingListBySrcGMEID.hasOwnProperty(gmeSrcID)) {
for (gmeDstID in this._connectionWaitingListBySrcGMEID[gmeSrcID]) {
if (this._connectionWaitingListBySrcGMEID[gmeSrcID].hasOwnProperty(gmeDstID)) {
len = this._connectionWaitingListBySrcGMEID[gmeSrcID][gmeDstID].length;
while (len--) {
connType = this._connectionWaitingListBySrcGMEID[gmeSrcID][gmeDstID][len][0];
connTexts = this._connectionWaitingListBySrcGMEID[gmeSrcID][gmeDstID][len][1];
c.push({
gmeSrcID: gmeSrcID,
gmeDstID: gmeDstID,
connType: connType,
connTexts: connTexts
});
}
}
}
delete this._connectionWaitingListBySrcGMEID[gmeSrcID];
}
len = c.length;
while (len--) {
gmeSrcID = c[len].gmeSrcID;
gmeDstID = c[len].gmeDstID;
connType = c[len].connType;
connTexts = c[len].connTexts;
this._createConnection(gmeSrcID, gmeDstID, connType, connTexts);
}
};
/**************************************************************************/
/* END OF --- HANDLE OBJECT LOAD DISPLAY IT WITH ALL THE POINTERS / ... */
/**************************************************************************/
/****************************************************************************/
/* HANDLE OBJECT UNLOAD --- DISPLAY IT WITH ALL THE POINTERS / SETS / ETC */
/****************************************************************************/
MetaEditorControl.prototype._processNodeUnload = function (gmeID) {
var componentID,
idx,
len,
i,
otherEnd,
pointerName,
aConns,
connectionID;
if (this._GMEID2ComponentID.hasOwnProperty(gmeID)) {
componentID = this._GMEID2ComponentID[gmeID];
//gather all the information that is stored in this node's META
//CONTAINMENT
len = this._nodeMetaContainment[gmeID].targets.length;
while (len--) {
otherEnd = this._nodeMetaContainment[gmeID].targets[len];
this._removeConnection(gmeID, otherEnd, MetaRelations.META_RELATIONS.CONTAINMENT);
}
//POINTERS
len = this._nodeMetaPointers[gmeID].combinedNames.length;
while (len--) {
pointerName = this._nodeMetaPointers[gmeID].combinedNames[len];
otherEnd = this._nodeMetaPointers[gmeID][pointerName].target;
pointerName = this._nodeMetaPointers[gmeID][pointerName].name;
this._removeConnection(gmeID, otherEnd, MetaRelations.META_RELATIONS.POINTER, pointerName);
}
//INHERITANCE
if (this._nodeMetaInheritance[gmeID] && !_.isEmpty(this._nodeMetaInheritance[gmeID])) {
this._removeConnection(this._nodeMetaInheritance[gmeID],
gmeID,
MetaRelations.META_RELATIONS.INHERITANCE);
}
//MIXINS
for (i = 0; i < this._nodeMixins[gmeID].length; i += 1) {
this._removeConnection(gmeID, this._nodeMixins[gmeID][i], MetaRelations.META_RELATIONS.MIXIN);
}
//POINTER LISTS
len = this._nodeMetaSets[gmeID].combinedNames.length;
while (len--) {
pointerName = this._nodeMetaSets[gmeID].combinedNames[len];
otherEnd = this._nodeMetaSets[gmeID][pointerName].target;
pointerName = this._nodeMetaSets[gmeID][pointerName].name;
this._removeConnection(gmeID, otherEnd, MetaRelations.META_RELATIONS.SET, pointerName);
}
//finally delete the guy from the screen
this.diagramDesigner.deleteComponent(componentID);
delete this._ComponentID2GMEID[componentID];
delete this._GMEID2ComponentID[gmeID];
idx = this._GMENodes.indexOf(gmeID);
this._GMENodes.splice(idx, 1);
//check if there is any more connection present that's associated with this object
//typically the connection end is this guy
//if so, remove but save to savedList
aConns = this._getAssociatedConnections(gmeID);
len = aConns.src.length;
while (len--) {
connectionID = aConns.src[len];
//save the connection to the waiting list, since the destination is still there
this._saveConnectionToWaitingList(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type,
this._connectionListByID[connectionID].connTexts);
this._removeConnection(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type);
}
len = aConns.dst.length;
while (len--) {
connectionID = aConns.dst[len];
if (this._connectionListByID[connectionID]) {
//save the connection to the waiting list, since the destination is still there
this._saveConnectionToWaitingList(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type,
this._connectionListByID[connectionID].connTexts);
this._removeConnection(this._connectionListByID[connectionID].GMESrcId,
this._connectionListByID[connectionID].GMEDstId,
this._connectionListByID[connectionID].type);
}
}
//check the waiting list and remove any connection that was waiting and this end was present
for (otherEnd in this._connectionWaitingListBySrcGMEID) {
if (this._connectionWaitingListBySrcGMEID.hasOwnProperty(otherEnd)) {
delete this._connectionWaitingListBySrcGMEID[otherEnd][gmeID];
if (_.isEmpty(this._connectionWaitingListBySrcGMEID[otherEnd])) {
delete this._connectionWaitingListBySrcGMEID[otherEnd];
}
}
}
for (otherEnd in this._connectionWaitingListByDstGMEID) {
if (this._connectionWaitingListByDstGMEID.hasOwnProperty(otherEnd)) {
delete this._connectionWaitingListByDstGMEID[otherEnd][gmeID];
if (_.isEmpty(this._connectionWaitingListByDstGMEID[otherEnd])) {
delete this._connectionWaitingListByDstGMEID[otherEnd];
}
}
}
//keep up accounting
delete this._nodeMetaContainment[gmeID];
delete this._nodeMetaPointers[gmeID];
delete this._nodeMetaInheritance[gmeID];
delete this._nodeMixins[gmeID];
delete this._nodeMetaSets[gmeID];
}
};
/****************************************************************************/
/* END OF --- HANDLE OBJECT UNLOAD */
/****************************************************************************/
/****************************************************************************/
/* CREATE A SPECIFIC TYPE OF CONNECTION BETWEEN 2 GME OBJECTS */
/****************************************************************************/
MetaEditorControl.prototype._createConnection = function (gmeSrcId, gmeDstId, connType, connTexts) {
var connDesc,
connComponent,
metaInfo;
//need to check if the src and dst objects are displayed or not
//if YES, create connection
//if NO, store information in a waiting queue
if (this._GMENodes.indexOf(gmeSrcId) !== -1 && this._GMENodes.indexOf(gmeDstId) !== -1) {
//source and destination is displayed
if (this._filteredOutConnTypes.indexOf(connType) === -1) {
//connection type is not filtered out
connDesc = {
srcObjId: this._GMEID2ComponentID[gmeSrcId],
srcSubCompId: undefined,
dstObjId: this._GMEID2ComponentID[gmeDstId],
dstSubCompId: undefined,
reconnectable: false,
name: '',
nameEdit: false
};
//set visual properties
_.extend(connDesc, MetaRelations.getLineVisualDescriptor(connType));
//fill out texts
if (connTexts) {
_.extend(connDesc, connTexts);
}
connComponent = this.diagramDesigner.createConnection(connDesc);
//set connection metaInfo and store connection type
//the MetaDecorator uses this information when queried for connectionArea
metaInfo = {};
metaInfo[MetaRelations.CONNECTION_META_INFO.TYPE] = connType;
connComponent.setMetaInfo(metaInfo);
this._saveConnection(gmeSrcId, gmeDstId, connType, connComponent.id, connTexts);
} else {
//connection type is filtered out
this._filteredOutConnectionDescriptors[connType].push([gmeSrcId, gmeDstId, connTexts]);
}
} else {
//source or destination is not displayed, store it in a queue
this._saveConnectionToWaitingList(gmeSrcId, gmeDstId, connType, connTexts);
}
};
MetaEditorControl.prototype._saveConnectionToWaitingList = function (gmeSrcId, gmeDstId, connType, connTexts) {
if (this._GMENodes.indexOf(gmeSrcId) !== -1 && this._GMENodes.indexOf(gmeDstId) === -1) {
//#1 - the destination object is missing from the screen
this._connectionWaitingListByDstGMEID[gmeDstId] = this._connectionWaitingListByDstGMEID[gmeDstId] || {};
this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId] =
this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId] || [];
this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId].push([connType, connTexts]);
} else if (this._GMENodes.indexOf(gmeSrcId) === -1 && this._GMENodes.indexOf(gmeDstId) !== -1) {
//#2 - the source object is missing from the screen
this._connectionWaitingListBySrcGMEID[gmeSrcId] = this._connectionWaitingListBySrcGMEID[gmeSrcId] || {};
this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId] =
this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId] || [];
this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId].push([connType, connTexts]);
} else {
//#3 - both gmeSrcId and gmeDstId is missing from the screen
//NOTE: this should never happen!!!
this.logger.error('_saveConnectionToWaitingList both gmeSrcId and gmeDstId is undefined...');
}
};
MetaEditorControl.prototype._saveConnection = function (gmeSrcId, gmeDstId, connType, connComponentId, connTexts) {
//save by SRC
this._connectionListBySrcGMEID[gmeSrcId] = this._connectionListBySrcGMEID[gmeSrcId] || {};
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId] = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId] || {};
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType] =
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType] || [];
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].push(connComponentId);
//save by DST
this._connectionListByDstGMEID[gmeDstId] = this._connectionListByDstGMEID[gmeDstId] || {};
this._connectionListByDstGMEID[gmeDstId][gmeSrcId] = this._connectionListByDstGMEID[gmeDstId][gmeSrcId] || {};
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType] =
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType] || [];
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType].push(connComponentId);
//save by type
this._connectionListByType[connType] = this._connectionListByType[connType] || [];
this._connectionListByType[connType].push(connComponentId);
//save by connectionID
this._connectionListByID[connComponentId] = {
GMESrcId: gmeSrcId,
GMEDstId: gmeDstId,
type: connType,
name: (connTexts && connTexts.name) ? connTexts.name : undefined,
connTexts: connTexts
};
};
/****************************************************************************/
/* END OF --- CREATE A SPECIFIC TYPE OF CONNECTION BETWEEN 2 GME OBJECTS */
/****************************************************************************/
/****************************************************************************/
/* REMOVES A SPECIFIC TYPE OF CONNECTION FROM 2 GME OBJECTS */
/****************************************************************************/
MetaEditorControl.prototype._removeConnection = function (gmeSrcId, gmeDstId, connType, pointerName) {
var connectionID,
idx,
len,
connectionPresent = false;
//only bother if
//- both the source and destination is present on the screen
//the connection in question is drawn
if (this._connectionListBySrcGMEID[gmeSrcId] &&
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId] &&
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType]) {
connectionPresent = true;
}
if (!connectionPresent) {
return;
}
len = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].length;
while (len--) {
connectionID = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType][len];
//if a pointer with a specific name should be removed
//clear out the connectionID if this connection is not the representation of that pointer
if (connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
this._connectionListByID[connectionID].name !== pointerName) {
connectionID = undefined;
}
//if the connectionID is still valid
if (connectionID) {
this.diagramDesigner.deleteComponent(connectionID);
//clean up accounting
delete this._connectionListByID[connectionID];
idx = this._connectionListByType[connType].indexOf(connectionID);
this._connectionListByType[connType].splice(idx, 1);
idx = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].indexOf(connectionID);
this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].splice(idx, 1);
idx = this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType].indexOf(connectionID);
this._connectionListByDstGMEID[gmeDstId][gmeSrcId][connType].splice(idx, 1);
}
}
};
/****************************************************************************/
/* END OF --- REMOVES A SPECIFIC TYPE OF CONNECTION FROM 2 GME OBJECTS */
/****************************************************************************/
/*****************************************************************************/
/* UPDATE CONNECTION TEXT */
/*****************************************************************************/
MetaEditorControl.prototype._updateConnectionText = function (gmeSrcId, gmeDstId, connType, connTexts) {
var connectionID,
idx,
len = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType].length,
pointerName = connTexts.name,
found = false,
connDesc;
while (len--) {
connectionID = this._connectionListBySrcGMEID[gmeSrcId][gmeDstId][connType][len];
//if a pointer with a specific name should be removed
//clear out the connectionID if this connection is not the representation of that pointer
if (connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
this._connectionListByID[connectionID].name !== pointerName) {
connectionID = undefined;
}
//if the connectionID is still valid
if (connectionID) {
this._connectionListByID[connectionID].name = connTexts.name;
this._connectionListByID[connectionID].connTexts = connTexts;
this.diagramDesigner.updateConnectionTexts(connectionID, connTexts);
found = true;
}
}
if (!found) {
//try to find it in the connection waiting list
if (this._GMENodes.indexOf(gmeSrcId) !== -1 && this._GMENodes.indexOf(gmeDstId) === -1) {
//#1 - the destination object is missing from the screen
len = this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId].length;
for (idx = 0; idx < len; idx += 1) {
connDesc = this._connectionWaitingListByDstGMEID[gmeDstId][gmeSrcId][idx];
if (connDesc[0] === connType) {
if (connType !== MetaRelations.META_RELATIONS.POINTER ||
(connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
connDesc[1].name === pointerName)) {
connDesc[1] = connTexts;
}
}
}
} else if (this._GMENodes.indexOf(gmeSrcId) === -1 && this._GMENodes.indexOf(gmeDstId) !== -1) {
//#2 - the source object is missing from the screen
len = this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId].length;
for (idx = 0; idx < len; idx += 1) {
connDesc = this._connectionWaitingListBySrcGMEID[gmeSrcId][gmeDstId][idx];
if (connDesc[0] === connType) {
if (connType !== MetaRelations.META_RELATIONS.POINTER ||
(connType === MetaRelations.META_RELATIONS.POINTER &&
pointerName &&
pointerName !== '' &&
connDesc[1].name === pointerName)) {
connDesc[1] = connTexts;
}
}
}
} else {
//#3 - both gmeSrcId and gmeDstId is missing from the screen
}
}
};
/*****************************************************************************/
/* END OF --- UPDATE CONNECTION TEXT */
/*****************************************************************************/
/**************************************************************************/
/* HANDLE OBJECT UPDATE --- DISPLAY IT WITH ALL THE POINTERS / SETS / ETC */
/**************************************************************************/
MetaEditorControl.prototype._processNodeUpdate = function (gmeID) {
var componentID,
decClass,
objDesc = {};
if (this._GMEID2ComponentID.hasOwnProperty(gmeID)) {
componentID = this._GMEID2ComponentID[gmeID];
decClass = this._client.decoratorManager.getDecoratorForWidget(META_DECORATOR, WIDGET_NAME);
objDesc.decoratorClass = decClass;
objDesc.preferencesHelper = PreferencesHelper.getPreferences([{
containerID: this.metaAspectContainerNodeID,
setID: MetaEditorConstants.META_ASPECT_SET_NAME
}]);
this.diagramDesigner.updateDesignerItem(componentID, objDesc);
//update set relations
this._processNodeMetaContainment(gmeID);
this._processNodeMetaPointers(gmeID, false);
this._processNodeMetaInheritance(gmeID);
this._processNodeMixins(gmeID);
this._processNodeMetaPointers(gmeID, true);
}
};
/**************************************************************************/
/* END OF --- HANDLE OBJECT UPDATE */
/**************************************************************************/
/***********************************************************************************/
/* DISPLAY META CONTAINMENT RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/***********************************************************************************/
MetaEditorControl.prototype._processNodeMetaContainment = function (gmeID) {
var containmentMetaDescriptor = this._client.getValidChildrenItems(gmeID) || [],
containmentOwnTypes = this._client.getOwnValidChildrenTypes(gmeID) || [],
len,
oldMetaContainment,
newMetaContainment = {targets: []},
diff,
containmentTarget,
idx;
this._nodeMetaContainment[gmeID] = this._nodeMetaContainment[gmeID] || {targets: []};
oldMetaContainment = this._nodeMetaContainment[gmeID];
len = containmentMetaDescriptor.length;
while (len--) {
if (containmentOwnTypes.indexOf(containmentMetaDescriptor[len].id) !== -1) {
newMetaContainment.targets.push(containmentMetaDescriptor[len].id);
newMetaContainment[containmentMetaDescriptor[len].id] = {
multiplicity: '' + (containmentMetaDescriptor[len].min || 0) + '..' +
(containmentMetaDescriptor[len].max || '*')
};
}
}
//compute updated connections
diff = _.intersection(oldMetaContainment.targets, newMetaContainment.targets);
len = diff.length;
while (len--) {
containmentTarget = diff[len];
if (oldMetaContainment[containmentTarget].multiplicity !==
newMetaContainment[containmentTarget].multiplicity) {
//update accounting
oldMetaContainment[containmentTarget].multiplicity = newMetaContainment[containmentTarget].multiplicity;
//update connection text
this._updateConnectionText(gmeID, containmentTarget, MetaRelations.META_RELATIONS.CONTAINMENT, {
dstText: newMetaContainment[containmentTarget].multiplicity,
dstTextEdit: true
});
}
}
//compute deleted pointers
diff = _.difference(oldMetaContainment.targets, newMetaContainment.targets);
len = diff.length;
while (len--) {
containmentTarget = diff[len];
this._removeConnection(gmeID, containmentTarget, MetaRelations.META_RELATIONS.CONTAINMENT);
idx = oldMetaContainment.targets.indexOf(containmentTarget);
oldMetaContainment.targets.splice(idx, 1);
delete oldMetaContainment[containmentTarget];
}
//compute added pointers
diff = _.difference(newMetaContainment.targets, oldMetaContainment.targets);
len = diff.length;
while (len--) {
containmentTarget = diff[len];
oldMetaContainment.targets.push(containmentTarget);
oldMetaContainment[containmentTarget] = {multiplicity: newMetaContainment[containmentTarget].multiplicity};
this._createConnection(gmeID, containmentTarget, MetaRelations.META_RELATIONS.CONTAINMENT, {
dstText: newMetaContainment[containmentTarget].multiplicity,
dstTextEdit: true
});
}
};
/**********************************************************************************************/
/* END OF --- DISPLAY META CONTAINMENT RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/**********************************************************************************************/
/*******************************************************************************/
/* DISPLAY META POINTER RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/*******************************************************************************/
MetaEditorControl.prototype._processNodeMetaPointers = function (gmeID, isSet) {
var node = this._client.getNode(gmeID),
pointerNames = isSet === true ? node.getValidSetNames() : node.getValidPointerNames(),
pointerMetaDescriptor,
pointerOwnMetaTypes,
len,
oldMetaPointers,
newMetaPointers = {names: [], combinedNames: []},
diff,
pointerTarget,
pointerName,
idx,
lenTargets,
combinedName,
ptrType = isSet === true ? MetaRelations.META_RELATIONS.SET : MetaRelations.META_RELATIONS.POINTER;
if (isSet !== true) {
this._nodeMetaPointers[gmeID] = this._nodeMetaPointers[gmeID] || {names: [], combinedNames: []};
oldMetaPointers = this._nodeMetaPointers[gmeID];
} else {
this._nodeMetaSets[gmeID] = this._nodeMetaSets[gmeID] || {names: [], combinedNames: []};
oldMetaPointers = this._nodeMetaSets[gmeID];
}
len = pointerNames.length;
while (len--) {
pointerMetaDescriptor = this._client.getValidTargetItems(gmeID, pointerNames[len]);
pointerOwnMetaTypes = this._client.getOwnValidTargetTypes(gmeID, pointerNames[len]);
if (pointerMetaDescriptor) {
lenTargets = pointerMetaDescriptor.length;
while (lenTargets--) {
if (pointerOwnMetaTypes.indexOf(pointerMetaDescriptor[lenTargets].id) !== -1) {
combinedName = pointerNames[len] + '_' + pointerMetaDescriptor[lenTargets].id;
newMetaPointers.names.push(pointerNames[len]);
newMetaPointers.combinedNames.push(combinedName);
newMetaPointers[combinedName] = {
name: pointerNames[len],
target: pointerMetaDescriptor[lenTargets].id
};
if (isSet) {
newMetaPointers[combinedName].multiplicity = '' +
(pointerMetaDescriptor[lenTargets].min || 0) +
'..' +
(pointerMetaDescriptor[lenTargets].max || '*');
}
}
}
}
}
//compute updated connections
diff = _.intersection(oldMetaPointers.combinedNames, newMetaPointers.combinedNames);
len = diff.length;
while (len--) {
combinedName = diff[len];
if (oldMetaPointers[combinedName].multiplicity !== newMetaPointers[combinedName].multiplicity) {
pointerName = oldMetaPointers[combinedName].name;
pointerTarget = oldMetaPointers[combinedName].target;
oldMetaPointers[combinedName].multiplicity = newMetaPointers[combinedName].multiplicity;
this._updateConnectionText(gmeID, pointerTarget, ptrType, {
name: pointerName,
dstText: newMetaPointers[combinedName].multiplicity,
dstTextEdit: true
});
}
}
//compute deleted pointers
diff = _.difference(oldMetaPointers.combinedNames, newMetaPointers.combinedNames);
len = diff.length;
while (len--) {
combinedName = diff[len];
pointerName = oldMetaPointers[combinedName].name;
pointerTarget = oldMetaPointers[combinedName].target;
this._removeConnection(gmeID, pointerTarget, ptrType, pointerName);
idx = oldMetaPointers.combinedNames.indexOf(combinedName);
oldMetaPointers.combinedNames.splice(idx, 1);
delete oldMetaPointers[combinedName];
}
//compute added pointers
diff = _.difference(newMetaPointers.combinedNames, oldMetaPointers.combinedNames);
len = diff.length;
while (len--) {
combinedName = diff[len];
pointerName = newMetaPointers[combinedName].name;
pointerTarget = newMetaPointers[combinedName].target;
oldMetaPointers.names.push(pointerName);
oldMetaPointers.combinedNames.push(combinedName);
oldMetaPointers[combinedName] = {
name: newMetaPointers[combinedName].name,
target: newMetaPointers[combinedName].target,
multiplicity: newMetaPointers[combinedName].multiplicity
};
this._createConnection(gmeID, pointerTarget, ptrType, {
name: pointerName,
dstText: newMetaPointers[combinedName].multiplicity,
dstTextEdit: true
});
}
};
/******************************************************************************************/
/* END OF --- DISPLAY META POINTER RELATIONS AS A CONNECTION FROM CONTAINER TO CONTAINED */
/******************************************************************************************/
/***********************************************************************************/
/* DISPLAY META INHERITANCE RELATIONS AS A CONNECTION FROM PARENT TO OBJECT */
/***********************************************************************************/
MetaEditorControl.prototype._processNodeMetaInheritance = function (gmeID) {
var node = this._client.getNode(gmeID),
oldMetaInheritance,
newMetaInheritance = node.getBaseId();
//if there was a valid old that's different than the current, delete the connection representing the old
oldMetaInheritance = this._nodeMetaInheritance[gmeID];
if (oldMetaInheritance && (oldMetaInheritance !== newMetaInheritance)) {
this._removeConnection(gmeID, oldMetaInheritance, MetaRelations.META_RELATIONS.INHERITANCE);
delete this._nodeMetaInheritance[gmeID];
}
if (newMetaInheritance && (oldMetaInheritance !== newMetaInheritance)) {
this._nodeMetaInheritance[gmeID] = newMetaInheritance;
this._createConnection(gmeID, newMetaInheritance, MetaRelations.META_RELATIONS.INHERITANCE, undefined);
}
};
/**********************************************************************************************/
/* END OF --- DISPLAY META CONTAINMENT RELATIONS AS A CONNECTION FROM PARENT TO OBJECT */
/**********************************************************************************************/
MetaEditorControl.prototype._processNodeMixins = function (gmeID) {
var node = this._client.getNode(gmeID),
oldMixins,
newMixins = node.getMixinPaths(),
i;
this.logger.debug('processing mixins for [' + gmeID + ']');
// If there was a valid old that's different than the current, delete the connection representing the old.
oldMixins = this._nodeMixins[gmeID] || [];
for (i = 0; i < oldMixins.length; i += 1) {
if (newMixins.indexOf(oldMixins[i]) === -1) {
this._removeConnection(gmeID, oldMixins[i], MetaRelations.META_RELATIONS.MIXIN);
}
}
for (i = 0; i < newMixins.length; i += 1) {
if (oldMixins.indexOf(newMixins[i]) === -1) {
this._createConnection(gmeID, newMixins[i], MetaRelations.META_RELATIONS.MIXIN, undefined);
}
}
this._nodeMixins[gmeID] = newMixins;
};
/****************************************************************************/
/* CREATE NEW CONNECTION BUTTONS AND THEIR EVENT HANDLERS */
/****************************************************************************/
MetaEditorControl.prototype._setNewConnectionType = function (connType) {
var connProps = MetaRelations.getLineVisualDescriptor(connType),
temp;
if (this._connType !== connType) {
this._connType = connType;
if (connType === MetaRelations.META_RELATIONS.CONTAINMENT) {
//for METACONTAINMENT AND INHERITANCE flip the visual end arrow style for drawing only
temp = connProps[DiagramDesignerWidgetConstants.LINE_START_ARROW];
connProps[DiagramDesignerWidgetConstants.LINE_START_ARROW] =
connProps[DiagramDesignerWidgetConstants.LINE_END_ARROW];
connProps[DiagramDesignerWidgetConstants.LINE_END_ARROW] = temp;
}
this.diagramDesigner.connectionDrawingManager.setConnectionInDrawProperties(connProps);
this.diagramDesigner.setFilterChecked(this._connType);
}
};
/****************************************************************************/
/* END OF --- CREATE NEW CONNECTION BUTTONS AND THEIR EVENT HANDLERS */
/****************************************************************************/
/****************************************************************************/
/* CREATE NEW CONNECTION BETWEEN TWO ITEMS */
/****************************************************************************/
MetaEditorControl.prototype._onCreateNewConnection = function (params) {
var sourceId = this._ComponentID2GMEID[params.src],
targetId = this._ComponentID2GMEID[params.dst];
switch (this._connType) {
case MetaRelations.META_RELATIONS.CONTAINMENT:
this._createContainmentRelationship(targetId, sourceId);
break;
case MetaRelations.META_RELATIONS.INHERITANCE:
this._createInheritanceRelationship(sourceId, targetId);
break;
case MetaRelations.META_RELATIONS.POINTER:
this._createPointerRelationship(sourceId, targetId, false);
break;
case MetaRelations.META_RELATIONS.SET:
this._createPointerRelationship(sourceId, targetId, true);
break;
case MetaRelations.META_RELATIONS.MIXIN:
this._createMixinRelationship(sourceId, targetId);
break;
default:
break;
}
};
MetaEditorControl.prototype._createContainmentRelationship = function (containerID, objectID) {
var containerNode = this._client.getNode(containerID),
objectNode = this._client.getNode(objectID);
if (containerNode && objectNode) {
this._client.updateValidChildrenItem(containerID, {id: objectID});
}
};
MetaEditorControl.prototype._deleteContainmentRelationship = function (containerID, objectID) {
var containerNode = this._client.getNode(containerID),
objectNode = this._client.getNode(objectID);
if (containerNode && objectNode) {
this._client.removeValidChildrenItem(containerID, objectID);
}
};
MetaEditorControl.prototype._createPointerRelationship = function (sourceID, targetID, isSet) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
pointerMetaDescriptor,
existingPointerNames,
notAllowedPointerNames,
self = this;
if (sourceNode && targetNode) {
notAllowedPointerNames = _.union(sourceNode.getSetNames(), sourceNode.getPointerNames());
if (isSet === true) {
//this is a pointer list
existingPointerNames = _.difference(sourceNode.getSetNames() || [],
this._client.getMetaAspectNames(sourceID));
} else {
//this is a single pointer
//get the list of existing pointers and show them in a dialog so the user can choose
existingPointerNames = sourceNode.getPointerNames() || [];
}
notAllowedPointerNames = _.difference(notAllowedPointerNames, existingPointerNames);
//handle RESERVED pointer names
existingPointerNames = _.difference(existingPointerNames, MetaEditorConstants.RESERVED_POINTER_NAMES);
notAllowedPointerNames = notAllowedPointerNames.concat(MetaEditorConstants.RESERVED_POINTER_NAMES);
//query pointer name from user
this.diagramDesigner.selectNewPointerName(existingPointerNames,
notAllowedPointerNames,
isSet,
function (userSelectedPointerName) {
self._client.startTransaction();
pointerMetaDescriptor = self._client.getOwnValidTargetItems(sourceID, userSelectedPointerName);
if (!pointerMetaDescriptor) {
if (isSet !== true) {
//single pointer
self._client.setPointerMeta(sourceID, userSelectedPointerName, {
min: 1,
max: 1,
items: [
{
id: targetID,
max: 1
}
]
});
self._client.makePointer(sourceID, userSelectedPointerName, null);
} else {
//pointer list
self._client.setPointerMeta(sourceID, userSelectedPointerName, {
items: [
{
id: targetID
}
]
});
self._client.createSet(sourceID, userSelectedPointerName);
}
} else {
if (isSet !== true) {
//single pointer
self._client.updateValidTargetItem(sourceID,
userSelectedPointerName,
{
id: targetID,
max: 1
});
} else {
//pointer list
self._client.updateValidTargetItem(sourceID, userSelectedPointerName, {id: targetID});
}
}
self._client.completeTransaction();
});
}
};
MetaEditorControl.prototype._deletePointerRelationship = function (sourceID, targetID, pointerName, isSet) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
pointerMetaDescriptor;
//NOTE: this method is called from inside a transaction, don't need to start/complete one
if (sourceNode && targetNode) {
this._client.removeValidTargetItem(sourceID, pointerName, targetID);
pointerMetaDescriptor = this._client.getValidTargetItems(sourceID, pointerName);
if (pointerMetaDescriptor && pointerMetaDescriptor.length === 0) {
if (isSet === false) {
//single pointer
this._client.deleteMetaPointer(sourceID, pointerName);
this._client.delPointer(sourceID, pointerName);
} else {
//pointer list
this._client.deleteMetaPointer(sourceID, pointerName);
this._client.deleteSet(sourceID, pointerName);
}
}
}
};
MetaEditorControl.prototype._createInheritanceRelationship = function (objectID, newBaseID) {
var newBaseNode = this._client.getNode(newBaseID),
objectNode = this._client.getNode(objectID),
objectBase;
if (newBaseNode && objectNode) {
objectBase = objectNode.getBaseId();
if (objectBase && !_.isEmpty(objectBase)) {
this.logger.debug('InheritanceRelationship from "' +
objectNode.getAttribute(nodePropertyNames.Attributes.name) +
'" (' + objectID + ') to parent "' + objectBase + '" already exists, but overwriting to "' +
newBaseNode.getAttribute(nodePropertyNames.Attributes.name) + '" (' + newBaseID + ')"');
}
this._client.setBase(objectID, newBaseID);
}
};
MetaEditorControl.prototype._deleteInheritanceRelationship = function (parentID, objectID) {
var objectNode = this._client.getNode(objectID),
objectBaseId,
baseNode;
if (objectNode) {
objectBaseId = objectNode.getBaseId();
if (objectBaseId) {
baseNode = this._client.getNode(objectBaseId);
if (baseNode) {
objectBaseId = baseNode.getAttribute(nodePropertyNames.Attributes.name) + ' (' + objectBaseId + ')';
}
/*this.logger.debug('Deleting InheritanceRelationship from "' +
objectNode.getAttribute(nodePropertyNames.Attributes.name) + '" (' + objectID + ') to parent "' +
objectBaseId + '"');
this._client.delBase(objectID);*/
//TEMPORARILY DO NOT ALLOW DELETING INHERITANCE RELATIONSHIP
this.logger.error('Deleting InheritanceRelationship from "' +
objectNode.getAttribute(nodePropertyNames.Attributes.name) + '" (' + objectID +
') to parent "' + objectBaseId + '" is not allowed...');
}
}
};
MetaEditorControl.prototype._createMixinRelationship = function (objectId, newMixinId) {
var newBaseNode = this._client.getNode(newMixinId),
objectNode = this._client.getNode(objectId),
objectBase;
if (newBaseNode && objectNode) {
this._client.addMixin(objectId, newMixinId);
} else {
this.logger.error('cannot set [' + newMixinId + '] as mixin for [' + objectId +
'] because not all node are loaded');
}
};
MetaEditorControl.prototype._deleteMixinRelationship = function (objectId, mixinToRemoveId) {
var newBaseNode = this._client.getNode(mixinToRemoveId),
objectNode = this._client.getNode(objectId),
objectBase;
if (newBaseNode && objectNode) {
this._client.delMixin(objectId, mixinToRemoveId);
} else {
this.logger.error('cannot remove [' + newMixinId + '] mixin from [' + objectId +
'] because not all node are loaded');
}
};
/****************************************************************************/
/* END OF --- CREATE NEW CONNECTION BETWEEN TWO ITEMS */
/****************************************************************************/
/****************************************************************************/
/* POINTER FILTER PANEL AND EVENT HANDLERS */
/****************************************************************************/
MetaEditorControl.prototype._initFilterPanel = function () {
var filterIcon;
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.CONTAINMENT);
this.diagramDesigner.addFilterItem('Containment', MetaRelations.META_RELATIONS.CONTAINMENT, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.POINTER);
this.diagramDesigner.addFilterItem('Pointer', MetaRelations.META_RELATIONS.POINTER, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.INHERITANCE);
this.diagramDesigner.addFilterItem('Inheritance', MetaRelations.META_RELATIONS.INHERITANCE, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.MIXIN);
this.diagramDesigner.addFilterItem('Mixin', MetaRelations.META_RELATIONS.MIXIN, filterIcon);
filterIcon = MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.SET);
this.diagramDesigner.addFilterItem('Set', MetaRelations.META_RELATIONS.SET, filterIcon);
};
MetaEditorControl.prototype._onConnectionTypeFilterCheckChanged = function (value, isChecked) {
var idx;
if (isChecked === true) {
//type should be enabled
idx = this._filteredOutConnTypes.indexOf(value);
this._filteredOutConnTypes.splice(idx, 1);
this._unfilterConnType(value);
} else {
this._filteredOutConnTypes.push(value);
this._filterConnType(value);
}
};
MetaEditorControl.prototype._filterConnType = function (connType) {
var len = this._connectionListByType &&
this._connectionListByType.hasOwnProperty(connType) ? this._connectionListByType[connType].length : 0,
connComponentId,
gmeSrcId,
gmeDstId,
connTexts,
pointerName;
this._filteredOutConnectionDescriptors[connType] = [];
this.diagramDesigner.beginUpdate();
while (len--) {
connComponentId = this._connectionListByType[connType][len];
gmeSrcId = this._connectionListByID[connComponentId].GMESrcId;
gmeDstId = this._connectionListByID[connComponentId].GMEDstId;
connTexts = this._connectionListByID[connComponentId].connTexts;
if (connType === MetaRelations.META_RELATIONS.POINTER) {
pointerName = this._connectionListByID[connComponentId].name;
}
this._filteredOutConnectionDescriptors[connType].push([gmeSrcId, gmeDstId, connTexts]);
this._removeConnection(gmeSrcId, gmeDstId, connType, pointerName);
}
this.diagramDesigner.endUpdate();
};
MetaEditorControl.prototype._unfilterConnType = function (connType) {
//FIXME: What does this mean?
var len = this._filteredOutConnectionDescriptors &&
this._filteredOutConnectionDescriptors.hasOwnProperty(connType) ?
this._filteredOutConnectionDescriptors[connType].length : 0,
gmeSrcId,
gmeDstId,
connTexts;
this.diagramDesigner.beginUpdate();
while (len--) {
gmeSrcId = this._filteredOutConnectionDescriptors[connType][len][0];
gmeDstId = this._filteredOutConnectionDescriptors[connType][len][1];
connTexts = this._filteredOutConnectionDescriptors[connType][len][2];
this._createConnection(gmeSrcId, gmeDstId, connType, connTexts);
}
delete this._filteredOutConnectionDescriptors[connType];
this.diagramDesigner.endUpdate();
};
/****************************************************************************/
/* END OF --- POINTER FILTER PANEL AND EVENT HANDLERS */
/****************************************************************************/
/****************************************************************************/
/* CONNECTION DESTINATION TEXT CHANGE */
/****************************************************************************/
MetaEditorControl.prototype._onConnectionDstTextChanged = function (connectionID, oldValue, newValue) {
var connDesc = this._connectionListByID[connectionID];
if (connDesc.type === MetaRelations.META_RELATIONS.CONTAINMENT) {
this._containmentRelationshipMultiplicityUpdate(connDesc.GMESrcId, connDesc.GMEDstId, oldValue, newValue);
} else if (connDesc.type === MetaRelations.META_RELATIONS.POINTER) {
this._pointerRelationshipMultiplicityUpdate(connDesc.GMESrcId,
connDesc.GMEDstId,
connDesc.name,
oldValue,
newValue);
} else if (connDesc.type === MetaRelations.META_RELATIONS.INHERITANCE) {
//never can happen
} else if (connDesc.type === MetaRelations.META_RELATIONS.SET) {
this._setRelationshipMultiplicityUpdate(connDesc.GMESrcId,
connDesc.GMEDstId,
connDesc.name,
oldValue,
newValue);
}
};
MetaEditorControl.prototype._containmentRelationshipMultiplicityUpdate = function (containerID, objectID, oldValue,
newValue) {
var containerNode = this._client.getNode(containerID),
objectNode = this._client.getNode(objectID),
multiplicity,
multiplicityValid;
multiplicityValid = function (value) {
var result = null,
pattNum = /^\d+$/g,
pattMinToMax = /^\d+\.\.\d+$/g,
pattMinToMany = /^\d+\.\.\*$/g;
//valid values for containment are 1, x..*, x..y
if (pattNum.test(value)) {
//#1: single digit number
result = {
min: parseInt(value, 10),
max: parseInt(value, 10)
};
} else if (pattMinToMax.test(value)) {
//#2: x..y
result = {
min: parseInt(value, 10),
max: parseInt(value.substring(value.indexOf('..') + 2), 10)
};
} else if (pattMinToMany.test(value)) {
//#3: x..*
result = {
min: parseInt(value, 10),
max: -1
};
}
return result;
};
if (containerNode && objectNode) {
multiplicity = multiplicityValid(newValue);
if (multiplicity) {
multiplicity.id = objectID;
this._client.updateValidChildrenItem(containerID, multiplicity);
} else {
this._updateConnectionText(containerID, objectID, MetaRelations.META_RELATIONS.CONTAINMENT, {
dstText: oldValue,
dstTextEdit: true
});
}
}
};
MetaEditorControl.prototype._pointerRelationshipMultiplicityUpdate = function (sourceID, targetID, pointerName,
oldValue, newValue) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
multiplicityValid,
multiplicity;
multiplicityValid = function (value) {
var result,
pattOne = '1',
pattZeroOne = '0..1';
//valid values for pointer are: 1, 0..1
if (value === pattOne) {
//#1: single digit number
result = {
min: 1,
max: 1
};
} else if (value === pattZeroOne) {
result = {
min: 0,
max: 1
};
}
return result;
};
if (sourceNode && targetNode) {
multiplicity = multiplicityValid(newValue);
if (multiplicity) {
multiplicity.id = targetID;
this._client.updateValidTargetItem(sourceID, pointerName, multiplicity);
} else {
this._updateConnectionText(sourceID, targetID, MetaRelations.META_RELATIONS.POINTER, {
name: pointerName,
dstText: oldValue,
dstTextEdit: true
});
}
}
};
MetaEditorControl.prototype._setRelationshipMultiplicityUpdate = function (sourceID, targetID, pointerName,
oldValue, newValue) {
var sourceNode = this._client.getNode(sourceID),
targetNode = this._client.getNode(targetID),
multiplicityValid,
multiplicity;
multiplicityValid = function (value) {
var result = null,
pattNum = /^\d+$/g,
pattMinToMax = /^\d+\.\.\d+$/g,
pattMinToMany = /^\d+\.\.\*$/g;
//valid value for pointer list are: 1, x..*, x..y
if (pattNum.test(value)) {
//#1: single digit number
result = {
min: parseInt(value, 10),
max: parseInt(value, 10)
};
} else if (pattMinToMax.test(value)) {
//#2: x..y
result = {
min: parseInt(value, 10),
max: parseInt(value.substring(value.indexOf('..') + 2), 10)
};
} else if (pattMinToMany.test(value)) {
//#3: x..*
result = {
min: parseInt(value, 10),
max: -1
};
}
return result;
};
if (sourceNode && targetNode) {
multiplicity = multiplicityValid(newValue);
if (multiplicity) {
multiplicity.id = targetID;
this._client.updateValidTargetItem(sourceID, pointerName, multiplicity);
} else {
this._updateConnectionText(sourceID, targetID, MetaRelations.META_RELATIONS.SET, {
name: pointerName,
dstText: oldValue,
dstTextEdit: true
});
}
}
};
/****************************************************************************/
/* END OF --- CONNECTION DESTINATION TEXT CHANGE */
/****************************************************************************/
MetaEditorControl.prototype._attachClientEventListeners = function () {
};
MetaEditorControl.prototype._detachClientEventListeners = function () {
};
MetaEditorControl.prototype.onActivate = function () {
if (this._selectedSheetID) {
WebGMEGlobal.State.registerActiveTab(this._selectedSheetID);
}
this._attachClientEventListeners();
this._displayToolbarItems();
};
MetaEditorControl.prototype.onDeactivate = function () {
this._detachClientEventListeners();
this._hideToolbarItems();
};
MetaEditorControl.prototype._displayToolbarItems = function () {
if (this._toolbarInitialized !== true) {
this._initializeToolbar();
} else {
for (var i = 0; i < this._toolbarItems.length; i++) {
this._toolbarItems[i].show();
}
}
};
MetaEditorControl.prototype._hideToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = 0; i < this._toolbarItems.length; i++) {
this._toolbarItems[i].hide();
}
}
};
MetaEditorControl.prototype._removeToolbarItems = function () {
if (this._toolbarInitialized === true) {
for (var i = 0; i < this._toolbarItems.length; i++) {
this._toolbarItems[i].destroy();
}
}
};
MetaEditorControl.prototype._initializeToolbar = function () {
var toolBar = WebGMEGlobal.Toolbar,
self = this;
this._toolbarItems = [];
/****************** ADD BUTTONS AND THEIR EVENT HANDLERS TO DIAGRAM DESIGNER ******************/
/************** CREATE META RELATION CONNECTION TYPES *****************/
this._radioButtonGroupMetaRelationType = toolBar.addRadioButtonGroup(function (data) {
self._setNewConnectionType(data.connType);
});
this._toolbarItems.push(this._radioButtonGroupMetaRelationType);
this._radioButtonGroupMetaRelationType.addButton({
title: 'Containment',
selected: true,
data: {connType: MetaRelations.META_RELATIONS.CONTAINMENT},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.CONTAINMENT)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Inheritance',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.INHERITANCE},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.INHERITANCE)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Mixin',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.MIXIN},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.MIXIN)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Pointer',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.POINTER},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.POINTER)
});
this._radioButtonGroupMetaRelationType.addButton({
title: 'Set',
selected: false,
data: {connType: MetaRelations.META_RELATIONS.SET},
icon: MetaRelations.createButtonIcon(MetaRelations.META_RELATIONS.SET)
});
/************** END OF - CREATE META RELATION CONNECTION TYPES *****************/
/************** PRINT NODE DATA *****************/
// TODO removed, but could be reimplemented if needed such function
//this._btnPrintNodeMetaData = toolBar.addButton({ "title": "Print node META data",
// "icon": "glyphicon glyphicon-share",
// "clickFn": function (/*data*/){
// self._printNodeData();
// }});
//this._toolbarItems.push(this._btnPrintNodeMetaData);
/************** END OF - PRINT NODE DATA *****************/
/****************** END OF - ADD BUTTONS AND THEIR EVENT HANDLERS TO DESIGNER CANVAS ******************/
this._toolbarInitialized = true;
};
MetaEditorControl.prototype._getAssociatedConnections = function (objectID) {
var result = {src: [], dst: []},
len,
cID,
checkConnections;
checkConnections = function (cList, res) {
var otherID,
connType;
//check objectID as source
if (cList.hasOwnProperty(objectID)) {
for (otherID in cList[objectID]) {
if (cList[objectID].hasOwnProperty(otherID)) {
for (connType in cList[objectID][otherID]) {
if (cList[objectID][otherID].hasOwnProperty(connType)) {
len = cList[objectID][otherID][connType].length;
while (len--) {
cID = cList[objectID][otherID][connType][len];
if (res.indexOf(cID) === -1) {
res.push(cID);
}
}
}
}
}
}
}
};
checkConnections(this._connectionListBySrcGMEID, result.src);
checkConnections(this._connectionListByDstGMEID, result.dst);
return result;
};
MetaEditorControl.prototype._processMetaAspectSheetsRegistry = function () {
var aspectNode = this._client.getNode(this.metaAspectContainerNodeID),
metaAspectSheetsRegistry = aspectNode.getEditableRegistry(REGISTRY_KEYS.META_SHEETS) || [],
i,
len,
sheetID,
selectedSheetID,
setName,
j,
gmeID;
//save old positions
var oldMetaAspectMembersCoordinatesPerSheet = this._metaAspectMembersCoordinatesPerSheet;
this._sheets = {};
this._metaAspectMembersPerSheet = {};
this._metaAspectMembersCoordinatesPerSheet = {};
this.diagramDesigner.clearTabs();
this._metaAspectSheetsPerMember = {};
metaAspectSheetsRegistry.sort(function (a, b) {
if (a.order < b.order) {
return -1;
} else {
return 1;
}
});
//here we have the metaAspectRegistry ordered by user defined order
this.diagramDesigner.addMultipleTabsBegin();
len = metaAspectSheetsRegistry.length;
for (i = 0; i < len; i += 1) {
setName = metaAspectSheetsRegistry[i].SetID;
sheetID = this.diagramDesigner.addTab(metaAspectSheetsRegistry[i].title, true, true);
this._sheets[sheetID] = setName;
//get the most up-to-date member list for each set
this._metaAspectMembersPerSheet[setName] = aspectNode.getMemberIds(setName);
//TODO: debug check to see if root for any reason is present among the members list
//TODO: remove, not needed, just for DEGUG reasons...
//TODO: it should never happen because it leads to double refresh when ROOT changes
//TODO: when onOneEvent will be eliminated this will not be an issue anymore
if (this._metaAspectMembersPerSheet[setName].indexOf(CONSTANTS.PROJECT_ROOT_ID) > -1) {
this.logger.error('ROOT is in MetaSet: ' + setName);
}
//get the sheet coordinates
this._metaAspectMembersCoordinatesPerSheet[setName] = {};
j = this._metaAspectMembersPerSheet[setName].length;
while (j--) {
gmeID = this._metaAspectMembersPerSheet[setName][j];
this._metaAspectMembersCoordinatesPerSheet[setName][gmeID] = aspectNode.getMemberRegistry(setName,
gmeID,
REGISTRY_KEYS.POSITION);
this._metaAspectSheetsPerMember[gmeID] = this._metaAspectSheetsPerMember[gmeID] || [];
this._metaAspectSheetsPerMember[gmeID].push(setName);
}
if (this._selectedMetaAspectSet &&
this._selectedMetaAspectSet === metaAspectSheetsRegistry[i].SetID) {
selectedSheetID = sheetID;
}
}
this.diagramDesigner.addMultipleTabsEnd();
//figure out whose position has changed
var positionUpdated = [];
if (this._selectedMetaAspectSet) {
var oldPositions = oldMetaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet];
var newPositions = this._metaAspectMembersCoordinatesPerSheet[this._selectedMetaAspectSet];
if (oldPositions && newPositions) {
for (var oldItemId in oldPositions) {
if (oldPositions.hasOwnProperty(oldItemId) && newPositions.hasOwnProperty(oldItemId)) {
if (oldPositions[oldItemId].x !== newPositions[oldItemId].x ||
oldPositions[oldItemId].y !== newPositions[oldItemId].y) {
positionUpdated.push(oldItemId);
}
}
}
}
}
//setting selectedSheetID from global STATE
if (WebGMEGlobal.State.getActiveTab() !== null && WebGMEGlobal.State.getActiveTab() !== undefined &&
metaAspectSheetsRegistry.length > WebGMEGlobal.State.getActiveTab()) {
//only the active panel should react to the global state
if (WebGMEGlobal.PanelManager._activePanel.control === this) {
selectedSheetID = WebGMEGlobal.State.getActiveTab().toString();
} else {
for (selectedSheetID in this._sheets || {}) {
if (this._sheets[selectedSheetID] === this._selectedMetaAspectSet) {
break;
}
}
}
}
if (!selectedSheetID) {
for (selectedSheetID in this._sheets) {
if (this._sheets.hasOwnProperty(selectedSheetID)) {
break;
}
}
}
this._selectedSheetID = selectedSheetID;
this.diagramDesigner.selectTab(selectedSheetID);
return positionUpdated;
};
MetaEditorControl.prototype._initializeSelectedSheet = function () {
var len,
self = this;
this.logger.debug('_initializeSelectedSheet');
//delete everything from model editor
this.diagramDesigner.clear();
//clean up local hash map
this._GMENodes = [];
this._GMEID2ComponentID = {};
this._ComponentID2GMEID = {};
this._connectionWaitingListByDstGMEID = {};
this._connectionWaitingListBySrcGMEID = {};
this._connectionListBySrcGMEID = {};
this._connectionListByDstGMEID = {};
this._connectionListByType = {};
this._connectionListByID = {};
this._nodeMetaContainment = {};
this._nodeMetaPointers = {};
this._nodeMetaSets = {};
this._nodeMetaInheritance = {};
this._nodeMixins = [];
this._selectedMetaAspectSheetMembers = [];
this._filteredOutConnectionDescriptors = {};
len = this._filteredOutConnTypes.length;
while (len--) {
this._filteredOutConnectionDescriptors[this._filteredOutConnTypes[len]] = [];
}
//remove current territory patterns
if (this._metaAspectMembersTerritoryId) {
this._client.removeUI(this._metaAspectMembersTerritoryId);
}
this._metaAspectMemberPatterns = {};
if (this._selectedMetaAspectSet && this._metaAspectMembersPerSheet[this._selectedMetaAspectSet]) {
len = this._metaAspectMembersPerSheet[this._selectedMetaAspectSet].length;
if (len > 0) {
this.diagramDesigner.showProgressbar();
}
while (len--) {
this._selectedMetaAspectSheetMembers.push(
this._metaAspectMembersPerSheet[this._selectedMetaAspectSet][len]);
this._metaAspectMemberPatterns[this._metaAspectMembersPerSheet[this._selectedMetaAspectSet][len]] =
{children: 0};
}
}
this._metaAspectMembersTerritoryId = this._client.addUI(this, function (events) {
self._eventCallback(events);
});
this._client.updateTerritory(this._metaAspectMembersTerritoryId, this._metaAspectMemberPatterns);
};
MetaEditorControl.prototype.setReadOnly = function (isReadOnly) {
this._radioButtonGroupMetaRelationType.enabled(!isReadOnly);
};
//attach MetaEditorControl - DiagramDesigner event handler functions
_.extend(MetaEditorControl.prototype, MetaEditorControlDiagramDesignerWidgetEventHandlers.prototype);
return MetaEditorControl;
});
| #919 Make remove ptr completely if no items
| src/client/js/Panels/MetaEditor/MetaEditorControl.js | #919 Make remove ptr completely if no items | <ide><path>rc/client/js/Panels/MetaEditor/MetaEditorControl.js
<ide> if (sourceNode && targetNode) {
<ide> this._client.removeValidTargetItem(sourceID, pointerName, targetID);
<ide> pointerMetaDescriptor = this._client.getValidTargetItems(sourceID, pointerName);
<del> if (pointerMetaDescriptor && pointerMetaDescriptor.length === 0) {
<add> if (!pointerMetaDescriptor || pointerMetaDescriptor.length === 0) {
<ide> if (isSet === false) {
<ide> //single pointer
<ide> this._client.deleteMetaPointer(sourceID, pointerName); |
|
Java | apache-2.0 | 9906b5f3b5cc14bb7ed39adf0daad2940e6fce7c | 0 | fluenda/ParCEFone | /*
* (C) Copyright 2016 Fluenda.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.fluenda.parcefone.event;
import com.martiansoftware.macnificent.MacAddress;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
/**
* Implements the Common Event Format (CEF) as documented by
* <a href="https://www.protect724.hpe.com/servlet/JiveServlet/downloadBody/1072-102-9-20354/CommonEventFormatv23.pdf">
* revision 23
* </a>
* (Retrieved on August 2016).
*
*/
public class CefRev23 extends CommonEvent {
// Note the conflict with javax.validation.constraints.Pattern...
final private java.util.regex.Pattern timeRegex = java.util.regex.Pattern.compile(
"(?<MONTH>\\w+(\\.)?)\\s(?<DAY>\\d{2})\\s(?:(?<YEAR>\\d{4})(?:\\s))?" +
"(?<HOUR>[012][0-9]):(?<MINUTE>[0-5][0-9]):(?<SECOND>[0-5][0-9])" +
"(?:\\.(?<MILLI>\\d{3}))?(?:\\s(?<TZ>\\w+))?");
final private Class<?> objClass = this.getClass();
final private Field[] fields = objClass.getDeclaredFields();
private ArrayList<String> populatedExtensions = new ArrayList<String>();
// Implements a " struct like" class that implements the Common Event
// Format v23 as described here:
// https://www.protect724.hpe.com/servlet/JiveServlet/downloadBody/1072-102-9-20354/CommonEventFormatv23.pdf
private int version;
private String deviceVendor;
private String deviceProduct;
private String deviceVersion;
// Device Event Class ID is defined as int or String (yay!) treating as
// string
private String deviceEventClassId;
private String name;
private String severity;
// The extension field and its list of KVs
@Size(max = 63)
private String act;
@Size(max = 31)
private String app;
private Inet6Address c6a1;
@Size(max = 1023)
private String c6a1Label;
private Inet6Address c6a2;
@Size(max = 1023)
private String c6a2Label;
private Inet6Address c6a3;
@Size(max = 1023)
private String c6a3Label;
private Inet6Address c6a4;
@Size(max = 1023)
private String c6a4Label;
private float cfp1;
@Size(max = 1023)
private String cfp1Label;
private float cfp2;
@Size(max = 1023)
private String cfp2Label;
private float cfp3;
@Size(max = 1023)
private String cfp3Label;
private float cfp4;
@Size(max = 1023)
private String cfp4Label;
private long cn1;
@Size(max = 1023)
private String cn1Label;
private long cn2;
@Size(max = 1023)
private String cn2Label;
private long cn3;
@Size(max = 1023)
private String cn3Label;
private long cnt;
@Size(max = 4000)
private String cs1;
@Size(max = 1023)
private String cs1Label;
@Size(max = 4000)
private String cs2;
@Size(max = 1023)
private String cs2Label;
@Size(max = 4000)
private String cs3;
@Size(max = 1023)
private String cs3Label;
@Size(max = 4000)
private String cs4;
@Size(max = 1023)
private String cs4Label;
@Size(max = 4000)
private String cs5;
@Size(max = 1023)
private String cs5Label;
@Size(max = 4000)
private String cs6;
@Size(max = 1023)
private String cs6Label;
@Size(max = 255)
private String destinationDnsDomain;
@Size(max = 1023)
private String destinationServiceName;
private Inet4Address destinationTranslatedAddress;
private int destinationTranslatedPort;
private Date deviceCustomDate1;
@Size(max = 1023)
private String deviceCustomeDate1Label;
private Date deviceCustomDate2;
@Size(max = 1023)
private String deviceCustomeDate2Label;
// OMG! Device direction is binary!!!
// 0 = inbound 1 is outbound
@Min(0)
@Max(1)
private int deviceDirection;
@Size(max = 255)
private String deviceDnsDomain;
@Size(max = 255)
private String deviceExternalId;
@Size(max = 1023)
private String deviceFacility;
@Size(max = 128)
private String deviceInboundInterface;
@Size(max = 255)
private String deviceNtDomain;
@Size(max = 128)
private String deviceOutboundInterface;
@Size(max = 128)
private String devicePayloadId;
@Size(max = 1023)
private String deviceProcessName;
private Inet4Address deviceTranslatedAddress;
@Size(max = 1023)
private String dhost;
private MacAddress dmac;
@Size(max = 255)
private String dntdom;
private int dpid;
@Size(max = 1023)
private String dpriv;
@Size(max = 1023)
private String dproc;
@Max(65535)
private int dpt;
private Inet4Address dst;
@Size(max = 255)
private String dtz;
@Size(max = 1023)
private String duid;
@Size(max = 1023)
private String duser;
private Inet4Address dvc;
@Size(max = 100)
private String dvchost;
private MacAddress dvcmac;
private int dvcpid;
private Date end;
@Size(max = 40)
private String externalId;
private Date fileCreateTime;
@Size(max = 255)
private String fileHash;
@Size(max = 1023)
private String field;
private Date fileModificationTime;
@Size(max = 1023)
private String filePath;
@Size(max = 1023)
private String filePermission;
@Size(max = 1023)
private String fileType;
private Date flexDate1;
@Size(max = 128)
private String flexDate1Label;
private long flexNumber1;
@Size(max = 128)
private String flexNumber1Label;
private long flexNumber2;
@Size(max = 128)
private String flexNumber2Label;
@Size(max = 1023)
private String flexString1;
@Size(max = 128)
private String flexString1Label;
@Size(max = 1023)
private String flexString2;
@Size(max = 128)
private String flexString2Label;
@Size(max = 1023)
private String fname;
private int fsize;
private int in;
@Size(max = 1023)
private String msg;
private Date oldFileCreateTime;
@Size(max = 255)
private String oldFileHash;
@Size(max = 1023)
private String oldField;
private Date oldFileModificationTime;
@Size(max = 1023)
private String oldFileName;
@Size(max = 1023)
private String oldFilePath;
@Size(max = 1023)
private String oldFilePermission;
private int oldFileSize;
@Size(max = 1023)
private String oldFileType;
private int out;
@Size(max = 63)
private String outcome;
@Pattern(regexp = "tcp|udp", flags = Pattern.Flag.CASE_INSENSITIVE)
@Size(max = 31)
private String proto;
@Size(max = 1023)
private String reason;
@Size(max = 1023)
private String request;
@Size(max = 1023)
private String requestClientApplication;
@Size(max = 2048)
private String requestContext;
@Size(max = 1023)
private String requestCookies;
@Size(max = 1023)
private String requestMethod;
private Date rt;
@Size(max = 1023)
private String shost;
private MacAddress smac;
@Size(max = 255)
private String sntdom;
@Size(max = 255)
private String sourceDnsDomain;
@Size(max = 1023)
private String sourceServiceName;
private Inet4Address sourceTranslatedAddress;
private int sourceTrnaslatedPort;
private int spid;
@Size(max = 1023)
private String spriv;
@Size(max = 1023)
private String sproc;
@Max(65535)
private int spt;
private Inet4Address src;
private Date start;
@Size(max = 1023)
private String suid;
@Size(max = 1023)
private String suser;
@Min(0)
@Max(3)
private int type;
@Size(max = 255)
private String agentDnsDomain;
@Size(max = 255)
private String agentNtDomain;
private Inet4Address agentTranslatedAddress;
@Size(max = 200)
private String agentTranslatedZoneExternalID;
@Size(max = 2048)
private String agentTranslatedZoneURI;
@Size(max = 200)
private String agentZoneExternalID;
@Size(max = 2048)
private String agentZoneURI;
private InetAddress agt;
@Size(max = 1023)
private String ahost;
@Size(max = 40)
private String aid;
private MacAddress amac;
private Date art;
@Size(max = 63)
private String at;
@Size(max = 255)
private String atz;
@Size(max = 31)
private String av;
@Size(max = 1023)
private String cat;
@Size(max = 200)
private String customerExternalID;
@Size(max = 2048)
private String customerURI;
@Size(max = 200)
private String destinationTranslatedZoneExternalID;
@Size(max = 2048)
private String destinationTranslatedZoneURI;
@Size(max = 200)
private String destinationZoneExternalID;
@Size(max = 2048)
private String destinationZoneURI;
@Size(max = 200)
private String deviceTranslatedZoneExternalID;
@Size(max = 2048)
private String deviceTranslatedZoneURI;
@Size(max = 200)
private String deviceZoneExternalID;
@Size(max = 2048)
private String deviceZoneURI;
private double dlat;
private double dlong;
private long eventId;
@Size(max = 4000)
private String rawEvent;
private double slat;
private double slong;
@Size(max = 200)
private String sourceTranslatedZoneExternalID;
@Size(max = 2048)
private String sourceTranslatedZoneURI;
@Size(max = 200)
private String sourceZoneExternalID;
@Size(max = 2048)
private String sourceZoneURI;
private Locale dateLocale;
public CefRev23(Locale locale) {
super();
this.dateLocale = locale;
}
public CefRev23() {
super();
// Defaults to ENGLISH locale when processing dates
this.dateLocale = Locale.ENGLISH;
}
/**
* @param headers A map containing the keys and values of headers of CEF event
* @throws CEFHandlingException when it has issues writing the values of the headers
*/
public void setHeader(Map<String, Object> headers) throws CEFHandlingException {
for (String key : headers.keySet()) {
try {
Field field = objClass.getDeclaredField(key);
Object value = headers.get(key);
field.set(this, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new CEFHandlingException("Error writing values to headers", e);
}
}
}
/**
* @return A map containing the keys and values of headers
* @throws CEFHandlingException when it has issues reading the headers of CEF event
*/
public Map<String, Object> getHeader() throws CEFHandlingException {
final HashMap<String, Object> headers = new HashMap<String, Object>();
List headersKeys = Arrays.asList(new String[] {"version", "deviceVendor", "deviceProduct", "deviceVersion", "deviceEventClassId", "name", "severity"});
for (Field f: fields) {
if (headersKeys.contains(f.getName())) {
try {
headers.put(f.getName(), f.get(this));
} catch (IllegalAccessException e) {
throw new CEFHandlingException("Error harvesting headers, e");
}
}
}
return headers;
}
/**
* @param extensions A map containing the keys and values of extensions of CEF event
* @throws CEFHandlingException when it has issues populating the extensions
*/
public void setExtension(Map<String, String> extensions) throws CEFHandlingException {
for (String key : extensions.keySet()) {
try {
Field field = objClass.getDeclaredField(key);
String value = extensions.get(key);
// Treat each Classes in a particular fashion
// Inet, Inet4 and Inet6 address
if (field.getType().equals(InetAddress.class) || field.getType().equals(Inet4Address.class) || field.getType().equals(Inet6Address.class)) {
try {
InetAddress inetAddress = InetAddress.getByName((String) value);
field.set(this, inetAddress);
} catch (UnknownHostException e) {
throw new CEFHandlingException("Error setting value to field " + key, e);
}
// Date (timestamps) - Note we force a particular date format (set as private dateFormat above
} else if (field.getType().equals(Date.class)) {
try {
// Use a ": "to match epoch vs. Dateformat
if (!value.toString().contains(":")) {
// This is epoch
field.set(this, new Date(Long.valueOf(value)));
} else {
// This is one of the remaining 8 possible values, regex it out...
Matcher matcher = timeRegex.matcher(value);
if (matcher.matches()) {
String year = matcher.group("YEAR") == null ? String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) : matcher.group("YEAR") ;
String milli = matcher.group("MILLI") == null ? "000" : matcher.group("MILLI");
String regexDate =
year + "-" +
matcher.group("MONTH") + "-" +
matcher.group("DAY") + " " +
matcher.group("HOUR") + ":" +
matcher.group("MINUTE") + ":" +
matcher.group("SECOND") + "." +
milli;
if (matcher.group("TZ") == null ) {
field.set(this, dateFormat(false).parse(regexDate));
} else {
regexDate = regexDate + " " + matcher.group("TZ");
field.set(this, dateFormat(true).parse(regexDate));
}
}
}
} catch (ParseException|NumberFormatException e) {
throw new CEFHandlingException("Error setting value to field " + key, e);
}
// Mac Addresses
} else if (field.getType().equals(MacAddress.class)) {
field.set(this, new MacAddress(value));
// Integers
} else if (field.getType().equals(int.class)) {
field.set(this, Integer.valueOf(value));
// Longs
} else if (field.getType().equals(long.class)){
field.set(this, Long.valueOf(value));
// Doubles
} else if (field.getType().equals(double.class)) {
field.set(this, Double.valueOf(value));
// Floats
} else if (field.getType().equals(float.class)) {
field.set(this, Float.valueOf(value));
// The rest (to be removed)
} else {
field.set(this, value );
}
// Add the key to the populate keys listt
populatedExtensions.add(key);
} catch (NoSuchFieldException e) {
// Ignore illegal key names;
continue;
} catch (IllegalAccessException e) {
throw new CEFHandlingException("Error while setting CEF extension values", e);
}
}
}
/**
* @param populatedOnly Boolean defining if Map should include all fields supported by {@link com.fluenda.parcefone.event.CefRev23}
* @return A map containing the keys and values of CEF extensions
* @throws CEFHandlingException when it hits issues (e.g. IllegalAccessException) reading the extensions
*/
public Map<String, Object> getExtension(boolean populatedOnly) throws CEFHandlingException {
final HashMap<String, Object> extensions = new HashMap<String, Object>();
List headersKeys = Arrays.asList(new String[] {"version", "deviceVendor", "deviceProduct", "deviceVersion", "deviceEventClassId", "name", "severity"});
for (Field f: fields) {
// Exclude header objects
if (!headersKeys.contains(f.getName())) {
// check if populatedOnly was requested
try {
Object value = f.get(this);
if (!populatedOnly){
extensions.put(f.getName(), value);
} else if (populatedOnly && populatedExtensions.contains(f.getName())) {
extensions.put(f.getName(), value);
}
} catch (IllegalAccessException e) {
throw new CEFHandlingException("Error while harvesting keys", e);
}
}
}
return extensions;
}
private SimpleDateFormat dateFormat(boolean containsTZ) {
if (containsTZ) {
return new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS zzz", this.dateLocale);
} else {
return new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS", this.dateLocale);
}
}
}
| src/main/java/com/fluenda/parcefone/event/CefRev23.java | /*
* (C) Copyright 2016 Fluenda.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.fluenda.parcefone.event;
import com.martiansoftware.macnificent.MacAddress;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
/**
* Implements the Common Event Format (CEF) as documented by
* <a href="https://www.protect724.hpe.com/servlet/JiveServlet/downloadBody/1072-102-9-20354/CommonEventFormatv23.pdf">
* revision 23
* </a>
* (Retrieved on August 2016).
*
*/
public class CefRev23 extends CommonEvent {
// Note the conflict with javax.validation.constraints.Pattern...
final private java.util.regex.Pattern timeRegex = java.util.regex.Pattern.compile(
"(?<MONTH>\\w+(\\.)?)\\s(?<DAY>\\d{2})\\s(?:(?<YEAR>\\d{4})(?:\\s))?" +
"(?<HOUR>[012][0-9]):(?<MINUTE>[0-5][0-9]):(?<SECOND>[0-5][0-9])" +
"(?:\\.(?<MILLI>\\d{3}))?(?:\\s(?<TZ>\\w+))?");
final private Class<?> objClass = this.getClass();
final private Field[] fields = objClass.getDeclaredFields();
private ArrayList<String> populatedExtensions = new ArrayList<String>();
// Implements a " struct like" class that implements the Common Event
// Format v23 as described here:
// https://www.protect724.hpe.com/servlet/JiveServlet/downloadBody/1072-102-9-20354/CommonEventFormatv23.pdf
private int version;
private String deviceVendor;
private String deviceProduct;
private String deviceVersion;
// Device Event Class ID is defined as int or String (yay!) treating as
// string
private String deviceEventClassId;
private String name;
private String severity;
// The extension field and its list of KVs
@Size(max = 63)
private String act;
@Size(max = 31)
private String app;
private Inet6Address c6a1;
@Size(max = 1023)
private String c6a1Label;
private Inet6Address c6a2;
@Size(max = 1023)
private String c6a2Label;
private Inet6Address c6a3;
@Size(max = 1023)
private String c6a3Label;
private Inet6Address c6a4;
@Size(max = 1023)
private String c6a4Label;
private float cfp1;
@Size(max = 1023)
private String cfp1Label;
private float cfp2;
@Size(max = 1023)
private String cfp2Label;
private float cfp3;
@Size(max = 1023)
private String cfp3Label;
private float cfp4;
@Size(max = 1023)
private String cfp4Label;
private long cn1;
@Size(max = 1023)
private String cn1Label;
private long cn2;
@Size(max = 1023)
private String cn2Label;
private long cn3;
@Size(max = 1023)
private String cn3Label;
private long cnt;
@Size(max = 4000)
private String cs1;
@Size(max = 1023)
private String cs1Label;
@Size(max = 4000)
private String cs2;
@Size(max = 1023)
private String cs2Label;
@Size(max = 4000)
private String cs3;
@Size(max = 1023)
private String cs3Label;
@Size(max = 4000)
private String cs4;
@Size(max = 1023)
private String cs4Label;
@Size(max = 4000)
private String cs5;
@Size(max = 1023)
private String cs5Label;
@Size(max = 4000)
private String cs6;
@Size(max = 1023)
private String cs6Label;
@Size(max = 255)
private String destinationDnsDomain;
@Size(max = 1023)
private String destinationServiceName;
private Inet4Address destinationTranslatedAddress;
private int destinationTranslatedPort;
private Date deviceCustomDate1;
@Size(max = 1023)
private String deviceCustomeDate1Label;
private Date deviceCustomDate2;
@Size(max = 1023)
private String deviceCustomeDate2Label;
// OMG! Device direction is binary!!!
// 0 = inbound 1 is outbound
@Min(0)
@Max(1)
private int deviceDirection;
@Size(max = 255)
private String deviceDnsDomain;
@Size(max = 255)
private String deviceExternalId;
@Size(max = 1023)
private String deviceFacility;
@Size(max = 128)
private String deviceInboundInterface;
@Size(max = 255)
private String deviceNtDomain;
@Size(max = 128)
private String deviceOutboundInterface;
@Size(max = 128)
private String devicePayloadId;
@Size(max = 1023)
private String deviceProcessName;
private Inet4Address deviceTranslatedAddress;
@Size(max = 1023)
private String dhost;
private MacAddress dmac;
@Size(max = 255)
private String dntdom;
private int dpid;
@Size(max = 1023)
private String dpriv;
@Size(max = 1023)
private String dproc;
@Max(65535)
private int dpt;
private Inet4Address dst;
@Size(max = 255)
private String dtz;
@Size(max = 1023)
private String duid;
@Size(max = 1023)
private String duser;
private Inet4Address dvc;
@Size(max = 100)
private String dvchost;
private MacAddress dvcmac;
private int dvcpid;
private Date end;
@Size(max = 40)
private String externalId;
private Date fileCreateTime;
@Size(max = 255)
private String fileHash;
@Size(max = 1023)
private String field;
private Date fileModificationTime;
@Size(max = 1023)
private String filePath;
@Size(max = 1023)
private String filePermission;
@Size(max = 1023)
private String fileType;
private Date flexDate1;
@Size(max = 128)
private String flexDate1Label;
private long flexNumber1;
@Size(max = 128)
private String flexNumber1Label;
private long flexNumber2;
@Size(max = 128)
private String flexNumber2Label;
@Size(max = 1023)
private String flexString1;
@Size(max = 128)
private String flexString1Label;
@Size(max = 1023)
private String flexString2;
@Size(max = 128)
private String flexString2Label;
@Size(max = 1023)
private String fname;
private int fsize;
private int in;
@Size(max = 1023)
private String msg;
private Date oldFileCreateTime;
@Size(max = 255)
private String oldFileHash;
@Size(max = 1023)
private String oldField;
private Date oldFileModificationTime;
@Size(max = 1023)
private String oldFileName;
@Size(max = 1023)
private String oldFilePath;
@Size(max = 1023)
private String oldFilePermission;
private int oldFileSize;
@Size(max = 1023)
private String oldFileType;
private int out;
@Size(max = 63)
private String outcome;
@Pattern(regexp = "tcp|udp", flags = Pattern.Flag.CASE_INSENSITIVE)
@Size(max = 31)
private String proto;
@Size(max = 1023)
private String reason;
@Size(max = 1023)
private String request;
@Size(max = 1023)
private String requestClientApplication;
@Size(max = 2048)
private String requestContext;
@Size(max = 1023)
private String requestCookies;
@Size(max = 1023)
private String requestMethod;
private Date rt;
@Size(max = 1023)
private String shost;
private MacAddress smac;
@Size(max = 255)
private String sntdom;
@Size(max = 255)
private String sourceDnsDomain;
@Size(max = 1023)
private String sourceServiceName;
private Inet4Address sourceTranslatedAddress;
private int sourceTrnaslatedPort;
private int spid;
@Size(max = 1023)
private String spriv;
@Size(max = 1023)
private String sproc;
@Max(65535)
private int spt;
private Inet4Address src;
private Date start;
@Size(max = 1023)
private String suid;
@Size(max = 1023)
private String suser;
@Min(0)
@Max(3)
private int type;
@Size(max = 255)
private String agentDnsDomain;
@Size(max = 255)
private String agentNtDomain;
private Inet4Address agentTranslatedAddress;
@Size(max = 200)
private String agentTranslatedZoneExternalID;
@Size(max = 2048)
private String agentTranslatedZoneURI;
@Size(max = 200)
private String agentZoneExternalID;
@Size(max = 2048)
private String agentZoneURI;
private InetAddress agt;
@Size(max = 1023)
private String ahost;
@Size(max = 40)
private String aid;
private MacAddress amac;
private Date art;
@Size(max = 63)
private String at;
@Size(max = 255)
private String atz;
@Size(max = 31)
private String av;
@Size(max = 1023)
private String cat;
@Size(max = 200)
private String customerExternalID;
@Size(max = 2048)
private String customerURI;
@Size(max = 200)
private String destinationTranslatedZoneExternalID;
@Size(max = 2048)
private String destinationTranslatedZoneURI;
@Size(max = 200)
private String destinationZoneExternalID;
@Size(max = 2048)
private String destinationZoneURI;
@Size(max = 200)
private String deviceTranslatedZoneExternalID;
@Size(max = 2048)
private String deviceTranslatedZoneURI;
@Size(max = 200)
private String deviceZoneExternalID;
@Size(max = 2048)
private String deviceZoneURI;
private double dlat;
private double dlong;
private long eventId;
@Size(max = 4000)
private String rawEvent;
private double slat;
private double slong;
@Size(max = 200)
private String sourceTranslatedZoneExternalID;
@Size(max = 2048)
private String sourceTranslatedZoneURI;
@Size(max = 200)
private String sourceZoneExternalID;
@Size(max = 2048)
private String sourceZoneURI;
private Locale dateLocale;
public CefRev23(Locale locale) {
super();
this.dateLocale = locale;
}
public CefRev23() {
super();
// Defaults to ENGLISH locale when processing dates
this.dateLocale = Locale.ENGLISH;
}
public void setHeader(Map<String, Object> headers) throws CEFHandlingException {
for (String key : headers.keySet()) {
try {
Field field = objClass.getDeclaredField(key);
Object value = headers.get(key);
field.set(this, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new CEFHandlingException("Error writing values to headers", e);
}
}
}
/**
* @return A map containing the keys and values of headers
* @throws CEFHandlingException when it has issues reading the headers of CEF event
*/
public Map<String, Object> getHeader() throws CEFHandlingException {
final HashMap<String, Object> headers = new HashMap<String, Object>();
List headersKeys = Arrays.asList(new String[] {"version", "deviceVendor", "deviceProduct", "deviceVersion", "deviceEventClassId", "name", "severity"});
for (Field f: fields) {
if (headersKeys.contains(f.getName())) {
try {
headers.put(f.getName(), f.get(this));
} catch (IllegalAccessException e) {
throw new CEFHandlingException("Error harvesting headers, e");
}
}
}
return headers;
}
/**
* @param extensions A map containing the keys and values of extensions of CEF event
* @throws CEFHandlingException when it has issues populating the extensions
*/
public void setExtension(Map<String, String> extensions) throws CEFHandlingException {
for (String key : extensions.keySet()) {
try {
Field field = objClass.getDeclaredField(key);
String value = extensions.get(key);
// Treat each Classes in a particular fashion
// Inet, Inet4 and Inet6 address
if (field.getType().equals(InetAddress.class) || field.getType().equals(Inet4Address.class) || field.getType().equals(Inet6Address.class)) {
try {
InetAddress inetAddress = InetAddress.getByName((String) value);
field.set(this, inetAddress);
} catch (UnknownHostException e) {
throw new CEFHandlingException("Error setting value to field " + key, e);
}
// Date (timestamps) - Note we force a particular date format (set as private dateFormat above
} else if (field.getType().equals(Date.class)) {
try {
// Use a ": "to match epoch vs. Dateformat
if (!value.toString().contains(":")) {
// This is epoch
field.set(this, new Date(Long.valueOf(value)));
} else {
// This is one of the remaining 8 possible values, regex it out...
Matcher matcher = timeRegex.matcher(value);
if (matcher.matches()) {
String year = matcher.group("YEAR") == null ? String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) : matcher.group("YEAR") ;
String milli = matcher.group("MILLI") == null ? "000" : matcher.group("MILLI");
String regexDate =
year + "-" +
matcher.group("MONTH") + "-" +
matcher.group("DAY") + " " +
matcher.group("HOUR") + ":" +
matcher.group("MINUTE") + ":" +
matcher.group("SECOND") + "." +
milli;
if (matcher.group("TZ") == null ) {
field.set(this, dateFormat(false).parse(regexDate));
} else {
regexDate = regexDate + " " + matcher.group("TZ");
field.set(this, dateFormat(true).parse(regexDate));
}
}
}
} catch (ParseException|NumberFormatException e) {
throw new CEFHandlingException("Error setting value to field " + key, e);
}
// Mac Addresses
} else if (field.getType().equals(MacAddress.class)) {
field.set(this, new MacAddress(value));
// Integers
} else if (field.getType().equals(int.class)) {
field.set(this, Integer.valueOf(value));
// Longs
} else if (field.getType().equals(long.class)){
field.set(this, Long.valueOf(value));
// Doubles
} else if (field.getType().equals(double.class)) {
field.set(this, Double.valueOf(value));
// Floats
} else if (field.getType().equals(float.class)) {
field.set(this, Float.valueOf(value));
// The rest (to be removed)
} else {
field.set(this, value );
}
// Add the key to the populate keys listt
populatedExtensions.add(key);
} catch (NoSuchFieldException e) {
// Ignore illegal key names;
continue;
} catch (IllegalAccessException e) {
throw new CEFHandlingException("Error while setting CEF extension values", e);
}
}
}
/**
* @param populatedOnly Boolean defining if Map should include all fields supported by {@link com.fluenda.parcefone.event.CefRev23}
* @return A map containing the keys and values of CEF extensions
* @throws CEFHandlingException when it hits issues (e.g. IllegalAccessException) reading the extensions
*/
public Map<String, Object> getExtension(boolean populatedOnly) throws CEFHandlingException {
final HashMap<String, Object> extensions = new HashMap<String, Object>();
List headersKeys = Arrays.asList(new String[] {"version", "deviceVendor", "deviceProduct", "deviceVersion", "deviceEventClassId", "name", "severity"});
for (Field f: fields) {
// Exclude header objects
if (!headersKeys.contains(f.getName())) {
// check if populatedOnly was requested
try {
Object value = f.get(this);
if (!populatedOnly){
extensions.put(f.getName(), value);
} else if (populatedOnly && populatedExtensions.contains(f.getName())) {
extensions.put(f.getName(), value);
}
} catch (IllegalAccessException e) {
throw new CEFHandlingException("Error while harvesting keys", e);
}
}
}
return extensions;
}
private SimpleDateFormat dateFormat(boolean containsTZ) {
if (containsTZ) {
return new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS zzz", this.dateLocale);
} else {
return new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS", this.dateLocale);
}
}
}
| Re-add accidentally deleted javadocs
| src/main/java/com/fluenda/parcefone/event/CefRev23.java | Re-add accidentally deleted javadocs | <ide><path>rc/main/java/com/fluenda/parcefone/event/CefRev23.java
<ide> this.dateLocale = Locale.ENGLISH;
<ide> }
<ide>
<add> /**
<add> * @param headers A map containing the keys and values of headers of CEF event
<add> * @throws CEFHandlingException when it has issues writing the values of the headers
<add> */
<ide> public void setHeader(Map<String, Object> headers) throws CEFHandlingException {
<ide> for (String key : headers.keySet()) {
<ide> try { |
|
Java | unlicense | ad7faf2f541cd95f7a670ab7bca2e9bc3e50749f | 0 | joserobjr/MyTown2,GameModsBR/MyTown2,MyEssentials/MyTown2 | package mytown.protection.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import mytown.MyTown;
import myessentials.entities.Volume;
import mytown.api.container.GettersContainer;
import mytown.entities.flag.FlagType;
import mytown.protection.Protection;
import mytown.protection.ProtectionHandler;
import mytown.protection.ProtectionUtils;
import mytown.protection.segment.*;
import mytown.protection.segment.caller.CallerField;
import mytown.protection.segment.caller.CallerMethod;
import mytown.protection.segment.enums.BlockType;
import mytown.protection.segment.enums.EntityType;
import mytown.protection.segment.enums.ItemType;
import mytown.protection.segment.caller.Caller;
import mytown.protection.segment.getter.Getter;
import mytown.protection.segment.getter.GetterConstant;
import mytown.protection.segment.getter.GetterDynamic;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
/**
* JSON Parser used to parse protection files.
*/
public class ProtectionParser {
private static String folderPath;
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(Caller.class, new CallerSerializer())
.registerTypeAdapter(Getter.class, new GetterSerializer())
.registerTypeAdapter(Protection.class, new ProtectionSerializer())
.registerTypeAdapter(Segment.class, new SegmentSerializer())
.registerTypeAdapter(Volume.class, new VolumeSerializer())
.registerTypeAdapter(FlagType.class, new FlagTypeSerializer())
.setPrettyPrinting().create();
private ProtectionParser() {
}
public static void setFolderPath(String folderPath) {
ProtectionParser.folderPath = folderPath;
}
public static boolean start() {
File folder = new File(folderPath);
if(!folder.exists()) {
if(!folder.mkdir())
return false;
createModel();
}
String[] extensions = new String[1];
extensions[0] = "json";
ProtectionUtils.protections.clear();
Protection vanillaProtection = null;
for (File file : FileUtils.listFiles(folder, extensions, true)) {
try {
FileReader reader = new FileReader(file);
MyTown.instance.LOG.info("Loading protection file: {}", file.getName());
Protection protection = gson.fromJson(reader, Protection.class);
if(protection != null) {
if ("Minecraft".equals(protection.modid)) {
vanillaProtection = protection;
} else if(isModLoaded(protection.modid, protection.version)) {
MyTown.instance.LOG.info("Adding protection for mod: {}", protection.modid);
ProtectionUtils.protections.add(protection);
}
}
reader.close();
} catch (Exception ex) {
MyTown.instance.LOG.error("Encountered error when parsing protection file: {}", file.getName());
MyTown.instance.LOG.error(ExceptionUtils.getStackTrace(ex));
}
}
if(vanillaProtection != null) {
MyTown.instance.LOG.info("Adding vanilla protection.");
ProtectionUtils.protections.add(vanillaProtection);
}
return true;
}
@SuppressWarnings("unchecked")
private static void createModel() {
List<Segment> segments = new ArrayList<Segment>();
segments.add(createSegmentBlock(net.minecraft.block.BlockButton.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockDoor.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, new Volume(0, -1, 0, 0, 1, 0)));
segments.add(createSegmentBlock(net.minecraft.block.BlockLever.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockFenceGate.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockDragonEgg.class, FlagType.ACTIVATE, null, null, BlockType.ANY_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockCake.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockTrapDoor.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockJukebox.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockRedstoneRepeater.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockRedstoneComparator.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockAnvil.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockCauldron.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockContainer.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockBed.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentEntity(net.minecraft.entity.monster.EntityMob.class, FlagType.MOBS, null, null, EntityType.TRACKED));
segments.add(createSegmentEntity(net.minecraft.entity.EntityAgeable.class, FlagType.PVE, null, null, EntityType.PROTECT));
GettersContainer getters = new GettersContainer();
getters.add(new GetterConstant("range", 5));
segments.add(createSegmentEntity(net.minecraft.entity.monster.EntityCreeper.class, FlagType.EXPLOSIONS, null, getters, EntityType.TRACKED));
getters = new GettersContainer();
getters.add(new GetterConstant("range", 5));
List<Caller> callers = new ArrayList<Caller>();
callers.add(new CallerField("field_94084_b", null));
callers.add(new CallerMethod("func_70005_c_", null));
getters.add(new GetterDynamic("owner", callers));
segments.add(createSegmentEntity(net.minecraft.entity.item.EntityTNTPrimed.class, FlagType.EXPLOSIONS, null, getters, EntityType.TRACKED));
segments.add(createSegmentEntity(net.minecraft.entity.item.EntityItemFrame.class, FlagType.PVE, null, null, EntityType.PROTECT));
segments.add(createSegmentItem(net.minecraft.item.ItemMonsterPlacer.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_BLOCK, true, null, false));
segments.add(createSegmentItem(net.minecraft.item.ItemMonsterPlacer.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_ENTITY, false, null, false));
segments.add(createSegmentItem(net.minecraft.item.ItemShears.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_ENTITY, false, null, false));
segments.add(createSegmentItem(net.minecraft.item.ItemHangingEntity.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_BLOCK, true, null, false));
Protection protection = new Protection("Minecraft", segments);
try {
FileWriter writer = new FileWriter(folderPath + "/Minecraft.json");
gson.toJson(protection, Protection.class, writer);
writer.close();
} catch (Exception ex) {
MyTown.instance.LOG.error("Failed to create protection model :( ");
MyTown.instance.LOG.error(ExceptionUtils.getStackTrace(ex));
}
}
private static boolean isModLoaded(String modid, String version) {
for(ModContainer mod : Loader.instance().getModList()) {
if(mod.getModId().equals(modid) && mod.getVersion().startsWith(version)) {
return true;
}
}
return false;
}
private static SegmentBlock createSegmentBlock(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, BlockType blockType, int meta, Volume clientUpdateCoords) {
SegmentBlock segment = new SegmentBlock(meta, clientUpdateCoords);
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.types.add(blockType);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
private static SegmentEntity createSegmentEntity(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, EntityType entityType) {
SegmentEntity segment = new SegmentEntity();
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.types.add(entityType);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
private static SegmentItem createSegmentItem(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, ItemType itemType, boolean onAdjacent, Volume clientUpdateCoords, boolean directionalClientUpdate) {
SegmentItem segment = new SegmentItem(onAdjacent, clientUpdateCoords, directionalClientUpdate);
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.types.add(itemType);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
private static SegmentTileEntity createSegmentTileEntity(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, boolean hasOwner) {
SegmentTileEntity segment = new SegmentTileEntity(hasOwner);
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
}
| src/main/java/mytown/protection/json/ProtectionParser.java | package mytown.protection.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import mytown.MyTown;
import myessentials.entities.Volume;
import mytown.api.container.GettersContainer;
import mytown.entities.flag.FlagType;
import mytown.protection.Protection;
import mytown.protection.ProtectionHandler;
import mytown.protection.ProtectionUtils;
import mytown.protection.segment.*;
import mytown.protection.segment.caller.CallerField;
import mytown.protection.segment.caller.CallerMethod;
import mytown.protection.segment.enums.BlockType;
import mytown.protection.segment.enums.EntityType;
import mytown.protection.segment.enums.ItemType;
import mytown.protection.segment.caller.Caller;
import mytown.protection.segment.getter.Getter;
import mytown.protection.segment.getter.GetterConstant;
import mytown.protection.segment.getter.GetterDynamic;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
/**
* JSON Parser used to parse protection files.
*/
public class ProtectionParser {
private static String folderPath;
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(Caller.class, new CallerSerializer())
.registerTypeAdapter(Getter.class, new GetterSerializer())
.registerTypeAdapter(Protection.class, new ProtectionSerializer())
.registerTypeAdapter(Segment.class, new SegmentSerializer())
.registerTypeAdapter(Volume.class, new VolumeSerializer())
.registerTypeAdapter(FlagType.class, new FlagTypeSerializer())
.setPrettyPrinting().create();
private ProtectionParser() {
}
public static void setFolderPath(String folderPath) {
ProtectionParser.folderPath = folderPath;
}
public static boolean start() {
File folder = new File(folderPath);
if(!folder.exists()) {
if(!folder.mkdir())
return false;
createModel();
}
String[] extensions = new String[1];
extensions[0] = "json";
ProtectionUtils.protections.clear();
Protection vanillaProtection = null;
for (File file : FileUtils.listFiles(folder, extensions, true)) {
try {
FileReader reader = new FileReader(file);
MyTown.instance.LOG.info("Loading protection file: {}", file.getName());
Protection protection = gson.fromJson(reader, Protection.class);
if(protection != null) {
if ("Minecraft".equals(protection.modid)) {
vanillaProtection = protection;
} else {
MyTown.instance.LOG.info("Adding protection for mod: {}", protection.modid);
ProtectionUtils.protections.add(protection);
}
}
reader.close();
} catch (Exception ex) {
MyTown.instance.LOG.error("Encountered error when parsing protection file: {}", file.getName());
MyTown.instance.LOG.error(ExceptionUtils.getStackTrace(ex));
}
}
if(vanillaProtection != null) {
MyTown.instance.LOG.info("Adding vanilla protection.");
ProtectionUtils.protections.add(vanillaProtection);
}
return true;
}
@SuppressWarnings("unchecked")
private static void createModel() {
List<Segment> segments = new ArrayList<Segment>();
segments.add(createSegmentBlock(net.minecraft.block.BlockButton.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockDoor.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, new Volume(0, -1, 0, 0, 1, 0)));
segments.add(createSegmentBlock(net.minecraft.block.BlockLever.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockFenceGate.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockDragonEgg.class, FlagType.ACTIVATE, null, null, BlockType.ANY_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockCake.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockTrapDoor.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockJukebox.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockRedstoneRepeater.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockRedstoneComparator.class, FlagType.ACTIVATE, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockAnvil.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockCauldron.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockContainer.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentBlock(net.minecraft.block.BlockBed.class, FlagType.ACCESS, null, null, BlockType.RIGHT_CLICK, -1, null));
segments.add(createSegmentEntity(net.minecraft.entity.monster.EntityMob.class, FlagType.MOBS, null, null, EntityType.TRACKED));
segments.add(createSegmentEntity(net.minecraft.entity.EntityAgeable.class, FlagType.PVE, null, null, EntityType.PROTECT));
GettersContainer getters = new GettersContainer();
getters.add(new GetterConstant("range", 5));
segments.add(createSegmentEntity(net.minecraft.entity.monster.EntityCreeper.class, FlagType.EXPLOSIONS, null, getters, EntityType.TRACKED));
getters = new GettersContainer();
getters.add(new GetterConstant("range", 5));
List<Caller> callers = new ArrayList<Caller>();
callers.add(new CallerField("field_94084_b", null));
callers.add(new CallerMethod("func_70005_c_", null));
getters.add(new GetterDynamic("owner", callers));
segments.add(createSegmentEntity(net.minecraft.entity.item.EntityTNTPrimed.class, FlagType.EXPLOSIONS, null, getters, EntityType.TRACKED));
segments.add(createSegmentEntity(net.minecraft.entity.item.EntityItemFrame.class, FlagType.PVE, null, null, EntityType.PROTECT));
segments.add(createSegmentItem(net.minecraft.item.ItemMonsterPlacer.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_BLOCK, true, null, false));
segments.add(createSegmentItem(net.minecraft.item.ItemMonsterPlacer.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_ENTITY, false, null, false));
segments.add(createSegmentItem(net.minecraft.item.ItemShears.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_ENTITY, false, null, false));
segments.add(createSegmentItem(net.minecraft.item.ItemHangingEntity.class, FlagType.USAGE, null, null, ItemType.RIGHT_CLICK_BLOCK, true, null, false));
Protection protection = new Protection("Minecraft", segments);
try {
FileWriter writer = new FileWriter(folderPath + "/Minecraft.json");
gson.toJson(protection, Protection.class, writer);
writer.close();
} catch (Exception ex) {
MyTown.instance.LOG.error("Failed to create protection model :( ");
MyTown.instance.LOG.error(ExceptionUtils.getStackTrace(ex));
}
}
private static SegmentBlock createSegmentBlock(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, BlockType blockType, int meta, Volume clientUpdateCoords) {
SegmentBlock segment = new SegmentBlock(meta, clientUpdateCoords);
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.types.add(blockType);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
private static SegmentEntity createSegmentEntity(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, EntityType entityType) {
SegmentEntity segment = new SegmentEntity();
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.types.add(entityType);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
private static SegmentItem createSegmentItem(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, ItemType itemType, boolean onAdjacent, Volume clientUpdateCoords, boolean directionalClientUpdate) {
SegmentItem segment = new SegmentItem(onAdjacent, clientUpdateCoords, directionalClientUpdate);
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.types.add(itemType);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
private static SegmentTileEntity createSegmentTileEntity(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, boolean hasOwner) {
SegmentTileEntity segment = new SegmentTileEntity(hasOwner);
if(getters != null) {
segment.getters.addAll(getters);
}
segment.setCheckClass(clazz);
segment.flags.add(flagType);
segment.setConditionString(conditionString);
return segment;
}
}
| Added check to see if mod is loaded before adding protection to it.
| src/main/java/mytown/protection/json/ProtectionParser.java | Added check to see if mod is loaded before adding protection to it. | <ide><path>rc/main/java/mytown/protection/json/ProtectionParser.java
<ide>
<ide> import com.google.gson.Gson;
<ide> import com.google.gson.GsonBuilder;
<add>import cpw.mods.fml.common.Loader;
<add>import cpw.mods.fml.common.ModContainer;
<ide> import mytown.MyTown;
<ide> import myessentials.entities.Volume;
<ide> import mytown.api.container.GettersContainer;
<ide> if(protection != null) {
<ide> if ("Minecraft".equals(protection.modid)) {
<ide> vanillaProtection = protection;
<del> } else {
<add> } else if(isModLoaded(protection.modid, protection.version)) {
<ide> MyTown.instance.LOG.info("Adding protection for mod: {}", protection.modid);
<ide> ProtectionUtils.protections.add(protection);
<ide> }
<ide> }
<ide> }
<ide>
<add> private static boolean isModLoaded(String modid, String version) {
<add> for(ModContainer mod : Loader.instance().getModList()) {
<add> if(mod.getModId().equals(modid) && mod.getVersion().startsWith(version)) {
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<ide> private static SegmentBlock createSegmentBlock(Class<?> clazz, FlagType<Boolean> flagType, String conditionString, GettersContainer getters, BlockType blockType, int meta, Volume clientUpdateCoords) {
<ide> SegmentBlock segment = new SegmentBlock(meta, clientUpdateCoords);
<ide> if(getters != null) {
<ide> segment.setConditionString(conditionString);
<ide> return segment;
<ide> }
<del>
<del>
<del>
<ide> } |
|
Java | lgpl-2.1 | 3dffd9208e95b6b378fec4ac99f1e288b7b97a8b | 0 | aaronc/jfreechart,aaronc/jfreechart,aaronc/jfreechart | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------------------
* CrosshairOverlayTest.java
* -------------------------
* (C) Copyright 2009-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 10-Apr-2009 : Version 1 (DG);
*
*/
package org.jfree.chart.panel;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import org.jfree.chart.TestUtilities;
import org.jfree.chart.plot.Crosshair;
import org.junit.Test;
/**
* Tests for the {@link CrosshairOverlay} class.
*/
public class CrosshairOverlayTest {
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
CrosshairOverlay o1 = new CrosshairOverlay();
CrosshairOverlay o2 = new CrosshairOverlay();
assertEquals(o1, o2);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
CrosshairOverlay o1 = new CrosshairOverlay();
o1.addDomainCrosshair(new Crosshair(99.9));
o1.addRangeCrosshair(new Crosshair(1.23, new GradientPaint(1.0f, 2.0f,
Color.red, 3.0f, 4.0f, Color.blue), new BasicStroke(1.1f)));
CrosshairOverlay o2 = (CrosshairOverlay) TestUtilities.serialised(o1);
assertEquals(o1, o2);
}
/**
* Basic checks for cloning.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
CrosshairOverlay o1 = new CrosshairOverlay();
o1.addDomainCrosshair(new Crosshair(99.9));
o1.addRangeCrosshair(new Crosshair(1.23, new GradientPaint(1.0f, 2.0f,
Color.red, 3.0f, 4.0f, Color.blue), new BasicStroke(1.1f)));
CrosshairOverlay o2 = (CrosshairOverlay) o1.clone();
assertTrue(o1 != o2);
assertTrue(o1.getClass() == o2.getClass());
assertTrue(o1.equals(o2));
o1.addDomainCrosshair(new Crosshair(3.21));
o1.addRangeCrosshair(new Crosshair(4.32));
assertFalse(o1.equals(o2));
}
}
| tests/org/jfree/chart/panel/CrosshairOverlayTest.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------------------
* CrosshairOverlayTest.java
* -------------------------
* (C) Copyright 2009-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 10-Apr-2009 : Version 1 (DG);
*
*/
package org.jfree.chart.panel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.TestUtilities;
import org.jfree.chart.plot.Crosshair;
/**
* Tests for the {@link CrosshairOverlay} class.
*/
public class CrosshairOverlayTest extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(CrosshairOverlayTest.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public CrosshairOverlayTest(String name) {
super(name);
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
public void testEquals() {
CrosshairOverlay o1 = new CrosshairOverlay();
CrosshairOverlay o2 = new CrosshairOverlay();
assertEquals(o1, o2);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
CrosshairOverlay o1 = new CrosshairOverlay();
o1.addDomainCrosshair(new Crosshair(99.9));
o1.addRangeCrosshair(new Crosshair(1.23, new GradientPaint(1.0f, 2.0f,
Color.red, 3.0f, 4.0f, Color.blue), new BasicStroke(1.1f)));
CrosshairOverlay o2 = (CrosshairOverlay) TestUtilities.serialised(o1);
assertEquals(o1, o2);
}
/**
* Basic checks for cloning.
*/
public void testCloning() throws CloneNotSupportedException {
CrosshairOverlay o1 = new CrosshairOverlay();
o1.addDomainCrosshair(new Crosshair(99.9));
o1.addRangeCrosshair(new Crosshair(1.23, new GradientPaint(1.0f, 2.0f,
Color.red, 3.0f, 4.0f, Color.blue), new BasicStroke(1.1f)));
CrosshairOverlay o2 = (CrosshairOverlay) o1.clone();
assertTrue(o1 != o2);
assertTrue(o1.getClass() == o2.getClass());
assertTrue(o1.equals(o2));
o1.addDomainCrosshair(new Crosshair(3.21));
o1.addRangeCrosshair(new Crosshair(4.32));
assertFalse(o1.equals(o2));
}
}
| Convert to JUnit 4.11
git-svn-id: ca96c60061366ac92493e2142a352bb838ea8caa@2873 4df5dd95-b682-48b0-b31b-748e37b65e73
| tests/org/jfree/chart/panel/CrosshairOverlayTest.java | Convert to JUnit 4.11 | <ide><path>ests/org/jfree/chart/panel/CrosshairOverlayTest.java
<ide>
<ide> package org.jfree.chart.panel;
<ide>
<add>import static org.junit.Assert.assertTrue;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertEquals;
<add>
<ide> import java.awt.BasicStroke;
<ide> import java.awt.Color;
<ide> import java.awt.GradientPaint;
<ide>
<del>import junit.framework.Test;
<del>import junit.framework.TestCase;
<del>import junit.framework.TestSuite;
<ide> import org.jfree.chart.TestUtilities;
<ide>
<ide> import org.jfree.chart.plot.Crosshair;
<add>import org.junit.Test;
<ide>
<ide> /**
<ide> * Tests for the {@link CrosshairOverlay} class.
<ide> */
<del>public class CrosshairOverlayTest extends TestCase {
<del>
<del> /**
<del> * Returns the tests as a test suite.
<del> *
<del> * @return The test suite.
<del> */
<del> public static Test suite() {
<del> return new TestSuite(CrosshairOverlayTest.class);
<del> }
<del>
<del> /**
<del> * Constructs a new set of tests.
<del> *
<del> * @param name the name of the tests.
<del> */
<del> public CrosshairOverlayTest(String name) {
<del> super(name);
<del> }
<add>public class CrosshairOverlayTest {
<ide>
<ide> /**
<ide> * Confirm that the equals method can distinguish all the required fields.
<ide> */
<add> @Test
<ide> public void testEquals() {
<ide> CrosshairOverlay o1 = new CrosshairOverlay();
<ide> CrosshairOverlay o2 = new CrosshairOverlay();
<ide> /**
<ide> * Serialize an instance, restore it, and check for equality.
<ide> */
<add> @Test
<ide> public void testSerialization() {
<ide> CrosshairOverlay o1 = new CrosshairOverlay();
<ide> o1.addDomainCrosshair(new Crosshair(99.9));
<ide> /**
<ide> * Basic checks for cloning.
<ide> */
<add> @Test
<ide> public void testCloning() throws CloneNotSupportedException {
<ide> CrosshairOverlay o1 = new CrosshairOverlay();
<ide> o1.addDomainCrosshair(new Crosshair(99.9)); |
|
Java | apache-2.0 | 3b845ea95c5feaf093629d6c09b43c3260ea6176 | 0 | apache/flink,zjureel/flink,twalthr/flink,godfreyhe/flink,wwjiang007/flink,tony810430/flink,zjureel/flink,zjureel/flink,twalthr/flink,godfreyhe/flink,xccui/flink,godfreyhe/flink,zentol/flink,lincoln-lil/flink,lincoln-lil/flink,gyfora/flink,gyfora/flink,tony810430/flink,lincoln-lil/flink,tony810430/flink,apache/flink,tony810430/flink,xccui/flink,apache/flink,wwjiang007/flink,wwjiang007/flink,zjureel/flink,lincoln-lil/flink,gyfora/flink,lincoln-lil/flink,xccui/flink,zjureel/flink,twalthr/flink,xccui/flink,zjureel/flink,zentol/flink,tony810430/flink,godfreyhe/flink,zentol/flink,apache/flink,lincoln-lil/flink,tony810430/flink,xccui/flink,wwjiang007/flink,apache/flink,xccui/flink,wwjiang007/flink,wwjiang007/flink,gyfora/flink,zentol/flink,twalthr/flink,apache/flink,tony810430/flink,godfreyhe/flink,wwjiang007/flink,twalthr/flink,zentol/flink,godfreyhe/flink,gyfora/flink,gyfora/flink,lincoln-lil/flink,zentol/flink,zjureel/flink,xccui/flink,gyfora/flink,twalthr/flink,zentol/flink,godfreyhe/flink,apache/flink,twalthr/flink | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.tests;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.connector.elasticsearch.sink.Elasticsearch7SinkBuilder;
import org.apache.flink.connector.elasticsearch.sink.ElasticsearchSink;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Requests;
import java.util.HashMap;
import java.util.Map;
/** End to end test for Elasticsearch7Sink. */
public class Elasticsearch7SinkExample {
public static void main(String[] args) throws Exception {
final ParameterTool parameterTool = ParameterTool.fromArgs(args);
if (parameterTool.getNumberOfParameters() < 2) {
System.out.println(
"Missing parameters!\n" + "Usage: --numRecords <numRecords> --index <index>");
return;
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(5000);
DataStream<Tuple2<String, String>> source =
env.fromSequence(0, parameterTool.getInt("numRecords") - 1)
.flatMap(
new FlatMapFunction<Long, Tuple2<String, String>>() {
@Override
public void flatMap(
Long value, Collector<Tuple2<String, String>> out) {
final String key = String.valueOf(value);
final String message = "message #" + value;
out.collect(Tuple2.of(key, message + "update #1"));
out.collect(Tuple2.of(key, message + "update #2"));
}
});
ElasticsearchSink<Tuple2<String, String>> sink =
new Elasticsearch7SinkBuilder<Tuple2<String, String>>()
.setHosts(new HttpHost("127.0.0.1", 9200, "http"))
.setEmitter(
(element, ctx, indexer) -> {
indexer.add(createIndexRequest(element.f1, parameterTool));
indexer.add(createUpdateRequest(element, parameterTool));
})
.setBulkFlushMaxActions(1) // emit after every element, don't buffer
.build();
source.sinkTo(sink);
env.execute("Elasticsearch 7.x end to end sink test example");
}
private static IndexRequest createIndexRequest(String element, ParameterTool parameterTool) {
Map<String, Object> json = new HashMap<>();
json.put("data", element);
return Requests.indexRequest()
.index(parameterTool.getRequired("index"))
.id(element)
.source(json);
}
private static UpdateRequest createUpdateRequest(
Tuple2<String, String> element, ParameterTool parameterTool) {
Map<String, Object> json = new HashMap<>();
json.put("data", element.f1);
return new UpdateRequest(parameterTool.getRequired("index"), element.f0)
.doc(json)
.upsert(json);
}
}
| flink-end-to-end-tests/flink-elasticsearch7-test/src/main/java/org/apache/flink/streaming/tests/Elasticsearch7SinkExample.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.tests;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ActionRequestFailureHandler;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch7.ElasticsearchSink;
import org.apache.flink.util.Collector;
import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Requests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** End to end test for Elasticsearch6Sink. */
public class Elasticsearch7SinkExample {
public static void main(String[] args) throws Exception {
final ParameterTool parameterTool = ParameterTool.fromArgs(args);
if (parameterTool.getNumberOfParameters() < 2) {
System.out.println(
"Missing parameters!\n" + "Usage: --numRecords <numRecords> --index <index>");
return;
}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(5000);
DataStream<Tuple2<String, String>> source =
env.generateSequence(0, parameterTool.getInt("numRecords") - 1)
.flatMap(
new FlatMapFunction<Long, Tuple2<String, String>>() {
@Override
public void flatMap(
Long value, Collector<Tuple2<String, String>> out) {
final String key = String.valueOf(value);
final String message = "message #" + value;
out.collect(Tuple2.of(key, message + "update #1"));
out.collect(Tuple2.of(key, message + "update #2"));
}
});
List<HttpHost> httpHosts = new ArrayList<>();
httpHosts.add(new HttpHost("127.0.0.1", 9200, "http"));
ElasticsearchSink.Builder<Tuple2<String, String>> esSinkBuilder =
new ElasticsearchSink.Builder<>(
httpHosts,
(Tuple2<String, String> element,
RuntimeContext ctx,
RequestIndexer indexer) -> {
indexer.add(createIndexRequest(element.f1, parameterTool));
indexer.add(createUpdateRequest(element, parameterTool));
});
esSinkBuilder.setFailureHandler(
new CustomFailureHandler(parameterTool.getRequired("index")));
// this instructs the sink to emit after every element, otherwise they would be buffered
esSinkBuilder.setBulkFlushMaxActions(1);
source.addSink(esSinkBuilder.build());
env.execute("Elasticsearch 7.x end to end sink test example");
}
private static class CustomFailureHandler implements ActionRequestFailureHandler {
private static final long serialVersionUID = 942269087742453482L;
private final String index;
CustomFailureHandler(String index) {
this.index = index;
}
@Override
public void onFailure(
ActionRequest action, Throwable failure, int restStatusCode, RequestIndexer indexer)
throws Throwable {
if (action instanceof IndexRequest) {
Map<String, Object> json = new HashMap<>();
json.put("data", ((IndexRequest) action).source());
indexer.add(
Requests.indexRequest()
.index(index)
.id(((IndexRequest) action).id())
.source(json));
} else {
throw new IllegalStateException("unexpected");
}
}
}
private static IndexRequest createIndexRequest(String element, ParameterTool parameterTool) {
Map<String, Object> json = new HashMap<>();
json.put("data", element);
String index;
if (element.startsWith("message #15")) {
index = ":intentional invalid index:";
} else {
index = parameterTool.getRequired("index");
}
return Requests.indexRequest().index(index).id(element).source(json);
}
private static UpdateRequest createUpdateRequest(
Tuple2<String, String> element, ParameterTool parameterTool) {
Map<String, Object> json = new HashMap<>();
json.put("data", element.f1);
return new UpdateRequest(parameterTool.getRequired("index"), element.f0)
.doc(json)
.upsert(json);
}
}
| [FLINK-26185] Update Elasticsearch7SinkExample to use new unified Sink interface
| flink-end-to-end-tests/flink-elasticsearch7-test/src/main/java/org/apache/flink/streaming/tests/Elasticsearch7SinkExample.java | [FLINK-26185] Update Elasticsearch7SinkExample to use new unified Sink interface | <ide><path>link-end-to-end-tests/flink-elasticsearch7-test/src/main/java/org/apache/flink/streaming/tests/Elasticsearch7SinkExample.java
<ide> package org.apache.flink.streaming.tests;
<ide>
<ide> import org.apache.flink.api.common.functions.FlatMapFunction;
<del>import org.apache.flink.api.common.functions.RuntimeContext;
<ide> import org.apache.flink.api.java.tuple.Tuple2;
<ide> import org.apache.flink.api.java.utils.ParameterTool;
<add>import org.apache.flink.connector.elasticsearch.sink.Elasticsearch7SinkBuilder;
<add>import org.apache.flink.connector.elasticsearch.sink.ElasticsearchSink;
<ide> import org.apache.flink.streaming.api.datastream.DataStream;
<ide> import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
<del>import org.apache.flink.streaming.connectors.elasticsearch.ActionRequestFailureHandler;
<del>import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
<del>import org.apache.flink.streaming.connectors.elasticsearch7.ElasticsearchSink;
<ide> import org.apache.flink.util.Collector;
<ide>
<ide> import org.apache.http.HttpHost;
<del>import org.elasticsearch.action.ActionRequest;
<ide> import org.elasticsearch.action.index.IndexRequest;
<ide> import org.elasticsearch.action.update.UpdateRequest;
<ide> import org.elasticsearch.client.Requests;
<ide>
<del>import java.util.ArrayList;
<ide> import java.util.HashMap;
<del>import java.util.List;
<ide> import java.util.Map;
<ide>
<del>/** End to end test for Elasticsearch6Sink. */
<add>/** End to end test for Elasticsearch7Sink. */
<ide> public class Elasticsearch7SinkExample {
<ide>
<ide> public static void main(String[] args) throws Exception {
<ide> env.enableCheckpointing(5000);
<ide>
<ide> DataStream<Tuple2<String, String>> source =
<del> env.generateSequence(0, parameterTool.getInt("numRecords") - 1)
<add> env.fromSequence(0, parameterTool.getInt("numRecords") - 1)
<ide> .flatMap(
<ide> new FlatMapFunction<Long, Tuple2<String, String>>() {
<ide> @Override
<ide> }
<ide> });
<ide>
<del> List<HttpHost> httpHosts = new ArrayList<>();
<del> httpHosts.add(new HttpHost("127.0.0.1", 9200, "http"));
<add> ElasticsearchSink<Tuple2<String, String>> sink =
<add> new Elasticsearch7SinkBuilder<Tuple2<String, String>>()
<add> .setHosts(new HttpHost("127.0.0.1", 9200, "http"))
<add> .setEmitter(
<add> (element, ctx, indexer) -> {
<add> indexer.add(createIndexRequest(element.f1, parameterTool));
<add> indexer.add(createUpdateRequest(element, parameterTool));
<add> })
<add> .setBulkFlushMaxActions(1) // emit after every element, don't buffer
<add> .build();
<ide>
<del> ElasticsearchSink.Builder<Tuple2<String, String>> esSinkBuilder =
<del> new ElasticsearchSink.Builder<>(
<del> httpHosts,
<del> (Tuple2<String, String> element,
<del> RuntimeContext ctx,
<del> RequestIndexer indexer) -> {
<del> indexer.add(createIndexRequest(element.f1, parameterTool));
<del> indexer.add(createUpdateRequest(element, parameterTool));
<del> });
<del>
<del> esSinkBuilder.setFailureHandler(
<del> new CustomFailureHandler(parameterTool.getRequired("index")));
<del>
<del> // this instructs the sink to emit after every element, otherwise they would be buffered
<del> esSinkBuilder.setBulkFlushMaxActions(1);
<del>
<del> source.addSink(esSinkBuilder.build());
<del>
<add> source.sinkTo(sink);
<ide> env.execute("Elasticsearch 7.x end to end sink test example");
<del> }
<del>
<del> private static class CustomFailureHandler implements ActionRequestFailureHandler {
<del>
<del> private static final long serialVersionUID = 942269087742453482L;
<del>
<del> private final String index;
<del>
<del> CustomFailureHandler(String index) {
<del> this.index = index;
<del> }
<del>
<del> @Override
<del> public void onFailure(
<del> ActionRequest action, Throwable failure, int restStatusCode, RequestIndexer indexer)
<del> throws Throwable {
<del> if (action instanceof IndexRequest) {
<del> Map<String, Object> json = new HashMap<>();
<del> json.put("data", ((IndexRequest) action).source());
<del>
<del> indexer.add(
<del> Requests.indexRequest()
<del> .index(index)
<del> .id(((IndexRequest) action).id())
<del> .source(json));
<del> } else {
<del> throw new IllegalStateException("unexpected");
<del> }
<del> }
<ide> }
<ide>
<ide> private static IndexRequest createIndexRequest(String element, ParameterTool parameterTool) {
<ide> Map<String, Object> json = new HashMap<>();
<ide> json.put("data", element);
<ide>
<del> String index;
<del> if (element.startsWith("message #15")) {
<del> index = ":intentional invalid index:";
<del> } else {
<del> index = parameterTool.getRequired("index");
<del> }
<del>
<del> return Requests.indexRequest().index(index).id(element).source(json);
<add> return Requests.indexRequest()
<add> .index(parameterTool.getRequired("index"))
<add> .id(element)
<add> .source(json);
<ide> }
<ide>
<ide> private static UpdateRequest createUpdateRequest( |
|
Java | mit | 983846ec7810616b70d8ddeb961d1c1c66279627 | 0 | GaloisInc/Votail,GaloisInc/Votail,GaloisInc/Votail | /**
* @author Dermot Cochran, 2010-2011, IT University of Copenhagen
*
* This class generates ballot boxes that create an electoral scenario,
* for example, one winner by tie breaker and two losers, or one winner
* by
* quota, one winner as the highest continuing candidate on the last
* round, and
* three losers below the threshold.
*/
package ie.votail.model.factory;
import ie.votail.model.ElectoralScenario;
import ie.votail.model.ElectionConfiguration;
import ie.votail.model.Outcome;
import java.util.Map;
import java.util.logging.Logger;
import edu.mit.csail.sdg.alloy4.A4Reporter;
import edu.mit.csail.sdg.alloy4.Err;
import edu.mit.csail.sdg.alloy4.ErrorSyntax;
import edu.mit.csail.sdg.alloy4.Pair;
import edu.mit.csail.sdg.alloy4.SafeList;
import edu.mit.csail.sdg.alloy4compiler.ast.Command;
import edu.mit.csail.sdg.alloy4compiler.ast.Expr;
import edu.mit.csail.sdg.alloy4compiler.ast.Sig;
import edu.mit.csail.sdg.alloy4compiler.ast.Sig.Field;
import edu.mit.csail.sdg.alloy4compiler.parser.CompModule;
import edu.mit.csail.sdg.alloy4compiler.parser.CompUtil;
import edu.mit.csail.sdg.alloy4compiler.translator.A4Options;
import edu.mit.csail.sdg.alloy4compiler.translator.A4Solution;
import edu.mit.csail.sdg.alloy4compiler.translator.A4TupleSet;
import edu.mit.csail.sdg.alloy4compiler.translator.TranslateAlloyToKodkod;
/**
*
*/
public class BallotBoxFactory {
public static final int DEFAULT_BIT_WIDTH = 7;
public static final String LOGGER_NAME = "votail.log";
public static final String MODELS_VOTING_ALS = "./models/voting.als";
protected final static Logger logger = Logger.getLogger(LOGGER_NAME);
private static final int MAX_SCOPE = 20;
protected String modelName;
/**
*
*/
public BallotBoxFactory() {
modelName = MODELS_VOTING_ALS;
logger.info("Using model " + modelName);
}
/**
* Generate Ballots for an Election Configuration from an Electoral Scenario
*
* @param scenario
* The scenario which will be tested by this ballot box
* @param scope
* The scope for model finding in Alloy Analyser
* @param byeElection
* @return The ELection Configuration (null if generation fails)
*/
public ElectionConfiguration /*@ non_null @*/extractBallots(
/*@ non_null*/ElectoralScenario scenario, int scope) {
return extractBallots(scenario, scope, MAX_SCOPE);
}
/**
* Generate ballot box test data
*
* @param scenario
* The set of election outcomes
* @param scope
* The initial scope for the Alloy solution
* @param upperBound
* The maximum scope
* @return The Ballot Box
*/
public ElectionConfiguration extractBallots(ElectoralScenario scenario,
int scope, int upperBound) {
final ElectionConfiguration electionConfiguration =
new ElectionConfiguration(scenario.canonical());
electionConfiguration.setNumberOfWinners(scenario.numberOfWinners());
final int numberOfSeats = scenario.numberOfWinners();
if (scenario.isByeElection()) {
electionConfiguration.setNumberOfSeats(1);
}
else {
electionConfiguration.setNumberOfSeats(numberOfSeats);
}
final int numberOfCandidates = scenario.getNumberOfCandidates();
electionConfiguration.setNumberOfCandidates(numberOfCandidates);
logger.info(numberOfCandidates + " candidates for " + numberOfSeats
+ " seats");
// Find a ballot box which creates this scenario
try {
A4Solution solution = findSolution(scenario, scope);
logger.info("Using scope = " + scope + " found scenario " + scenario);
if (solution.satisfiable()) { // Extract ballots from the solution
// Iterate through the solution and add each vote to the table
for (Sig sig : solution.getAllReachableSigs()) {
// Log the model version number
if (sig.label.contains("Version")) {
for (Field field : sig.getFields()) {
if (field.label.contains("year")) {
A4TupleSet tupleSet = solution.eval(field);
logger.info("Model version year = " + tupleSet.toString());
}
else if (field.label.contains("month")) {
A4TupleSet tupleSet = solution.eval(field);
logger.info("Model version month = " + tupleSet.toString());
}
else if (field.label.contains("day")) {
A4TupleSet tupleSet = solution.eval(field);
logger.info("Model version day = " + tupleSet.toString());
}
}
}
else if (sig.label.contains("this/Ballot")) {
for (Field field : sig.getFields()) {
if (field.label.contains("preferences")) {
A4TupleSet tupleSet = solution.eval(field);
//@ assert tupleSet != null;
electionConfiguration.extractPreferences(tupleSet);
}
}
}
}
logger.info("Scenario for " + scenario + " has "
+ electionConfiguration);
return electionConfiguration.trim();
}
// Increase the scope and try again
if (!scenario.hasOutcome(Outcome.TiedSoreLoser) && scope < upperBound) {
return extractBallots(scenario, scope + 1);
}
else {
logger.info("Skipped this scenario " + scenario.toString());
return electionConfiguration.trim();
}
}
catch (Err e) {
// Log failure to find scenario
logger.severe("Unable to find ballot box for this scenario "
+ scenario.toString() + " with scope " + scope + " and predicate "
+ scenario.toPredicate() + " because " + e.msg);
return electionConfiguration.trim();
}
}
/**
* Find the Alloy solution for an electoral scenario
*
* @param scenario
* The electoral scenario
* @param scope
* The scope of the search
* @return The Alloy solution
* @throws Err
* @throws ErrorSyntax
*/
protected A4Solution findSolution(ElectoralScenario scenario, int scope)
throws Err, ErrorSyntax {
A4Reporter reporter = new A4Reporter();
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.SAT4J;
Map<String, String> loaded = null;
CompModule world =
CompUtil.parseEverything_fromFile(reporter, loaded, modelName);
SafeList<Pair<String, Expr>> facts = world.getAllFacts();
Expr predicate =
CompUtil.parseOneExpression_fromString(world, scenario.toPredicate());
logger.finest("Using this predicate: " + predicate.toString() + " "
+ predicate.getDescription());
Command command =
new Command(false, scope, DEFAULT_BIT_WIDTH, scope, predicate);
logger.info("using scope " + scope + " and bitwidth " + DEFAULT_BIT_WIDTH);
A4Solution solution =
TranslateAlloyToKodkod.execute_command(reporter, world
.getAllReachableSigs(), command, options);
logger.finest("Found this solution: " + solution.toString());
return solution;
}
}
| src/ie/votail/model/factory/BallotBoxFactory.java | /**
* @author Dermot Cochran, 2010-2011, IT University of Copenhagen
*
* This class generates ballot boxes that create an electoral scenario,
* for example, one winner by tie breaker and two losers, or one winner
* by
* quota, one winner as the highest continuing candidate on the last
* round, and
* three losers below the threshold.
*/
package ie.votail.model.factory;
import ie.votail.model.ElectoralScenario;
import ie.votail.model.ElectionConfiguration;
import ie.votail.model.Outcome;
import java.util.Map;
import java.util.logging.Logger;
import edu.mit.csail.sdg.alloy4.A4Reporter;
import edu.mit.csail.sdg.alloy4.Err;
import edu.mit.csail.sdg.alloy4.ErrorSyntax;
import edu.mit.csail.sdg.alloy4.Pair;
import edu.mit.csail.sdg.alloy4.SafeList;
import edu.mit.csail.sdg.alloy4compiler.ast.Command;
import edu.mit.csail.sdg.alloy4compiler.ast.Expr;
import edu.mit.csail.sdg.alloy4compiler.ast.Sig;
import edu.mit.csail.sdg.alloy4compiler.ast.Sig.Field;
import edu.mit.csail.sdg.alloy4compiler.parser.CompModule;
import edu.mit.csail.sdg.alloy4compiler.parser.CompUtil;
import edu.mit.csail.sdg.alloy4compiler.translator.A4Options;
import edu.mit.csail.sdg.alloy4compiler.translator.A4Solution;
import edu.mit.csail.sdg.alloy4compiler.translator.A4TupleSet;
import edu.mit.csail.sdg.alloy4compiler.translator.TranslateAlloyToKodkod;
/**
*
*/
public class BallotBoxFactory {
public static final int DEFAULT_BIT_WIDTH = 7;
public static final String LOGGER_NAME = "votail.log";
public static final String MODELS_VOTING_ALS = "./models/voting.als";
protected final static Logger logger = Logger.getLogger(LOGGER_NAME);
private static final int MAX_SCOPE = 20;
protected String modelName;
/**
*
*/
public BallotBoxFactory() {
modelName = MODELS_VOTING_ALS;
logger.info("Using model " + modelName);
}
/**
* Generate Ballots for an Election Configuration from an Electoral Scenario
*
* @param scenario
* The scenario which will be tested by this ballot box
* @param scope
* The scope for model finding in Alloy Analyser
* @param byeElection
* @return The ELection Configuration (null if generation fails)
*/
public ElectionConfiguration /*@ non_null @*/extractBallots(
/*@ non_null*/ElectoralScenario scenario, int scope) {
return extractBallots(scenario, scope, MAX_SCOPE);
}
/**
* Generate ballot box test data
*
* @param scenario The set of election outcomes
* @param scope The initial scope for the Alloy solution
* @param upperBound The maximum scope
* @return The Ballot Box
*/
public ElectionConfiguration extractBallots(ElectoralScenario scenario,
int scope, int upperBound) {
final ElectionConfiguration electionConfiguration =
new ElectionConfiguration(scenario.canonical());
electionConfiguration.setNumberOfWinners(scenario.numberOfWinners());
final int numberOfSeats = scenario.numberOfWinners();
if (scenario.isByeElection()) {
electionConfiguration.setNumberOfSeats(1);
}
else {
electionConfiguration.setNumberOfSeats(numberOfSeats);
}
final int numberOfCandidates = scenario.getNumberOfCandidates();
electionConfiguration.setNumberOfCandidates(numberOfCandidates);
logger.info(numberOfCandidates + " candidates for " + numberOfSeats
+ " seats");
// Find a ballot box which creates this scenario
try {
A4Solution solution = findSolution(scenario, scope);
logger.info("Using scope = " + scope + " found scenario " + scenario);
if (solution.satisfiable()) { // Extract ballots from the solution
// Iterate through the solution and add each vote to the table
for (Sig sig : solution.getAllReachableSigs()) {
// Log the model version number
if (sig.label.contains("Version")) {
for (Field field : sig.getFields()) {
if (field.label.contains("year")) {
A4TupleSet tupleSet = solution.eval(field);
logger.info(tupleSet.toString());
}
else if (field.label.contains("month")) {
A4TupleSet tupleSet = solution.eval(field);
logger.info(tupleSet.toString());
}
else if (field.label.contains("day")) {
A4TupleSet tupleSet = solution.eval(field);
logger.info(tupleSet.toString());
}
}
}
else if (sig.label.contains("this/Ballot")) {
for (Field field : sig.getFields()) {
if (field.label.contains("preferences")) {
A4TupleSet tupleSet = solution.eval(field);
//@ assert tupleSet != null;
electionConfiguration.extractPreferences(tupleSet);
}
}
}
}
logger.info("Scenario for " + scenario + " has "
+ electionConfiguration);
return electionConfiguration.trim();
}
// Increase the scope and try again
if (!scenario.hasOutcome(Outcome.TiedSoreLoser) && scope < upperBound) {
return extractBallots(scenario, scope + 1);
}
else {
logger.info("Skipped this scenario " + scenario.toString());
return electionConfiguration.trim();
}
}
catch (Err e) {
// Log failure to find scenario
logger.severe("Unable to find ballot box for this scenario "
+ scenario.toString() + " with scope " + scope + " and predicate "
+ scenario.toPredicate() + " because " + e.msg);
return electionConfiguration.trim();
}
}
/**
* Find the Alloy solution for an electoral scenario
*
* @param scenario The electoral scenario
* @param scope The scope of the search
* @return The Alloy solution
* @throws Err
* @throws ErrorSyntax
*/
protected A4Solution findSolution(ElectoralScenario scenario, int scope)
throws Err, ErrorSyntax {
A4Reporter reporter = new A4Reporter();
A4Options options = new A4Options();
options.solver = A4Options.SatSolver.SAT4J;
Map<String, String> loaded = null;
CompModule world =
CompUtil.parseEverything_fromFile(reporter, loaded, modelName);
SafeList<Pair<String, Expr>> facts = world.getAllFacts();
Expr predicate =
CompUtil.parseOneExpression_fromString(world, scenario.toPredicate());
logger.finest("Using this predicate: " + predicate.toString() + " "
+ predicate.getDescription());
Command command =
new Command(false, scope, DEFAULT_BIT_WIDTH, scope, predicate);
logger.info("using scope " + scope + " and bitwidth " + DEFAULT_BIT_WIDTH);
A4Solution solution =
TranslateAlloyToKodkod.execute_command(reporter, world
.getAllReachableSigs(), command, options);
logger.finest("Found this solution: " + solution.toString());
return solution;
}
}
| Improved logging of model version date.
| src/ie/votail/model/factory/BallotBoxFactory.java | Improved logging of model version date. | <ide><path>rc/ie/votail/model/factory/BallotBoxFactory.java
<ide>
<ide> return extractBallots(scenario, scope, MAX_SCOPE);
<ide> }
<del>
<add>
<ide> /**
<ide> * Generate ballot box test data
<ide> *
<del> * @param scenario The set of election outcomes
<del> * @param scope The initial scope for the Alloy solution
<del> * @param upperBound The maximum scope
<add> * @param scenario
<add> * The set of election outcomes
<add> * @param scope
<add> * The initial scope for the Alloy solution
<add> * @param upperBound
<add> * The maximum scope
<ide> * @return The Ballot Box
<ide> */
<ide> public ElectionConfiguration extractBallots(ElectoralScenario scenario,
<ide> for (Field field : sig.getFields()) {
<ide> if (field.label.contains("year")) {
<ide> A4TupleSet tupleSet = solution.eval(field);
<del> logger.info(tupleSet.toString());
<add> logger.info("Model version year = " + tupleSet.toString());
<ide> }
<ide> else if (field.label.contains("month")) {
<ide> A4TupleSet tupleSet = solution.eval(field);
<del> logger.info(tupleSet.toString());
<add> logger.info("Model version month = " + tupleSet.toString());
<ide> }
<ide> else if (field.label.contains("day")) {
<ide> A4TupleSet tupleSet = solution.eval(field);
<del> logger.info(tupleSet.toString());
<add> logger.info("Model version day = " + tupleSet.toString());
<ide> }
<ide> }
<ide> }
<ide> /**
<ide> * Find the Alloy solution for an electoral scenario
<ide> *
<del> * @param scenario The electoral scenario
<del> * @param scope The scope of the search
<add> * @param scenario
<add> * The electoral scenario
<add> * @param scope
<add> * The scope of the search
<ide> * @return The Alloy solution
<ide> * @throws Err
<ide> * @throws ErrorSyntax |
|
Java | apache-2.0 | da5d251dac01b36eaf20fd7db018a50c37ae4e8e | 0 | vtatai/srec,vtatai/srec | package com.github.srec.jemmy;
import com.github.srec.UnsupportedFeatureException;
import com.github.srec.command.exception.AssertionFailedException;
import com.github.srec.util.AWTTreeScanner;
import com.github.srec.util.ScannerMatcher;
import com.github.srec.util.Utils;
import org.apache.log4j.Logger;
import org.netbeans.jemmy.ComponentChooser;
import org.netbeans.jemmy.ComponentSearcher;
import org.netbeans.jemmy.JemmyException;
import org.netbeans.jemmy.JemmyProperties;
import org.netbeans.jemmy.TestOut;
import org.netbeans.jemmy.Timeouts;
import org.netbeans.jemmy.Waitable;
import org.netbeans.jemmy.Waiter;
import org.netbeans.jemmy.operators.AbstractButtonOperator;
import org.netbeans.jemmy.operators.ComponentOperator;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JCheckBoxOperator;
import org.netbeans.jemmy.operators.JComboBoxOperator;
import org.netbeans.jemmy.operators.JComponentOperator;
import org.netbeans.jemmy.operators.JDialogOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JInternalFrameOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.JListOperator;
import org.netbeans.jemmy.operators.JMenuBarOperator;
import org.netbeans.jemmy.operators.JMenuItemOperator;
import org.netbeans.jemmy.operators.JMenuOperator;
import org.netbeans.jemmy.operators.JRadioButtonOperator;
import org.netbeans.jemmy.operators.JScrollBarOperator;
import org.netbeans.jemmy.operators.JScrollPaneOperator;
import org.netbeans.jemmy.operators.JSliderOperator;
import org.netbeans.jemmy.operators.JTabbedPaneOperator;
import org.netbeans.jemmy.operators.JTableHeaderOperator;
import org.netbeans.jemmy.operators.JTableOperator;
import org.netbeans.jemmy.operators.JTextAreaOperator;
import org.netbeans.jemmy.operators.JTextComponentOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import org.netbeans.jemmy.operators.JToggleButtonOperator;
import org.netbeans.jemmy.operators.Operator;
import org.netbeans.jemmy.operators.Operator.StringComparator;
import org.netbeans.jemmy.util.NameComponentChooser;
import java.awt.FontMetrics;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import javax.swing.text.JTextComponent;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* A DSL wrapper for Jemmy operators.
*
* @author Victor Tatai
*/
public class JemmyDSL {
private static final Logger logger = Logger.getLogger(JemmyDSL.class);
private static final StringComparator comparator = new Operator.DefaultStringComparator(true,false);
public enum ComponentType {
text_field(JTextFieldOperator.class, JTextField.class),
combo_box(JComboBoxOperator.class, JComboBox.class),
button(JButtonOperator.class, JButton.class),
radio_button(JRadioButtonOperator.class, JRadioButton.class),
check_box(JCheckBoxOperator.class, JCheckBox.class),
table(TableOperator.class, JTable.class),
menu_bar(JMenuBarOperator.class, JMenuBar.class),
dialog(JDialogOperator.class, JDialog.class),
text_area(JTextAreaOperator.class, JTextArea.class),
scroll_pane(JScrollPaneOperator.class, JScrollPane.class);
private final Class<? extends ComponentOperator> operatorClass;
private final Class<? extends java.awt.Component> awtClass;
ComponentType(Class<? extends ComponentOperator> operatorClass,
Class<? extends java.awt.Component> awtClass) {
this.operatorClass = operatorClass;
this.awtClass = awtClass;
}
public Class<? extends ComponentOperator> getOperatorClass() {
return operatorClass;
}
public Class<? extends java.awt.Component> getAwtClass() {
return awtClass;
}
}
private static Window currentWindow;
private static Properties props = new Properties();
static {
props.put("ComponentOperator.WaitComponentEnabledTimeout", "15000");
props.put("ComponentOperator.WaitComponentTimeout", "15000");
props.put("ComponentOperator.WaitStateTimeout", "10000");
props.put("DialogWaiter.WaitDialogTimeout", "10000");
props.put("FrameWaiter.WaitFrameTimeout", "10000");
props.put("JComboBoxOperator.WaitListTimeout", "30000");
props.put("JScrollBarOperator.WholeScrollTimeout", "10000");
props.put("JSliderOperator.WholeScrollTimeout", "10000");
props.put("JSplitPaneOperator.WholeScrollTimeout", "10000");
props.put("ScrollbarOperator.WholeScrollTimeout", "10000");
props.put("Waiter.WaitingTime", "10000");
props.put("WindowWaiter.WaitWindowTimeout", "10000");
}
private static List<java.awt.Container> ignored = new ArrayList<java.awt.Container>();
private static ComponentMap componentMap = new DefaultComponentMap();
public static void init(java.awt.Container... ignored) {
Timeouts timeouts = JemmyProperties.getCurrentTimeouts();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
timeouts.setTimeout((String) entry.getKey(), Long.parseLong((String) entry.getValue()));
}
currentWindow = null;
JemmyDSL.ignored = Arrays.asList(ignored);
JemmyProperties.setCurrentOutput(new TestOut(System.in, (PrintStream) null, null));
robotMode();
}
public static void robotMode() {
JemmyProperties.setCurrentDispatchingModel(JemmyProperties.ROBOT_MODEL_MASK);
}
public static void dispatchingMode() {
JemmyProperties.setCurrentDispatchingModel(JemmyProperties.QUEUE_MODEL_MASK);
}
public static boolean isRobotMode() {
return JemmyProperties.getCurrentDispatchingModel() == JemmyProperties.ROBOT_MODEL_MASK;
}
public static ComponentMap getComponentMap() {
return componentMap;
}
public static void setComponentMap(ComponentMap componentMap) {
JemmyDSL.componentMap = componentMap;
}
public static Frame frame(String title) {
Frame frame = new Frame(title);
currentWindow = frame;
return frame;
}
public static Frame frame() {
return (Frame) currentWindow;
}
public static Window currentWindow() {
if (currentWindow == null) {
logger.info("No current container found, trying to find one.");
currentWindow = findActiveWindow();
} else if (!currentWindow.isActive()) {
currentWindow = findActiveWindow();
}
if (currentWindow == null)
throw new JemmyDSLException("Cannot find a currently active window");
logger.info("Using as current container: " + currentWindow.getComponent());
return currentWindow;
}
private static Window findActiveWindow() {
java.awt.Window[] windows = JFrame.getWindows();
for (java.awt.Window w : windows) {
if (ignored.contains(w))
continue;
if (!w.isActive())
continue;
if (w instanceof JFrame) {
return new Frame((JFrame) w);
} else if (w instanceof JDialog) {
return new Dialog((JDialog) w);
} else {
logger.info("Found a window which is neither a JFrame nor JDialog");
}
}
return null;
}
public static Container container(JFrame frame) {
currentWindow = new Frame(frame);
return currentWindow;
}
public static Dialog dialog(String title) {
final Dialog dialog = new Dialog(title);
currentWindow = dialog;
return dialog;
}
public static TextField textField(String locator) {
return new TextField(locator);
}
public static TextArea textArea(String locator) {
return new TextArea(locator);
}
public static Button button(String locator) {
return new Button(locator);
}
public static ComboBox comboBox(String locator) {
return new ComboBox(locator);
}
public static CheckBox checkBox(String locator) {
return new CheckBox(locator);
}
public static Table table(String locator) {
return new Table(locator);
}
/**
* Finds a component and stores it under the given id. The component can later be used on other
* commands using the locator "id=ID_ASSIGNED". This method searches both VISIBLE and INVISIBLE
* components.
*
* @param locator The locator (accepted are name (default), title, text, label)
* @param id The id
* @param componentType The component type
* @return The component found
*/
@SuppressWarnings({"unchecked"})
public static Component find(String locator, String id, String componentType) {
java.awt.Component component = findComponent(locator, currentWindow().getComponent()
.getSource());
if (component == null) {
componentMap.putComponent(id, null);
return null;
}
JComponentOperator operator = convertFind(component);
componentMap.putComponent(id, operator);
final Component finalComponent = convertFind(operator);
if (finalComponent instanceof Window) {
currentWindow = (Window) finalComponent;
}
return finalComponent;
}
@SuppressWarnings({"unchecked"})
private static Class<? extends java.awt.Component> translateFindType(String findType) {
for (ComponentType componentType : ComponentType.values()) {
if (findType.equals(componentType.name()))
return componentType.getAwtClass();
}
try {
return (Class<? extends java.awt.Component>) Class.forName(findType);
} catch (ClassNotFoundException e) {
throw new JemmyDSLException("Unsupported find type " + findType);
}
}
public static java.awt.Component findComponent(String locator, java.awt.Component component) {
assert locator != null;
String[] strs = parseLocator(locator);
if (strs.length != 2)
throw new JemmyDSLException("Invalid locator " + locator);
if (strs[0].equals("id")) {
return componentMap.getComponent(strs[1]).getSource();
} else {
return AWTTreeScanner.scan(component, compileMatcher(strs));
}
}
private static String[] parseLocator(String locator) {
int i = locator.indexOf("=");
if (i == -1) {
return new String[]{"name", locator.substring(i + 1).trim()};
}
return new String[]{locator.substring(0, i).trim(), locator.substring(i + 1).trim()};
}
private static ScannerMatcher compileMatcher(String[] strs) {
if (strs[0].equals("name"))
return new AWTTreeScanner.NameScannerMatcher(strs[1]);
if (strs[0].equals("title"))
return new AWTTreeScanner.TitleScannerMatcher(strs[1]);
if (strs[0].equals("text"))
return new AWTTreeScanner.TextScannerMatcher(strs[1]);
throw new JemmyDSLException("Invalid locator " + strs[0] + "=" + strs[1]);
}
/**
* Returns a list of all visible components which are instances of the given class. If one needs
* a find that returns an invisible component should add a parameter here. But the default
* behavior must be returning only visible components as it is the most common operation and
* required for compatibility with scripts converted from jfcunit. see #15790.
*
* @param container
* @param componentClass
* @return
*/
private static List<java.awt.Component> findComponents(java.awt.Container container,
Class<? extends java.awt.Component> componentClass) {
List<java.awt.Component> list = new ArrayList<java.awt.Component>();
for (java.awt.Component component : container.getComponents()) {
if (component.isVisible() && componentClass.isAssignableFrom(component.getClass())) {
list.add(component);
}
if (component instanceof java.awt.Container) {
List<java.awt.Component> children = findComponents((java.awt.Container) component,
componentClass);
list.addAll(children);
}
}
return list;
}
private static JComponentOperator convertFind(java.awt.Component comp) {
if (comp instanceof JComboBox)
return new JComboBoxOperator((JComboBox) comp);
if (comp instanceof JTextArea)
return new JTextAreaOperator((JTextArea) comp);
if (comp instanceof JTextComponent)
return new JTextFieldOperator((JTextField) comp);
if (comp instanceof JScrollPane)
return new JScrollPaneOperator((JScrollPane) comp);
if (comp instanceof JCheckBox)
return new JCheckBoxOperator((JCheckBox) comp);
if (comp instanceof JRadioButton)
return new JRadioButtonOperator((JRadioButton) comp);
if (comp instanceof JButton)
return new JButtonOperator((JButton) comp);
if (comp instanceof AbstractButton)
return new AbstractButtonOperator((AbstractButton) comp);
if (comp instanceof JTable) {
return new TableOperator((JTable) comp);
}
if (comp instanceof JMenuBar)
return new JMenuBarOperator((JMenuBar) comp);
if (comp instanceof JScrollBar)
return new JScrollBarOperator((JScrollBar) comp);
if (comp instanceof JInternalFrame)
return new JInternalFrameOperator((JInternalFrame) comp);
throw new JemmyDSLException("Unsupported find type " + comp);
}
private static Component convertFind(JComponentOperator comp) {
if (comp instanceof JComboBoxOperator)
return new ComboBox((JComboBoxOperator) comp);
if (comp instanceof JTextAreaOperator)
return new TextArea((JTextAreaOperator) comp);
if (comp instanceof JTextComponentOperator)
return new TextField((JTextFieldOperator) comp);
if (comp instanceof JScrollPaneOperator)
return new ScrollPane((JScrollPaneOperator) comp);
if (comp instanceof JCheckBoxOperator)
return new CheckBox((JCheckBoxOperator) comp);
if (comp instanceof JRadioButtonOperator)
return new RadioButton((JRadioButtonOperator) comp);
if (comp instanceof JButtonOperator)
return new Button((JButtonOperator) comp);
if (comp instanceof AbstractButtonOperator)
return new GenericButton((AbstractButtonOperator) comp);
if (comp instanceof JTableOperator)
return new Table((JTableOperator) comp);
if (comp instanceof JMenuBarOperator)
return new MenuBar((JMenuBarOperator) comp);
if (comp instanceof JScrollBarOperator)
return new ScrollBar((JScrollBarOperator) comp);
// not really sure this is the right thing to do, but constructor here expects a component
// and not an operator:
if (comp instanceof JInternalFrameOperator)
return new InternalFrame((JInternalFrame) ((JInternalFrameOperator) comp).getSource());
throw new JemmyDSLException("Unsupported find type " + comp);
}
/**
* Finds the first component with the given component type and stores it under the given id. The
* component can later be used on other commands using the locator "id=ID_ASSIGNED". This method
* searches both VISIBLE and INVISIBLE components.
*
* @param id The id
* @param componentType The component type
* @return The component found
*/
@SuppressWarnings({"unchecked"})
public static Component findByComponentType(String id,
String containerId,
String componentType,
int index) {
java.awt.Container container;
if (isBlank(containerId)) {
container = (java.awt.Container) currentWindow().getComponent().getSource();
} else {
ComponentOperator op = componentMap.getComponent(containerId);
if (op != null && op.getSource() instanceof java.awt.Container) {
container = (java.awt.Container) op.getSource();
} else {
container = (java.awt.Container) currentWindow().getComponent().getSource();
}
}
List<java.awt.Component> list = findComponents(container, translateFindType(componentType));
if (logger.isDebugEnabled()) {
logger.debug("findComponents returned list :");
for (java.awt.Component c : list) {
logger.debug(" " + c.getName());
}
logger.debug(" index = " + index);
}
if (index < 0 || index >= list.size()) {
return null;
}
java.awt.Component component = list.get(index);
if (component == null) {
componentMap.putComponent(id, null);
logger.debug("findByComponentType returned null");
return null;
}
JComponentOperator operator = convertFind(component);
componentMap.putComponent(id, operator);
if (logger.isDebugEnabled()) {
logger.debug("findByComponentType returned " + component);
}
return convertFind(operator);
}
public static void click(String locator, int count, String modifiers) {
final JComponentOperator operator = find(locator, JComponentOperator.class);
if (operator == null)
throw new JemmyDSLException("Could not find component for clicking " + locator);
operator.clickMouse(operator.getCenterXForClick(),
operator.getCenterYForClick(),
count,
InputEvent.BUTTON1_MASK,
convertModifiers(modifiers));
}
public static void typeSpecial(String locator, String keyString, String modifiers) {
final ContainerOperator operator = find(locator, ContainerOperator.class);
if (operator == null)
throw new JemmyDSLException("Could not find component for typing key " + locator);
int key = convertKey(keyString);
// TODO: find a better way to guarantee focus on the target typing component
// The solution proposed here tries to guarantee that the textField has the focus
// to make the test as closes as the human interactions as possible.
operator.requestFocus();
operator.pushKey(key, convertModifiers(modifiers));
}
private static int convertModifiers(String modifiers) {
if (isBlank(modifiers))
return 0;
String[] mods = modifiers.split("[ |\\+|,]+");
int flags = 0;
for (String mod : mods) {
if ("Shift".equalsIgnoreCase(mod)) {
flags |= InputEvent.SHIFT_MASK;
} else if ("Control".equalsIgnoreCase(mod) || "Ctrl".equalsIgnoreCase(mod)) {
flags |= InputEvent.CTRL_MASK;
} else if ("Alt".equalsIgnoreCase(mod)) {
flags |= InputEvent.ALT_MASK;
} else {
throw new JemmyDSLException("Unknown modifier " + mod);
}
}
return flags;
}
@SuppressWarnings({"unchecked"})
public static <X extends ContainerOperator> X find(String locator, Class<X> clazz) {
Map<String, String> locatorMap = Utils.parseLocator(locator);
X component;
if (locatorMap.containsKey("name")) {
component = newInstance(clazz,
currentWindow().getComponent(),
new NameComponentChooser(locator));
} else if (locatorMap.containsKey("label")) {
JLabelOperator jlabel = new JLabelOperator(currentWindow().getComponent(),
locatorMap.get("label"));
if (!(jlabel.getLabelFor() instanceof JTextField)) {
throw new JemmyDSLException("Associated component for " + locator
+ " is not a JTextComponent");
}
component = newInstance(clazz, JTextField.class, (JTextField) jlabel.getLabelFor());
} else if (locatorMap.containsKey("text")) {
if (JTextComponentOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz,
currentWindow().getComponent(),
new JTextComponentOperator.JTextComponentByTextFinder(
locatorMap.get("text")));
} else if (AbstractButtonOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz,
currentWindow().getComponent(),
new AbstractButtonOperator.AbstractButtonByLabelFinder(
locatorMap.get("text")));
} else if (JComponentOperator.class.isAssignableFrom(clazz)) {
// Hack, we assume that what was really meant was AbstractButtonOperator
component = newInstance(clazz,
currentWindow().getComponent(),
new AbstractButtonOperator.AbstractButtonByLabelFinder(
locatorMap.get("text")));
} else {
throw new JemmyDSLException(
"Unsupported component type for location by text locator: " + locator);
}
} else if (locatorMap.containsKey("id")) {
ComponentOperator operator = componentMap.getComponent(locatorMap.get("id"));
if (operator == null)
return null;
if (!clazz.isAssignableFrom(operator.getClass())) {
throw new JemmyDSLException("Cannot convert component with " + locator + " from "
+ operator.getClass().getName() + " to " + clazz.getName());
}
component = (X) operator;
} else if (locatorMap.containsKey("title")) {
if (JInternalFrameOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz,
currentWindow().getComponent(),
new JInternalFrameOperator.JInternalFrameByTitleFinder(
locatorMap.get("title")));
} else {
throw new JemmyDSLException(
"Unsupported component type for location by text locator: " + locator);
}
} else {
throw new JemmyDSLException("Unsupported locator: " + locator);
}
return component;
}
private static <X extends ContainerOperator> X newInstance(Class<X> clazz,
ContainerOperator parent,
ComponentChooser chooser) {
try {
Constructor<X> c = clazz.getConstructor(ContainerOperator.class, ComponentChooser.class);
return c.newInstance(parent, chooser);
} catch (Exception e) {
// Check to see if the nested exception was caused by a regular Jemmy exception
if (e.getCause() != null && e.getCause() instanceof JemmyException)
throw (JemmyException) e.getCause();
throw new JemmyDSLException(e);
}
}
private static <X extends ContainerOperator, Y> X newInstance(Class<X> clazz,
Class<Y> componentClass,
JComponent component) {
try {
Constructor<X> c = findConstructor(clazz, componentClass);
return c.newInstance(component);
} catch (Exception e) {
// Check to see if the nested exception was caused by a regular Jemmy exception
if (e.getCause() != null && e.getCause() instanceof JemmyException)
throw (JemmyException) e.getCause();
throw new JemmyDSLException(e);
}
}
@SuppressWarnings({"unchecked"})
private static <X, Y> Constructor<X> findConstructor(Class<X> clazz, Class<Y> componentClass) {
Constructor<X>[] cs = (Constructor<X>[]) clazz.getConstructors();
for (Constructor<X> c : cs) {
final Class<?>[] types = c.getParameterTypes();
if (types.length == 1 && types[0].isAssignableFrom(componentClass))
return c;
}
throw new JemmyDSLException("Could not find suitable constructor in class "
+ clazz.getCanonicalName());
}
public static JComponent getSwingComponentById(String id) {
ComponentOperator op = componentMap.getComponent(id);
return (JComponent) op.getSource();
}
public static Dialog getDialogById(String id) {
ComponentOperator op = componentMap.getComponent(id);
if (!(op instanceof JDialogOperator))
return null;
return new Dialog((JDialog) op.getSource());
}
public static Label label(String locator) {
return new Label(find(locator, JLabelOperator.class));
}
public static TabbedPane tabbedPane(String locator) {
return new TabbedPane(locator);
}
public static Slider slider(String locator) {
return new Slider(locator);
}
public static InternalFrame internalFrame(String locator) {
return new InternalFrame(locator);
}
/**
* Gets the menu bar for the last activated frame.
*
* @return The menu bar
*/
public static MenuBar menuBar() {
return new MenuBar();
}
public static void waitEnabled(String locator, boolean enabled) {
JComponentOperator op = find(locator, JComponentOperator.class);
try {
if (enabled) {
op.waitComponentEnabled();
} else {
waitComponentDisabled(op);
}
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public static void waitHasFocus(String locator) {
JComponentOperator op = find(locator, JComponentOperator.class);
op.waitHasFocus();
}
public static void waitChecked(String locator, boolean checked) {
JToggleButtonOperator op = find(locator, JToggleButtonOperator.class);
try {
waitComponentChecked(op, checked);
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
private static void waitComponentDisabled(final ComponentOperator op)
throws InterruptedException {
Waiter waiter = new Waiter(new Waitable() {
public Object actionProduced(Object obj) {
if (((java.awt.Component) obj).isEnabled()) {
return null;
} else {
return obj;
}
}
public String getDescription() {
return ("Component description: " + op.getSource().getClass().toString());
}
});
waiter.setOutput(op.getOutput());
waiter.setTimeoutsToCloneOf(op.getTimeouts(),
"ComponentOperator.WaitComponentEnabledTimeout");
waiter.waitAction(op.getSource());
}
private static void waitComponentChecked(final JToggleButtonOperator op, final boolean checked)
throws InterruptedException {
Waiter waiter = new Waiter(new Waitable() {
public Object actionProduced(Object obj) {
if (((JToggleButton) obj).isSelected() != checked) {
return null;
} else {
return obj;
}
}
public String getDescription() {
return ("Component description: " + op.getSource().getClass().toString());
}
});
waiter.setOutput(op.getOutput());
waiter.setTimeoutsToCloneOf(op.getTimeouts(),
"ComponentOperator.WaitComponentEnabledTimeout");
waiter.waitAction(op.getSource());
}
private static int convertKey(String keyString) {
if ("Tab".equalsIgnoreCase(keyString))
return KeyEvent.VK_TAB;
else if ("Enter".equalsIgnoreCase(keyString))
return KeyEvent.VK_ENTER;
else if ("End".equalsIgnoreCase(keyString))
return KeyEvent.VK_END;
else if ("Backspace".equalsIgnoreCase(keyString))
return KeyEvent.VK_BACK_SPACE;
else if ("Delete".equalsIgnoreCase(keyString))
return KeyEvent.VK_DELETE;
else if ("Up".equalsIgnoreCase(keyString))
return KeyEvent.VK_UP;
else if ("Down".equalsIgnoreCase(keyString))
return KeyEvent.VK_DOWN;
else if ("Right".equalsIgnoreCase(keyString))
return KeyEvent.VK_RIGHT;
else if ("Left".equalsIgnoreCase(keyString))
return KeyEvent.VK_LEFT;
else if ("Home".equalsIgnoreCase(keyString))
return KeyEvent.VK_HOME;
else if ("End".equalsIgnoreCase(keyString))
return KeyEvent.VK_END;
else if ("F4".equalsIgnoreCase(keyString))
return KeyEvent.VK_F4;
else if ("F5".equalsIgnoreCase(keyString))
return KeyEvent.VK_F5;
else if ("Space".equalsIgnoreCase(keyString))
return KeyEvent.VK_SPACE;
else if ("F7".equalsIgnoreCase(keyString))
return KeyEvent.VK_F7;
else
throw new UnsupportedFeatureException("Type special for " + keyString
+ " not supported");
}
public static abstract class Component {
public abstract ComponentOperator getComponent();
public void assertEnabled() {
try {
getComponent().waitComponentEnabled();
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public void assertDisabled() {
try {
waitComponentDisabled(getComponent());
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public void store(String id) {
componentMap.putComponent(id, getComponent());
}
}
public static abstract class Container extends Component {
@Override
public abstract ContainerOperator getComponent();
}
public static abstract class Window extends Container {
public abstract boolean isActive();
public abstract boolean isShowing();
}
public static class Frame extends Window {
private final JFrameOperator component;
public Frame(String title) {
component = new JFrameOperator(title);
}
public Frame(JFrame frame) {
component = new JFrameOperator(frame);
}
public Frame close() {
component.requestClose();
return this;
}
public Frame activate() {
component.activate();
currentWindow = this;
return this;
}
@Override
public boolean isActive() {
return component.isActive();
}
@Override
public boolean isShowing() {
return component.isShowing();
}
@Override
public JFrameOperator getComponent() {
return component;
}
}
public static class Dialog extends Window {
private final JDialogOperator component;
public Dialog(String title) {
component = new JDialogOperator(title);
}
public Dialog(JDialog dialog) {
component = new JDialogOperator(dialog);
}
public Dialog close() {
component.requestClose();
return this;
}
@Override
public JDialogOperator getComponent() {
return component;
}
public Dialog activate() {
component.activate();
currentWindow = this;
return this;
}
@Override
public boolean isShowing() {
return component.isShowing();
}
@Override
public boolean isActive() {
return component.isActive();
}
public void assertText(String text) {
final String t = text;
if (text == null)
text = "";
java.awt.Component c = component.findSubComponent(new ComponentChooser() {
@Override
public String getDescription() {
return null;
}
@Override
public boolean checkComponent(java.awt.Component comp) {
if (!comp.isVisible())
return false;
if (comp instanceof JTextField) {
String compText = ((JTextField) comp).getText();
if (compText == null)
compText = "";
return t.equals(compText);
} else if (comp instanceof JLabel) {
String compText = ((JLabel) comp).getText();
if (compText == null)
compText = "";
return t.equals(compText);
}
return false;
}
});
if (c == null) {
throw new AssertionFailedException(
"assert_dialog: could not find component with text " + text);
}
}
}
public static class ScrollPane extends Component {
private final JScrollPaneOperator component;
public ScrollPane(String locator) {
component = find(locator, JScrollPaneOperator.class);
}
public ScrollPane(JScrollPaneOperator component) {
this.component = component;
}
@Override
public ComponentOperator getComponent() {
return component;
}
}
public static class TextField extends Component {
private final JTextComponentOperator component;
public TextField(String locator) {
component = find(locator, JTextComponentOperator.class);
component.setComparator(new Operator.DefaultStringComparator(true, true));
}
public TextField(JTextFieldOperator component) {
this.component = component;
component.setComparator(new Operator.DefaultStringComparator(true, true));
}
public TextField type(String text) {
if (text.contains("\t") || text.contains("\r") || text.contains("\n")) {
throw new IllegalParametersException("Text cannot contain \\t \\r \\n");
}
dispatchingMode();
try {
// TODO: find a better way to guarantee focus on the target typing component
// The solution proposed here tries to guarantee that the textField has the focus
// to make the test as closes as the human interactions as possible.
component.requestFocus();
component.setVerification(false);
component.typeText(text);
return this;
} finally {
robotMode();
}
}
public TextField type(char key) {
component.typeKey(key);
if (!isRobotMode()) {
// This is a hack because type key in queue mode does not wait for events to be
// fired
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
return this;
}
public TextField type(int key) {
component.pushKey(key);
return this;
}
public String text() {
return component.getText();
}
public void assertText(String text) {
component.waitText(text);
}
@Override
public JTextComponentOperator getComponent() {
return component;
}
public TextField assertEmpty() {
component.waitText("");
return this;
}
public TextField assertNotEmpty() {
String text = component.getText();
if (text == null || text.length() == 0) {
throw new AssertionFailedException("TextField [" + component.getName() + "] is empty.");
}
return this;
}
public TextField clickCharPosition(int pos, String modifiers, int count) {
FontMetrics fm = component.getFontMetrics(component.getFont());
component.clickMouse(fm.stringWidth(component.getText().substring(0, pos))
+ component.getInsets().left,
component.getCenterYForClick(),
count,
KeyEvent.BUTTON1_MASK,
convertModifiers(modifiers));
return this;
}
}
public static class TextArea extends Component {
private final JTextAreaOperator component;
public TextArea(String locator) {
component = find(locator, JTextAreaOperator.class);
}
public TextArea(JTextAreaOperator component) {
this.component = component;
}
public TextArea type(String text) {
if (text.contains("\t") || text.contains("\r") || text.contains("\n")) {
throw new IllegalParametersException("Text cannot contain \\t \\r \\n");
}
component.setVerification(false);
component.typeText(text);
return this;
}
public String text() {
return component.getText();
}
@Override
public JTextAreaOperator getComponent() {
return component;
}
public TextArea assertEmpty() {
component.waitText("");
return this;
}
public TextArea assertNotEmpty() {
String text = component.getText();
if (text == null || text.length() == 0) {
throw new AssertionFailedException("TextArea [" + component.getName() + "] is empty.");
}
return this;
}
}
public static class ComboBox extends Component {
private final JComboBoxOperator component;
public ComboBox(String locator) {
component = find(locator, JComboBoxOperator.class);
}
public ComboBox(JComboBoxOperator comp) {
this.component = comp;
}
public void select(String text) {
Map<String, String> selectedItem = Utils.parseLocator(text);
if (selectedItem.containsKey("name")) {
clickDropDown();
component.selectItem(selectedItem.get("name"));
} else if (selectedItem.containsKey("index")) {
select(Integer.parseInt(selectedItem.get("index")));
} else {
throw new IllegalParametersException("Illegal parameters " + text
+ " for select command");
}
}
public void select(int index) {
clickDropDown();
component.setSelectedIndex(index);
component.waitItemSelected(index);
component.hidePopup();
}
private void clickDropDown() {
component.pushComboButton();
component.waitList();
}
@Override
public JComboBoxOperator getComponent() {
return component;
}
public void assertSelected(String text) {
component.waitItemSelected(text);
}
}
public static class GenericButton extends Component {
protected AbstractButtonOperator component;
protected GenericButton() {}
public GenericButton(String locator) {
component = find(locator, AbstractButtonOperator.class);
}
public GenericButton(AbstractButtonOperator component) {
this.component = component;
}
public void click() {
component.push();
}
@Override
public AbstractButtonOperator getComponent() {
return component;
}
}
public static class Button extends GenericButton {
public Button(String locator) {
component = find(locator, JButtonOperator.class);
}
public Button(JButtonOperator component) {
super(component);
}
@Override
public JButtonOperator getComponent() {
return (JButtonOperator) component;
}
}
public static class CheckBox extends GenericButton {
public CheckBox(String locator) {
component = find(locator, JCheckBoxOperator.class);
}
public CheckBox(JCheckBoxOperator component) {
super(component);
}
@Override
public JCheckBoxOperator getComponent() {
return (JCheckBoxOperator) component;
}
}
public static class RadioButton extends GenericButton {
public RadioButton(String locator) {
component = find(locator, JRadioButtonOperator.class);
}
public RadioButton(JRadioButtonOperator component) {
super(component);
}
@Override
public JRadioButtonOperator getComponent() {
return (JRadioButtonOperator) component;
}
}
public static class Table extends Component {
private final JTableOperator component;
public Table(String locator) {
component = find(locator, JTableOperator.class);
}
public Table(JTableOperator component) {
this.component = component;
}
public Row row(int index) {
return new Row(component, index);
}
public TableHeader header() {
return new TableHeader(component.getTableHeader());
}
public Table selectRows(int first, int last) {
component.setRowSelectionInterval(first, last);
return this;
}
@Override
public JTableOperator getComponent() {
return component;
}
}
public static class TableOperator extends JTableOperator {
public static class XJTableByCellFinder extends JTableByCellFinder {
private final String label;
private final int row;
private final int column;
private final StringComparator comparator;
@Override
public boolean checkComponent(java.awt.Component comp) {
if (!"".equals(label)) {
return super.checkComponent(comp);
} else if (comp instanceof JTable) {
if (((JTable) comp).getRowCount() > row
&& ((JTable) comp).getColumnCount() > column) {
int r = row;
if (r == -1) {
int[] rows = ((JTable) comp).getSelectedRows();
if (rows.length != 0) {
r = rows[0];
} else {
return (false);
}
}
int c = column;
if (c == -1) {
int[] columns = ((JTable) comp).getSelectedColumns();
if (columns.length != 0) {
c = columns[0];
} else {
return (false);
}
}
Object value = ((JTable) comp).getValueAt(r, c);
if (value == null) {
value = "";
}
return (comparator.equals(value.toString(), label));
}
}
return (false);
}
public XJTableByCellFinder(String lb, int r, int c, StringComparator comparator) {
super(lb, r, c, comparator);
this.label = lb;
this.row = r;
this.column = c;
this.comparator = comparator;
}
public XJTableByCellFinder(String lb, int r, int c) {
this(lb, r, c, Operator.getDefaultStringComparator());
}
}
public TableOperator(JTable b) {
super(b);
}
/**
* Overridden to prevent trying to scroll to the row header (which can't be done as the row
* header is located totally to the left of the scroll bar).
*/
@Override
public void scrollToCell(int row, int column) {
// try to find JScrollPane under.
JScrollPane scroll = (JScrollPane) getContainer(new JScrollPaneOperator.JScrollPaneFinder(
ComponentSearcher.getTrueChooser("JScrollPane")));
if (scroll == null) {
return;
}
// if source is the row header table, do nothing
if (getSource() == scroll.getRowHeader().getView()) {
return;
}
super.scrollToCell(row, column);
}
/**
* Overridden method to allow searching for empty strings
*/
@Override
public void waitCell(String cellText, int row, int column) {
waitState(new XJTableByCellFinder(cellText, row, column, getComparator()));
}
}
public static class Row {
private final JTableOperator component;
private final int index;
public Row(JTableOperator component, int index) {
this.component = component;
this.index = index;
}
public Row assertColumn(int col, String value) {
component.waitCell(value, index, col);
return this;
}
/**
* Asserts that a table's cell is not empty, nor null.
*
* @param col Column index of the table, starting at 0.
* @return Cell's row that is asserted to not be empty.
*/
public Row assertNotEmptyColumn(int col) {
String value = (String) component.getValueAt(index, col);
if (value == null || value.length() == 0) {
throw new AssertionFailedException("Table cell (" + index + ", " + col + ") is empty.");
}
return this;
}
public Row select() {
component.setRowSelectionInterval(index, index);
return this;
}
public Row assertSelected(final boolean selected) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JTable) comp).isRowSelected(index) == selected;
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
public Row selectCell(int col) {
component.selectCell(index, col);
return this;
}
public Row clickCell(int col, int clicks) {
component.clickOnCell(index, col, clicks);
return this;
}
}
public static class TableHeader {
private final JTableHeaderOperator component;
public TableHeader(JTableHeader swingComponent) {
component = new JTableHeaderOperator(swingComponent);
}
public TableHeader assertTitle(final int col, final String title) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JTableHeader) comp).getColumnModel()
.getColumn(col)
.getHeaderValue()
.equals(title);
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
/**
* Clicks in a column's table header. <p/>
*
* @param columnIndex Column' index. It's zero based.
* @param count Number of clicks
*/
public void click(int columnIndex, int count) {
TableColumnModel columnModel =
component.getTable().getColumnModel();
int columnCenterX = 0;
int counter = 0;
int convertedColIndex = 0;
while (counter < columnIndex) {
int columnWidth = columnModel.getColumn(convertedColIndex)
.getWidth();
if (columnWidth > 0) {
columnCenterX += columnWidth;
counter++;
}
convertedColIndex++;
}
// get the X value for the center of the column
columnCenterX += (columnModel.getColumn(convertedColIndex)
.getWidth() / 2);
component.clickMouse(columnCenterX,
component.getCenterYForClick(),
count,
InputEvent.BUTTON1_MASK,
convertModifiers(null));
}
}
public static class Label {
private final JLabelOperator component;
public Label(JLabelOperator component) {
this.component = component;
}
public Label text(String text) {
component.waitText(text);
return this;
}
}
public static class TabbedPane extends Component {
private final JTabbedPaneOperator component;
public TabbedPane(String locator) {
component = find(locator, JTabbedPaneOperator.class);
}
public TabbedPane select(String title) {
component.selectPage(title);
return this;
}
public TabbedPane select(int index) {
component.selectPage(index);
return this;
}
@Override
public JTabbedPaneOperator getComponent() {
return component;
}
}
public static class Slider extends Component {
private final JSliderOperator component;
public Slider(String locator) {
component = find(locator, JSliderOperator.class);
}
public Slider value(int i) {
component.setValue(i);
return this;
}
public Slider assertValue(final int i) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JSlider) comp).getValue() == i;
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
@Override
public ComponentOperator getComponent() {
return component;
}
}
public static class MenuBar extends Container {
private final JMenuBarOperator component;
public MenuBar() {
component = new JMenuBarOperator(currentWindow().getComponent());
}
public MenuBar(JMenuBarOperator component) {
this.component = component;
}
public MenuBar clickMenu(int... indexes) {
if (indexes.length == 0)
return this;
String[] texts = new String[indexes.length];
JMenu menu = component.getMenu(indexes[0]);
texts[0] = menu.getText();
for (int i = 1; i < indexes.length; i++) {
int index = indexes[i];
assert menu != null;
if (i == indexes.length - 1) {
JMenuItem item = (JMenuItem) menu.getMenuComponent(index);
texts[i] = item.getText();
menu = null;
} else {
menu = (JMenu) menu.getMenuComponent(index);
texts[i] = menu.getText();
}
}
clickMenu(texts);
return this;
}
public MenuBar clickMenu(String... texts) {
if (texts.length == 0)
return this;
component.showMenuItem(texts[0]);
for (int i = 1; i < texts.length; i++) {
String text = texts[i];
JMenuOperator jmenu = new JMenuOperator(currentWindow().getComponent(), texts[i - 1]);
jmenu.setComparator(comparator);
jmenu.showMenuItem(new String[]{text});
}
String text = texts[texts.length - 1];
ComponentChooser chooser = new JMenuItemOperator.JMenuItemByLabelFinder(text, comparator);
new JMenuItemOperator(currentWindow().getComponent(), chooser).clickMouse();
return this;
}
@Override
public JMenuBarOperator getComponent() {
return component;
}
}
public static class Menu extends Container {
private JMenuOperator component;
public Menu() {}
@Override
public JMenuOperator getComponent() {
return component;
}
}
public static class InternalFrame extends Container {
private final JInternalFrameOperator component;
public InternalFrame(String locator) {
component = find(locator, JInternalFrameOperator.class);
}
public InternalFrame(JInternalFrame frame) {
component = new JInternalFrameOperator(frame);
}
public InternalFrame close() {
((JInternalFrame) component.getSource()).doDefaultCloseAction();
return this;
}
public InternalFrame hide() {
component.setVisible(false);
return this;
}
public InternalFrame show() {
component.setVisible(true);
return this;
}
public InternalFrame activate() {
component.activate();
return this;
}
public InternalFrame assertVisible(Boolean visible) {
component.waitComponentVisible(visible);
return this;
}
@Override
public JInternalFrameOperator getComponent() {
return component;
}
}
public static class ScrollBar extends Component {
private final JScrollBarOperator component;
public ScrollBar(String locator) {
component = find(locator, JScrollBarOperator.class);
}
public ScrollBar(JScrollBarOperator component) {
this.component = component;
}
@Override
public JScrollBarOperator getComponent() {
return component;
}
}
}
| core/src/main/java/com/github/srec/jemmy/JemmyDSL.java | package com.github.srec.jemmy;
import com.github.srec.UnsupportedFeatureException;
import com.github.srec.command.exception.AssertionFailedException;
import com.github.srec.util.AWTTreeScanner;
import com.github.srec.util.ScannerMatcher;
import com.github.srec.util.Utils;
import org.apache.log4j.Logger;
import org.netbeans.jemmy.ComponentChooser;
import org.netbeans.jemmy.ComponentSearcher;
import org.netbeans.jemmy.JemmyException;
import org.netbeans.jemmy.JemmyProperties;
import org.netbeans.jemmy.TestOut;
import org.netbeans.jemmy.Timeouts;
import org.netbeans.jemmy.Waitable;
import org.netbeans.jemmy.Waiter;
import org.netbeans.jemmy.operators.AbstractButtonOperator;
import org.netbeans.jemmy.operators.ComponentOperator;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JCheckBoxOperator;
import org.netbeans.jemmy.operators.JComboBoxOperator;
import org.netbeans.jemmy.operators.JComponentOperator;
import org.netbeans.jemmy.operators.JDialogOperator;
import org.netbeans.jemmy.operators.JFrameOperator;
import org.netbeans.jemmy.operators.JInternalFrameOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.JListOperator;
import org.netbeans.jemmy.operators.JMenuBarOperator;
import org.netbeans.jemmy.operators.JMenuItemOperator;
import org.netbeans.jemmy.operators.JMenuOperator;
import org.netbeans.jemmy.operators.JRadioButtonOperator;
import org.netbeans.jemmy.operators.JScrollBarOperator;
import org.netbeans.jemmy.operators.JScrollPaneOperator;
import org.netbeans.jemmy.operators.JSliderOperator;
import org.netbeans.jemmy.operators.JTabbedPaneOperator;
import org.netbeans.jemmy.operators.JTableHeaderOperator;
import org.netbeans.jemmy.operators.JTableOperator;
import org.netbeans.jemmy.operators.JTextAreaOperator;
import org.netbeans.jemmy.operators.JTextComponentOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import org.netbeans.jemmy.operators.JToggleButtonOperator;
import org.netbeans.jemmy.operators.Operator;
import org.netbeans.jemmy.util.NameComponentChooser;
import java.awt.FontMetrics;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import javax.swing.text.JTextComponent;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* A DSL wrapper for Jemmy operators.
*
* @author Victor Tatai
*/
public class JemmyDSL {
private static final Logger logger = Logger.getLogger(JemmyDSL.class);
public enum ComponentType {
text_field(JTextFieldOperator.class, JTextField.class),
combo_box(JComboBoxOperator.class, JComboBox.class),
button(JButtonOperator.class, JButton.class),
radio_button(JRadioButtonOperator.class, JRadioButton.class),
check_box(JCheckBoxOperator.class, JCheckBox.class),
table(TableOperator.class, JTable.class),
menu_bar(JMenuBarOperator.class, JMenuBar.class),
dialog(JDialogOperator.class, JDialog.class),
text_area(JTextAreaOperator.class, JTextArea.class),
scroll_pane(JScrollPaneOperator.class, JScrollPane.class);
private final Class<? extends ComponentOperator> operatorClass;
private final Class<? extends java.awt.Component> awtClass;
ComponentType(Class<? extends ComponentOperator> operatorClass,
Class<? extends java.awt.Component> awtClass) {
this.operatorClass = operatorClass;
this.awtClass = awtClass;
}
public Class<? extends ComponentOperator> getOperatorClass() {
return operatorClass;
}
public Class<? extends java.awt.Component> getAwtClass() {
return awtClass;
}
}
private static Window currentWindow;
private static Properties props = new Properties();
static {
props.put("ComponentOperator.WaitComponentEnabledTimeout", "15000");
props.put("ComponentOperator.WaitComponentTimeout", "15000");
props.put("ComponentOperator.WaitStateTimeout", "10000");
props.put("DialogWaiter.WaitDialogTimeout", "10000");
props.put("FrameWaiter.WaitFrameTimeout", "10000");
props.put("JComboBoxOperator.WaitListTimeout", "30000");
props.put("JScrollBarOperator.WholeScrollTimeout", "10000");
props.put("JSliderOperator.WholeScrollTimeout", "10000");
props.put("JSplitPaneOperator.WholeScrollTimeout", "10000");
props.put("ScrollbarOperator.WholeScrollTimeout", "10000");
props.put("Waiter.WaitingTime", "10000");
props.put("WindowWaiter.WaitWindowTimeout", "10000");
}
private static List<java.awt.Container> ignored = new ArrayList<java.awt.Container>();
private static ComponentMap componentMap = new DefaultComponentMap();
public static void init(java.awt.Container... ignored) {
Timeouts timeouts = JemmyProperties.getCurrentTimeouts();
for (Map.Entry<Object, Object> entry : props.entrySet()) {
timeouts.setTimeout((String) entry.getKey(), Long.parseLong((String) entry.getValue()));
}
currentWindow = null;
JemmyDSL.ignored = Arrays.asList(ignored);
JemmyProperties.setCurrentOutput(new TestOut(System.in, (PrintStream) null, null));
robotMode();
}
public static void robotMode() {
JemmyProperties.setCurrentDispatchingModel(JemmyProperties.ROBOT_MODEL_MASK);
}
public static void dispatchingMode() {
JemmyProperties.setCurrentDispatchingModel(JemmyProperties.QUEUE_MODEL_MASK);
}
public static boolean isRobotMode() {
return JemmyProperties.getCurrentDispatchingModel() == JemmyProperties.ROBOT_MODEL_MASK;
}
public static ComponentMap getComponentMap() {
return componentMap;
}
public static void setComponentMap(ComponentMap componentMap) {
JemmyDSL.componentMap = componentMap;
}
public static Frame frame(String title) {
Frame frame = new Frame(title);
currentWindow = frame;
return frame;
}
public static Frame frame() {
return (Frame) currentWindow;
}
public static Window currentWindow() {
if (currentWindow == null) {
logger.info("No current container found, trying to find one.");
currentWindow = findActiveWindow();
} else if (!currentWindow.isActive()) {
currentWindow = findActiveWindow();
}
if (currentWindow == null)
throw new JemmyDSLException("Cannot find a currently active window");
logger.info("Using as current container: " + currentWindow.getComponent());
return currentWindow;
}
private static Window findActiveWindow() {
java.awt.Window[] windows = JFrame.getWindows();
for (java.awt.Window w : windows) {
if (ignored.contains(w))
continue;
if (!w.isActive())
continue;
if (w instanceof JFrame) {
return new Frame((JFrame) w);
} else if (w instanceof JDialog) {
return new Dialog((JDialog) w);
} else {
logger.info("Found a window which is neither a JFrame nor JDialog");
}
}
return null;
}
public static Container container(JFrame frame) {
currentWindow = new Frame(frame);
return currentWindow;
}
public static Dialog dialog(String title) {
final Dialog dialog = new Dialog(title);
currentWindow = dialog;
return dialog;
}
public static TextField textField(String locator) {
return new TextField(locator);
}
public static TextArea textArea(String locator) {
return new TextArea(locator);
}
public static Button button(String locator) {
return new Button(locator);
}
public static ComboBox comboBox(String locator) {
return new ComboBox(locator);
}
public static CheckBox checkBox(String locator) {
return new CheckBox(locator);
}
public static Table table(String locator) {
return new Table(locator);
}
/**
* Finds a component and stores it under the given id. The component can later be used on other
* commands using the locator "id=ID_ASSIGNED". This method searches both VISIBLE and INVISIBLE
* components.
*
* @param locator The locator (accepted are name (default), title, text, label)
* @param id The id
* @param componentType The component type
* @return The component found
*/
@SuppressWarnings({"unchecked"})
public static Component find(String locator, String id, String componentType) {
java.awt.Component component = findComponent(locator, currentWindow().getComponent()
.getSource());
if (component == null) {
componentMap.putComponent(id, null);
return null;
}
JComponentOperator operator = convertFind(component);
componentMap.putComponent(id, operator);
final Component finalComponent = convertFind(operator);
if (finalComponent instanceof Window) {
currentWindow = (Window) finalComponent;
}
return finalComponent;
}
@SuppressWarnings({"unchecked"})
private static Class<? extends java.awt.Component> translateFindType(String findType) {
for (ComponentType componentType : ComponentType.values()) {
if (findType.equals(componentType.name()))
return componentType.getAwtClass();
}
try {
return (Class<? extends java.awt.Component>) Class.forName(findType);
} catch (ClassNotFoundException e) {
throw new JemmyDSLException("Unsupported find type " + findType);
}
}
public static java.awt.Component findComponent(String locator, java.awt.Component component) {
assert locator != null;
String[] strs = parseLocator(locator);
if (strs.length != 2)
throw new JemmyDSLException("Invalid locator " + locator);
if (strs[0].equals("id")) {
return componentMap.getComponent(strs[1]).getSource();
} else {
return AWTTreeScanner.scan(component, compileMatcher(strs));
}
}
private static String[] parseLocator(String locator) {
int i = locator.indexOf("=");
if (i == -1) {
return new String[]{"name", locator.substring(i + 1).trim()};
}
return new String[]{locator.substring(0, i).trim(), locator.substring(i + 1).trim()};
}
private static ScannerMatcher compileMatcher(String[] strs) {
if (strs[0].equals("name"))
return new AWTTreeScanner.NameScannerMatcher(strs[1]);
if (strs[0].equals("title"))
return new AWTTreeScanner.TitleScannerMatcher(strs[1]);
if (strs[0].equals("text"))
return new AWTTreeScanner.TextScannerMatcher(strs[1]);
throw new JemmyDSLException("Invalid locator " + strs[0] + "=" + strs[1]);
}
/**
* Returns a list of all visible components which are instances of the given class. If one needs
* a find that returns an invisible component should add a parameter here. But the default
* behavior must be returning only visible components as it is the most common operation and
* required for compatibility with scripts converted from jfcunit. see #15790.
*
* @param container
* @param componentClass
* @return
*/
private static List<java.awt.Component> findComponents(java.awt.Container container,
Class<? extends java.awt.Component> componentClass) {
List<java.awt.Component> list = new ArrayList<java.awt.Component>();
for (java.awt.Component component : container.getComponents()) {
if (component.isVisible() && componentClass.isAssignableFrom(component.getClass())) {
list.add(component);
}
if (component instanceof java.awt.Container) {
List<java.awt.Component> children = findComponents((java.awt.Container) component,
componentClass);
list.addAll(children);
}
}
return list;
}
private static JComponentOperator convertFind(java.awt.Component comp) {
if (comp instanceof JComboBox)
return new JComboBoxOperator((JComboBox) comp);
if (comp instanceof JTextArea)
return new JTextAreaOperator((JTextArea) comp);
if (comp instanceof JTextComponent)
return new JTextFieldOperator((JTextField) comp);
if (comp instanceof JScrollPane)
return new JScrollPaneOperator((JScrollPane) comp);
if (comp instanceof JCheckBox)
return new JCheckBoxOperator((JCheckBox) comp);
if (comp instanceof JRadioButton)
return new JRadioButtonOperator((JRadioButton) comp);
if (comp instanceof JButton)
return new JButtonOperator((JButton) comp);
if (comp instanceof AbstractButton)
return new AbstractButtonOperator((AbstractButton) comp);
if (comp instanceof JTable) {
return new TableOperator((JTable) comp);
}
if (comp instanceof JMenuBar)
return new JMenuBarOperator((JMenuBar) comp);
if (comp instanceof JScrollBar)
return new JScrollBarOperator((JScrollBar) comp);
if (comp instanceof JInternalFrame)
return new JInternalFrameOperator((JInternalFrame) comp);
throw new JemmyDSLException("Unsupported find type " + comp);
}
private static Component convertFind(JComponentOperator comp) {
if (comp instanceof JComboBoxOperator)
return new ComboBox((JComboBoxOperator) comp);
if (comp instanceof JTextAreaOperator)
return new TextArea((JTextAreaOperator) comp);
if (comp instanceof JTextComponentOperator)
return new TextField((JTextFieldOperator) comp);
if (comp instanceof JScrollPaneOperator)
return new ScrollPane((JScrollPaneOperator) comp);
if (comp instanceof JCheckBoxOperator)
return new CheckBox((JCheckBoxOperator) comp);
if (comp instanceof JRadioButtonOperator)
return new RadioButton((JRadioButtonOperator) comp);
if (comp instanceof JButtonOperator)
return new Button((JButtonOperator) comp);
if (comp instanceof AbstractButtonOperator)
return new GenericButton((AbstractButtonOperator) comp);
if (comp instanceof JTableOperator)
return new Table((JTableOperator) comp);
if (comp instanceof JMenuBarOperator)
return new MenuBar((JMenuBarOperator) comp);
if (comp instanceof JScrollBarOperator)
return new ScrollBar((JScrollBarOperator) comp);
// not really sure this is the right thing to do, but constructor here expects a component
// and not an operator:
if (comp instanceof JInternalFrameOperator)
return new InternalFrame((JInternalFrame) ((JInternalFrameOperator) comp).getSource());
throw new JemmyDSLException("Unsupported find type " + comp);
}
/**
* Finds the first component with the given component type and stores it under the given id. The
* component can later be used on other commands using the locator "id=ID_ASSIGNED". This method
* searches both VISIBLE and INVISIBLE components.
*
* @param id The id
* @param componentType The component type
* @return The component found
*/
@SuppressWarnings({"unchecked"})
public static Component findByComponentType(String id,
String containerId,
String componentType,
int index) {
java.awt.Container container;
if (isBlank(containerId)) {
container = (java.awt.Container) currentWindow().getComponent().getSource();
} else {
ComponentOperator op = componentMap.getComponent(containerId);
if (op != null && op.getSource() instanceof java.awt.Container) {
container = (java.awt.Container) op.getSource();
} else {
container = (java.awt.Container) currentWindow().getComponent().getSource();
}
}
List<java.awt.Component> list = findComponents(container, translateFindType(componentType));
if (logger.isDebugEnabled()) {
logger.debug("findComponents returned list :");
for (java.awt.Component c : list) {
logger.debug(" " + c.getName());
}
logger.debug(" index = " + index);
}
if (index < 0 || index >= list.size()) {
return null;
}
java.awt.Component component = list.get(index);
if (component == null) {
componentMap.putComponent(id, null);
logger.debug("findByComponentType returned null");
return null;
}
JComponentOperator operator = convertFind(component);
componentMap.putComponent(id, operator);
if (logger.isDebugEnabled()) {
logger.debug("findByComponentType returned " + component);
}
return convertFind(operator);
}
public static void click(String locator, int count, String modifiers) {
final JComponentOperator operator = find(locator, JComponentOperator.class);
if (operator == null)
throw new JemmyDSLException("Could not find component for clicking " + locator);
operator.clickMouse(operator.getCenterXForClick(),
operator.getCenterYForClick(),
count,
InputEvent.BUTTON1_MASK,
convertModifiers(modifiers));
}
public static void typeSpecial(String locator, String keyString, String modifiers) {
final ContainerOperator operator = find(locator, ContainerOperator.class);
if (operator == null)
throw new JemmyDSLException("Could not find component for typing key " + locator);
int key = convertKey(keyString);
// TODO: find a better way to guarantee focus on the target typing component
// The solution proposed here tries to guarantee that the textField has the focus
// to make the test as closes as the human interactions as possible.
operator.requestFocus();
operator.pushKey(key, convertModifiers(modifiers));
}
private static int convertModifiers(String modifiers) {
if (isBlank(modifiers))
return 0;
String[] mods = modifiers.split("[ |\\+|,]+");
int flags = 0;
for (String mod : mods) {
if ("Shift".equalsIgnoreCase(mod)) {
flags |= InputEvent.SHIFT_MASK;
} else if ("Control".equalsIgnoreCase(mod) || "Ctrl".equalsIgnoreCase(mod)) {
flags |= InputEvent.CTRL_MASK;
} else if ("Alt".equalsIgnoreCase(mod)) {
flags |= InputEvent.ALT_MASK;
} else {
throw new JemmyDSLException("Unknown modifier " + mod);
}
}
return flags;
}
@SuppressWarnings({"unchecked"})
public static <X extends ContainerOperator> X find(String locator, Class<X> clazz) {
Map<String, String> locatorMap = Utils.parseLocator(locator);
X component;
if (locatorMap.containsKey("name")) {
component = newInstance(clazz,
currentWindow().getComponent(),
new NameComponentChooser(locator));
} else if (locatorMap.containsKey("label")) {
JLabelOperator jlabel = new JLabelOperator(currentWindow().getComponent(),
locatorMap.get("label"));
if (!(jlabel.getLabelFor() instanceof JTextField)) {
throw new JemmyDSLException("Associated component for " + locator
+ " is not a JTextComponent");
}
component = newInstance(clazz, JTextField.class, (JTextField) jlabel.getLabelFor());
} else if (locatorMap.containsKey("text")) {
if (JTextComponentOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz,
currentWindow().getComponent(),
new JTextComponentOperator.JTextComponentByTextFinder(
locatorMap.get("text")));
} else if (AbstractButtonOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz,
currentWindow().getComponent(),
new AbstractButtonOperator.AbstractButtonByLabelFinder(
locatorMap.get("text")));
} else if (JComponentOperator.class.isAssignableFrom(clazz)) {
// Hack, we assume that what was really meant was AbstractButtonOperator
component = newInstance(clazz,
currentWindow().getComponent(),
new AbstractButtonOperator.AbstractButtonByLabelFinder(
locatorMap.get("text")));
} else {
throw new JemmyDSLException(
"Unsupported component type for location by text locator: " + locator);
}
} else if (locatorMap.containsKey("id")) {
ComponentOperator operator = componentMap.getComponent(locatorMap.get("id"));
if (operator == null)
return null;
if (!clazz.isAssignableFrom(operator.getClass())) {
throw new JemmyDSLException("Cannot convert component with " + locator + " from "
+ operator.getClass().getName() + " to " + clazz.getName());
}
component = (X) operator;
} else if (locatorMap.containsKey("title")) {
if (JInternalFrameOperator.class.isAssignableFrom(clazz)) {
component = newInstance(clazz,
currentWindow().getComponent(),
new JInternalFrameOperator.JInternalFrameByTitleFinder(
locatorMap.get("title")));
} else {
throw new JemmyDSLException(
"Unsupported component type for location by text locator: " + locator);
}
} else {
throw new JemmyDSLException("Unsupported locator: " + locator);
}
return component;
}
private static <X extends ContainerOperator> X newInstance(Class<X> clazz,
ContainerOperator parent,
ComponentChooser chooser) {
try {
Constructor<X> c = clazz.getConstructor(ContainerOperator.class, ComponentChooser.class);
return c.newInstance(parent, chooser);
} catch (Exception e) {
// Check to see if the nested exception was caused by a regular Jemmy exception
if (e.getCause() != null && e.getCause() instanceof JemmyException)
throw (JemmyException) e.getCause();
throw new JemmyDSLException(e);
}
}
private static <X extends ContainerOperator, Y> X newInstance(Class<X> clazz,
Class<Y> componentClass,
JComponent component) {
try {
Constructor<X> c = findConstructor(clazz, componentClass);
return c.newInstance(component);
} catch (Exception e) {
// Check to see if the nested exception was caused by a regular Jemmy exception
if (e.getCause() != null && e.getCause() instanceof JemmyException)
throw (JemmyException) e.getCause();
throw new JemmyDSLException(e);
}
}
@SuppressWarnings({"unchecked"})
private static <X, Y> Constructor<X> findConstructor(Class<X> clazz, Class<Y> componentClass) {
Constructor<X>[] cs = (Constructor<X>[]) clazz.getConstructors();
for (Constructor<X> c : cs) {
final Class<?>[] types = c.getParameterTypes();
if (types.length == 1 && types[0].isAssignableFrom(componentClass))
return c;
}
throw new JemmyDSLException("Could not find suitable constructor in class "
+ clazz.getCanonicalName());
}
public static JComponent getSwingComponentById(String id) {
ComponentOperator op = componentMap.getComponent(id);
return (JComponent) op.getSource();
}
public static Dialog getDialogById(String id) {
ComponentOperator op = componentMap.getComponent(id);
if (!(op instanceof JDialogOperator))
return null;
return new Dialog((JDialog) op.getSource());
}
public static Label label(String locator) {
return new Label(find(locator, JLabelOperator.class));
}
public static TabbedPane tabbedPane(String locator) {
return new TabbedPane(locator);
}
public static Slider slider(String locator) {
return new Slider(locator);
}
public static InternalFrame internalFrame(String locator) {
return new InternalFrame(locator);
}
/**
* Gets the menu bar for the last activated frame.
*
* @return The menu bar
*/
public static MenuBar menuBar() {
return new MenuBar();
}
public static void waitEnabled(String locator, boolean enabled) {
JComponentOperator op = find(locator, JComponentOperator.class);
try {
if (enabled) {
op.waitComponentEnabled();
} else {
waitComponentDisabled(op);
}
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public static void waitHasFocus(String locator) {
JComponentOperator op = find(locator, JComponentOperator.class);
op.waitHasFocus();
}
public static void waitChecked(String locator, boolean checked) {
JToggleButtonOperator op = find(locator, JToggleButtonOperator.class);
try {
waitComponentChecked(op, checked);
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
private static void waitComponentDisabled(final ComponentOperator op)
throws InterruptedException {
Waiter waiter = new Waiter(new Waitable() {
public Object actionProduced(Object obj) {
if (((java.awt.Component) obj).isEnabled()) {
return null;
} else {
return obj;
}
}
public String getDescription() {
return ("Component description: " + op.getSource().getClass().toString());
}
});
waiter.setOutput(op.getOutput());
waiter.setTimeoutsToCloneOf(op.getTimeouts(),
"ComponentOperator.WaitComponentEnabledTimeout");
waiter.waitAction(op.getSource());
}
private static void waitComponentChecked(final JToggleButtonOperator op, final boolean checked)
throws InterruptedException {
Waiter waiter = new Waiter(new Waitable() {
public Object actionProduced(Object obj) {
if (((JToggleButton) obj).isSelected() != checked) {
return null;
} else {
return obj;
}
}
public String getDescription() {
return ("Component description: " + op.getSource().getClass().toString());
}
});
waiter.setOutput(op.getOutput());
waiter.setTimeoutsToCloneOf(op.getTimeouts(),
"ComponentOperator.WaitComponentEnabledTimeout");
waiter.waitAction(op.getSource());
}
private static int convertKey(String keyString) {
if ("Tab".equalsIgnoreCase(keyString))
return KeyEvent.VK_TAB;
else if ("Enter".equalsIgnoreCase(keyString))
return KeyEvent.VK_ENTER;
else if ("End".equalsIgnoreCase(keyString))
return KeyEvent.VK_END;
else if ("Backspace".equalsIgnoreCase(keyString))
return KeyEvent.VK_BACK_SPACE;
else if ("Delete".equalsIgnoreCase(keyString))
return KeyEvent.VK_DELETE;
else if ("Up".equalsIgnoreCase(keyString))
return KeyEvent.VK_UP;
else if ("Down".equalsIgnoreCase(keyString))
return KeyEvent.VK_DOWN;
else if ("Right".equalsIgnoreCase(keyString))
return KeyEvent.VK_RIGHT;
else if ("Left".equalsIgnoreCase(keyString))
return KeyEvent.VK_LEFT;
else if ("Home".equalsIgnoreCase(keyString))
return KeyEvent.VK_HOME;
else if ("End".equalsIgnoreCase(keyString))
return KeyEvent.VK_END;
else if ("F4".equalsIgnoreCase(keyString))
return KeyEvent.VK_F4;
else if ("F5".equalsIgnoreCase(keyString))
return KeyEvent.VK_F5;
else if ("Space".equalsIgnoreCase(keyString))
return KeyEvent.VK_SPACE;
else if ("F7".equalsIgnoreCase(keyString))
return KeyEvent.VK_F7;
else
throw new UnsupportedFeatureException("Type special for " + keyString
+ " not supported");
}
public static abstract class Component {
public abstract ComponentOperator getComponent();
public void assertEnabled() {
try {
getComponent().waitComponentEnabled();
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public void assertDisabled() {
try {
waitComponentDisabled(getComponent());
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
public void store(String id) {
componentMap.putComponent(id, getComponent());
}
}
public static abstract class Container extends Component {
@Override
public abstract ContainerOperator getComponent();
}
public static abstract class Window extends Container {
public abstract boolean isActive();
public abstract boolean isShowing();
}
public static class Frame extends Window {
private final JFrameOperator component;
public Frame(String title) {
component = new JFrameOperator(title);
}
public Frame(JFrame frame) {
component = new JFrameOperator(frame);
}
public Frame close() {
component.requestClose();
return this;
}
public Frame activate() {
component.activate();
currentWindow = this;
return this;
}
@Override
public boolean isActive() {
return component.isActive();
}
@Override
public boolean isShowing() {
return component.isShowing();
}
@Override
public JFrameOperator getComponent() {
return component;
}
}
public static class Dialog extends Window {
private final JDialogOperator component;
public Dialog(String title) {
component = new JDialogOperator(title);
}
public Dialog(JDialog dialog) {
component = new JDialogOperator(dialog);
}
public Dialog close() {
component.requestClose();
return this;
}
@Override
public JDialogOperator getComponent() {
return component;
}
public Dialog activate() {
component.activate();
currentWindow = this;
return this;
}
@Override
public boolean isShowing() {
return component.isShowing();
}
@Override
public boolean isActive() {
return component.isActive();
}
public void assertText(String text) {
final String t = text;
if (text == null)
text = "";
java.awt.Component c = component.findSubComponent(new ComponentChooser() {
@Override
public String getDescription() {
return null;
}
@Override
public boolean checkComponent(java.awt.Component comp) {
if (!comp.isVisible())
return false;
if (comp instanceof JTextField) {
String compText = ((JTextField) comp).getText();
if (compText == null)
compText = "";
return t.equals(compText);
} else if (comp instanceof JLabel) {
String compText = ((JLabel) comp).getText();
if (compText == null)
compText = "";
return t.equals(compText);
}
return false;
}
});
if (c == null) {
throw new AssertionFailedException(
"assert_dialog: could not find component with text " + text);
}
}
}
public static class ScrollPane extends Component {
private final JScrollPaneOperator component;
public ScrollPane(String locator) {
component = find(locator, JScrollPaneOperator.class);
}
public ScrollPane(JScrollPaneOperator component) {
this.component = component;
}
@Override
public ComponentOperator getComponent() {
return component;
}
}
public static class TextField extends Component {
private final JTextComponentOperator component;
public TextField(String locator) {
component = find(locator, JTextComponentOperator.class);
component.setComparator(new Operator.DefaultStringComparator(true, true));
}
public TextField(JTextFieldOperator component) {
this.component = component;
component.setComparator(new Operator.DefaultStringComparator(true, true));
}
public TextField type(String text) {
if (text.contains("\t") || text.contains("\r") || text.contains("\n")) {
throw new IllegalParametersException("Text cannot contain \\t \\r \\n");
}
dispatchingMode();
try {
// TODO: find a better way to guarantee focus on the target typing component
// The solution proposed here tries to guarantee that the textField has the focus
// to make the test as closes as the human interactions as possible.
component.requestFocus();
component.setVerification(false);
component.typeText(text);
return this;
} finally {
robotMode();
}
}
public TextField type(char key) {
component.typeKey(key);
if (!isRobotMode()) {
// This is a hack because type key in queue mode does not wait for events to be
// fired
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new JemmyDSLException(e);
}
}
return this;
}
public TextField type(int key) {
component.pushKey(key);
return this;
}
public String text() {
return component.getText();
}
public void assertText(String text) {
component.waitText(text);
}
@Override
public JTextComponentOperator getComponent() {
return component;
}
public TextField assertEmpty() {
component.waitText("");
return this;
}
public TextField assertNotEmpty() {
String text = component.getText();
if (text == null || text.length() == 0) {
throw new AssertionFailedException("TextField [" + component.getName() + "] is empty.");
}
return this;
}
public TextField clickCharPosition(int pos, String modifiers, int count) {
FontMetrics fm = component.getFontMetrics(component.getFont());
component.clickMouse(fm.stringWidth(component.getText().substring(0, pos))
+ component.getInsets().left,
component.getCenterYForClick(),
count,
KeyEvent.BUTTON1_MASK,
convertModifiers(modifiers));
return this;
}
}
public static class TextArea extends Component {
private final JTextAreaOperator component;
public TextArea(String locator) {
component = find(locator, JTextAreaOperator.class);
}
public TextArea(JTextAreaOperator component) {
this.component = component;
}
public TextArea type(String text) {
if (text.contains("\t") || text.contains("\r") || text.contains("\n")) {
throw new IllegalParametersException("Text cannot contain \\t \\r \\n");
}
component.setVerification(false);
component.typeText(text);
return this;
}
public String text() {
return component.getText();
}
@Override
public JTextAreaOperator getComponent() {
return component;
}
public TextArea assertEmpty() {
component.waitText("");
return this;
}
public TextArea assertNotEmpty() {
String text = component.getText();
if (text == null || text.length() == 0) {
throw new AssertionFailedException("TextArea [" + component.getName() + "] is empty.");
}
return this;
}
}
public static class ComboBox extends Component {
private final JComboBoxOperator component;
public ComboBox(String locator) {
component = find(locator, JComboBoxOperator.class);
}
public ComboBox(JComboBoxOperator comp) {
this.component = comp;
}
public void select(String text) {
Map<String, String> selectedItem = Utils.parseLocator(text);
if (selectedItem.containsKey("name")) {
clickDropDown();
component.selectItem(selectedItem.get("name"));
} else if (selectedItem.containsKey("index")) {
select(Integer.parseInt(selectedItem.get("index")));
} else {
throw new IllegalParametersException("Illegal parameters " + text
+ " for select command");
}
}
public void select(int index) {
clickDropDown();
component.setSelectedIndex(index);
component.waitItemSelected(index);
component.hidePopup();
}
private void clickDropDown() {
component.pushComboButton();
component.waitList();
}
@Override
public JComboBoxOperator getComponent() {
return component;
}
public void assertSelected(String text) {
component.waitItemSelected(text);
}
}
public static class GenericButton extends Component {
protected AbstractButtonOperator component;
protected GenericButton() {}
public GenericButton(String locator) {
component = find(locator, AbstractButtonOperator.class);
}
public GenericButton(AbstractButtonOperator component) {
this.component = component;
}
public void click() {
component.push();
}
@Override
public AbstractButtonOperator getComponent() {
return component;
}
}
public static class Button extends GenericButton {
public Button(String locator) {
component = find(locator, JButtonOperator.class);
}
public Button(JButtonOperator component) {
super(component);
}
@Override
public JButtonOperator getComponent() {
return (JButtonOperator) component;
}
}
public static class CheckBox extends GenericButton {
public CheckBox(String locator) {
component = find(locator, JCheckBoxOperator.class);
}
public CheckBox(JCheckBoxOperator component) {
super(component);
}
@Override
public JCheckBoxOperator getComponent() {
return (JCheckBoxOperator) component;
}
}
public static class RadioButton extends GenericButton {
public RadioButton(String locator) {
component = find(locator, JRadioButtonOperator.class);
}
public RadioButton(JRadioButtonOperator component) {
super(component);
}
@Override
public JRadioButtonOperator getComponent() {
return (JRadioButtonOperator) component;
}
}
public static class Table extends Component {
private final JTableOperator component;
public Table(String locator) {
component = find(locator, JTableOperator.class);
}
public Table(JTableOperator component) {
this.component = component;
}
public Row row(int index) {
return new Row(component, index);
}
public TableHeader header() {
return new TableHeader(component.getTableHeader());
}
public Table selectRows(int first, int last) {
component.setRowSelectionInterval(first, last);
return this;
}
@Override
public JTableOperator getComponent() {
return component;
}
}
public static class TableOperator extends JTableOperator {
public static class XJTableByCellFinder extends JTableByCellFinder {
private final String label;
private final int row;
private final int column;
private final StringComparator comparator;
@Override
public boolean checkComponent(java.awt.Component comp) {
if (!"".equals(label)) {
return super.checkComponent(comp);
} else if (comp instanceof JTable) {
if (((JTable) comp).getRowCount() > row
&& ((JTable) comp).getColumnCount() > column) {
int r = row;
if (r == -1) {
int[] rows = ((JTable) comp).getSelectedRows();
if (rows.length != 0) {
r = rows[0];
} else {
return (false);
}
}
int c = column;
if (c == -1) {
int[] columns = ((JTable) comp).getSelectedColumns();
if (columns.length != 0) {
c = columns[0];
} else {
return (false);
}
}
Object value = ((JTable) comp).getValueAt(r, c);
if (value == null) {
value = "";
}
return (comparator.equals(value.toString(), label));
}
}
return (false);
}
public XJTableByCellFinder(String lb, int r, int c, StringComparator comparator) {
super(lb, r, c, comparator);
this.label = lb;
this.row = r;
this.column = c;
this.comparator = comparator;
}
public XJTableByCellFinder(String lb, int r, int c) {
this(lb, r, c, Operator.getDefaultStringComparator());
}
}
public TableOperator(JTable b) {
super(b);
}
/**
* Overridden to prevent trying to scroll to the row header (which can't be done as the row
* header is located totally to the left of the scroll bar).
*/
@Override
public void scrollToCell(int row, int column) {
// try to find JScrollPane under.
JScrollPane scroll = (JScrollPane) getContainer(new JScrollPaneOperator.JScrollPaneFinder(
ComponentSearcher.getTrueChooser("JScrollPane")));
if (scroll == null) {
return;
}
// if source is the row header table, do nothing
if (getSource() == scroll.getRowHeader().getView()) {
return;
}
super.scrollToCell(row, column);
}
/**
* Overridden method to allow searching for empty strings
*/
@Override
public void waitCell(String cellText, int row, int column) {
waitState(new XJTableByCellFinder(cellText, row, column, getComparator()));
}
}
public static class Row {
private final JTableOperator component;
private final int index;
public Row(JTableOperator component, int index) {
this.component = component;
this.index = index;
}
public Row assertColumn(int col, String value) {
component.waitCell(value, index, col);
return this;
}
/**
* Asserts that a table's cell is not empty, nor null.
*
* @param col Column index of the table, starting at 0.
* @return Cell's row that is asserted to not be empty.
*/
public Row assertNotEmptyColumn(int col) {
String value = (String) component.getValueAt(index, col);
if (value == null || value.length() == 0) {
throw new AssertionFailedException("Table cell (" + index + ", " + col + ") is empty.");
}
return this;
}
public Row select() {
component.setRowSelectionInterval(index, index);
return this;
}
public Row assertSelected(final boolean selected) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JTable) comp).isRowSelected(index) == selected;
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
public Row selectCell(int col) {
component.selectCell(index, col);
return this;
}
public Row clickCell(int col, int clicks) {
component.clickOnCell(index, col, clicks);
return this;
}
}
public static class TableHeader {
private final JTableHeaderOperator component;
public TableHeader(JTableHeader swingComponent) {
component = new JTableHeaderOperator(swingComponent);
}
public TableHeader assertTitle(final int col, final String title) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JTableHeader) comp).getColumnModel()
.getColumn(col)
.getHeaderValue()
.equals(title);
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
/**
* Clicks in a column's table header. <p/>
*
* @param columnIndex Column' index. It's zero based.
* @param count Number of clicks
*/
public void click(int columnIndex, int count) {
TableColumnModel columnModel =
component.getTable().getColumnModel();
int columnCenterX = 0;
int counter = 0;
int convertedColIndex = 0;
while (counter < columnIndex) {
int columnWidth = columnModel.getColumn(convertedColIndex)
.getWidth();
if (columnWidth > 0) {
columnCenterX += columnWidth;
counter++;
}
convertedColIndex++;
}
// get the X value for the center of the column
columnCenterX += (columnModel.getColumn(convertedColIndex)
.getWidth() / 2);
component.clickMouse(columnCenterX,
component.getCenterYForClick(),
count,
InputEvent.BUTTON1_MASK,
convertModifiers(null));
}
}
public static class Label {
private final JLabelOperator component;
public Label(JLabelOperator component) {
this.component = component;
}
public Label text(String text) {
component.waitText(text);
return this;
}
}
public static class TabbedPane extends Component {
private final JTabbedPaneOperator component;
public TabbedPane(String locator) {
component = find(locator, JTabbedPaneOperator.class);
}
public TabbedPane select(String title) {
component.selectPage(title);
return this;
}
public TabbedPane select(int index) {
component.selectPage(index);
return this;
}
@Override
public JTabbedPaneOperator getComponent() {
return component;
}
}
public static class Slider extends Component {
private final JSliderOperator component;
public Slider(String locator) {
component = find(locator, JSliderOperator.class);
}
public Slider value(int i) {
component.setValue(i);
return this;
}
public Slider assertValue(final int i) {
component.waitState(new ComponentChooser() {
@Override
public boolean checkComponent(java.awt.Component comp) {
return ((JSlider) comp).getValue() == i;
}
@Override
public String getDescription() {
return null;
}
});
return this;
}
@Override
public ComponentOperator getComponent() {
return component;
}
}
public static class MenuBar extends Container {
private final JMenuBarOperator component;
public MenuBar() {
component = new JMenuBarOperator(currentWindow().getComponent());
}
public MenuBar(JMenuBarOperator component) {
this.component = component;
}
public MenuBar clickMenu(int... indexes) {
if (indexes.length == 0)
return this;
String[] texts = new String[indexes.length];
JMenu menu = component.getMenu(indexes[0]);
texts[0] = menu.getText();
for (int i = 1; i < indexes.length; i++) {
int index = indexes[i];
assert menu != null;
if (i == indexes.length - 1) {
JMenuItem item = (JMenuItem) menu.getMenuComponent(index);
texts[i] = item.getText();
menu = null;
} else {
menu = (JMenu) menu.getMenuComponent(index);
texts[i] = menu.getText();
}
}
clickMenu(texts);
return this;
}
public MenuBar clickMenu(String... texts) {
if (texts.length == 0)
return this;
component.showMenuItem(texts[0]);
for (int i = 1; i < texts.length; i++) {
String text = texts[i];
new JMenuOperator(currentWindow().getComponent(), texts[i - 1]).showMenuItem(new String[]{text});
}
new JMenuItemOperator(currentWindow().getComponent(), texts[texts.length - 1]).clickMouse();
return this;
}
@Override
public JMenuBarOperator getComponent() {
return component;
}
}
public static class Menu extends Container {
private JMenuOperator component;
public Menu() {}
@Override
public JMenuOperator getComponent() {
return component;
}
}
public static class InternalFrame extends Container {
private final JInternalFrameOperator component;
public InternalFrame(String locator) {
component = find(locator, JInternalFrameOperator.class);
}
public InternalFrame(JInternalFrame frame) {
component = new JInternalFrameOperator(frame);
}
public InternalFrame close() {
((JInternalFrame) component.getSource()).doDefaultCloseAction();
return this;
}
public InternalFrame hide() {
component.setVisible(false);
return this;
}
public InternalFrame show() {
component.setVisible(true);
return this;
}
public InternalFrame activate() {
component.activate();
return this;
}
public InternalFrame assertVisible(Boolean visible) {
component.waitComponentVisible(visible);
return this;
}
@Override
public JInternalFrameOperator getComponent() {
return component;
}
}
public static class ScrollBar extends Component {
private final JScrollBarOperator component;
public ScrollBar(String locator) {
component = find(locator, JScrollBarOperator.class);
}
public ScrollBar(JScrollBarOperator component) {
this.component = component;
}
@Override
public JScrollBarOperator getComponent() {
return component;
}
}
}
| Compare Menu's texts using equals
| core/src/main/java/com/github/srec/jemmy/JemmyDSL.java | Compare Menu's texts using equals | <ide><path>ore/src/main/java/com/github/srec/jemmy/JemmyDSL.java
<ide> import org.netbeans.jemmy.operators.JTextFieldOperator;
<ide> import org.netbeans.jemmy.operators.JToggleButtonOperator;
<ide> import org.netbeans.jemmy.operators.Operator;
<add>import org.netbeans.jemmy.operators.Operator.StringComparator;
<ide> import org.netbeans.jemmy.util.NameComponentChooser;
<ide>
<ide> import java.awt.FontMetrics;
<ide> */
<ide> public class JemmyDSL {
<ide> private static final Logger logger = Logger.getLogger(JemmyDSL.class);
<add> private static final StringComparator comparator = new Operator.DefaultStringComparator(true,false);
<ide>
<ide> public enum ComponentType {
<ide> text_field(JTextFieldOperator.class, JTextField.class),
<ide> clickMenu(texts);
<ide> return this;
<ide> }
<del>
<add>
<ide> public MenuBar clickMenu(String... texts) {
<ide> if (texts.length == 0)
<ide> return this;
<ide> component.showMenuItem(texts[0]);
<ide> for (int i = 1; i < texts.length; i++) {
<ide> String text = texts[i];
<del> new JMenuOperator(currentWindow().getComponent(), texts[i - 1]).showMenuItem(new String[]{text});
<del> }
<del> new JMenuItemOperator(currentWindow().getComponent(), texts[texts.length - 1]).clickMouse();
<add> JMenuOperator jmenu = new JMenuOperator(currentWindow().getComponent(), texts[i - 1]);
<add> jmenu.setComparator(comparator);
<add> jmenu.showMenuItem(new String[]{text});
<add> }
<add> String text = texts[texts.length - 1];
<add> ComponentChooser chooser = new JMenuItemOperator.JMenuItemByLabelFinder(text, comparator);
<add> new JMenuItemOperator(currentWindow().getComponent(), chooser).clickMouse();
<add>
<ide> return this;
<ide> }
<ide> |
|
Java | mit | 5321d5965ad8187661222ad5303f5bd40b270563 | 0 | fr1kin/ForgeHax,fr1kin/ForgeHax | package com.matt.forgehax.mods;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.command.Setting;
import com.matt.forgehax.util.mod.Category;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import net.minecraft.init.Items;
import net.minecraft.inventory.ClickType;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@RegisterMod
public class AutoTotemMod extends ToggleMod {
private final int OFFHAND_SLOT = 45;
public AutoTotemMod() {
super(Category.COMBAT, "AutoTotem", false, "Automatically move totems to off-hand");
}
private final Setting<Boolean> allowGui =
getCommandStub()
.builders()
.<Boolean>newSettingBuilder()
.name("allow-gui")
.description(
"Lets AutoTotem work in menus.")
.defaultTo(false)
.build();
@Override
public String getDisplayText() {
final long totemCount =
IntStream.rangeClosed(9, 45) // include offhand slot
.mapToObj(i -> MC.player.inventoryContainer.getSlot(i).getStack().getItem())
.filter(stack -> stack == Items.TOTEM_OF_UNDYING)
.count();
return String.format(super.getDisplayText() + "[%d]", totemCount);
}
@SubscribeEvent
public void onPlayerUpdate(LocalPlayerUpdateEvent event) {
if (!getOffhand().isEmpty()) {
return; // if there's an item in offhand slot
}
if (MC.currentScreen != null && !allowGui.getAsBoolean()) {
return; // if in inventory
}
findItem(Items.TOTEM_OF_UNDYING)
.ifPresent(
slot -> {
invPickup(slot);
invPickup(OFFHAND_SLOT);
});
}
private void invPickup(final int slot) {
MC.playerController.windowClick(0, slot, 0, ClickType.PICKUP, MC.player);
}
private OptionalInt findItem(final Item ofType) {
for (int i = 9; i <= 44; i++) {
if (MC.player.inventoryContainer.getSlot(i).getStack().getItem() == ofType) {
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
private ItemStack getOffhand() {
return MC.player.getItemStackFromSlot(EntityEquipmentSlot.OFFHAND);
}
}
| src/main/java/com/matt/forgehax/mods/AutoTotemMod.java | package com.matt.forgehax.mods;
import com.matt.forgehax.events.LocalPlayerUpdateEvent;
import com.matt.forgehax.util.mod.Category;
import com.matt.forgehax.util.mod.ToggleMod;
import com.matt.forgehax.util.mod.loader.RegisterMod;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import net.minecraft.init.Items;
import net.minecraft.inventory.ClickType;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@RegisterMod
public class AutoTotemMod extends ToggleMod {
private final int OFFHAND_SLOT = 45;
public AutoTotemMod() {
super(Category.COMBAT, "AutoTotem", false, "Automatically move totems to off-hand");
}
@Override
public String getDisplayText() {
final long totemCount =
IntStream.rangeClosed(9, 45) // include offhand slot
.mapToObj(i -> MC.player.inventoryContainer.getSlot(i).getStack().getItem())
.filter(stack -> stack == Items.TOTEM_OF_UNDYING)
.count();
return String.format(super.getDisplayText() + "[%d]", totemCount);
}
@SubscribeEvent
public void onPlayerUpdate(LocalPlayerUpdateEvent event) {
if (!getOffhand().isEmpty()) {
return; // if there's an item in offhand slot
}
if (MC.currentScreen != null) {
return; // if in inventory
}
findItem(Items.TOTEM_OF_UNDYING)
.ifPresent(
slot -> {
invPickup(slot);
invPickup(OFFHAND_SLOT);
});
}
private void invPickup(final int slot) {
MC.playerController.windowClick(0, slot, 0, ClickType.PICKUP, MC.player);
}
private OptionalInt findItem(final Item ofType) {
for (int i = 9; i <= 44; i++) {
if (MC.player.inventoryContainer.getSlot(i).getStack().getItem() == ofType) {
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
private ItemStack getOffhand() {
return MC.player.getItemStackFromSlot(EntityEquipmentSlot.OFFHAND);
}
}
| Added Menu Patch to Auto Totem (#142)
| src/main/java/com/matt/forgehax/mods/AutoTotemMod.java | Added Menu Patch to Auto Totem (#142) | <ide><path>rc/main/java/com/matt/forgehax/mods/AutoTotemMod.java
<ide> package com.matt.forgehax.mods;
<ide>
<ide> import com.matt.forgehax.events.LocalPlayerUpdateEvent;
<add>import com.matt.forgehax.util.command.Setting;
<ide> import com.matt.forgehax.util.mod.Category;
<ide> import com.matt.forgehax.util.mod.ToggleMod;
<ide> import com.matt.forgehax.util.mod.loader.RegisterMod;
<ide> public AutoTotemMod() {
<ide> super(Category.COMBAT, "AutoTotem", false, "Automatically move totems to off-hand");
<ide> }
<del>
<add>
<add> private final Setting<Boolean> allowGui =
<add> getCommandStub()
<add> .builders()
<add> .<Boolean>newSettingBuilder()
<add> .name("allow-gui")
<add> .description(
<add> "Lets AutoTotem work in menus.")
<add> .defaultTo(false)
<add> .build();
<add>
<ide> @Override
<ide> public String getDisplayText() {
<ide> final long totemCount =
<ide> if (!getOffhand().isEmpty()) {
<ide> return; // if there's an item in offhand slot
<ide> }
<del> if (MC.currentScreen != null) {
<add> if (MC.currentScreen != null && !allowGui.getAsBoolean()) {
<ide> return; // if in inventory
<ide> }
<ide> |
|
Java | mit | 8d5cb6391086c438b4e265bcd30858b9bdab391d | 0 | Ordinastie/MalisisCore | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.malisis.core.util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
/**
* Utility class to handle different interactions with {@link BlockPos}.
*
* @author Ordinastie
*
*/
public class BlockPosUtils
{
/**
* Rotates the {@link BlockPos} around the Y axis around the origin (0,0,0).
*
* @param pos the pos
* @param rotation the rotation
* @return the block pos
*/
public static BlockPos rotate(BlockPos pos, int rotation)
{
int[] cos = { 1, 0, -1, 0 };
int[] sin = { 0, 1, 0, -1 };
int a = -rotation & 3;
int newX = (pos.getX() * cos[a]) - (pos.getZ() * sin[a]);
int newZ = (pos.getX() * sin[a]) + (pos.getZ() * cos[a]);
return new BlockPos(newX, pos.getY(), newZ);
}
/**
* Converts the {@link BlockPos} to its position relative to the chunk it's in.
*
* @param pos the pos
* @return the block pos
*/
public static BlockPos chunkPosition(BlockPos pos)
{
return new BlockPos(pos.getX() - (pos.getX() >> 4) * 16, pos.getY() - (pos.getY() >> 4) * 16, pos.getZ() - (pos.getZ() >> 4) * 16);
}
/**
* Gets an iterable iterating through all the {@link BlockPos} intersecting the passed {@link AxisAlignedBB}.
*
* @param aabb the aabb
* @return the all in box
*/
public static Iterable<BlockPos> getAllInBox(AxisAlignedBB aabb)
{
return BlockPos.getAllInBox(new BlockPos(aabb.minX, aabb.minY, aabb.minZ),
new BlockPos(Math.ceil(aabb.maxX) - 1, Math.ceil(aabb.maxY) - 1, Math.ceil(aabb.maxZ) - 1));
}
public static ByteBuf toBytes(BlockPos pos)
{
ByteBuf buf = Unpooled.buffer(8);
buf.writeLong(pos.toLong());
return buf;
}
public static BlockPos fromBytes(ByteBuf buf)
{
return BlockPos.fromLong(buf.readLong());
}
/**
* Compares the distance of the passed {@link BlockPos} to the origin (0,0,0).
*
* @param pos1 the pos 1
* @param pos2 the pos 2
* @return the int
*/
public static int compare(BlockPos pos1, BlockPos pos2)
{
return compare(new Point(0, 0, 0), pos1, pos2);
}
/**
* Compares the distance of the passed {@link BlockPos} to the <i>offset</i> {@link Point}.
*
* @param offset the offset
* @param pos1 the pos 1
* @param pos2 the pos 2
* @return the int
*/
public static int compare(Point offset, BlockPos pos1, BlockPos pos2)
{
if (pos1.equals(pos2))
return 0;
return Double.compare(pos1.distanceSq(offset.x, offset.y, offset.z), pos2.distanceSq(offset.x, offset.y, offset.z));
}
}
| src/main/java/net/malisis/core/util/BlockPosUtils.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.malisis.core.util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
/**
* Utility class to handle different interactions with {@link BlockPos}.
*
* @author Ordinastie
*
*/
public class BlockPosUtils
{
/**
* Rotates the {@link BlockPos} around the Y axis around the origin (0,0,0).
*
* @param pos the pos
* @param rotation the rotation
* @return the block pos
*/
public static BlockPos rotate(BlockPos pos, int rotation)
{
int[] cos = { 1, 0, -1, 0 };
int[] sin = { 0, 1, 0, -1 };
int a = -rotation & 3;
int newX = (pos.getX() * cos[a]) - (pos.getZ() * sin[a]);
int newZ = (pos.getX() * sin[a]) + (pos.getZ() * cos[a]);
return new BlockPos(newX, pos.getY(), newZ);
}
/**
* Converts the {@link BlockPos} to its position relative to the chunk it's in.
*
* @param pos the pos
* @return the block pos
*/
public static BlockPos chunkPosition(BlockPos pos)
{
return new BlockPos(pos.getX() - (pos.getX() >> 4) * 16, pos.getY() - (pos.getY() >> 4) * 16, pos.getZ() - (pos.getZ() >> 4) * 16);
}
/**
* Gets an iterable iterating through all the {@link BlockPos} intersecting the passed {@link AxisAlignedBB}.
*
* @param aabb the aabb
* @return the all in box
*/
public static Iterable<BlockPos> getAllInBox(AxisAlignedBB aabb)
{
return BlockPos.getAllInBox(new BlockPos(aabb.minX, aabb.minY, aabb.minZ),
new BlockPos(Math.ceil(aabb.maxX) - 1, Math.ceil(aabb.maxY) - 1, Math.ceil(aabb.maxZ) - 1));
}
public static ByteBuf toBytes(BlockPos pos)
{
ByteBuf buf = Unpooled.buffer(8);
buf.writeLong(pos.toLong());
return buf;
}
public static BlockPos fromBytes(ByteBuf buf)
{
return BlockPos.fromLong(buf.readLong());
}
/**
* Compares the distance of the passed {@link BlockPos} to the origin (0,0,0).
*
* @param pos1 the pos 1
* @param pos2 the pos 2
* @return the int
*/
public static int compare(BlockPos pos1, BlockPos pos2)
{
return compare(new Point(0, 0, 0), pos1, pos2);
}
/**
* Compares the distance of the passed {@link BlockPos} to the <i>offset</i> {@link Point}.
*
* @param offset the offset
* @param pos1 the pos 1
* @param pos2 the pos 2
* @return the int
*/
public static int compare(Point offset, BlockPos pos1, BlockPos pos2)
{
if (pos1.equals(pos2))
return 0;
return (int) (pos1.distanceSq(offset.x, offset.y, offset.z) - pos2.distanceSq(offset.x, offset.y, offset.z));
}
}
| Changed compare to use Double.compare | src/main/java/net/malisis/core/util/BlockPosUtils.java | Changed compare to use Double.compare | <ide><path>rc/main/java/net/malisis/core/util/BlockPosUtils.java
<ide> if (pos1.equals(pos2))
<ide> return 0;
<ide>
<del> return (int) (pos1.distanceSq(offset.x, offset.y, offset.z) - pos2.distanceSq(offset.x, offset.y, offset.z));
<add> return Double.compare(pos1.distanceSq(offset.x, offset.y, offset.z), pos2.distanceSq(offset.x, offset.y, offset.z));
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 96bca5ecfb6f460c179d3dae0a4ba251e0a47273 | 0 | apache/empire-db,apache/empire-db,apache/empire-db,apache/empire-db | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.empire.db.expr.column;
import java.util.Set;
// Java
import org.apache.empire.data.DataType;
import org.apache.empire.db.DBColumn;
import org.apache.empire.db.DBColumnExpr;
import org.apache.empire.db.DBExpr;
/**
* This class is used for performing various SQL functions on a column or column expression.
* <P>
* There is no need to explicitly create instances of this class.<BR>
* Instead use any of the following functions:<BR>
* {@link DBColumnExpr#abs() }, {@link DBColumnExpr#coalesce(Object) }, {@link DBColumnExpr#convertTo(DataType) },
* {@link DBColumnExpr#decode(java.util.Map, Object) }, {@link DBColumnExpr#lower() }, {@link DBColumnExpr#min() },
* {@link DBColumnExpr#max() }, {@link DBColumnExpr#month() }, {@link DBColumnExpr#sum() },
* {@link DBColumnExpr#trim() }, {@link DBColumnExpr#upper() }, {@link DBColumnExpr#year() }
* <P>
*
*/
public class DBFuncExpr extends DBAbstractFuncExpr
{
private final static long serialVersionUID = 1L;
protected final int phrase;
protected final Object[] params;
protected String template;
/**
* Constructs a new DBFuncExpr object set the specified parameters to this object.
* Do not use directly - use any of the DBColumnExpr.??? factory functions instead!
*
* The sql function string is built from a string template.
* The template string is identified by the phrase param and obtained from the driver.
*
* @param expr the DBColumnExpr object
* @param phrase the SQL-phrase
* @param params an array of params which will be replaced in the template
* @param updateColumn optional update column if any. This parameter may be null
* @param isAggregate indicates whether the function is an aggregate function (sum, min, max, avg, ...)
* @param dataType indicates the data type of the function result
*/
public DBFuncExpr(DBColumnExpr expr, int phrase, Object[] params, DBColumn updateColumn, boolean isAggregate, DataType dataType)
{
super(expr, updateColumn, isAggregate, dataType);
// Set Phrase and Params
this.phrase = phrase;
this.params = params;
this.template = null;
}
/**
* Constructs a new DBFuncExpr object set the specified parameters to this object.
*
* The sql function string is built from a string template.
* The template string must contain a ? which is a placeholder for the column expression.
*
* @param expr the DBColumnExpr object
* @param template specifies a template for the expression. The template must contain a ? placeholder for the column expression
* @param params an array of params which will be replaced in the template
* @param updateColumn optional update column if any. This parameter may be null
* @param isAggregate indicates whether the function is an aggregate function (sum, min, max, avg, ...)
* @param dataType indicates the data type of the function result
*/
public DBFuncExpr(DBColumnExpr expr, String template, Object[] params, DBColumn updateColumn, boolean isAggregate, DataType dataType)
{
super(expr, updateColumn, isAggregate, dataType);
// Set Phrase and Params
this.phrase = 0;
this.params = params;
this.template = template;
}
@Override
protected String getFunctionName()
{
// Get the template
if (template==null && getDatabaseDriver()!=null)
template = getDatabaseDriver().getSQLPhrase(phrase);
// Get the first word
if (template!=null)
{
String s = template.trim();
int i=0;
for (; i<s.length(); i++)
if (s.charAt(i)<'A')
break;
// return name
if (i>0)
return s.substring(0,i);
}
// default
return "func_" + String.valueOf(phrase);
}
/**
* @see org.apache.empire.db.DBExpr#addReferencedColumns(Set)
*/
@Override
public void addReferencedColumns(Set<DBColumn> list)
{
super.addReferencedColumns(list);
if (this.params==null)
return;
// Check params
for (int i=0; i<this.params.length; i++)
{ // add referenced columns
if (params[i] instanceof DBExpr)
((DBExpr)params[i]).addReferencedColumns(list);
}
}
/**
* Creates the SQL-Command adds a function to the SQL-Command.
*
* @param sql the SQL-Command
* @param context the current SQL-Command context
*/
@Override
public void addSQL(StringBuilder sql, long context)
{
// Get the template
if (template==null)
template = getDatabaseDriver().getSQLPhrase(phrase);
// Add SQL
super.addSQL(sql, template, params, context);
}
} | empire-db/src/main/java/org/apache/empire/db/expr/column/DBFuncExpr.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.empire.db.expr.column;
// Java
import org.apache.empire.data.DataType;
import org.apache.empire.db.DBColumn;
import org.apache.empire.db.DBColumnExpr;
/**
* This class is used for performing various SQL functions on a column or column expression.
* <P>
* There is no need to explicitly create instances of this class.<BR>
* Instead use any of the following functions:<BR>
* {@link DBColumnExpr#abs() }, {@link DBColumnExpr#coalesce(Object) }, {@link DBColumnExpr#convertTo(DataType) },
* {@link DBColumnExpr#decode(java.util.Map, Object) }, {@link DBColumnExpr#lower() }, {@link DBColumnExpr#min() },
* {@link DBColumnExpr#max() }, {@link DBColumnExpr#month() }, {@link DBColumnExpr#sum() },
* {@link DBColumnExpr#trim() }, {@link DBColumnExpr#upper() }, {@link DBColumnExpr#year() }
* <P>
*
*/
public class DBFuncExpr extends DBAbstractFuncExpr
{
private final static long serialVersionUID = 1L;
protected final int phrase;
protected final Object[] params;
protected String template;
/**
* Constructs a new DBFuncExpr object set the specified parameters to this object.
* Do not use directly - use any of the DBColumnExpr.??? factory functions instead!
*
* The sql function string is built from a string template.
* The template string is identified by the phrase param and obtained from the driver.
*
* @param expr the DBColumnExpr object
* @param phrase the SQL-phrase
* @param params an array of params which will be replaced in the template
* @param updateColumn optional update column if any. This parameter may be null
* @param isAggregate indicates whether the function is an aggregate function (sum, min, max, avg, ...)
* @param dataType indicates the data type of the function result
*/
public DBFuncExpr(DBColumnExpr expr, int phrase, Object[] params, DBColumn updateColumn, boolean isAggregate, DataType dataType)
{
super(expr, updateColumn, isAggregate, dataType);
// Set Phrase and Params
this.phrase = phrase;
this.params = params;
this.template = null;
}
/**
* Constructs a new DBFuncExpr object set the specified parameters to this object.
*
* The sql function string is built from a string template.
* The template string must contain a ? which is a placeholder for the column expression.
*
* @param expr the DBColumnExpr object
* @param template specifies a template for the expression. The template must contain a ? placeholder for the column expression
* @param params an array of params which will be replaced in the template
* @param updateColumn optional update column if any. This parameter may be null
* @param isAggregate indicates whether the function is an aggregate function (sum, min, max, avg, ...)
* @param dataType indicates the data type of the function result
*/
public DBFuncExpr(DBColumnExpr expr, String template, Object[] params, DBColumn updateColumn, boolean isAggregate, DataType dataType)
{
super(expr, updateColumn, isAggregate, dataType);
// Set Phrase and Params
this.phrase = 0;
this.params = params;
this.template = template;
}
@Override
protected String getFunctionName()
{
// Get the template
if (template==null && getDatabaseDriver()!=null)
template = getDatabaseDriver().getSQLPhrase(phrase);
// Get the first word
if (template!=null)
{
String s = template.trim();
int i=0;
for (; i<s.length(); i++)
if (s.charAt(i)<'A')
break;
// return name
if (i>0)
return s.substring(0,i);
}
// default
return "func_" + String.valueOf(phrase);
}
/**
* Creates the SQL-Command adds a function to the SQL-Command.
*
* @param sql the SQL-Command
* @param context the current SQL-Command context
*/
@Override
public void addSQL(StringBuilder sql, long context)
{
// Get the template
if (template==null)
template = getDatabaseDriver().getSQLPhrase(phrase);
// Add SQL
super.addSQL(sql, template, params, context);
}
} | EMPIREDB-295: bufix addRerferencedColumns()
| empire-db/src/main/java/org/apache/empire/db/expr/column/DBFuncExpr.java | EMPIREDB-295: bufix addRerferencedColumns() | <ide><path>mpire-db/src/main/java/org/apache/empire/db/expr/column/DBFuncExpr.java
<ide> */
<ide> package org.apache.empire.db.expr.column;
<ide>
<add>import java.util.Set;
<add>
<ide> // Java
<ide> import org.apache.empire.data.DataType;
<ide> import org.apache.empire.db.DBColumn;
<ide> import org.apache.empire.db.DBColumnExpr;
<add>import org.apache.empire.db.DBExpr;
<ide>
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<add> * @see org.apache.empire.db.DBExpr#addReferencedColumns(Set)
<add> */
<add> @Override
<add> public void addReferencedColumns(Set<DBColumn> list)
<add> {
<add> super.addReferencedColumns(list);
<add> if (this.params==null)
<add> return;
<add> // Check params
<add> for (int i=0; i<this.params.length; i++)
<add> { // add referenced columns
<add> if (params[i] instanceof DBExpr)
<add> ((DBExpr)params[i]).addReferencedColumns(list);
<add> }
<add> }
<add>
<add> /**
<ide> * Creates the SQL-Command adds a function to the SQL-Command.
<ide> *
<ide> * @param sql the SQL-Command |
|
Java | apache-2.0 | 75b21da2c41aa4ecf409fa9698f51420d44e0c2f | 0 | dudzislaw/SORCER,mwsobol/SORCER,s13372/SORCER,dudzislaw/SORCER,s8537/SORCER,s8537/SORCER,s13372/SORCER,mwsobol/SORCER,dudzislaw/SORCER,s8537/SORCER,mwsobol/SORCER,s13372/SORCER | package sorcer.netlet.util;
/**
* Copyright 2013, 2014 Sorcersoft.com S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.rioproject.resolver.Artifact;
import sorcer.resolver.*;
import sorcer.resolver.SorcerResolver;
import sorcer.resolver.SorcerResolverException;
import sorcer.util.JavaSystemProperties;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used by LoaderConfiguration and ScriptThread to load jars from path
* User: Pawel.Rubach
* Date: 06.06.13
* Time: 01:56
* To change this template use File | Settings | File Templates.
*/
public class LoaderConfigurationHelper {
private static final char WILDCARD = '*';
public static final String LOAD_PREFIX = "load";
public static final String CODEBASE_PREFIX = "codebase";
static final Logger logger = LoggerFactory.getLogger(LoaderConfigurationHelper.class.getName());
private static SorcerResolver sorcerResolver = SorcerResolver.getInstance();
public static List<URL> load(String str) {
List<URL> urlsList = new ArrayList<URL>();
URI uri;
str = assignProperties(str);
//first check for simple artifact coordinates
if (Artifact.isArtifact(str))
try {
URL[] classpath = SorcerRioResolver.toURLs(sorcerResolver.doResolve(str));
Collections.addAll(urlsList, classpath);
} catch (SorcerResolverException e) {
logger.error("Could not resolve " + str, e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
else {
try {
uri = new URI(str);
} catch (URISyntaxException e) {
logger.error( "Error while parsing URL " + str, e);
return urlsList;
}
String scheme = uri.getScheme();
if ("http".equals(scheme)) {
try {
urlsList.add(new URL(str));
} catch (MalformedURLException e) {
logger.error("Problem creating URL: " + str);
}
} else if ("artifact".equals(scheme)) {
try {
urlsList.add(uri.toURL());
URL[] classpath = SorcerRioResolver.toURLs(sorcerResolver.doResolve(uri.toString()));
Collections.addAll(urlsList, classpath);
} catch (SorcerResolverException e) {
logger.error( "Could not resolve " + str, e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} else if ("file".equals(scheme) || scheme==null || (new File(str).exists())) {
return getFilesFromFilteredPath(str);
}
}
return urlsList;
}
public static List<URL> setCodebase(List<String> codebaseLines, PrintStream out) {
String curCodebase = System.getProperty(JavaSystemProperties.RMI_SERVER_CODEBASE);
StringBuilder codebaseSb = new StringBuilder();
if (curCodebase!=null) codebaseSb.append(curCodebase);
List<URL> codebaseUrls = new ArrayList<URL>();
for (String codebaseStr : codebaseLines) {
if (codebaseStr.startsWith(LoaderConfigurationHelper.CODEBASE_PREFIX))
codebaseStr = codebaseStr.substring(LoaderConfigurationHelper.CODEBASE_PREFIX.length()).trim();
if ((!codebaseStr.startsWith("http://")) && (!codebaseStr.startsWith("artifact:"))) {
if (out!=null) out.println("Codebase can only be specified using http:// or artifact:");
else logger.error("Codebase can only be specified using mvn://, http:// or artifact:");
return null;
}
if (codebaseStr != null) {
try {
codebaseUrls.add(new URL(codebaseStr));
} catch (MalformedURLException me) {
if (out != null) out.println("Codebase url is malformed: " + me.getMessage());
else logger.error("Codebase url is malformed: " + me.getMessage());
}
codebaseSb.append(" ").append(codebaseStr);
}
}
System.setProperty(JavaSystemProperties.RMI_SERVER_CODEBASE, codebaseSb.toString());
return codebaseUrls;
}
public static boolean existRemoteFile(URL url) {
try {
HttpURLConnection huc = ( HttpURLConnection ) url.openConnection();
huc.setRequestMethod("HEAD");
if (huc.getResponseCode() == HttpURLConnection.HTTP_OK)
return true;
} catch (ProtocolException e) {
logger.error("Problem with protocol while loading URL to classpath: " + url.toString() + "\n" + e.getMessage());
} catch (IOException e) {
logger.error("Problem adding remote file to classpath, file does not exist: " + url.toString() + "\n" + e.getMessage());
}
return false;
}
/*
* Expands the properties inside the given string to it's values.
*/
public static String assignProperties(String str) {
int propertyIndexStart = 0, propertyIndexEnd = 0;
boolean requireProperty;
String result = "";
while (propertyIndexStart < str.length()) {
{
int i1 = str.indexOf("${", propertyIndexStart);
int i2 = str.indexOf("!{", propertyIndexStart);
if (i1 == -1) {
propertyIndexStart = i2;
} else if (i2 == -1) {
propertyIndexStart = i1;
} else {
propertyIndexStart = Math.min(i1, i2);
}
requireProperty = propertyIndexStart == i2;
}
if (propertyIndexStart == -1) break;
result += str.substring(propertyIndexEnd, propertyIndexStart);
propertyIndexEnd = str.indexOf("}", propertyIndexStart);
if (propertyIndexEnd == -1) break;
String propertyKey = str.substring(propertyIndexStart + 2, propertyIndexEnd);
String propertyValue;
propertyValue = System.getProperty(propertyKey);
// assume properties contain paths
if (propertyValue == null) {
if (requireProperty) {
throw new IllegalArgumentException("Variable " + propertyKey + " in nsh.config references a non-existent System property! Try passing the property to the VM using -D" + propertyKey + "=myValue in JAVA_OPTS");
} else {
return null;
}
}
propertyValue = getSlashyPath(propertyValue);
propertyValue = correctDoubleSlash(propertyValue,propertyIndexEnd,str);
result += propertyValue;
propertyIndexEnd++;
propertyIndexStart = propertyIndexEnd;
}
if (propertyIndexStart == -1 || propertyIndexStart >= str.length()) {
result += str.substring(propertyIndexEnd);
} else if (propertyIndexEnd == -1) {
result += str.substring(propertyIndexStart);
}
return result;
}
/**
* Get files to load a possibly filtered path. Filters are defined
* by using the * wildcard like in any shell.
*/
public static List<URL> getFilesFromFilteredPath(String filter) {
List<URL> filesToLoad = new ArrayList<URL>();
if (filter == null) return null;
filter = getSlashyPath(filter);
int starIndex = filter.indexOf(WILDCARD);
if (starIndex == -1) {
try {
filesToLoad.add(new File(filter).toURI().toURL());
} catch (MalformedURLException e) {
logger.error("Problem converting file to URL: " + e.getMessage());
}
//addFile(new File(filter));
return filesToLoad;
}
return filesToLoad;
}
private static String correctDoubleSlash(String propertyValue, int propertyIndexEnd, String str) {
int index = propertyIndexEnd+1;
if ( index<str.length() && str.charAt(index)=='/' &&
propertyValue.endsWith("/") &&
propertyValue.length()>0)
{
propertyValue = propertyValue.substring(0,propertyValue.length()-1);
}
return propertyValue;
}
// change path representation to something more system independent.
// This solution is based on an absolute path
private static String getSlashyPath(final String path) {
String changedPath = path;
if (File.separatorChar != '/')
changedPath = changedPath.replace(File.separatorChar, '/');
return changedPath;
}
}
| core/sorcer-platform/src/main/java/sorcer/netlet/util/LoaderConfigurationHelper.java | package sorcer.netlet.util;
/**
* Copyright 2013, 2014 Sorcersoft.com S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.rioproject.resolver.Artifact;
import sorcer.resolver.*;
import sorcer.resolver.SorcerResolver;
import sorcer.resolver.SorcerResolverException;
import sorcer.util.JavaSystemProperties;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.*;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used by LoaderConfiguration and ScriptThread to load jars from path
* User: Pawel.Rubach
* Date: 06.06.13
* Time: 01:56
* To change this template use File | Settings | File Templates.
*/
public class LoaderConfigurationHelper {
private static final char WILDCARD = '*';
public static final String LOAD_PREFIX = "load";
public static final String CODEBASE_PREFIX = "codebase";
static final Logger logger = LoggerFactory.getLogger(LoaderConfigurationHelper.class.getName());
private static SorcerResolver sorcerResolver = SorcerResolver.getInstance();
public static List<URL> load(String str) {
List<URL> urlsList = new ArrayList<URL>();
URI uri;
str = assignProperties(str);
//first check for simple artifact coordinates
if (Artifact.isArtifact(str))
try {
URL[] classpath = SorcerRioResolver.toURLs(sorcerResolver.doResolve(str));
Collections.addAll(urlsList, classpath);
} catch (SorcerResolverException e) {
logger.error("Could not resolve " + str, e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
else {
try {
uri = new URI(str);
} catch (URISyntaxException e) {
logger.error( "Error while parsing URL " + str, e);
return urlsList;
}
String scheme = uri.getScheme();
if ("http".equals(scheme)) {
try {
urlsList.add(new URL(str));
} catch (MalformedURLException e) {
logger.error("Problem creating URL: " + str);
}
} else if ("artifact".equals(scheme)) {
try {
urlsList.add(uri.toURL());
URL[] classpath = SorcerRioResolver.toURLs(sorcerResolver.doResolve(uri.toString()));
Collections.addAll(urlsList, classpath);
} catch (SorcerResolverException e) {
logger.error( "Could not resolve " + str, e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
} else if ("file".equals(scheme) || scheme==null) {
return getFilesFromFilteredPath(str);
}
}
return urlsList;
}
public static List<URL> setCodebase(List<String> codebaseLines, PrintStream out) {
String curCodebase = System.getProperty(JavaSystemProperties.RMI_SERVER_CODEBASE);
StringBuilder codebaseSb = new StringBuilder();
if (curCodebase!=null) codebaseSb.append(curCodebase);
List<URL> codebaseUrls = new ArrayList<URL>();
for (String codebaseStr : codebaseLines) {
if (codebaseStr.startsWith(LoaderConfigurationHelper.CODEBASE_PREFIX))
codebaseStr = codebaseStr.substring(LoaderConfigurationHelper.CODEBASE_PREFIX.length()).trim();
if ((!codebaseStr.startsWith("http://")) && (!codebaseStr.startsWith("artifact:"))) {
if (out!=null) out.println("Codebase can only be specified using http:// or artifact:");
else logger.error("Codebase can only be specified using mvn://, http:// or artifact:");
return null;
}
if (codebaseStr != null) {
try {
codebaseUrls.add(new URL(codebaseStr));
} catch (MalformedURLException me) {
if (out != null) out.println("Codebase url is malformed: " + me.getMessage());
else logger.error("Codebase url is malformed: " + me.getMessage());
}
codebaseSb.append(" ").append(codebaseStr);
}
}
System.setProperty(JavaSystemProperties.RMI_SERVER_CODEBASE, codebaseSb.toString());
return codebaseUrls;
}
public static boolean existRemoteFile(URL url) {
try {
HttpURLConnection huc = ( HttpURLConnection ) url.openConnection();
huc.setRequestMethod("HEAD");
if (huc.getResponseCode() == HttpURLConnection.HTTP_OK)
return true;
} catch (ProtocolException e) {
logger.error("Problem with protocol while loading URL to classpath: " + url.toString() + "\n" + e.getMessage());
} catch (IOException e) {
logger.error("Problem adding remote file to classpath, file does not exist: " + url.toString() + "\n" + e.getMessage());
}
return false;
}
/*
* Expands the properties inside the given string to it's values.
*/
public static String assignProperties(String str) {
int propertyIndexStart = 0, propertyIndexEnd = 0;
boolean requireProperty;
String result = "";
while (propertyIndexStart < str.length()) {
{
int i1 = str.indexOf("${", propertyIndexStart);
int i2 = str.indexOf("!{", propertyIndexStart);
if (i1 == -1) {
propertyIndexStart = i2;
} else if (i2 == -1) {
propertyIndexStart = i1;
} else {
propertyIndexStart = Math.min(i1, i2);
}
requireProperty = propertyIndexStart == i2;
}
if (propertyIndexStart == -1) break;
result += str.substring(propertyIndexEnd, propertyIndexStart);
propertyIndexEnd = str.indexOf("}", propertyIndexStart);
if (propertyIndexEnd == -1) break;
String propertyKey = str.substring(propertyIndexStart + 2, propertyIndexEnd);
String propertyValue;
propertyValue = System.getProperty(propertyKey);
// assume properties contain paths
if (propertyValue == null) {
if (requireProperty) {
throw new IllegalArgumentException("Variable " + propertyKey + " in nsh.config references a non-existent System property! Try passing the property to the VM using -D" + propertyKey + "=myValue in JAVA_OPTS");
} else {
return null;
}
}
propertyValue = getSlashyPath(propertyValue);
propertyValue = correctDoubleSlash(propertyValue,propertyIndexEnd,str);
result += propertyValue;
propertyIndexEnd++;
propertyIndexStart = propertyIndexEnd;
}
if (propertyIndexStart == -1 || propertyIndexStart >= str.length()) {
result += str.substring(propertyIndexEnd);
} else if (propertyIndexEnd == -1) {
result += str.substring(propertyIndexStart);
}
return result;
}
/**
* Get files to load a possibly filtered path. Filters are defined
* by using the * wildcard like in any shell.
*/
public static List<URL> getFilesFromFilteredPath(String filter) {
List<URL> filesToLoad = new ArrayList<URL>();
if (filter == null) return null;
filter = getSlashyPath(filter);
int starIndex = filter.indexOf(WILDCARD);
if (starIndex == -1) {
try {
filesToLoad.add(new File(filter).toURI().toURL());
} catch (MalformedURLException e) {
logger.error("Problem converting file to URL: " + e.getMessage());
}
//addFile(new File(filter));
return filesToLoad;
}
return filesToLoad;
}
private static String correctDoubleSlash(String propertyValue, int propertyIndexEnd, String str) {
int index = propertyIndexEnd+1;
if ( index<str.length() && str.charAt(index)=='/' &&
propertyValue.endsWith("/") &&
propertyValue.length()>0)
{
propertyValue = propertyValue.substring(0,propertyValue.length()-1);
}
return propertyValue;
}
// change path representation to something more system independent.
// This solution is based on an absolute path
private static String getSlashyPath(final String path) {
String changedPath = path;
if (File.separatorChar != '/')
changedPath = changedPath.replace(File.separatorChar, '/');
return changedPath;
}
}
| Fix loading libs in shell
| core/sorcer-platform/src/main/java/sorcer/netlet/util/LoaderConfigurationHelper.java | Fix loading libs in shell | <ide><path>ore/sorcer-platform/src/main/java/sorcer/netlet/util/LoaderConfigurationHelper.java
<ide> } catch (MalformedURLException e) {
<ide> throw new RuntimeException(e);
<ide> }
<del> } else if ("file".equals(scheme) || scheme==null) {
<add> } else if ("file".equals(scheme) || scheme==null || (new File(str).exists())) {
<ide> return getFilesFromFilteredPath(str);
<ide> }
<ide> } |
|
Java | apache-2.0 | fe6dd560c62fba739387ac9edb60e86b904dd802 | 0 | FITeagle/native,FITeagle/native,FITeagle/native | package org.fiteagle.fnative.rest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.fiteagle.api.core.IResourceRepository;
import org.fiteagle.api.core.IResourceRepository.Serialization;
@Path("/repo")
public class ResourceRepository {
private static Logger log = Logger.getLogger(ResourceRepository.class
.toString());
private IResourceRepository repo;
@Inject
private JMSContext context;
@Resource(mappedName = "java:/topic/core")
private Topic topic;
public ResourceRepository() throws NamingException {
final Context context = new InitialContext();
repo = (IResourceRepository) context
.lookup("java:global/core-resourcerepository/ResourceRepositoryEJB");
}
@GET
@Path("/resources.rdf")
@Produces("application/rdf+xml")
public String listResourcesXML() {
log.log(Level.INFO, "Getting resources as RDF...");
return repo.listResources(Serialization.XML);
}
@GET
@Path("/resources.ttl")
@Produces("text/turtle")
public String listResourcesTTL() {
log.log(Level.INFO, "Getting resources as TTL...");
return repo.listResources(Serialization.TTL);
}
@GET
@Path("/async/resources.rdf")
@Produces("application/rdf+xml")
public String listResourcesXMLviaMDB() throws JMSException {
String text = "timeout";
log.log(Level.INFO, "Getting resources as RDF via MDB...");
JMSProducer producer = context.createProducer();
producer.send(topic, "test");
JMSConsumer consumer = context.createConsumer(topic);
TextMessage result = (TextMessage) consumer.receive(3000);
if (null != result)
text = result.getText();
return text;
}
}
| src/main/java/org/fiteagle/fnative/rest/ResourceRepository.java | package org.fiteagle.fnative.rest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.fiteagle.api.core.IResourceRepository;
import org.fiteagle.api.core.IResourceRepository.Serialization;
@Path("/repo")
public class ResourceRepository{
private static Logger log = Logger.getLogger(ResourceRepository.class.toString());
private IResourceRepository repo;
public ResourceRepository() throws NamingException{
final Context context = new InitialContext();
repo = (IResourceRepository) context.lookup("java:global/core-resourcerepository/ResourceRepository");
}
@GET
@Path("/resources.rdf")
@Produces("application/rdf+xml")
public String listResourcesXML() {
log.log(Level.INFO, "Getting resources as RDF...");
return repo.listResources(Serialization.XML);
}
@GET
@Path("/resources.ttl")
@Produces("text/turtle")
public String listResourcesTTL() {
log.log(Level.INFO, "Getting resources as TTL...");
return repo.listResources(Serialization.TTL);
}
}
| added async example (not finished)
| src/main/java/org/fiteagle/fnative/rest/ResourceRepository.java | added async example (not finished) | <ide><path>rc/main/java/org/fiteagle/fnative/rest/ResourceRepository.java
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide>
<add>import javax.annotation.Resource;
<add>import javax.inject.Inject;
<add>import javax.jms.JMSConsumer;
<add>import javax.jms.JMSContext;
<add>import javax.jms.JMSException;
<add>import javax.jms.JMSProducer;
<add>import javax.jms.TextMessage;
<add>import javax.jms.Topic;
<ide> import javax.naming.Context;
<ide> import javax.naming.InitialContext;
<ide> import javax.naming.NamingException;
<ide> import org.fiteagle.api.core.IResourceRepository;
<ide> import org.fiteagle.api.core.IResourceRepository.Serialization;
<ide>
<add>@Path("/repo")
<add>public class ResourceRepository {
<ide>
<del>@Path("/repo")
<del>public class ResourceRepository{
<del>
<del> private static Logger log = Logger.getLogger(ResourceRepository.class.toString());
<del>
<del> private IResourceRepository repo;
<del>
<del> public ResourceRepository() throws NamingException{
<del> final Context context = new InitialContext();
<del> repo = (IResourceRepository) context.lookup("java:global/core-resourcerepository/ResourceRepository");
<del> }
<del>
<del> @GET
<del> @Path("/resources.rdf")
<del> @Produces("application/rdf+xml")
<del> public String listResourcesXML() {
<del> log.log(Level.INFO, "Getting resources as RDF...");
<del> return repo.listResources(Serialization.XML);
<del> }
<add> private static Logger log = Logger.getLogger(ResourceRepository.class
<add> .toString());
<add> private IResourceRepository repo;
<add> @Inject
<add> private JMSContext context;
<add> @Resource(mappedName = "java:/topic/core")
<add> private Topic topic;
<ide>
<del> @GET
<del> @Path("/resources.ttl")
<del> @Produces("text/turtle")
<del> public String listResourcesTTL() {
<del> log.log(Level.INFO, "Getting resources as TTL...");
<del> return repo.listResources(Serialization.TTL);
<del> }
<add> public ResourceRepository() throws NamingException {
<add> final Context context = new InitialContext();
<add> repo = (IResourceRepository) context
<add> .lookup("java:global/core-resourcerepository/ResourceRepositoryEJB");
<add> }
<add>
<add> @GET
<add> @Path("/resources.rdf")
<add> @Produces("application/rdf+xml")
<add> public String listResourcesXML() {
<add> log.log(Level.INFO, "Getting resources as RDF...");
<add> return repo.listResources(Serialization.XML);
<add> }
<add>
<add> @GET
<add> @Path("/resources.ttl")
<add> @Produces("text/turtle")
<add> public String listResourcesTTL() {
<add> log.log(Level.INFO, "Getting resources as TTL...");
<add> return repo.listResources(Serialization.TTL);
<add> }
<add>
<add> @GET
<add> @Path("/async/resources.rdf")
<add> @Produces("application/rdf+xml")
<add> public String listResourcesXMLviaMDB() throws JMSException {
<add> String text = "timeout";
<add>
<add> log.log(Level.INFO, "Getting resources as RDF via MDB...");
<add> JMSProducer producer = context.createProducer();
<add> producer.send(topic, "test");
<add> JMSConsumer consumer = context.createConsumer(topic);
<add>
<add> TextMessage result = (TextMessage) consumer.receive(3000);
<add> if (null != result)
<add> text = result.getText();
<add>
<add> return text;
<add> }
<ide>
<ide> } |
|
Java | apache-2.0 | f6286f35b595bae749100b9263517f62ae833717 | 0 | ryano144/intellij-community,jexp/idea2,amith01994/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,blademainer/intellij-community,ryano144/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,FHannes/intellij-community,allotria/intellij-community,slisson/intellij-community,vladmm/intellij-community,ernestp/consulo,kool79/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,FHannes/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,semonte/intellij-community,robovm/robovm-studio,holmes/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,samthor/intellij-community,Lekanich/intellij-community,semonte/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,caot/intellij-community,signed/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,signed/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,slisson/intellij-community,amith01994/intellij-community,allotria/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,ernestp/consulo,Lekanich/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,supersven/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,slisson/intellij-community,amith01994/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,kool79/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,petteyg/intellij-community,jexp/idea2,salguarnieri/intellij-community,fitermay/intellij-community,apixandru/intellij-community,slisson/intellij-community,allotria/intellij-community,izonder/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,consulo/consulo,caot/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,holmes/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,blademainer/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,supersven/intellij-community,petteyg/intellij-community,blademainer/intellij-community,semonte/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,fitermay/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,robovm/robovm-studio,allotria/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,jexp/idea2,MER-GROUP/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,kool79/intellij-community,supersven/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,petteyg/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,consulo/consulo,ibinti/intellij-community,caot/intellij-community,izonder/intellij-community,robovm/robovm-studio,jexp/idea2,kool79/intellij-community,jagguli/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,consulo/consulo,joewalnes/idea-community,blademainer/intellij-community,semonte/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,izonder/intellij-community,slisson/intellij-community,clumsy/intellij-community,izonder/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,caot/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,caot/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,holmes/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,supersven/intellij-community,kdwink/intellij-community,blademainer/intellij-community,jexp/idea2,ibinti/intellij-community,jagguli/intellij-community,fnouama/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,jexp/idea2,tmpgit/intellij-community,kool79/intellij-community,caot/intellij-community,apixandru/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,signed/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,caot/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,semonte/intellij-community,diorcety/intellij-community,signed/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,supersven/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,signed/intellij-community,joewalnes/idea-community,ernestp/consulo,pwoodworth/intellij-community,kool79/intellij-community,clumsy/intellij-community,samthor/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,amith01994/intellij-community,semonte/intellij-community,diorcety/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,semonte/intellij-community,supersven/intellij-community,tmpgit/intellij-community,signed/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,fnouama/intellij-community,hurricup/intellij-community,consulo/consulo,tmpgit/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,da1z/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,dslomov/intellij-community,consulo/consulo,retomerz/intellij-community,asedunov/intellij-community,ryano144/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,fitermay/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,vladmm/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,slisson/intellij-community,signed/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ernestp/consulo,nicolargo/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,clumsy/intellij-community,asedunov/intellij-community,apixandru/intellij-community,vladmm/intellij-community,ernestp/consulo,petteyg/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,caot/intellij-community,lucafavatella/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ahb0327/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,petteyg/intellij-community,semonte/intellij-community,asedunov/intellij-community,vladmm/intellij-community,supersven/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,fnouama/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,holmes/intellij-community,da1z/intellij-community,slisson/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,caot/intellij-community,jagguli/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,jagguli/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,vvv1559/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,retomerz/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,vladmm/intellij-community,apixandru/intellij-community,allotria/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,FHannes/intellij-community,vladmm/intellij-community,asedunov/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,dslomov/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,robovm/robovm-studio,da1z/intellij-community,samthor/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,dslomov/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,signed/intellij-community,petteyg/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,holmes/intellij-community,samthor/intellij-community,kool79/intellij-community,jagguli/intellij-community,semonte/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,FHannes/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,izonder/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,da1z/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,holmes/intellij-community,dslomov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,youdonghai/intellij-community,izonder/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,slisson/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,holmes/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,jexp/idea2,allotria/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,samthor/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,consulo/consulo,hurricup/intellij-community,adedayo/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,hurricup/intellij-community,ahb0327/intellij-community,holmes/intellij-community,petteyg/intellij-community,allotria/intellij-community,petteyg/intellij-community,izonder/intellij-community,adedayo/intellij-community,holmes/intellij-community,xfournet/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,robovm/robovm-studio,caot/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,apixandru/intellij-community,slisson/intellij-community,clumsy/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ibinti/intellij-community,dslomov/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fnouama/intellij-community,amith01994/intellij-community | package com.intellij.codeInsight;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import gnu.trove.THashSet;
import java.util.*;
/**
* @author mike
*/
public class ExceptionUtil {
public static PsiClassType[] getThrownExceptions(PsiElement[] elements) {
List<PsiClassType> array = new ArrayList<PsiClassType>();
for (int i = 0; i < elements.length; i++) {
PsiClassType[] exceptions = getThrownExceptions(elements[i]);
addExceptions(array, exceptions);
}
return array.toArray(new PsiClassType[array.size()]);
}
public static PsiClassType[] getThrownCheckedExceptions(PsiElement[] elements) {
PsiClassType[] exceptions = getThrownExceptions(elements);
if (exceptions.length == 0) return exceptions;
exceptions = filterOutUncheckedExceptions(exceptions);
return exceptions;
}
private static PsiClassType[] filterOutUncheckedExceptions(PsiClassType[] exceptions) {
if (exceptions.length == 0) return exceptions;
List<PsiClassType> array = new ArrayList<PsiClassType>();
for (int i = 0; i < exceptions.length; i++) {
PsiClassType exception = exceptions[i];
if (!isUncheckedException(exception)) array.add(exception);
}
return array.toArray(new PsiClassType[array.size()]);
}
public static PsiClassType[] getThrownExceptions(PsiElement element) {
if (element instanceof PsiClass) {
return PsiClassType.EMPTY_ARRAY; // filter class declaration in code
}
else if (element instanceof PsiMethodCallExpression) {
PsiReferenceExpression methodRef = ((PsiMethodCallExpression)element).getMethodExpression();
PsiMethod method = (PsiMethod)methodRef.resolve();
return getExceptionsByMethodAndChildren(element, method);
}
else if (element instanceof PsiNewExpression) {
PsiMethod constructor = ((PsiNewExpression)element).resolveConstructor();
return getExceptionsByMethodAndChildren(element, constructor);
}
else if (element instanceof PsiThrowStatement) {
PsiExpression expr = ((PsiThrowStatement)element).getException();
if (expr == null) return PsiClassType.EMPTY_ARRAY;
PsiType exception = expr.getType();
List<PsiClassType> array = new ArrayList<PsiClassType>();
if (exception != null && exception instanceof PsiClassType) {
array.add((PsiClassType)exception);
}
addExceptions(array, getThrownExceptions(expr));
return array.toArray(new PsiClassType[array.size()]);
}
else if (element instanceof PsiTryStatement) {
PsiTryStatement tryStatement = (PsiTryStatement)element;
final PsiCodeBlock tryBlock = tryStatement.getTryBlock();
List<PsiClassType> array = new ArrayList<PsiClassType>();
if (tryBlock != null) {
PsiClassType[] exceptions = getThrownExceptions(tryBlock);
for (int i = 0; i < exceptions.length; i++) {
array.add(exceptions[i]);
}
}
PsiParameter[] parameters = tryStatement.getCatchBlockParameters();
for (int i = 0; i < parameters.length; i++) {
PsiParameter parm = parameters[i];
PsiType exception = parm.getType();
for (int j = array.size()-1; j>=0; j--) {
PsiType exception1 = array.get(j);
if (exception.isAssignableFrom(exception1)) {
array.remove(exception1);
}
}
}
PsiCodeBlock[] catchBlocks = tryStatement.getCatchBlocks();
for (int i = 0; i < catchBlocks.length; i++) {
PsiCodeBlock catchBlock = catchBlocks[i];
addExceptions(array, getThrownExceptions(catchBlock));
}
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock != null) {
// if finally block completes normally, exception not catched
// if finally block completes abruptly, exception gets lost
try {
ControlFlow flow = ControlFlowFactory.getControlFlow(finallyBlock, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(), false);
int completionReasons = ControlFlowUtil.getCompletionReasons(flow, 0, flow.getSize());
PsiClassType[] thrownExceptions = getThrownExceptions(finallyBlock);
if ((completionReasons & ControlFlowUtil.NORMAL_COMPLETION_REASON) == 0) {
array = new ArrayList<PsiClassType>(Arrays.asList(thrownExceptions));
}
else {
addExceptions(array, thrownExceptions);
}
}
catch (AnalysisCanceledException e) {
// incomplete code
}
}
return array.toArray(new PsiClassType[array.size()]);
}
else {
return getThrownExceptions(element.getChildren());
}
}
private static PsiClassType[] getExceptionsByMethodAndChildren(PsiElement element, PsiMethod method) {
List<PsiClassType> array = new ArrayList<PsiClassType>();
if (method != null) {
array.addAll(Arrays.asList(method.getThrowsList().getReferencedTypes()));
}
PsiElement[] children = element.getChildren();
for (int i = 0; i < children.length; i++) {
addExceptions(array, getThrownExceptions(children[i]));
}
return array.toArray(new PsiClassType[array.size()]);
}
private static void addExceptions(List<PsiClassType> array, PsiClassType[] exceptions) {
for (int i = 0; i < exceptions.length; i++) {
addException(array, exceptions[i]);
}
}
private static void addException(List<PsiClassType> array, PsiClassType exception) {
for (int i = array.size()-1; i>=0; i--) {
PsiClassType exception1 = array.get(i);
if (exception1.isAssignableFrom(exception)) return;
if (exception.isAssignableFrom(exception1)) {
array.remove(i);
}
}
array.add(exception);
}
public static PsiClassType[] collectUnhandledExceptions(PsiElement element, PsiElement topElement) {
final Set<PsiClassType> set = collectUnhandledExceptions(element, topElement, null);
return set == null ? PsiClassType.EMPTY_ARRAY : (PsiClassType[])set.toArray(new PsiClassType[set.size()]);
}
private static Set<PsiClassType> collectUnhandledExceptions(PsiElement element, PsiElement topElement, Set<PsiClassType> foundExceptions) {
PsiClassType[] unhandledExceptions = null;
if (element instanceof PsiCallExpression) {
PsiCallExpression expression = (PsiCallExpression)element;
unhandledExceptions = getUnhandledExceptions(expression, topElement);
}
else if (element instanceof PsiThrowStatement) {
PsiThrowStatement statement = (PsiThrowStatement)element;
unhandledExceptions = getUnhandledExceptions(statement, topElement);
}
else if (element instanceof PsiCodeBlock
&& element.getParent() instanceof PsiMethod
&& ((PsiMethod)element.getParent()).isConstructor()
&& !firstStatementIsConstructorCall((PsiCodeBlock)element)) {
// there is implicit parent constructor call
final PsiMethod constructor = (PsiMethod)element.getParent();
final PsiClass aClass = constructor.getContainingClass();
final PsiClass superClass = aClass == null ? null : aClass.getSuperClass();
final PsiMethod[] superConstructors = superClass == null ? PsiMethod.EMPTY_ARRAY : superClass.getConstructors();
Set<PsiClassType> unhandled = new HashSet<PsiClassType>();
for (int i = 0; i < superConstructors.length; i++) {
PsiMethod superConstructor = superConstructors[i];
if (!superConstructor.hasModifierProperty(PsiModifier.PRIVATE) &&
superConstructor.getParameterList().getParameters().length == 0) {
final PsiClassType[] exceptionTypes = superConstructor.getThrowsList().getReferencedTypes();
for (int j = 0; j < exceptionTypes.length; j++) {
PsiClassType exceptionType = exceptionTypes[j];
if (!isUncheckedException(exceptionType) && !isHandled(element, exceptionType, topElement)) {
unhandled.add(exceptionType);
}
}
break;
}
}
// plus all exceptions thrown in instance class initializers
if (aClass != null) {
final PsiClassInitializer[] initializers = aClass.getInitializers();
final Set<PsiClassType> thrownByInitializer = new THashSet<PsiClassType>();
for (int i = 0; i < initializers.length; i++) {
PsiClassInitializer initializer = initializers[i];
if (initializer.hasModifierProperty(PsiModifier.STATIC)) continue;
thrownByInitializer.clear();
collectUnhandledExceptions(initializer.getBody(), initializer, thrownByInitializer);
for (Iterator<PsiClassType> iterator = thrownByInitializer.iterator(); iterator.hasNext();) {
PsiClassType thrown = iterator.next();
if (!isHandled(constructor.getBody(), thrown, topElement)) {
unhandled.add(thrown);
}
}
}
}
unhandledExceptions = unhandled.toArray(new PsiClassType[unhandled.size()]);
}
if (unhandledExceptions != null) {
if (foundExceptions == null) {
foundExceptions = new HashSet<PsiClassType>();
}
for (int i = 0; i < unhandledExceptions.length; i++) {
PsiClassType unhandledException = unhandledExceptions[i];
foundExceptions.add(unhandledException);
}
}
for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
foundExceptions = collectUnhandledExceptions(child, topElement, foundExceptions);
}
return foundExceptions;
}
private static boolean firstStatementIsConstructorCall(PsiCodeBlock constructorBody) {
final PsiStatement[] statements = constructorBody.getStatements();
if (statements.length == 0) return false;
if (!(statements[0] instanceof PsiExpressionStatement)) return false;
final PsiExpression expression = ((PsiExpressionStatement)statements[0]).getExpression();
if (!(expression instanceof PsiMethodCallExpression)) return false;
final PsiMethod method = (PsiMethod)((PsiMethodCallExpression)expression).getMethodExpression().resolve();
if (method == null || !method.isConstructor()) return false;
return true;
}
public static PsiClassType[] getUnhandledExceptions(PsiElement[] elements) {
final List<PsiClassType> array = new ArrayList<PsiClassType>();
PsiRecursiveElementVisitor visitor = new PsiRecursiveElementVisitor() {
public void visitCallExpression(PsiCallExpression expression) {
addExceptions(array, getUnhandledExceptions(expression, null));
visitElement(expression);
}
public void visitThrowStatement(PsiThrowStatement statement) {
addExceptions(array, getUnhandledExceptions(statement, null));
visitElement(statement);
}
};
for (int i = 0; i < elements.length; i++) {
elements[i].accept(visitor);
}
return array.toArray(new PsiClassType[array.size()]);
}
public static PsiClassType[] getUnhandledExceptions(PsiElement element) {
if (element instanceof PsiCallExpression) {
PsiCallExpression expression = (PsiCallExpression)element;
return getUnhandledExceptions(expression, null);
}
else if (element instanceof PsiThrowStatement) {
PsiThrowStatement throwStatement = (PsiThrowStatement)element;
return getUnhandledExceptions(throwStatement, null);
}
return PsiClassType.EMPTY_ARRAY;
}
public static PsiClassType[] getUnhandledExceptions(PsiCallExpression methodCall, PsiElement topElement) {
final ResolveResult result = methodCall.resolveMethodGenerics();
PsiMethod method = (PsiMethod)result.getElement();
return getUnhandledExceptions(method, methodCall, topElement, result.getSubstitutor());
}
public static PsiClassType[] getUnhandledExceptions(PsiThrowStatement throwStatement, PsiElement topElement) {
final PsiExpression exception = throwStatement.getException();
if (exception != null) {
final PsiType type = exception.getType();
if (type instanceof PsiClassType) {
PsiClassType classType = (PsiClassType)type;
if (!isUncheckedException(classType) && !isHandled(throwStatement, classType, topElement)) {
return new PsiClassType[]{classType};
}
}
}
return PsiClassType.EMPTY_ARRAY;
}
private static PsiClassType[] getUnhandledExceptions(PsiMethod method,
PsiElement element,
PsiElement topElement,
PsiSubstitutor substitutor) {
if (method == null || isArrayClone(method, element)) {
return PsiClassType.EMPTY_ARRAY;
}
final PsiReferenceList throwsList = method.getThrowsList();
if (throwsList == null) {
return PsiClassType.EMPTY_ARRAY;
}
final PsiClassType[] referencedTypes = throwsList.getReferencedTypes();
if (referencedTypes != null && referencedTypes.length != 0) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (int i = 0; i < referencedTypes.length; i++) {
PsiClassType referencedType = referencedTypes[i];
final PsiType type = substitutor.substitute(referencedType);
if (!(type instanceof PsiClassType)) continue;
PsiClassType classType = (PsiClassType)type;
PsiClass exceptionClass = ((PsiClassType)type).resolve();
if (exceptionClass == null) continue;
if (isUncheckedException(classType)) continue;
if (isHandled(element, classType, topElement)) continue;
result.add((PsiClassType)type);
}
return result.toArray(new PsiClassType[result.size()]);
}
return PsiClassType.EMPTY_ARRAY;
}
private static boolean isArrayClone(PsiMethod method, PsiElement element) {
if (!(element instanceof PsiMethodCallExpression)) return false;
if (!method.getName().equals("clone")) return false;
PsiClass containingClass = method.getContainingClass();
if (containingClass == null || !"java.lang.Object".equals(containingClass.getQualifiedName())) {
return false;
}
PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)element;
final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
if (qualifierExpression == null) return false;
if (qualifierExpression.getType() instanceof PsiArrayType) return true;
return false;
}
public static boolean isUncheckedException(PsiClassType type) {
GlobalSearchScope searchScope = type.getResolveScope();
PsiClass aClass = type.resolve();
if (aClass == null) return false;
PsiClass runtimeExceptionClass = aClass.getManager().findClass("java.lang.RuntimeException", searchScope);
if (runtimeExceptionClass != null &&
InheritanceUtil.isInheritorOrSelf(aClass, runtimeExceptionClass, true)) {
return true;
}
PsiClass errorClass = aClass.getManager().findClass("java.lang.Error", searchScope);
if (errorClass != null && InheritanceUtil.isInheritorOrSelf(aClass, errorClass, true)) return true;
return false;
}
public static boolean isUncheckedExceptionOrSuperclass(PsiClassType type) {
if (type == null) return false;
String canonicalText = type.getCanonicalText();
return "java.lang.Throwable".equals(canonicalText) ||
"java.lang.Exception".equals(canonicalText) ||
isUncheckedException(type);
}
public static boolean isHandled(PsiClassType exceptionType, PsiElement throwPlace) {
return isHandled(throwPlace, exceptionType, throwPlace.getContainingFile());
}
private static boolean isHandled(PsiElement element, PsiClassType exceptionType, PsiElement topElement) {
if (element == null || element.getParent() == topElement || element.getParent() == null) return false;
final PsiElement parent = element.getParent();
if (parent instanceof PsiMethod) {
PsiMethod method = (PsiMethod)parent;
return isHandledByMethodThrowsClause(method, exceptionType);
}
else if (parent instanceof PsiClass) {
if (parent instanceof PsiAnonymousClass /*&& element instanceof PsiExpressionList*/) {
// arguments to anon class constructor should be handled higher
// like in void f() throws XXX { new AA(methodThrowingXXX()) { ... }; }
return isHandled(parent, exceptionType, topElement);
}
return false;
}
else if (parent instanceof PsiClassInitializer) {
if (((PsiClassInitializer)parent).hasModifierProperty(PsiModifier.STATIC)) return false;
// anonymous class initializers can throw any exceptions
if (!(parent.getParent() instanceof PsiAnonymousClass)) {
// exception thrown from within class instance initializer must be handled in every class constructor
// check each constructor throws exception or superclass (there must be at least one)
final PsiClass aClass = ((PsiClassInitializer)parent).getContainingClass();
return isAllConstructorsThrow(aClass, exceptionType);
}
}
else if (parent instanceof PsiTryStatement) {
PsiTryStatement tryStatement = (PsiTryStatement)parent;
if (tryStatement.getTryBlock() == element && isCatched(tryStatement, exceptionType)) {
return true;
}
else {
return isHandled(parent, exceptionType, topElement);
}
}
else if (parent instanceof JspFile) {
return true;
}
else if (parent instanceof PsiFile) {
return false;
}
else if (parent instanceof PsiField && ((PsiField)parent).getInitializer() == element) {
final PsiClass aClass = ((PsiField)parent).getContainingClass();
if (aClass != null && !(aClass instanceof PsiAnonymousClass) && !((PsiField)parent).hasModifierProperty(PsiModifier.STATIC)) {
// exceptions thrown in field initalizers should be thrown in all class constructors
return isAllConstructorsThrow(aClass, exceptionType);
}
}
return isHandled(parent, exceptionType, topElement);
}
private static boolean isAllConstructorsThrow(final PsiClass aClass, PsiClassType exceptionType) {
if (aClass == null) return false;
final PsiMethod[] constructors = aClass.getConstructors();
boolean thrown = constructors.length != 0;
for (int i = 0; i < constructors.length; i++) {
PsiMethod constructor = constructors[i];
if (!isHandledByMethodThrowsClause(constructor, exceptionType)) {
thrown = false;
break;
}
}
return thrown;
}
private static boolean isCatched(PsiTryStatement tryStatement, PsiClassType exceptionType) {
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock != null) {
PsiClassType[] exceptions = getUnhandledExceptions(finallyBlock);
List<PsiClassType> unhandledFinallyExceptions = Arrays.asList(exceptions);
if (unhandledFinallyExceptions.contains(exceptionType)) return false;
// if finally block completes normally, exception not catched
// if finally block completes abruptly, exception gets lost
try {
ControlFlow flow = ControlFlowFactory.getControlFlow(finallyBlock, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(),
false);
int completionReasons = ControlFlowUtil.getCompletionReasons(flow, 0, flow.getSize());
if ((completionReasons & ControlFlowUtil.NORMAL_COMPLETION_REASON) == 0) return true;
}
catch (AnalysisCanceledException e) {
return true;
}
}
final PsiParameter[] catchBlockParameters = tryStatement.getCatchBlockParameters();
for (int i = 0; i < catchBlockParameters.length; i++) {
PsiParameter parameter = catchBlockParameters[i];
PsiType paramType = parameter.getType();
if (paramType.isAssignableFrom(exceptionType)) return true;
}
return false;
}
public static boolean isHandledByMethodThrowsClause(PsiMethod method, PsiClassType exceptionType) {
final PsiReferenceList throwsList = method.getThrowsList();
if (throwsList == null) return false;
final PsiClassType[] referencedTypes = throwsList.getReferencedTypes();
return isHandledBy(exceptionType, referencedTypes);
}
public static boolean isHandledBy(PsiClassType exceptionType, final PsiClassType[] referencedTypes) {
if (referencedTypes == null) return false;
for (int i = 0; i < referencedTypes.length; i++) {
PsiClassType classType = referencedTypes[i];
if (classType.isAssignableFrom(exceptionType)) return true;
}
return false;
}
}
| source/com/intellij/codeInsight/ExceptionUtil.java | package com.intellij.codeInsight;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.InheritanceUtil;
import gnu.trove.THashSet;
import java.util.*;
/**
* @author mike
*/
public class ExceptionUtil {
public static PsiClassType[] getThrownExceptions(PsiElement[] elements) {
List<PsiClassType> array = new ArrayList<PsiClassType>();
for (int i = 0; i < elements.length; i++) {
PsiClassType[] exceptions = getThrownExceptions(elements[i]);
addExceptions(array, exceptions);
}
return array.toArray(new PsiClassType[array.size()]);
}
public static PsiClassType[] getThrownCheckedExceptions(PsiElement[] elements) {
PsiClassType[] exceptions = getThrownExceptions(elements);
if (exceptions.length == 0) return exceptions;
exceptions = filterOutUncheckedExceptions(exceptions);
return exceptions;
}
private static PsiClassType[] filterOutUncheckedExceptions(PsiClassType[] exceptions) {
if (exceptions.length == 0) return exceptions;
List<PsiClassType> array = new ArrayList<PsiClassType>();
for (int i = 0; i < exceptions.length; i++) {
PsiClassType exception = exceptions[i];
if (!isUncheckedException(exception)) array.add(exception);
}
return array.toArray(new PsiClassType[array.size()]);
}
public static PsiClassType[] getThrownExceptions(PsiElement element) {
if (element instanceof PsiClass) {
return PsiClassType.EMPTY_ARRAY; // filter class declaration in code
}
else if (element instanceof PsiMethodCallExpression) {
PsiReferenceExpression methodRef = ((PsiMethodCallExpression)element).getMethodExpression();
PsiMethod method = (PsiMethod)methodRef.resolve();
return getExceptionsByMethodAndChildren(element, method);
}
else if (element instanceof PsiNewExpression) {
PsiMethod constructor = ((PsiNewExpression)element).resolveConstructor();
return getExceptionsByMethodAndChildren(element, constructor);
}
else if (element instanceof PsiThrowStatement) {
PsiExpression expr = ((PsiThrowStatement)element).getException();
if (expr == null) return PsiClassType.EMPTY_ARRAY;
PsiType exception = expr.getType();
List<PsiClassType> array = new ArrayList<PsiClassType>();
if (exception != null && exception instanceof PsiClassType) {
array.add((PsiClassType)exception);
}
addExceptions(array, getThrownExceptions(expr));
return array.toArray(new PsiClassType[array.size()]);
}
else if (element instanceof PsiTryStatement) {
PsiTryStatement tryStatement = (PsiTryStatement)element;
final PsiCodeBlock tryBlock = tryStatement.getTryBlock();
List<PsiClassType> array = new ArrayList<PsiClassType>();
if (tryBlock != null) {
PsiClassType[] exceptions = getThrownExceptions(tryBlock);
for (int i = 0; i < exceptions.length; i++) {
array.add(exceptions[i]);
}
}
PsiParameter[] parameters = tryStatement.getCatchBlockParameters();
for (int i = 0; i < parameters.length; i++) {
PsiParameter parm = parameters[i];
PsiType exception = parm.getType();
for (int j = array.size()-1; j>=0; j--) {
PsiType exception1 = array.get(j);
if (exception.isAssignableFrom(exception1)) {
array.remove(exception1);
}
}
}
PsiCodeBlock[] catchBlocks = tryStatement.getCatchBlocks();
for (int i = 0; i < catchBlocks.length; i++) {
PsiCodeBlock catchBlock = catchBlocks[i];
addExceptions(array, getThrownExceptions(catchBlock));
}
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock != null) {
// if finally block completes normally, exception not catched
// if finally block completes abruptly, exception gets lost
try {
ControlFlow flow = ControlFlowFactory.getControlFlow(finallyBlock, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(), false);
int completionReasons = ControlFlowUtil.getCompletionReasons(flow, 0, flow.getSize());
PsiClassType[] thrownExceptions = getThrownExceptions(finallyBlock);
if ((completionReasons & ControlFlowUtil.NORMAL_COMPLETION_REASON) == 0) {
array = new ArrayList<PsiClassType>(Arrays.asList(thrownExceptions));
}
else {
addExceptions(array, thrownExceptions);
}
}
catch (AnalysisCanceledException e) {
// incomplete code
}
}
return array.toArray(new PsiClassType[array.size()]);
}
else {
return getThrownExceptions(element.getChildren());
}
}
private static PsiClassType[] getExceptionsByMethodAndChildren(PsiElement element, PsiMethod method) {
List<PsiClassType> array = new ArrayList<PsiClassType>();
if (method != null) {
array.addAll(Arrays.asList(method.getThrowsList().getReferencedTypes()));
}
PsiElement[] children = element.getChildren();
for (int i = 0; i < children.length; i++) {
addExceptions(array, getThrownExceptions(children[i]));
}
return array.toArray(new PsiClassType[array.size()]);
}
private static void addExceptions(List<PsiClassType> array, PsiClassType[] exceptions) {
for (int i = 0; i < exceptions.length; i++) {
addException(array, exceptions[i]);
}
}
private static void addException(List<PsiClassType> array, PsiClassType exception) {
for (int i = array.size()-1; i>=0; i--) {
PsiClassType exception1 = array.get(i);
if (exception1.isAssignableFrom(exception)) return;
if (exception.isAssignableFrom(exception1)) {
array.remove(i);
}
}
array.add(exception);
}
public static PsiClassType[] collectUnhandledExceptions(PsiElement element, PsiElement topElement) {
final Set<PsiClassType> set = collectUnhandledExceptions(element, topElement, null);
return set == null ? PsiClassType.EMPTY_ARRAY : (PsiClassType[])set.toArray(new PsiClassType[set.size()]);
}
private static Set<PsiClassType> collectUnhandledExceptions(PsiElement element, PsiElement topElement, Set<PsiClassType> foundExceptions) {
PsiClassType[] unhandledExceptions = null;
if (element instanceof PsiCallExpression) {
PsiCallExpression expression = (PsiCallExpression)element;
unhandledExceptions = getUnhandledExceptions(expression, topElement);
}
else if (element instanceof PsiThrowStatement) {
PsiThrowStatement statement = (PsiThrowStatement)element;
unhandledExceptions = getUnhandledExceptions(statement, topElement);
}
else if (element instanceof PsiCodeBlock
&& element.getParent() instanceof PsiMethod
&& ((PsiMethod)element.getParent()).isConstructor()
&& !firstStatementIsConstructorCall((PsiCodeBlock)element)) {
// there is implicit parent constructor call
final PsiMethod constructor = (PsiMethod)element.getParent();
final PsiClass aClass = constructor.getContainingClass();
final PsiClass superClass = aClass == null ? null : aClass.getSuperClass();
final PsiMethod[] superConstructors = superClass == null ? PsiMethod.EMPTY_ARRAY : superClass.getConstructors();
Set<PsiClassType> unhandled = new HashSet<PsiClassType>();
for (int i = 0; i < superConstructors.length; i++) {
PsiMethod superConstructor = superConstructors[i];
if (!superConstructor.hasModifierProperty(PsiModifier.PRIVATE) &&
superConstructor.getParameterList().getParameters().length == 0) {
final PsiClassType[] exceptionTypes = superConstructor.getThrowsList().getReferencedTypes();
for (int j = 0; j < exceptionTypes.length; j++) {
PsiClassType exceptionType = exceptionTypes[j];
if (!isUncheckedException(exceptionType) && !isHandled(element, exceptionType, topElement)) {
unhandled.add(exceptionType);
}
}
break;
}
}
// plus all exceptions thrown in instance class initializers
if (aClass != null) {
final PsiClassInitializer[] initializers = aClass.getInitializers();
final Set<PsiClassType> thrownByInitializer = new THashSet<PsiClassType>();
for (int i = 0; i < initializers.length; i++) {
PsiClassInitializer initializer = initializers[i];
if (initializer.hasModifierProperty(PsiModifier.STATIC)) continue;
thrownByInitializer.clear();
collectUnhandledExceptions(initializer.getBody(), initializer, thrownByInitializer);
for (Iterator<PsiClassType> iterator = thrownByInitializer.iterator(); iterator.hasNext();) {
PsiClassType thrown = iterator.next();
if (!isHandled(constructor.getBody(), thrown, topElement)) {
unhandled.add(thrown);
}
}
}
}
unhandledExceptions = unhandled.toArray(new PsiClassType[unhandled.size()]);
}
if (unhandledExceptions != null) {
if (foundExceptions == null) {
foundExceptions = new HashSet<PsiClassType>();
}
for (int i = 0; i < unhandledExceptions.length; i++) {
PsiClassType unhandledException = unhandledExceptions[i];
foundExceptions.add(unhandledException);
}
}
for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
foundExceptions = collectUnhandledExceptions(child, topElement, foundExceptions);
}
return foundExceptions;
}
private static boolean firstStatementIsConstructorCall(PsiCodeBlock constructorBody) {
final PsiStatement[] statements = constructorBody.getStatements();
if (statements.length == 0) return false;
if (!(statements[0] instanceof PsiExpressionStatement)) return false;
final PsiExpression expression = ((PsiExpressionStatement)statements[0]).getExpression();
if (!(expression instanceof PsiMethodCallExpression)) return false;
final PsiMethod method = (PsiMethod)((PsiMethodCallExpression)expression).getMethodExpression().resolve();
if (method == null || !method.isConstructor()) return false;
return true;
}
public static PsiClassType[] getUnhandledExceptions(PsiElement[] elements) {
final List<PsiClassType> array = new ArrayList<PsiClassType>();
PsiRecursiveElementVisitor visitor = new PsiRecursiveElementVisitor() {
public void visitCallExpression(PsiCallExpression expression) {
addExceptions(array, getUnhandledExceptions(expression, null));
visitElement(expression);
}
public void visitThrowStatement(PsiThrowStatement statement) {
addExceptions(array, getUnhandledExceptions(statement, null));
visitElement(statement);
}
};
for (int i = 0; i < elements.length; i++) {
elements[i].accept(visitor);
}
return array.toArray(new PsiClassType[array.size()]);
}
public static PsiClassType[] getUnhandledExceptions(PsiElement element) {
if (element instanceof PsiCallExpression) {
PsiCallExpression expression = (PsiCallExpression)element;
return getUnhandledExceptions(expression, null);
}
else if (element instanceof PsiThrowStatement) {
PsiThrowStatement throwStatement = (PsiThrowStatement)element;
return getUnhandledExceptions(throwStatement, null);
}
return PsiClassType.EMPTY_ARRAY;
}
public static PsiClassType[] getUnhandledExceptions(PsiCallExpression methodCall, PsiElement topElement) {
final ResolveResult result = methodCall.resolveMethodGenerics();
PsiMethod method = (PsiMethod)result.getElement();
return getUnhandledExceptions(method, methodCall, topElement, result.getSubstitutor());
}
public static PsiClassType[] getUnhandledExceptions(PsiThrowStatement throwStatement, PsiElement topElement) {
final PsiExpression exception = throwStatement.getException();
if (exception != null) {
final PsiType type = exception.getType();
if (type instanceof PsiClassType) {
PsiClassType classType = (PsiClassType)type;
if (!isUncheckedException(classType) && !isHandled(throwStatement, classType, topElement)) {
return new PsiClassType[]{classType};
}
}
}
return PsiClassType.EMPTY_ARRAY;
}
private static PsiClassType[] getUnhandledExceptions(PsiMethod method,
PsiElement element,
PsiElement topElement,
PsiSubstitutor substitutor) {
if (method == null || isArrayClone(method, element)) {
return PsiClassType.EMPTY_ARRAY;
}
final PsiReferenceList throwsList = method.getThrowsList();
if (throwsList == null) {
return PsiClassType.EMPTY_ARRAY;
}
final PsiClassType[] referencedTypes = throwsList.getReferencedTypes();
if (referencedTypes != null && referencedTypes.length != 0) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (int i = 0; i < referencedTypes.length; i++) {
PsiClassType referencedType = referencedTypes[i];
final PsiType type = substitutor.substitute(referencedType);
if (!(type instanceof PsiClassType)) continue;
PsiClassType classType = (PsiClassType)type;
PsiClass exceptionClass = ((PsiClassType)type).resolve();
if (exceptionClass == null) continue;
if (isUncheckedException(classType)) continue;
if (isHandled(element, classType, topElement)) continue;
result.add((PsiClassType)type);
}
return result.toArray(new PsiClassType[result.size()]);
}
return PsiClassType.EMPTY_ARRAY;
}
private static boolean isArrayClone(PsiMethod method, PsiElement element) {
if (!(element instanceof PsiMethodCallExpression)) return false;
if (!method.getName().equals("clone")) return false;
PsiClass containingClass = method.getContainingClass();
if (containingClass == null || !"java.lang.Object".equals(containingClass.getQualifiedName())) {
return false;
}
PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)element;
final PsiExpression qualifierExpression = methodCallExpression.getMethodExpression().getQualifierExpression();
if (qualifierExpression == null) return false;
if (qualifierExpression.getType() instanceof PsiArrayType) return true;
return false;
}
public static boolean isUncheckedException(PsiClassType type) {
GlobalSearchScope searchScope = type.getResolveScope();
PsiClass aClass = type.resolve();
if (aClass == null) return false;
PsiClass runtimeExceptionClass = aClass.getManager().findClass("java.lang.RuntimeException", searchScope);
if (runtimeExceptionClass != null &&
InheritanceUtil.isInheritorOrSelf(aClass, runtimeExceptionClass, true)) {
return true;
}
PsiClass errorClass = aClass.getManager().findClass("java.lang.Error", searchScope);
if (errorClass != null && InheritanceUtil.isInheritorOrSelf(aClass, errorClass, true)) return true;
return false;
}
public static boolean isUncheckedExceptionOrSuperclass(PsiClassType type) {
if (type == null) return false;
String canonicalText = type.getCanonicalText();
return "java.lang.Throwable".equals(canonicalText) ||
"java.lang.Exception".equals(canonicalText) ||
isUncheckedException(type);
}
public static boolean isHandled(PsiClassType exceptionType, PsiElement throwPlace) {
return isHandled(throwPlace, exceptionType, throwPlace.getContainingFile());
}
private static boolean isHandled(PsiElement element, PsiClassType exceptionType, PsiElement topElement) {
if (element == null || element.getParent() == topElement || element.getParent() == null) return false;
final PsiElement parent = element.getParent();
if (parent instanceof PsiMethod) {
PsiMethod method = (PsiMethod)parent;
return isHandledByMethodThrowsClause(method, exceptionType);
}
else if (parent instanceof PsiClass) {
if (parent instanceof PsiAnonymousClass /*&& element instanceof PsiExpressionList*/) {
// arguments to anon class constructor should be handled higher
// like in void f() throws XXX { new AA(methodThrowingXXX()) { ... }; }
return isHandled(parent, exceptionType, topElement);
}
return false;
}
else if (parent instanceof PsiClassInitializer) {
// anonymous class initializers can throw any exceptions
if (!(parent.getParent() instanceof PsiAnonymousClass)) {
// exception thrown from within class instance initializer must be handled in every class constructor
// check each constructor throws exception or superclass (there must be at least one)
final PsiClass aClass = ((PsiClassInitializer)parent).getContainingClass();
return isAllConstructorsThrow(aClass, exceptionType);
}
}
else if (parent instanceof PsiTryStatement) {
PsiTryStatement tryStatement = (PsiTryStatement)parent;
if (tryStatement.getTryBlock() == element && isCatched(tryStatement, exceptionType)) {
return true;
}
else {
return isHandled(parent, exceptionType, topElement);
}
}
else if (parent instanceof JspFile) {
return true;
}
else if (parent instanceof PsiFile) {
return false;
}
else if (parent instanceof PsiField && ((PsiField)parent).getInitializer() == element) {
final PsiClass aClass = ((PsiField)parent).getContainingClass();
if (aClass != null && !(aClass instanceof PsiAnonymousClass) && !((PsiField)parent).hasModifierProperty(PsiModifier.STATIC)) {
// exceptions thrown in field initalizers should be thrown in all class constructors
return isAllConstructorsThrow(aClass, exceptionType);
}
}
return isHandled(parent, exceptionType, topElement);
}
private static boolean isAllConstructorsThrow(final PsiClass aClass, PsiClassType exceptionType) {
if (aClass == null) return false;
final PsiMethod[] constructors = aClass.getConstructors();
boolean thrown = constructors.length != 0;
for (int i = 0; i < constructors.length; i++) {
PsiMethod constructor = constructors[i];
if (!isHandledByMethodThrowsClause(constructor, exceptionType)) {
thrown = false;
break;
}
}
return thrown;
}
private static boolean isCatched(PsiTryStatement tryStatement, PsiClassType exceptionType) {
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if (finallyBlock != null) {
PsiClassType[] exceptions = getUnhandledExceptions(finallyBlock);
List<PsiClassType> unhandledFinallyExceptions = Arrays.asList(exceptions);
if (unhandledFinallyExceptions.contains(exceptionType)) return false;
// if finally block completes normally, exception not catched
// if finally block completes abruptly, exception gets lost
try {
ControlFlow flow = ControlFlowFactory.getControlFlow(finallyBlock, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(),
false);
int completionReasons = ControlFlowUtil.getCompletionReasons(flow, 0, flow.getSize());
if ((completionReasons & ControlFlowUtil.NORMAL_COMPLETION_REASON) == 0) return true;
}
catch (AnalysisCanceledException e) {
return true;
}
}
final PsiParameter[] catchBlockParameters = tryStatement.getCatchBlockParameters();
for (int i = 0; i < catchBlockParameters.length; i++) {
PsiParameter parameter = catchBlockParameters[i];
PsiType paramType = parameter.getType();
if (paramType.isAssignableFrom(exceptionType)) return true;
}
return false;
}
public static boolean isHandledByMethodThrowsClause(PsiMethod method, PsiClassType exceptionType) {
final PsiReferenceList throwsList = method.getThrowsList();
if (throwsList == null) return false;
final PsiClassType[] referencedTypes = throwsList.getReferencedTypes();
return isHandledBy(exceptionType, referencedTypes);
}
public static boolean isHandledBy(PsiClassType exceptionType, final PsiClassType[] referencedTypes) {
if (referencedTypes == null) return false;
for (int i = 0; i < referencedTypes.length; i++) {
PsiClassType classType = referencedTypes[i];
if (classType.isAssignableFrom(exceptionType)) return true;
}
return false;
}
}
| (no message) | source/com/intellij/codeInsight/ExceptionUtil.java | (no message) | <ide><path>ource/com/intellij/codeInsight/ExceptionUtil.java
<ide> return false;
<ide> }
<ide> else if (parent instanceof PsiClassInitializer) {
<add> if (((PsiClassInitializer)parent).hasModifierProperty(PsiModifier.STATIC)) return false;
<ide> // anonymous class initializers can throw any exceptions
<ide> if (!(parent.getParent() instanceof PsiAnonymousClass)) {
<ide> // exception thrown from within class instance initializer must be handled in every class constructor |
|
Java | apache-2.0 | 9321c9c6e95c0c5e545e18f4335c15a5641bde57 | 0 | jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.sandwell.JavaSimulation3D;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.DoubleListInput;
import com.sandwell.JavaSimulation.DoubleVector;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityListInput;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.Simulation;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation.Vector;
import com.sandwell.JavaSimulation.Vector3dInput;
import com.sandwell.JavaSimulation3D.util.Circle;
import com.sandwell.JavaSimulation3D.util.Cube;
import com.sandwell.JavaSimulation3D.util.Shape;
import javax.media.j3d.Node;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.media.j3d.Appearance;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.DistanceLOD;
import javax.media.j3d.LineArray;
import javax.media.j3d.OrderedGroup;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Switch;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.vecmath.Point3d;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3d;
/**
* Encapsulates the methods and data needed to display a simulation object in the 3D environment.
* Extends the basic functionality of entity in order to have access to the basic system
* components like the eventManager.
*
* <h3>Visual Heirarchy</h3>
*
* GraphicsSimulation.rootLocale (Locale)<br>
* -stores regionBranchGroups in the Vector: regionModels<br>
* -this vector corrects the J3D memory leak when the visual universe has no viewers<br>
*<br>
* Region.branchGroup (BranchGroup from DisplayEntity)<br>
*<br>
* Region.rootTransform (TransformGroup from DisplayEntity)<br>
*<br>
* Region.scaleTransform (TransformGroup from DisplayEntity)<br>
*<br>
* DisplayEntity.branchGroup (BranchGroup)<br>
* ** allows detach, pick reporting<br>
* - provides the container to add and remove from a region<br>
* - the basis for selecting an object from the visual display<br>
*<br>
* DisplayEntity.rootTransform (TransformGroup)<br>
* ** allows writing and extending children, changing transforms<br>
* - provides the basis for local transformations of position and orientation<br>
* - host for visual utilities bounds, name and axis<br>
*<br>
* DisplayEntity.scaleTransform (TransformGroup)<br>
* ** allows changing transforms<br>
* - provides the basis for local transformation of scaling<br>
* - used to scale model, but not visual utilities like bounds and axis<br>
*<br>
* DisplayEntity.displayModel (BranchGroup)<br>
* ** allows detach, reading, writing, extending children<br>
* - provides the container for user models to be added to the visual universe<br>
* - capabilities to allow manipulation of the model's components<br>
*<br>
* Shape3D, BranchGroup, SharedGroup, Shape2D (Rectangle, Circle, Label, ...) (Node)<br>
* - model for the DisplayEntity comprised of components of Shape3Ds<br>
* - may be loaded from a geometry file<br>
*
*
*
* <h3>DisplayEntity Structure</h3>
*
* DisplayEntity is defined to be compatible with Audition DisplayPerformers, as such origin and extent
* are provided. Since the display of objects using Java3D is not bound to 2 dimensions nor a fixed
* range of pixels, some changes are required.<br>
*<br>
* - extent does not provides physical visual bounds of the DisplayEntity, rather it is a convenience used
* to determine where the logical dimensions of the object. It has no effect on visual display<br>
*<br>
* - origin represents the bottom left (in 2D space) of the DisplayEntity. It is calculate from the
* more fundamental center and is related by the extent value. Origin can still be used for positioning
* but rather center should be used for future compatibility.<br>
*<br>
* - center represents the position of the object in 3D space. This is the default positioning mechanism
* for DisplayEntities. Setting the origin will be translated into setting the center. The center represents
* the position on the Region of the local origin for the displayModel.<br>
*/
public class DisplayEntity extends Entity {
private static final ArrayList<DisplayEntity> allInstances;
// simulation properties
/** Graphic Simulation object this model is running under **/
protected static GraphicSimulation simulation;
// J3D graphics properties
private final BranchGroup branchGroup; // connects to the region
private final TransformGroup rootTransform; // provides universal transformations for the DisplayEntity's entire model
private final TransformGroup scaleTransform; // provides scaling for display models
private final OrderedGroup displayNode; // container for DisplayEntity's specific model
private boolean needsRender = true;
private final Vector3dInput positionInput;
private final Vector3d position = new Vector3d();
private final Vector3d size = new Vector3d(1.0d, 1.0d, 1.0d);
private final Vector3d orient = new Vector3d();
private final Vector3d align = new Vector3d();
private final Vector3d scale = new Vector3d(1.0d, 1.0d, 1.0d);
private DoubleListInput levelOfDetail;
private final EntityListInput<DisplayModel> displayModelList; // DisplayModel from the input
protected final ArrayList<DisplayModelBG> displayModels; // DisplayModel which represents this DisplayEntity
private final EntityInput<DisplayEntity> relativeEntity;
private final BooleanInput show;
private final BooleanInput active;
private final BooleanInput movable;
private boolean animated = false;
// continuous motion properties
/** a Vector of Vector3d with coordinates for points along the track to be traversed */
protected Vector displayTrack;
/** the distance of the entity along the track in screen units */
protected double displayDistanceAlongTrack;
/** Distance in screen units of each portion in the track */
protected DoubleVector displayTrackDistanceList;
/** Angle in radians for each portion in the track */
protected Vector displayTrackOrientationList;
/** Total distance in screen units of the track */
protected double displayTrackTotalDistance;
/** the display speed of the entity in screen units per hour for continuous motion */
protected double displaySpeedAlongTrack;
/** the time at which the entity was last moved */
private double timeOfLastMovement;
// resize and rotate listener
private boolean showResize = false;
private BranchGroup rotateSizeBounds; // holds the extent outline
private LineArray resizeLine; // bounding box for the entity for picking
// setup a default appearance for the default displayModel
private static Appearance axisLineAppearance;
// vector of mouseNodes
private ArrayList<MouseNode> mouseNodes;
protected double mouseNodesSize;
protected BooleanInput showToolTip; // true => show the tooltip on the screen for the DisplayEntity
protected boolean graphicsSetup = false;
static {
axisLineAppearance = new Appearance();
axisLineAppearance.setLineAttributes( new javax.media.j3d.LineAttributes( 2, javax.media.j3d.LineAttributes.PATTERN_SOLID, false ) );
allInstances = new ArrayList<DisplayEntity>(100);
}
{
positionInput = new Vector3dInput("Position", "Graphics", new Vector3d());
positionInput.setUnits("m");
this.addInput(positionInput, true);
addEditableKeyword( "Alignment", "", "0.000 0.000 0.000", false, "Graphics" );
addEditableKeyword( "Size", "", "1.000 1.000 1.000", false, "Graphics" );
addEditableKeyword( "Orientation", "", "0.000 0.000 0.000", false, "Graphics" );
addEditableKeyword( "Region", "", "ModelStage", false, "Graphics" );
showToolTip = new BooleanInput("ToolTip", "Graphics", true);
this.addInput(showToolTip, true);
addEditableKeyword( "MouseNodesExtent", " - ", " - ", false, "Graphics" );
relativeEntity = new EntityInput<DisplayEntity>(DisplayEntity.class, "RelativeEntity", "Graphics", null);
this.addInput(relativeEntity, true);
displayModelList = new EntityListInput<DisplayModel>( DisplayModel.class, "DisplayModel", "Graphics", null);
this.addInput(displayModelList, true);
displayModelList.setUnique(false);
levelOfDetail = new DoubleListInput("LevelOfDetail", "Graphics", null);
levelOfDetail.setValidRange( 0.0d, Double.POSITIVE_INFINITY );
this.addInput(levelOfDetail, true);
show = new BooleanInput("Show", "Graphics", true);
this.addInput(show, true);
active = new BooleanInput("Active", "Graphics", true);
this.addInput(active, true);
movable = new BooleanInput("Movable", "Graphics", true);
this.addInput(movable, true);
}
/**
* Constructor: initializing the DisplayEntity's graphics
*/
public DisplayEntity() {
super();
allInstances.add(this);
// Create a branchgroup and make it detachable.
branchGroup = new BranchGroup();
branchGroup.setCapability( BranchGroup.ALLOW_DETACH );
branchGroup.setCapability( BranchGroup.ENABLE_PICK_REPORTING );
// Hold a reference to the DisplayEntity in the topmost branchgroup to
// speed up picking lookups
branchGroup.setUserData(this);
// Initialize the root transform to be the identity
rootTransform = new TransformGroup();
rootTransform.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_EXTEND );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_READ );
branchGroup.addChild( rootTransform );
// Initialize the root transform to be the identity
scaleTransform = new TransformGroup();
scaleTransform.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
scaleTransform.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
scaleTransform.setCapability( TransformGroup.ALLOW_CHILDREN_EXTEND );
rootTransform.addChild( scaleTransform );
displayTrack = new Vector( 1, 1 );
displayDistanceAlongTrack = 0.0;
displayTrackDistanceList = new DoubleVector( 1, 1 );
displayTrackOrientationList = new Vector( 1, 1 ); // Vector of Vector3d
displayTrackTotalDistance = 0.0;
displaySpeedAlongTrack = 0.0;
timeOfLastMovement = 0.0;
// create a placeholder of the model
displayNode = new OrderedGroup();
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_WRITE );
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_EXTEND );
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_READ );
scaleTransform.addChild( displayNode );
mouseNodes = new ArrayList<MouseNode>();
setMouseNodesSize(0.050);
displayModels = new ArrayList<DisplayModelBG>();
DisplayModel dm = this.getDefaultDisplayModel();
if(dm != null) {
ArrayList<DisplayModel> defList = new ArrayList<DisplayModel>();
defList.add(dm);
displayModelList.setDefaultValue(defList);
}
}
public static ArrayList<? extends DisplayEntity> getAll() {
return allInstances;
}
/**
* Sets the Graphic Simulation object for the entity.
* @param newSimulation - states the new simulation the entity is controled by
*/
public static void setSimulation( GraphicSimulation newSimulation ) {
simulation = newSimulation;
}
/**
* Removes the entity from its current region and assigns a new region
* @param newRegion - the region the entity will be assigned to
*/
public void setRegion( Region newRegion ) {
exitRegion();
currentRegion = newRegion;
}
/**
* Visually adds the entity to its currently assigned region
*/
public void enterRegion() {
if( currentRegion != null ) {
currentRegion.addEntity( this );
}
else {
throw new RuntimeException( "Region not set" );
}
if (!this.getShow()) {
exitRegion();
}
}
/**
* Removes the entity from its current region and visually adds the entity to the specified region.
* @param newRegion - the region the entity will be assigned to
*/
public void enterRegion( Region newRegion ) {
setRegion( newRegion );
enterRegion();
}
/**
* Visually removes the entity from its region. The current region for the entity is maintained.
*/
public void exitRegion() {
if( currentRegion != null ) {
currentRegion.removeEntity( this );
}
}
private void duplicate() {
ObjectType type = ObjectType.getFor(this.getClass());
if(type == null)
return;
DisplayEntity copiedEntity = (DisplayEntity)type.getNewInstance();
// Unique name
int i = 1;
String name = String.format("Copy_of_%s", getInputName());
while (Simulation.getNamedEntity(name) != null) {
name = String.format("Copy%d_of_%s", i, getInputName());
i++;
}
copiedEntity.setInputName(name);
copiedEntity.setName(name);
// Match all the inputs
for(Input<?> each: getEditableInputs() ){
if(!each.getValueString().isEmpty())
EditBox.processEntity_Keyword_Value(copiedEntity, each.getKeyword(), each.getValueString());
}
Vector3d pos = copiedEntity.getPosition();
Vector3d offset = copiedEntity.getSize();
offset.scale(0.5);
offset.setZ(0);
pos.add(offset);
copiedEntity.setPosition(pos);
copiedEntity.initializeGraphics();
copiedEntity.enterRegion();
FrameBox.setSelectedEntity(copiedEntity);
}
private void addLabel() {
ObjectType type = ObjectType.getFor(TextLabel.class);
if(type == null)
return;
TextLabel label = (TextLabel)type.getNewInstance();
// Unique name
int i = 1;
String name = String.format("Label_for_%s", getInputName());
while (Simulation.getNamedEntity(name) != null) {
name = String.format("Label%d_of_%s", i, getInputName());
i++;
}
label.setName(name);
label.setInputName(name);
EditBox.processEntity_Keyword_Value(label, "RelativeEntity", this.getInputName() );
EditBox.processEntity_Keyword_Value(label, "Position", "1.0, -1.0, 0.0" );
EditBox.processEntity_Keyword_Value(label, "Region", currentRegion.getInputName() );
label.setText(this.getName());
label.initializeGraphics();
label.enterRegion();
FrameBox.setSelectedEntity(label);
}
/**
* Destroys the branchGroup hierarchy for the entity
*/
public void kill() {
super.kill();
for (MouseNode each : mouseNodes) {
each.kill();
}
allInstances.remove(this);
exitRegion();
if(OrbitBehavior.selectedEntity == this)
OrbitBehavior.selectedEntity = null;
currentRegion = null;
clearModel();
displayTrack = null;
displayDistanceAlongTrack = 0.0;
displayTrackDistanceList = null;
displayTrackOrientationList = null;
displayTrackTotalDistance = 0.0;
displaySpeedAlongTrack = 0.0;
}
public void render(double time) {
synchronized (position) {
if (animated)
this.animate(time);
if (!needsRender && relativeEntity.getValue() == null)
return;
Transform3D temp = new Transform3D();
temp.setEuler(orient);
Vector3d offset = new Vector3d(size.x * align.x, size.y * align.y, size.z * align.z);
temp.transform(offset);
offset.sub(position, offset);
offset.add(getOffsetToRelativeEntity());
temp.setTranslation(offset);
rootTransform.setTransform(temp);
temp.setIdentity();
temp.setScale(scale);
scaleTransform.setTransform(temp);
if( !graphicsSetup ) {
this.setupGraphics();
graphicsSetup = true;
}
if (showResize) {
if( mouseNodes.size() > 0 ) {
nodesOn();
}
else {
if (rotateSizeBounds == null)
makeResizeBounds();
updateResizeBounds(size.x, size.y, size.z);
}
}
else {
if( mouseNodes.size() > 0 ) {
nodesOff();
}
else {
if (rotateSizeBounds != null) {
rootTransform.removeChild(rotateSizeBounds);
rotateSizeBounds = null;
}
}
}
for (DisplayModelBG each : displayModels) {
each.setModelSize(size);
}
needsRender = false;
}
}
private void calculateEulerRotation(Vector3d val, Vector3d euler) {
double sinx = Math.sin(euler.x);
double siny = Math.sin(euler.y);
double sinz = Math.sin(euler.z);
double cosx = Math.cos(euler.x);
double cosy = Math.cos(euler.y);
double cosz = Math.cos(euler.z);
// Calculate a 3x3 rotation matrix
double m00 = cosy * cosz;
double m01 = -(cosx * sinz) + (sinx * siny * cosz);
double m02 = (sinx * sinz) + (cosx * siny * cosz);
double m10 = cosy * sinz;
double m11 = (cosx * cosz) + (sinx * siny * sinz);
double m12 = -(sinx * cosz) + (cosx * siny * sinz);
double m20 = -siny;
double m21 = sinx * cosy;
double m22 = cosx * cosy;
double x = m00 * val.x + m01 * val.y + m02 * val.z;
double y = m10 * val.x + m11 * val.y + m12 * val.z;
double z = m20 * val.x + m21 * val.y + m22 * val.z;
val.set(x, y, z);
}
public Vector3d getPositionForAlignment(Vector3d alignment) {
Vector3d temp = new Vector3d(alignment);
synchronized (position) {
temp.sub(align);
temp.x *= size.x;
temp.y *= size.y;
temp.z *= size.z;
calculateEulerRotation(temp, orient);
temp.add(position);
}
return temp;
}
public Vector3d getOrientation() {
synchronized (position) {
return new Vector3d(orient);
}
}
public void setOrientation(Vector3d orientation) {
synchronized (position) {
orient.set(orientation);
needsRender = true;
}
}
public void setAngle(double theta) {
this.setOrientation(new Vector3d(0.0, 0.0, theta * Math.PI / 180.0));
}
/** Translates the object to a new position, the same distance from centerOfOrigin,
* but at angle theta radians
* counterclockwise
* @param centerOfOrigin
* @param Theta
*/
public void polarTranslationAroundPointByAngle( Vector3d centerOfOrigin, double Theta ) {
Vector3d centerOfEntityRotated = new Vector3d();
Vector3d centerOfEntity = this.getPositionForAlignment(new Vector3d());
centerOfEntityRotated.x = centerOfOrigin.x + Math.cos( Theta ) * ( centerOfEntity.x - centerOfOrigin.x ) - Math.sin( Theta ) * ( centerOfEntity.y - centerOfOrigin.y );
centerOfEntityRotated.y = centerOfOrigin.y + Math.cos( Theta ) * ( centerOfEntity.y - centerOfOrigin.y ) + Math.sin( Theta ) * ( centerOfEntity.x - centerOfOrigin.x );
centerOfEntityRotated.z = centerOfOrigin.z;
this.setPosition(centerOfEntityRotated);
this.setAlignment(new Vector3d());
}
/** Get the position of the DisplayEntity if it Rotates (counterclockwise) around the centerOfOrigin by
* Theta radians assuming the object centers at pos
*
* @param centerOfOrigin
* @param Theta
* @param pos
*/
public Vector3d getCoordinatesForRotationAroundPointByAngleForPosition( Vector3d centerOfOrigin, double Theta, Vector3d pos ) {
Vector3d centerOfEntityRotated = new Vector3d();
centerOfEntityRotated.x = centerOfOrigin.x + Math.cos( Theta ) * ( pos.x - centerOfOrigin.x ) - Math.sin( Theta ) * ( pos.y - centerOfOrigin.y );
centerOfEntityRotated.y = centerOfOrigin.y + Math.cos( Theta ) * ( pos.y - centerOfOrigin.y ) + Math.sin( Theta ) * ( pos.x - centerOfOrigin.x );
centerOfEntityRotated.z = centerOfOrigin.z;
return centerOfEntityRotated;
}
public Vector getDisplayTrack() {
return displayTrack;
}
public DoubleVector getDisplayTrackDistanceList() {
return displayTrackDistanceList;
}
public Vector getDisplayTrackOrientationList() {
return displayTrackOrientationList;
}
/**
* Method to set the display track of the entity
* @param track - the DisplayEntity's new track
*/
public void setDisplayTrack( Vector track ) {
displayTrack = track;
}
/**
* Method to set the display track distances of the entity
* @param distances - the DisplayEntity's new track distances
*/
public void setDisplayTrackDistanceList( DoubleVector distances ) {
displayTrackDistanceList = distances;
displayTrackTotalDistance = distances.sum();
}
/**
* Method to set the display track orientations of the entity
* @param distances - the DisplayEntity's new track orientations
*/
public void setDisplayTrackOrientationList( Vector orientations ) {
displayTrackOrientationList = orientations;
}
/**
* Method to set the display distance along track of the entity
* @param d - the DisplayEntity's new display distance along track
*/
public void setDisplayDistanceAlongTrack( double d ) {
// this.trace( "setDisplayDistanceAlongTrack( "+d+" )" );
displayDistanceAlongTrack = d;
}
/**
* Method to set the display distance along track of the entity
* @param d - the DisplayEntity's new display distance along track
*/
public void setDisplayTrackTotalDistance( double d ) {
// this.trace( "setDisplayTrackTotalDistance( "+d+" )" );
displayTrackTotalDistance = d;
}
/**
* Method to set the display speed of the entity
* @param s - the DisplayEntity's new display speed
*/
public void setDisplaySpeedAlongTrack( double s ) {
// If the display speed is the same, do nothing
if( s == displaySpeedAlongTrack ) {
return;
}
// Was the object previously moving?
if( displaySpeedAlongTrack > 0 ) {
// Determine the time since the last movement for the entity
double dt = getCurrentTime() - timeOfLastMovement;
// Update the displayDistanceAlongTrack
displayDistanceAlongTrack += ( displaySpeedAlongTrack * dt );
}
displaySpeedAlongTrack = s;
timeOfLastMovement = getCurrentTime();
if (s == 0.0)
animated = false;
else
animated = true;
}
/**
* Returns the display distance for the DisplayEntity
* @return double - display distance for the DisplayEntity
**/
public double getDisplayDistanceAlongTrack() {
return displayDistanceAlongTrack;
}
public double getDisplayTrackTotalDistance() {
return displayTrackTotalDistance;
}
public void setSize(Vector3d size) {
synchronized (position) {
this.size.set(size);
needsRender = true;
}
this.setScale(size.x, size.y, size.z);
}
public Vector3d getPosition() {
synchronized (position) {
return new Vector3d(position);
}
}
DisplayEntity getRelativeEntity() {
return relativeEntity.getValue();
}
private Vector3d getOffsetToRelativeEntity() {
Vector3d offset = new Vector3d();
DisplayEntity entity = this.getRelativeEntity();
if(entity != null && entity != this) {
offset.add( entity.getPosition() );
}
return offset;
}
/*
* Returns the center relative to the origin
*/
public Vector3d getAbsoluteCenter() {
Vector3d cent = this.getPositionForAlignment(new Vector3d());
cent.add(getOffsetToRelativeEntity());
return cent;
}
public Vector3d getAbsolutePositionForAlignment(Vector3d alignment) {
Vector3d extent = this.getSize();
alignment.x *= extent.x;
alignment.y *= extent.y;
alignment.z *= extent.z;
calculateEulerRotation(alignment, orient);
alignment.add(this.getAbsoluteCenter());
return alignment;
}
/**
* Returns the extent for the DisplayEntity
* @return Vector3d - width, height and depth of the bounds for the DisplayEntity
*/
public Vector3d getSize() {
synchronized (position) {
return new Vector3d(size);
}
}
public void setScale( double x, double y, double z ) {
synchronized (position) {
scale.set( x, y, z );
needsRender = true;
}
}
public Vector3d getScale() {
synchronized (position) {
return new Vector3d(scale);
}
}
public Vector3d getAlignment() {
synchronized (position) {
return new Vector3d(align);
}
}
public void setAlignment(Vector3d align) {
synchronized (position) {
this.align.set(align);
needsRender = true;
}
}
public void setPosition(Vector3d pos) {
synchronized (position) {
position.set(pos);
needsRender = true;
}
}
/**
* Accessor to return the branchGroup of the display entity.
* @return BranchGroup - the attachment point for the DisplayEntity's graphics
*/
public BranchGroup getBranchGroup() {
return branchGroup;
}
/**
Returns a vector of strings describing the DisplayEntity.
Override to add details
@return Vector - tab delimited strings describing the DisplayEntity
**/
public Vector getInfo() {
Vector info = super.getInfo();
if( getCurrentRegion() != null )
info.addElement( "Region" + "\t" + getCurrentRegion().getName() );
else
info.addElement( "Region\t<no region>" );
return info;
}
private void updateResizeBounds(double x, double y, double z) {
double radius = 0.10 * Math.min(x, y);
((Circle)rotateSizeBounds.getChild(0)).setCenterRadius(-x, 0.0, 0.0, radius);
((Circle)rotateSizeBounds.getChild(1)).setCenterRadius(-x/2, y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(2)).setCenterRadius(x/2, y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(3)).setCenterRadius(0.0, y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(4)).setCenterRadius( x/2, 0.0, 0.0, radius);
((Circle)rotateSizeBounds.getChild(5)).setCenterRadius(-x/2, 0.0, 0.0, radius);
((Circle)rotateSizeBounds.getChild(6)).setCenterRadius(-x/2, -y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(7)).setCenterRadius( x/2, -y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(8)).setCenterRadius(0.0, -y/2, 0.0, radius);
resizeLine.setCoordinate(1, new Point3d(-x, 0.0d, 0.0d));
((Cube)rotateSizeBounds.getChild(10)).setSize(x, y, z);
}
private void makeResizeBounds() {
rotateSizeBounds = new BranchGroup();
rotateSizeBounds.setCapability(BranchGroup.ALLOW_DETACH);
resizeLine = new LineArray(2, LineArray.COORDINATES);
resizeLine.setCapability(LineArray.ALLOW_COORDINATE_WRITE);
resizeLine.setCoordinate(0, new Point3d(0.0, 0.0, 0.0));
resizeLine.setCoordinate(1, new Point3d(1.0, 0.0, 0.0));
for (int i = 0; i < 9; i++) {
Circle temp = new Circle(0.0, 0.0, 0.0, 0.1, 36, Circle.SHAPE_FILLED);
temp.setColor(Shape.getColorWithName("darkgreen"));
rotateSizeBounds.addChild(temp);
}
rotateSizeBounds.addChild(new Shape3D(resizeLine, axisLineAppearance));
Cube boundsModel = new Cube(Cube.SHAPE_OUTLINE, "boundsModel");
boundsModel.setColor(Shape.getColorWithName("mint"));
rotateSizeBounds.addChild(boundsModel);
rotateSizeBounds.compile();
rootTransform.addChild(rotateSizeBounds);
}
public void setResizeBounds( boolean bool ) {
synchronized (position) {
showResize = bool;
needsRender = true;
}
}
/**
* Accessor method to obtain the display model for the DisplayEntity
* created: Feb 21, 2003 by JM
* To change the model for the DisplayEntity, obtain the refence to the model using this method
* then, add desired graphics to this Group.
* @return the BranchGroup for the DisplayEntity that the display model can be added to.
*/
public OrderedGroup getModel() {
return displayNode;
}
/**
* Adds a shape to the shapelist and to the DisplayEntity Java3D hierarchy.
* Takes into account the desired layer for the added shape.
*
* @param shape the shape to add.
*/
public void addShape( Shape shape ) {
synchronized (getModel()) {
// Make sure we don't get added twice, try to remove it first in case
getModel().removeChild(shape);
getModel().addChild(shape);
}
}
/**
* Adds a mouseNode at the given position
* Empty in DisplayEntity -- must be overloaded for entities which can have mouseNodes such as RouteSegment and Path
* @param posn
*/
public void addMouseNodeAt( Vector3d posn ) {
}
/**
* Remove a shape from the shapelist and the java3d model. Return if the
* shape is not on the list.
*
* @param shape the shape to be removed.
*/
public void removeShape( Shape shape ) {
synchronized (getModel()) {
getModel().removeChild(shape);
}
}
/** removes a components from the displayModel, clearing the graphics **/
public void clearModel() {
synchronized (position) {
// remove all of the submodels from the model
getModel().removeAllChildren();
if(displayModels.size() != 0){
DoubleVector distances;
distances = new DoubleVector(0);
if(levelOfDetail.getValue() != null){
distances = levelOfDetail.getValue();
}
// LOD is defined
if(distances.size() > 0){
Enumeration<?> children = rootTransform.getAllChildren();
while(children.hasMoreElements()){
Node child = (Node) children.nextElement();
if(child.getName() != null && child.getName().equalsIgnoreCase("lodTransformGroup")) {
rootTransform.removeChild(child);
for(DisplayModelBG each: displayModels){
each.removeAllChildren();
}
}
}
}
// One display model
else{
rootTransform.removeChild(displayModels.get(0));
displayModels.get(0).removeAllChildren();
}
displayModels.clear();
}
}
}
void addScaledBG(BranchGroup node) {
synchronized (scaleTransform) {
scaleTransform.addChild(node);
}
}
void removeScaledBG(BranchGroup node) {
synchronized (scaleTransform) {
scaleTransform.removeChild(node);
}
}
/**
* Allows overridding to add menu items for user menus
* @param menu - the Popup menu to add items to
* @param xLoc - the x location of the mouse when the mouse event occurred
* @param yLoc - the y location of the mouse when the mouse event occurred
**/
public void addMenuItems( JPopupMenu menu, final int xLoc, final int yLoc ) {
JMenuItem input = new JMenuItem("Input Editor");
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
EditBox.getInstance().setVisible(true);
EditBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(input);
JMenuItem prop = new JMenuItem("Property Viewer");
prop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
PropertyBox.getInstance().setVisible(true);
PropertyBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(prop);
JMenuItem output = new JMenuItem("Output Viewer");
output.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
InfoBox.getInstance().setVisible(true);
InfoBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(output);
if (!this.testFlag(Entity.FLAG_GENERATED)) {
JMenuItem copy = new JMenuItem( "Copy" );
copy.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
duplicate();
}
} );
// Only if this object is selected
if(OrbitBehavior.selectedEntity == this)
menu.add( copy );
}
JMenuItem delete = new JMenuItem( "Delete" );
delete.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
DisplayEntity.this.kill();
FrameBox.setSelectedEntity(null);
}
} );
// Only if this object is selected
if(OrbitBehavior.selectedEntity == this)
menu.add( delete );
JMenuItem displayModel = new JMenuItem( "Change Graphics" );
displayModel.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
// More than one DisplayModel(LOD) or No DisplayModel
if(displayModels.size() > 1 || displayModelList.getValue() == null)
return;
GraphicBox graphicBox = GraphicBox.getInstance( DisplayEntity.this, xLoc, yLoc );
graphicBox.setVisible( true );
}
} );
menu.add( displayModel );
JMenuItem addLabel = new JMenuItem( "Add Label" );
addLabel.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
DisplayEntity.this.addLabel();
}
} );
menu.add( addLabel );
}
public void readData_ForKeyword(StringVector data, String keyword, boolean syntaxOnly, boolean isCfgInput)
throws InputErrorException {
if ("ALIGNMENT".equalsIgnoreCase(keyword)) {
Vector3d temp = Input.parseVector3d(data);
this.setAlignment(temp);
return;
}
if ("SIZE".equalsIgnoreCase(keyword)) {
Vector3d val = Input.parseVector3d(data);
setSize(val);
return;
}
if( "ORIENTATION".equalsIgnoreCase( keyword ) ) {
Vector3d val = Input.parseVector3d(data);
this.setOrientation(val);
return;
}
if( "Label".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword Label no longer has any effect");
return;
}
if( "LABELBOTTOMLEFT".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword LABELBOTTOMLEFT no longer has any effect");
return;
}
if( "TextHeight".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword TextHeight no longer has any effect");
return;
}
if( "FontName".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontName no longer has any effect");
return;
}
if( "FontStyle".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontStyle no longer has any effect");
return;
}
if ("FontColour".equalsIgnoreCase(keyword) ||
"FontColor".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontColour no longer has any effect");
return;
}
if( "ANGLE".equalsIgnoreCase( keyword ) ) {
Input.assertCount(data, 1);
double temp = Input.parseDouble(data.get(0));
setAngle(temp);
return;
}
if( keyword.equalsIgnoreCase( "Region" ) ) {
Input.assertCount(data, 1);
this.setRegion(Input.parseEntity(data.get(0), Region.class));
return;
}
if( "MOUSENODESEXTENT".equalsIgnoreCase( keyword ) ) {
Vector3d vec = Input.parseVector3d(data, 0.0d, Double.POSITIVE_INFINITY);
this.setMouseNodesSize( vec.x );
return;
}
super.readData_ForKeyword( data, keyword, syntaxOnly, isCfgInput );
}
/**
* Return the orientation for the specified distance along the display track
*/
public Vector3d getDisplayTrackOrientationForDistance( double distance ) {
// If there is no orientation, return no orientation
if( displayTrackOrientationList.size() == 0 ) {
return ( new Vector3d( 0.0, 0.0, 0.0 ) );
}
// If there is only one orientation, return it
if( displayTrackOrientationList.size() == 1 ) {
return (Vector3d)displayTrackOrientationList.get( 0 );
}
distance = Math.max( distance, 0.0 );
distance = Math.min( distance, displayTrackTotalDistance );
// Determine the line for the position
double totalLength = 0.0;
for( int i = 0; i < displayTrackDistanceList.size(); i++ ) {
totalLength += displayTrackDistanceList.get( i );
if( distance <= totalLength ) {
return (Vector3d)displayTrackOrientationList.get( i );
}
}
throw new ErrorException( "Could not find orientation for obect " + this.getName() );
}
/**
* Return the screen coordinates for the specified distance along the display track
*/
public Vector3d getDisplayTrackCoordinatesForDistance( double distance ) {
double ratio;
Vector3d p1 = (Vector3d)displayTrack.get( 0 );
Vector3d p2 = (Vector3d)displayTrack.lastElement();
// Are the inputs valid for calculation?
//if( distance - displayTrackTotalDistance > 0.2 ) {
// throw new ErrorException( this.getName() + " Specified distance must be less than or equal to the track distance. " + distance + " / " + displayTrackTotalDistance );
//}
if( distance < -0.2 ) {
throw new ErrorException( " The specified distance must be positive. " );
}
// Find the ratio of the track length to the specified distance
if( displayTrackTotalDistance == 0.0 ) {
ratio = 1.0;
}
else {
distance = Math.max( distance, 0.0 );
distance = Math.min( distance, displayTrackTotalDistance );
ratio = (distance / displayTrackTotalDistance);
}
// Are there bends in the segment?
if( displayTrack.size() > 2 ) {
// Determine the line for the position and the fraction of the way through the line
double totalLength = 0.0;
double distanceInLine;
for( int i = 0; i < displayTrackDistanceList.size(); i++ ) {
distanceInLine = distance - totalLength;
totalLength += displayTrackDistanceList.get( i );
if( distance <= totalLength ) {
p1 = (Vector3d)displayTrack.get( i );
p2 = (Vector3d)displayTrack.get( i + 1 );
if( displayTrackDistanceList.get( i ) > 0 ) {
ratio = distanceInLine / displayTrackDistanceList.get( i );
}
else {
ratio = 0.0;
}
break;
}
}
}
// Calculate the resulting point
Vector3d vec = new Vector3d();
vec.sub(p2, p1);
vec.scale(ratio);
vec.add(p1);
return vec;
}
private void animate(double t) {
//this.trace( "updateMovementAtTime( " + t + " )" );
// Determine the display speed
double s = this.displaySpeedAlongTrack;
if( s == 0.0 ) {
return;
}
//this.trace( "Display Speed Along Track (SCREEN UNITS/h)= "+s );
// Determine the time since the last movement for the entity
double dt = t - timeOfLastMovement;
if( dt <= 0.0 ) {
return;
}
//this.trace( "Time of last movement = "+ this.getTimeOfLastMovement() );
//this.trace( "Time For this update (dt) = "+dt );
// Find the display distance moved since the last update
double distance = this.getDisplayDistanceAlongTrack() + ( dt * s );
//this.trace( "distance travelled during this update (SCREEN UNITS) = "+distance );
this.setDisplayDistanceAlongTrack( distance );
// Set the new location
Vector3d loc = this.getDisplayTrackCoordinatesForDistance( distance );
this.setPosition(loc);
this.setAlignment(new Vector3d());
timeOfLastMovement = t;
this.setOrientation(this.getDisplayTrackOrientationForDistance(distance));
}
/**
* Move the DisplayEntity to the given destination over the given time.
* If a non-empty path is specified, then the DisplayEntity will follow the path.
* Otherwise, it will follow a straight line to the destination.
*/
public void moveToPosition_FollowingVectors3d_DuringTime_WithChangingOrientation( Vector3d destination, Vector path, double t, boolean orientationChanges ) {
// Create a list of all the points to be followed
Vector pts = new Vector();
pts.addElement(this.getPosition());
pts.addAllLast( path );
pts.addElement( destination );
// Store the new track and track distances
Vector newDisplayTrack = new Vector( 1, 1 );
DoubleVector newDisplayTrackDistanceList = new DoubleVector( 1, 1 );
Vector newDisplayTrackOrientationList = new Vector( 1, 1 );
double dx, dy, dz;
Vector3d p1, p2;
Vector3d prevPt, nextPt;
// Add the present location to the display track
newDisplayTrack.addElement(this.getPosition());
for( int i = 0; i < (pts.size() - 1); i++ ) {
prevPt = (Vector3d)newDisplayTrack.get( i );
// Determine the offset to the next point
p1 = (Vector3d)pts.get( i );
p2 = (Vector3d)pts.get( i + 1 );
dx = p2.x - p1.x;
dy = p2.y - p1.y;
dz = p2.z - p1.z;
// Add the next point to the display track
nextPt = new Vector3d( prevPt.x + dx, prevPt.y + dy, prevPt.z + dz );
newDisplayTrack.addElement( nextPt );
// Add the next distance to the display track distances
Vector3d vec = new Vector3d();
vec.sub( nextPt, prevPt );
double distance = vec.length();
newDisplayTrackDistanceList.add(distance);
if( orientationChanges ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0.0, -1.0 * Math.atan2( dz, Math.hypot( dx, dy ) ), Math.atan2( dy, dx ) ) );
}
else {
newDisplayTrackOrientationList.addElement(this.getOrientation());
}
}
// Set the new track and distances
this.setDisplayTrack( newDisplayTrack );
this.setDisplayTrackDistanceList( newDisplayTrackDistanceList );
displayTrackTotalDistance = newDisplayTrackDistanceList.sum();
this.setDisplayTrackOrientationList( newDisplayTrackOrientationList );
// Set the distance along track
displayDistanceAlongTrack = 0.0;
// Set the display speed to the destination (in Java screen units per hour)
this.setDisplaySpeedAlongTrack( displayTrackTotalDistance / t );
// Give this event slightly higher priority in case the entity exits region after the wait.
// We want to resume this method first so that we can set the origin of the entity on its present region before it exits region.
scheduleWait( t, 4 );
this.setDisplaySpeedAlongTrack( 0.0 );
this.setPosition(destination);
}
/**
* Move the DisplayEntity to the given destination over the given time.
* If a non-empty path is specified, then the DisplayEntity will follow the path and the given orientations.
* Otherwise, it will follow a straight line to the destination.
*/
public void moveToPosition_FollowingVectors3d_DuringTime_WithOrientations( Vector3d destination, Vector path, double t, DoubleVector orientations ) {
// Create a list of all the points to be followed
Vector pts = new Vector();
pts.addElement( this.getPositionForAlignment(new Vector3d()) );
pts.addAllLast( path );
pts.addElement( destination );
// Store the new track and track distances
Vector newDisplayTrack = new Vector( 1, 1 );
DoubleVector newDisplayTrackDistanceList = new DoubleVector( 1, 1 );
Vector newDisplayTrackOrientationList = new Vector( 1, 1 );
double dx, dy;
Vector3d p1, p2;
Vector3d prevPt, nextPt;
// Add the present location to the display track
newDisplayTrack.addElement(this.getPositionForAlignment(new Vector3d()));
for( int i = 0; i < (pts.size() - 1); i++ ) {
prevPt = (Vector3d)newDisplayTrack.get( i );
// Determine the offset to the next point
p1 = (Vector3d)pts.get( i );
p2 = (Vector3d)pts.get( i + 1 );
dx = p2.x - p1.x;
dy = p2.y - p1.y;
// Add the next point to the display track
nextPt = new Vector3d( prevPt.x + dx, prevPt.y + dy, 0.0 );
newDisplayTrack.addElement( nextPt );
// Add the next distance to the display track distances
Vector3d vec = new Vector3d();
vec.sub( nextPt, prevPt );
double distance = vec.length();
newDisplayTrackDistanceList.add(distance);
if( i == 0 ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.get( 0 ) * Math.PI / 180.0 ) );
}
else {
if( i == pts.size() - 2 ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.lastElement() * Math.PI / 180.0 ) );
}
else {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.get( i-1 ) * Math.PI / 180.0 ) );
}
}
}
// Set the new track and distances
this.setDisplayTrack( newDisplayTrack );
this.setDisplayTrackDistanceList( newDisplayTrackDistanceList );
displayTrackTotalDistance = newDisplayTrackDistanceList.sum();
this.setDisplayTrackOrientationList( newDisplayTrackOrientationList );
// Set the distance along track
displayDistanceAlongTrack = 0.0;
// Set the display speed to the destination (in Java screen units per hour)
this.setDisplaySpeedAlongTrack( displayTrackTotalDistance / t );
// Give this event slightly higher priority in case the entity exits region after the wait.
// We want to resume this method first so that we can set the origin of the entity on its present region before it exits region.
scheduleWait( t, 4 );
this.setDisplaySpeedAlongTrack( 0.0 );
this.setPosition(destination);
this.setAlignment(new Vector3d());
}
public void updateGraphics() {}
public void initializeGraphics() {}
public void setupGraphics() {
// No DisplayModel
if(displayModelList.getValue() == null)
return;
clearModel();
synchronized (position) {
if(this.getDisplayModelList().getValue() != null){
for(DisplayModel each: this.getDisplayModelList().getValue()){
DisplayModelBG dm = each.getDisplayModel();
dm.setModelSize(size);
displayModels.add(dm);
}
}
DoubleVector distances;
distances = new DoubleVector(0);
if(this.getLevelOfDetail() != null){
distances = this.getLevelOfDetail();
}
// LOD is defined
if(distances.size() > 0){
Switch targetSwitch;
DistanceLOD dLOD;
float[] dists= new float[distances.size()];
for(int i = 0; i < distances.size(); i++){
dists[i] = (float)distances.get(i);
}
targetSwitch = new Switch();
targetSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
dLOD = new DistanceLOD(dists, new Point3f());
BranchGroup lodBranchGroup = new BranchGroup();
lodBranchGroup.setName("lodBranchGroup");
// TODO: The bounding box should be big enough to include the camera. Otherwise, the model could not be seen
BoundingSphere bounds = new BoundingSphere(new Point3d(0,0,0), Double.POSITIVE_INFINITY);
for(DisplayModelBG each: displayModels){
targetSwitch.addChild(each);
}
dLOD.addSwitch(targetSwitch);
dLOD.setSchedulingBounds(bounds);
lodBranchGroup.addChild(dLOD);
lodBranchGroup.addChild(targetSwitch);
rootTransform.addChild(lodBranchGroup);
}
// One display model
else if (displayModels.size() > 0){
rootTransform.addChild(displayModels.get(0));
}
}
// Moving DisplayEntity with label (i.e. Truck and Train) is creating new DisplayEntity for its label when
// enterRegion(). This causes the ConcurrentModificationException to the caller of this method if it
// iterates through DisplayModel.getAll(). This is the place for the DisplayEntity to enterRegion though
if(this.getClass() == DisplayEntity.class){
enterRegion();
}
}
public DisplayModel getDefaultDisplayModel(){
return DisplayModel.getDefaultDisplayModelForClass(this.getClass());
}
public EntityListInput<DisplayModel> getDisplayModelList() {
return displayModelList;
}
public DoubleVector getLevelOfDetail() {
return levelOfDetail.getValue();
}
/** Callback method so that the UI can inform a DisplayEntity it is about to be dragged by the user.<br>
* Called by the user interface to allow the DisplayEntity to setup properties or UI before it is moved
* in the user interface.
**/
public void preDrag() {}
/** Callback method so that the UI can inform a DisplayEntity that dragged by the user is complete.<br>
* Called by the user interface to allow the DisplayEntity to setup properties or UI after it has been moved
* in the user interface.
**/
public void postDrag() {}
public void dragged(Vector3d distance) {
Vector3d newPos = this.getPosition();
newPos.add(distance);
this.setPosition(newPos);
// update mouseNode positions
for( int i = 0; i < this.getMouseNodes().size(); i++ ) {
MouseNode node = this.getMouseNodes().get(i);
Vector3d nodePos = node.getPosition();
nodePos.add(distance);
node.setPosition(nodePos);
node.enterRegion( this.getCurrentRegion() );
}
// inform simulation and editBox of new positions
this.updateInputPosition();
}
/**
* Inform simulation and editBox of new positions.
* This method works for any DisplayEntity that uses the keyword "Center".
* Any DisplayEntity that does not use the keyword "Center" must overwrite this method.
*/
public void updateInputPosition() {
Vector3d vec = this.getPosition();
EditBox.processEntity_Keyword_Value(this, positionInput.getKeyword(), String.format( "%.3f %.3f %.3f %s", vec.x, vec.y, vec.z, positionInput.getUnits() ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
/**
* Inform simulation and editBox of new size.
* This method works for any DisplayEntity that sets size via the keyword "Extent".
* Any DisplayEntity that does not set size via the keyword "Extent" must overwrite this method.
*/
public void updateInputSize() {
Vector3d vec = this.getSize();
EditBox.processEntity_Keyword_Value(this, "Size", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
/**
* Inform simulation and editBox of new angle.
* This method works for any DisplayEntity that sets angle via the keyword "Orientation".
* Any DisplayEntity that does not set angle via the keyword "Orientation" must overwrite this method.
*/
public void updateInputOrientation() {
Vector3d vec = this.getOrientation();
EditBox.processEntity_Keyword_Value(this, "Orientation", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
public void updateInputAlignment() {
Vector3d vec = this.getAlignment();
EditBox.processEntity_Keyword_Value(this, "Alignment", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
public ArrayList<MouseNode> getMouseNodes() {
return mouseNodes;
}
public void killMouseNodes() {
for( int i = this.getMouseNodes().size() - 1; i >= 0; i-- ) {
MouseNode node = this.getMouseNodes().get( i );
this.getMouseNodes().remove( node );
node.kill();
}
}
public double getMouseNodesSize() {
return mouseNodesSize;
}
public void setMouseNodesSize( double size ) {
mouseNodesSize = size;
Vector3d nodeSize = new Vector3d(size, size, size);
for (MouseNode each : this.getMouseNodes()) {
each.setSize(nodeSize);
}
}
public void nodesOn() {
for (MouseNode each : mouseNodes) {
each.enterRegion(currentRegion);
}
}
public void nodesOff() {
for (MouseNode each : mouseNodes) {
each.exitRegion();
}
}
public boolean isActive() {
return active.getValue();
}
public boolean getShow() {
return show.getValue();
}
public boolean isMovable() {
return movable.getValue();
}
/**
* Method to return the name of the entity. Used when building Edit tree labels.
* @return the unique identifier of the entity, <region>/<entityName>, unless region == null or the default region
*/
public String toString() {
if(( currentRegion == simulation.getDefaultRegion() ) || (currentRegion == null) ) {
return getName();
}
else {
return (currentRegion.getName()+"/"+getName() );
}
}
public boolean showToolTip() {
return showToolTip.getValue();
}
public void validate()
throws InputErrorException {
super.validate();
Input.validateIndexedLists(displayModelList.getValue(), levelOfDetail.getValue(), "DisplayModel", "LevelOfDetail");
if(getRelativeEntity() == this) {
this.warning("validate()", "Relative Entities should not be defined in a circular loop", "");
}
// Set property from input
// Technically, this is not validation, but it should be done before earlyInit
this.setPosition( positionInput.getValue() );
}
}
| com/sandwell/JavaSimulation3D/DisplayEntity.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.sandwell.JavaSimulation3D;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.DoubleListInput;
import com.sandwell.JavaSimulation.DoubleVector;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityListInput;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.Simulation;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation.Vector;
import com.sandwell.JavaSimulation3D.util.Circle;
import com.sandwell.JavaSimulation3D.util.Cube;
import com.sandwell.JavaSimulation3D.util.Shape;
import javax.media.j3d.Node;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.media.j3d.Appearance;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.DistanceLOD;
import javax.media.j3d.LineArray;
import javax.media.j3d.OrderedGroup;
import javax.media.j3d.Shape3D;
import javax.media.j3d.Switch;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.vecmath.Point3d;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3d;
/**
* Encapsulates the methods and data needed to display a simulation object in the 3D environment.
* Extends the basic functionality of entity in order to have access to the basic system
* components like the eventManager.
*
* <h3>Visual Heirarchy</h3>
*
* GraphicsSimulation.rootLocale (Locale)<br>
* -stores regionBranchGroups in the Vector: regionModels<br>
* -this vector corrects the J3D memory leak when the visual universe has no viewers<br>
*<br>
* Region.branchGroup (BranchGroup from DisplayEntity)<br>
*<br>
* Region.rootTransform (TransformGroup from DisplayEntity)<br>
*<br>
* Region.scaleTransform (TransformGroup from DisplayEntity)<br>
*<br>
* DisplayEntity.branchGroup (BranchGroup)<br>
* ** allows detach, pick reporting<br>
* - provides the container to add and remove from a region<br>
* - the basis for selecting an object from the visual display<br>
*<br>
* DisplayEntity.rootTransform (TransformGroup)<br>
* ** allows writing and extending children, changing transforms<br>
* - provides the basis for local transformations of position and orientation<br>
* - host for visual utilities bounds, name and axis<br>
*<br>
* DisplayEntity.scaleTransform (TransformGroup)<br>
* ** allows changing transforms<br>
* - provides the basis for local transformation of scaling<br>
* - used to scale model, but not visual utilities like bounds and axis<br>
*<br>
* DisplayEntity.displayModel (BranchGroup)<br>
* ** allows detach, reading, writing, extending children<br>
* - provides the container for user models to be added to the visual universe<br>
* - capabilities to allow manipulation of the model's components<br>
*<br>
* Shape3D, BranchGroup, SharedGroup, Shape2D (Rectangle, Circle, Label, ...) (Node)<br>
* - model for the DisplayEntity comprised of components of Shape3Ds<br>
* - may be loaded from a geometry file<br>
*
*
*
* <h3>DisplayEntity Structure</h3>
*
* DisplayEntity is defined to be compatible with Audition DisplayPerformers, as such origin and extent
* are provided. Since the display of objects using Java3D is not bound to 2 dimensions nor a fixed
* range of pixels, some changes are required.<br>
*<br>
* - extent does not provides physical visual bounds of the DisplayEntity, rather it is a convenience used
* to determine where the logical dimensions of the object. It has no effect on visual display<br>
*<br>
* - origin represents the bottom left (in 2D space) of the DisplayEntity. It is calculate from the
* more fundamental center and is related by the extent value. Origin can still be used for positioning
* but rather center should be used for future compatibility.<br>
*<br>
* - center represents the position of the object in 3D space. This is the default positioning mechanism
* for DisplayEntities. Setting the origin will be translated into setting the center. The center represents
* the position on the Region of the local origin for the displayModel.<br>
*/
public class DisplayEntity extends Entity {
private static final ArrayList<DisplayEntity> allInstances;
// simulation properties
/** Graphic Simulation object this model is running under **/
protected static GraphicSimulation simulation;
// J3D graphics properties
private final BranchGroup branchGroup; // connects to the region
private final TransformGroup rootTransform; // provides universal transformations for the DisplayEntity's entire model
private final TransformGroup scaleTransform; // provides scaling for display models
private final OrderedGroup displayNode; // container for DisplayEntity's specific model
private boolean needsRender = true;
private final Vector3d position = new Vector3d();
private final Vector3d size = new Vector3d(1.0d, 1.0d, 1.0d);
private final Vector3d orient = new Vector3d();
private final Vector3d align = new Vector3d();
private final Vector3d scale = new Vector3d(1.0d, 1.0d, 1.0d);
private DoubleListInput levelOfDetail;
private final EntityListInput<DisplayModel> displayModelList; // DisplayModel from the input
protected final ArrayList<DisplayModelBG> displayModels; // DisplayModel which represents this DisplayEntity
private final EntityInput<DisplayEntity> relativeEntity;
private final BooleanInput show;
private final BooleanInput active;
private final BooleanInput movable;
private boolean animated = false;
// continuous motion properties
/** a Vector of Vector3d with coordinates for points along the track to be traversed */
protected Vector displayTrack;
/** the distance of the entity along the track in screen units */
protected double displayDistanceAlongTrack;
/** Distance in screen units of each portion in the track */
protected DoubleVector displayTrackDistanceList;
/** Angle in radians for each portion in the track */
protected Vector displayTrackOrientationList;
/** Total distance in screen units of the track */
protected double displayTrackTotalDistance;
/** the display speed of the entity in screen units per hour for continuous motion */
protected double displaySpeedAlongTrack;
/** the time at which the entity was last moved */
private double timeOfLastMovement;
// resize and rotate listener
private boolean showResize = false;
private BranchGroup rotateSizeBounds; // holds the extent outline
private LineArray resizeLine; // bounding box for the entity for picking
// setup a default appearance for the default displayModel
private static Appearance axisLineAppearance;
// vector of mouseNodes
private ArrayList<MouseNode> mouseNodes;
protected double mouseNodesSize;
protected BooleanInput showToolTip; // true => show the tooltip on the screen for the DisplayEntity
protected boolean graphicsSetup = false;
static {
axisLineAppearance = new Appearance();
axisLineAppearance.setLineAttributes( new javax.media.j3d.LineAttributes( 2, javax.media.j3d.LineAttributes.PATTERN_SOLID, false ) );
allInstances = new ArrayList<DisplayEntity>(100);
}
{
// Add editable keywords for size and position
addEditableKeyword( "Position", "", "0.000 0.000 0.000", false, "Graphics" );
addEditableKeyword( "Alignment", "", "0.000 0.000 0.000", false, "Graphics" );
addEditableKeyword( "Size", "", "1.000 1.000 1.000", false, "Graphics" );
addEditableKeyword( "Orientation", "", "0.000 0.000 0.000", false, "Graphics" );
addEditableKeyword( "Region", "", "ModelStage", false, "Graphics" );
showToolTip = new BooleanInput("ToolTip", "Graphics", true);
this.addInput(showToolTip, true);
addEditableKeyword( "MouseNodesExtent", " - ", " - ", false, "Graphics" );
relativeEntity = new EntityInput<DisplayEntity>(DisplayEntity.class, "RelativeEntity", "Graphics", null);
this.addInput(relativeEntity, true);
displayModelList = new EntityListInput<DisplayModel>( DisplayModel.class, "DisplayModel", "Graphics", null);
this.addInput(displayModelList, true);
displayModelList.setUnique(false);
levelOfDetail = new DoubleListInput("LevelOfDetail", "Graphics", null);
levelOfDetail.setValidRange( 0.0d, Double.POSITIVE_INFINITY );
this.addInput(levelOfDetail, true);
show = new BooleanInput("Show", "Graphics", true);
this.addInput(show, true);
active = new BooleanInput("Active", "Graphics", true);
this.addInput(active, true);
movable = new BooleanInput("Movable", "Graphics", true);
this.addInput(movable, true);
}
/**
* Constructor: initializing the DisplayEntity's graphics
*/
public DisplayEntity() {
super();
allInstances.add(this);
// Create a branchgroup and make it detachable.
branchGroup = new BranchGroup();
branchGroup.setCapability( BranchGroup.ALLOW_DETACH );
branchGroup.setCapability( BranchGroup.ENABLE_PICK_REPORTING );
// Hold a reference to the DisplayEntity in the topmost branchgroup to
// speed up picking lookups
branchGroup.setUserData(this);
// Initialize the root transform to be the identity
rootTransform = new TransformGroup();
rootTransform.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_EXTEND );
rootTransform.setCapability( TransformGroup.ALLOW_CHILDREN_READ );
branchGroup.addChild( rootTransform );
// Initialize the root transform to be the identity
scaleTransform = new TransformGroup();
scaleTransform.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
scaleTransform.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
scaleTransform.setCapability( TransformGroup.ALLOW_CHILDREN_EXTEND );
rootTransform.addChild( scaleTransform );
displayTrack = new Vector( 1, 1 );
displayDistanceAlongTrack = 0.0;
displayTrackDistanceList = new DoubleVector( 1, 1 );
displayTrackOrientationList = new Vector( 1, 1 ); // Vector of Vector3d
displayTrackTotalDistance = 0.0;
displaySpeedAlongTrack = 0.0;
timeOfLastMovement = 0.0;
// create a placeholder of the model
displayNode = new OrderedGroup();
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_WRITE );
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_EXTEND );
displayNode.setCapability( BranchGroup.ALLOW_CHILDREN_READ );
scaleTransform.addChild( displayNode );
mouseNodes = new ArrayList<MouseNode>();
setMouseNodesSize(0.050);
displayModels = new ArrayList<DisplayModelBG>();
DisplayModel dm = this.getDefaultDisplayModel();
if(dm != null) {
ArrayList<DisplayModel> defList = new ArrayList<DisplayModel>();
defList.add(dm);
displayModelList.setDefaultValue(defList);
}
}
public static ArrayList<? extends DisplayEntity> getAll() {
return allInstances;
}
/**
* Sets the Graphic Simulation object for the entity.
* @param newSimulation - states the new simulation the entity is controled by
*/
public static void setSimulation( GraphicSimulation newSimulation ) {
simulation = newSimulation;
}
/**
* Removes the entity from its current region and assigns a new region
* @param newRegion - the region the entity will be assigned to
*/
public void setRegion( Region newRegion ) {
exitRegion();
currentRegion = newRegion;
}
/**
* Visually adds the entity to its currently assigned region
*/
public void enterRegion() {
if( currentRegion != null ) {
currentRegion.addEntity( this );
}
else {
throw new RuntimeException( "Region not set" );
}
if (!this.getShow()) {
exitRegion();
}
}
/**
* Removes the entity from its current region and visually adds the entity to the specified region.
* @param newRegion - the region the entity will be assigned to
*/
public void enterRegion( Region newRegion ) {
setRegion( newRegion );
enterRegion();
}
/**
* Visually removes the entity from its region. The current region for the entity is maintained.
*/
public void exitRegion() {
if( currentRegion != null ) {
currentRegion.removeEntity( this );
}
}
private void duplicate() {
ObjectType type = ObjectType.getFor(this.getClass());
if(type == null)
return;
DisplayEntity copiedEntity = (DisplayEntity)type.getNewInstance();
// Unique name
int i = 1;
String name = String.format("Copy_of_%s", getInputName());
while (Simulation.getNamedEntity(name) != null) {
name = String.format("Copy%d_of_%s", i, getInputName());
i++;
}
copiedEntity.setInputName(name);
copiedEntity.setName(name);
// Match all the inputs
for(Input<?> each: getEditableInputs() ){
if(!each.getValueString().isEmpty())
EditBox.processEntity_Keyword_Value(copiedEntity, each.getKeyword(), each.getValueString());
}
Vector3d pos = copiedEntity.getPosition();
Vector3d offset = copiedEntity.getSize();
offset.scale(0.5);
offset.setZ(0);
pos.add(offset);
copiedEntity.setPosition(pos);
copiedEntity.initializeGraphics();
copiedEntity.enterRegion();
FrameBox.setSelectedEntity(copiedEntity);
}
private void addLabel() {
ObjectType type = ObjectType.getFor(TextLabel.class);
if(type == null)
return;
TextLabel label = (TextLabel)type.getNewInstance();
// Unique name
int i = 1;
String name = String.format("Label_for_%s", getInputName());
while (Simulation.getNamedEntity(name) != null) {
name = String.format("Label%d_of_%s", i, getInputName());
i++;
}
label.setName(name);
label.setInputName(name);
EditBox.processEntity_Keyword_Value(label, "RelativeEntity", this.getInputName() );
EditBox.processEntity_Keyword_Value(label, "Position", "1.0, -1.0, 0.0" );
EditBox.processEntity_Keyword_Value(label, "Region", currentRegion.getInputName() );
label.setText(this.getName());
label.initializeGraphics();
label.enterRegion();
FrameBox.setSelectedEntity(label);
}
/**
* Destroys the branchGroup hierarchy for the entity
*/
public void kill() {
super.kill();
for (MouseNode each : mouseNodes) {
each.kill();
}
allInstances.remove(this);
exitRegion();
if(OrbitBehavior.selectedEntity == this)
OrbitBehavior.selectedEntity = null;
currentRegion = null;
clearModel();
displayTrack = null;
displayDistanceAlongTrack = 0.0;
displayTrackDistanceList = null;
displayTrackOrientationList = null;
displayTrackTotalDistance = 0.0;
displaySpeedAlongTrack = 0.0;
}
public void render(double time) {
synchronized (position) {
if (animated)
this.animate(time);
if (!needsRender && relativeEntity.getValue() == null)
return;
Transform3D temp = new Transform3D();
temp.setEuler(orient);
Vector3d offset = new Vector3d(size.x * align.x, size.y * align.y, size.z * align.z);
temp.transform(offset);
offset.sub(position, offset);
offset.add(getOffsetToRelativeEntity());
temp.setTranslation(offset);
rootTransform.setTransform(temp);
temp.setIdentity();
temp.setScale(scale);
scaleTransform.setTransform(temp);
if( !graphicsSetup ) {
this.setupGraphics();
graphicsSetup = true;
}
if (showResize) {
if( mouseNodes.size() > 0 ) {
nodesOn();
}
else {
if (rotateSizeBounds == null)
makeResizeBounds();
updateResizeBounds(size.x, size.y, size.z);
}
}
else {
if( mouseNodes.size() > 0 ) {
nodesOff();
}
else {
if (rotateSizeBounds != null) {
rootTransform.removeChild(rotateSizeBounds);
rotateSizeBounds = null;
}
}
}
for (DisplayModelBG each : displayModels) {
each.setModelSize(size);
}
needsRender = false;
}
}
private void calculateEulerRotation(Vector3d val, Vector3d euler) {
double sinx = Math.sin(euler.x);
double siny = Math.sin(euler.y);
double sinz = Math.sin(euler.z);
double cosx = Math.cos(euler.x);
double cosy = Math.cos(euler.y);
double cosz = Math.cos(euler.z);
// Calculate a 3x3 rotation matrix
double m00 = cosy * cosz;
double m01 = -(cosx * sinz) + (sinx * siny * cosz);
double m02 = (sinx * sinz) + (cosx * siny * cosz);
double m10 = cosy * sinz;
double m11 = (cosx * cosz) + (sinx * siny * sinz);
double m12 = -(sinx * cosz) + (cosx * siny * sinz);
double m20 = -siny;
double m21 = sinx * cosy;
double m22 = cosx * cosy;
double x = m00 * val.x + m01 * val.y + m02 * val.z;
double y = m10 * val.x + m11 * val.y + m12 * val.z;
double z = m20 * val.x + m21 * val.y + m22 * val.z;
val.set(x, y, z);
}
public Vector3d getPositionForAlignment(Vector3d alignment) {
Vector3d temp = new Vector3d(alignment);
synchronized (position) {
temp.sub(align);
temp.x *= size.x;
temp.y *= size.y;
temp.z *= size.z;
calculateEulerRotation(temp, orient);
temp.add(position);
}
return temp;
}
public Vector3d getOrientation() {
synchronized (position) {
return new Vector3d(orient);
}
}
public void setOrientation(Vector3d orientation) {
synchronized (position) {
orient.set(orientation);
needsRender = true;
}
}
public void setAngle(double theta) {
this.setOrientation(new Vector3d(0.0, 0.0, theta * Math.PI / 180.0));
}
/** Translates the object to a new position, the same distance from centerOfOrigin,
* but at angle theta radians
* counterclockwise
* @param centerOfOrigin
* @param Theta
*/
public void polarTranslationAroundPointByAngle( Vector3d centerOfOrigin, double Theta ) {
Vector3d centerOfEntityRotated = new Vector3d();
Vector3d centerOfEntity = this.getPositionForAlignment(new Vector3d());
centerOfEntityRotated.x = centerOfOrigin.x + Math.cos( Theta ) * ( centerOfEntity.x - centerOfOrigin.x ) - Math.sin( Theta ) * ( centerOfEntity.y - centerOfOrigin.y );
centerOfEntityRotated.y = centerOfOrigin.y + Math.cos( Theta ) * ( centerOfEntity.y - centerOfOrigin.y ) + Math.sin( Theta ) * ( centerOfEntity.x - centerOfOrigin.x );
centerOfEntityRotated.z = centerOfOrigin.z;
this.setPosition(centerOfEntityRotated);
this.setAlignment(new Vector3d());
}
/** Get the position of the DisplayEntity if it Rotates (counterclockwise) around the centerOfOrigin by
* Theta radians assuming the object centers at pos
*
* @param centerOfOrigin
* @param Theta
* @param pos
*/
public Vector3d getCoordinatesForRotationAroundPointByAngleForPosition( Vector3d centerOfOrigin, double Theta, Vector3d pos ) {
Vector3d centerOfEntityRotated = new Vector3d();
centerOfEntityRotated.x = centerOfOrigin.x + Math.cos( Theta ) * ( pos.x - centerOfOrigin.x ) - Math.sin( Theta ) * ( pos.y - centerOfOrigin.y );
centerOfEntityRotated.y = centerOfOrigin.y + Math.cos( Theta ) * ( pos.y - centerOfOrigin.y ) + Math.sin( Theta ) * ( pos.x - centerOfOrigin.x );
centerOfEntityRotated.z = centerOfOrigin.z;
return centerOfEntityRotated;
}
public Vector getDisplayTrack() {
return displayTrack;
}
public DoubleVector getDisplayTrackDistanceList() {
return displayTrackDistanceList;
}
public Vector getDisplayTrackOrientationList() {
return displayTrackOrientationList;
}
/**
* Method to set the display track of the entity
* @param track - the DisplayEntity's new track
*/
public void setDisplayTrack( Vector track ) {
displayTrack = track;
}
/**
* Method to set the display track distances of the entity
* @param distances - the DisplayEntity's new track distances
*/
public void setDisplayTrackDistanceList( DoubleVector distances ) {
displayTrackDistanceList = distances;
displayTrackTotalDistance = distances.sum();
}
/**
* Method to set the display track orientations of the entity
* @param distances - the DisplayEntity's new track orientations
*/
public void setDisplayTrackOrientationList( Vector orientations ) {
displayTrackOrientationList = orientations;
}
/**
* Method to set the display distance along track of the entity
* @param d - the DisplayEntity's new display distance along track
*/
public void setDisplayDistanceAlongTrack( double d ) {
// this.trace( "setDisplayDistanceAlongTrack( "+d+" )" );
displayDistanceAlongTrack = d;
}
/**
* Method to set the display distance along track of the entity
* @param d - the DisplayEntity's new display distance along track
*/
public void setDisplayTrackTotalDistance( double d ) {
// this.trace( "setDisplayTrackTotalDistance( "+d+" )" );
displayTrackTotalDistance = d;
}
/**
* Method to set the display speed of the entity
* @param s - the DisplayEntity's new display speed
*/
public void setDisplaySpeedAlongTrack( double s ) {
// If the display speed is the same, do nothing
if( s == displaySpeedAlongTrack ) {
return;
}
// Was the object previously moving?
if( displaySpeedAlongTrack > 0 ) {
// Determine the time since the last movement for the entity
double dt = getCurrentTime() - timeOfLastMovement;
// Update the displayDistanceAlongTrack
displayDistanceAlongTrack += ( displaySpeedAlongTrack * dt );
}
displaySpeedAlongTrack = s;
timeOfLastMovement = getCurrentTime();
if (s == 0.0)
animated = false;
else
animated = true;
}
/**
* Returns the display distance for the DisplayEntity
* @return double - display distance for the DisplayEntity
**/
public double getDisplayDistanceAlongTrack() {
return displayDistanceAlongTrack;
}
public double getDisplayTrackTotalDistance() {
return displayTrackTotalDistance;
}
public void setSize(Vector3d size) {
synchronized (position) {
this.size.set(size);
needsRender = true;
}
this.setScale(size.x, size.y, size.z);
}
public Vector3d getPosition() {
synchronized (position) {
return new Vector3d(position);
}
}
DisplayEntity getRelativeEntity() {
return relativeEntity.getValue();
}
private Vector3d getOffsetToRelativeEntity() {
Vector3d offset = new Vector3d();
DisplayEntity entity = this.getRelativeEntity();
if(entity != null && entity != this) {
offset.add( entity.getPosition() );
}
return offset;
}
/*
* Returns the center relative to the origin
*/
public Vector3d getAbsoluteCenter() {
Vector3d cent = this.getPositionForAlignment(new Vector3d());
cent.add(getOffsetToRelativeEntity());
return cent;
}
public Vector3d getAbsolutePositionForAlignment(Vector3d alignment) {
Vector3d extent = this.getSize();
alignment.x *= extent.x;
alignment.y *= extent.y;
alignment.z *= extent.z;
calculateEulerRotation(alignment, orient);
alignment.add(this.getAbsoluteCenter());
return alignment;
}
/**
* Returns the extent for the DisplayEntity
* @return Vector3d - width, height and depth of the bounds for the DisplayEntity
*/
public Vector3d getSize() {
synchronized (position) {
return new Vector3d(size);
}
}
public void setScale( double x, double y, double z ) {
synchronized (position) {
scale.set( x, y, z );
needsRender = true;
}
}
public Vector3d getScale() {
synchronized (position) {
return new Vector3d(scale);
}
}
public Vector3d getAlignment() {
synchronized (position) {
return new Vector3d(align);
}
}
public void setAlignment(Vector3d align) {
synchronized (position) {
this.align.set(align);
needsRender = true;
}
}
public void setPosition(Vector3d pos) {
synchronized (position) {
position.set(pos);
needsRender = true;
}
}
/**
* Accessor to return the branchGroup of the display entity.
* @return BranchGroup - the attachment point for the DisplayEntity's graphics
*/
public BranchGroup getBranchGroup() {
return branchGroup;
}
/**
Returns a vector of strings describing the DisplayEntity.
Override to add details
@return Vector - tab delimited strings describing the DisplayEntity
**/
public Vector getInfo() {
Vector info = super.getInfo();
if( getCurrentRegion() != null )
info.addElement( "Region" + "\t" + getCurrentRegion().getName() );
else
info.addElement( "Region\t<no region>" );
return info;
}
private void updateResizeBounds(double x, double y, double z) {
double radius = 0.10 * Math.min(x, y);
((Circle)rotateSizeBounds.getChild(0)).setCenterRadius(-x, 0.0, 0.0, radius);
((Circle)rotateSizeBounds.getChild(1)).setCenterRadius(-x/2, y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(2)).setCenterRadius(x/2, y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(3)).setCenterRadius(0.0, y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(4)).setCenterRadius( x/2, 0.0, 0.0, radius);
((Circle)rotateSizeBounds.getChild(5)).setCenterRadius(-x/2, 0.0, 0.0, radius);
((Circle)rotateSizeBounds.getChild(6)).setCenterRadius(-x/2, -y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(7)).setCenterRadius( x/2, -y/2, 0.0, radius);
((Circle)rotateSizeBounds.getChild(8)).setCenterRadius(0.0, -y/2, 0.0, radius);
resizeLine.setCoordinate(1, new Point3d(-x, 0.0d, 0.0d));
((Cube)rotateSizeBounds.getChild(10)).setSize(x, y, z);
}
private void makeResizeBounds() {
rotateSizeBounds = new BranchGroup();
rotateSizeBounds.setCapability(BranchGroup.ALLOW_DETACH);
resizeLine = new LineArray(2, LineArray.COORDINATES);
resizeLine.setCapability(LineArray.ALLOW_COORDINATE_WRITE);
resizeLine.setCoordinate(0, new Point3d(0.0, 0.0, 0.0));
resizeLine.setCoordinate(1, new Point3d(1.0, 0.0, 0.0));
for (int i = 0; i < 9; i++) {
Circle temp = new Circle(0.0, 0.0, 0.0, 0.1, 36, Circle.SHAPE_FILLED);
temp.setColor(Shape.getColorWithName("darkgreen"));
rotateSizeBounds.addChild(temp);
}
rotateSizeBounds.addChild(new Shape3D(resizeLine, axisLineAppearance));
Cube boundsModel = new Cube(Cube.SHAPE_OUTLINE, "boundsModel");
boundsModel.setColor(Shape.getColorWithName("mint"));
rotateSizeBounds.addChild(boundsModel);
rotateSizeBounds.compile();
rootTransform.addChild(rotateSizeBounds);
}
public void setResizeBounds( boolean bool ) {
synchronized (position) {
showResize = bool;
needsRender = true;
}
}
/**
* Accessor method to obtain the display model for the DisplayEntity
* created: Feb 21, 2003 by JM
* To change the model for the DisplayEntity, obtain the refence to the model using this method
* then, add desired graphics to this Group.
* @return the BranchGroup for the DisplayEntity that the display model can be added to.
*/
public OrderedGroup getModel() {
return displayNode;
}
/**
* Adds a shape to the shapelist and to the DisplayEntity Java3D hierarchy.
* Takes into account the desired layer for the added shape.
*
* @param shape the shape to add.
*/
public void addShape( Shape shape ) {
synchronized (getModel()) {
// Make sure we don't get added twice, try to remove it first in case
getModel().removeChild(shape);
getModel().addChild(shape);
}
}
/**
* Adds a mouseNode at the given position
* Empty in DisplayEntity -- must be overloaded for entities which can have mouseNodes such as RouteSegment and Path
* @param posn
*/
public void addMouseNodeAt( Vector3d posn ) {
}
/**
* Remove a shape from the shapelist and the java3d model. Return if the
* shape is not on the list.
*
* @param shape the shape to be removed.
*/
public void removeShape( Shape shape ) {
synchronized (getModel()) {
getModel().removeChild(shape);
}
}
/** removes a components from the displayModel, clearing the graphics **/
public void clearModel() {
synchronized (position) {
// remove all of the submodels from the model
getModel().removeAllChildren();
if(displayModels.size() != 0){
DoubleVector distances;
distances = new DoubleVector(0);
if(levelOfDetail.getValue() != null){
distances = levelOfDetail.getValue();
}
// LOD is defined
if(distances.size() > 0){
Enumeration<?> children = rootTransform.getAllChildren();
while(children.hasMoreElements()){
Node child = (Node) children.nextElement();
if(child.getName() != null && child.getName().equalsIgnoreCase("lodTransformGroup")) {
rootTransform.removeChild(child);
for(DisplayModelBG each: displayModels){
each.removeAllChildren();
}
}
}
}
// One display model
else{
rootTransform.removeChild(displayModels.get(0));
displayModels.get(0).removeAllChildren();
}
displayModels.clear();
}
}
}
void addScaledBG(BranchGroup node) {
synchronized (scaleTransform) {
scaleTransform.addChild(node);
}
}
void removeScaledBG(BranchGroup node) {
synchronized (scaleTransform) {
scaleTransform.removeChild(node);
}
}
/**
* Allows overridding to add menu items for user menus
* @param menu - the Popup menu to add items to
* @param xLoc - the x location of the mouse when the mouse event occurred
* @param yLoc - the y location of the mouse when the mouse event occurred
**/
public void addMenuItems( JPopupMenu menu, final int xLoc, final int yLoc ) {
JMenuItem input = new JMenuItem("Input Editor");
input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
EditBox.getInstance().setVisible(true);
EditBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(input);
JMenuItem prop = new JMenuItem("Property Viewer");
prop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
PropertyBox.getInstance().setVisible(true);
PropertyBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(prop);
JMenuItem output = new JMenuItem("Output Viewer");
output.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
InfoBox.getInstance().setVisible(true);
InfoBox.getInstance().setExtendedState(JFrame.NORMAL);
FrameBox.setSelectedEntity(DisplayEntity.this);
}
});
menu.add(output);
if (!this.testFlag(Entity.FLAG_GENERATED)) {
JMenuItem copy = new JMenuItem( "Copy" );
copy.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
duplicate();
}
} );
// Only if this object is selected
if(OrbitBehavior.selectedEntity == this)
menu.add( copy );
}
JMenuItem delete = new JMenuItem( "Delete" );
delete.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
DisplayEntity.this.kill();
FrameBox.setSelectedEntity(null);
}
} );
// Only if this object is selected
if(OrbitBehavior.selectedEntity == this)
menu.add( delete );
JMenuItem displayModel = new JMenuItem( "Change Graphics" );
displayModel.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
// More than one DisplayModel(LOD) or No DisplayModel
if(displayModels.size() > 1 || displayModelList.getValue() == null)
return;
GraphicBox graphicBox = GraphicBox.getInstance( DisplayEntity.this, xLoc, yLoc );
graphicBox.setVisible( true );
}
} );
menu.add( displayModel );
JMenuItem addLabel = new JMenuItem( "Add Label" );
addLabel.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event ) {
DisplayEntity.this.addLabel();
}
} );
menu.add( addLabel );
}
public void readData_ForKeyword(StringVector data, String keyword, boolean syntaxOnly, boolean isCfgInput)
throws InputErrorException {
if ("POSITION".equalsIgnoreCase(keyword)) {
Vector3d temp = Input.parseVector3d(data);
this.setPosition(temp);
return;
}
if ("ALIGNMENT".equalsIgnoreCase(keyword)) {
Vector3d temp = Input.parseVector3d(data);
this.setAlignment(temp);
return;
}
if ("SIZE".equalsIgnoreCase(keyword)) {
Vector3d val = Input.parseVector3d(data);
setSize(val);
return;
}
if( "ORIENTATION".equalsIgnoreCase( keyword ) ) {
Vector3d val = Input.parseVector3d(data);
this.setOrientation(val);
return;
}
if( "Label".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword Label no longer has any effect");
return;
}
if( "LABELBOTTOMLEFT".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword LABELBOTTOMLEFT no longer has any effect");
return;
}
if( "TextHeight".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword TextHeight no longer has any effect");
return;
}
if( "FontName".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontName no longer has any effect");
return;
}
if( "FontStyle".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontStyle no longer has any effect");
return;
}
if ("FontColour".equalsIgnoreCase(keyword) ||
"FontColor".equalsIgnoreCase( keyword ) ) {
InputAgent.logWarning("The keyword FontColour no longer has any effect");
return;
}
if( "ANGLE".equalsIgnoreCase( keyword ) ) {
Input.assertCount(data, 1);
double temp = Input.parseDouble(data.get(0));
setAngle(temp);
return;
}
if( keyword.equalsIgnoreCase( "Region" ) ) {
Input.assertCount(data, 1);
this.setRegion(Input.parseEntity(data.get(0), Region.class));
return;
}
if( "MOUSENODESEXTENT".equalsIgnoreCase( keyword ) ) {
Vector3d vec = Input.parseVector3d(data, 0.0d, Double.POSITIVE_INFINITY);
this.setMouseNodesSize( vec.x );
return;
}
super.readData_ForKeyword( data, keyword, syntaxOnly, isCfgInput );
}
/**
* Return the orientation for the specified distance along the display track
*/
public Vector3d getDisplayTrackOrientationForDistance( double distance ) {
// If there is no orientation, return no orientation
if( displayTrackOrientationList.size() == 0 ) {
return ( new Vector3d( 0.0, 0.0, 0.0 ) );
}
// If there is only one orientation, return it
if( displayTrackOrientationList.size() == 1 ) {
return (Vector3d)displayTrackOrientationList.get( 0 );
}
distance = Math.max( distance, 0.0 );
distance = Math.min( distance, displayTrackTotalDistance );
// Determine the line for the position
double totalLength = 0.0;
for( int i = 0; i < displayTrackDistanceList.size(); i++ ) {
totalLength += displayTrackDistanceList.get( i );
if( distance <= totalLength ) {
return (Vector3d)displayTrackOrientationList.get( i );
}
}
throw new ErrorException( "Could not find orientation for obect " + this.getName() );
}
/**
* Return the screen coordinates for the specified distance along the display track
*/
public Vector3d getDisplayTrackCoordinatesForDistance( double distance ) {
double ratio;
Vector3d p1 = (Vector3d)displayTrack.get( 0 );
Vector3d p2 = (Vector3d)displayTrack.lastElement();
// Are the inputs valid for calculation?
//if( distance - displayTrackTotalDistance > 0.2 ) {
// throw new ErrorException( this.getName() + " Specified distance must be less than or equal to the track distance. " + distance + " / " + displayTrackTotalDistance );
//}
if( distance < -0.2 ) {
throw new ErrorException( " The specified distance must be positive. " );
}
// Find the ratio of the track length to the specified distance
if( displayTrackTotalDistance == 0.0 ) {
ratio = 1.0;
}
else {
distance = Math.max( distance, 0.0 );
distance = Math.min( distance, displayTrackTotalDistance );
ratio = (distance / displayTrackTotalDistance);
}
// Are there bends in the segment?
if( displayTrack.size() > 2 ) {
// Determine the line for the position and the fraction of the way through the line
double totalLength = 0.0;
double distanceInLine;
for( int i = 0; i < displayTrackDistanceList.size(); i++ ) {
distanceInLine = distance - totalLength;
totalLength += displayTrackDistanceList.get( i );
if( distance <= totalLength ) {
p1 = (Vector3d)displayTrack.get( i );
p2 = (Vector3d)displayTrack.get( i + 1 );
if( displayTrackDistanceList.get( i ) > 0 ) {
ratio = distanceInLine / displayTrackDistanceList.get( i );
}
else {
ratio = 0.0;
}
break;
}
}
}
// Calculate the resulting point
Vector3d vec = new Vector3d();
vec.sub(p2, p1);
vec.scale(ratio);
vec.add(p1);
return vec;
}
private void animate(double t) {
//this.trace( "updateMovementAtTime( " + t + " )" );
// Determine the display speed
double s = this.displaySpeedAlongTrack;
if( s == 0.0 ) {
return;
}
//this.trace( "Display Speed Along Track (SCREEN UNITS/h)= "+s );
// Determine the time since the last movement for the entity
double dt = t - timeOfLastMovement;
if( dt <= 0.0 ) {
return;
}
//this.trace( "Time of last movement = "+ this.getTimeOfLastMovement() );
//this.trace( "Time For this update (dt) = "+dt );
// Find the display distance moved since the last update
double distance = this.getDisplayDistanceAlongTrack() + ( dt * s );
//this.trace( "distance travelled during this update (SCREEN UNITS) = "+distance );
this.setDisplayDistanceAlongTrack( distance );
// Set the new location
Vector3d loc = this.getDisplayTrackCoordinatesForDistance( distance );
this.setPosition(loc);
this.setAlignment(new Vector3d());
timeOfLastMovement = t;
this.setOrientation(this.getDisplayTrackOrientationForDistance(distance));
}
/**
* Move the DisplayEntity to the given destination over the given time.
* If a non-empty path is specified, then the DisplayEntity will follow the path.
* Otherwise, it will follow a straight line to the destination.
*/
public void moveToPosition_FollowingVectors3d_DuringTime_WithChangingOrientation( Vector3d destination, Vector path, double t, boolean orientationChanges ) {
// Create a list of all the points to be followed
Vector pts = new Vector();
pts.addElement(this.getPosition());
pts.addAllLast( path );
pts.addElement( destination );
// Store the new track and track distances
Vector newDisplayTrack = new Vector( 1, 1 );
DoubleVector newDisplayTrackDistanceList = new DoubleVector( 1, 1 );
Vector newDisplayTrackOrientationList = new Vector( 1, 1 );
double dx, dy, dz;
Vector3d p1, p2;
Vector3d prevPt, nextPt;
// Add the present location to the display track
newDisplayTrack.addElement(this.getPosition());
for( int i = 0; i < (pts.size() - 1); i++ ) {
prevPt = (Vector3d)newDisplayTrack.get( i );
// Determine the offset to the next point
p1 = (Vector3d)pts.get( i );
p2 = (Vector3d)pts.get( i + 1 );
dx = p2.x - p1.x;
dy = p2.y - p1.y;
dz = p2.z - p1.z;
// Add the next point to the display track
nextPt = new Vector3d( prevPt.x + dx, prevPt.y + dy, prevPt.z + dz );
newDisplayTrack.addElement( nextPt );
// Add the next distance to the display track distances
Vector3d vec = new Vector3d();
vec.sub( nextPt, prevPt );
double distance = vec.length();
newDisplayTrackDistanceList.add(distance);
if( orientationChanges ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0.0, -1.0 * Math.atan2( dz, Math.hypot( dx, dy ) ), Math.atan2( dy, dx ) ) );
}
else {
newDisplayTrackOrientationList.addElement(this.getOrientation());
}
}
// Set the new track and distances
this.setDisplayTrack( newDisplayTrack );
this.setDisplayTrackDistanceList( newDisplayTrackDistanceList );
displayTrackTotalDistance = newDisplayTrackDistanceList.sum();
this.setDisplayTrackOrientationList( newDisplayTrackOrientationList );
// Set the distance along track
displayDistanceAlongTrack = 0.0;
// Set the display speed to the destination (in Java screen units per hour)
this.setDisplaySpeedAlongTrack( displayTrackTotalDistance / t );
// Give this event slightly higher priority in case the entity exits region after the wait.
// We want to resume this method first so that we can set the origin of the entity on its present region before it exits region.
scheduleWait( t, 4 );
this.setDisplaySpeedAlongTrack( 0.0 );
this.setPosition(destination);
}
/**
* Move the DisplayEntity to the given destination over the given time.
* If a non-empty path is specified, then the DisplayEntity will follow the path and the given orientations.
* Otherwise, it will follow a straight line to the destination.
*/
public void moveToPosition_FollowingVectors3d_DuringTime_WithOrientations( Vector3d destination, Vector path, double t, DoubleVector orientations ) {
// Create a list of all the points to be followed
Vector pts = new Vector();
pts.addElement( this.getPositionForAlignment(new Vector3d()) );
pts.addAllLast( path );
pts.addElement( destination );
// Store the new track and track distances
Vector newDisplayTrack = new Vector( 1, 1 );
DoubleVector newDisplayTrackDistanceList = new DoubleVector( 1, 1 );
Vector newDisplayTrackOrientationList = new Vector( 1, 1 );
double dx, dy;
Vector3d p1, p2;
Vector3d prevPt, nextPt;
// Add the present location to the display track
newDisplayTrack.addElement(this.getPositionForAlignment(new Vector3d()));
for( int i = 0; i < (pts.size() - 1); i++ ) {
prevPt = (Vector3d)newDisplayTrack.get( i );
// Determine the offset to the next point
p1 = (Vector3d)pts.get( i );
p2 = (Vector3d)pts.get( i + 1 );
dx = p2.x - p1.x;
dy = p2.y - p1.y;
// Add the next point to the display track
nextPt = new Vector3d( prevPt.x + dx, prevPt.y + dy, 0.0 );
newDisplayTrack.addElement( nextPt );
// Add the next distance to the display track distances
Vector3d vec = new Vector3d();
vec.sub( nextPt, prevPt );
double distance = vec.length();
newDisplayTrackDistanceList.add(distance);
if( i == 0 ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.get( 0 ) * Math.PI / 180.0 ) );
}
else {
if( i == pts.size() - 2 ) {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.lastElement() * Math.PI / 180.0 ) );
}
else {
newDisplayTrackOrientationList.addElement( new Vector3d( 0, 0, orientations.get( i-1 ) * Math.PI / 180.0 ) );
}
}
}
// Set the new track and distances
this.setDisplayTrack( newDisplayTrack );
this.setDisplayTrackDistanceList( newDisplayTrackDistanceList );
displayTrackTotalDistance = newDisplayTrackDistanceList.sum();
this.setDisplayTrackOrientationList( newDisplayTrackOrientationList );
// Set the distance along track
displayDistanceAlongTrack = 0.0;
// Set the display speed to the destination (in Java screen units per hour)
this.setDisplaySpeedAlongTrack( displayTrackTotalDistance / t );
// Give this event slightly higher priority in case the entity exits region after the wait.
// We want to resume this method first so that we can set the origin of the entity on its present region before it exits region.
scheduleWait( t, 4 );
this.setDisplaySpeedAlongTrack( 0.0 );
this.setPosition(destination);
this.setAlignment(new Vector3d());
}
public void updateGraphics() {}
public void initializeGraphics() {}
public void setupGraphics() {
// No DisplayModel
if(displayModelList.getValue() == null)
return;
clearModel();
synchronized (position) {
if(this.getDisplayModelList().getValue() != null){
for(DisplayModel each: this.getDisplayModelList().getValue()){
DisplayModelBG dm = each.getDisplayModel();
dm.setModelSize(size);
displayModels.add(dm);
}
}
DoubleVector distances;
distances = new DoubleVector(0);
if(this.getLevelOfDetail() != null){
distances = this.getLevelOfDetail();
}
// LOD is defined
if(distances.size() > 0){
Switch targetSwitch;
DistanceLOD dLOD;
float[] dists= new float[distances.size()];
for(int i = 0; i < distances.size(); i++){
dists[i] = (float)distances.get(i);
}
targetSwitch = new Switch();
targetSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE);
dLOD = new DistanceLOD(dists, new Point3f());
BranchGroup lodBranchGroup = new BranchGroup();
lodBranchGroup.setName("lodBranchGroup");
// TODO: The bounding box should be big enough to include the camera. Otherwise, the model could not be seen
BoundingSphere bounds = new BoundingSphere(new Point3d(0,0,0), Double.POSITIVE_INFINITY);
for(DisplayModelBG each: displayModels){
targetSwitch.addChild(each);
}
dLOD.addSwitch(targetSwitch);
dLOD.setSchedulingBounds(bounds);
lodBranchGroup.addChild(dLOD);
lodBranchGroup.addChild(targetSwitch);
rootTransform.addChild(lodBranchGroup);
}
// One display model
else if (displayModels.size() > 0){
rootTransform.addChild(displayModels.get(0));
}
}
// Moving DisplayEntity with label (i.e. Truck and Train) is creating new DisplayEntity for its label when
// enterRegion(). This causes the ConcurrentModificationException to the caller of this method if it
// iterates through DisplayModel.getAll(). This is the place for the DisplayEntity to enterRegion though
if(this.getClass() == DisplayEntity.class){
enterRegion();
}
}
public DisplayModel getDefaultDisplayModel(){
return DisplayModel.getDefaultDisplayModelForClass(this.getClass());
}
public EntityListInput<DisplayModel> getDisplayModelList() {
return displayModelList;
}
public DoubleVector getLevelOfDetail() {
return levelOfDetail.getValue();
}
/** Callback method so that the UI can inform a DisplayEntity it is about to be dragged by the user.<br>
* Called by the user interface to allow the DisplayEntity to setup properties or UI before it is moved
* in the user interface.
**/
public void preDrag() {}
/** Callback method so that the UI can inform a DisplayEntity that dragged by the user is complete.<br>
* Called by the user interface to allow the DisplayEntity to setup properties or UI after it has been moved
* in the user interface.
**/
public void postDrag() {}
public void dragged(Vector3d distance) {
Vector3d newPos = this.getPosition();
newPos.add(distance);
this.setPosition(newPos);
// update mouseNode positions
for( int i = 0; i < this.getMouseNodes().size(); i++ ) {
MouseNode node = this.getMouseNodes().get(i);
Vector3d nodePos = node.getPosition();
nodePos.add(distance);
node.setPosition(nodePos);
node.enterRegion( this.getCurrentRegion() );
}
// inform simulation and editBox of new positions
this.updateInputPosition();
}
/**
* Inform simulation and editBox of new positions.
* This method works for any DisplayEntity that uses the keyword "Center".
* Any DisplayEntity that does not use the keyword "Center" must overwrite this method.
*/
public void updateInputPosition() {
Vector3d vec = this.getPosition();
EditBox.processEntity_Keyword_Value(this, "Position", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
/**
* Inform simulation and editBox of new size.
* This method works for any DisplayEntity that sets size via the keyword "Extent".
* Any DisplayEntity that does not set size via the keyword "Extent" must overwrite this method.
*/
public void updateInputSize() {
Vector3d vec = this.getSize();
EditBox.processEntity_Keyword_Value(this, "Size", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
/**
* Inform simulation and editBox of new angle.
* This method works for any DisplayEntity that sets angle via the keyword "Orientation".
* Any DisplayEntity that does not set angle via the keyword "Orientation" must overwrite this method.
*/
public void updateInputOrientation() {
Vector3d vec = this.getOrientation();
EditBox.processEntity_Keyword_Value(this, "Orientation", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
public void updateInputAlignment() {
Vector3d vec = this.getAlignment();
EditBox.processEntity_Keyword_Value(this, "Alignment", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
InputAgent.addEditedEntity(this);
FrameBox.valueUpdate();
}
public ArrayList<MouseNode> getMouseNodes() {
return mouseNodes;
}
public void killMouseNodes() {
for( int i = this.getMouseNodes().size() - 1; i >= 0; i-- ) {
MouseNode node = this.getMouseNodes().get( i );
this.getMouseNodes().remove( node );
node.kill();
}
}
public double getMouseNodesSize() {
return mouseNodesSize;
}
public void setMouseNodesSize( double size ) {
mouseNodesSize = size;
Vector3d nodeSize = new Vector3d(size, size, size);
for (MouseNode each : this.getMouseNodes()) {
each.setSize(nodeSize);
}
}
public void nodesOn() {
for (MouseNode each : mouseNodes) {
each.enterRegion(currentRegion);
}
}
public void nodesOff() {
for (MouseNode each : mouseNodes) {
each.exitRegion();
}
}
public boolean isActive() {
return active.getValue();
}
public boolean getShow() {
return show.getValue();
}
public boolean isMovable() {
return movable.getValue();
}
/**
* Method to return the name of the entity. Used when building Edit tree labels.
* @return the unique identifier of the entity, <region>/<entityName>, unless region == null or the default region
*/
public String toString() {
if(( currentRegion == simulation.getDefaultRegion() ) || (currentRegion == null) ) {
return getName();
}
else {
return (currentRegion.getName()+"/"+getName() );
}
}
public boolean showToolTip() {
return showToolTip.getValue();
}
public void validate()
throws InputErrorException {
super.validate();
Input.validateIndexedLists(displayModelList.getValue(), levelOfDetail.getValue(), "DisplayModel", "LevelOfDetail");
if(getRelativeEntity() == this) {
this.warning("validate()", "Relative Entities should not be defined in a circular loop", "");
}
}
}
| JS3D: Converted DisplayEntity keyword Position to a Vector3dInput with units of m
For example, input may now be specified as:
Berth1 Position { -5.415 -40738.275 0.000 m }
Signed-off-by: Stephen Wong <[email protected]>
Signed-off-by: Harvey Harrison <[email protected]>
| com/sandwell/JavaSimulation3D/DisplayEntity.java | JS3D: Converted DisplayEntity keyword Position to a Vector3dInput with units of m | <ide><path>om/sandwell/JavaSimulation3D/DisplayEntity.java
<ide> import com.sandwell.JavaSimulation.Simulation;
<ide> import com.sandwell.JavaSimulation.StringVector;
<ide> import com.sandwell.JavaSimulation.Vector;
<add>import com.sandwell.JavaSimulation.Vector3dInput;
<ide> import com.sandwell.JavaSimulation3D.util.Circle;
<ide> import com.sandwell.JavaSimulation3D.util.Cube;
<ide> import com.sandwell.JavaSimulation3D.util.Shape;
<add>
<ide> import javax.media.j3d.Node;
<ide>
<ide> import java.awt.event.ActionEvent;
<ide> private final OrderedGroup displayNode; // container for DisplayEntity's specific model
<ide>
<ide> private boolean needsRender = true;
<add> private final Vector3dInput positionInput;
<add>
<ide> private final Vector3d position = new Vector3d();
<ide> private final Vector3d size = new Vector3d(1.0d, 1.0d, 1.0d);
<ide> private final Vector3d orient = new Vector3d();
<ide> }
<ide>
<ide> {
<del> // Add editable keywords for size and position
<del> addEditableKeyword( "Position", "", "0.000 0.000 0.000", false, "Graphics" );
<add> positionInput = new Vector3dInput("Position", "Graphics", new Vector3d());
<add> positionInput.setUnits("m");
<add> this.addInput(positionInput, true);
<add>
<ide> addEditableKeyword( "Alignment", "", "0.000 0.000 0.000", false, "Graphics" );
<ide> addEditableKeyword( "Size", "", "1.000 1.000 1.000", false, "Graphics" );
<ide> addEditableKeyword( "Orientation", "", "0.000 0.000 0.000", false, "Graphics" );
<ide>
<ide> public void readData_ForKeyword(StringVector data, String keyword, boolean syntaxOnly, boolean isCfgInput)
<ide> throws InputErrorException {
<del> if ("POSITION".equalsIgnoreCase(keyword)) {
<del> Vector3d temp = Input.parseVector3d(data);
<del> this.setPosition(temp);
<del> return;
<del> }
<ide> if ("ALIGNMENT".equalsIgnoreCase(keyword)) {
<ide> Vector3d temp = Input.parseVector3d(data);
<ide> this.setAlignment(temp);
<ide> */
<ide> public void updateInputPosition() {
<ide> Vector3d vec = this.getPosition();
<del> EditBox.processEntity_Keyword_Value(this, "Position", String.format( "%.3f %.3f %.3f", vec.x, vec.y, vec.z ));
<add> EditBox.processEntity_Keyword_Value(this, positionInput.getKeyword(), String.format( "%.3f %.3f %.3f %s", vec.x, vec.y, vec.z, positionInput.getUnits() ));
<ide> InputAgent.addEditedEntity(this);
<ide> FrameBox.valueUpdate();
<ide> }
<ide> if(getRelativeEntity() == this) {
<ide> this.warning("validate()", "Relative Entities should not be defined in a circular loop", "");
<ide> }
<add>
<add> // Set property from input
<add> // Technically, this is not validation, but it should be done before earlyInit
<add> this.setPosition( positionInput.getValue() );
<ide> }
<ide> } |
|
Java | bsd-3-clause | 6f3a6403a41f4af08b7ccc488fe2fc2d3e25262a | 0 | interdroid/smartsockets,kastur/interdroid-smartsockets,interdroid/smartsockets,kastur/interdroid-smartsockets,kastur/interdroid-smartsockets | package ibis.smartsockets.virtual;
import ibis.smartsockets.SmartSocketsProperties;
import ibis.smartsockets.direct.DirectSocket;
import ibis.smartsockets.direct.DirectSocketAddress;
import ibis.smartsockets.direct.DirectSocketFactory;
import ibis.smartsockets.discovery.Discovery;
import ibis.smartsockets.hub.Hub;
import ibis.smartsockets.hub.servicelink.ServiceLink;
import ibis.smartsockets.util.TypedProperties;
import ibis.smartsockets.virtual.modules.AbstractDirectModule;
import ibis.smartsockets.virtual.modules.AcceptHandler;
import ibis.smartsockets.virtual.modules.ConnectModule;
import ibis.smartsockets.virtual.modules.direct.Direct;
import ibis.smartsockets.util.ThreadPool;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.SocketTimeoutException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class implements a virtual socket factory.
*
* The VirtualSocketFactory is the public interface to the virtual connection
* layer of SmartSockets. It implements several types of connection setup using
* the direct connection layer (see {@link DirectSocketFactory}) and a
* {@link ServiceLink} to the {@link Hub}.
*<p>
* The different connection setup schemes are implemented in separate modules
* each extending the {@link ConnectModule} class.
*<p>
* Currently, 4 different connect modules are available:<br>
*<p>
* {@link Direct}: creates a direct connection to the target.<br>
* {@link Reverse}: reverses the connection setup.such that the target creates a
* direct connection to the source.<br>
* {@link Splice}: uses TCP splicing to create a direct connection to the
* target.<br>
* {@link Hubrouted}: create a virtual connection that routes all traffic
* through the hub overlay.<br>
*<p>
* To create a new connection, each module is tried in sequence until a
* connection is established, or until it is clear that a connection can not be
* established at all (e.g., because the destination port does not exist on the
* target machine). By default, the order<br>
*<p>
* Direct, Reverse, Splice, Routed
* <p>is used. This order prefers modules that produce a direct connection. This
* default order can be changed using the
* smartsockets.modules.order property. The order can also be
* adjusted on a per connection basis by providing this property to the
* createClientSocket method.
*
* @see ibis.smartsockets.virtual.modules
* @see DirectSocketFactory
* @see ServiceLink
* @see Hub
*
* @author Jason Maassen
* @version 1.0 Jan 30, 2006
* @since 1.0
*
*/
public final class VirtualSocketFactory {
/**
* An inner class the prints connection statistics at a regular interval.
*/
private static class StatisticsPrinter implements Runnable {
private int timeout;
private VirtualSocketFactory factory;
private String prefix;
StatisticsPrinter(final VirtualSocketFactory factory, final int timeout,
final String prefix) {
this.timeout = timeout;
this.factory = factory;
this.prefix = prefix;
}
public void run() {
int t = getTimeout();
while (t > 0) {
try {
synchronized (this) {
wait(t);
}
} catch (InterruptedException e) {
// ignore
}
t = getTimeout();
if (t > 0) {
try {
factory.printStatistics(prefix);
} catch (Exception e) {
logger.warn("Failed to print statistics", e);
}
}
}
}
private synchronized int getTimeout() {
return timeout;
}
public synchronized void adjustInterval(final int interval) {
timeout = interval;
notifyAll();
}
}
private static final Map<String, VirtualSocketFactory> factories =
new HashMap<String, VirtualSocketFactory>();
private static VirtualSocketFactory defaultFactory = null;
/** Generic logger for this class. */
protected static final Logger logger =
LoggerFactory.getLogger("ibis.smartsockets.virtual.misc");
/** Logger for connection related logging. */
protected static final Logger conlogger =
LoggerFactory.getLogger("ibis.smartsockets.virtual.connect");
private static final Logger statslogger = LoggerFactory
.getLogger("ibis.smartsockets.statistics");
private final DirectSocketFactory directSocketFactory;
private final ArrayList<ConnectModule> modules =
new ArrayList<ConnectModule>();
private ConnectModule direct;
private final TypedProperties properties;
private final int DEFAULT_BACKLOG;
private final int DEFAULT_TIMEOUT;
private final int DEFAULT_ACCEPT_TIMEOUT;
private final boolean DETAILED_EXCEPTIONS;
private final Random random;
private final HashMap<Integer, VirtualServerSocket> serverSockets =
new HashMap<Integer, VirtualServerSocket>();
private int nextPort = 3000;
private DirectSocketAddress myAddresses;
private DirectSocketAddress hubAddress;
private VirtualSocketAddress localVirtualAddress;
private String localVirtualAddressAsString;
private ServiceLink serviceLink;
private Hub hub;
private VirtualClusters clusters;
private boolean printStatistics = false;
private String statisticPrefix = null;
private StatisticsPrinter printer = null;
/**
* An innerclass that accepts incoming connections for a hub.
*
* Only used when hub delegation is active: a hub and VirtualSocketFactory
* are running in the same process and share one contact address. This is
* only used in special server processes (such as the Ibis Registry).
*/
private static class HubAcceptor implements AcceptHandler {
private final Hub hub;
private HubAcceptor(Hub hub) {
this.hub = hub;
}
public void accept(DirectSocket s, int targetPort, long time) {
hub.delegateAccept(s);
}
}
private VirtualSocketFactory(DirectSocketFactory df, TypedProperties p)
throws InitializationException {
directSocketFactory = df;
if (logger.isInfoEnabled()) {
logger.info("Creating VirtualSocketFactory");
}
random = new Random();
properties = p;
DETAILED_EXCEPTIONS = p.booleanProperty(
SmartSocketsProperties.DETAILED_EXCEPTIONS, false);
DEFAULT_BACKLOG = p.getIntProperty(SmartSocketsProperties.BACKLOG, 50);
DEFAULT_ACCEPT_TIMEOUT = p.getIntProperty(
SmartSocketsProperties.ACCEPT_TIMEOUT, 60000);
// NOTE: order is VERY important here!
try {
loadModules();
} catch (Exception e) {
logger.info("Failed to load modules!", e);
throw new InitializationException(e.getMessage(), e);
}
if (modules.size() == 0) {
logger.info("Failed to load any modules!");
throw new InitializationException("Failed to load any modules!");
}
// -- this depends on the modules being loaded
DEFAULT_TIMEOUT = determineDefaultTimeout(p);
startHub(p);
// We now create the service link. This may connect to the hub that we
// have just started.
String localCluster = p.getProperty(
SmartSocketsProperties.CLUSTER_MEMBER, null);
createServiceLink(localCluster);
// Once the servicelink is up and running, we can start the modules.
startModules();
if (modules.size() == 0) {
logger.info("Failed to start any modules!");
throw new InitializationException("Failed to load any modules!");
}
loadClusterDefinitions();
localVirtualAddress = new VirtualSocketAddress(myAddresses, 0,
hubAddress, clusters.localCluster());
localVirtualAddressAsString = localVirtualAddress.toString();
printStatistics =
p.booleanProperty(SmartSocketsProperties.STATISTICS_PRINT);
if (printStatistics) {
statisticPrefix = p.getProperty(
SmartSocketsProperties.STATISTICS_PREFIX, "SmartSockets");
int tmp = p.getIntProperty(
SmartSocketsProperties.STATISTICS_INTERVAL, 0);
if (tmp > 0) {
printer = new StatisticsPrinter(this, tmp * 1000,
statisticPrefix);
ThreadPool
.createNew(printer, "SmartSockets Statistics Printer");
}
}
}
private void startHub(TypedProperties p)
throws InitializationException {
if (p.booleanProperty(SmartSocketsProperties.START_HUB, false)) {
AbstractDirectModule d = null;
// Check if the hub should delegate it's accept call to the direct
// module. This way, only a single server port (and address) is
// needed to reach both this virtual socket factory and the hub.
boolean delegate = p.booleanProperty(
SmartSocketsProperties.HUB_DELEGATE, false);
if (delegate) {
logger.info("Factory delegating hub accepts to direct module!");
// We should now add an AcceptHandler to the direct module that
// intercepts incoming connections for the hub. Start by finding
// the direct module...
for (ConnectModule m : modules) {
if (m.module.equals("ConnectModule(Direct)")) {
d = (AbstractDirectModule) m;
break;
}
}
if (d == null) {
throw new InitializationException("Cannot start hub: "
+ "Failed to find direct module!");
}
// And add its address to the property set as the 'delegation'
// address. This is needed by the hub (since it needs to know
// its own address).
p.setProperty(SmartSocketsProperties.HUB_DELEGATE_ADDRESS, d
.getAddresses().toString());
}
// Now we create the hub
logger.info("Factory is starting hub");
try {
hub = new Hub(p);
logger.info("Hub running on: " + hub.getHubAddress());
} catch (IOException e) {
throw new InitializationException("Failed to start hub", e);
}
// Finally, if delegation is used, we install the accept handler
if (delegate) {
// Get the 'virtual port' that the hub pretends to be on.
int port = p.getIntProperty(
SmartSocketsProperties.HUB_VIRTUAL_PORT, 42);
d.installAcceptHandler(port, new HubAcceptor(hub));
}
}
}
private void loadClusterDefinitions() {
clusters = new VirtualClusters(this, properties, getModules());
}
private DirectSocketAddress discoverHub(String localCluster) {
DirectSocketAddress address = null;
if (logger.isInfoEnabled()) {
logger.info("Attempting to discover hub using UDP multicast...");
}
int port = properties
.getIntProperty(SmartSocketsProperties.DISCOVERY_PORT);
int time = properties
.getIntProperty(SmartSocketsProperties.DISCOVERY_TIMEOUT);
Discovery d = new Discovery(port, 0, time);
String message = "Any Proxies? ";
message += localCluster;
String result = d.broadcastWithReply(message);
if (result != null) {
try {
address = DirectSocketAddress.getByAddress(result);
if (logger.isInfoEnabled()) {
logger.info("Hub found at: " + address.toString());
}
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Got unknown reply to hub discovery!");
}
}
} else {
if (logger.isInfoEnabled()) {
logger.info("No hubs found.");
}
}
return address;
}
private void createServiceLink(String localCluster) {
List<DirectSocketAddress> hubs = new LinkedList<DirectSocketAddress>();
if (hub != null) {
hubs.add(hub.getHubAddress());
}
// Check if the hub address was passed as a property.
String[] tmp = properties
.getStringList(SmartSocketsProperties.HUB_ADDRESSES);
if (tmp != null && tmp.length > 0) {
for (String a : tmp) {
try {
hubs.add(DirectSocketAddress.getByAddress(a));
} catch (Exception e) {
logger.warn("Failed to understand hub address: "
+ Arrays.deepToString(tmp), e);
}
}
}
// If we don't have a hub address, we try to find one ourselves
if (hubs.size() == 0) {
boolean useDiscovery = properties.booleanProperty(
SmartSocketsProperties.DISCOVERY_ALLOWED, false);
boolean discoveryPreferred = properties.booleanProperty(
SmartSocketsProperties.DISCOVERY_PREFERRED, false);
DirectSocketAddress address = null;
if (useDiscovery && (discoveryPreferred || hub == null)) {
address = discoverHub(localCluster);
}
if (address != null) {
hubs.add(address);
}
}
// Still no address ? Give up...
if (hubs.size() == 0) {
// properties not set, so no central hub is available
logger.warn("ServiceLink not created: no hub address available!");
return;
}
// Sort addresses according to locality ?
boolean force = properties
.booleanProperty(SmartSocketsProperties.SL_FORCE);
try {
serviceLink = ServiceLink.getServiceLink(properties, hubs,
myAddresses);
hubAddress = serviceLink.getAddress();
} catch (Exception e) {
logger.warn("Failed to obtain service link to hub!", e);
if (force) {
// FIXME!!
logger.error("Permanent failure of servicelink! -- will exit");
System.exit(1);
}
return;
}
if (force) {
int retries = Math.max(1, properties
.getIntProperty(SmartSocketsProperties.SL_RETRIES));
boolean connected = false;
while (!connected && retries > 0) {
try {
serviceLink.waitConnected(properties
.getIntProperty(SmartSocketsProperties.SL_TIMEOUT));
connected = true;
} catch (Exception e) {
logger.warn("Failed to connect service link to hub "
+ hubAddress, e);
}
retries--;
}
if (!connected) {
// FIXME
logger.error("Permanent failure of servicelink! -- will exit");
System.exit(1);
}
} else {
try {
serviceLink.waitConnected(properties
.getIntProperty(SmartSocketsProperties.SL_TIMEOUT));
} catch (Exception e) {
logger.warn("Failed to connect service link to hub "
+ hubAddress, e);
return;
}
}
// Check if the users want us to register any properties with the hub.
String[] props = properties.getStringList(
"smartsockets.register.property", ",", null);
if (props != null && props.length > 0) {
try {
if (props.length == 1) {
serviceLink.registerProperty(props[0], "");
} else {
serviceLink.registerProperty(props[0], props[1]);
}
} catch (Exception e) {
if (props.length == 1) {
logger
.warn("Failed to register user property: "
+ props[0]);
} else {
logger.warn("Failed to register user property: " + props[0]
+ "=" + props[1]);
}
}
}
}
private ConnectModule instantiateModule(String name) {
if (logger.isInfoEnabled()) {
logger.info("Loading module: " + name);
}
String classname = properties.getProperty(
SmartSocketsProperties.MODULES_PREFIX + name, null);
if (classname == null) {
// The class implementing the module is not explicitly defined, so
// instead we use an 'educated guess' of the form:
//
// smartsockets.virtual.modules.<name>.<Name>
//
StringBuffer tmp = new StringBuffer();
tmp.append("ibis.smartsockets.virtual.modules.");
tmp.append(name.toLowerCase());
tmp.append(".");
tmp.append(Character.toUpperCase(name.charAt(0)));
tmp.append(name.substring(1));
classname = tmp.toString();
}
if (logger.isInfoEnabled()) {
logger.info(" class name: " + classname);
}
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class<?> c;
// Check if there is a context class loader
if (cl != null) {
c = cl.loadClass(classname);
} else {
c = Class.forName(classname);
}
// Check if the class we loaded is indeed a flavor of ConnectModule
if (!ConnectModule.class.isAssignableFrom(c)) {
logger.warn("Cannot load module " + classname + " since it is "
+ " not a subclass of ConnectModule!");
return null;
}
return (ConnectModule) c.newInstance();
} catch (Exception e) {
logger.info("Failed to load module " + classname, e);
}
return null;
}
private void loadModule(final String name) throws Exception {
ConnectModule m = instantiateModule(name);
m.init(this, name, properties, logger);
DirectSocketAddress tmp = m.getAddresses();
if (tmp != null) {
if (myAddresses == null) {
myAddresses = tmp;
} else {
myAddresses = DirectSocketAddress.merge(myAddresses, tmp);
}
}
modules.add(m);
}
private void loadModules() throws Exception {
// Get the list of modules that we should load. Note that we should
// always load the "direct" module, since it is needed to implement the
// others. Note that this doesn't neccesarily mean that the user wants
// to use it though...
String[] mods = properties.getStringList(
SmartSocketsProperties.MODULES_DEFINE, ",", new String[0]);
if (mods == null || mods.length == 0) {
// Should not happen!
throw new NoModulesDefinedException(
"No smartsockets modules defined!");
}
// Get the list of modules to skip. Note that the direct module cannot
// be skipped completely (it is needed to implement the others).
String[] skip = properties.getStringList(
SmartSocketsProperties.MODULES_SKIP, ",", null);
int count = mods.length;
// Remove all modules that should be skipped.
if (skip != null) {
for (int s = 0; s < skip.length; s++) {
for (int m = 0; m < mods.length; m++) {
if (skip[s].equals(mods[m])) {
if (logger.isInfoEnabled()) {
logger.info("Skipping module " + mods[m]);
}
mods[m] = null;
count--;
}
}
}
}
if (logger.isInfoEnabled()) {
String t = "";
for (int i = 0; i < mods.length; i++) {
if (mods[i] != null) {
t += mods[i] + " ";
}
}
logger.info("Loading " + count + " modules: " + t);
}
if (count == 0) {
throw new NoModulesDefinedException("No smartsockets modules "
+ "left after filtering!");
}
// We start by loading the direct module. This one is always needed to
// support the other modules, but not necessarily used by the client.
try {
direct = new Direct(directSocketFactory);
direct.init(this, "direct", properties, logger);
myAddresses = direct.getAddresses();
} catch (Exception e) {
logger.info("Failed to load direct module!", e);
throw e;
}
if (myAddresses == null) {
logger.info("Failed to retrieve my own address!");
throw new NoLocalAddressException(
"Failed to retrieve local address!");
}
for (int i = 0; i < mods.length; i++) {
if (mods[i] != null) {
if (mods[i].equals("direct")) {
modules.add(direct);
} else {
try {
loadModule(mods[i]);
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Failed to load module: " + mods[i], e);
}
mods[i] = null;
count--;
}
}
}
}
if (logger.isInfoEnabled()) {
logger.info(count + " modules loaded.");
}
if (count == 0) {
throw new NoModulesDefinedException("Failed to load any modules");
}
}
private int determineDefaultTimeout(TypedProperties p) {
int[] tmp = new int[modules.size()];
int totalTimeout = 0;
for (int i = 0; i < modules.size(); i++) {
// Get the module defined timeout
tmp[i] = modules.get(i).getDefaultTimeout();
totalTimeout += tmp[i];
}
int timeout = p.getIntProperty(SmartSocketsProperties.CONNECT_TIMEOUT,
-1);
if (timeout <= 0) {
// It's up to the modules to determine their own timeout
timeout = totalTimeout;
} else {
// A user-defined timeout should be distributed over the modules
for (int i = 0; i < modules.size(); i++) {
double t = (((double) tmp[i]) / totalTimeout) * timeout;
modules.get(i).setTimeout((int) t);
}
}
if (logger.isInfoEnabled()) {
logger.info("Total timeout set to: " + timeout);
for (ConnectModule m : modules) {
logger.info(" " + m.getName() + ": " + m.getTimeout());
}
}
return timeout;
}
/**
* Retrieve an array of the available connection modules.
* @return array of available connection modules.
*/
protected ConnectModule[] getModules() {
return modules.toArray(new ConnectModule[modules.size()]);
}
/**
* Retrieve an array of the available connection modules whose names are
* listed in names.
*
* @param names set of modules that may be returned.
* @return array of available connection modules whose name was included in
* names.
*/
protected ConnectModule[] getModules(String[] names) {
ArrayList<ConnectModule> tmp = new ArrayList<ConnectModule>();
for (int i = 0; i < names.length; i++) {
boolean found = false;
if (names[i] != null && !names[i].equals("none")) {
for (int j = 0; j < modules.size(); j++) {
ConnectModule m = modules.get(j);
if (m.getName().equals(names[i])) {
tmp.add(m);
found = true;
break;
}
}
if (!found) {
logger.warn("Module " + names[i] + " not found!");
}
}
}
return tmp.toArray(new ConnectModule[tmp.size()]);
}
private void startModules() {
ArrayList<ConnectModule> failed = new ArrayList<ConnectModule>();
if (serviceLink == null) {
// No servicelink, so remove all modules that depend on it....
for (ConnectModule c : modules) {
if (c.requiresServiceLink) {
failed.add(c);
}
}
for (ConnectModule c : failed) {
logger
.info("Module " + c.module
+ " removed (no serviceLink)!");
modules.remove(c);
}
failed.clear();
}
for (ConnectModule c : modules) {
try {
c.startModule(serviceLink);
} catch (Exception e) {
// Remove all modules that fail to start...
logger.warn("Module " + c.module
+ " did not accept serviceLink!", e);
failed.add(c);
}
}
for (ConnectModule c : failed) {
logger.warn("Module " + c.module
+ " removed (exception during setup)!");
modules.remove(c);
}
failed.clear();
}
/**
* Retrieve VirtualServerSocket that is bound to given port.
*
* @param port port for which to retrieve VirtualServerSocket.
* @return VirtualServerSocket bound to port, or null if port is not in use.
*/
public VirtualServerSocket getServerSocket(int port) {
synchronized (serverSockets) {
return serverSockets.get(port);
}
}
/**
* Retrieve the ConnectModule with a given name.
*
* @param name name of requested ConnectModule.
* @return ConnectModule bound to name, or null is this name is not in use.
*/
public ConnectModule findModule(String name) {
// Direct is special, since it may be loaded without being part of the
// modules array.
if (name.equals("direct")) {
return direct;
}
for (ConnectModule m : modules) {
if (m.module.equals(name)) {
return m;
}
}
return null;
}
/**
* Close a VirtualSocket and its related I/O Streams while ignoring
* exceptions.
*
* @param s VirtualSocket to close (may be null).
* @param out OutputStream to close (may be null).
* @param in InputStream to close (may be null).
*/
public static void close(VirtualSocket s, OutputStream out,
InputStream in) {
try {
if (out != null) {
out.close();
}
} catch (Throwable e) {
logger.info("Failed to close OutputStream", e);
}
try {
if (in != null) {
in.close();
}
} catch (Throwable e) {
logger.info("Failed to close InputStream", e);
}
try {
if (s != null) {
s.close();
}
} catch (Throwable e) {
logger.info("Failed to close Socket", e);
}
}
/**
* Close a VirtualSocket and its related SocketChannel while ignoring
* exceptions.
*
* @param s VirtualSocket to close (may be null).
* @param channel SocketChannel to close (may be null).
*/
public static void close(VirtualSocket s, SocketChannel channel) {
if (channel != null) {
try {
channel.close();
} catch (Exception e) {
logger.info("Failed to close SocketChannel", e);
}
}
if (s != null) {
try {
s.close();
} catch (Exception e) {
logger.info("Failed to close Socket", e);
}
}
}
/**
* This method implements a connect using a specific module.
*
* This method will return null when:
* <p>
* - runtime requirements do not match
* - the module throws a NonFatalIOException
* <p>
* When a connection is successfully established, we wait for a accept from
* the remote side. There are three possible outcomes:
* <p>
* - the connection is accepted in time
* - the connection is not accepted in time or the connection is lost
* - the remote side is overloaded and closes the connection
* <p>
* In the first case the newly created socket is returned and in the second
* case an exception is thrown. In the last case the connection will be
* retried using a backoff mechanism until 'timeleft' (the total timeout
* specified by the user) is spend. Each new try behaves exactly the same as
* the previous attempts.
*
* @param m ConnectModule to use in connection attempt.
* @param target Target VirtualServerSocket.
* @param timeout Timeout to use for this specific attempt.
* @param timeLeft Total timeout left.
* @param fillTimeout Should we retry until the timeout expires ?
* @param properties Properties to use in connection setup.
* @return a VirtualSocket if the connection setup succeeded, null
* otherwise.
* @throws IOException a non-transient error occured (i.e., target port does
* not exist).
* @throws NonFatalIOException a transient error occured (i.e., timeout).
*/
private VirtualSocket createClientSocket(ConnectModule m,
VirtualSocketAddress target, int timeout, int timeLeft,
boolean fillTimeout, Map<String, Object> properties)
throws IOException, NonFatalIOException {
int backoff = 1000;
if (!m.matchRuntimeRequirements(properties)) {
if (conlogger.isInfoEnabled()) {
conlogger.warn("Failed: module " + m.module
+ " may not be used to set " + "up connection to "
+ target);
}
m.connectNotAllowed();
return null;
}
if (conlogger.isDebugEnabled()) {
conlogger.debug("Using module " + m.module + " to set up "
+ "connection to " + target + " timeout = " + timeout
+ " timeleft = " + timeLeft);
}
// We now try to set up a connection. Normally we may not exceed the
// timeout, but when we succesfully create a connection we are allowed
// to extend this time to timeLeft (either to wait for an accept, or to
// retry after a TargetOverLoaded exception). Note that any exception
// other than ModuleNotSuitable or TargetOverloaded is passed to the
// user.
VirtualSocket vs = null;
int overloaded = 0;
long start = System.currentTimeMillis();
boolean lastAttempt = false;
while (true) {
long t = System.currentTimeMillis() - start;
// Check if we ran out of time. If so, the throw a target overloaded
// exception or a timeout exception depending on the value of the
// overloaded counter.
if (t >= timeLeft) {
if (conlogger.isDebugEnabled()) {
conlogger.debug("Timeout while using module " + m.module
+ " to set up " + "connection to " + target
+ " timeout = " + timeout + " timeleft = "
+ timeLeft + " t = " + t);
}
if (overloaded > 0) {
m.connectRejected(t);
throw new TargetOverloadedException("Failed to create "
+ "virtual connection to " + target + " within "
+ timeLeft + " ms. (Target overloaded "
+ overloaded + " times)");
} else {
m.connectFailed(t);
throw new SocketTimeoutException("Timeout while creating"
+ " connection to " + target);
}
}
try {
vs = m.connect(target, timeout, properties);
} catch (NonFatalIOException e) {
long end = System.currentTimeMillis();
// Just print and try the next module...
if (conlogger.isInfoEnabled()) {
conlogger.info("Module " + m.module + " failed to connect "
+ "to " + target + " after " + (end - start)
+ " ms.): " + e.getMessage());
}
m.connectFailed(end - start);
throw e;
// NOTE: The modules may also throw IOExceptions for
// non-transient errors (i.e., port not found). These are
// forwarded to the user.
}
t = System.currentTimeMillis() - start;
if (vs != null) {
// We now have a connection to the correct machine and must wait
// for an accept from the serversocket. Since we don't have to
// try any other modules, we are allowed to spend all of the
// time that is left. Therefore, we start by calculating a new
// timeout here, which is based on the left over time for the
// entire connect call, minus the time we have spend so far in
// this connect. This is the timeout we pass to 'waitForAccept'.
int newTimeout = (int) (timeLeft - t);
if (newTimeout <= 0) {
// Bit of a hack. If we run out of time at the last moment
// we allow some extra time to finish the connection setup.
// TODO: should we do this ?
newTimeout = 1000;
}
if (conlogger.isInfoEnabled()) {
conlogger.info(getVirtualAddressAsString() + ": Success "
+ m.module + " connected to " + target
+ " now waiting for accept (for max. " + newTimeout
+ " ms.)");
}
try {
vs.waitForAccept(newTimeout);
vs.setTcpNoDelay(false);
long end = System.currentTimeMillis();
if (conlogger.isInfoEnabled()) {
conlogger.info(getVirtualAddressAsString()
+ ": Success " + m.module + " connected to "
+ target + " (time = " + (end - start)
+ " ms.)");
}
m.connectSucces(end - start);
return vs;
} catch (TargetOverloadedException e) {
// This is always allowed.
if (conlogger.isDebugEnabled()) {
conlogger.debug("Connection failed, target " + target
+ " overloaded (" + overloaded
+ ") while using " + " module " + m.module);
}
overloaded++;
} catch (IOException e) {
if (conlogger.isDebugEnabled()) {
conlogger.debug("Connection failed, target " + target
+ ", got exception (" + e.getMessage()
+ ") while using " + " module " + m.module);
}
if (!fillTimeout) {
m.connectFailed(System.currentTimeMillis() - start);
// We'll only retry if 'fillTimeout' is true
throw e;
}
}
// The target has refused our connection. Since we have
// obviously found a working module, we will not return.
// Instead we will retry using a backoff algorithm until
// we run out of time...
t = System.currentTimeMillis() - start;
m.connectRejected(t);
int leftover = (int) (timeLeft - t);
if (!lastAttempt && leftover > 0) {
int sleeptime = 0;
if (backoff < leftover) {
// Use a randomized sleep value to ensure the attempts
// are distributed.
sleeptime = random.nextInt(backoff);
} else {
sleeptime = leftover;
lastAttempt = true;
}
// System.err.println("Backoff = " + backoff +
// " Leftover = " + leftover + " Sleep time = " +
// sleeptime);
if (sleeptime > 0) {
try {
Thread.sleep(sleeptime);
} catch (Exception x) {
// ignored
}
}
if (leftover < 500) {
// We're done!
timeLeft = 0;
} else {
backoff *= 2;
}
} else {
// We're done
timeLeft = 0;
}
}
}
}
private String[] getNames(ConnectModule[] modules) {
String[] names = new String[modules.length];
for (int n = 0; n < modules.length; n++) {
names[n] = modules[n].getName();
}
return names;
}
/**
* This method loops over and array of connection modules, trying to setup
* a connection with each of them each in turn.
* <p>
* This method returns when:<br>
* - a connection is established<b>
* - a non-transient error occurs (i.e. remote port not found)<b>
* - all modules have failed<b>
* - a timeout occurred<b>
*
* @param target Target VirtualServerSocket.
* @param order ConnectModules in the order in which they should be tried.
* @param timeouts Timeouts for each of the modules.
* @param totalTimeout Total timeout for the connection setup.
* @param timing Array in which to record the time required by each module.
* @param fillTimeout Should we retry until the timeout expires ?
* @param properties Properties to use in connection setup.
* @return a VirtualSocket if the connection setup succeeded, null
* otherwise.
* @throws IOException a non-transient error occurred (i.e., target port
* does not exist on receiver).
* @throws NoSuitableModuleException No module could create the connection.
*/
private VirtualSocket createClientSocket(VirtualSocketAddress target,
ConnectModule[] order, int[] timeouts, int totalTimeout,
long[] timing, boolean fillTimeout, Map<String, Object> prop)
throws IOException, NoSuitableModuleException {
Throwable[] exceptions = new Throwable[order.length];
try {
int timeLeft = totalTimeout;
VirtualSocket vs = null;
// Now try the remaining modules (or all of them if we weren't
// using the cache in the first place...)
for (int i = 0; i < order.length; i++) {
ConnectModule m = order[i];
int timeout = (timeouts != null ? timeouts[i] : m.getTimeout());
long start = System.currentTimeMillis();
/*
* if (timing != null) { timing[1 + i] = System.nanoTime();
*
* if (i > 0) { prop.put("direct.detailed.timing.ignore", null);
* } }
*/
try {
vs = createClientSocket(m, target, timeout, timeLeft,
fillTimeout, prop);
} catch (NonFatalIOException e) {
// Store the exeception and continue with the next module
exceptions[i] = e;
}
/*
* if (timing != null) { timing[1 + i] = System.nanoTime() -
* timing[1 + i]; }
*/
if (vs != null) {
if (i > 0) {
// We managed to connect, but not with the first module,
// so we remember this to speed up later connections.
clusters.succes(target, m);
}
return vs;
}
if (order.length > 1 && i < order.length - 1) {
timeLeft -= System.currentTimeMillis() - start;
if (timeLeft <= 0) {
// NOTE: This can only happen when a module breaks
// the rules (defensive programming).
throw new NoSuitableModuleException("Timeout during "
+ " connect to " + target, getNames(order),
exceptions);
}
}
}
if (logger.isInfoEnabled()) {
logger.info("No suitable module found to connect to " + target);
}
// No suitable modules found...
throw new NoSuitableModuleException("No suitable module found to"
+ " connect to " + target + " (timeouts="
+ Arrays.toString(timeouts) + ", fillTimeout="
+ fillTimeout + ")", getNames(order), exceptions);
} finally {
if (timing != null && prop != null) {
timing[0] = System.nanoTime() - timing[0];
prop.remove("direct.detailed.timing.ignore");
}
}
}
// Distribute a given timeout over a number of modules, taking the relative
// sizes of the default module timeouts into account.
private int[] distributesTimeout(int timeout, int[] timeouts,
ConnectModule[] modules) {
if (timeouts == null) {
timeouts = new int[modules.length];
}
for (int i = 0; i < modules.length; i++) {
double t = (((double) modules[i].getTimeout()) / DEFAULT_TIMEOUT);
timeouts[i] = (int) (t * timeout);
}
return timeouts;
}
/**
* Create a connection to the VirtualServerSocket at target.
*
* This method will attempt to setup a connection to the VirtualServerSocket
* at target within the given timeout. Using the prop parameter, properties
* can be specified that modify the connection setup behavior.
*
* @param target Address of target VirtualServerSocket.
* @param timeout The maximum timeout for the connection setup in
* milliseconds. When the timeout is zero the call may block indefinitely,
* while a negative timeout will revert to the default value.
* @param prop Properties that modify the connection setup behavior (may be
* null).
* @return a VirtualSocket when the connection setup was successful.
* @throws IOException when the connection setup failed.
*/
public VirtualSocket createClientSocket(VirtualSocketAddress target,
int timeout, Map<String, Object> prop) throws IOException {
return createClientSocket(target, timeout, false, prop);
}
/**
* Create a connection to the VirtualServerSocket at target.
*
* This method will attempt to setup a connection to the VirtualServerSocket
* at target within the given timeout. Using the prop parameter, properties
* can be specified that modify the connection setup behavior.
*
* @param target Address of target VirtualServerSocket.
* @param timeout The maximum timeout for the connection setup in
* milliseconds. When the timeout is zero the call may block indefinitely,
* while a negative timeout will revert to the default value.
* @param fillTimeout Should we retry until the timeout expires ?
* @param prop Properties that modify the connection setup behavior (may be
* null).
* @return a VirtualSocket when the connection setup was successful.
* @throws IOException when the connection setup failed.
*/
public VirtualSocket createClientSocket(VirtualSocketAddress target,
int timeout, boolean fillTimeout, Map<String, Object> prop)
throws IOException {
// Note: it's up to the user to ensure that this thing is large enough!
// i.e., it should be of size 1+modules.length
if (conlogger.isDebugEnabled()) {
conlogger.debug("createClientSocket(" + target + ", " + timeout
+ ", " + fillTimeout + ", " + prop + ")");
}
/*
* long [] timing = null;
*
* if (prop != null) { // Note: it's up to the user to ensure that this
* thing is large // enough! i.e., it should be of size 1+modules.length
* timing = (long[]) prop.get("virtual.detailed.timing");
*
* if (timing != null) { timing[0] = System.nanoTime(); } }
*/
// Check the timeout here. If it is not set, we will use the default
if (timeout <= 0) {
timeout = DEFAULT_TIMEOUT;
}
ConnectModule[] order = clusters.getOrder(target);
int timeLeft = timeout;
int[] timeouts = null;
boolean lastAttempt = false;
int backoff = 250;
NoSuitableModuleException exception = null;
LinkedList<NoSuitableModuleException> exceptions = null;
if (DETAILED_EXCEPTIONS) {
exceptions = new LinkedList<NoSuitableModuleException>();
}
do {
if (timeLeft <= DEFAULT_TIMEOUT) {
// determine timeout for each module. We assume that this time
// is used completely and therefore only do this once.
timeouts = distributesTimeout(timeLeft, timeouts, order);
fillTimeout = false;
}
long start = System.currentTimeMillis();
try {
return createClientSocket(target, order, timeouts, timeLeft,
/* timing */null, fillTimeout, prop);
} catch (NoSuitableModuleException e) {
// All modules where tried and failed. It now depends on the
// user if he would like to try another round or give up.
if (conlogger.isDebugEnabled()) {
conlogger.debug("createClientSocket failed. Will "
+ (fillTimeout ? "" : "NOT ") + "retry");
}
if (DETAILED_EXCEPTIONS) {
exceptions.add(e);
} else {
exception = e;
}
}
timeLeft -= System.currentTimeMillis() - start;
if (!lastAttempt && fillTimeout && timeLeft > 0) {
int sleeptime = 0;
if (backoff < timeLeft) {
sleeptime = random.nextInt(backoff);
} else {
sleeptime = timeLeft;
lastAttempt = true;
}
if (sleeptime >= timeLeft) {
// In the last attempt we sleep half a second shorter.
// This allows us to attempt a connection setup.
if (sleeptime > 500) {
sleeptime -= 500;
} else {
// We're done!
sleeptime = 0;
fillTimeout = false;
}
}
if (sleeptime > 0) {
try {
Thread.sleep(sleeptime);
} catch (Exception x) {
// ignored
}
}
backoff *= 2;
} else {
fillTimeout = false;
}
} while (fillTimeout);
if (DETAILED_EXCEPTIONS) {
throw new NoSuitableModuleException("No suitable module found to "
+ "connect to " + target + "(timeout=" + timeout
+ ", fillTimeout=" + fillTimeout + ")", exceptions);
} else {
throw exception;
}
}
private int getPort() {
// TODO: should this be random ?
synchronized (serverSockets) {
while (true) {
if (!serverSockets.containsKey(nextPort)) {
return nextPort++;
} else {
nextPort++;
}
}
}
}
/**
* Create a new VirtualServerSocket bound the the given port.
*
* This method will create a new VirtualServerSocket bound the the given,
* and using the specified backlog. If port is zero or negative, a valid
* unused port number will be generated. If the backlog is zero or negative,
* the default value will be used.
* <p>
* The properties parameter used to modify the connection setup behavior of
* the new VirtualServerSocket.
*
* @param port The port number to use.
* @param backlog The maximum number of pending connections this
* VirtualServerSocket will allow.
* @param retry Retry if the VirtualServerSocket creation fails.
* @param properties Properties that modify the connection setup behavior
* (may be null).
* @return the new VirtualServerSocket, or null if the creation failed.
*/
public VirtualServerSocket createServerSocket(int port, int backlog,
boolean retry, java.util.Properties properties) {
// Fix: extract all string properties, don't use the properties object
// as a map! --Ceriel
HashMap<String, Object> props = new HashMap<String, Object>();
if (properties != null) {
// Fix: stringPropertyNames method isn't available on android, so
// added a cast --Roelof
// for (String s : properties.stringPropertyNames()) {
for (Object string : properties.keySet()) {
props.put((String) string, properties
.getProperty((String) string));
}
}
VirtualServerSocket result = null;
while (result == null) {
try {
// Did not pass on properties. Fixed. --Ceriel
// result = createServerSocket(port, backlog, null);
result = createServerSocket(port, backlog, props);
} catch (Exception e) {
// retry
if (logger.isDebugEnabled()) {
logger.debug("Failed to open serversocket on port " + port
+ " (will retry): ", e);
}
}
}
return result;
}
/**
* Create a new unbound VirtualServerSocket.
*
* This method will create a new VirtualServerSocket that is not yet bound
* to a port.
* <p>
* The properties parameter used to modify the connection setup behavior of
* the new VirtualServerSocket.
*
* @param props Properties that modify the connection setup behavior
* (may be null).
* @return the new VirtualServerSocket.
* @throws IOException the VirtualServerSocket creation has failed.
*/
public VirtualServerSocket createServerSocket(Map<String, Object> props)
throws IOException {
return new VirtualServerSocket(this, DEFAULT_ACCEPT_TIMEOUT, props);
}
/**
* Bind an unbound VirtualServerSocket to a port.
*
* @param vss The VirtualServerSocket to bind to the port.
* @param port The port to bind the VirtualServerSocket to.
* @throws BindException Failed to bind the port to the VirtualServerSocket.
*/
protected void bindServerSocket(VirtualServerSocket vss, int port)
throws BindException {
synchronized (serverSockets) {
if (serverSockets.containsKey(port)) {
throw new BindException("Port " + port + " already in use!");
}
serverSockets.put(port, vss);
}
}
/**
* Create a new VirtualServerSocket bound the the given port.
*
* This method will create a new VirtualServerSocket bound the the given,
* and using the specified backlog. If port is zero or negative, a valid
* unused port number will be generated. If the backlog is zero or negative,
* the default value will be used.
* <p>
* The properties parameter used to modify the connection setup behavior of
* the new VirtualServerSocket.
*
* @param port The port number to use.
* @param backlog The maximum number of pending connections this
* VirtualServerSocket will allow.
* @param properties Properties that modify the connection setup behavior
* (may be null).
* @return the new VirtualServerSocket, or null if the creation failed.
*/
public VirtualServerSocket createServerSocket(int port, int backlog,
Map<String, Object> properties) throws IOException {
if (backlog <= 0) {
backlog = DEFAULT_BACKLOG;
}
if (port <= 0) {
port = getPort();
}
if (logger.isInfoEnabled()) {
logger.info("Creating VirtualServerSocket(" + port + ", " + backlog
+ ", " + properties + ")");
}
synchronized (serverSockets) {
if (serverSockets.containsKey(port)) {
throw new BindException("Port " + port + " already in use!");
}
VirtualSocketAddress a = new VirtualSocketAddress(myAddresses,
port, hubAddress, clusters.localCluster());
VirtualServerSocket vss = new VirtualServerSocket(this, a, port,
backlog, DEFAULT_ACCEPT_TIMEOUT, properties);
serverSockets.put(port, vss);
return vss;
}
}
// TODO: hide this thing ?
/**
* Retrieve the ServiceLink that is connected to the hub.
* @return the ServiceLink that is connected to the Hub
*/
public ServiceLink getServiceLink() {
return serviceLink;
}
/**
* Retrieve the DirectSocketAddress of this machine.
* @return the DirectSocketAddress of this machine.
*/
public DirectSocketAddress getLocalHost() {
return myAddresses;
}
/**
* Retrieve the name of the local cluster.
* @return the name of the local cluster.
*/
public String getLocalCluster() {
return clusters.localCluster();
}
/**
* Retrieve the DirectSocketAddress of the hub this VirtualSocketFactory is
* connected to.
* @return the DirectSocketAddress of the hub this VirtualSocketFactory is
* connected to.
*/
public DirectSocketAddress getLocalHub() {
return hubAddress;
}
/**
* Provide a list of hub addresses to the VirtualSocketFactory.
* @param hubs The hub addresses.
*/
public void addHubs(DirectSocketAddress... hubs) {
if (hub != null) {
hub.addHubs(hubs);
} else if (serviceLink != null) {
serviceLink.addHubs(hubs);
}
}
/**
* Provide a list of hub addresses to the VirtualSocketFactory.
* @param hubs The hub addresses.
*/
public void addHubs(String... hubs) {
if (hub != null) {
hub.addHubs(hubs);
} else if (serviceLink != null) {
serviceLink.addHubs(hubs);
}
}
/**
* Retrieve the known hub addresses.
* @return an array containing the known hub addresses.
*/
public DirectSocketAddress[] getKnownHubs() {
if (hub != null) {
return hub.knownHubs();
} else if (serviceLink != null) {
try {
return serviceLink.hubs();
} catch (IOException e) {
logger.info("Failed to retrieve hub list!", e);
}
}
return null;
}
/**
* Shutdown the VirtualSocketFactory.
*/
public void end() {
if (printer != null) {
printer.adjustInterval(-1);
}
if (printStatistics) {
printStatistics(statisticPrefix + " [EXIT]");
}
if (serviceLink != null) {
serviceLink.setDone();
}
if (hub != null) {
hub.end();
}
}
/**
* Close a port.
* @param port the port to close.
*/
protected void closed(int port) {
synchronized (serverSockets) {
serverSockets.remove(Integer.valueOf(port));
}
}
/**
* Retrieve a previously created (and configured) VirtualSocketFactory.
*
* @param name the VirtualSocketFactory to retrieve.
* @return the VirtualSocketFactory, or null if it does not exist.
*/
public static synchronized VirtualSocketFactory getSocketFactory(
String name) {
return factories.get(name);
}
/**
* Get a VirtualSocketFactory, either by retrieving or by creating it.
*
* If the VirtualSocketFactory already existed, the provided properties will
* be compared to those of the existing VirtualSocketFactory to ensure that
* they are the same. If they are not, an InitializationException will be
* thrown.
* <p>
* If the VirtualSocketFactory did not exist, it will be created and stored
* under name for later lookup.
*
* @param name the name of the VirtualSocketFactory to retrieve or create.
* @param p A set of properties that configure the VirtualSocketFactory.
* @param addDefaults Add the default properties to the configuration.
* @return the retrieved or created VirtualSocketFactory.
* @throws InitializationException if the VirtualSocketFactory could not be
* created or received.
*/
public static synchronized VirtualSocketFactory getOrCreateSocketFactory(
String name, java.util.Properties p, boolean addDefaults)
throws InitializationException {
VirtualSocketFactory result = factories.get(name);
if (result == null) {
result = createSocketFactory(p, addDefaults);
factories.put(name, result);
} else {
TypedProperties typedProperties = new TypedProperties();
if (addDefaults) {
typedProperties.putAll(SmartSocketsProperties
.getDefaultProperties());
}
if (p != null) {
typedProperties.putAll(p);
}
if (!typedProperties.equals(result.properties)) {
throw new InitializationException("could not retrieve existing"
+ " factory, properties are not equal");
}
}
return result;
}
/**
* Register an existing VirtualSocketFactory under a different name.
* @param name The name to register the VirtualSocketFactory.
* @param factory The VirtualSocketFactory to register.
*/
public static synchronized void registerSocketFactory(String name,
VirtualSocketFactory factory) {
factories.put(name, factory);
}
/**
* Retrieve a VirtualSocketFactory using the default configuration.
*
* @return a VirtualSocketFactory using the default configuration.
* @throws InitializationException the VirtualSocketFactory could not be
* retrieved.
*/
public static synchronized VirtualSocketFactory getDefaultSocketFactory()
throws InitializationException {
if (defaultFactory == null) {
defaultFactory = createSocketFactory();
}
return defaultFactory;
}
/**
* Create a VirtualSocketFactory using the default configuration.
*
* @return a VirtualSocketFactory using the default configuration.
* @throws InitializationException the VirtualSocketFactory could not be
* created.
*/
public static VirtualSocketFactory createSocketFactory()
throws InitializationException {
return createSocketFactory((java.util.Properties) null, true);
}
/**
* Create a VirtualSocketFactory using the configuration provided in p.
*
* @param p the configuration to use (as a key-value map).
* @param addDefaults Should the default configuration be added ?
* @return a VirtualSocketFactory using the configuration in p.
* @throws InitializationException the VirtualSocketFactory could not be
* created.
*/
public static VirtualSocketFactory createSocketFactory(Map<String, ?> p,
boolean addDefaults) throws InitializationException {
return createSocketFactory(new TypedProperties(p), addDefaults);
}
/**
* Create a VirtualSocketFactory using the configuration provided in
* properties.
*
* @param properties the configuration to use.
* @param addDefaults Should the default configuration be added ?
* @return a VirtualSocketFactory using the configuration in properties.
* @throws InitializationException the VirtualSocketFactory could not be
* created.
*/
public static VirtualSocketFactory createSocketFactory(
java.util.Properties properties, boolean addDefaults)
throws InitializationException {
TypedProperties typedProperties = new TypedProperties();
if (addDefaults) {
typedProperties.putAll(SmartSocketsProperties
.getDefaultProperties());
}
if (properties != null) {
typedProperties.putAll(properties);
}
if (typedProperties.booleanProperty(SmartSocketsProperties.START_HUB,
false)) {
boolean allowSSHForHub = typedProperties.booleanProperty(
SmartSocketsProperties.HUB_SSH_ALLOWED, true);
if (allowSSHForHub) {
typedProperties.setProperty(SmartSocketsProperties.SSH_IN,
"true");
// Do we need this one ?
// typedProperties.setProperty(SmartSocketsProperties.SSH_OUT,
// "true");
}
}
VirtualSocketFactory factory = new VirtualSocketFactory(
DirectSocketFactory.getSocketFactory(typedProperties),
typedProperties);
return factory;
}
/**
* Retrieve the contact address of this VirtualSocketFactory.
*
* @return a VirtualSocketAddress containing the contact address of this
* VirtualSocketFactory.
*/
public VirtualSocketAddress getLocalVirtual() {
return localVirtualAddress;
}
/**
* Retrieve the contact address of this VirtualSocketFactory.
*
* @return a String containing the contact address of this
* VirtualSocketFactory.
*/
public String getVirtualAddressAsString() {
return localVirtualAddressAsString;
}
/**
* Print statistics on the connections created by this VirtualSocketFactory.
*
* Every line printed will prepended with the given prefix.
*
* @param prefix the prefix to use when printing.
*/
public void printStatistics(String prefix) {
if (statslogger.isInfoEnabled()) {
statslogger.info(prefix + " === VirtualSocketFactory ("
+ modules.size() + " / "
+ (serviceLink == null ? "No SL" : "SL") + ") ===");
for (ConnectModule c : modules) {
c.printStatistics(prefix);
}
if (serviceLink != null) {
serviceLink.printStatistics(prefix);
}
}
}
}
| src/ibis/smartsockets/virtual/VirtualSocketFactory.java | package ibis.smartsockets.virtual;
import ibis.smartsockets.SmartSocketsProperties;
import ibis.smartsockets.direct.DirectSocket;
import ibis.smartsockets.direct.DirectSocketAddress;
import ibis.smartsockets.direct.DirectSocketFactory;
import ibis.smartsockets.discovery.Discovery;
import ibis.smartsockets.hub.Hub;
import ibis.smartsockets.hub.servicelink.ServiceLink;
import ibis.smartsockets.util.TypedProperties;
import ibis.smartsockets.virtual.modules.AbstractDirectModule;
import ibis.smartsockets.virtual.modules.AcceptHandler;
import ibis.smartsockets.virtual.modules.ConnectModule;
import ibis.smartsockets.virtual.modules.direct.Direct;
import ibis.smartsockets.virtual.modules.hubrouted.Hubrouted;
import ibis.smartsockets.virtual.modules.reverse.Reverse;
import ibis.smartsockets.virtual.modules.splice.Splice;
import ibis.smartsockets.util.ThreadPool;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.SocketTimeoutException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.java_cup.internal.runtime.virtual_parse_stack;
/**
* This class implements a virtual socket factory.
*
* The VirtualSocketFactory is the public interface to the virtual connection
* layer of SmartSockets. It implements several types of connection setup using
* the direct connection layer (see {@link DirectSocketFactory}) and a
* {@link ServiceLink} to the {@link Hub}.
*<p>
* The different connection setup schemes are implemented in separate modules
* each extending the {@link ConnectModule} class.
*<p>
* Currently, 4 different connect modules are available:<br>
*<p>
* {@link Direct}: creates a direct connection to the target.<br>
* {@link Reverse}: reverses the connection setup.such that the target creates a
* direct connection to the source.<br>
* {@link Splice}: uses TCP splicing to create a direct connection to the
* target.<br>
* {@link Hubrouted}: create a virtual connection that routes all traffic
* through the hub overlay.<br>
*<p>
* To create a new connection, each module is tried in sequence until a
* connection is established, or until it is clear that a connection can not be
* established at all (e.g., because the destination port does not exist on the
* target machine). By default, the order<br>
*<p>
* Direct, Reverse, Splice, Routed
* <p>is used. This order prefers modules that produce a direct connection. This
* default order can be changed using the
* smartsockets.modules.order property. The order can also be
* adjusted on a per connection basis by providing this property to the
* createClientSocket method.
*
* @see ibis.smartsockets.virtual.modules
* @see DirectSocketFactory
* @see ServiceLink
* @see Hub
*
* @author Jason Maassen
* @version 1.0 Jan 30, 2006
* @since 1.0
*
*/
public final class VirtualSocketFactory {
private static class StatisticsPrinter implements Runnable {
private int timeout;
private VirtualSocketFactory factory;
private String prefix;
StatisticsPrinter(VirtualSocketFactory factory, int timeout,
String prefix) {
this.timeout = timeout;
this.factory = factory;
this.prefix = prefix;
}
public void run() {
int t = getTimeout();
while (t > 0) {
try {
synchronized (this) {
wait(t);
}
} catch (Exception e) {
// ignore
}
t = getTimeout();
if (t > 0) {
try {
factory.printStatistics(prefix);
} catch (Exception e) {
// TODO: IGNORE ?
}
}
}
}
private synchronized int getTimeout() {
return timeout;
}
public synchronized void adjustInterval(int interval) {
timeout = interval;
notifyAll();
}
}
private static final Map<String, VirtualSocketFactory> factories =
new HashMap<String, VirtualSocketFactory>();
private static VirtualSocketFactory defaultFactory = null;
protected static final Logger logger =
LoggerFactory.getLogger("ibis.smartsockets.virtual.misc");
protected static final Logger conlogger =
LoggerFactory.getLogger("ibis.smartsockets.virtual.connect");
private static final Logger statslogger = LoggerFactory
.getLogger("ibis.smartsockets.statistics");
private final DirectSocketFactory directSocketFactory;
private final ArrayList<ConnectModule> modules =
new ArrayList<ConnectModule>();
private ConnectModule direct;
private final TypedProperties properties;
private final int DEFAULT_BACKLOG;
private final int DEFAULT_TIMEOUT;
private final int DEFAULT_ACCEPT_TIMEOUT;
private final boolean DETAILED_EXCEPTIONS;
private final Random random;
private final HashMap<Integer, VirtualServerSocket> serverSockets =
new HashMap<Integer, VirtualServerSocket>();
private int nextPort = 3000;
private DirectSocketAddress myAddresses;
private DirectSocketAddress hubAddress;
private VirtualSocketAddress localVirtualAddress;
private String localVirtualAddressAsString;
private ServiceLink serviceLink;
private Hub hub;
private VirtualClusters clusters;
private boolean printStatistics = false;
private String statisticPrefix = null;
private StatisticsPrinter printer = null;
private static class HubAcceptor implements AcceptHandler {
private final Hub hub;
private HubAcceptor(Hub hub) {
this.hub = hub;
}
public void accept(DirectSocket s, int targetPort, long time) {
hub.delegateAccept(s);
}
}
private VirtualSocketFactory(DirectSocketFactory df, TypedProperties p)
throws InitializationException {
directSocketFactory = df;
if (logger.isInfoEnabled()) {
logger.info("Creating VirtualSocketFactory");
}
random = new Random();
properties = p;
DETAILED_EXCEPTIONS = p.booleanProperty(
SmartSocketsProperties.DETAILED_EXCEPTIONS, false);
DEFAULT_BACKLOG = p.getIntProperty(SmartSocketsProperties.BACKLOG, 50);
DEFAULT_ACCEPT_TIMEOUT = p.getIntProperty(
SmartSocketsProperties.ACCEPT_TIMEOUT, 60000);
// NOTE: order is VERY important here!
try {
loadModules();
} catch (Exception e) {
logger.info("Failed to load modules!", e);
throw new InitializationException(e.getMessage(), e);
}
if (modules.size() == 0) {
logger.info("Failed to load any modules!");
throw new InitializationException("Failed to load any modules!");
}
// -- this depends on the modules being loaded
DEFAULT_TIMEOUT = determineDefaultTimeout(p);
startHub(p);
// We now create the service link. This may connect to the hub that we
// have just started.
String localCluster = p.getProperty(
SmartSocketsProperties.CLUSTER_MEMBER, null);
createServiceLink(localCluster);
// Once the servicelink is up and running, we can start the modules.
startModules();
if (modules.size() == 0) {
logger.info("Failed to start any modules!");
throw new InitializationException("Failed to load any modules!");
}
loadClusterDefinitions();
localVirtualAddress = new VirtualSocketAddress(myAddresses, 0,
hubAddress, clusters.localCluster());
localVirtualAddressAsString = localVirtualAddress.toString();
printStatistics =
p.booleanProperty(SmartSocketsProperties.STATISTICS_PRINT);
if (printStatistics) {
statisticPrefix = p.getProperty(
SmartSocketsProperties.STATISTICS_PREFIX, "SmartSockets");
int tmp = p.getIntProperty(
SmartSocketsProperties.STATISTICS_INTERVAL, 0);
if (tmp > 0) {
printer = new StatisticsPrinter(this, tmp * 1000,
statisticPrefix);
ThreadPool
.createNew(printer, "SmartSockets Statistics Printer");
}
}
}
private void startHub(TypedProperties p) throws InitializationException {
if (p.booleanProperty(SmartSocketsProperties.START_HUB, false)) {
AbstractDirectModule d = null;
// Check if the hub should delegate it's accept call to the direct
// module. This way, only a single server port (and address) is
// needed to reach both this virtual socket factory and the hub.
boolean delegate = p.booleanProperty(
SmartSocketsProperties.HUB_DELEGATE, false);
if (delegate) {
logger.info("Factory delegating hub accepts to direct module!");
// We should now add an AcceptHandler to the direct module that
// intercepts incoming connections for the hub. Start by finding
// the direct module...
for (ConnectModule m : modules) {
if (m.module.equals("ConnectModule(Direct)")) {
d = (AbstractDirectModule) m;
break;
}
}
if (d == null) {
throw new InitializationException("Cannot start hub: "
+ "Failed to find direct module!");
}
// And add its address to the property set as the 'delegation'
// address. This is needed by the hub (since it needs to know
// its own address).
p.setProperty(SmartSocketsProperties.HUB_DELEGATE_ADDRESS, d
.getAddresses().toString());
}
// Now we create the hub
logger.info("Factory is starting hub");
try {
hub = new Hub(p);
logger.info("Hub running on: " + hub.getHubAddress());
} catch (IOException e) {
throw new InitializationException("Failed to start hub", e);
}
// Finally, if delegation is used, we install the accept handler
if (delegate) {
// Get the 'virtual port' that the hub pretends to be on.
int port = p.getIntProperty(
SmartSocketsProperties.HUB_VIRTUAL_PORT, 42);
d.installAcceptHandler(port, new HubAcceptor(hub));
}
}
}
private void loadClusterDefinitions() {
clusters = new VirtualClusters(this, properties, getModules());
}
private DirectSocketAddress discoverHub(String localCluster) {
DirectSocketAddress address = null;
if (logger.isInfoEnabled()) {
logger.info("Attempting to discover hub using UDP multicast...");
}
int port = properties
.getIntProperty(SmartSocketsProperties.DISCOVERY_PORT);
int time = properties
.getIntProperty(SmartSocketsProperties.DISCOVERY_TIMEOUT);
Discovery d = new Discovery(port, 0, time);
String message = "Any Proxies? ";
message += localCluster;
String result = d.broadcastWithReply(message);
if (result != null) {
try {
address = DirectSocketAddress.getByAddress(result);
if (logger.isInfoEnabled()) {
logger.info("Hub found at: " + address.toString());
}
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Got unknown reply to hub discovery!");
}
}
} else {
if (logger.isInfoEnabled()) {
logger.info("No hubs found.");
}
}
return address;
}
private void createServiceLink(String localCluster) {
List<DirectSocketAddress> hubs = new LinkedList<DirectSocketAddress>();
if (hub != null) {
hubs.add(hub.getHubAddress());
}
// Check if the hub address was passed as a property.
String[] tmp = properties
.getStringList(SmartSocketsProperties.HUB_ADDRESSES);
if (tmp != null && tmp.length > 0) {
for (String a : tmp) {
try {
hubs.add(DirectSocketAddress.getByAddress(a));
} catch (Exception e) {
logger.warn("Failed to understand hub address: "
+ Arrays.deepToString(tmp), e);
}
}
}
// If we don't have a hub address, we try to find one ourselves
if (hubs.size() == 0) {
boolean useDiscovery = properties.booleanProperty(
SmartSocketsProperties.DISCOVERY_ALLOWED, false);
boolean discoveryPreferred = properties.booleanProperty(
SmartSocketsProperties.DISCOVERY_PREFERRED, false);
DirectSocketAddress address = null;
if (useDiscovery && (discoveryPreferred || hub == null)) {
address = discoverHub(localCluster);
}
if (address != null) {
hubs.add(address);
}
}
// Still no address ? Give up...
if (hubs.size() == 0) {
// properties not set, so no central hub is available
logger.warn("ServiceLink not created: no hub address available!");
return;
}
// Sort addresses according to locality ?
boolean force = properties
.booleanProperty(SmartSocketsProperties.SL_FORCE);
try {
serviceLink = ServiceLink.getServiceLink(properties, hubs,
myAddresses);
hubAddress = serviceLink.getAddress();
} catch (Exception e) {
logger.warn("Failed to obtain service link to hub!", e);
if (force) {
// FIXME!!
logger.error("Permanent failure of servicelink! -- will exit");
System.exit(1);
}
return;
}
if (force) {
int retries = Math.max(1, properties
.getIntProperty(SmartSocketsProperties.SL_RETRIES));
boolean connected = false;
while (!connected && retries > 0) {
try {
serviceLink.waitConnected(properties
.getIntProperty(SmartSocketsProperties.SL_TIMEOUT));
connected = true;
} catch (Exception e) {
logger.warn("Failed to connect service link to hub "
+ hubAddress, e);
}
retries--;
}
if (!connected) {
// FIXME
logger.error("Permanent failure of servicelink! -- will exit");
System.exit(1);
}
} else {
try {
serviceLink.waitConnected(properties
.getIntProperty(SmartSocketsProperties.SL_TIMEOUT));
} catch (Exception e) {
logger.warn("Failed to connect service link to hub "
+ hubAddress, e);
return;
}
}
// Check if the users want us to register any properties with the hub.
String[] props = properties.getStringList(
"smartsockets.register.property", ",", null);
if (props != null && props.length > 0) {
try {
if (props.length == 1) {
serviceLink.registerProperty(props[0], "");
} else {
serviceLink.registerProperty(props[0], props[1]);
}
} catch (Exception e) {
if (props.length == 1) {
logger
.warn("Failed to register user property: "
+ props[0]);
} else {
logger.warn("Failed to register user property: " + props[0]
+ "=" + props[1]);
}
}
}
}
private ConnectModule instantiateModule(String name) {
if (logger.isInfoEnabled()) {
logger.info("Loading module: " + name);
}
String classname = properties.getProperty(
SmartSocketsProperties.MODULES_PREFIX + name, null);
if (classname == null) {
// The class implementing the module is not explicitly defined, so
// instead we use an 'educated guess' of the form:
//
// smartsockets.virtual.modules.<name>.<Name>
//
StringBuffer tmp = new StringBuffer();
tmp.append("ibis.smartsockets.virtual.modules.");
tmp.append(name.toLowerCase());
tmp.append(".");
tmp.append(Character.toUpperCase(name.charAt(0)));
tmp.append(name.substring(1));
classname = tmp.toString();
}
if (logger.isInfoEnabled()) {
logger.info(" class name: " + classname);
}
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class<?> c;
// Check if there is a context class loader
if (cl != null) {
c = cl.loadClass(classname);
} else {
c = Class.forName(classname);
}
// Check if the class we loaded is indeed a flavor of ConnectModule
if (!ConnectModule.class.isAssignableFrom(c)) {
logger.warn("Cannot load module " + classname + " since it is "
+ " not a subclass of ConnectModule!");
return null;
}
return (ConnectModule) c.newInstance();
} catch (Exception e) {
logger.info("Failed to load module " + classname, e);
}
return null;
}
private void loadModule(String name) throws Exception {
ConnectModule m = instantiateModule(name);
m.init(this, name, properties, logger);
DirectSocketAddress tmp = m.getAddresses();
if (tmp != null) {
if (myAddresses == null) {
myAddresses = tmp;
} else {
myAddresses = DirectSocketAddress.merge(myAddresses, tmp);
}
}
modules.add(m);
}
private void loadModules() throws Exception {
// Get the list of modules that we should load. Note that we should
// always load the "direct" module, since it is needed to implement the
// others. Note that this doesn't neccesarily mean that the user wants
// to use it though...
String[] mods = properties.getStringList(
SmartSocketsProperties.MODULES_DEFINE, ",", new String[0]);
if (mods == null || mods.length == 0) {
// Should not happen!
throw new NoModulesDefinedException(
"No smartsockets modules defined!");
}
// Get the list of modules to skip. Note that the direct module cannot
// be skipped completely (it is needed to implement the others).
String[] skip = properties.getStringList(
SmartSocketsProperties.MODULES_SKIP, ",", null);
int count = mods.length;
// Remove all modules that should be skipped.
if (skip != null) {
for (int s = 0; s < skip.length; s++) {
for (int m = 0; m < mods.length; m++) {
if (skip[s].equals(mods[m])) {
if (logger.isInfoEnabled()) {
logger.info("Skipping module " + mods[m]);
}
mods[m] = null;
count--;
}
}
}
}
if (logger.isInfoEnabled()) {
String t = "";
for (int i = 0; i < mods.length; i++) {
if (mods[i] != null) {
t += mods[i] + " ";
}
}
logger.info("Loading " + count + " modules: " + t);
}
if (count == 0) {
throw new NoModulesDefinedException("No smartsockets modules "
+ "left after filtering!");
}
// We start by loading the direct module. This one is always needed to
// support the other modules, but not necessarily used by the client.
try {
direct = new Direct(directSocketFactory);
direct.init(this, "direct", properties, logger);
myAddresses = direct.getAddresses();
} catch (Exception e) {
logger.info("Failed to load direct module!", e);
throw e;
}
if (myAddresses == null) {
logger.info("Failed to retrieve my own address!");
throw new NoLocalAddressException(
"Failed to retrieve local address!");
}
for (int i = 0; i < mods.length; i++) {
if (mods[i] != null) {
if (mods[i].equals("direct")) {
modules.add(direct);
} else {
try {
loadModule(mods[i]);
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Failed to load module: " + mods[i], e);
}
mods[i] = null;
count--;
}
}
}
}
if (logger.isInfoEnabled()) {
logger.info(count + " modules loaded.");
}
if (count == 0) {
throw new NoModulesDefinedException("Failed to load any modules");
}
}
private int determineDefaultTimeout(TypedProperties p) {
int[] tmp = new int[modules.size()];
int totalTimeout = 0;
for (int i = 0; i < modules.size(); i++) {
// Get the module defined timeout
tmp[i] = modules.get(i).getDefaultTimeout();
totalTimeout += tmp[i];
}
int timeout = p.getIntProperty(SmartSocketsProperties.CONNECT_TIMEOUT,
-1);
if (timeout <= 0) {
// It's up to the modules to determine their own timeout
timeout = totalTimeout;
} else {
// A user-defined timeout should be distributed over the modules
for (int i = 0; i < modules.size(); i++) {
double t = (((double) tmp[i]) / totalTimeout) * timeout;
modules.get(i).setTimeout((int) t);
}
}
if (logger.isInfoEnabled()) {
logger.info("Total timeout set to: " + timeout);
for (ConnectModule m : modules) {
logger.info(" " + m.getName() + ": " + m.getTimeout());
}
}
return timeout;
}
protected ConnectModule[] getModules() {
return modules.toArray(new ConnectModule[modules.size()]);
}
protected ConnectModule[] getModules(String[] names) {
ArrayList<ConnectModule> tmp = new ArrayList<ConnectModule>();
for (int i = 0; i < names.length; i++) {
boolean found = false;
if (names[i] != null && !names[i].equals("none")) {
for (int j = 0; j < modules.size(); j++) {
ConnectModule m = modules.get(j);
if (m.getName().equals(names[i])) {
tmp.add(m);
found = true;
break;
}
}
if (!found) {
logger.warn("Module " + names[i] + " not found!");
}
}
}
return tmp.toArray(new ConnectModule[tmp.size()]);
}
private void startModules() {
ArrayList<ConnectModule> failed = new ArrayList<ConnectModule>();
if (serviceLink == null) {
// No servicelink, so remove all modules that depend on it....
for (ConnectModule c : modules) {
if (c.requiresServiceLink) {
failed.add(c);
}
}
for (ConnectModule c : failed) {
logger
.info("Module " + c.module
+ " removed (no serviceLink)!");
modules.remove(c);
}
failed.clear();
}
for (ConnectModule c : modules) {
try {
c.startModule(serviceLink);
} catch (Exception e) {
// Remove all modules that fail to start...
logger.warn("Module " + c.module
+ " did not accept serviceLink!", e);
failed.add(c);
}
}
for (ConnectModule c : failed) {
logger.warn("Module " + c.module
+ " removed (exception during setup)!");
modules.remove(c);
}
failed.clear();
}
public VirtualServerSocket getServerSocket(int port) {
synchronized (serverSockets) {
return serverSockets.get(port);
}
}
public ConnectModule findModule(String name) {
// Direct is special, since it may be loaded without being part of the
// modules array.
if (name.equals("direct")) {
return direct;
}
for (ConnectModule m : modules) {
if (m.module.equals(name)) {
return m;
}
}
return null;
}
public static void close(VirtualSocket s, OutputStream out, InputStream in) {
try {
if (out != null) {
out.close();
}
} catch (Throwable e) {
// ignore
}
try {
if (in != null) {
in.close();
}
} catch (Throwable e) {
// ignore
}
try {
if (s != null) {
s.close();
}
} catch (Throwable e) {
// ignore
}
}
public static void close(VirtualSocket s, SocketChannel channel) {
if (channel != null) {
try {
channel.close();
} catch (Exception e) {
// ignore
}
}
if (s != null) {
try {
s.close();
} catch (Exception e) {
// ignore
}
}
}
// This method implements a connect using a specific module. This method
// will return null when:
//
// - runtime requirements do not match
// - the module throws a NonFatalIOException
//
// When a connection is succesfully establed, we wait for a accept from the
// remote. There are three possible outcomes:
//
// - the connection is accepted in time
// - the connection is not accepted in time or the connection is lost
// - the remote side is overloaded and closes the connection
//
// In the first case the newly created socket is returned and in the second
// case an exception is thrown. In the last case the connection will be
// retried using a backoff mechanism until 'timeleft' (the total timeout
// specified by the user) is spend. Each new try behaves exactly the same as
// the previous attempts.
private VirtualSocket createClientSocket(ConnectModule m,
VirtualSocketAddress target, int timeout, int timeLeft,
boolean fillTimeout, Map<String, Object> properties)
throws IOException, NonFatalIOException {
int backoff = 1000;
if (!m.matchRuntimeRequirements(properties)) {
if (conlogger.isInfoEnabled()) {
conlogger.warn("Failed: module " + m.module
+ " may not be used to set " + "up connection to "
+ target);
}
m.connectNotAllowed();
return null;
}
if (conlogger.isDebugEnabled()) {
conlogger.debug("Using module " + m.module + " to set up "
+ "connection to " + target + " timeout = " + timeout
+ " timeleft = " + timeLeft);
}
// We now try to set up a connection. Normally we may not exceed the
// timeout, but when we succesfully create a connection we are allowed
// to extend this time to timeLeft (either to wait for an accept, or to
// retry after a TargetOverLoaded exception). Note that any exception
// other than ModuleNotSuitable or TargetOverloaded is passed to the
// user.
VirtualSocket vs = null;
int overloaded = 0;
long start = System.currentTimeMillis();
boolean lastAttempt = false;
while (true) {
long t = System.currentTimeMillis() - start;
// Check if we ran out of time. If so, the throw a target overloaded
// exception or a timeout exception depending on the value of the
// overloaded counter.
if (t >= timeLeft) {
if (conlogger.isDebugEnabled()) {
conlogger.debug("Timeout while using module " + m.module
+ " to set up " + "connection to " + target
+ " timeout = " + timeout + " timeleft = "
+ timeLeft + " t = " + t);
}
if (overloaded > 0) {
m.connectRejected(t);
throw new TargetOverloadedException("Failed to create "
+ "virtual connection to " + target + " within "
+ timeLeft + " ms. (Target overloaded "
+ overloaded + " times)");
} else {
m.connectFailed(t);
throw new SocketTimeoutException("Timeout while creating"
+ " connection to " + target);
}
}
try {
vs = m.connect(target, timeout, properties);
} catch (NonFatalIOException e) {
long end = System.currentTimeMillis();
// Just print and try the next module...
if (conlogger.isInfoEnabled()) {
conlogger.info("Module " + m.module + " failed to connect "
+ "to " + target + " after " + (end - start)
+ " ms.): " + e.getMessage());
}
m.connectFailed(end - start);
throw e;
// NOTE: The modules may also throw IOExceptions for
// non-transient errors (i.e., port not found). These are
// forwarded to the user.
}
t = System.currentTimeMillis() - start;
if (vs != null) {
// We now have a connection to the correct machine and must wait
// for an accept from the serversocket. Since we don't have to
// try any other modules, we are allowed to spend all of the
// time that is left. Therefore, we start by calculating a new
// timeout here, which is based on the left over time for the
// entire connect call, minus the time we have spend so far in
// this connect. This is the timeout we pass to 'waitForAccept'.
int newTimeout = (int) (timeLeft - t);
if (newTimeout <= 0) {
// Bit of a hack. If we run out of time at the last moment
// we allow some extra time to finish the connection setup.
// TODO: should we do this ?
newTimeout = 1000;
}
if (conlogger.isInfoEnabled()) {
conlogger.info(getVirtualAddressAsString() + ": Success "
+ m.module + " connected to " + target
+ " now waiting for accept (for max. " + newTimeout
+ " ms.)");
}
try {
vs.waitForAccept(newTimeout);
vs.setTcpNoDelay(false);
long end = System.currentTimeMillis();
if (conlogger.isInfoEnabled()) {
conlogger.info(getVirtualAddressAsString()
+ ": Success " + m.module + " connected to "
+ target + " (time = " + (end - start)
+ " ms.)");
}
m.connectSucces(end - start);
return vs;
} catch (TargetOverloadedException e) {
// This is always allowed.
if (conlogger.isDebugEnabled()) {
conlogger.debug("Connection failed, target " + target
+ " overloaded (" + overloaded
+ ") while using " + " module " + m.module);
}
overloaded++;
} catch (IOException e) {
if (conlogger.isDebugEnabled()) {
conlogger.debug("Connection failed, target " + target
+ ", got exception (" + e.getMessage()
+ ") while using " + " module " + m.module);
}
if (!fillTimeout) {
m.connectFailed(System.currentTimeMillis() - start);
// We'll only retry if 'fillTimeout' is true
throw e;
}
}
// The target has refused our connection. Since we have
// obviously found a working module, we will not return.
// Instead we will retry using a backoff algorithm until
// we run out of time...
t = System.currentTimeMillis() - start;
m.connectRejected(t);
int leftover = (int) (timeLeft - t);
if (!lastAttempt && leftover > 0) {
int sleeptime = 0;
if (backoff < leftover) {
// Use a randomized sleep value to ensure the attempts
// are distributed.
sleeptime = random.nextInt(backoff);
} else {
sleeptime = leftover;
lastAttempt = true;
}
// System.err.println("Backoff = " + backoff +
// " Leftover = " + leftover + " Sleep time = " +
// sleeptime);
if (sleeptime > 0) {
try {
Thread.sleep(sleeptime);
} catch (Exception x) {
// ignored
}
}
if (leftover < 500) {
// We're done!
timeLeft = 0;
} else {
backoff *= 2;
}
} else {
// We're done
timeLeft = 0;
}
}
}
}
private String[] getNames(ConnectModule[] modules) {
String[] names = new String[modules.length];
for (int n = 0; n < modules.length; n++) {
names[n] = modules[n].getName();
}
return names;
}
// This method loops over and array of connection modules, trying to setup
// a connection with each of them each in turn. Returns when:
// - a connection is established
// - a non-transient error occurs (i.e. remote port not found)
// - all modules have failed
// - a timeout occurred
//
private VirtualSocket createClientSocket(VirtualSocketAddress target,
ConnectModule[] order, int[] timeouts, int totalTimeout,
long[] timing, boolean fillTimeout, Map<String, Object> prop)
throws IOException, NoSuitableModuleException {
Throwable[] exceptions = new Throwable[order.length];
try {
int timeLeft = totalTimeout;
VirtualSocket vs = null;
// Now try the remaining modules (or all of them if we weren't
// using the cache in the first place...)
for (int i = 0; i < order.length; i++) {
ConnectModule m = order[i];
int timeout = (timeouts != null ? timeouts[i] : m.getTimeout());
long start = System.currentTimeMillis();
/*
* if (timing != null) { timing[1 + i] = System.nanoTime();
*
* if (i > 0) { prop.put("direct.detailed.timing.ignore", null);
* } }
*/
try {
vs = createClientSocket(m, target, timeout, timeLeft,
fillTimeout, prop);
} catch (NonFatalIOException e) {
// Store the exeception and continue with the next module
exceptions[i] = e;
}
/*
* if (timing != null) { timing[1 + i] = System.nanoTime() -
* timing[1 + i]; }
*/
if (vs != null) {
if (i > 0) {
// We managed to connect, but not with the first module,
// so we remember this to speed up later connections.
clusters.succes(target, m);
}
return vs;
}
if (order.length > 1 && i < order.length - 1) {
timeLeft -= System.currentTimeMillis() - start;
if (timeLeft <= 0) {
// NOTE: This can only happen when a module breaks
// the rules (defensive programming).
throw new NoSuitableModuleException("Timeout during "
+ " connect to " + target, getNames(order),
exceptions);
}
}
}
if (logger.isInfoEnabled()) {
logger.info("No suitable module found to connect to " + target);
}
// No suitable modules found...
throw new NoSuitableModuleException("No suitable module found to"
+ " connect to " + target + " (timeouts="
+ Arrays.toString(timeouts) + ", fillTimeout="
+ fillTimeout + ")", getNames(order), exceptions);
} finally {
if (timing != null && prop != null) {
timing[0] = System.nanoTime() - timing[0];
prop.remove("direct.detailed.timing.ignore");
}
}
}
// Distribute a given timeout over a number of modules, taking the relative
// sizes of the default module timeouts into account.
private int[] distributesTimeout(int timeout, int[] timeouts,
ConnectModule[] modules) {
if (timeouts == null) {
timeouts = new int[modules.length];
}
for (int i = 0; i < modules.length; i++) {
double t = (((double) modules[i].getTimeout()) / DEFAULT_TIMEOUT);
timeouts[i] = (int) (t * timeout);
}
return timeouts;
}
public VirtualSocket createClientSocket(VirtualSocketAddress target,
int timeout, Map<String, Object> prop) throws IOException {
return createClientSocket(target, timeout, false, prop);
}
public VirtualSocket createClientSocket(VirtualSocketAddress target,
int timeout, boolean fillTimeout, Map<String, Object> prop)
throws IOException {
// Note: it's up to the user to ensure that this thing is large enough!
// i.e., it should be of size 1+modules.length
if (conlogger.isDebugEnabled()) {
conlogger.debug("createClientSocket(" + target + ", " + timeout
+ ", " + fillTimeout + ", " + prop + ")");
}
/*
* long [] timing = null;
*
* if (prop != null) { // Note: it's up to the user to ensure that this
* thing is large // enough! i.e., it should be of size 1+modules.length
* timing = (long[]) prop.get("virtual.detailed.timing");
*
* if (timing != null) { timing[0] = System.nanoTime(); } }
*/
// Check the timeout here. If it is not set, we will use the default
if (timeout <= 0) {
timeout = DEFAULT_TIMEOUT;
}
ConnectModule[] order = clusters.getOrder(target);
int timeLeft = timeout;
int[] timeouts = null;
boolean lastAttempt = false;
int backoff = 250;
NoSuitableModuleException exception = null;
LinkedList<NoSuitableModuleException> exceptions = null;
if (DETAILED_EXCEPTIONS) {
exceptions = new LinkedList<NoSuitableModuleException>();
}
do {
if (timeLeft <= DEFAULT_TIMEOUT) {
// determine timeout for each module. We assume that this time
// is used completely and therefore only do this once.
timeouts = distributesTimeout(timeLeft, timeouts, order);
fillTimeout = false;
}
long start = System.currentTimeMillis();
try {
return createClientSocket(target, order, timeouts, timeLeft,
/* timing */null, fillTimeout, prop);
} catch (NoSuitableModuleException e) {
// All modules where tried and failed. It now depends on the
// user if he would like to try another round or give up.
if (conlogger.isDebugEnabled()) {
conlogger.debug("createClientSocket failed. Will "
+ (fillTimeout ? "" : "NOT ") + "retry");
}
if (DETAILED_EXCEPTIONS) {
exceptions.add(e);
} else {
exception = e;
}
}
timeLeft -= System.currentTimeMillis() - start;
if (!lastAttempt && fillTimeout && timeLeft > 0) {
int sleeptime = 0;
if (backoff < timeLeft) {
sleeptime = random.nextInt(backoff);
} else {
sleeptime = timeLeft;
lastAttempt = true;
}
if (sleeptime >= timeLeft) {
// In the last attempt we sleep half a second shorter.
// This allows us to attempt a connection setup.
if (sleeptime > 500) {
sleeptime -= 500;
} else {
// We're done!
sleeptime = 0;
fillTimeout = false;
}
}
if (sleeptime > 0) {
try {
Thread.sleep(sleeptime);
} catch (Exception x) {
// ignored
}
}
backoff *= 2;
} else {
fillTimeout = false;
}
} while (fillTimeout);
if (DETAILED_EXCEPTIONS) {
throw new NoSuitableModuleException("No suitable module found to "
+ "connect to " + target + "(timeout=" + timeout
+ ", fillTimeout=" + fillTimeout + ")", exceptions);
} else {
throw exception;
}
}
private int getPort() {
// TODO: should this be random ?
synchronized (serverSockets) {
while (true) {
if (!serverSockets.containsKey(nextPort)) {
return nextPort++;
} else {
nextPort++;
}
}
}
}
public VirtualServerSocket createServerSocket(int port, int backlog,
boolean retry, java.util.Properties properties) {
// Fix: extract all string properties, don't use the properties object
// as a map! --Ceriel
HashMap<String, Object> props = new HashMap<String, Object>();
if (properties != null) {
// Fix: stringPropertyNames method isn't available on android, so
// added a cast --Roelof
// for (String s : properties.stringPropertyNames()) {
for (Object string : properties.keySet()) {
props.put((String) string, properties
.getProperty((String) string));
}
}
VirtualServerSocket result = null;
while (result == null) {
try {
// Did not pass on properties. Fixed. --Ceriel
// result = createServerSocket(port, backlog, null);
result = createServerSocket(port, backlog, props);
} catch (Exception e) {
// retry
if (logger.isDebugEnabled()) {
logger.debug("Failed to open serversocket on port " + port
+ " (will retry): ", e);
}
}
}
return result;
}
public VirtualServerSocket createServerSocket(Map<String, Object> properties)
throws IOException {
return new VirtualServerSocket(this, DEFAULT_ACCEPT_TIMEOUT, properties);
}
protected void bindServerSocket(VirtualServerSocket vss, int port)
throws BindException {
synchronized (serverSockets) {
if (serverSockets.containsKey(port)) {
throw new BindException("Port " + port + " already in use!");
}
serverSockets.put(port, vss);
}
}
public VirtualServerSocket createServerSocket(int port, int backlog,
Map<String, Object> properties) throws IOException {
if (backlog <= 0) {
backlog = DEFAULT_BACKLOG;
}
if (port <= 0) {
port = getPort();
}
if (logger.isInfoEnabled()) {
logger.info("Creating VirtualServerSocket(" + port + ", " + backlog
+ ", " + properties + ")");
}
synchronized (serverSockets) {
if (serverSockets.containsKey(port)) {
throw new BindException("Port " + port + " already in use!");
}
VirtualSocketAddress a = new VirtualSocketAddress(myAddresses,
port, hubAddress, clusters.localCluster());
VirtualServerSocket vss = new VirtualServerSocket(this, a, port,
backlog, DEFAULT_ACCEPT_TIMEOUT, properties);
serverSockets.put(port, vss);
return vss;
}
}
// TODO: hide this thing ?
public ServiceLink getServiceLink() {
return serviceLink;
}
public DirectSocketAddress getLocalHost() {
return myAddresses;
}
public String getLocalCluster() {
return clusters.localCluster();
}
public DirectSocketAddress getLocalHub() {
return hubAddress;
}
public void addHubs(DirectSocketAddress... hubs) {
if (hub != null) {
hub.addHubs(hubs);
} else if (serviceLink != null) {
serviceLink.addHubs(hubs);
}
}
public void addHubs(String... hubs) {
if (hub != null) {
hub.addHubs(hubs);
} else if (serviceLink != null) {
serviceLink.addHubs(hubs);
}
}
public DirectSocketAddress[] getKnownHubs() {
if (hub != null) {
return hub.knownHubs();
} else if (serviceLink != null) {
try {
return serviceLink.hubs();
} catch (IOException e) {
logger.info("Failed to retrieve hub list!", e);
}
}
return null;
}
public void end() {
if (printer != null) {
printer.adjustInterval(-1);
}
if (printStatistics) {
printStatistics(statisticPrefix + " [EXIT]");
}
if (serviceLink != null) {
serviceLink.setDone();
}
if (hub != null) {
hub.end();
}
}
protected void closed(int port) {
synchronized (serverSockets) {
serverSockets.remove(Integer.valueOf(port));
}
}
public static synchronized VirtualSocketFactory getSocketFactory(String name) {
return factories.get(name);
}
public static synchronized VirtualSocketFactory getOrCreateSocketFactory(
String name, java.util.Properties p, boolean addDefaults)
throws InitializationException {
VirtualSocketFactory result = factories.get(name);
if (result == null) {
result = createSocketFactory(p, addDefaults);
factories.put(name, result);
} else {
TypedProperties typedProperties = new TypedProperties();
if (addDefaults) {
typedProperties.putAll(SmartSocketsProperties
.getDefaultProperties());
}
if (p != null) {
typedProperties.putAll(p);
}
if (!typedProperties.equals(result.properties)) {
throw new InitializationException("could not retrieve existing"
+ " factory, properties are not equal");
}
}
return result;
}
public static synchronized void registerSocketFactory(String name,
VirtualSocketFactory factory) {
factories.put(name, factory);
}
public static synchronized VirtualSocketFactory getDefaultSocketFactory()
throws InitializationException {
if (defaultFactory == null) {
defaultFactory = createSocketFactory();
}
return defaultFactory;
}
public static VirtualSocketFactory createSocketFactory()
throws InitializationException {
return createSocketFactory((java.util.Properties) null, true);
}
public static VirtualSocketFactory createSocketFactory(Map<String, ?> p,
boolean addDefaults) throws InitializationException {
return createSocketFactory(new TypedProperties(p), addDefaults);
}
public static VirtualSocketFactory createSocketFactory(
java.util.Properties properties, boolean addDefaults)
throws InitializationException {
TypedProperties typedProperties = new TypedProperties();
if (addDefaults) {
typedProperties.putAll(SmartSocketsProperties
.getDefaultProperties());
}
if (properties != null) {
typedProperties.putAll(properties);
}
if (typedProperties.booleanProperty(SmartSocketsProperties.START_HUB,
false)) {
boolean allowSSHForHub = typedProperties.booleanProperty(
SmartSocketsProperties.HUB_SSH_ALLOWED, true);
if (allowSSHForHub) {
typedProperties.setProperty(SmartSocketsProperties.SSH_IN,
"true");
// Do we need this one ?
// typedProperties.setProperty(SmartSocketsProperties.SSH_OUT,
// "true");
}
}
VirtualSocketFactory factory = new VirtualSocketFactory(
DirectSocketFactory.getSocketFactory(typedProperties),
typedProperties);
return factory;
}
public VirtualSocketAddress getLocalVirtual() {
return localVirtualAddress;
}
public String getVirtualAddressAsString() {
return localVirtualAddressAsString;
}
public void printStatistics(String prefix) {
if (statslogger.isInfoEnabled()) {
statslogger.info(prefix + " === VirtualSocketFactory ("
+ modules.size() + " / "
+ (serviceLink == null ? "No SL" : "SL") + ") ===");
for (ConnectModule c : modules) {
c.printStatistics(prefix);
}
if (serviceLink != null) {
serviceLink.printStatistics(prefix);
}
}
}
}
|
git-svn-id: http://gforge.cs.vu.nl/svn/ibis/smartsockets/trunk@13464 aaf88347-d911-0410-b711-e54d386773bb
| src/ibis/smartsockets/virtual/VirtualSocketFactory.java | <ide><path>rc/ibis/smartsockets/virtual/VirtualSocketFactory.java
<ide> import ibis.smartsockets.virtual.modules.AcceptHandler;
<ide> import ibis.smartsockets.virtual.modules.ConnectModule;
<ide> import ibis.smartsockets.virtual.modules.direct.Direct;
<del>import ibis.smartsockets.virtual.modules.hubrouted.Hubrouted;
<del>import ibis.smartsockets.virtual.modules.reverse.Reverse;
<del>import ibis.smartsockets.virtual.modules.splice.Splice;
<ide> import ibis.smartsockets.util.ThreadPool;
<ide>
<ide> import java.io.IOException;
<ide>
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<del>
<del>import com.sun.java_cup.internal.runtime.virtual_parse_stack;
<ide>
<ide> /**
<ide> * This class implements a virtual socket factory.
<ide> */
<ide> public final class VirtualSocketFactory {
<ide>
<add> /**
<add> * An inner class the prints connection statistics at a regular interval.
<add> */
<ide> private static class StatisticsPrinter implements Runnable {
<ide>
<ide> private int timeout;
<ide> private VirtualSocketFactory factory;
<ide> private String prefix;
<ide>
<del> StatisticsPrinter(VirtualSocketFactory factory, int timeout,
<del> String prefix) {
<add> StatisticsPrinter(final VirtualSocketFactory factory, final int timeout,
<add> final String prefix) {
<ide> this.timeout = timeout;
<ide> this.factory = factory;
<ide> this.prefix = prefix;
<ide> synchronized (this) {
<ide> wait(t);
<ide> }
<del> } catch (Exception e) {
<add> } catch (InterruptedException e) {
<ide> // ignore
<ide> }
<ide>
<ide> try {
<ide> factory.printStatistics(prefix);
<ide> } catch (Exception e) {
<del> // TODO: IGNORE ?
<add> logger.warn("Failed to print statistics", e);
<ide> }
<ide> }
<ide> }
<ide> return timeout;
<ide> }
<ide>
<del> public synchronized void adjustInterval(int interval) {
<add> public synchronized void adjustInterval(final int interval) {
<ide> timeout = interval;
<ide> notifyAll();
<ide> }
<ide>
<ide> private static VirtualSocketFactory defaultFactory = null;
<ide>
<del>
<add> /** Generic logger for this class. */
<ide> protected static final Logger logger =
<ide> LoggerFactory.getLogger("ibis.smartsockets.virtual.misc");
<ide>
<add> /** Logger for connection related logging. */
<ide> protected static final Logger conlogger =
<ide> LoggerFactory.getLogger("ibis.smartsockets.virtual.connect");
<ide>
<ide>
<ide> private StatisticsPrinter printer = null;
<ide>
<add> /**
<add> * An innerclass that accepts incoming connections for a hub.
<add> *
<add> * Only used when hub delegation is active: a hub and VirtualSocketFactory
<add> * are running in the same process and share one contact address. This is
<add> * only used in special server processes (such as the Ibis Registry).
<add> */
<ide> private static class HubAcceptor implements AcceptHandler {
<ide>
<ide> private final Hub hub;
<ide> }
<ide> }
<ide>
<del> private void startHub(TypedProperties p) throws InitializationException {
<add> private void startHub(TypedProperties p)
<add> throws InitializationException {
<ide>
<ide> if (p.booleanProperty(SmartSocketsProperties.START_HUB, false)) {
<ide>
<ide> return null;
<ide> }
<ide>
<del> private void loadModule(String name) throws Exception {
<add> private void loadModule(final String name) throws Exception {
<ide>
<ide> ConnectModule m = instantiateModule(name);
<ide> m.init(this, name, properties, logger);
<ide> return timeout;
<ide> }
<ide>
<add> /**
<add> * Retrieve an array of the available connection modules.
<add> * @return array of available connection modules.
<add> */
<ide> protected ConnectModule[] getModules() {
<ide> return modules.toArray(new ConnectModule[modules.size()]);
<ide> }
<ide>
<add> /**
<add> * Retrieve an array of the available connection modules whose names are
<add> * listed in names.
<add> *
<add> * @param names set of modules that may be returned.
<add> * @return array of available connection modules whose name was included in
<add> * names.
<add> */
<ide> protected ConnectModule[] getModules(String[] names) {
<ide>
<ide> ArrayList<ConnectModule> tmp = new ArrayList<ConnectModule>();
<ide> failed.clear();
<ide> }
<ide>
<add> /**
<add> * Retrieve VirtualServerSocket that is bound to given port.
<add> *
<add> * @param port port for which to retrieve VirtualServerSocket.
<add> * @return VirtualServerSocket bound to port, or null if port is not in use.
<add> */
<ide> public VirtualServerSocket getServerSocket(int port) {
<ide> synchronized (serverSockets) {
<ide> return serverSockets.get(port);
<ide> }
<ide> }
<ide>
<add> /**
<add> * Retrieve the ConnectModule with a given name.
<add> *
<add> * @param name name of requested ConnectModule.
<add> * @return ConnectModule bound to name, or null is this name is not in use.
<add> */
<ide> public ConnectModule findModule(String name) {
<ide>
<ide> // Direct is special, since it may be loaded without being part of the
<ide> return null;
<ide> }
<ide>
<del> public static void close(VirtualSocket s, OutputStream out, InputStream in) {
<add> /**
<add> * Close a VirtualSocket and its related I/O Streams while ignoring
<add> * exceptions.
<add> *
<add> * @param s VirtualSocket to close (may be null).
<add> * @param out OutputStream to close (may be null).
<add> * @param in InputStream to close (may be null).
<add> */
<add> public static void close(VirtualSocket s, OutputStream out,
<add> InputStream in) {
<ide>
<ide> try {
<ide> if (out != null) {
<ide> out.close();
<ide> }
<ide> } catch (Throwable e) {
<del> // ignore
<add> logger.info("Failed to close OutputStream", e);
<ide> }
<ide>
<ide> try {
<ide> in.close();
<ide> }
<ide> } catch (Throwable e) {
<del> // ignore
<add> logger.info("Failed to close InputStream", e);
<ide> }
<ide>
<ide> try {
<ide> s.close();
<ide> }
<ide> } catch (Throwable e) {
<del> // ignore
<del> }
<del> }
<del>
<add> logger.info("Failed to close Socket", e);
<add> }
<add> }
<add>
<add> /**
<add> * Close a VirtualSocket and its related SocketChannel while ignoring
<add> * exceptions.
<add> *
<add> * @param s VirtualSocket to close (may be null).
<add> * @param channel SocketChannel to close (may be null).
<add> */
<ide> public static void close(VirtualSocket s, SocketChannel channel) {
<ide>
<ide> if (channel != null) {
<ide> try {
<ide> channel.close();
<ide> } catch (Exception e) {
<del> // ignore
<add> logger.info("Failed to close SocketChannel", e);
<ide> }
<ide> }
<ide>
<ide> try {
<ide> s.close();
<ide> } catch (Exception e) {
<del> // ignore
<del> }
<del> }
<del> }
<del>
<del> // This method implements a connect using a specific module. This method
<del> // will return null when:
<del> //
<del> // - runtime requirements do not match
<del> // - the module throws a NonFatalIOException
<del> //
<del> // When a connection is succesfully establed, we wait for a accept from the
<del> // remote. There are three possible outcomes:
<del> //
<del> // - the connection is accepted in time
<del> // - the connection is not accepted in time or the connection is lost
<del> // - the remote side is overloaded and closes the connection
<del> //
<del> // In the first case the newly created socket is returned and in the second
<del> // case an exception is thrown. In the last case the connection will be
<del> // retried using a backoff mechanism until 'timeleft' (the total timeout
<del> // specified by the user) is spend. Each new try behaves exactly the same as
<del> // the previous attempts.
<add> logger.info("Failed to close Socket", e);
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * This method implements a connect using a specific module.
<add> *
<add> * This method will return null when:
<add> * <p>
<add> * - runtime requirements do not match
<add> * - the module throws a NonFatalIOException
<add> * <p>
<add> * When a connection is successfully established, we wait for a accept from
<add> * the remote side. There are three possible outcomes:
<add> * <p>
<add> * - the connection is accepted in time
<add> * - the connection is not accepted in time or the connection is lost
<add> * - the remote side is overloaded and closes the connection
<add> * <p>
<add> * In the first case the newly created socket is returned and in the second
<add> * case an exception is thrown. In the last case the connection will be
<add> * retried using a backoff mechanism until 'timeleft' (the total timeout
<add> * specified by the user) is spend. Each new try behaves exactly the same as
<add> * the previous attempts.
<add> *
<add> * @param m ConnectModule to use in connection attempt.
<add> * @param target Target VirtualServerSocket.
<add> * @param timeout Timeout to use for this specific attempt.
<add> * @param timeLeft Total timeout left.
<add> * @param fillTimeout Should we retry until the timeout expires ?
<add> * @param properties Properties to use in connection setup.
<add> * @return a VirtualSocket if the connection setup succeeded, null
<add> * otherwise.
<add> * @throws IOException a non-transient error occured (i.e., target port does
<add> * not exist).
<add> * @throws NonFatalIOException a transient error occured (i.e., timeout).
<add> */
<ide> private VirtualSocket createClientSocket(ConnectModule m,
<ide> VirtualSocketAddress target, int timeout, int timeLeft,
<ide> boolean fillTimeout, Map<String, Object> properties)
<ide> return names;
<ide> }
<ide>
<del> // This method loops over and array of connection modules, trying to setup
<del> // a connection with each of them each in turn. Returns when:
<del> // - a connection is established
<del> // - a non-transient error occurs (i.e. remote port not found)
<del> // - all modules have failed
<del> // - a timeout occurred
<del> //
<add> /**
<add> * This method loops over and array of connection modules, trying to setup
<add> * a connection with each of them each in turn.
<add> * <p>
<add> * This method returns when:<br>
<add> * - a connection is established<b>
<add> * - a non-transient error occurs (i.e. remote port not found)<b>
<add> * - all modules have failed<b>
<add> * - a timeout occurred<b>
<add> *
<add> * @param target Target VirtualServerSocket.
<add> * @param order ConnectModules in the order in which they should be tried.
<add> * @param timeouts Timeouts for each of the modules.
<add> * @param totalTimeout Total timeout for the connection setup.
<add> * @param timing Array in which to record the time required by each module.
<add> * @param fillTimeout Should we retry until the timeout expires ?
<add> * @param properties Properties to use in connection setup.
<add> * @return a VirtualSocket if the connection setup succeeded, null
<add> * otherwise.
<add> * @throws IOException a non-transient error occurred (i.e., target port
<add> * does not exist on receiver).
<add> * @throws NoSuitableModuleException No module could create the connection.
<add> */
<ide> private VirtualSocket createClientSocket(VirtualSocketAddress target,
<ide> ConnectModule[] order, int[] timeouts, int totalTimeout,
<ide> long[] timing, boolean fillTimeout, Map<String, Object> prop)
<ide> return timeouts;
<ide> }
<ide>
<add> /**
<add> * Create a connection to the VirtualServerSocket at target.
<add> *
<add> * This method will attempt to setup a connection to the VirtualServerSocket
<add> * at target within the given timeout. Using the prop parameter, properties
<add> * can be specified that modify the connection setup behavior.
<add> *
<add> * @param target Address of target VirtualServerSocket.
<add> * @param timeout The maximum timeout for the connection setup in
<add> * milliseconds. When the timeout is zero the call may block indefinitely,
<add> * while a negative timeout will revert to the default value.
<add> * @param prop Properties that modify the connection setup behavior (may be
<add> * null).
<add> * @return a VirtualSocket when the connection setup was successful.
<add> * @throws IOException when the connection setup failed.
<add> */
<ide> public VirtualSocket createClientSocket(VirtualSocketAddress target,
<ide> int timeout, Map<String, Object> prop) throws IOException {
<ide> return createClientSocket(target, timeout, false, prop);
<ide> }
<ide>
<add> /**
<add> * Create a connection to the VirtualServerSocket at target.
<add> *
<add> * This method will attempt to setup a connection to the VirtualServerSocket
<add> * at target within the given timeout. Using the prop parameter, properties
<add> * can be specified that modify the connection setup behavior.
<add> *
<add> * @param target Address of target VirtualServerSocket.
<add> * @param timeout The maximum timeout for the connection setup in
<add> * milliseconds. When the timeout is zero the call may block indefinitely,
<add> * while a negative timeout will revert to the default value.
<add> * @param fillTimeout Should we retry until the timeout expires ?
<add> * @param prop Properties that modify the connection setup behavior (may be
<add> * null).
<add> * @return a VirtualSocket when the connection setup was successful.
<add> * @throws IOException when the connection setup failed.
<add> */
<ide> public VirtualSocket createClientSocket(VirtualSocketAddress target,
<ide> int timeout, boolean fillTimeout, Map<String, Object> prop)
<ide> throws IOException {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Create a new VirtualServerSocket bound the the given port.
<add> *
<add> * This method will create a new VirtualServerSocket bound the the given,
<add> * and using the specified backlog. If port is zero or negative, a valid
<add> * unused port number will be generated. If the backlog is zero or negative,
<add> * the default value will be used.
<add> * <p>
<add> * The properties parameter used to modify the connection setup behavior of
<add> * the new VirtualServerSocket.
<add> *
<add> * @param port The port number to use.
<add> * @param backlog The maximum number of pending connections this
<add> * VirtualServerSocket will allow.
<add> * @param retry Retry if the VirtualServerSocket creation fails.
<add> * @param properties Properties that modify the connection setup behavior
<add> * (may be null).
<add> * @return the new VirtualServerSocket, or null if the creation failed.
<add> */
<ide> public VirtualServerSocket createServerSocket(int port, int backlog,
<ide> boolean retry, java.util.Properties properties) {
<ide>
<ide> return result;
<ide> }
<ide>
<del> public VirtualServerSocket createServerSocket(Map<String, Object> properties)
<add> /**
<add> * Create a new unbound VirtualServerSocket.
<add> *
<add> * This method will create a new VirtualServerSocket that is not yet bound
<add> * to a port.
<add> * <p>
<add> * The properties parameter used to modify the connection setup behavior of
<add> * the new VirtualServerSocket.
<add> *
<add> * @param props Properties that modify the connection setup behavior
<add> * (may be null).
<add> * @return the new VirtualServerSocket.
<add> * @throws IOException the VirtualServerSocket creation has failed.
<add> */
<add> public VirtualServerSocket createServerSocket(Map<String, Object> props)
<ide> throws IOException {
<del> return new VirtualServerSocket(this, DEFAULT_ACCEPT_TIMEOUT, properties);
<del> }
<del>
<add> return new VirtualServerSocket(this, DEFAULT_ACCEPT_TIMEOUT, props);
<add> }
<add>
<add> /**
<add> * Bind an unbound VirtualServerSocket to a port.
<add> *
<add> * @param vss The VirtualServerSocket to bind to the port.
<add> * @param port The port to bind the VirtualServerSocket to.
<add> * @throws BindException Failed to bind the port to the VirtualServerSocket.
<add> */
<ide> protected void bindServerSocket(VirtualServerSocket vss, int port)
<ide> throws BindException {
<ide>
<ide> }
<ide> }
<ide>
<add> /**
<add> * Create a new VirtualServerSocket bound the the given port.
<add> *
<add> * This method will create a new VirtualServerSocket bound the the given,
<add> * and using the specified backlog. If port is zero or negative, a valid
<add> * unused port number will be generated. If the backlog is zero or negative,
<add> * the default value will be used.
<add> * <p>
<add> * The properties parameter used to modify the connection setup behavior of
<add> * the new VirtualServerSocket.
<add> *
<add> * @param port The port number to use.
<add> * @param backlog The maximum number of pending connections this
<add> * VirtualServerSocket will allow.
<add> * @param properties Properties that modify the connection setup behavior
<add> * (may be null).
<add> * @return the new VirtualServerSocket, or null if the creation failed.
<add> */
<add>
<add>
<ide> public VirtualServerSocket createServerSocket(int port, int backlog,
<ide> Map<String, Object> properties) throws IOException {
<ide>
<ide> }
<ide>
<ide> // TODO: hide this thing ?
<add> /**
<add> * Retrieve the ServiceLink that is connected to the hub.
<add> * @return the ServiceLink that is connected to the Hub
<add> */
<ide> public ServiceLink getServiceLink() {
<ide> return serviceLink;
<ide> }
<ide>
<add> /**
<add> * Retrieve the DirectSocketAddress of this machine.
<add> * @return the DirectSocketAddress of this machine.
<add> */
<ide> public DirectSocketAddress getLocalHost() {
<ide> return myAddresses;
<ide> }
<ide>
<add> /**
<add> * Retrieve the name of the local cluster.
<add> * @return the name of the local cluster.
<add> */
<ide> public String getLocalCluster() {
<ide> return clusters.localCluster();
<ide> }
<ide>
<add> /**
<add> * Retrieve the DirectSocketAddress of the hub this VirtualSocketFactory is
<add> * connected to.
<add> * @return the DirectSocketAddress of the hub this VirtualSocketFactory is
<add> * connected to.
<add> */
<ide> public DirectSocketAddress getLocalHub() {
<ide> return hubAddress;
<ide> }
<ide>
<add> /**
<add> * Provide a list of hub addresses to the VirtualSocketFactory.
<add> * @param hubs The hub addresses.
<add> */
<ide> public void addHubs(DirectSocketAddress... hubs) {
<ide> if (hub != null) {
<ide> hub.addHubs(hubs);
<ide> }
<ide> }
<ide>
<add> /**
<add> * Provide a list of hub addresses to the VirtualSocketFactory.
<add> * @param hubs The hub addresses.
<add> */
<ide> public void addHubs(String... hubs) {
<ide> if (hub != null) {
<ide> hub.addHubs(hubs);
<ide> }
<ide> }
<ide>
<add> /**
<add> * Retrieve the known hub addresses.
<add> * @return an array containing the known hub addresses.
<add> */
<ide> public DirectSocketAddress[] getKnownHubs() {
<ide>
<ide> if (hub != null) {
<ide> return null;
<ide> }
<ide>
<add> /**
<add> * Shutdown the VirtualSocketFactory.
<add> */
<ide> public void end() {
<ide>
<ide> if (printer != null) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Close a port.
<add> * @param port the port to close.
<add> */
<ide> protected void closed(int port) {
<ide> synchronized (serverSockets) {
<ide> serverSockets.remove(Integer.valueOf(port));
<ide> }
<ide> }
<ide>
<del> public static synchronized VirtualSocketFactory getSocketFactory(String name) {
<add> /**
<add> * Retrieve a previously created (and configured) VirtualSocketFactory.
<add> *
<add> * @param name the VirtualSocketFactory to retrieve.
<add> * @return the VirtualSocketFactory, or null if it does not exist.
<add> */
<add> public static synchronized VirtualSocketFactory getSocketFactory(
<add> String name) {
<ide>
<ide> return factories.get(name);
<ide> }
<ide>
<add>
<add> /**
<add> * Get a VirtualSocketFactory, either by retrieving or by creating it.
<add> *
<add> * If the VirtualSocketFactory already existed, the provided properties will
<add> * be compared to those of the existing VirtualSocketFactory to ensure that
<add> * they are the same. If they are not, an InitializationException will be
<add> * thrown.
<add> * <p>
<add> * If the VirtualSocketFactory did not exist, it will be created and stored
<add> * under name for later lookup.
<add> *
<add> * @param name the name of the VirtualSocketFactory to retrieve or create.
<add> * @param p A set of properties that configure the VirtualSocketFactory.
<add> * @param addDefaults Add the default properties to the configuration.
<add> * @return the retrieved or created VirtualSocketFactory.
<add> * @throws InitializationException if the VirtualSocketFactory could not be
<add> * created or received.
<add> */
<ide> public static synchronized VirtualSocketFactory getOrCreateSocketFactory(
<ide> String name, java.util.Properties p, boolean addDefaults)
<ide> throws InitializationException {
<ide> return result;
<ide> }
<ide>
<add> /**
<add> * Register an existing VirtualSocketFactory under a different name.
<add> * @param name The name to register the VirtualSocketFactory.
<add> * @param factory The VirtualSocketFactory to register.
<add> */
<ide> public static synchronized void registerSocketFactory(String name,
<ide> VirtualSocketFactory factory) {
<ide> factories.put(name, factory);
<ide> }
<ide>
<add> /**
<add> * Retrieve a VirtualSocketFactory using the default configuration.
<add> *
<add> * @return a VirtualSocketFactory using the default configuration.
<add> * @throws InitializationException the VirtualSocketFactory could not be
<add> * retrieved.
<add> */
<ide> public static synchronized VirtualSocketFactory getDefaultSocketFactory()
<ide> throws InitializationException {
<ide>
<ide> return defaultFactory;
<ide> }
<ide>
<add> /**
<add> * Create a VirtualSocketFactory using the default configuration.
<add> *
<add> * @return a VirtualSocketFactory using the default configuration.
<add> * @throws InitializationException the VirtualSocketFactory could not be
<add> * created.
<add> */
<ide> public static VirtualSocketFactory createSocketFactory()
<ide> throws InitializationException {
<ide>
<ide> return createSocketFactory((java.util.Properties) null, true);
<ide> }
<ide>
<add> /**
<add> * Create a VirtualSocketFactory using the configuration provided in p.
<add> *
<add> * @param p the configuration to use (as a key-value map).
<add> * @param addDefaults Should the default configuration be added ?
<add> * @return a VirtualSocketFactory using the configuration in p.
<add> * @throws InitializationException the VirtualSocketFactory could not be
<add> * created.
<add> */
<ide> public static VirtualSocketFactory createSocketFactory(Map<String, ?> p,
<ide> boolean addDefaults) throws InitializationException {
<ide> return createSocketFactory(new TypedProperties(p), addDefaults);
<ide> }
<ide>
<add> /**
<add> * Create a VirtualSocketFactory using the configuration provided in
<add> * properties.
<add> *
<add> * @param properties the configuration to use.
<add> * @param addDefaults Should the default configuration be added ?
<add> * @return a VirtualSocketFactory using the configuration in properties.
<add> * @throws InitializationException the VirtualSocketFactory could not be
<add> * created.
<add> */
<ide> public static VirtualSocketFactory createSocketFactory(
<ide> java.util.Properties properties, boolean addDefaults)
<ide> throws InitializationException {
<ide> return factory;
<ide> }
<ide>
<add> /**
<add> * Retrieve the contact address of this VirtualSocketFactory.
<add> *
<add> * @return a VirtualSocketAddress containing the contact address of this
<add> * VirtualSocketFactory.
<add> */
<ide> public VirtualSocketAddress getLocalVirtual() {
<ide> return localVirtualAddress;
<ide> }
<ide>
<add> /**
<add> * Retrieve the contact address of this VirtualSocketFactory.
<add> *
<add> * @return a String containing the contact address of this
<add> * VirtualSocketFactory.
<add> */
<ide> public String getVirtualAddressAsString() {
<ide> return localVirtualAddressAsString;
<ide> }
<ide>
<add> /**
<add> * Print statistics on the connections created by this VirtualSocketFactory.
<add> *
<add> * Every line printed will prepended with the given prefix.
<add> *
<add> * @param prefix the prefix to use when printing.
<add> */
<ide> public void printStatistics(String prefix) {
<ide>
<ide> if (statslogger.isInfoEnabled()) { |
||
Java | apache-2.0 | 1f53c5fb9253cd72cf2e0876ead483f2cefa2e98 | 0 | Netflix/Priam | /**
* Copyright 2017 Netflix, Inc.
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.priam.aws;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration.Rule;
import com.amazonaws.services.s3.model.CompleteMultipartUploadResult;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.RateLimiter;
import com.google.inject.Provider;
import com.netflix.priam.backup.AbstractBackupPath;
import com.netflix.priam.backup.AbstractFileSystem;
import com.netflix.priam.backup.BackupRestoreException;
import com.netflix.priam.compress.ICompression;
import com.netflix.priam.config.IConfiguration;
import com.netflix.priam.merics.BackupMetrics;
import com.netflix.priam.notification.BackupNotificationMgr;
import com.netflix.priam.scheduler.BlockingSubmitThreadPoolExecutor;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class S3FileSystemBase extends AbstractFileSystem {
private static final int MAX_CHUNKS = 10000;
static final long MAX_BUFFERED_IN_STREAM_SIZE = 5 * 1024 * 1024;
private static final Logger logger = LoggerFactory.getLogger(S3FileSystemBase.class);
AmazonS3 s3Client;
final IConfiguration config;
final ICompression compress;
final BlockingSubmitThreadPoolExecutor executor;
// a throttling mechanism, we can limit the amount of bytes uploaded to endpoint per second.
final RateLimiter rateLimiter;
S3FileSystemBase(
Provider<AbstractBackupPath> pathProvider,
ICompression compress,
final IConfiguration config,
BackupMetrics backupMetrics,
BackupNotificationMgr backupNotificationMgr) {
super(config, backupMetrics, backupNotificationMgr, pathProvider);
this.compress = compress;
this.config = config;
int threads = config.getBackupThreads();
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(threads);
this.executor =
new BlockingSubmitThreadPoolExecutor(threads, queue, config.getUploadTimeout());
double throttleLimit = config.getUploadThrottle();
this.rateLimiter = RateLimiter.create(throttleLimit < 1 ? Double.MAX_VALUE : throttleLimit);
}
private AmazonS3 getS3Client() {
return s3Client;
}
/*
* A means to change the default handle to the S3 client.
*/
public void setS3Client(AmazonS3 client) {
s3Client = client;
}
@Override
public void cleanup() {
AmazonS3 s3Client = getS3Client();
String clusterPath = pathProvider.get().clusterPrefix("");
logger.debug("Bucket: {}", config.getBackupPrefix());
BucketLifecycleConfiguration lifeConfig =
s3Client.getBucketLifecycleConfiguration(config.getBackupPrefix());
logger.debug("Got bucket:{} lifecycle.{}", config.getBackupPrefix(), lifeConfig);
if (lifeConfig == null) {
lifeConfig = new BucketLifecycleConfiguration();
List<Rule> rules = Lists.newArrayList();
lifeConfig.setRules(rules);
}
List<Rule> rules = lifeConfig.getRules();
if (updateLifecycleRule(config, rules, clusterPath)) {
if (rules.size() > 0) {
lifeConfig.setRules(rules);
s3Client.setBucketLifecycleConfiguration(config.getBackupPrefix(), lifeConfig);
} else s3Client.deleteBucketLifecycleConfiguration(config.getBackupPrefix());
}
}
private boolean updateLifecycleRule(IConfiguration config, List<Rule> rules, String prefix) {
Rule rule = null;
for (BucketLifecycleConfiguration.Rule lcRule : rules) {
if (lcRule.getPrefix().equals(prefix)) {
rule = lcRule;
break;
}
}
if (rule == null && config.getBackupRetentionDays() <= 0) return false;
if (rule != null && rule.getExpirationInDays() == config.getBackupRetentionDays()) {
logger.info("Cleanup rule already set");
return false;
}
if (rule == null) {
// Create a new rule
rule =
new BucketLifecycleConfiguration.Rule()
.withExpirationInDays(config.getBackupRetentionDays())
.withPrefix(prefix);
rule.setStatus(BucketLifecycleConfiguration.ENABLED);
rule.setId(prefix);
rules.add(rule);
logger.info(
"Setting cleanup for {} to {} days",
rule.getPrefix(),
rule.getExpirationInDays());
} else if (config.getBackupRetentionDays() > 0) {
logger.info(
"Setting cleanup for {} to {} days",
rule.getPrefix(),
config.getBackupRetentionDays());
rule.setExpirationInDays(config.getBackupRetentionDays());
} else {
logger.info("Removing cleanup rule for {}", rule.getPrefix());
rules.remove(rule);
}
return true;
}
void checkSuccessfulUpload(
CompleteMultipartUploadResult resultS3MultiPartUploadComplete, Path localPath)
throws BackupRestoreException {
if (null != resultS3MultiPartUploadComplete
&& null != resultS3MultiPartUploadComplete.getETag()) {
logger.info(
"Uploaded file: {}, object eTag: {}",
localPath,
resultS3MultiPartUploadComplete.getETag());
} else {
throw new BackupRestoreException(
"Error uploading file as ETag or CompleteMultipartUploadResult is NULL -"
+ localPath);
}
}
@Override
public long getFileSize(Path remotePath) throws BackupRestoreException {
return s3Client.getObjectMetadata(getShard(), remotePath.toString()).getContentLength();
}
@Override
public boolean doesRemoteFileExist(Path remotePath) throws BackupRestoreException {
boolean exists = false;
try {
exists = s3Client.doesObjectExist(getShard(), remotePath.toString());
} catch (AmazonClientException ex) {
// No point throwing this exception up.
logger.error(
"Exception while checking existence of object: {}. Error: {}",
remotePath,
ex.getMessage());
}
return exists;
}
@Override
public void shutdown() {
if (executor != null) executor.shutdown();
}
@Override
public Iterator<String> listFileSystem(String prefix, String delimiter, String marker) {
return new S3Iterator(s3Client, getShard(), prefix, delimiter, marker);
}
@Override
public void deleteRemoteFiles(List<Path> remotePaths) throws BackupRestoreException {
if (remotePaths.isEmpty()) return;
try {
List<DeleteObjectsRequest.KeyVersion> keys =
remotePaths
.stream()
.map(
remotePath ->
new DeleteObjectsRequest.KeyVersion(
remotePath.toString()))
.collect(Collectors.toList());
s3Client.deleteObjects(
new DeleteObjectsRequest(getShard()).withKeys(keys).withQuiet(true));
logger.info("Deleted {} objects from S3", remotePaths.size());
} catch (Exception e) {
logger.error("Error while trying to delete the objects from S3: {}", e.getMessage());
throw new BackupRestoreException(e + " while trying to delete the objects");
}
}
final long getChunkSize(Path localPath) throws BackupRestoreException {
long chunkSize = config.getBackupChunkSize();
long fileSize = localPath.toFile().length();
// compute the size of each block we will upload to endpoint
if (fileSize > 0)
chunkSize =
(fileSize / chunkSize >= MAX_CHUNKS)
? (fileSize / (MAX_CHUNKS - 1))
: chunkSize;
return chunkSize;
}
}
| priam/src/main/java/com/netflix/priam/aws/S3FileSystemBase.java | /**
* Copyright 2017 Netflix, Inc.
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.priam.aws;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration.Rule;
import com.amazonaws.services.s3.model.CompleteMultipartUploadResult;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.RateLimiter;
import com.google.inject.Provider;
import com.netflix.priam.backup.AbstractBackupPath;
import com.netflix.priam.backup.AbstractFileSystem;
import com.netflix.priam.backup.BackupRestoreException;
import com.netflix.priam.compress.ICompression;
import com.netflix.priam.config.IConfiguration;
import com.netflix.priam.merics.BackupMetrics;
import com.netflix.priam.notification.BackupNotificationMgr;
import com.netflix.priam.scheduler.BlockingSubmitThreadPoolExecutor;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class S3FileSystemBase extends AbstractFileSystem {
private static final int MAX_CHUNKS = 10000;
static final long MAX_BUFFERED_IN_STREAM_SIZE = 5 * 1024 * 1024;
private static final Logger logger = LoggerFactory.getLogger(S3FileSystemBase.class);
AmazonS3 s3Client;
final IConfiguration config;
final ICompression compress;
final BlockingSubmitThreadPoolExecutor executor;
// a throttling mechanism, we can limit the amount of bytes uploaded to endpoint per second.
final RateLimiter rateLimiter;
S3FileSystemBase(
Provider<AbstractBackupPath> pathProvider,
ICompression compress,
final IConfiguration config,
BackupMetrics backupMetrics,
BackupNotificationMgr backupNotificationMgr) {
super(config, backupMetrics, backupNotificationMgr, pathProvider);
this.compress = compress;
this.config = config;
int threads = config.getBackupThreads();
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(threads);
this.executor =
new BlockingSubmitThreadPoolExecutor(threads, queue, config.getUploadTimeout());
double throttleLimit = config.getUploadThrottle();
this.rateLimiter = RateLimiter.create(throttleLimit < 1 ? Double.MAX_VALUE : throttleLimit);
}
private AmazonS3 getS3Client() {
return s3Client;
}
/*
* A means to change the default handle to the S3 client.
*/
public void setS3Client(AmazonS3 client) {
s3Client = client;
}
@Override
public void cleanup() {
AmazonS3 s3Client = getS3Client();
String clusterPath = pathProvider.get().clusterPrefix("");
logger.debug("Bucket: {}", config.getBackupPrefix());
BucketLifecycleConfiguration lifeConfig =
s3Client.getBucketLifecycleConfiguration(config.getBackupPrefix());
logger.debug("Got bucket:{} lifecycle.{}", config.getBackupPrefix(), lifeConfig);
if (lifeConfig == null) {
lifeConfig = new BucketLifecycleConfiguration();
List<Rule> rules = Lists.newArrayList();
lifeConfig.setRules(rules);
}
List<Rule> rules = lifeConfig.getRules();
if (updateLifecycleRule(config, rules, clusterPath)) {
if (rules.size() > 0) {
lifeConfig.setRules(rules);
s3Client.setBucketLifecycleConfiguration(config.getBackupPrefix(), lifeConfig);
} else s3Client.deleteBucketLifecycleConfiguration(config.getBackupPrefix());
}
}
private boolean updateLifecycleRule(IConfiguration config, List<Rule> rules, String prefix) {
Rule rule = null;
for (BucketLifecycleConfiguration.Rule lcRule : rules) {
if (lcRule.getPrefix().equals(prefix)) {
rule = lcRule;
break;
}
}
if (rule == null && config.getBackupRetentionDays() <= 0) return false;
if (rule != null && rule.getExpirationInDays() == config.getBackupRetentionDays()) {
logger.info("Cleanup rule already set");
return false;
}
if (rule == null) {
// Create a new rule
rule =
new BucketLifecycleConfiguration.Rule()
.withExpirationInDays(config.getBackupRetentionDays())
.withPrefix(prefix);
rule.setStatus(BucketLifecycleConfiguration.ENABLED);
rule.setId(prefix);
rules.add(rule);
logger.info(
"Setting cleanup for {} to {} days",
rule.getPrefix(),
rule.getExpirationInDays());
} else if (config.getBackupRetentionDays() > 0) {
logger.info(
"Setting cleanup for {} to {} days",
rule.getPrefix(),
config.getBackupRetentionDays());
rule.setExpirationInDays(config.getBackupRetentionDays());
} else {
logger.info("Removing cleanup rule for {}", rule.getPrefix());
rules.remove(rule);
}
return true;
}
void checkSuccessfulUpload(
CompleteMultipartUploadResult resultS3MultiPartUploadComplete, Path localPath)
throws BackupRestoreException {
if (null != resultS3MultiPartUploadComplete
&& null != resultS3MultiPartUploadComplete.getETag()) {
logger.info(
"Uploaded file: {}, object eTag: {}",
localPath,
resultS3MultiPartUploadComplete.getETag());
} else {
throw new BackupRestoreException(
"Error uploading file as ETag or CompleteMultipartUploadResult is NULL -"
+ localPath);
}
}
@Override
public long getFileSize(Path remotePath) throws BackupRestoreException {
return s3Client.getObjectMetadata(getShard(), remotePath.toString()).getContentLength();
}
@Override
public boolean doesRemoteFileExist(Path remotePath) throws BackupRestoreException {
boolean exists = false;
try {
exists = s3Client.doesObjectExist(getShard(), remotePath.toString());
} catch (Exception ex) {
// No point throwing this exception up.
logger.error(
"Exception while checking existence of object: {}. Error: {}",
remotePath,
ex.getMessage());
}
return exists;
}
@Override
public void shutdown() {
if (executor != null) executor.shutdown();
}
@Override
public Iterator<String> listFileSystem(String prefix, String delimiter, String marker) {
return new S3Iterator(s3Client, getShard(), prefix, delimiter, marker);
}
@Override
public void deleteRemoteFiles(List<Path> remotePaths) throws BackupRestoreException {
if (remotePaths.isEmpty()) return;
try {
List<DeleteObjectsRequest.KeyVersion> keys =
remotePaths
.stream()
.map(
remotePath ->
new DeleteObjectsRequest.KeyVersion(
remotePath.toString()))
.collect(Collectors.toList());
s3Client.deleteObjects(
new DeleteObjectsRequest(getShard()).withKeys(keys).withQuiet(true));
logger.info("Deleted {} objects from S3", remotePaths.size());
} catch (Exception e) {
logger.error("Error while trying to delete the objects from S3: {}", e.getMessage());
throw new BackupRestoreException(e + " while trying to delete the objects");
}
}
final long getChunkSize(Path localPath) throws BackupRestoreException {
long chunkSize = config.getBackupChunkSize();
long fileSize = localPath.toFile().length();
// compute the size of each block we will upload to endpoint
if (fileSize > 0)
chunkSize =
(fileSize / chunkSize >= MAX_CHUNKS)
? (fileSize / (MAX_CHUNKS - 1))
: chunkSize;
return chunkSize;
}
}
| Change the exception scope
| priam/src/main/java/com/netflix/priam/aws/S3FileSystemBase.java | Change the exception scope | <ide><path>riam/src/main/java/com/netflix/priam/aws/S3FileSystemBase.java
<ide> */
<ide> package com.netflix.priam.aws;
<ide>
<add>import com.amazonaws.AmazonClientException;
<ide> import com.amazonaws.services.s3.AmazonS3;
<ide> import com.amazonaws.services.s3.model.BucketLifecycleConfiguration;
<ide> import com.amazonaws.services.s3.model.BucketLifecycleConfiguration.Rule;
<ide> boolean exists = false;
<ide> try {
<ide> exists = s3Client.doesObjectExist(getShard(), remotePath.toString());
<del> } catch (Exception ex) {
<add> } catch (AmazonClientException ex) {
<ide> // No point throwing this exception up.
<ide> logger.error(
<ide> "Exception while checking existence of object: {}. Error: {}", |
|
Java | apache-2.0 | 20ddcbc13808fc98ff0b4b7fcb3cda6614bbd012 | 0 | petteyg/intellij-community,diorcety/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,adedayo/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,fnouama/intellij-community,retomerz/intellij-community,da1z/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,caot/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,ryano144/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,supersven/intellij-community,supersven/intellij-community,hurricup/intellij-community,holmes/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,allotria/intellij-community,joewalnes/idea-community,allotria/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,semonte/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,jexp/idea2,allotria/intellij-community,Distrotech/intellij-community,samthor/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,clumsy/intellij-community,vladmm/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,fnouama/intellij-community,adedayo/intellij-community,da1z/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,signed/intellij-community,hurricup/intellij-community,supersven/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,slisson/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,kdwink/intellij-community,hurricup/intellij-community,fnouama/intellij-community,dslomov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,blademainer/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,apixandru/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,izonder/intellij-community,signed/intellij-community,slisson/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,caot/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,jexp/idea2,xfournet/intellij-community,samthor/intellij-community,semonte/intellij-community,dslomov/intellij-community,semonte/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,xfournet/intellij-community,petteyg/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,kdwink/intellij-community,da1z/intellij-community,ernestp/consulo,michaelgallacher/intellij-community,robovm/robovm-studio,da1z/intellij-community,apixandru/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,semonte/intellij-community,consulo/consulo,ryano144/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,semonte/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,kdwink/intellij-community,consulo/consulo,kool79/intellij-community,xfournet/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,robovm/robovm-studio,da1z/intellij-community,izonder/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ibinti/intellij-community,slisson/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,izonder/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,signed/intellij-community,izonder/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,jexp/idea2,da1z/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,hurricup/intellij-community,consulo/consulo,nicolargo/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,fitermay/intellij-community,xfournet/intellij-community,supersven/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,kool79/intellij-community,ernestp/consulo,vladmm/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,signed/intellij-community,jexp/idea2,allotria/intellij-community,holmes/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,asedunov/intellij-community,robovm/robovm-studio,slisson/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,caot/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,suncycheng/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,signed/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,izonder/intellij-community,kool79/intellij-community,allotria/intellij-community,tmpgit/intellij-community,signed/intellij-community,caot/intellij-community,asedunov/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,dslomov/intellij-community,jexp/idea2,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,amith01994/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,adedayo/intellij-community,kool79/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,holmes/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,supersven/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,consulo/consulo,ibinti/intellij-community,kdwink/intellij-community,blademainer/intellij-community,semonte/intellij-community,robovm/robovm-studio,fitermay/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,fnouama/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,holmes/intellij-community,holmes/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,apixandru/intellij-community,supersven/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,blademainer/intellij-community,kool79/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,signed/intellij-community,FHannes/intellij-community,fitermay/intellij-community,amith01994/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,fnouama/intellij-community,jagguli/intellij-community,clumsy/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,hurricup/intellij-community,diorcety/intellij-community,allotria/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,xfournet/intellij-community,slisson/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,kdwink/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,supersven/intellij-community,clumsy/intellij-community,clumsy/intellij-community,kool79/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,holmes/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,ernestp/consulo,fnouama/intellij-community,fnouama/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,kool79/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,da1z/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,FHannes/intellij-community,caot/intellij-community,apixandru/intellij-community,hurricup/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,holmes/intellij-community,asedunov/intellij-community,ryano144/intellij-community,adedayo/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,retomerz/intellij-community,fnouama/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,jexp/idea2,blademainer/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,samthor/intellij-community,kool79/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,amith01994/intellij-community,blademainer/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,samthor/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ernestp/consulo,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,caot/intellij-community,allotria/intellij-community,amith01994/intellij-community,asedunov/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,izonder/intellij-community,jexp/idea2,consulo/consulo,apixandru/intellij-community,lucafavatella/intellij-community,signed/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,dslomov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,signed/intellij-community,petteyg/intellij-community,petteyg/intellij-community,consulo/consulo,fitermay/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ernestp/consulo,semonte/intellij-community,izonder/intellij-community,Distrotech/intellij-community,slisson/intellij-community,adedayo/intellij-community,supersven/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,fnouama/intellij-community,ibinti/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,kool79/intellij-community,dslomov/intellij-community,slisson/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,samthor/intellij-community,jexp/idea2,akosyakov/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,semonte/intellij-community,robovm/robovm-studio,amith01994/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,robovm/robovm-studio,gnuhub/intellij-community | package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupItemUtil;
import com.intellij.codeInsight.template.*;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* @author ven
*/
public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreatePropertyFromUsageFix");
@NonNls private static final String FIELD_VARIABLE = "FIELD_NAME_VARIABLE";
@NonNls private static final String TYPE_VARIABLE = "FIELD_TYPE_VARIABLE";
@NonNls private static final String GET_PREFIX = "get";
@NonNls private static final String IS_PREFIX = "is";
@NonNls private static final String SET_PREFIX = "set";
public CreatePropertyFromUsageFix(PsiMethodCallExpression methodCall) {
myMethodCall = methodCall;
}
private final PsiMethodCallExpression myMethodCall;
@NotNull
public String getFamilyName() {
return QuickFixBundle.message("create.property.from.usage.family");
}
protected PsiElement getElement() {
if (!myMethodCall.isValid() || !myMethodCall.getManager().isInProject(myMethodCall)) return null;
return myMethodCall;
}
protected boolean isAvailableImpl(int offset) {
if (CreateMethodFromUsageFix.hasErrorsInArgumentList(myMethodCall)) return false;
PsiReferenceExpression ref = myMethodCall.getMethodExpression();
String methodName = myMethodCall.getMethodExpression().getReferenceName();
LOG.assertTrue(methodName != null);
String propertyName = PropertyUtil.getPropertyName(methodName);
if (propertyName == null || propertyName.length() == 0) return false;
String getterOrSetter = null;
if (methodName.startsWith(GET_PREFIX) || methodName.startsWith(IS_PREFIX)) {
if (myMethodCall.getArgumentList().getExpressions().length != 0) return false;
getterOrSetter = QuickFixBundle.message("create.getter");
}
else if (methodName.startsWith(SET_PREFIX)) {
if (myMethodCall.getArgumentList().getExpressions().length != 1) return false;
getterOrSetter = QuickFixBundle.message("create.setter");
}
else {
LOG.error("Internal error in create property intention");
}
List<PsiClass> classes = getTargetClasses(myMethodCall);
if (classes.isEmpty()) return false;
for (PsiClass aClass : classes) {
if (!aClass.isInterface()) {
if (CreateFromUsageUtils.shouldShowTag(offset, ref.getReferenceNameElement(), myMethodCall)) {
setText(getterOrSetter);
return true;
}
else {
return false;
}
}
}
return false;
}
static class FieldExpression extends Expression {
private String myDefaultFieldName;
private final PsiField myField;
private final PsiClass myClass;
private final PsiType[] myExpectedTypes;
public FieldExpression(PsiField field, PsiClass aClass, PsiType[] expectedTypes) {
myField = field;
myClass = aClass;
myExpectedTypes = expectedTypes;
myDefaultFieldName = field.getName();
}
public Result calculateResult(ExpressionContext context) {
return new TextResult(myDefaultFieldName);
}
public Result calculateQuickResult(ExpressionContext context) {
return new TextResult(myDefaultFieldName);
}
public LookupElement[] calculateLookupItems(ExpressionContext context) {
Set<LookupItem> set = new LinkedHashSet<LookupItem>();
LookupItemUtil.addLookupItem(set, myField);
PsiField[] fields = myClass.getFields();
for (PsiField otherField : fields) {
if (!myDefaultFieldName.equals(otherField.getName())) {
PsiType otherType = otherField.getType();
for (PsiType type : myExpectedTypes) {
if (type.equals(otherType)) {
LookupItemUtil.addLookupItem(set, otherField);
}
}
}
}
if (set.size() < 2) return null;
return set.toArray(new LookupItem[set.size()]);
}
}
@NotNull
protected List<PsiClass> getTargetClasses(PsiElement element) {
List<PsiClass> all = super.getTargetClasses(element);
if (all.isEmpty()) return all;
List<PsiClass> nonInterfaces = new ArrayList<PsiClass>();
for (PsiClass aClass : all) {
if (!aClass.isInterface()) nonInterfaces.add(aClass);
}
return nonInterfaces;
}
protected void invokeImpl(PsiClass targetClass) {
PsiManager manager = myMethodCall.getManager();
final Project project = manager.getProject();
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
boolean isStatic = false;
PsiExpression qualifierExpression = myMethodCall.getMethodExpression().getQualifierExpression();
if (qualifierExpression != null) {
PsiReference reference = qualifierExpression.getReference();
if (reference != null) {
isStatic = reference.resolve() instanceof PsiClass;
}
}
else {
PsiMethod method = PsiTreeUtil.getParentOfType(myMethodCall, PsiMethod.class);
if (method != null) {
isStatic = method.hasModifierProperty(PsiModifier.STATIC);
}
}
String fieldName = getVariableName(myMethodCall, isStatic);
LOG.assertTrue(fieldName != null);
String callText = myMethodCall.getMethodExpression().getReferenceName();
LOG.assertTrue(callText != null, myMethodCall.getMethodExpression());
PsiType[] expectedTypes;
PsiType type;
if (callText.startsWith(GET_PREFIX)) {
expectedTypes = CreateFromUsageUtils.guessType(myMethodCall, false);
type = expectedTypes[0];
}
else if (callText.startsWith(IS_PREFIX)) {
type = PsiType.BOOLEAN;
expectedTypes = new PsiType[]{type};
}
else {
type = myMethodCall.getArgumentList().getExpressions()[0].getType();
if (type == null || type == PsiType.NULL) type = PsiType.getJavaLangObject(manager, myMethodCall.getResolveScope());
expectedTypes = new PsiType[]{type};
}
positionCursor(project, targetClass.getContainingFile(), targetClass);
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
try {
PsiField field = targetClass.findFieldByName(fieldName, true);
if (field == null) {
field = factory.createField(fieldName, type);
field.getModifierList().setModifierProperty(PsiModifier.STATIC, isStatic);
}
PsiMethod accessor;
PsiElement fieldReference;
PsiElement typeReference;
PsiCodeBlock body;
if (callText.startsWith(GET_PREFIX) || callText.startsWith(IS_PREFIX)) {
accessor = (PsiMethod)targetClass.add(PropertyUtil.generateGetterPrototype(field));
body = accessor.getBody();
LOG.assertTrue(body != null, accessor.getText());
fieldReference = ((PsiReturnStatement)body.getStatements()[0]).getReturnValue();
typeReference = accessor.getReturnTypeElement();
}
else {
accessor = (PsiMethod)targetClass.add(PropertyUtil.generateSetterPrototype(field, targetClass));
body = accessor.getBody();
LOG.assertTrue(body != null, accessor.getText());
PsiAssignmentExpression expr = (PsiAssignmentExpression)((PsiExpressionStatement)body.getStatements()[0]).getExpression();
fieldReference = ((PsiReferenceExpression)expr.getLExpression()).getReferenceNameElement();
typeReference = accessor.getParameterList().getParameters()[0].getTypeElement();
}
accessor.setName(callText);
accessor.getModifierList().setModifierProperty(PsiModifier.STATIC, isStatic);
TemplateBuilder builder = new TemplateBuilder(accessor);
builder.replaceElement(typeReference, TYPE_VARIABLE, new TypeExpression(project, expectedTypes), true);
builder.replaceElement(fieldReference, FIELD_VARIABLE, new FieldExpression(field, targetClass, expectedTypes), true);
builder.setEndVariableAfter(body.getLBrace());
accessor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(accessor);
targetClass = accessor.getContainingClass();
LOG.assertTrue(targetClass != null);
Template template = builder.buildTemplate();
TextRange textRange = accessor.getTextRange();
final PsiFile file = targetClass.getContainingFile();
final Editor editor = positionCursor(project, targetClass.getContainingFile(), accessor);
editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
editor.getCaretModel().moveToOffset(textRange.getStartOffset());
final boolean isStatic1 = isStatic;
startTemplate(editor, template, project, new TemplateEditingAdapter() {
public void beforeTemplateFinished(final TemplateState state, Template template) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
String fieldName = state.getVariableValue(FIELD_VARIABLE).getText();
if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(fieldName)) return;
String fieldType = state.getVariableValue(TYPE_VARIABLE).getText();
PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
if (aClass == null) return;
if (aClass.findFieldByName(fieldName, true) != null) return;
PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
try {
PsiType type = factory.createTypeFromText(fieldType, aClass);
try {
PsiField field = factory.createField(fieldName, type);
field = (PsiField)aClass.add(field);
field.getModifierList().setModifierProperty(PsiModifier.STATIC, isStatic1);
positionCursor(project, field.getContainingFile(), field);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
catch (IncorrectOperationException e) {
}
}
});
}
});
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private static String getVariableName(PsiMethodCallExpression methodCall, boolean isStatic) {
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(methodCall.getProject());
String methodName = methodCall.getMethodExpression().getReferenceName();
String propertyName = PropertyUtil.getPropertyName(methodName);
if (propertyName != null && propertyName.length() > 0) {
VariableKind kind = isStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD;
return codeStyleManager.propertyNameToVariableName(propertyName, kind);
}
return null;
}
protected boolean isValidElement(PsiElement element) {
PsiMethodCallExpression methodCall = (PsiMethodCallExpression) element;
return methodCall.getMethodExpression().resolve() != null;
}
}
| codeInsight/impl/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java | package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupItemUtil;
import com.intellij.codeInsight.template.*;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* @author ven
*/
public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreatePropertyFromUsageFix");
@NonNls private static final String FIELD_VARIABLE = "FIELD_NAME_VARIABLE";
@NonNls private static final String TYPE_VARIABLE = "FIELD_TYPE_VARIABLE";
@NonNls private static final String GET_PREFIX = "get";
@NonNls private static final String IS_PREFIX = "is";
@NonNls private static final String SET_PREFIX = "set";
public CreatePropertyFromUsageFix(PsiMethodCallExpression methodCall) {
myMethodCall = methodCall;
}
private final PsiMethodCallExpression myMethodCall;
@NotNull
public String getFamilyName() {
return QuickFixBundle.message("create.property.from.usage.family");
}
protected PsiElement getElement() {
if (!myMethodCall.isValid() || !myMethodCall.getManager().isInProject(myMethodCall)) return null;
return myMethodCall;
}
protected boolean isAvailableImpl(int offset) {
if (CreateMethodFromUsageFix.hasErrorsInArgumentList(myMethodCall)) return false;
PsiReferenceExpression ref = myMethodCall.getMethodExpression();
String methodName = myMethodCall.getMethodExpression().getReferenceName();
LOG.assertTrue(methodName != null);
String propertyName = PropertyUtil.getPropertyName(methodName);
if (propertyName == null || propertyName.length() == 0) return false;
String getterOrSetter = null;
if (methodName.startsWith(GET_PREFIX) || methodName.startsWith(IS_PREFIX)) {
if (myMethodCall.getArgumentList().getExpressions().length != 0) return false;
getterOrSetter = QuickFixBundle.message("create.getter");
}
else if (methodName.startsWith(SET_PREFIX)) {
if (myMethodCall.getArgumentList().getExpressions().length != 1) return false;
getterOrSetter = QuickFixBundle.message("create.setter");
}
else {
LOG.error("Internal error in create property intention");
}
List<PsiClass> classes = getTargetClasses(myMethodCall);
if (classes.isEmpty()) return false;
for (PsiClass aClass : classes) {
if (!aClass.isInterface()) {
if (CreateFromUsageUtils.shouldShowTag(offset, ref.getReferenceNameElement(), myMethodCall)) {
setText(getterOrSetter);
return true;
}
else {
return false;
}
}
}
return false;
}
static class FieldExpression extends Expression {
private LookupItem[] myItems;
private String myDefaultFieldName;
public FieldExpression(PsiField field, PsiClass aClass, PsiType[] expectedTypes) {
String fieldName = field.getName();
Set<LookupItem> set = new LinkedHashSet<LookupItem>();
LookupItemUtil.addLookupItem(set, field);
PsiField[] fields = aClass.getFields();
for (PsiField otherField : fields) {
if (!fieldName.equals(otherField.getName())) {
PsiType otherType = otherField.getType();
for (PsiType type : expectedTypes) {
if (type.equals(otherType)) {
LookupItemUtil.addLookupItem(set, otherField);
}
}
}
}
myDefaultFieldName = fieldName;
myItems = set.toArray(new LookupItem[set.size()]);
}
public Result calculateResult(ExpressionContext context) {
return new TextResult(myDefaultFieldName);
}
public Result calculateQuickResult(ExpressionContext context) {
return new TextResult(myDefaultFieldName);
}
public LookupElement[] calculateLookupItems(ExpressionContext context) {
if (myItems.length < 2) return null;
return myItems;
}
}
@NotNull
protected List<PsiClass> getTargetClasses(PsiElement element) {
List<PsiClass> all = super.getTargetClasses(element);
if (all.isEmpty()) return all;
List<PsiClass> nonInterfaces = new ArrayList<PsiClass>();
for (PsiClass aClass : all) {
if (!aClass.isInterface()) nonInterfaces.add(aClass);
}
return nonInterfaces;
}
protected void invokeImpl(PsiClass targetClass) {
PsiManager manager = myMethodCall.getManager();
final Project project = manager.getProject();
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
boolean isStatic = false;
PsiExpression qualifierExpression = myMethodCall.getMethodExpression().getQualifierExpression();
if (qualifierExpression != null) {
PsiReference reference = qualifierExpression.getReference();
if (reference != null) {
isStatic = reference.resolve() instanceof PsiClass;
}
}
else {
PsiMethod method = PsiTreeUtil.getParentOfType(myMethodCall, PsiMethod.class);
if (method != null) {
isStatic = method.hasModifierProperty(PsiModifier.STATIC);
}
}
String fieldName = getVariableName(myMethodCall, isStatic);
LOG.assertTrue(fieldName != null);
String callText = myMethodCall.getMethodExpression().getReferenceName();
LOG.assertTrue(callText != null, myMethodCall.getMethodExpression());
PsiType[] expectedTypes;
PsiType type;
if (callText.startsWith(GET_PREFIX)) {
expectedTypes = CreateFromUsageUtils.guessType(myMethodCall, false);
type = expectedTypes[0];
}
else if (callText.startsWith(IS_PREFIX)) {
type = PsiType.BOOLEAN;
expectedTypes = new PsiType[]{type};
}
else {
type = myMethodCall.getArgumentList().getExpressions()[0].getType();
if (type == null || type == PsiType.NULL) type = PsiType.getJavaLangObject(manager, myMethodCall.getResolveScope());
expectedTypes = new PsiType[]{type};
}
positionCursor(project, targetClass.getContainingFile(), targetClass);
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
try {
PsiField field = targetClass.findFieldByName(fieldName, true);
if (field == null) {
field = factory.createField(fieldName, type);
field.getModifierList().setModifierProperty(PsiModifier.STATIC, isStatic);
}
PsiMethod accessor;
PsiElement fieldReference;
PsiElement typeReference;
PsiCodeBlock body;
if (callText.startsWith(GET_PREFIX) || callText.startsWith(IS_PREFIX)) {
accessor = (PsiMethod)targetClass.add(PropertyUtil.generateGetterPrototype(field));
body = accessor.getBody();
LOG.assertTrue(body != null, accessor.getText());
fieldReference = ((PsiReturnStatement)body.getStatements()[0]).getReturnValue();
typeReference = accessor.getReturnTypeElement();
}
else {
accessor = (PsiMethod)targetClass.add(PropertyUtil.generateSetterPrototype(field, targetClass));
body = accessor.getBody();
LOG.assertTrue(body != null, accessor.getText());
PsiAssignmentExpression expr = (PsiAssignmentExpression)((PsiExpressionStatement)body.getStatements()[0]).getExpression();
fieldReference = ((PsiReferenceExpression)expr.getLExpression()).getReferenceNameElement();
typeReference = accessor.getParameterList().getParameters()[0].getTypeElement();
}
accessor.setName(callText);
accessor.getModifierList().setModifierProperty(PsiModifier.STATIC, isStatic);
TemplateBuilder builder = new TemplateBuilder(accessor);
builder.replaceElement(typeReference, TYPE_VARIABLE, new TypeExpression(project, expectedTypes), true);
builder.replaceElement(fieldReference, FIELD_VARIABLE, new FieldExpression(field, targetClass, expectedTypes), true);
builder.setEndVariableAfter(body.getLBrace());
accessor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(accessor);
targetClass = accessor.getContainingClass();
LOG.assertTrue(targetClass != null);
Template template = builder.buildTemplate();
TextRange textRange = accessor.getTextRange();
final PsiFile file = targetClass.getContainingFile();
final Editor editor = positionCursor(project, targetClass.getContainingFile(), accessor);
editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
editor.getCaretModel().moveToOffset(textRange.getStartOffset());
final boolean isStatic1 = isStatic;
startTemplate(editor, template, project, new TemplateEditingAdapter() {
public void beforeTemplateFinished(final TemplateState state, Template template) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
String fieldName = state.getVariableValue(FIELD_VARIABLE).getText();
if (!JavaPsiFacade.getInstance(project).getNameHelper().isIdentifier(fieldName)) return;
String fieldType = state.getVariableValue(TYPE_VARIABLE).getText();
PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
if (aClass == null) return;
if (aClass.findFieldByName(fieldName, true) != null) return;
PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
try {
PsiType type = factory.createTypeFromText(fieldType, aClass);
try {
PsiField field = factory.createField(fieldName, type);
field = (PsiField)aClass.add(field);
field.getModifierList().setModifierProperty(PsiModifier.STATIC, isStatic1);
positionCursor(project, field.getContainingFile(), field);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
catch (IncorrectOperationException e) {
}
}
});
}
});
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private static String getVariableName(PsiMethodCallExpression methodCall, boolean isStatic) {
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(methodCall.getProject());
String methodName = methodCall.getMethodExpression().getReferenceName();
String propertyName = PropertyUtil.getPropertyName(methodName);
if (propertyName != null && propertyName.length() > 0) {
VariableKind kind = isStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD;
return codeStyleManager.propertyNameToVariableName(propertyName, kind);
}
return null;
}
protected boolean isValidElement(PsiElement element) {
PsiMethodCallExpression methodCall = (PsiMethodCallExpression) element;
return methodCall.getMethodExpression().resolve() != null;
}
}
| IDEADEV-30711 assert: LookupImpl.addItem
| codeInsight/impl/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java | IDEADEV-30711 assert: LookupImpl.addItem | <ide><path>odeInsight/impl/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java
<ide> }
<ide>
<ide> static class FieldExpression extends Expression {
<del> private LookupItem[] myItems;
<ide> private String myDefaultFieldName;
<add> private final PsiField myField;
<add> private final PsiClass myClass;
<add> private final PsiType[] myExpectedTypes;
<ide>
<ide> public FieldExpression(PsiField field, PsiClass aClass, PsiType[] expectedTypes) {
<del> String fieldName = field.getName();
<add> myField = field;
<add> myClass = aClass;
<add> myExpectedTypes = expectedTypes;
<add> myDefaultFieldName = field.getName();
<add> }
<add>
<add> public Result calculateResult(ExpressionContext context) {
<add> return new TextResult(myDefaultFieldName);
<add> }
<add>
<add> public Result calculateQuickResult(ExpressionContext context) {
<add> return new TextResult(myDefaultFieldName);
<add> }
<add>
<add> public LookupElement[] calculateLookupItems(ExpressionContext context) {
<ide> Set<LookupItem> set = new LinkedHashSet<LookupItem>();
<del> LookupItemUtil.addLookupItem(set, field);
<del> PsiField[] fields = aClass.getFields();
<add> LookupItemUtil.addLookupItem(set, myField);
<add> PsiField[] fields = myClass.getFields();
<ide> for (PsiField otherField : fields) {
<del> if (!fieldName.equals(otherField.getName())) {
<add> if (!myDefaultFieldName.equals(otherField.getName())) {
<ide> PsiType otherType = otherField.getType();
<del> for (PsiType type : expectedTypes) {
<add> for (PsiType type : myExpectedTypes) {
<ide> if (type.equals(otherType)) {
<ide> LookupItemUtil.addLookupItem(set, otherField);
<ide> }
<ide> }
<ide> }
<ide> }
<del> myDefaultFieldName = fieldName;
<del> myItems = set.toArray(new LookupItem[set.size()]);
<del> }
<del>
<del> public Result calculateResult(ExpressionContext context) {
<del> return new TextResult(myDefaultFieldName);
<del> }
<del>
<del> public Result calculateQuickResult(ExpressionContext context) {
<del> return new TextResult(myDefaultFieldName);
<del> }
<del>
<del> public LookupElement[] calculateLookupItems(ExpressionContext context) {
<del> if (myItems.length < 2) return null;
<del> return myItems;
<add>
<add> if (set.size() < 2) return null;
<add> return set.toArray(new LookupItem[set.size()]);
<ide> }
<ide> }
<ide> |
|
Java | mit | 005f3ac189f6c06d082b31f61c1bccda1b0428f8 | 0 | tschechlovdev/jabref,grimes2/jabref,mairdl/jabref,mredaelli/jabref,Siedlerchr/jabref,Siedlerchr/jabref,mairdl/jabref,oscargus/jabref,motokito/jabref,tobiasdiez/jabref,mairdl/jabref,Braunch/jabref,jhshinn/jabref,zellerdev/jabref,ayanai1/jabref,Siedlerchr/jabref,sauliusg/jabref,obraliar/jabref,obraliar/jabref,tobiasdiez/jabref,mredaelli/jabref,oscargus/jabref,grimes2/jabref,Mr-DLib/jabref,Braunch/jabref,jhshinn/jabref,sauliusg/jabref,obraliar/jabref,obraliar/jabref,obraliar/jabref,mredaelli/jabref,Siedlerchr/jabref,oscargus/jabref,zellerdev/jabref,mredaelli/jabref,sauliusg/jabref,ayanai1/jabref,mairdl/jabref,tschechlovdev/jabref,ayanai1/jabref,shitikanth/jabref,Braunch/jabref,motokito/jabref,ayanai1/jabref,tschechlovdev/jabref,shitikanth/jabref,tschechlovdev/jabref,shitikanth/jabref,bartsch-dev/jabref,shitikanth/jabref,bartsch-dev/jabref,ayanai1/jabref,zellerdev/jabref,grimes2/jabref,bartsch-dev/jabref,shitikanth/jabref,tobiasdiez/jabref,mredaelli/jabref,tobiasdiez/jabref,Mr-DLib/jabref,Mr-DLib/jabref,jhshinn/jabref,Braunch/jabref,Braunch/jabref,grimes2/jabref,grimes2/jabref,Mr-DLib/jabref,motokito/jabref,Mr-DLib/jabref,tschechlovdev/jabref,oscargus/jabref,jhshinn/jabref,JabRef/jabref,JabRef/jabref,sauliusg/jabref,bartsch-dev/jabref,JabRef/jabref,motokito/jabref,bartsch-dev/jabref,jhshinn/jabref,mairdl/jabref,JabRef/jabref,oscargus/jabref,motokito/jabref,zellerdev/jabref,zellerdev/jabref | package net.sf.jabref.logic.journals;
import org.junit.Assert;
import org.junit.Test;
public class ShippedJournalAbbreviationDuplicateTest {
@Test
public void noDuplicatesInShippedJournalAbbreviations() {
JournalAbbreviationRepository repoBuiltIn = new JournalAbbreviationRepository();
repoBuiltIn.readJournalListFromResource(Abbreviations.JOURNALS_FILE_BUILTIN);
JournalAbbreviationRepository repoBuiltInIEEEOfficial = new JournalAbbreviationRepository();
repoBuiltInIEEEOfficial.readJournalListFromResource(Abbreviations.JOURNALS_IEEE_ABBREVIATION_LIST_WITH_CODE);
JournalAbbreviationRepository repoBuiltInIEEEStandard = new JournalAbbreviationRepository();
repoBuiltInIEEEStandard.readJournalListFromResource(Abbreviations.JOURNALS_IEEE_ABBREVIATION_LIST_WITH_TEXT);
for(Abbreviation abbreviation : repoBuiltInIEEEOfficial.getAbbreviations()) {
Assert.assertFalse("duplicate name " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getName()).isPresent());
Assert.assertFalse("duplicate iso " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getIsoAbbreviation()).isPresent());
Assert.assertFalse("duplicate medline " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getMedlineAbbreviation()).isPresent());
}
for(Abbreviation abbreviation : repoBuiltInIEEEStandard.getAbbreviations()) {
Assert.assertFalse("duplicate name " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getName()).isPresent());
Assert.assertFalse("duplicate iso " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getIsoAbbreviation()).isPresent());
Assert.assertFalse("duplicate medline " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getMedlineAbbreviation()).isPresent());
}
}
}
| src/test/java/net/sf/jabref/logic/journals/ShippedJournalAbbreviationDuplicateTest.java | package net.sf.jabref.logic.journals;
import junit.framework.Assert;
import org.junit.Test;
public class ShippedJournalAbbreviationDuplicateTest {
@Test
public void noDuplicatesInShippedJournalAbbreviations() {
JournalAbbreviationRepository repoBuiltIn = new JournalAbbreviationRepository();
repoBuiltIn.readJournalListFromResource(Abbreviations.JOURNALS_FILE_BUILTIN);
JournalAbbreviationRepository repoBuiltInIEEEOfficial = new JournalAbbreviationRepository();
repoBuiltInIEEEOfficial.readJournalListFromResource(Abbreviations.JOURNALS_IEEE_ABBREVIATION_LIST_WITH_CODE);
JournalAbbreviationRepository repoBuiltInIEEEStandard = new JournalAbbreviationRepository();
repoBuiltInIEEEStandard.readJournalListFromResource(Abbreviations.JOURNALS_IEEE_ABBREVIATION_LIST_WITH_TEXT);
for(Abbreviation abbreviation : repoBuiltInIEEEOfficial.getAbbreviations()) {
Assert.assertFalse("duplicate name " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getName()).isPresent());
Assert.assertFalse("duplicate iso " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getIsoAbbreviation()).isPresent());
Assert.assertFalse("duplicate medline " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getMedlineAbbreviation()).isPresent());
}
for(Abbreviation abbreviation : repoBuiltInIEEEStandard.getAbbreviations()) {
Assert.assertFalse("duplicate name " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getName()).isPresent());
Assert.assertFalse("duplicate iso " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getIsoAbbreviation()).isPresent());
Assert.assertFalse("duplicate medline " + abbreviation.toString(), repoBuiltIn.getAbbreviation(abbreviation.getMedlineAbbreviation()).isPresent());
}
}
}
| Use correct import
| src/test/java/net/sf/jabref/logic/journals/ShippedJournalAbbreviationDuplicateTest.java | Use correct import | <ide><path>rc/test/java/net/sf/jabref/logic/journals/ShippedJournalAbbreviationDuplicateTest.java
<ide> package net.sf.jabref.logic.journals;
<ide>
<del>import junit.framework.Assert;
<add>import org.junit.Assert;
<ide> import org.junit.Test;
<ide>
<ide> public class ShippedJournalAbbreviationDuplicateTest { |
|
Java | lgpl-2.1 | 3594dfd4c773079290f9fbadcbd2683a90a19842 | 0 | dizzzz/exist,ambs/exist,ambs/exist,lcahlander/exist,lcahlander/exist,windauer/exist,lcahlander/exist,windauer/exist,eXist-db/exist,ambs/exist,eXist-db/exist,windauer/exist,adamretter/exist,wolfgangmm/exist,adamretter/exist,windauer/exist,lcahlander/exist,adamretter/exist,lcahlander/exist,adamretter/exist,wolfgangmm/exist,windauer/exist,eXist-db/exist,dizzzz/exist,adamretter/exist,windauer/exist,wolfgangmm/exist,eXist-db/exist,dizzzz/exist,eXist-db/exist,ambs/exist,wolfgangmm/exist,ambs/exist,dizzzz/exist,wolfgangmm/exist,lcahlander/exist,ambs/exist,wolfgangmm/exist,dizzzz/exist,dizzzz/exist,adamretter/exist,eXist-db/exist | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2016 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.repo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.storage.DBBroker;
import org.exist.storage.StartupTrigger;
import org.exist.storage.txn.Txn;
import org.exist.util.FileUtils;
import org.expath.pkg.repo.*;
/**
* Startup trigger for automatic deployment of application packages. Scans the "autodeploy" directory
* for .xar files. Installs any application which does not yet exist in the database.
*/
public class AutoDeploymentTrigger implements StartupTrigger {
private final static Logger LOG = LogManager.getLogger(AutoDeploymentTrigger.class);
public final static String AUTODEPLOY_DIRECTORY = "autodeploy";
public final static String AUTODEPLOY_PROPERTY = "exist.autodeploy";
public final static String AUTODEPLOY_DIRECTORY_PROPERTY = "exist.autodeploy.dir";
@Override
public void execute(final DBBroker sysBroker, final Txn transaction, final Map<String, List<? extends Object>> params) {
// do not process if the system property exist.autodeploy=off
final String property = System.getProperty(AUTODEPLOY_PROPERTY, "on");
if (property.equalsIgnoreCase("off")) {
return;
}
Path autodeployDir = Optional.ofNullable(System.getProperty(AUTODEPLOY_DIRECTORY_PROPERTY)).map(Paths::get).orElse(null);
if (autodeployDir == null) {
final Optional<Path> homeDir = sysBroker.getConfiguration().getExistHome();
autodeployDir = FileUtils.resolve(homeDir, AUTODEPLOY_DIRECTORY);
}
if (!Files.isReadable(autodeployDir) && Files.isDirectory(autodeployDir)) {
return;
}
try {
final List<Path> xars = Files
.find(autodeployDir, 1, (path, attrs) -> (!attrs.isDirectory()) && FileUtils.fileName(path).endsWith(".xar"))
.sorted(Comparator.comparing(Path::getFileName))
.collect(Collectors.toList());
LOG.info("Scanning autodeploy directory. Found " + xars.size() + " app packages.");
final Deployment deployment = new Deployment();
// build a map with uri -> file so we can resolve dependencies
final Map<String, Path> packages = new HashMap<>();
for (final Path xar : xars) {
try {
final Optional<String> name = deployment.getNameFromDescriptor(sysBroker, new XarFileSource(xar));
if(name.isPresent()) {
packages.put(name.get(), xar);
} else {
LOG.error("No descriptor name for: " + xar.toAbsolutePath().toString());
}
} catch (final IOException | PackageException e) {
LOG.error("Caught exception while reading app package " + xar.toAbsolutePath().toString(), e);
}
}
final PackageLoader loader = (name, version) -> {
// TODO: enforce version check
final Path p = packages.get(name);
if(p == null) {
return null;
}
return new XarFileSource(p);
};
for (final Path xar : xars) {
try {
deployment.installAndDeploy(sysBroker, transaction, new XarFileSource(xar), loader, false);
} catch (final PackageException | IOException e) {
LOG.error("Exception during deployment of app " + FileUtils.fileName(xar) + ": " + e.getMessage(), e);
sysBroker.getBrokerPool().reportStatus("An error occurred during app deployment: " + e.getMessage());
}
}
} catch(final IOException ioe) {
LOG.error(ioe);
}
}
}
| exist-core/src/main/java/org/exist/repo/AutoDeploymentTrigger.java | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2016 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.repo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.storage.DBBroker;
import org.exist.storage.StartupTrigger;
import org.exist.storage.txn.Txn;
import org.exist.util.FileUtils;
import org.expath.pkg.repo.*;
/**
* Startup trigger for automatic deployment of application packages. Scans the "autodeploy" directory
* for .xar files. Installs any application which does not yet exist in the database.
*/
public class AutoDeploymentTrigger implements StartupTrigger {
private final static Logger LOG = LogManager.getLogger(AutoDeploymentTrigger.class);
public final static String AUTODEPLOY_DIRECTORY = "autodeploy";
public final static String AUTODEPLOY_PROPERTY = "exist.autodeploy";
@Override
public void execute(final DBBroker sysBroker, final Txn transaction, final Map<String, List<? extends Object>> params) {
// do not process if the system property exist.autodeploy=off
final String property = System.getProperty(AUTODEPLOY_PROPERTY, "on");
if (property.equalsIgnoreCase("off")) {
return;
}
final Optional<Path> homeDir = sysBroker.getConfiguration().getExistHome();
final Path autodeployDir = FileUtils.resolve(homeDir, AUTODEPLOY_DIRECTORY);
if (!Files.isReadable(autodeployDir) && Files.isDirectory(autodeployDir)) {
return;
}
try {
final List<Path> xars = Files
.find(autodeployDir, 1, (path, attrs) -> (!attrs.isDirectory()) && FileUtils.fileName(path).endsWith(".xar"))
.sorted(Comparator.comparing(Path::getFileName))
.collect(Collectors.toList());
LOG.info("Scanning autodeploy directory. Found " + xars.size() + " app packages.");
final Deployment deployment = new Deployment();
// build a map with uri -> file so we can resolve dependencies
final Map<String, Path> packages = new HashMap<>();
for (final Path xar : xars) {
try {
final Optional<String> name = deployment.getNameFromDescriptor(sysBroker, new XarFileSource(xar));
if(name.isPresent()) {
packages.put(name.get(), xar);
} else {
LOG.error("No descriptor name for: " + xar.toAbsolutePath().toString());
}
} catch (final IOException | PackageException e) {
LOG.error("Caught exception while reading app package " + xar.toAbsolutePath().toString(), e);
}
}
final PackageLoader loader = (name, version) -> {
// TODO: enforce version check
final Path p = packages.get(name);
if(p == null) {
return null;
}
return new XarFileSource(p);
};
for (final Path xar : xars) {
try {
deployment.installAndDeploy(sysBroker, transaction, new XarFileSource(xar), loader, false);
} catch (final PackageException | IOException e) {
LOG.error("Exception during deployment of app " + FileUtils.fileName(xar) + ": " + e.getMessage(), e);
sysBroker.getBrokerPool().reportStatus("An error occurred during app deployment: " + e.getMessage());
}
}
} catch(final IOException ioe) {
LOG.error(ioe);
}
}
}
| [feature] Allow the autodeploy dir to be overriden by a system property: exist.autodeploy.dir
| exist-core/src/main/java/org/exist/repo/AutoDeploymentTrigger.java | [feature] Allow the autodeploy dir to be overriden by a system property: exist.autodeploy.dir | <ide><path>xist-core/src/main/java/org/exist/repo/AutoDeploymentTrigger.java
<ide> import java.io.IOException;
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<add>import java.nio.file.Paths;
<ide> import java.util.*;
<ide> import java.util.stream.Collectors;
<ide>
<ide> public final static String AUTODEPLOY_DIRECTORY = "autodeploy";
<ide>
<ide> public final static String AUTODEPLOY_PROPERTY = "exist.autodeploy";
<add> public final static String AUTODEPLOY_DIRECTORY_PROPERTY = "exist.autodeploy.dir";
<ide>
<ide> @Override
<ide> public void execute(final DBBroker sysBroker, final Txn transaction, final Map<String, List<? extends Object>> params) {
<ide> return;
<ide> }
<ide>
<del> final Optional<Path> homeDir = sysBroker.getConfiguration().getExistHome();
<del> final Path autodeployDir = FileUtils.resolve(homeDir, AUTODEPLOY_DIRECTORY);
<add> Path autodeployDir = Optional.ofNullable(System.getProperty(AUTODEPLOY_DIRECTORY_PROPERTY)).map(Paths::get).orElse(null);
<add> if (autodeployDir == null) {
<add> final Optional<Path> homeDir = sysBroker.getConfiguration().getExistHome();
<add> autodeployDir = FileUtils.resolve(homeDir, AUTODEPLOY_DIRECTORY);
<add> }
<add>
<ide> if (!Files.isReadable(autodeployDir) && Files.isDirectory(autodeployDir)) {
<ide> return;
<ide> } |
|
Java | bsd-3-clause | 180f8a83af68f5c94bcab3f3ae076d7ec80ee15b | 0 | NCIP/catissue-core,krishagni/openspecimen,asamgir/openspecimen,krishagni/openspecimen,NCIP/catissue-core,asamgir/openspecimen,asamgir/openspecimen,NCIP/catissue-core,krishagni/openspecimen | package edu.wustl.catissuecore.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.exception.UserNotAuthenticatedException;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.util.logger.Logger;
/**
* This is the base class for all other Actions. The class provides generic
* methods that are resuable by all subclasses. In addition, this class ensures
* that the user is authenticated before calling the executeWorkflow of the
* subclass. If the User is not authenticated then an
* UserNotAuthenticatedException is thrown.
*
* @author Aarti Sharma
*
*/
public abstract class BaseAction extends Action
{
/*
* Method ensures that the user is authenticated before calling the
* executeAction of the subclass. If the User is not authenticated then an
* UserNotAuthenticatedException is thrown.
*
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm,
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public final ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
/* The case of session time out */
if (getSessionData(request) == null)
{
//Forward to the Login
throw new UserNotAuthenticatedException();
}
setRequestData(request);
setSelectedMenu(request);
//Mandar 17-Apr-06 : 1667:- Application URL
Utility.setApplicationURL(request.getRequestURL().toString());
return executeAction(mapping, form, request, response);
}
protected void setRequestData(HttpServletRequest request)
{
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
if(operation!=null)
{
//Sets the operation attribute to be used in the Add/Edit User Page.
request.setAttribute(Constants.OPERATION, operation);
}
}
/**
* Returns the current User authenticated by CSM Authentication.
*/
protected String getUserLoginName(HttpServletRequest request)
{
SessionDataBean sessionData = getSessionData(request);
if(sessionData != null)
{
return sessionData.getUserName();
}
return null;
}
protected SessionDataBean getSessionData(HttpServletRequest request)
{
Object obj = request.getSession().getAttribute(Constants.SESSION_DATA);
if(obj!=null)
{
SessionDataBean sessionData = (SessionDataBean) obj;
return sessionData;
}
return null;
}
/**
* Subclasses should implement the action's business logic in this method
* and can be sure that an authenticated user is present.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
protected abstract ActionForward executeAction(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception;
protected void setSelectedMenu(HttpServletRequest request)
{
Logger.out.debug("Inside setSelectedMenu.....");
String strMenu = request.getParameter(Constants.MENU_SELECTED );
if(strMenu != null )
{
request.setAttribute(Constants.MENU_SELECTED ,strMenu);
Logger.out.debug(Constants.MENU_SELECTED + " " +strMenu +" set successfully");
}
}
/**
* This function checks call to the action and sets/removes required attributes if AddNew or ForwardTo activity is executing.
* @param request - HTTPServletRequest calling the action
*/
protected void checkAddNewOperation(HttpServletRequest request)
{
String submittedFor = (String) request.getAttribute(Constants.SUBMITTED_FOR);
Logger.out.debug("SubmittedFor in checkAddNewOperation()------------->"+submittedFor);
String submittedForParameter=(String)request.getParameter(Constants.SUBMITTED_FOR);
//if AddNew loop is going on
if( ( (submittedFor !=null)&& (submittedFor.equals("AddNew")) ) )
{
Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is AddNew in checkAddNewOperation() >>>>>>>>>>>>>");
//Storing SUBMITTED_FOR attribute into Request
request.setAttribute(Constants.SUBMITTED_FOR, Constants.SUBMITTED_FOR_ADD_NEW);
}
//if Page is submitted on same page
else if( (submittedForParameter !=null)&& (submittedForParameter.equals("AddNew")) )
{
Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor parameter is AddNew in checkAddNewOperation() >>>>>>>>>>>>>");
if( (submittedFor !=null)&& (submittedFor.equals("Default")) )
{
//Storing SUBMITTED_FOR attribute into Request
request.setAttribute(Constants.SUBMITTED_FOR, Constants.SUBMITTED_FOR_DEFAULT);
}
else
{
//Storing SUBMITTED_FOR attribute into Request
request.setAttribute(Constants.SUBMITTED_FOR, Constants.SUBMITTED_FOR_ADD_NEW);
}
}
//if ForwardTo request is submitted
else if((submittedFor !=null)&& (submittedFor.equals("ForwardTo")) )
{
Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is ForwardTo in checkAddNewOperation() >>>>>>>>>>>>>");
request.setAttribute(Constants.SUBMITTED_FOR,Constants.SUBMITTED_FOR_FORWARD_TO);
Logger.out.debug("<<<<<<<<<<<< Checking for FormBeanStack to remove in checkAddNewOperation() >>>>>>>>>>>>>");
HttpSession session = request.getSession();
if((session.getAttribute(Constants.FORM_BEAN_STACK)) !=null)
{
Logger.out.debug("Removing FormBeanStack from Session in checkAddNewOperation()............");
session.removeAttribute(Constants.FORM_BEAN_STACK);
}
}
//if AddNew loop is over
else if( (submittedFor !=null)&& (submittedFor.equals("Default")) )
{
Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is Default in checkAddNewOperation() >>>>>>>>>>>>>");
request.setAttribute(Constants.SUBMITTED_FOR,Constants.SUBMITTED_FOR_DEFAULT);
Logger.out.debug("<<<<<<<<<<<< Checking for FormBeanStack to remove in checkAddNewOperation() >>>>>>>>>>>>>");
HttpSession session = request.getSession();
if((session.getAttribute(Constants.FORM_BEAN_STACK)) !=null)
{
Logger.out.debug("Removing FormBeanStack from Session in checkAddNewOperation()............");
session.removeAttribute(Constants.FORM_BEAN_STACK);
}
}
//if AddNew or ForwardTo loop is broken...
else
{
Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is NULL in checkAddNewOperation() >>>>>>>>>>>>>");
Logger.out.debug("<<<<<<<<<<<< Checking for FormBeanStack to remove in checkAddNewOperation() >>>>>>>>>>>>>");
HttpSession session = request.getSession();
if((session.getAttribute(Constants.FORM_BEAN_STACK)) !=null)
{
Logger.out.debug("Removing FormBeanStack from Session in checkAddNewOperation()............");
session.removeAttribute(Constants.FORM_BEAN_STACK);
}
}
}
} | WEB-INF/src/edu/wustl/catissuecore/action/BaseAction.java | package edu.wustl.catissuecore.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.exception.UserNotAuthenticatedException;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.util.logger.Logger;
/**
* This is the base class for all other Actions. The class provides generic
* methods that are resuable by all subclasses. In addition, this class ensures
* that the user is authenticated before calling the executeWorkflow of the
* subclass. If the User is not authenticated then an
* UserNotAuthenticatedException is thrown.
*
* @author Aarti Sharma
*
*/
public abstract class BaseAction extends Action
{
/*
* Method ensures that the user is authenticated before calling the
* executeAction of the subclass. If the User is not authenticated then an
* UserNotAuthenticatedException is thrown.
*
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm,
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public final ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
/* The case of session time out */
if (getSessionData(request) == null)
{
//Forward to the Login
throw new UserNotAuthenticatedException();
}
setRequestData(request);
setSelectedMenu(request);
//Mandar 17-Apr-06 : 1667:- Application URL
Utility.setApplicationURL(request.getRequestURL().toString());
return executeAction(mapping, form, request, response);
}
protected void setRequestData(HttpServletRequest request)
{
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
if(operation!=null)
{
//Sets the operation attribute to be used in the Add/Edit User Page.
request.setAttribute(Constants.OPERATION, operation);
}
}
/**
* Returns the current User authenticated by CSM Authentication.
*/
protected String getUserLoginName(HttpServletRequest request)
{
SessionDataBean sessionData = getSessionData(request);
if(sessionData != null)
{
return sessionData.getUserName();
}
return null;
}
protected SessionDataBean getSessionData(HttpServletRequest request)
{
Object obj = request.getSession().getAttribute(Constants.SESSION_DATA);
if(obj!=null)
{
SessionDataBean sessionData = (SessionDataBean) obj;
return sessionData;
}
return null;
}
/**
* Subclasses should implement the action's business logic in this method
* and can be sure that an authenticated user is present.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
protected abstract ActionForward executeAction(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception;
protected void setSelectedMenu(HttpServletRequest request)
{
Logger.out.debug("Inside setSelectedMenu.....");
String strMenu = request.getParameter(Constants.MENU_SELECTED );
if(strMenu != null )
{
request.setAttribute(Constants.MENU_SELECTED ,strMenu);
Logger.out.debug(Constants.MENU_SELECTED + " " +strMenu +" set successfully");
}
}
} | added checkAddNewOperation() for AddNew functionality
SVN-Revision: 3358
| WEB-INF/src/edu/wustl/catissuecore/action/BaseAction.java | added checkAddNewOperation() for AddNew functionality | <ide><path>EB-INF/src/edu/wustl/catissuecore/action/BaseAction.java
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<add>import javax.servlet.http.HttpSession;
<ide>
<ide> import org.apache.struts.action.Action;
<ide> import org.apache.struts.action.ActionForm;
<ide> Logger.out.debug(Constants.MENU_SELECTED + " " +strMenu +" set successfully");
<ide> }
<ide> }
<add>
<add> /**
<add> * This function checks call to the action and sets/removes required attributes if AddNew or ForwardTo activity is executing.
<add> * @param request - HTTPServletRequest calling the action
<add> */
<add> protected void checkAddNewOperation(HttpServletRequest request)
<add> {
<add> String submittedFor = (String) request.getAttribute(Constants.SUBMITTED_FOR);
<add> Logger.out.debug("SubmittedFor in checkAddNewOperation()------------->"+submittedFor);
<add>
<add> String submittedForParameter=(String)request.getParameter(Constants.SUBMITTED_FOR);
<add>
<add> //if AddNew loop is going on
<add> if( ( (submittedFor !=null)&& (submittedFor.equals("AddNew")) ) )
<add> {
<add> Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is AddNew in checkAddNewOperation() >>>>>>>>>>>>>");
<add>
<add> //Storing SUBMITTED_FOR attribute into Request
<add> request.setAttribute(Constants.SUBMITTED_FOR, Constants.SUBMITTED_FOR_ADD_NEW);
<add> }
<add> //if Page is submitted on same page
<add> else if( (submittedForParameter !=null)&& (submittedForParameter.equals("AddNew")) )
<add> {
<add> Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor parameter is AddNew in checkAddNewOperation() >>>>>>>>>>>>>");
<add> if( (submittedFor !=null)&& (submittedFor.equals("Default")) )
<add> {
<add> //Storing SUBMITTED_FOR attribute into Request
<add> request.setAttribute(Constants.SUBMITTED_FOR, Constants.SUBMITTED_FOR_DEFAULT);
<add> }
<add> else
<add> {
<add> //Storing SUBMITTED_FOR attribute into Request
<add> request.setAttribute(Constants.SUBMITTED_FOR, Constants.SUBMITTED_FOR_ADD_NEW);
<add> }
<add> }
<add> //if ForwardTo request is submitted
<add> else if((submittedFor !=null)&& (submittedFor.equals("ForwardTo")) )
<add> {
<add> Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is ForwardTo in checkAddNewOperation() >>>>>>>>>>>>>");
<add>
<add> request.setAttribute(Constants.SUBMITTED_FOR,Constants.SUBMITTED_FOR_FORWARD_TO);
<add>
<add> Logger.out.debug("<<<<<<<<<<<< Checking for FormBeanStack to remove in checkAddNewOperation() >>>>>>>>>>>>>");
<add> HttpSession session = request.getSession();
<add> if((session.getAttribute(Constants.FORM_BEAN_STACK)) !=null)
<add> {
<add> Logger.out.debug("Removing FormBeanStack from Session in checkAddNewOperation()............");
<add> session.removeAttribute(Constants.FORM_BEAN_STACK);
<add> }
<add> }
<add> //if AddNew loop is over
<add> else if( (submittedFor !=null)&& (submittedFor.equals("Default")) )
<add> {
<add> Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is Default in checkAddNewOperation() >>>>>>>>>>>>>");
<add>
<add> request.setAttribute(Constants.SUBMITTED_FOR,Constants.SUBMITTED_FOR_DEFAULT);
<add>
<add> Logger.out.debug("<<<<<<<<<<<< Checking for FormBeanStack to remove in checkAddNewOperation() >>>>>>>>>>>>>");
<add> HttpSession session = request.getSession();
<add> if((session.getAttribute(Constants.FORM_BEAN_STACK)) !=null)
<add> {
<add> Logger.out.debug("Removing FormBeanStack from Session in checkAddNewOperation()............");
<add> session.removeAttribute(Constants.FORM_BEAN_STACK);
<add> }
<add> }
<add> //if AddNew or ForwardTo loop is broken...
<add> else
<add> {
<add> Logger.out.debug("<<<<<<<<<<<<<< SubmittedFor is NULL in checkAddNewOperation() >>>>>>>>>>>>>");
<add>
<add> Logger.out.debug("<<<<<<<<<<<< Checking for FormBeanStack to remove in checkAddNewOperation() >>>>>>>>>>>>>");
<add> HttpSession session = request.getSession();
<add> if((session.getAttribute(Constants.FORM_BEAN_STACK)) !=null)
<add> {
<add> Logger.out.debug("Removing FormBeanStack from Session in checkAddNewOperation()............");
<add> session.removeAttribute(Constants.FORM_BEAN_STACK);
<add> }
<add> }
<add> }
<ide> } |
|
Java | mit | e363bc5a053172bdf6a50019fd3428c02aa121b4 | 0 | sizezero/dice-probabilities,sizezero/dice-probabilities | package org.kleemann.diceprobabilities;
import android.view.View;
import android.widget.Button;
/**
* <p>
* A special type of CurrentDicePile that represents the integer target of the
* roll. Primary difference is the rendering of the value and a different
* default value.
*/
public class Target implements View.OnClickListener {
private static final String GREATER_THAN_OR_EQUAL_TO = "\u2265";
private final int defaultTarget;
private int count;
private Button button;
private View.OnClickListener changed;
public Target(Button button, View.OnClickListener changed) {
this.defaultTarget = button.getResources().getInteger(
R.integer.default_target);
this.count = defaultTarget;
this.button = button;
this.changed = changed;
button.setOnClickListener(this);
updateButton();
}
private void updateButton() {
button.setText(GREATER_THAN_OR_EQUAL_TO + count);
}
public int getCount() {
return count;
}
public void setCount(int count) {
assert (count >= 0);
this.count = count;
updateButton();
changed.onClick(button);
}
public void add(int count) {
int n = this.count + count;
setCount(n < 0 ? 0 : n);
}
public void clear() {
setCount(defaultTarget);
}
/**
* Cycle between 0, 10, 20, 30
*/
@Override
public void onClick(View v) {
int n = (((count + 10) / 10) * 10);
if (n > 30) {
n = 0;
}
setCount(n);
}
}
| src/org/kleemann/diceprobabilities/Target.java | package org.kleemann.diceprobabilities;
import android.view.View;
import android.widget.Button;
/**
* <p>A special type of CurrentDicePile that represents the integer
* target of the roll. Primary difference is the rendering of the value
* and a different default value.
*/
public class Target implements View.OnClickListener {
private static final String GREATER_THAN_OR_EQUAL_TO = "\u2265";
private final int defaultTarget;
private int count;
private Button button;
private View.OnClickListener changed;
public Target(Button button, View.OnClickListener changed) {
this.defaultTarget = button.getResources().getInteger(R.integer.default_target);
this.count = defaultTarget;
this.button = button;
this.changed = changed;
button.setOnClickListener(this);
updateButton();
}
private void updateButton() {
button.setText(GREATER_THAN_OR_EQUAL_TO + count);
}
public int getCount() { return count; }
public void setCount(int count) {
assert(count >= 0);
this.count = count;
updateButton();
changed.onClick(button);
}
public void add(int count) {
int n = this.count + count;
setCount(n<0 ? 0 : n);
}
public void clear() {
setCount(defaultTarget);
}
@Override
public void onClick(View v) { add(-1); }
}
| pressing target cycles between large values
| src/org/kleemann/diceprobabilities/Target.java | pressing target cycles between large values | <ide><path>rc/org/kleemann/diceprobabilities/Target.java
<ide> import android.widget.Button;
<ide>
<ide> /**
<del> * <p>A special type of CurrentDicePile that represents the integer
<del> * target of the roll. Primary difference is the rendering of the value
<del> * and a different default value.
<add> * <p>
<add> * A special type of CurrentDicePile that represents the integer target of the
<add> * roll. Primary difference is the rendering of the value and a different
<add> * default value.
<ide> */
<ide> public class Target implements View.OnClickListener {
<ide>
<del> private static final String GREATER_THAN_OR_EQUAL_TO = "\u2265";
<del>
<add> private static final String GREATER_THAN_OR_EQUAL_TO = "\u2265";
<add>
<ide> private final int defaultTarget;
<ide> private int count;
<ide> private Button button;
<ide> private View.OnClickListener changed;
<del>
<add>
<ide> public Target(Button button, View.OnClickListener changed) {
<del> this.defaultTarget = button.getResources().getInteger(R.integer.default_target);
<add> this.defaultTarget = button.getResources().getInteger(
<add> R.integer.default_target);
<ide> this.count = defaultTarget;
<ide> this.button = button;
<ide> this.changed = changed;
<ide> private void updateButton() {
<ide> button.setText(GREATER_THAN_OR_EQUAL_TO + count);
<ide> }
<del>
<del> public int getCount() { return count; }
<del>
<add>
<add> public int getCount() {
<add> return count;
<add> }
<add>
<ide> public void setCount(int count) {
<del> assert(count >= 0);
<add> assert (count >= 0);
<ide> this.count = count;
<ide> updateButton();
<del> changed.onClick(button);
<add> changed.onClick(button);
<ide> }
<del>
<add>
<ide> public void add(int count) {
<ide> int n = this.count + count;
<del> setCount(n<0 ? 0 : n);
<add> setCount(n < 0 ? 0 : n);
<ide> }
<ide>
<ide> public void clear() {
<ide> setCount(defaultTarget);
<ide> }
<del>
<add>
<add> /**
<add> * Cycle between 0, 10, 20, 30
<add> */
<ide> @Override
<del> public void onClick(View v) { add(-1); }
<add> public void onClick(View v) {
<add> int n = (((count + 10) / 10) * 10);
<add> if (n > 30) {
<add> n = 0;
<add> }
<add> setCount(n);
<add> }
<ide> } |
|
JavaScript | mit | 1a7a218922fd77a1e371e2eaf02d0e48706b57ff | 0 | taf2/select2,zhangwei900808/select2,stretch4x4/select2,sitexa/select2,MAubreyK/select2,taf2/select2,sujonvidia/select2,jiawenbo/select2,binaryvo/select2,qq645381995/select2,NabiKAZ/select2,khallaghi/select2,inway/select2,jiawenbo/select2,vgrish/select2,megahallon/select2,gitkiselev/select2,riiiiizzzzzohmmmmm/select2,BenJenkinson/select2,sujonvidia/select2,theyec/select2,UziTech/select2,213736015/s2,riiiiizzzzzohmmmmm/select2,myactionreplay/select2,ZaArsProgger/select2,tb/select2,mizalewski/select2,iestruch/select2,brees01/select2,ForeverPx/select2,nopash/select2,goodwall/select2,myactionreplay/select2,LockonZero/select2,syndbg/select2,ForeverPx/select2,loogart/select2,InteractiveIntelligence/select2,od3n/select2,monobasic/select2,khallaghi/select2,binary-koan/select2,fk/select2,loogart/select2,MAubreyK/select2,jlgarciakitmaker/select2,ibrahimyu/select2,213736015/s2,bottomline/select2,gitkiselev/select2,chungth/select2,Burick/select2,alexlondon07/select2,openbizgit/select2,theyec/select2,tzellman/select2,azotos/select2,lisong521/select2,kartik-v/select2,farzak/select2,xtrepo/select2,CodingJoker/select2,zhangwei900808/select2,InteractiveIntelligence/select2,od3n/select2,LockonZero/select2,Restless-ET/select2,NabiKAZ/select2,IntelliTect/select2,Youraiseme/select2,iestruch/select2,michael-brade/select2,BenJenkinson/select2,murb/select2,blackbricksoftware/select2,trileuco/select2,vgrish/select2,fsw/select2,mizalewski/select2,trileuco/select2,marcoheyrex/select2,afelixnieto/select2,keitler/select2,shuai959980629/select2,openbizgit/select2,xtrepo/select2,adrianpietka/select2,monobasic/select2,laborautonomo/select2,Currency-One/select2-v4,CodingJoker/select2,sitexa/select2,nikolas/select2,nikolas/select2,adrianpietka/select2,Currency-One/select2-v4,murb/select2,ZaArsProgger/select2,AnthonyDiSanti/select2,alexlondon07/select2,select2/select2,stretch4x4/select2,ianawilson/select2,fk/select2,goodwall/select2,jlgarciakitmaker/select2,ibrahimyu/select2,brees01/select2,azotos/select2,RickMeasham/select2,Burick/select2,zhaoyan158567/select2,chungth/select2,zhaoyan158567/select2,AhmedMoosa/select2,Restless-ET/select2,AhmedMoosa/select2,gianndall/select2,matixmatix/select2,fashionsun/select2,AnthonyDiSanti/select2,nopash/select2,michael-brade/select2,fashionsun/select2,gianndall/select2,qq645381995/select2,UziTech/select2,slowcolor/select2,lewis-ing/select2,tzellman/select2,bottomline/select2,18098924759/select2,keitler/select2,shuai959980629/select2,binary-koan/select2,matixmatix/select2,RickMeasham/select2,lisong521/select2,thiagocarlossilverio/select2,jkgroupe/select2,lewis-ing/select2,IntelliTect/select2,syndbg/select2,Youraiseme/select2,fsw/select2,tb/select2,marcoheyrex/select2,jkgroupe/select2,inway/select2,ianawilson/select2,slowcolor/select2,blackbricksoftware/select2,farzak/select2,kahwee/select2,jdecuyper/select2,select2/select2,merutak/select2,kahwee/select2,binaryvo/select2,megahallon/select2,merutak/select2,afelixnieto/select2,laborautonomo/select2,jdecuyper/select2,18098924759/select2,thiagocarlossilverio/select2,perdona/select2,perdona/select2 | /**
* Select2 Brazilian Portuguese translation
*/
(function ($) {
"use strict";
$.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "Nenhum resultado encontrado"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Digite mais " + n + " caracter" + (n == 1? "" : "es"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Apague " + n + " caracter" + (n == 1? "" : "es"); },
formatSelectionTooBig: function (limit) { return "Só é possível selecionar " + limit + " elemento" + (limit == 1 ? "" : "s"); },
formatLoadMore: function (pageNumber) { return "Carregando mais resultados…"; },
formatSearching: function () { return "Buscando…"; }
});
})(jQuery);
| select2_locale_pt-BR.js | /**
* Select2 Brazilian Portuguese translation
*/
(function ($) {
"use strict";
$.extend($.fn.select2.defaults, {
formatNoMatches: function () { return "Nenhum resultado encontrado"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Informe " + n + " caractere" + (n == 1? "" : "s"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Apague " + n + " caractere" + (n == 1? "" : "s"); },
formatSelectionTooBig: function (limit) { return "Só é possível selecionar " + limit + " elemento" + (limit == 1 ? "" : "s"); },
formatLoadMore: function (pageNumber) { return "Carregando mais resultados…"; },
formatSearching: function () { return "Buscando…"; }
});
})(jQuery);
| Update select2_locale_pt-BR.js
Fix typo | select2_locale_pt-BR.js | Update select2_locale_pt-BR.js | <ide><path>elect2_locale_pt-BR.js
<ide>
<ide> $.extend($.fn.select2.defaults, {
<ide> formatNoMatches: function () { return "Nenhum resultado encontrado"; },
<del> formatInputTooShort: function (input, min) { var n = min - input.length; return "Informe " + n + " caractere" + (n == 1? "" : "s"); },
<del> formatInputTooLong: function (input, max) { var n = input.length - max; return "Apague " + n + " caractere" + (n == 1? "" : "s"); },
<add> formatInputTooShort: function (input, min) { var n = min - input.length; return "Digite mais " + n + " caracter" + (n == 1? "" : "es"); },
<add> formatInputTooLong: function (input, max) { var n = input.length - max; return "Apague " + n + " caracter" + (n == 1? "" : "es"); },
<ide> formatSelectionTooBig: function (limit) { return "Só é possível selecionar " + limit + " elemento" + (limit == 1 ? "" : "s"); },
<ide> formatLoadMore: function (pageNumber) { return "Carregando mais resultados…"; },
<ide> formatSearching: function () { return "Buscando…"; } |
|
JavaScript | mit | 1a566630d1f2d177c01f6b9f3eef1bc05400b824 | 0 | saydulk/stalker_portal,saydulk/stalker_portal,saydulk/stalker_portal,saydulk/stalker_portal,saydulk/stalker_portal | /**
* Media browser.
*/
(function(){
/* MEDIA BROWSER */
function media_browser_constructor(){
this.layer_name = 'media_browser';
this.row_blocks = ["dir", "back", "playing", "paused", "fav", "name", "seek_bar"];
this.mounted = false;
this.cur_dir_list = [];
this.data_items = [];
this.is_audio = false;
this.play_all = true;
this.smb_auth_history = [];
this.favorites = [];
this.change_level = true;
this.sort_by_date = false;
this.superclass = ListLayer.prototype;
this.dir_hist = [{"path" : "/media/", "page" : 1, "row" : 1}];
this.image_extensions = stb.usbdisk.image_ext.split(' ') || [];
this.audio_extensions = stb.usbdisk.audio_ext.split(' ') || [];
this.video_extensions = stb.usbdisk.video_ext.split(' ') || [];
this.init = function(){
this.superclass.init.call(this);
var self = this;
this.init_smb_auth_dialog();
this.get_smb_passwords();
this.get_favorites();
stb.usbdisk.add_onmount_callback(function(){
self.load_data();
});
stb.usbdisk.add_onumount_callback(function(){
_debug('media_browser onunmount');
_debug('self.on', self.on);
if (stb.player.prev_layer == self || self.on){
if (stb.player.on){
stb.player.stop();
}
self.hide();
main_menu.show();
}
});
stb.player.addCustomEventListener("audiostart", function(item){
_debug('media_browser.audiostart', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].playing = 0;
self.map[cur_idx].playing_block.hide();
}
_debug('item.cmd', item.cmd);
var idx = self.data_items.getIdxByVal("cmd", item.cmd);
if (idx == -1){
return;
}
_debug('idx', idx);
self.data_items[idx].playing = 1;
self.map[idx].playing_block.show();
self.data_items[cur_idx].paused = 0;
self.map[cur_idx].paused_block.hide();
if (self.cur_row == idx){
self.active_row.playing_block.show();
self.active_row.paused_block.hide();
}
self.set_active_row(self.cur_row);
}
});
stb.player.addCustomEventListener("audiostop", function(item){
_debug('media_browser.audiostop', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].playing = 0;
self.map[cur_idx].playing_block.hide();
self.data_items[cur_idx].paused = 0;
self.map[cur_idx].paused_block.hide();
if (self.cur_row == cur_idx){
self.active_row.playing_block.hide();
self.active_row.paused_block.hide();
}
}
window.clearInterval(self.seek_bar_interval);
self.set_active_row(self.cur_row);
}
});
stb.player.addCustomEventListener("audiopause", function(item){
_debug('media_browser.audiopause', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].playing = 0;
self.map[cur_idx].playing_block.hide();
self.data_items[cur_idx].paused = 1;
self.map[cur_idx].paused_block.show();
if (self.cur_row == cur_idx){
self.active_row.playing_block.hide();
self.active_row.paused_block.show();
}
}
}
});
stb.player.addCustomEventListener("audiocontinue", function(item){
_debug('media_browser.audiocontinue', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].paused = 0;
self.map[cur_idx].paused_block.hide();
self.data_items[cur_idx].playing = 1;
self.map[cur_idx].playing_block.show();
if (self.cur_row == cur_idx){
self.active_row.paused_block.hide();
self.active_row.playing_block.show();
}
}
}
});
};
this.get_smb_passwords = function(){
_debug('media_browser.get_smb_passwords');
if (!stb.LoadUserData){
return;
}
var smb_data = Utf8.decode(stb.LoadUserData('smb_data')) || "[]";
_debug('smb_data', smb_data);
smb_data = eval(smb_data);
if (typeof(smb_data) == 'object'){
this.smb_auth_history = smb_data;
}
};
this.save_smb_passwords = function(){
_debug('media_browser.save_smb_passwords');
if (stb.firmware_version < 214){
return;
}
var smb_passwords = JSON.stringify(this.smb_auth_history);
_debug('smb_passwords', smb_passwords);
stb.SaveUserData('smb_data',Utf8.encode(smb_passwords));
};
this.init_smb_auth_dialog = function(){
var self = this;
this.smb_auth_dialog = new ModalForm({"title" : get_word('smb_auth')});
this.smb_auth_dialog.addItem(new ModalFormInput({"label" : get_word('smb_username'), "name" : "login"}));
this.smb_auth_dialog.addItem(new ModalFormInput({"label" : get_word('smb_password'), "name" : "password"}));
this.smb_auth_dialog.enableOnExitClose();
this.smb_auth_dialog.addCustomEventListener("hide", function(){
_debug('smb_auth_dialog hide');
self.on = true
});
this.smb_auth_dialog.addItem(new ModalFormButton(
{
"value" : "OK",
"onclick" : function(){
var login = self.smb_auth_dialog.getItemByName("login").getValue();
var password = self.smb_auth_dialog.getItemByName("password").getValue();
_debug("login", login);
_debug("password", password);
self.smb_auth_dialog.hide();
self.mount_smb_share(login, password);
}
}
));
this.smb_auth_dialog.addItem(new ModalFormButton(
{
"value" : "Cancel",
"onclick" : function(){
self.smb_auth_dialog.hide();
}
}
));
};
this.show = function(do_not_load){
_debug('media_browser.show', do_not_load);
this.change_level = true;
this.superclass.show.call(this, do_not_load);
this.update_breadcrumbs();
this.refresh_play_all_switch();
};
this.hide = function(do_not_reset){
_debug('media_browser.hide', do_not_reset);
try{
/*if (this.on){*/
if (stb.player.on && !this.is_audio){
stb.player.stop();
}
/*}*/
this.superclass.hide.call(this, do_not_reset);
if (!do_not_reset){
this.dir_hist.splice(1, this.dir_hist.length-1);
this.reset();
}
}catch(e){
_debug(e);
}
};
this.reset = function(){
this.cur_row = 0;
this.cur_page = 1;
this.total_pages = 1;
window.clearInterval(this.seek_bar_interval);
};
this.load_data = function(item){
_debug('load_data');
var cur_hist_item = this.dir_hist[this.dir_hist.length - 1];
var cur_dir = cur_hist_item.path;
var smb_param = cur_hist_item.param;
_debug('cur_dir', cur_dir);
_debug('smb_param', smb_param);
if (cur_dir == 'SMB'){
this.load_smb_groups();
return;
}else if (cur_dir == 'SMB_GROUP'){
this.load_smb_servers(smb_param);
return;
}else if (cur_dir == 'SMB_SERVER'){
this.load_smb_shares(smb_param);
return;
}else if (cur_dir == 'FAV'){
var list = [{"name" : "..", "back" : 1}];
list = list.concat(this.favorites);
this.fill_page(list);
return;
}
this.load_mount_data(item || cur_hist_item);
};
this.load_mount_data = function(item){
_debug('media_browser.load_mount_data', item);
if (item && item.hasOwnProperty('full_path')){
if (item.full_path.indexOf('smb://') == 0){
this.smb_path = this.parse_smb_path(item.full_path).path || '';
path = '/ram/mnt/smb/' + this.smb_path;
}else{
path = item.full_path;
}
}else{
var path = this.compile_path();
}
//var path = this.compile_path();
this.path = path;
_debug('path', path);
if (this.change_level){
stb.usbdisk.read_dir(path);
}
//_debug(txt);
//_debug('stb.storages', stb.storages);
_debug('stb.usbdisk.dirs', stb.usbdisk.dirs);
try{
var storage_info = JSON.parse(stb.RDir('get_storage_info'));
}catch(e){
_debug(e);
}
var devices = {};
if (storage_info){
for (var i=0; i<storage_info.length; i++){
devices['USB-' + storage_info[i].sn + '-' + storage_info[i].partitionNum] = storage_info[i].vendor
+ ' ' + storage_info[i].model
+ (storage_info[i].label ? '(' + storage_info[i].label + ')' : '')
+ (storage_info.length > 1 ? ' #' + storage_info[i].partitionNum : '');
}
}
if (this.dir_hist.length == 1){
stb.usbdisk.dirs = stb.usbdisk.dirs.filter(function(el){return !stb.storages.hasOwnProperty(el.substr(0, el.length-1))});
}
_debug('stb.usbdisk.dirs 2', stb.usbdisk.dirs);
var new_dirs = [];
for (var i=0; i < stb.usbdisk.dirs.length; i++){
if (!empty(stb.usbdisk.dirs[i])){
if (devices[stb.usbdisk.dirs[i].substring(0, stb.usbdisk.dirs[i].length - 1)]){
var name = devices[stb.usbdisk.dirs[i].substring(0, stb.usbdisk.dirs[i].length - 1)];
}else{
name = stb.usbdisk.dirs[i].substring(0, stb.usbdisk.dirs[i].length - 1);
}
if (name == 'av'){
name = 'UPnP';
}else if (name.indexOf('USB-') == 0 || name.indexOf('tmp-smb') == 0 || name.indexOf('SAMBA') == 0){
continue;
}
var is_playable = this.is_playable_folder(path+'/'+name);
_debug('is_playable', is_playable);
if (is_playable){
new_dirs.push({"name" : name, "dir" : 1, "dir_name" : stb.usbdisk.dirs[i], "cmd" : "extBDDVD "+path+'/'+name})
}else{
new_dirs.push({"name" : name, "dir" : 1, "dir_name" : stb.usbdisk.dirs[i]})
}
//new_dirs.push({"name" : name, "dir" : 1, "dir_name" : stb.usbdisk.dirs[i]/*, "_id" : this.get_id({"name" : name, "dir_name" : stb.usbdisk.dirs[i]})*/})
}
}
var new_files = [];
for (var i=0; i < stb.usbdisk.files.length; i++){
if (!empty(stb.usbdisk.files[i]) && ['srt', 'sub', 'ass'].indexOf(stb.usbdisk.files[i].name.substring(stb.usbdisk.files[i].name.lastIndexOf('.')+1)) == -1){
if (stb.usbdisk.files[i].name.toLowerCase().indexOf('.iso') == stb.usbdisk.files[i].name.length-4){
var solution = 'extBDDVD';
}else{
solution = 'auto';
}
new_files.push({
"name" : stb.usbdisk.files[i].name,
"cmd" : (solution + " " + path + stb.usbdisk.files[i].name),
"size" : stb.usbdisk.files[i].size,
"last_modified" : (stb.usbdisk.files[i].last_modified || 0)
});
}
}
if (new_files && new_files.length && new_files[0].hasOwnProperty('last_modified') && new_files[0].last_modified){
if (this.sort_by_date){
new_files = this.sort_list_by_date(new_files);
}
this.color_buttons.get('green').enable();
}else{
this.color_buttons.get('green').disable();
}
var list = new_dirs.concat(new_files);
if (this.dir_hist.length == 1){
var clear_arr = [];
}else{
clear_arr = [{"name" : "..", "back" : 1}];
}
for (var i=0; i < list.length; i++){
if (!empty(list[i])){
clear_arr.push(list[i]);
}
}
if (this.dir_hist.length == 1 && stb.GetSmbGroups){
var lan_item = {"name" : "LAN", "dir" : 1, "dir_name" : "SMB"/*, "_id" : this.get_id({"name" : "LAN", "dir_name" : "SMB"})*/};
if (clear_arr.length >= 1){
clear_arr.splice(1, 0, lan_item);
}else{
clear_arr.push(lan_item);
}
}
if (this.dir_hist.length == 1){
var fav_item = {"name" : get_word('media_favorites'), "dir" : 1, "dir_name" : "FAV"};
if (clear_arr.length >= 2){
clear_arr.splice(2, 0, fav_item);
}else{
clear_arr.push(fav_item);
}
}
this.fill_page(clear_arr);
};
this.is_playable_folder = function(path){
_debug('media_browser.is_playable_folder', path);
return stb.IsFolderExist(Utf8.encode(path+'/VIDEO_TS/'))
|| stb.IsFolderExist(Utf8.encode(path+'/BDMV/'))
|| stb.IsFileExist(Utf8.encode(path+'/VIDEO_TS.IFO'))
|| stb.IsFolderExist(Utf8.encode(path+'/video_ts/'))
|| stb.IsFolderExist(Utf8.encode(path+'/bdmv/'))
|| stb.IsFileExist(Utf8.encode(path+'/video_ts.ifo'));
};
this.load_smb_groups = function(){
_debug('media_browser.load_smb_groups');
if (!this.change_level){
this.fill_page(this.cur_dir_list);
return;
}
var groups = JSON.parse(stb.GetSmbGroups());
_debug('groups', groups);
groups.result = groups.result || [];
if (!groups || !groups.result || groups.errMsg){
return;
}
var self = this;
groups = groups.result.map(function(group){
return {"name" : group, "dir" : 1, "dir_name" : "SMB_GROUP"/*, "_id" : self.get_id({"name" : group, "dir_name" : "SMB_GROUP"})*/}
});
groups.unshift({"name" : "..", "back" : 1});
_debug('groups', groups);
this.fill_page(groups);
};
this.load_smb_servers = function(group){
_debug('media_browser.load_smb_servers', group);
if (!this.change_level){
this.fill_page(this.cur_dir_list);
return;
}
var args = '{"group":"' + group + '"}';
_debug('args', args);
var servers = JSON.parse(stb.GetSmbServers(args));
_debug('servers', servers);
if (!servers || !servers.result || servers.errMsg){
return;
}
var self = this;
servers = servers.result.map(function(server){
return {"name" : server, "dir" : 1, "dir_name" : "SMB_SERVER"/*, "_id" : self.get_id({"name" : server, "dir_name" : "SMB_SERVER"})*/}
});
servers.unshift({"name" : "..", "back" : 1});
_debug('servers', servers);
this.fill_page(servers);
};
this.load_smb_shares = function(server){
_debug('media_browser.load_smb_shares', server);
if (!this.change_level){
this.fill_page(this.cur_dir_list);
return;
}
var args = '{"server":"' + server + '"}';
_debug('args', args);
var shares = JSON.parse(stb.GetSmbShares(args));
_debug('shares', shares);
if (!shares || !shares.result || shares.errMsg){
return;
}
shares.result.shares = shares.result.shares || [];
this.smb_server_ip = shares.result.serverIP;
var self = this;
shares = shares.result.shares.map(function(share){
return {"name" : share, "dir" : 1, "dir_name" : "SMB_SHARE"/*, "_id" : self.get_id({"name" : share, "dir_name" : "SMB_SHARE"})*/}
});
shares.unshift({"name" : "..", "back" : 1});
_debug('shares', shares);
this.fill_page(shares);
};
this.mount_smb_share = function(login, password){
_debug('media_browser.mount_smb_share');
/*login = login || "guest";
password = password || "";*/
if (login == undefined){
var auth_params = this.get_auth_params(this.smb_server_ip, this.smb_share);
login = auth_params.login;
password = auth_params.pass;
}
_debug('this.smb_server_ip', this.smb_server_ip);
_debug('this.smb_share', this.smb_share);
_debug('password', password);
_debug('login', login);
var mount_str = 'mount cifs //' + Utf8.encode(this.smb_server_ip + '/' + this.smb_share) + ' /ram/mnt/smb username=' + login + ',password=' + password + ',iocharset=utf8';
_debug('mount_str', mount_str);
var smb_mount_result = stb.RDir(mount_str);
_debug('smb_mount_result', smb_mount_result);
if (smb_mount_result == "Error: mount failed"){
this.on = false;
this.smb_auth_dialog.show();
}else{
if (login != "guest"){
this.save_auth_params(this.smb_server_ip, this.smb_share, login, password)
}
this.in_dir(this.active_item);
}
};
this.save_auth_params = function(server, share, login, password){
_debug('media_browser.save_auth_params', server, share, login, password);
var url = '//' + server + '/' + share;
var idx = this.smb_auth_history.getIdxByVal("url", url);
var save_obj = {"url" : url, "login" : login, "pass" : password, "automount" : 0};
if (idx != null){
this.smb_auth_history[idx] = save_obj;
}else{
this.smb_auth_history.push(save_obj);
}
this.save_smb_passwords();
};
this.get_auth_params = function(server, share){
_debug('media_browser.save_auth_params', server, share);
var url = '//' + server + '/' + share;
var idx = this.smb_auth_history.getIdxByVal("url", url);
if (idx == null){
return {"login" : "guest", "pass" : ""};
}
return {"login" : this.smb_auth_history[idx].login, "pass" : this.smb_auth_history[idx].pass};
};
this.fill_page = function(data){
this.total_pages = Math.ceil(data.length/14);
this.cur_dir_list = data;
if (stb.player.cur_media_item && this.change_level){
var contain_playing_item_idx = this.cur_dir_list.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('contain_playing_item_idx', contain_playing_item_idx);
}else{
contain_playing_item_idx = null;
}
if (contain_playing_item_idx !== null){
this.cur_page = Math.ceil((contain_playing_item_idx + 1)/ 14);
this.cur_row = contain_playing_item_idx - (this.cur_page - 1) * 14
}
_debug('this.cur_page', this.cur_page);
_debug('this.cur_row', this.cur_row);
if (this.dir_hist.length > 1){
this.set_total_items(data.length - 1);
}else{
this.set_total_items(data.length);
}
var begin = (this.cur_page - 1) * 14;
var end = this.cur_page * 14;
this.data_items = this.cur_dir_list.slice(begin, end);
var self = this;
this.fill_list(this.data_items);
};
this.compile_path = function(){
_debug('media_browser.compile_path');
_debug('this.dir_hist', this.dir_hist);
if (this.dir_hist[this.dir_hist.length - 1].path == 'SMB_SHARE'){
return '/ram/mnt/smb/'
}
var path = '';
for(var i=0; i<this.dir_hist.length; i++){
if (['SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(this.dir_hist[i].path) >= 0){
continue;
}else if (this.dir_hist[i].path == 'SMB'){
path = '/ram/mnt/smb/';
}else if (this.dir_hist[i].hasOwnProperty('full_path')){
path = this.dir_hist[i].full_path;
}else{
path += '/' + this.dir_hist[i].path;
}
}
return path;
};
this.action = function(){
if (this.data_items[this.cur_row].hasOwnProperty('dir') && !this.data_items[this.cur_row].hasOwnProperty('cmd')){
this.check_for_mount(this.data_items[this.cur_row]);
}else if (this.data_items[this.cur_row].hasOwnProperty('back')){
this.out_dir();
}else{
var self = this;
var is_image = this.image_extensions.some(
function(item){
return self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) >= 0 && self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) == self.data_items[self.cur_row].name.length - item.length;
});
_debug('is_image', is_image);
var is_audio = this.audio_extensions.some(
function(item){
return self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) >= 0 && self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) == self.data_items[self.cur_row].name.length - item.length;
});
_debug('is_audio', is_audio);
var item = this.data_items[this.cur_row].clone();
if (is_audio && this.play_all){
item.playlist = this.audio_list;
}
var is_video = this.video_extensions.some(
function(item){
return self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) >= 0 && self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) == self.data_items[self.cur_row].name.length - item.length;
});
_debug('is_video', is_video);
if (is_video && this.play_all){
item.playlist = this.video_list;
}
_debug('item', item);
if (is_image){
this.on = false;
module.image_viewer.show(this.image_list, this.data_items[this.cur_row].name, this.compile_path(), this);
}else{
//this.play(this.data_items[this.cur_row]);
this.play(item);
}
}
};
this.play = function(item){
_debug('media_browser.play');
if (stb.player.get_file_type(item) == 'audio'){
this.is_audio = true;
stb.player.need_show_info = 0;
}else{
this.is_audio = false;
this.hide(true);
stb.player.prev_layer = this;
stb.player.need_show_info = 1;
}
_debug('this.dir_hist', this.dir_hist);
_debug('stb.player.on', stb.player.on);
if (stb.player.on){
stb.player.stop();
}
item['subtitles'] = this.find_subtitles(item['cmd']);
stb.player.play(item);
};
this.find_subtitles = function(cmd){
_debug('media_browser.find_subtitles', cmd);
var filename = cmd.substring(cmd.lastIndexOf('/')+1);
if (!filename){
return null;
}
var base = filename.substring(0, filename.lastIndexOf('.'));
_debug('base', base);
if (!base){
return null;
}
_debug('stb.usbdisk.files', stb.usbdisk.files);
var subtitle_files = stb.usbdisk.files.filter(function(item){
_debug('item', item);
_debug('item.name', item.name);
if (item.name){
_debug('item.name.indexOf(base)', item.name.indexOf(base));
_debug('indexOf...', ['srt', 'sub', 'ass'].indexOf(item.name.substring(item.name.lastIndexOf('.')+1)));
}
return item && item.name && item.name.indexOf(base) === 0 && ['srt', 'sub', 'ass'].indexOf(item.name.substring(item.name.lastIndexOf('.')+1)) != -1;
});
_debug('subtitle_files', subtitle_files);
var self = this;
var subtitles = subtitle_files.map(function(item, idx){
var lang = item.name.substring(base.length, item.name.lastIndexOf('.'));
if (lang[0] == '_' || lang[0] == '.'){
lang = lang.substr(1);
}
return {"pid" : 'external_'+idx, "lang" : [lang, ''], "file" : self.path + item.name};
});
_debug('subtitles', subtitles);
return subtitles;
};
this.out_dir = function(){
_debug('out_dir');
if (this.dir_hist.length > 1){
this.dir_hist.pop();
this.reset();
this.cur_row = this.dir_hist[this.dir_hist.length - 1].row;
this.cur_page = this.dir_hist[this.dir_hist.length - 1].page;
this.change_level = true;
this.update_breadcrumbs();
this.load_data();
}
};
this.check_for_mount = function(item){
_debug('media_browser.check_for_mount', item);
//_debug('item.name', item.name);
//_debug('item.name.split()', item.name.split(''));
//item.name.split('').map(function(letter){
// _debug('letter code', letter.charCodeAt(0));
//});
this.active_item = item;
var is_smb = this.dir_hist.some(function(dir){
return ['SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(dir.path) >= 0 || dir.full_path && dir.full_path.indexOf('smb://') == 0;
});
_debug('is_smb', is_smb);
if (is_smb){
var smb_full_path = this.get_full_smb_path(item);
_debug('smb_full_path', smb_full_path);
item.full_path = item._id = smb_full_path;
}
if (item.dir_name == 'SMB_SHARE' || item.hasOwnProperty('full_path') && item.full_path.indexOf('smb://') == 0 && this.parse_smb_path(item.full_path).hasOwnProperty('share')){
stb.ExecAction('make_dir /ram/mnt/smb/');
stb.ExecAction('umount_dir /ram/mnt/smb/');
if (item.hasOwnProperty('full_path')){
var path = this.parse_smb_path(item.full_path);
_debug('smb path', path);
if (path.hasOwnProperty('server')){
this.smb_server_ip = this.get_smb_server_ip_by_name(path.server);
}
if (path.hasOwnProperty('path')){
this.smb_path = path.path;
}else{
this.smb_path = '';
}
if (path.hasOwnProperty('share')){
this.smb_share = path.share;
}
}else{
this.smb_share = item.name;
}
this.mount_smb_share();
return;
}
this.in_dir(item);
};
this.in_dir = function(item){
var dir = item.dir_name;
_debug('in_dir', dir);
this.dir_hist[this.dir_hist.length - 1].page = this.cur_page;
this.dir_hist[this.dir_hist.length - 1].row = this.cur_row;
var hist_item = {'path' : dir , 'param' : item.name, 'page' : 1, 'row' : 1};
if (item.hasOwnProperty('full_path')){
hist_item.full_path = item.full_path;
}
this.dir_hist.push(hist_item);
this.reset();
this.change_level = true;
this.update_breadcrumbs();
this.load_data(item);
};
this.update_breadcrumbs = function(){
_debug('media_browser.update_breadcrumbs');
var breadcrumbs = '';
for(var i=1; i<this.dir_hist.length; i++){
if (this.dir_hist[i].path == 'SMB_GROUP'){
}else if (['SMB', 'SMB_SERVER', 'SMB_SHARE', 'FAV'].indexOf(this.dir_hist[i].path) >= 0 || this.dir_hist[i].path.indexOf('USB-') === 0){
breadcrumbs += this.dir_hist[i].param + '/';
}else{
breadcrumbs += this.dir_hist[i].path;
}
}
breadcrumbs = breadcrumbs.substr(0, breadcrumbs.length - 1);
this.update_header_path([{"alias" : "breadcrumbs", "item" : breadcrumbs}]);
};
this.bind = function(){
this.superclass.bind.apply(this);
this.action.bind(key.OK, this);
/*(function(){
this.hide();
main_menu.show();
}).bind(key.EXIT, this);*/
(function(){
this.hide();
main_menu.show();
}).bind(key.LEFT, this).bind(key.MENU, this);
(function(){
if (this.dir_hist.length == 1){
this.hide();
main_menu.show();
}else{
this.out_dir();
}
}).bind(key.BACK, this).bind(key.EXIT, this);
};
this.fill_list = function(data){
this.data_items = data;
var self = this;
this.data_items = this.data_items.map(function(item){
if (stb.player.cur_media_item && item.cmd == stb.player.cur_media_item.cmd && stb.player.on){
if (stb.player.pause.on){
item.paused = 1;
}else{
item.playing = 1;
}
}
if (item.dir){
item.fav = self.favorites.some(function(favorite){
return favorite._id == (item._id || self.get_id(item));
}) ? 1 : 0;
}
return item;
});
this.get_image_list();
this.get_audio_list();
this.get_video_list();
if (!this.change_level){
if (this.page_dir > 0){
this.cur_row = 0;
}else{
this.cur_row = this.data_items.length - 1;
}
}
this.change_level = false;
this.superclass.fill_list.call(this, data);
};
this.get_image_list = function(){
var self = this;
this.image_list = this.cur_dir_list.filter(function(item){
return self.image_extensions.some(function(ext){
return item.name.toLowerCase().lastIndexOf(ext) >= 0 && item.name.toLowerCase().lastIndexOf(ext) == item.name.length - ext.length;
});
});
_debug('this.image_list', this.image_list);
};
this.get_audio_list = function(){
_debug('media_browser.get_audio_list');
var self = this;
var path = this.compile_path();
_debug('path', path);
_debug('this.cur_dir_list', this.cur_dir_list);
this.audio_list = this.cur_dir_list.filter(function(item){
return new RegExp("(" + self.audio_extensions.join("|") + ")$").test(item.name);
});
this.audio_list = this.audio_list.map(function(item){
//return 'auto ' + path + item.name;
return item.cmd;
});
_debug('this.audio_list', this.audio_list);
};
this.get_video_list = function(){
var self = this;
var path = this.compile_path();
this.video_list = this.cur_dir_list.filter(function(item){
return new RegExp("(" + self.video_extensions.join("|") + ")$").test(item.name);
});
this.video_list = this.video_list.map(function(item){
//return 'auto ' + path + item.name;
return item.cmd;
});
_debug('this.video_list', this.video_list);
};
this.set_active_row = function(num){
_debug('media_browser.set_active_row', num);
this.superclass.set_active_row.call(this, num);
_debug('this.data_items[this.cur_row].cmd', this.data_items[this.cur_row].cmd);
_debug('stb.player.on', stb.player.on);
if (stb.player.cur_media_item && this.data_items[this.cur_row].cmd == stb.player.cur_media_item.cmd && stb.player.on && stb.player.file_type == 'audio'){
this.active_row['row'].setAttribute("status", "playing");
this.active_row['row'].addClass("playing");
if (this.active_row.seek_bar_block.childNodes.length > 0){
this.active_row.seek_bar_block.childNodes[0].style.width = 0;
}
this.active_row.seek_bar_block.show();
this._start_updating_seek_bar();
}else{
this.active_row['row'].setAttribute("status", "");
this.active_row['row'].removeClass("playing");
this.active_row.seek_bar_block.hide();
if (this.active_row.seek_bar_block.childNodes.length > 0){
this.active_row.seek_bar_block.childNodes[0].style.width = 0;
}
window.clearInterval(this.seek_bar_interval);
}
if (this.data_items[this.cur_row].dir && this.dir_hist.length>1){
this.color_buttons.get('yellow').enable();
}else{
this.color_buttons.get('yellow').disable();
}
_debug('this.active_row[row].getAttribute(status)', this.active_row['row'].getAttribute("status"));
};
this._start_updating_seek_bar = function(){
_debug('media_browser._start_updating_seek_bar');
var self = this;
window.clearInterval(this.seek_bar_interval);
this._update_seek_bar();
this.seek_bar_interval = window.setInterval(function(){
self._update_seek_bar();
}, 1000);
};
this._update_seek_bar = function(){
if (this.active_row.seek_bar_block.childNodes.length == 0){
var inner = create_block_element("seek_bar_inner", this.active_row.seek_bar_block);
}else{
inner = this.active_row.seek_bar_block.childNodes[0];
}
var pos_time = stb.GetPosTime();
var media_len = stb.GetMediaLen();
_debug('pos_time', pos_time);
_debug('media_len', media_len);
_debug('this.active_row.seek_bar_block.offsetWidth', this.active_row.seek_bar_block.offsetWidth);
var width = this.active_row.seek_bar_block.offsetWidth * pos_time / media_len;
_debug('width', width);
if (width > this.active_row.seek_bar_block.offsetWidth){
width = this.active_row.seek_bar_block.offsetWidth;
}
if (media_len == 0){
width = 0;
}
_debug('width 2', width);
inner.style.width = width + 'px';
};
this.play_all_switch = function(){
_debug('media_browser.play_all_switch');
this.play_all = !this.play_all;
_debug('this.play_all', this.play_all);
this.refresh_play_all_switch();
};
this.refresh_play_all_switch = function(){
_debug('media_browser.refresh_play_all_switch');
_debug('this.play_all', this.play_all);
this.color_buttons.get("red").text_obj.innerHTML = get_word('play_all') + ": " + (this.play_all ? get_word('on') : get_word('off'));
};
this.add_del_fav = function(){
_debug('media_browser.add_del_fav');
_debug('this.data_items[this.cur_row]', this.data_items[this.cur_row]);
if (!this.data_items[this.cur_row].hasOwnProperty('dir') || this.data_items[this.cur_row].dir != '1'){
return;
}
var _id = this.data_items[this.cur_row]._id || this.get_id(this.data_items[this.cur_row]);
_debug('_id', _id);
var idx = this.favorites.getIdxByVal('_id', _id);
_debug('idx', idx);
this.data_items[this.cur_row]._id = _id;
this.data_items[this.cur_row].full_path = this.data_items[this.cur_row].full_path || this.get_full_path(this.data_items[this.cur_row]);
if (this.data_items[this.cur_row].fav){
this.del_from_fav(this.data_items[this.cur_row]);
}else{
this.add_to_fav(this.data_items[this.cur_row]);
}
this.save_favorites();
};
this.add_to_fav = function(item){
_debug('media_browser.add_to_fav');
this.data_items[this.cur_row].fav = 1;
this.map[this.cur_row].fav_block.show();
this.active_row.fav_block.show();
this.favorites.push(item);
};
this.del_from_fav = function(item){
_debug('media_browser.del_from_fav');
this.data_items[this.cur_row].fav = 0;
this.map[this.cur_row].fav_block.hide();
this.active_row.fav_block.hide();
var idx = this.favorites.getIdxByVal('_id', item._id);
_debug('idx', idx);
if (idx !== null){
this.favorites.splice(idx, 1);
}
};
this.get_full_path = function(item){
_debug('media_browser.get_full_path');
_debug('this.dir_hist', this.dir_hist);
var is_smb = this.dir_hist.some(function(dir){
return ['SMB', 'SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(dir.path) >= 0;
}) || item.dir_name == 'SMB';
_debug('is_smb', is_smb);
if (is_smb){
var smb_full_path = this.get_full_smb_path(item);
_debug('smb_full_path', smb_full_path);
return smb_full_path;
}
var full_path = this.compile_path();
_debug('full_path 1', full_path);
if (full_path[full_path.length-1] == '/'){
//full_path = full_path.substring(0, full_path.length-1);
}
_debug('full_path 2', full_path);
return full_path + '/' + item.dir_name;
};
this.get_full_smb_path = function(item){
_debug('media_browser.get_full_smb_path');
_debug('this.dir_hist', this.dir_hist);
var path = 'smb:/';
for(var i=0; i<this.dir_hist.length; i++){
/*if (this.dir_hist[i].path == 'SMB'){
path = 'smb:/';*/
if (this.dir_hist[i].hasOwnProperty('full_path')){
path = this.dir_hist[i].full_path;
}else if (this.dir_hist[i].path == 'SMB'){
path = 'smb:/';
}else /*if (['SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(this.dir_hist[i].path) >= 0)*/{
path += '/' + this.dir_hist[i].param;
}
}
return path + '/' + item.name;
};
this.parse_smb_path = function(full_path){
_debug('media_browser.parse_smb_path', full_path);
var path = {};
var match = full_path.match("smb://([^\/]*)\/?([^\/]*)\/?([^\/]*)\/?(.*)");
_debug('match', match);
if (match){
if (match[1]){
path.workgroup = match[1];
}
if (match[2]){
path.server = match[2];
}
if (match[3]){
path.share = match[3];
}
if (match[4]){
path.path = match[4] + '/';
}
}
return path;
};
this.get_smb_server_ip_by_name = function(name){
_debug('media_browser.get_smb_server_ip_by_name', name);
var args = '{"server":"' + name + '"}';
_debug('args', args);
var shares = JSON.parse(stb.GetSmbShares(args));
_debug('shares', shares);
if (!shares || !shares.result || shares.errMsg){
return null;
}
shares.result.shares = shares.result.shares || [];
return shares.result.serverIP;
};
this.get_id = function(item){
_debug('media_browser.get_id', item);
return this.get_full_path(item);
};
this.get_favorites = function(){
_debug('media_browser.get_favorites');
stb.load(
{
"type" : "media_favorites",
"action" : "get_all"
},
function(result){
_debug('on get_favorites', result);
this.favorites = result && JSON.parse(result) || [];
},
this
)
};
this.save_favorites = function(){
_debug('media_browser.save_favorites');
stb.load(
{
"type" : "media_favorites",
"action" : "save",
"favorites" : JSON.stringify(this.favorites)
},
function(result){
_debug("on save_favorites", result);
},
this
);
};
this.init_sort_menu = function(map, options){
_debug('media_browser.init_sort_menu');
this.sort_menu = new bottom_menu(this, options);
this.sort_menu.init(map);
this.sort_menu.bind();
};
this.sort_menu_switcher = function(){
_debug('media_browser.sort_menu_switcher');
if (this.sort_menu && this.sort_menu.on){
this.sort_menu.hide();
}else{
this.sort_menu.show();
}
};
this.sort_list_by_date = function(list){
_debug('media_browser.sort_list_by_date', list);
var times = list.map(function(item){
return (item.last_modified || 0)+'_'+item.name;
});
times.sort(function(a,b){return parseInt(b, 10) - parseInt(a, 10)});
_debug('times', times);
var sorted_list = [];
list.every(function(item){
var idx = times.indexOf(item.last_modified+'_'+item.name);
sorted_list[idx] = item;
return true;
});
_debug('sorted_list', sorted_list);
return sorted_list;
};
}
var Utf8 = {
// public method for url encoding
encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// public method for url decoding
decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
media_browser_constructor.prototype = new ListLayer();
var media_browser = new media_browser_constructor();
media_browser.bind();
media_browser.init();
media_browser.set_wide_container();
media_browser.init_left_ear(word['ears_back']);
media_browser.init_header_path(word['mbrowser_title']);
media_browser.init_color_buttons([
{"label" : word['play_all'], "cmd" : media_browser.play_all_switch},
{"label" : word['tv_sort'], "cmd" : media_browser.sort_menu_switcher},
{"label" : get_word('favorite'), "cmd" : media_browser.add_del_fav},
{"label" : word['empty'], "cmd" : ""}
]);
var sort_menu_map = [
{
"label" : get_word("mbrowser_sort_by_name"),
"cmd" : function(){
this.parent.sort_by_date = false;
},
"selector" : "*"
},
{
"label" : get_word("mbrowser_sort_by_date"),
"cmd" : function(){
this.parent.sort_by_date = true;
}
}
];
media_browser.init_sort_menu(
sort_menu_map,
{
"color" : "green",
"need_update_header" : false
}
);
media_browser.hide();
module.media_browser = media_browser;
/* END MEDIA BROWSER */
main_menu.add(word['mbrowser_title'], [], 'mm_ico_usb.png', function(){
main_menu.hide();
module.media_browser.show();
},
module.media_browser
);
})();
loader.next(); | c/media_browser.js | /**
* Media browser.
*/
(function(){
/* MEDIA BROWSER */
function media_browser_constructor(){
this.layer_name = 'media_browser';
this.row_blocks = ["dir", "back", "playing", "paused", "fav", "name", "seek_bar"];
this.mounted = false;
this.cur_dir_list = [];
this.data_items = [];
this.is_audio = false;
this.play_all = true;
this.smb_auth_history = [];
this.favorites = [];
this.change_level = true;
this.sort_by_date = false;
this.superclass = ListLayer.prototype;
this.dir_hist = [{"path" : "/media/", "page" : 1, "row" : 1}];
this.image_extensions = stb.usbdisk.image_ext.split(' ') || [];
this.audio_extensions = stb.usbdisk.audio_ext.split(' ') || [];
this.video_extensions = stb.usbdisk.video_ext.split(' ') || [];
this.init = function(){
this.superclass.init.call(this);
var self = this;
this.init_smb_auth_dialog();
this.get_smb_passwords();
this.get_favorites();
stb.usbdisk.add_onmount_callback(function(){
self.load_data();
});
stb.usbdisk.add_onumount_callback(function(){
_debug('media_browser onunmount');
_debug('self.on', self.on);
if (stb.player.prev_layer == self || self.on){
if (stb.player.on){
stb.player.stop();
}
self.hide();
main_menu.show();
}
});
stb.player.addCustomEventListener("audiostart", function(item){
_debug('media_browser.audiostart', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].playing = 0;
self.map[cur_idx].playing_block.hide();
}
_debug('item.cmd', item.cmd);
var idx = self.data_items.getIdxByVal("cmd", item.cmd);
if (idx == -1){
return;
}
_debug('idx', idx);
self.data_items[idx].playing = 1;
self.map[idx].playing_block.show();
self.data_items[cur_idx].paused = 0;
self.map[cur_idx].paused_block.hide();
if (self.cur_row == idx){
self.active_row.playing_block.show();
self.active_row.paused_block.hide();
}
self.set_active_row(self.cur_row);
}
});
stb.player.addCustomEventListener("audiostop", function(item){
_debug('media_browser.audiostop', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].playing = 0;
self.map[cur_idx].playing_block.hide();
self.data_items[cur_idx].paused = 0;
self.map[cur_idx].paused_block.hide();
if (self.cur_row == cur_idx){
self.active_row.playing_block.hide();
self.active_row.paused_block.hide();
}
}
window.clearInterval(self.seek_bar_interval);
self.set_active_row(self.cur_row);
}
});
stb.player.addCustomEventListener("audiopause", function(item){
_debug('media_browser.audiopause', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].playing = 0;
self.map[cur_idx].playing_block.hide();
self.data_items[cur_idx].paused = 1;
self.map[cur_idx].paused_block.show();
if (self.cur_row == cur_idx){
self.active_row.playing_block.hide();
self.active_row.paused_block.show();
}
}
}
});
stb.player.addCustomEventListener("audiocontinue", function(item){
_debug('media_browser.audiocontinue', item);
if (self.on){
var cur_idx = self.data_items.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('cur_idx', cur_idx);
if (cur_idx >= 0){
self.data_items[cur_idx].paused = 0;
self.map[cur_idx].paused_block.hide();
self.data_items[cur_idx].playing = 1;
self.map[cur_idx].playing_block.show();
if (self.cur_row == cur_idx){
self.active_row.paused_block.hide();
self.active_row.playing_block.show();
}
}
}
});
};
this.get_smb_passwords = function(){
_debug('media_browser.get_smb_passwords');
if (!stb.LoadUserData){
return;
}
var smb_data = Utf8.decode(stb.LoadUserData('smb_data')) || "[]";
_debug('smb_data', smb_data);
smb_data = eval(smb_data);
if (typeof(smb_data) == 'object'){
this.smb_auth_history = smb_data;
}
};
this.save_smb_passwords = function(){
_debug('media_browser.save_smb_passwords');
if (stb.firmware_version < 214){
return;
}
var smb_passwords = JSON.stringify(this.smb_auth_history);
_debug('smb_passwords', smb_passwords);
stb.SaveUserData('smb_data',Utf8.encode(smb_passwords));
};
this.init_smb_auth_dialog = function(){
var self = this;
this.smb_auth_dialog = new ModalForm({"title" : get_word('smb_auth')});
this.smb_auth_dialog.addItem(new ModalFormInput({"label" : get_word('smb_username'), "name" : "login"}));
this.smb_auth_dialog.addItem(new ModalFormInput({"label" : get_word('smb_password'), "name" : "password"}));
this.smb_auth_dialog.enableOnExitClose();
this.smb_auth_dialog.addCustomEventListener("hide", function(){
_debug('smb_auth_dialog hide');
self.on = true
});
this.smb_auth_dialog.addItem(new ModalFormButton(
{
"value" : "OK",
"onclick" : function(){
var login = self.smb_auth_dialog.getItemByName("login").getValue();
var password = self.smb_auth_dialog.getItemByName("password").getValue();
_debug("login", login);
_debug("password", password);
self.smb_auth_dialog.hide();
self.mount_smb_share(login, password);
}
}
));
this.smb_auth_dialog.addItem(new ModalFormButton(
{
"value" : "Cancel",
"onclick" : function(){
self.smb_auth_dialog.hide();
}
}
));
};
this.show = function(do_not_load){
_debug('media_browser.show', do_not_load);
this.change_level = true;
this.superclass.show.call(this, do_not_load);
this.update_breadcrumbs();
this.refresh_play_all_switch();
};
this.hide = function(do_not_reset){
_debug('media_browser.hide', do_not_reset);
try{
/*if (this.on){*/
if (stb.player.on && !this.is_audio){
stb.player.stop();
}
/*}*/
this.superclass.hide.call(this, do_not_reset);
if (!do_not_reset){
this.dir_hist.splice(1, this.dir_hist.length-1);
this.reset();
}
}catch(e){
_debug(e);
}
};
this.reset = function(){
this.cur_row = 0;
this.cur_page = 1;
this.total_pages = 1;
window.clearInterval(this.seek_bar_interval);
};
this.load_data = function(item){
_debug('load_data');
var cur_hist_item = this.dir_hist[this.dir_hist.length - 1];
var cur_dir = cur_hist_item.path;
var smb_param = cur_hist_item.param;
_debug('cur_dir', cur_dir);
_debug('smb_param', smb_param);
if (cur_dir == 'SMB'){
this.load_smb_groups();
return;
}else if (cur_dir == 'SMB_GROUP'){
this.load_smb_servers(smb_param);
return;
}else if (cur_dir == 'SMB_SERVER'){
this.load_smb_shares(smb_param);
return;
}else if (cur_dir == 'FAV'){
var list = [{"name" : "..", "back" : 1}];
list = list.concat(this.favorites);
this.fill_page(list);
return;
}
this.load_mount_data(item || cur_hist_item);
};
this.load_mount_data = function(item){
_debug('media_browser.load_mount_data', item);
if (item && item.hasOwnProperty('full_path')){
if (item.full_path.indexOf('smb://') == 0){
this.smb_path = this.parse_smb_path(item.full_path).path || '';
path = '/ram/mnt/smb/' + this.smb_path;
}else{
path = item.full_path;
}
}else{
var path = this.compile_path();
}
//var path = this.compile_path();
this.path = path;
_debug('path', path);
if (this.change_level){
stb.usbdisk.read_dir(path);
}
//_debug(txt);
//_debug('stb.storages', stb.storages);
_debug('stb.usbdisk.dirs', stb.usbdisk.dirs);
try{
var storage_info = JSON.parse(stb.RDir('get_storage_info'));
}catch(e){
_debug(e);
}
var devices = {};
if (storage_info){
for (var i=0; i<storage_info.length; i++){
devices['USB-' + storage_info[i].sn + '-' + storage_info[i].partitionNum] = storage_info[i].vendor
+ ' ' + storage_info[i].model
+ (storage_info[i].label ? '(' + storage_info[i].label + ')' : '')
+ (storage_info.length > 1 ? ' #' + storage_info[i].partitionNum : '');
}
}
if (this.dir_hist.length == 1){
stb.usbdisk.dirs = stb.usbdisk.dirs.filter(function(el){return !stb.storages.hasOwnProperty(el.substr(0, el.length-1))});
}
_debug('stb.usbdisk.dirs 2', stb.usbdisk.dirs);
var new_dirs = [];
for (var i=0; i < stb.usbdisk.dirs.length; i++){
if (!empty(stb.usbdisk.dirs[i])){
if (devices[stb.usbdisk.dirs[i].substring(0, stb.usbdisk.dirs[i].length - 1)]){
var name = devices[stb.usbdisk.dirs[i].substring(0, stb.usbdisk.dirs[i].length - 1)];
}else{
name = stb.usbdisk.dirs[i].substring(0, stb.usbdisk.dirs[i].length - 1);
}
if (name == 'av'){
name = 'UPnP';
}else if (name.indexOf('USB-') == 0 || name.indexOf('tmp-smb') == 0 || name.indexOf('SAMBA') == 0){
continue;
}
var is_playable = this.is_playable_folder(path+'/'+name);
_debug('is_playable', is_playable);
if (is_playable){
new_dirs.push({"name" : name, "dir" : 1, "dir_name" : stb.usbdisk.dirs[i], "cmd" : "extBDDVD "+path+'/'+name})
}else{
new_dirs.push({"name" : name, "dir" : 1, "dir_name" : stb.usbdisk.dirs[i]})
}
//new_dirs.push({"name" : name, "dir" : 1, "dir_name" : stb.usbdisk.dirs[i]/*, "_id" : this.get_id({"name" : name, "dir_name" : stb.usbdisk.dirs[i]})*/})
}
}
var new_files = [];
for (var i=0; i < stb.usbdisk.files.length; i++){
if (!empty(stb.usbdisk.files[i]) && ['srt', 'sub', 'ass'].indexOf(stb.usbdisk.files[i].name.substring(stb.usbdisk.files[i].name.lastIndexOf('.')+1)) == -1){
if (stb.usbdisk.files[i].name.toLowerCase().indexOf('.iso') == stb.usbdisk.files[i].name.length-4){
var solution = 'extBDDVD';
}else{
solution = 'auto';
}
new_files.push({
"name" : stb.usbdisk.files[i].name,
"cmd" : (solution + " " + path + stb.usbdisk.files[i].name),
"size" : stb.usbdisk.files[i].size,
"last_modified" : (stb.usbdisk.files[i].last_modified || 0)
});
}
}
if (new_files && new_files.length && new_files[0].hasOwnProperty('last_modified') && new_files[0].last_modified){
if (this.sort_by_date){
new_files = this.sort_list_by_date(new_files);
}
this.color_buttons.get('green').enable();
}else{
this.color_buttons.get('green').disable();
}
var list = new_dirs.concat(new_files);
if (this.dir_hist.length == 1){
var clear_arr = [];
}else{
clear_arr = [{"name" : "..", "back" : 1}];
}
for (var i=0; i < list.length; i++){
if (!empty(list[i])){
clear_arr.push(list[i]);
}
}
if (this.dir_hist.length == 1 && stb.GetSmbGroups){
var lan_item = {"name" : "LAN", "dir" : 1, "dir_name" : "SMB"/*, "_id" : this.get_id({"name" : "LAN", "dir_name" : "SMB"})*/};
if (clear_arr.length >= 1){
clear_arr.splice(1, 0, lan_item);
}else{
clear_arr.push(lan_item);
}
}
if (this.dir_hist.length == 1){
var fav_item = {"name" : get_word('media_favorites'), "dir" : 1, "dir_name" : "FAV"};
if (clear_arr.length >= 2){
clear_arr.splice(2, 0, fav_item);
}else{
clear_arr.push(fav_item);
}
}
this.fill_page(clear_arr);
};
this.is_playable_folder = function(path){
_debug('media_browser.is_playable_folder', path);
return stb.IsFolderExist(Utf8.encode(path+'/VIDEO_TS/'))
|| stb.IsFolderExist(Utf8.encode(path+'/BDMV/'))
|| stb.IsFileExist(Utf8.encode(path+'/VIDEO_TS.IFO'))
|| stb.IsFolderExist(Utf8.encode(path+'/video_ts/'))
|| stb.IsFolderExist(Utf8.encode(path+'/bdmv/'))
|| stb.IsFileExist(Utf8.encode(path+'/video_ts.ifo'));
};
this.load_smb_groups = function(){
_debug('media_browser.load_smb_groups');
if (!this.change_level){
this.fill_page(this.cur_dir_list);
return;
}
var groups = JSON.parse(stb.GetSmbGroups());
_debug('groups', groups);
groups.result = groups.result || [];
if (!groups || !groups.result || groups.errMsg){
return;
}
var self = this;
groups = groups.result.map(function(group){
return {"name" : group, "dir" : 1, "dir_name" : "SMB_GROUP"/*, "_id" : self.get_id({"name" : group, "dir_name" : "SMB_GROUP"})*/}
});
groups.unshift({"name" : "..", "back" : 1});
_debug('groups', groups);
this.fill_page(groups);
};
this.load_smb_servers = function(group){
_debug('media_browser.load_smb_servers', group);
if (!this.change_level){
this.fill_page(this.cur_dir_list);
return;
}
var args = '{"group":"' + group + '"}';
_debug('args', args);
var servers = JSON.parse(stb.GetSmbServers(args));
_debug('servers', servers);
if (!servers || !servers.result || servers.errMsg){
return;
}
var self = this;
servers = servers.result.map(function(server){
return {"name" : server, "dir" : 1, "dir_name" : "SMB_SERVER"/*, "_id" : self.get_id({"name" : server, "dir_name" : "SMB_SERVER"})*/}
});
servers.unshift({"name" : "..", "back" : 1});
_debug('servers', servers);
this.fill_page(servers);
};
this.load_smb_shares = function(server){
_debug('media_browser.load_smb_shares', server);
if (!this.change_level){
this.fill_page(this.cur_dir_list);
return;
}
var args = '{"server":"' + server + '"}';
_debug('args', args);
var shares = JSON.parse(stb.GetSmbShares(args));
_debug('shares', shares);
if (!shares || !shares.result || shares.errMsg){
return;
}
shares.result.shares = shares.result.shares || [];
this.smb_server_ip = shares.result.serverIP;
var self = this;
shares = shares.result.shares.map(function(share){
return {"name" : share, "dir" : 1, "dir_name" : "SMB_SHARE"/*, "_id" : self.get_id({"name" : share, "dir_name" : "SMB_SHARE"})*/}
});
shares.unshift({"name" : "..", "back" : 1});
_debug('shares', shares);
this.fill_page(shares);
};
this.mount_smb_share = function(login, password){
_debug('media_browser.mount_smb_share');
/*login = login || "guest";
password = password || "";*/
if (login == undefined){
var auth_params = this.get_auth_params(this.smb_server_ip, this.smb_share);
login = auth_params.login;
password = auth_params.pass;
}
_debug('this.smb_server_ip', this.smb_server_ip);
_debug('this.smb_share', this.smb_share);
_debug('password', password);
_debug('login', login);
var mount_str = 'mount cifs //' + Utf8.encode(this.smb_server_ip + '/' + this.smb_share) + ' /ram/mnt/smb username=' + login + ',password=' + password + ',iocharset=utf8';
_debug('mount_str', mount_str);
var smb_mount_result = stb.RDir(mount_str);
_debug('smb_mount_result', smb_mount_result);
if (smb_mount_result == "Error: mount failed"){
this.on = false;
this.smb_auth_dialog.show();
}else{
if (login != "guest"){
this.save_auth_params(this.smb_server_ip, this.smb_share, login, password)
}
this.in_dir(this.active_item);
}
};
this.save_auth_params = function(server, share, login, password){
_debug('media_browser.save_auth_params', server, share, login, password);
var url = '//' + server + '/' + share;
var idx = this.smb_auth_history.getIdxByVal("url", url);
var save_obj = {"url" : url, "login" : login, "pass" : password, "automount" : 0};
if (idx != null){
this.smb_auth_history[idx] = save_obj;
}else{
this.smb_auth_history.push(save_obj);
}
this.save_smb_passwords();
};
this.get_auth_params = function(server, share){
_debug('media_browser.save_auth_params', server, share);
var url = '//' + server + '/' + share;
var idx = this.smb_auth_history.getIdxByVal("url", url);
if (idx == null){
return {"login" : "guest", "pass" : ""};
}
return {"login" : this.smb_auth_history[idx].login, "pass" : this.smb_auth_history[idx].pass};
};
this.fill_page = function(data){
this.total_pages = Math.ceil(data.length/14);
this.cur_dir_list = data;
if (this.change_level){
var contain_playing_item_idx = this.cur_dir_list.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
_debug('contain_playing_item_idx', contain_playing_item_idx);
}else{
contain_playing_item_idx = null;
}
if (contain_playing_item_idx !== null){
this.cur_page = Math.ceil((contain_playing_item_idx + 1)/ 14);
this.cur_row = contain_playing_item_idx - (this.cur_page - 1) * 14
}
_debug('this.cur_page', this.cur_page);
_debug('this.cur_row', this.cur_row);
if (this.dir_hist.length > 1){
this.set_total_items(data.length - 1);
}else{
this.set_total_items(data.length);
}
var begin = (this.cur_page - 1) * 14;
var end = this.cur_page * 14;
this.data_items = this.cur_dir_list.slice(begin, end);
var self = this;
this.fill_list(this.data_items);
};
this.compile_path = function(){
_debug('media_browser.compile_path');
_debug('this.dir_hist', this.dir_hist);
if (this.dir_hist[this.dir_hist.length - 1].path == 'SMB_SHARE'){
return '/ram/mnt/smb/'
}
var path = '';
for(var i=0; i<this.dir_hist.length; i++){
if (['SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(this.dir_hist[i].path) >= 0){
continue;
}else if (this.dir_hist[i].path == 'SMB'){
path = '/ram/mnt/smb/';
}else if (this.dir_hist[i].hasOwnProperty('full_path')){
path = this.dir_hist[i].full_path;
}else{
path += '/' + this.dir_hist[i].path;
}
}
return path;
};
this.action = function(){
if (this.data_items[this.cur_row].hasOwnProperty('dir') && !this.data_items[this.cur_row].hasOwnProperty('cmd')){
this.check_for_mount(this.data_items[this.cur_row]);
}else if (this.data_items[this.cur_row].hasOwnProperty('back')){
this.out_dir();
}else{
var self = this;
var is_image = this.image_extensions.some(
function(item){
return self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) >= 0 && self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) == self.data_items[self.cur_row].name.length - item.length;
});
_debug('is_image', is_image);
var is_audio = this.audio_extensions.some(
function(item){
return self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) >= 0 && self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) == self.data_items[self.cur_row].name.length - item.length;
});
_debug('is_audio', is_audio);
var item = this.data_items[this.cur_row].clone();
if (is_audio && this.play_all){
item.playlist = this.audio_list;
}
var is_video = this.video_extensions.some(
function(item){
return self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) >= 0 && self.data_items[self.cur_row].name.toLowerCase().lastIndexOf(item) == self.data_items[self.cur_row].name.length - item.length;
});
_debug('is_video', is_video);
if (is_video && this.play_all){
item.playlist = this.video_list;
}
_debug('item', item);
if (is_image){
this.on = false;
module.image_viewer.show(this.image_list, this.data_items[this.cur_row].name, this.compile_path(), this);
}else{
//this.play(this.data_items[this.cur_row]);
this.play(item);
}
}
};
this.play = function(item){
_debug('media_browser.play');
if (stb.player.get_file_type(item) == 'audio'){
this.is_audio = true;
stb.player.need_show_info = 0;
}else{
this.is_audio = false;
this.hide(true);
stb.player.prev_layer = this;
stb.player.need_show_info = 1;
}
_debug('this.dir_hist', this.dir_hist);
_debug('stb.player.on', stb.player.on);
if (stb.player.on){
stb.player.stop();
}
item['subtitles'] = this.find_subtitles(item['cmd']);
stb.player.play(item);
};
this.find_subtitles = function(cmd){
_debug('media_browser.find_subtitles', cmd);
var filename = cmd.substring(cmd.lastIndexOf('/')+1);
if (!filename){
return null;
}
var base = filename.substring(0, filename.lastIndexOf('.'));
_debug('base', base);
if (!base){
return null;
}
_debug('stb.usbdisk.files', stb.usbdisk.files);
var subtitle_files = stb.usbdisk.files.filter(function(item){
_debug('item', item);
_debug('item.name', item.name);
if (item.name){
_debug('item.name.indexOf(base)', item.name.indexOf(base));
_debug('indexOf...', ['srt', 'sub', 'ass'].indexOf(item.name.substring(item.name.lastIndexOf('.')+1)));
}
return item && item.name && item.name.indexOf(base) === 0 && ['srt', 'sub', 'ass'].indexOf(item.name.substring(item.name.lastIndexOf('.')+1)) != -1;
});
_debug('subtitle_files', subtitle_files);
var self = this;
var subtitles = subtitle_files.map(function(item, idx){
var lang = item.name.substring(base.length, item.name.lastIndexOf('.'));
if (lang[0] == '_' || lang[0] == '.'){
lang = lang.substr(1);
}
return {"pid" : 'external_'+idx, "lang" : [lang, ''], "file" : self.path + item.name};
});
_debug('subtitles', subtitles);
return subtitles;
};
this.out_dir = function(){
_debug('out_dir');
if (this.dir_hist.length > 1){
this.dir_hist.pop();
this.reset();
this.cur_row = this.dir_hist[this.dir_hist.length - 1].row;
this.cur_page = this.dir_hist[this.dir_hist.length - 1].page;
this.change_level = true;
this.update_breadcrumbs();
this.load_data();
}
};
this.check_for_mount = function(item){
_debug('media_browser.check_for_mount', item);
//_debug('item.name', item.name);
//_debug('item.name.split()', item.name.split(''));
//item.name.split('').map(function(letter){
// _debug('letter code', letter.charCodeAt(0));
//});
this.active_item = item;
var is_smb = this.dir_hist.some(function(dir){
return ['SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(dir.path) >= 0 || dir.full_path && dir.full_path.indexOf('smb://') == 0;
});
_debug('is_smb', is_smb);
if (is_smb){
var smb_full_path = this.get_full_smb_path(item);
_debug('smb_full_path', smb_full_path);
item.full_path = item._id = smb_full_path;
}
if (item.dir_name == 'SMB_SHARE' || item.hasOwnProperty('full_path') && item.full_path.indexOf('smb://') == 0 && this.parse_smb_path(item.full_path).hasOwnProperty('share')){
stb.ExecAction('make_dir /ram/mnt/smb/');
stb.ExecAction('umount_dir /ram/mnt/smb/');
if (item.hasOwnProperty('full_path')){
var path = this.parse_smb_path(item.full_path);
_debug('smb path', path);
if (path.hasOwnProperty('server')){
this.smb_server_ip = this.get_smb_server_ip_by_name(path.server);
}
if (path.hasOwnProperty('path')){
this.smb_path = path.path;
}else{
this.smb_path = '';
}
if (path.hasOwnProperty('share')){
this.smb_share = path.share;
}
}else{
this.smb_share = item.name;
}
this.mount_smb_share();
return;
}
this.in_dir(item);
};
this.in_dir = function(item){
var dir = item.dir_name;
_debug('in_dir', dir);
this.dir_hist[this.dir_hist.length - 1].page = this.cur_page;
this.dir_hist[this.dir_hist.length - 1].row = this.cur_row;
var hist_item = {'path' : dir , 'param' : item.name, 'page' : 1, 'row' : 1};
if (item.hasOwnProperty('full_path')){
hist_item.full_path = item.full_path;
}
this.dir_hist.push(hist_item);
this.reset();
this.change_level = true;
this.update_breadcrumbs();
this.load_data(item);
};
this.update_breadcrumbs = function(){
_debug('media_browser.update_breadcrumbs');
var breadcrumbs = '';
for(var i=1; i<this.dir_hist.length; i++){
if (this.dir_hist[i].path == 'SMB_GROUP'){
}else if (['SMB', 'SMB_SERVER', 'SMB_SHARE', 'FAV'].indexOf(this.dir_hist[i].path) >= 0 || this.dir_hist[i].path.indexOf('USB-') === 0){
breadcrumbs += this.dir_hist[i].param + '/';
}else{
breadcrumbs += this.dir_hist[i].path;
}
}
breadcrumbs = breadcrumbs.substr(0, breadcrumbs.length - 1);
this.update_header_path([{"alias" : "breadcrumbs", "item" : breadcrumbs}]);
};
this.bind = function(){
this.superclass.bind.apply(this);
this.action.bind(key.OK, this);
/*(function(){
this.hide();
main_menu.show();
}).bind(key.EXIT, this);*/
(function(){
this.hide();
main_menu.show();
}).bind(key.LEFT, this).bind(key.MENU, this);
(function(){
if (this.dir_hist.length == 1){
this.hide();
main_menu.show();
}else{
this.out_dir();
}
}).bind(key.BACK, this).bind(key.EXIT, this);
};
this.fill_list = function(data){
this.data_items = data;
var self = this;
this.data_items = this.data_items.map(function(item){
if (item.cmd == stb.player.cur_media_item.cmd && stb.player.on){
if (stb.player.pause.on){
item.paused = 1;
}else{
item.playing = 1;
}
}
if (item.dir){
item.fav = self.favorites.some(function(favorite){
return favorite._id == (item._id || self.get_id(item));
}) ? 1 : 0;
}
return item;
});
this.get_image_list();
this.get_audio_list();
this.get_video_list();
if (!this.change_level){
if (this.page_dir > 0){
this.cur_row = 0;
}else{
this.cur_row = this.data_items.length - 1;
}
}
this.change_level = false;
this.superclass.fill_list.call(this, data);
};
this.get_image_list = function(){
var self = this;
this.image_list = this.cur_dir_list.filter(function(item){
return self.image_extensions.some(function(ext){
return item.name.toLowerCase().lastIndexOf(ext) >= 0 && item.name.toLowerCase().lastIndexOf(ext) == item.name.length - ext.length;
});
});
_debug('this.image_list', this.image_list);
};
this.get_audio_list = function(){
_debug('media_browser.get_audio_list');
var self = this;
var path = this.compile_path();
_debug('path', path);
_debug('this.cur_dir_list', this.cur_dir_list);
this.audio_list = this.cur_dir_list.filter(function(item){
return new RegExp("(" + self.audio_extensions.join("|") + ")$").test(item.name);
});
this.audio_list = this.audio_list.map(function(item){
//return 'auto ' + path + item.name;
return item.cmd;
});
_debug('this.audio_list', this.audio_list);
};
this.get_video_list = function(){
var self = this;
var path = this.compile_path();
this.video_list = this.cur_dir_list.filter(function(item){
return new RegExp("(" + self.video_extensions.join("|") + ")$").test(item.name);
});
this.video_list = this.video_list.map(function(item){
//return 'auto ' + path + item.name;
return item.cmd;
});
_debug('this.video_list', this.video_list);
};
this.set_active_row = function(num){
_debug('media_browser.set_active_row', num);
this.superclass.set_active_row.call(this, num);
_debug('this.data_items[this.cur_row].cmd', this.data_items[this.cur_row].cmd);
_debug('stb.player.cur_media_item.cmd', stb.player.cur_media_item.cmd);
_debug('stb.player.on', stb.player.on);
if (this.data_items[this.cur_row].cmd == stb.player.cur_media_item.cmd && stb.player.on && stb.player.file_type == 'audio'){
this.active_row['row'].setAttribute("status", "playing");
this.active_row['row'].addClass("playing");
if (this.active_row.seek_bar_block.childNodes.length > 0){
this.active_row.seek_bar_block.childNodes[0].style.width = 0;
}
this.active_row.seek_bar_block.show();
this._start_updating_seek_bar();
}else{
this.active_row['row'].setAttribute("status", "");
this.active_row['row'].removeClass("playing");
this.active_row.seek_bar_block.hide();
if (this.active_row.seek_bar_block.childNodes.length > 0){
this.active_row.seek_bar_block.childNodes[0].style.width = 0;
}
window.clearInterval(this.seek_bar_interval);
}
if (this.data_items[this.cur_row].dir && this.dir_hist.length>1){
this.color_buttons.get('yellow').enable();
}else{
this.color_buttons.get('yellow').disable();
}
_debug('this.active_row[row].getAttribute(status)', this.active_row['row'].getAttribute("status"));
};
this._start_updating_seek_bar = function(){
_debug('media_browser._start_updating_seek_bar');
var self = this;
window.clearInterval(this.seek_bar_interval);
this._update_seek_bar();
this.seek_bar_interval = window.setInterval(function(){
self._update_seek_bar();
}, 1000);
};
this._update_seek_bar = function(){
if (this.active_row.seek_bar_block.childNodes.length == 0){
var inner = create_block_element("seek_bar_inner", this.active_row.seek_bar_block);
}else{
inner = this.active_row.seek_bar_block.childNodes[0];
}
var pos_time = stb.GetPosTime();
var media_len = stb.GetMediaLen();
_debug('pos_time', pos_time);
_debug('media_len', media_len);
_debug('this.active_row.seek_bar_block.offsetWidth', this.active_row.seek_bar_block.offsetWidth);
var width = this.active_row.seek_bar_block.offsetWidth * pos_time / media_len;
_debug('width', width);
if (width > this.active_row.seek_bar_block.offsetWidth){
width = this.active_row.seek_bar_block.offsetWidth;
}
if (media_len == 0){
width = 0;
}
_debug('width 2', width);
inner.style.width = width + 'px';
};
this.play_all_switch = function(){
_debug('media_browser.play_all_switch');
this.play_all = !this.play_all;
_debug('this.play_all', this.play_all);
this.refresh_play_all_switch();
};
this.refresh_play_all_switch = function(){
_debug('media_browser.refresh_play_all_switch');
_debug('this.play_all', this.play_all);
this.color_buttons.get("red").text_obj.innerHTML = get_word('play_all') + ": " + (this.play_all ? get_word('on') : get_word('off'));
};
this.add_del_fav = function(){
_debug('media_browser.add_del_fav');
_debug('this.data_items[this.cur_row]', this.data_items[this.cur_row]);
if (!this.data_items[this.cur_row].hasOwnProperty('dir') || this.data_items[this.cur_row].dir != '1'){
return;
}
var _id = this.data_items[this.cur_row]._id || this.get_id(this.data_items[this.cur_row]);
_debug('_id', _id);
var idx = this.favorites.getIdxByVal('_id', _id);
_debug('idx', idx);
this.data_items[this.cur_row]._id = _id;
this.data_items[this.cur_row].full_path = this.data_items[this.cur_row].full_path || this.get_full_path(this.data_items[this.cur_row]);
if (this.data_items[this.cur_row].fav){
this.del_from_fav(this.data_items[this.cur_row]);
}else{
this.add_to_fav(this.data_items[this.cur_row]);
}
this.save_favorites();
};
this.add_to_fav = function(item){
_debug('media_browser.add_to_fav');
this.data_items[this.cur_row].fav = 1;
this.map[this.cur_row].fav_block.show();
this.active_row.fav_block.show();
this.favorites.push(item);
};
this.del_from_fav = function(item){
_debug('media_browser.del_from_fav');
this.data_items[this.cur_row].fav = 0;
this.map[this.cur_row].fav_block.hide();
this.active_row.fav_block.hide();
var idx = this.favorites.getIdxByVal('_id', item._id);
_debug('idx', idx);
if (idx !== null){
this.favorites.splice(idx, 1);
}
};
this.get_full_path = function(item){
_debug('media_browser.get_full_path');
_debug('this.dir_hist', this.dir_hist);
var is_smb = this.dir_hist.some(function(dir){
return ['SMB', 'SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(dir.path) >= 0;
}) || item.dir_name == 'SMB';
_debug('is_smb', is_smb);
if (is_smb){
var smb_full_path = this.get_full_smb_path(item);
_debug('smb_full_path', smb_full_path);
return smb_full_path;
}
var full_path = this.compile_path();
_debug('full_path 1', full_path);
if (full_path[full_path.length-1] == '/'){
//full_path = full_path.substring(0, full_path.length-1);
}
_debug('full_path 2', full_path);
return full_path + '/' + item.dir_name;
};
this.get_full_smb_path = function(item){
_debug('media_browser.get_full_smb_path');
_debug('this.dir_hist', this.dir_hist);
var path = 'smb:/';
for(var i=0; i<this.dir_hist.length; i++){
/*if (this.dir_hist[i].path == 'SMB'){
path = 'smb:/';*/
if (this.dir_hist[i].hasOwnProperty('full_path')){
path = this.dir_hist[i].full_path;
}else if (this.dir_hist[i].path == 'SMB'){
path = 'smb:/';
}else /*if (['SMB_GROUP', 'SMB_SERVER', 'SMB_SHARE'].indexOf(this.dir_hist[i].path) >= 0)*/{
path += '/' + this.dir_hist[i].param;
}
}
return path + '/' + item.name;
};
this.parse_smb_path = function(full_path){
_debug('media_browser.parse_smb_path', full_path);
var path = {};
var match = full_path.match("smb://([^\/]*)\/?([^\/]*)\/?([^\/]*)\/?(.*)");
_debug('match', match);
if (match){
if (match[1]){
path.workgroup = match[1];
}
if (match[2]){
path.server = match[2];
}
if (match[3]){
path.share = match[3];
}
if (match[4]){
path.path = match[4] + '/';
}
}
return path;
};
this.get_smb_server_ip_by_name = function(name){
_debug('media_browser.get_smb_server_ip_by_name', name);
var args = '{"server":"' + name + '"}';
_debug('args', args);
var shares = JSON.parse(stb.GetSmbShares(args));
_debug('shares', shares);
if (!shares || !shares.result || shares.errMsg){
return null;
}
shares.result.shares = shares.result.shares || [];
return shares.result.serverIP;
};
this.get_id = function(item){
_debug('media_browser.get_id', item);
return this.get_full_path(item);
};
this.get_favorites = function(){
_debug('media_browser.get_favorites');
stb.load(
{
"type" : "media_favorites",
"action" : "get_all"
},
function(result){
_debug('on get_favorites', result);
this.favorites = result && JSON.parse(result) || [];
},
this
)
};
this.save_favorites = function(){
_debug('media_browser.save_favorites');
stb.load(
{
"type" : "media_favorites",
"action" : "save",
"favorites" : JSON.stringify(this.favorites)
},
function(result){
_debug("on save_favorites", result);
},
this
);
};
this.init_sort_menu = function(map, options){
_debug('media_browser.init_sort_menu');
this.sort_menu = new bottom_menu(this, options);
this.sort_menu.init(map);
this.sort_menu.bind();
};
this.sort_menu_switcher = function(){
_debug('media_browser.sort_menu_switcher');
if (this.sort_menu && this.sort_menu.on){
this.sort_menu.hide();
}else{
this.sort_menu.show();
}
};
this.sort_list_by_date = function(list){
_debug('media_browser.sort_list_by_date', list);
var times = list.map(function(item){
return (item.last_modified || 0)+'_'+item.name;
});
times.sort(function(a,b){return parseInt(b, 10) - parseInt(a, 10)});
_debug('times', times);
var sorted_list = [];
list.every(function(item){
var idx = times.indexOf(item.last_modified+'_'+item.name);
sorted_list[idx] = item;
return true;
});
_debug('sorted_list', sorted_list);
return sorted_list;
};
}
var Utf8 = {
// public method for url encoding
encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// public method for url decoding
decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
media_browser_constructor.prototype = new ListLayer();
var media_browser = new media_browser_constructor();
media_browser.bind();
media_browser.init();
media_browser.set_wide_container();
media_browser.init_left_ear(word['ears_back']);
media_browser.init_header_path(word['mbrowser_title']);
media_browser.init_color_buttons([
{"label" : word['play_all'], "cmd" : media_browser.play_all_switch},
{"label" : word['tv_sort'], "cmd" : media_browser.sort_menu_switcher},
{"label" : get_word('favorite'), "cmd" : media_browser.add_del_fav},
{"label" : word['empty'], "cmd" : ""}
]);
var sort_menu_map = [
{
"label" : get_word("mbrowser_sort_by_name"),
"cmd" : function(){
this.parent.sort_by_date = false;
},
"selector" : "*"
},
{
"label" : get_word("mbrowser_sort_by_date"),
"cmd" : function(){
this.parent.sort_by_date = true;
}
}
];
media_browser.init_sort_menu(
sort_menu_map,
{
"color" : "green",
"need_update_header" : false
}
);
media_browser.hide();
module.media_browser = media_browser;
/* END MEDIA BROWSER */
main_menu.add(word['mbrowser_title'], [], 'mm_ico_usb.png', function(){
main_menu.hide();
module.media_browser.show();
},
module.media_browser
);
})();
loader.next(); | Fix media browser (issue #1565)
| c/media_browser.js | Fix media browser (issue #1565) | <ide><path>/media_browser.js
<ide>
<ide> this.cur_dir_list = data;
<ide>
<del> if (this.change_level){
<add> if (stb.player.cur_media_item && this.change_level){
<ide> var contain_playing_item_idx = this.cur_dir_list.getIdxByVal("cmd", stb.player.cur_media_item.cmd);
<ide>
<ide> _debug('contain_playing_item_idx', contain_playing_item_idx);
<ide>
<ide> this.data_items = this.data_items.map(function(item){
<ide>
<del> if (item.cmd == stb.player.cur_media_item.cmd && stb.player.on){
<add> if (stb.player.cur_media_item && item.cmd == stb.player.cur_media_item.cmd && stb.player.on){
<ide> if (stb.player.pause.on){
<ide> item.paused = 1;
<ide> }else{
<ide> this.superclass.set_active_row.call(this, num);
<ide>
<ide> _debug('this.data_items[this.cur_row].cmd', this.data_items[this.cur_row].cmd);
<del> _debug('stb.player.cur_media_item.cmd', stb.player.cur_media_item.cmd);
<ide> _debug('stb.player.on', stb.player.on);
<ide>
<del> if (this.data_items[this.cur_row].cmd == stb.player.cur_media_item.cmd && stb.player.on && stb.player.file_type == 'audio'){
<add> if (stb.player.cur_media_item && this.data_items[this.cur_row].cmd == stb.player.cur_media_item.cmd && stb.player.on && stb.player.file_type == 'audio'){
<ide>
<ide> this.active_row['row'].setAttribute("status", "playing");
<ide> |
|
Java | apache-2.0 | c3dc3a2c378d6980b5d9d816979f1ec83bfbd495 | 0 | ctripcorp/zeus,sdgdsffdsfff/zeus,ctripcorp/zeus,ctripcorp/zeus,ctripcorp/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus | package com.ctrip.zeus.restful.resource;
import com.ctrip.zeus.auth.Authorize;
import com.ctrip.zeus.exceptions.ValidationException;
import com.ctrip.zeus.executor.TaskManager;
import com.ctrip.zeus.model.entity.*;
import com.ctrip.zeus.restful.message.ResponseHandler;
import com.ctrip.zeus.service.build.ConfigHandler;
import com.ctrip.zeus.service.message.queue.MessageQueue;
import com.ctrip.zeus.service.message.queue.MessageType;
import com.ctrip.zeus.service.model.*;
import com.ctrip.zeus.service.model.handler.GroupValidator;
import com.ctrip.zeus.service.model.handler.TrafficPolicyValidator;
import com.ctrip.zeus.service.query.GroupCriteriaQuery;
import com.ctrip.zeus.service.task.constant.TaskOpsType;
import com.ctrip.zeus.tag.PropertyBox;
import com.ctrip.zeus.task.entity.OpsTask;
import com.ctrip.zeus.task.entity.TaskResult;
import com.ctrip.zeus.task.entity.TaskResultList;
import com.ctrip.zeus.util.MessageUtil;
import com.google.common.base.Joiner;
import com.netflix.config.DynamicLongProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.util.*;
/**
* Created by fanqq on 2015/6/11.
*/
@Component
@Path("/deactivate")
public class DeactivateResource {
@Resource
private PropertyBox propertyBox;
@Resource
private SlbRepository slbRepository;
@Resource
private ResponseHandler responseHandler;
@Resource
private TaskManager taskManager;
@Resource
private EntityFactory entityFactory;
@Resource
private GroupCriteriaQuery groupCriteriaQuery;
@Resource
private TrafficPolicyValidator trafficPolicyValidator;
@Resource
private GroupValidator groupValidator;
@Resource
private MessageQueue messageQueue;
@Resource
private ConfigHandler configHandler;
@Resource
private TrafficPolicyRepository trafficPolicyRepository;
private static DynamicLongProperty apiTimeout = DynamicPropertyFactory.getInstance().getLongProperty("api.timeout", 15000L);
@GET
@Path("/group")
@Authorize(name = "deactivate")
public Response deactivateGroup(@Context HttpServletRequest request, @Context HttpHeaders hh, @QueryParam("groupId") List<Long> groupIds, @QueryParam("groupName") List<String> groupNames) throws Exception {
Set<Long> _groupIds = new HashSet<>();
if (groupIds != null && !groupIds.isEmpty()) {
_groupIds.addAll(groupIds);
}
if (groupNames != null && !groupNames.isEmpty()) {
for (String groupName : groupNames) {
Long groupId = groupCriteriaQuery.queryByName(groupName);
if (groupId != null && !groupId.equals(0L)) {
_groupIds.add(groupId);
}
}
}
Long[] gids = _groupIds.toArray(new Long[]{});
ModelStatusMapping<Group> groupMap = entityFactory.getGroupsByIds(gids);
groupValidator.validateForDeactivate(gids);
_groupIds.removeAll(groupMap.getOnlineMapping().keySet());
if (_groupIds.size() > 0) {
throw new ValidationException("Groups with id (" + Joiner.on(",").join(_groupIds) + ") are not activated.");
}
Set<Long> vsIds = new HashSet<>();
for (Map.Entry<Long, Group> e : groupMap.getOnlineMapping().entrySet()) {
Group group = e.getValue();
if (group == null) {
throw new Exception("Unexpected online group with null value. groupId=" + e.getKey() + ".");
}
for (GroupVirtualServer vs : group.getGroupVirtualServers()) {
vsIds.add(vs.getVirtualServer().getId());
}
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(vsIds.toArray(new Long[]{}));
List<OpsTask> tasks = new ArrayList<>();
for (Map.Entry<Long, Group> e : groupMap.getOnlineMapping().entrySet()) {
Group group = e.getValue();
Set<Long> slbIds = new HashSet<>();
for (GroupVirtualServer gvs : group.getGroupVirtualServers()) {
VirtualServer vs = vsMap.getOnlineMapping().get(gvs.getVirtualServer().getId());
if (vs == null) {
throw new ValidationException("Virtual server " + gvs.getVirtualServer().getId() + " is found deactivated.");
}
slbIds.addAll(vs.getSlbIds());
}
for (Long slbId : slbIds) {
OpsTask task = new OpsTask();
task.setGroupId(e.getKey());
task.setOpsType(TaskOpsType.DEACTIVATE_GROUP);
task.setTargetSlbId(slbId);
tasks.add(task);
}
}
List<Long> taskIds = taskManager.addTask(tasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
try {
propertyBox.set("status", "deactivated", "group", groupMap.getOnlineMapping().keySet().toArray(new Long[groupMap.getOnlineMapping().size()]));
} catch (Exception ex) {
}
String slbMessageData = MessageUtil.getMessageData(request,
groupMap.getOfflineMapping().values().toArray(new Group[groupMap.getOfflineMapping().size()]), null, null, null, true);
for (Long id : groupMap.getOfflineMapping().keySet()) {
if (configHandler.getEnable("use.new,message.queue.producer", false)) {
messageQueue.produceMessage(request.getRequestURI(), id, slbMessageData);
} else {
messageQueue.produceMessage(MessageType.DeactivateGroup, id, slbMessageData);
}
}
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/vs")
@Authorize(name = "activate")
public Response deactivateVirtualServer(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId) throws Exception {
Set<IdVersion> relatedGroupIds = groupCriteriaQuery.queryByVsId(vsId);
if (relatedGroupIds.size() > 0) {
Set<Long> groupIds = new HashSet<>();
for (IdVersion key : relatedGroupIds) {
groupIds.add(key.getId());
}
relatedGroupIds.retainAll(groupCriteriaQuery.queryByIdsAndMode(groupIds.toArray(new Long[groupIds.size()]), SelectionMode.ONLINE_EXCLUSIVE));
if (relatedGroupIds.size() > 0) {
throw new ValidationException("Activated groups are found related to Vs[" + vsId + "].");
}
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
if (vsMap.getOnlineMapping() == null || vsMap.getOnlineMapping().get(vsId) == null) {
throw new ValidationException("Vs is not activated. VsId:" + vsId);
}
VirtualServer vs = vsMap.getOnlineMapping().get(vsId);
List<OpsTask> deactivatingTask = new ArrayList<>();
for (Long slbId : vs.getSlbIds()) {
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId);
task.setCreateTime(new Date());
task.setOpsType(TaskOpsType.DEACTIVATE_VS);
task.setTargetSlbId(slbId);
deactivatingTask.add(task);
}
List<Long> taskIds = taskManager.addTask(deactivatingTask);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
try {
propertyBox.set("status", "deactivated", "vs", vsId);
} catch (Exception ex) {
}
String slbMessageData = MessageUtil.getMessageData(request, null,
new VirtualServer[]{vsMap.getOfflineMapping().get(vsId)}, null, null, true);
if (configHandler.getEnable("use.new,message.queue.producer", false)) {
messageQueue.produceMessage(request.getRequestURI(), vsId, slbMessageData);
} else {
messageQueue.produceMessage(MessageType.DeactivateVs, vsId, slbMessageData);
}
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/soft/group")
@Authorize(name = "activate")
public Response softDeactivateGroup(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId,
@QueryParam("groupId") Long groupId) throws Exception {
IdVersion[] groupIdsOffline = groupCriteriaQuery.queryByIdAndMode(groupId, SelectionMode.OFFLINE_FIRST);
if (groupIdsOffline.length == 0) {
throw new ValidationException("Cannot find group by groupId-" + groupId + ".");
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
if (vsMap.getOnlineMapping() == null || vsMap.getOnlineMapping().get(vsId) == null) {
throw new ValidationException("Vs is not activated.VsId:" + vsId);
}
VirtualServer vs = vsMap.getOnlineMapping().get(vsId);
List<OpsTask> softDeactivatingTasks = new ArrayList<>();
for (Long slbId : vs.getSlbIds()) {
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId);
task.setCreateTime(new Date());
task.setOpsType(TaskOpsType.SOFT_DEACTIVATE_GROUP);
task.setTargetSlbId(slbId);
task.setGroupId(groupId);
task.setVersion(groupIdsOffline[0].getVersion());
softDeactivatingTasks.add(task);
}
List<Long> taskIds = taskManager.addTask(softDeactivatingTasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/soft/vs")
public Response activateVirtualServer(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId,
@QueryParam("slbId") Long slbId) throws Exception {
if (vsId == null || slbId == null) {
throw new ValidationException("Query param vsId, slbId are required.");
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
VirtualServer offlineVersion = vsMap.getOfflineMapping().get(vsId);
if (offlineVersion == null) {
throw new ValidationException("Cannot find vs by id " + vsId + ".");
}
ModelStatusMapping<Slb> slbMap = entityFactory.getSlbsByIds(new Long[]{slbId});
Slb slb = slbMap.getOnlineMapping().get(slbId);
if (slb == null) {
throw new Exception("Slb " + slbId + " is found deactivated.");
}
List<OpsTask> tasks = new ArrayList<>();
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId)
.setTargetSlbId(slbId)
.setVersion(offlineVersion.getVersion())
.setOpsType(TaskOpsType.SOFT_DEACTIVATE_VS)
.setCreateTime(new Date());
tasks.add(task);
List<Long> taskIds = taskManager.addTask(tasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/slb")
@Authorize(name = "activate")
public Response deactivateSlb(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("slbId") Long slbId) throws Exception {
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesBySlbIds(slbId);
if (vsMap.getOnlineMapping() != null && vsMap.getOnlineMapping().size() > 0) {
throw new ValidationException("Has Activated Vses Related to Slb[" + slbId + "]");
}
IdVersion idVersion = new IdVersion(slbId, 0);
slbRepository.updateStatus(new IdVersion[]{idVersion});
try {
propertyBox.set("status", "deactivated", "slb", slbId);
} catch (Exception ex) {
}
Slb slb = slbRepository.getById(slbId);
String slbMessageData = MessageUtil.getMessageData(request, null, null,
new Slb[]{slb}, null, true);
if (configHandler.getEnable("use.new,message.queue.producer", false)) {
messageQueue.produceMessage(request.getRequestURI(), slbId, slbMessageData);
} else {
messageQueue.produceMessage(MessageType.DeactivateSlb, slbId, slbMessageData);
}
return responseHandler.handle(slb, hh.getMediaType());
}
@GET
@Path("/soft/policy")
@Authorize(name = "activate")
public Response softDeactivatePolicy(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId,
@QueryParam("policyId") Long policyId) throws Exception {
TrafficPolicy policy = trafficPolicyRepository.getById(policyId);
if (policy == null) {
throw new ValidationException("Cannot find policy by Id-" + policyId + ".");
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
if (vsMap.getOnlineMapping() == null || vsMap.getOnlineMapping().get(vsId) == null) {
throw new ValidationException("Vs is not activated.VsId:" + vsId);
}
VirtualServer vs = vsMap.getOnlineMapping().get(vsId);
List<OpsTask> softDeactivatingTasks = new ArrayList<>();
for (Long slbId : vs.getSlbIds()) {
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId);
task.setCreateTime(new Date());
task.setOpsType(TaskOpsType.SOFT_DEACTIVATE_POLICY);
task.setTargetSlbId(slbId);
task.setPolicyId(policyId);
task.setVersion(policy.getVersion());
softDeactivatingTasks.add(task);
}
List<Long> taskIds = taskManager.addTask(softDeactivatingTasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/policy")
@Authorize(name = "deactivate")
public Response deactivatePolicy(@Context HttpServletRequest request, @Context HttpHeaders hh, @QueryParam("policyId") List<Long> policyIds) throws Exception {
ModelStatusMapping<TrafficPolicy> tpMap = entityFactory.getPoliciesByIds(policyIds.toArray(new Long[]{}));
if (!tpMap.getOnlineMapping().keySet().containsAll(policyIds)) {
throw new ValidationException("Have inactivated policy in " + Joiner.on(",").join(policyIds));
}
trafficPolicyValidator.validateForDeactivate(policyIds.toArray(new Long[]{}));
Set<Long> vsIds = new HashSet<>();
for (Map.Entry<Long, TrafficPolicy> e : tpMap.getOnlineMapping().entrySet()) {
TrafficPolicy policy = e.getValue();
if (policy == null) {
throw new Exception("Unexpected online group with null value. groupId=" + e.getKey() + ".");
}
for (PolicyVirtualServer vs : policy.getPolicyVirtualServers()) {
vsIds.add(vs.getVirtualServer().getId());
}
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(vsIds.toArray(new Long[]{}));
List<OpsTask> tasks = new ArrayList<>();
for (Map.Entry<Long, TrafficPolicy> e : tpMap.getOnlineMapping().entrySet()) {
TrafficPolicy policy = e.getValue();
Set<Long> slbIds = new HashSet<>();
for (PolicyVirtualServer pvs : policy.getPolicyVirtualServers()) {
VirtualServer vs = vsMap.getOnlineMapping().get(pvs.getVirtualServer().getId());
if (vs == null) {
throw new ValidationException("Virtual server " + pvs.getVirtualServer().getId() + " is found deactivated.");
}
slbIds.addAll(vs.getSlbIds());
}
for (Long slbId : slbIds) {
OpsTask task = new OpsTask();
task.setPolicyId(e.getKey());
task.setOpsType(TaskOpsType.DEACTIVATE_POLICY);
task.setTargetSlbId(slbId);
tasks.add(task);
}
}
List<Long> taskIds = taskManager.addTask(tasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
try {
propertyBox.set("status", "deactivated", "policy", tpMap.getOnlineMapping().keySet().toArray(new Long[tpMap.getOnlineMapping().size()]));
} catch (Exception ex) {
}
String slbMessageData = MessageUtil.getMessageData(request,
null, null, null, null, true);
for (Long id : tpMap.getOfflineMapping().keySet()) {
messageQueue.produceMessage(request.getRequestURI(), id, slbMessageData);
}
return responseHandler.handle(resultList, hh.getMediaType());
}
}
| src/main/java/com/ctrip/zeus/restful/resource/DeactivateResource.java | package com.ctrip.zeus.restful.resource;
import com.ctrip.zeus.auth.Authorize;
import com.ctrip.zeus.exceptions.ValidationException;
import com.ctrip.zeus.executor.TaskManager;
import com.ctrip.zeus.model.entity.*;
import com.ctrip.zeus.restful.message.ResponseHandler;
import com.ctrip.zeus.service.build.ConfigHandler;
import com.ctrip.zeus.service.message.queue.MessageQueue;
import com.ctrip.zeus.service.message.queue.MessageType;
import com.ctrip.zeus.service.model.*;
import com.ctrip.zeus.service.query.GroupCriteriaQuery;
import com.ctrip.zeus.service.task.constant.TaskOpsType;
import com.ctrip.zeus.tag.PropertyBox;
import com.ctrip.zeus.task.entity.OpsTask;
import com.ctrip.zeus.task.entity.TaskResult;
import com.ctrip.zeus.task.entity.TaskResultList;
import com.ctrip.zeus.util.MessageUtil;
import com.google.common.base.Joiner;
import com.netflix.config.DynamicLongProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.util.*;
/**
* Created by fanqq on 2015/6/11.
*/
@Component
@Path("/deactivate")
public class DeactivateResource {
@Resource
private PropertyBox propertyBox;
@Resource
private SlbRepository slbRepository;
@Resource
private ResponseHandler responseHandler;
@Resource
private TaskManager taskManager;
@Resource
private EntityFactory entityFactory;
@Resource
private GroupCriteriaQuery groupCriteriaQuery;
@Resource
private MessageQueue messageQueue;
@Resource
private ConfigHandler configHandler;
@Resource
private TrafficPolicyRepository trafficPolicyRepository;
private static DynamicLongProperty apiTimeout = DynamicPropertyFactory.getInstance().getLongProperty("api.timeout", 15000L);
@GET
@Path("/group")
@Authorize(name = "deactivate")
public Response deactivateGroup(@Context HttpServletRequest request, @Context HttpHeaders hh, @QueryParam("groupId") List<Long> groupIds, @QueryParam("groupName") List<String> groupNames) throws Exception {
Set<Long> _groupIds = new HashSet<>();
if (groupIds != null && !groupIds.isEmpty()) {
_groupIds.addAll(groupIds);
}
if (groupNames != null && !groupNames.isEmpty()) {
for (String groupName : groupNames) {
Long groupId = groupCriteriaQuery.queryByName(groupName);
if (groupId != null && !groupId.equals(0L)) {
_groupIds.add(groupId);
}
}
}
ModelStatusMapping<Group> groupMap = entityFactory.getGroupsByIds(_groupIds.toArray(new Long[]{}));
_groupIds.removeAll(groupMap.getOnlineMapping().keySet());
if (_groupIds.size() > 0) {
throw new ValidationException("Groups with id (" + Joiner.on(",").join(_groupIds) + ") are not activated.");
}
Set<Long> vsIds = new HashSet<>();
for (Map.Entry<Long, Group> e : groupMap.getOnlineMapping().entrySet()) {
Group group = e.getValue();
if (group == null) {
throw new Exception("Unexpected online group with null value. groupId=" + e.getKey() + ".");
}
for (GroupVirtualServer vs : group.getGroupVirtualServers()) {
vsIds.add(vs.getVirtualServer().getId());
}
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(vsIds.toArray(new Long[]{}));
List<OpsTask> tasks = new ArrayList<>();
for (Map.Entry<Long, Group> e : groupMap.getOnlineMapping().entrySet()) {
Group group = e.getValue();
Set<Long> slbIds = new HashSet<>();
for (GroupVirtualServer gvs : group.getGroupVirtualServers()) {
VirtualServer vs = vsMap.getOnlineMapping().get(gvs.getVirtualServer().getId());
if (vs == null) {
throw new ValidationException("Virtual server " + gvs.getVirtualServer().getId() + " is found deactivated.");
}
slbIds.addAll(vs.getSlbIds());
}
for (Long slbId : slbIds) {
OpsTask task = new OpsTask();
task.setGroupId(e.getKey());
task.setOpsType(TaskOpsType.DEACTIVATE_GROUP);
task.setTargetSlbId(slbId);
tasks.add(task);
}
}
List<Long> taskIds = taskManager.addTask(tasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
try {
propertyBox.set("status", "deactivated", "group", groupMap.getOnlineMapping().keySet().toArray(new Long[groupMap.getOnlineMapping().size()]));
} catch (Exception ex) {
}
String slbMessageData = MessageUtil.getMessageData(request,
groupMap.getOfflineMapping().values().toArray(new Group[groupMap.getOfflineMapping().size()]), null, null, null, true);
for (Long id : groupMap.getOfflineMapping().keySet()) {
if (configHandler.getEnable("use.new,message.queue.producer", false)) {
messageQueue.produceMessage(request.getRequestURI(), id, slbMessageData);
} else {
messageQueue.produceMessage(MessageType.DeactivateGroup, id, slbMessageData);
}
}
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/vs")
@Authorize(name = "activate")
public Response deactivateVirtualServer(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId) throws Exception {
Set<IdVersion> relatedGroupIds = groupCriteriaQuery.queryByVsId(vsId);
if (relatedGroupIds.size() > 0) {
Set<Long> groupIds = new HashSet<>();
for (IdVersion key : relatedGroupIds) {
groupIds.add(key.getId());
}
relatedGroupIds.retainAll(groupCriteriaQuery.queryByIdsAndMode(groupIds.toArray(new Long[groupIds.size()]), SelectionMode.ONLINE_EXCLUSIVE));
if (relatedGroupIds.size() > 0) {
throw new ValidationException("Activated groups are found related to Vs[" + vsId + "].");
}
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
if (vsMap.getOnlineMapping() == null || vsMap.getOnlineMapping().get(vsId) == null) {
throw new ValidationException("Vs is not activated. VsId:" + vsId);
}
VirtualServer vs = vsMap.getOnlineMapping().get(vsId);
List<OpsTask> deactivatingTask = new ArrayList<>();
for (Long slbId : vs.getSlbIds()) {
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId);
task.setCreateTime(new Date());
task.setOpsType(TaskOpsType.DEACTIVATE_VS);
task.setTargetSlbId(slbId);
deactivatingTask.add(task);
}
List<Long> taskIds = taskManager.addTask(deactivatingTask);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
try {
propertyBox.set("status", "deactivated", "vs", vsId);
} catch (Exception ex) {
}
String slbMessageData = MessageUtil.getMessageData(request, null,
new VirtualServer[]{vsMap.getOfflineMapping().get(vsId)}, null, null, true);
if (configHandler.getEnable("use.new,message.queue.producer", false)) {
messageQueue.produceMessage(request.getRequestURI(), vsId, slbMessageData);
} else {
messageQueue.produceMessage(MessageType.DeactivateVs, vsId, slbMessageData);
}
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/soft/group")
@Authorize(name = "activate")
public Response softDeactivateGroup(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId,
@QueryParam("groupId") Long groupId) throws Exception {
IdVersion[] groupIdsOffline = groupCriteriaQuery.queryByIdAndMode(groupId, SelectionMode.OFFLINE_FIRST);
if (groupIdsOffline.length == 0) {
throw new ValidationException("Cannot find group by groupId-" + groupId + ".");
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
if (vsMap.getOnlineMapping() == null || vsMap.getOnlineMapping().get(vsId) == null) {
throw new ValidationException("Vs is not activated.VsId:" + vsId);
}
VirtualServer vs = vsMap.getOnlineMapping().get(vsId);
List<OpsTask> softDeactivatingTasks = new ArrayList<>();
for (Long slbId : vs.getSlbIds()) {
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId);
task.setCreateTime(new Date());
task.setOpsType(TaskOpsType.SOFT_DEACTIVATE_GROUP);
task.setTargetSlbId(slbId);
task.setGroupId(groupId);
task.setVersion(groupIdsOffline[0].getVersion());
softDeactivatingTasks.add(task);
}
List<Long> taskIds = taskManager.addTask(softDeactivatingTasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/soft/vs")
public Response activateVirtualServer(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId,
@QueryParam("slbId") Long slbId) throws Exception {
if (vsId == null || slbId == null) {
throw new ValidationException("Query param vsId, slbId are required.");
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
VirtualServer offlineVersion = vsMap.getOfflineMapping().get(vsId);
if (offlineVersion == null) {
throw new ValidationException("Cannot find vs by id " + vsId + ".");
}
ModelStatusMapping<Slb> slbMap = entityFactory.getSlbsByIds(new Long[]{slbId});
Slb slb = slbMap.getOnlineMapping().get(slbId);
if (slb == null) {
throw new Exception("Slb " + slbId + " is found deactivated.");
}
List<OpsTask> tasks = new ArrayList<>();
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId)
.setTargetSlbId(slbId)
.setVersion(offlineVersion.getVersion())
.setOpsType(TaskOpsType.SOFT_DEACTIVATE_VS)
.setCreateTime(new Date());
tasks.add(task);
List<Long> taskIds = taskManager.addTask(tasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/slb")
@Authorize(name = "activate")
public Response deactivateSlb(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("slbId") Long slbId) throws Exception {
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesBySlbIds(slbId);
if (vsMap.getOnlineMapping() != null && vsMap.getOnlineMapping().size() > 0) {
throw new ValidationException("Has Activated Vses Related to Slb[" + slbId + "]");
}
IdVersion idVersion = new IdVersion(slbId, 0);
slbRepository.updateStatus(new IdVersion[]{idVersion});
try {
propertyBox.set("status", "deactivated", "slb", slbId);
} catch (Exception ex) {
}
Slb slb = slbRepository.getById(slbId);
String slbMessageData = MessageUtil.getMessageData(request, null, null,
new Slb[]{slb}, null, true);
if (configHandler.getEnable("use.new,message.queue.producer", false)) {
messageQueue.produceMessage(request.getRequestURI(), slbId, slbMessageData);
} else {
messageQueue.produceMessage(MessageType.DeactivateSlb, slbId, slbMessageData);
}
return responseHandler.handle(slb, hh.getMediaType());
}
@GET
@Path("/soft/policy")
@Authorize(name = "activate")
public Response softDeactivatePolicy(@Context HttpServletRequest request,
@Context HttpHeaders hh,
@QueryParam("vsId") Long vsId,
@QueryParam("policyId") Long policyId) throws Exception {
TrafficPolicy policy = trafficPolicyRepository.getById(policyId);
if (policy == null) {
throw new ValidationException("Cannot find policy by Id-" + policyId + ".");
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(new Long[]{vsId});
if (vsMap.getOnlineMapping() == null || vsMap.getOnlineMapping().get(vsId) == null) {
throw new ValidationException("Vs is not activated.VsId:" + vsId);
}
VirtualServer vs = vsMap.getOnlineMapping().get(vsId);
List<OpsTask> softDeactivatingTasks = new ArrayList<>();
for (Long slbId : vs.getSlbIds()) {
OpsTask task = new OpsTask();
task.setSlbVirtualServerId(vsId);
task.setCreateTime(new Date());
task.setOpsType(TaskOpsType.SOFT_DEACTIVATE_POLICY);
task.setTargetSlbId(slbId);
task.setPolicyId(policyId);
task.setVersion(policy.getVersion());
softDeactivatingTasks.add(task);
}
List<Long> taskIds = taskManager.addTask(softDeactivatingTasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
return responseHandler.handle(resultList, hh.getMediaType());
}
@GET
@Path("/policy")
@Authorize(name = "deactivate")
public Response deactivatePolicy(@Context HttpServletRequest request, @Context HttpHeaders hh, @QueryParam("policyId") List<Long> policyIds) throws Exception {
ModelStatusMapping<TrafficPolicy> tpMap = entityFactory.getPoliciesByIds(policyIds.toArray(new Long[]{}));
if (!tpMap.getOnlineMapping().keySet().containsAll(policyIds)) {
throw new ValidationException("Have inactivated policy in " + Joiner.on(",").join(policyIds));
}
Set<Long> vsIds = new HashSet<>();
for (Map.Entry<Long, TrafficPolicy> e : tpMap.getOnlineMapping().entrySet()) {
TrafficPolicy policy = e.getValue();
if (policy == null) {
throw new Exception("Unexpected online group with null value. groupId=" + e.getKey() + ".");
}
for (PolicyVirtualServer vs : policy.getPolicyVirtualServers()) {
vsIds.add(vs.getVirtualServer().getId());
}
}
ModelStatusMapping<VirtualServer> vsMap = entityFactory.getVsesByIds(vsIds.toArray(new Long[]{}));
List<OpsTask> tasks = new ArrayList<>();
for (Map.Entry<Long, TrafficPolicy> e : tpMap.getOnlineMapping().entrySet()) {
TrafficPolicy policy = e.getValue();
Set<Long> slbIds = new HashSet<>();
for (PolicyVirtualServer pvs : policy.getPolicyVirtualServers()) {
VirtualServer vs = vsMap.getOnlineMapping().get(pvs.getVirtualServer().getId());
if (vs == null) {
throw new ValidationException("Virtual server " + pvs.getVirtualServer().getId() + " is found deactivated.");
}
slbIds.addAll(vs.getSlbIds());
}
for (Long slbId : slbIds) {
OpsTask task = new OpsTask();
task.setPolicyId(e.getKey());
task.setOpsType(TaskOpsType.DEACTIVATE_POLICY);
task.setTargetSlbId(slbId);
tasks.add(task);
}
}
List<Long> taskIds = taskManager.addTask(tasks);
List<TaskResult> results = taskManager.getResult(taskIds, apiTimeout.get());
TaskResultList resultList = new TaskResultList();
for (TaskResult t : results) {
resultList.addTaskResult(t);
}
resultList.setTotal(results.size());
try {
propertyBox.set("status", "deactivated", "policy", tpMap.getOnlineMapping().keySet().toArray(new Long[tpMap.getOnlineMapping().size()]));
} catch (Exception ex) {
}
String slbMessageData = MessageUtil.getMessageData(request,
null, null, null, null, true);
for (Long id : tpMap.getOfflineMapping().keySet()) {
messageQueue.produceMessage(request.getRequestURI(), id, slbMessageData);
}
return responseHandler.handle(resultList, hh.getMediaType());
}
}
| add validate for deactivate
| src/main/java/com/ctrip/zeus/restful/resource/DeactivateResource.java | add validate for deactivate | <ide><path>rc/main/java/com/ctrip/zeus/restful/resource/DeactivateResource.java
<ide> import com.ctrip.zeus.service.message.queue.MessageQueue;
<ide> import com.ctrip.zeus.service.message.queue.MessageType;
<ide> import com.ctrip.zeus.service.model.*;
<add>import com.ctrip.zeus.service.model.handler.GroupValidator;
<add>import com.ctrip.zeus.service.model.handler.TrafficPolicyValidator;
<ide> import com.ctrip.zeus.service.query.GroupCriteriaQuery;
<ide> import com.ctrip.zeus.service.task.constant.TaskOpsType;
<ide> import com.ctrip.zeus.tag.PropertyBox;
<ide> @Resource
<ide> private GroupCriteriaQuery groupCriteriaQuery;
<ide> @Resource
<add> private TrafficPolicyValidator trafficPolicyValidator;
<add> @Resource
<add> private GroupValidator groupValidator;
<add> @Resource
<ide> private MessageQueue messageQueue;
<ide> @Resource
<ide> private ConfigHandler configHandler;
<ide> }
<ide> }
<ide> }
<del>
<del> ModelStatusMapping<Group> groupMap = entityFactory.getGroupsByIds(_groupIds.toArray(new Long[]{}));
<add> Long[] gids = _groupIds.toArray(new Long[]{});
<add> ModelStatusMapping<Group> groupMap = entityFactory.getGroupsByIds(gids);
<add>
<add> groupValidator.validateForDeactivate(gids);
<ide>
<ide> _groupIds.removeAll(groupMap.getOnlineMapping().keySet());
<ide> if (_groupIds.size() > 0) {
<ide> throw new ValidationException("Have inactivated policy in " + Joiner.on(",").join(policyIds));
<ide> }
<ide>
<add> trafficPolicyValidator.validateForDeactivate(policyIds.toArray(new Long[]{}));
<add>
<ide> Set<Long> vsIds = new HashSet<>();
<ide> for (Map.Entry<Long, TrafficPolicy> e : tpMap.getOnlineMapping().entrySet()) {
<ide> TrafficPolicy policy = e.getValue(); |
|
Java | mit | c50fbd91dff00fc480680a76c25290cf4ff704e2 | 0 | MeowInnovation/Item-Render,MascusJeoraly/Item-Render | /*
* Copyright (c) 2015 Jerrell Fang
*
* This project is Open Source and distributed under The MIT License (MIT)
* (http://opensource.org/licenses/MIT)
*
* You should have received a copy of the The MIT License along with
* this project. If not, see <http://opensource.org/licenses/MIT>.
*/
package itemrender.client.keybind;
import itemrender.client.rendering.FBOHelper;
import itemrender.client.rendering.Renderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class KeybindRenderEntity {
public static float EntityRenderScale = 1.0F;
public final KeyBinding key;
/**
* Key descriptions
*/
private final String desc;
/**
* Default key values
*/
private final int keyValue;
public FBOHelper fbo;
private String filenameSuffix = "";
public KeybindRenderEntity(int textureSize, String filename_suffix, int keyVal, String des) {
fbo = new FBOHelper(textureSize);
filenameSuffix = filename_suffix;
keyValue = keyVal;
desc = des;
key = new KeyBinding(desc, keyValue, "Item Render");
ClientRegistry.registerKeyBinding(key);
}
@SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event) {
if (FMLClientHandler.instance().isGUIOpen(GuiChat.class))
return;
if (key.isPressed()) {
Minecraft minecraft = FMLClientHandler.instance().getClient();
if (minecraft.pointedEntity != null)
Renderer.renderEntity((EntityLivingBase) minecraft.pointedEntity, fbo, filenameSuffix, false);
}
}
}
| src/main/java/itemrender/client/keybind/KeybindRenderEntity.java | /*
* Copyright (c) 2015 Jerrell Fang
*
* This project is Open Source and distributed under The MIT License (MIT)
* (http://opensource.org/licenses/MIT)
*
* You should have received a copy of the The MIT License along with
* this project. If not, see <http://opensource.org/licenses/MIT>.
*/
package itemrender.client.keybind;
import itemrender.client.rendering.FBOHelper;
import itemrender.client.rendering.Renderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class KeybindRenderEntity {
public static float EntityRenderScale = 1.0F;
public final KeyBinding key;
/**
* Key descriptions
*/
private final String desc;
/**
* Default key values
*/
private final int keyValue;
public FBOHelper fbo;
private String filenameSuffix = "";
public KeybindRenderEntity(int textureSize, String filename_suffix, int keyVal, String des) {
fbo = new FBOHelper(textureSize);
filenameSuffix = filename_suffix;
keyValue = keyval;
desc = des;
key = new KeyBinding(desc, keyValue, "Item Render");
ClientRegistry.registerKeyBinding(key);
}
@SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event) {
if (FMLClientHandler.instance().isGUIOpen(GuiChat.class))
return;
if (key.isPressed()) {
Minecraft minecraft = FMLClientHandler.instance().getClient();
if (minecraft.pointedEntity != null)
Renderer.renderEntity((EntityLivingBase) minecraft.pointedEntity, fbo, filenameSuffix, false);
}
}
}
| Update KeybindRenderEntity.java
| src/main/java/itemrender/client/keybind/KeybindRenderEntity.java | Update KeybindRenderEntity.java | <ide><path>rc/main/java/itemrender/client/keybind/KeybindRenderEntity.java
<ide> public KeybindRenderEntity(int textureSize, String filename_suffix, int keyVal, String des) {
<ide> fbo = new FBOHelper(textureSize);
<ide> filenameSuffix = filename_suffix;
<del> keyValue = keyval;
<add> keyValue = keyVal;
<ide> desc = des;
<ide> key = new KeyBinding(desc, keyValue, "Item Render");
<ide> ClientRegistry.registerKeyBinding(key); |
|
Java | bsd-2-clause | ed616d8453401276156286f24494b2fbed0cee4a | 0 | LittleMikeDev/jextend | package uk.co.littlemike.jextend.impl;
import uk.co.littlemike.jextend.validation.ExtensionClassNotAnInterfaceException;
import uk.co.littlemike.jextend.validation.UnimplementedExtensionMethodException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public class ExtensionConfiguration<C, E extends C> {
private final Class<C> baseClass;
private final Class<E> extensionInterface;
private Set<Method> delegateMethods = new HashSet<>();
private Set<Method> defaultMethods = new HashSet<>();
private Set<Method> unimplementedMethods = new HashSet<>();
public ExtensionConfiguration(Class<C> baseClass, Class<E> extensionInterface) {
this.baseClass = baseClass;
this.extensionInterface = extensionInterface;
for (Method method : extensionInterface.getMethods()) {
categorizeMethod(method);
}
validate();
}
private void categorizeMethod(Method method) {
if (isInBaseClass(method)) {
delegateMethods.add(method);
} else if (method.isDefault()) {
defaultMethods.add(method);
} else {
unimplementedMethods.add(method);
}
}
private boolean isInBaseClass(Method m) {
return m.getDeclaringClass().isAssignableFrom(baseClass);
}
private void validate() {
if (!extensionInterface.isInterface()) {
throw new ExtensionClassNotAnInterfaceException(baseClass, extensionInterface);
}
if (!unimplementedMethods.isEmpty()) {
throw new UnimplementedExtensionMethodException(baseClass, extensionInterface, unimplementedMethods);
}
}
public Class<C> getBaseClass() {
return baseClass;
}
public Class<E> getExtensionInterface() {
return extensionInterface;
}
public Set<Method> getDelegateMethods() {
return delegateMethods;
}
public Set<Method> getDefaultMethods() {
return defaultMethods;
}
}
| jextend-core/src/main/java/uk/co/littlemike/jextend/impl/ExtensionConfiguration.java | package uk.co.littlemike.jextend.impl;
import uk.co.littlemike.jextend.validation.ExtensionClassNotAnInterfaceException;
import uk.co.littlemike.jextend.validation.UnimplementedExtensionMethodException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static java.util.stream.Collectors.toList;
public class ExtensionConfiguration<C, E extends C> {
private final Class<C> baseClass;
private final Class<E> extensionInterface;
private Set<Method> delegateMethods = new HashSet<>();
private Set<Method> defaultMethods = new HashSet<>();
public ExtensionConfiguration(Class<C> baseClass, Class<E> extensionInterface) {
this.baseClass = baseClass;
this.extensionInterface = extensionInterface;
for (Method method : extensionInterface.getMethods()) {
categorizeMethod(method);
}
validate();
}
private void categorizeMethod(Method method) {
if (isInBaseClass(method)) {
delegateMethods.add(method);
} else {
defaultMethods.add(method);
}
}
public Class<C> getBaseClass() {
return baseClass;
}
public Class<E> getExtensionInterface() {
return extensionInterface;
}
private void validate() {
if (!extensionInterface.isInterface()) {
throw new ExtensionClassNotAnInterfaceException(baseClass, extensionInterface);
}
List<Method> unimplementedMethods = Arrays.stream(extensionInterface.getMethods())
.filter(m -> !isInBaseClass(m))
.filter(m -> !m.isDefault())
.collect(toList());
if (!unimplementedMethods.isEmpty()) {
throw new UnimplementedExtensionMethodException(baseClass, extensionInterface, unimplementedMethods);
}
}
private boolean isInBaseClass(Method m) {
return m.getDeclaringClass().isAssignableFrom(baseClass);
}
public Set<Method> getDelegateMethods() {
return delegateMethods;
}
public Set<Method> getDefaultMethods() {
return defaultMethods;
}
}
| Collect unimplemented methods during categorization for validation
| jextend-core/src/main/java/uk/co/littlemike/jextend/impl/ExtensionConfiguration.java | Collect unimplemented methods during categorization for validation | <ide><path>extend-core/src/main/java/uk/co/littlemike/jextend/impl/ExtensionConfiguration.java
<ide> import uk.co.littlemike.jextend.validation.UnimplementedExtensionMethodException;
<ide>
<ide> import java.lang.reflect.Method;
<del>import java.util.Arrays;
<ide> import java.util.HashSet;
<del>import java.util.List;
<ide> import java.util.Set;
<del>
<del>import static java.util.stream.Collectors.toList;
<ide>
<ide> public class ExtensionConfiguration<C, E extends C> {
<ide> private final Class<C> baseClass;
<ide> private final Class<E> extensionInterface;
<ide> private Set<Method> delegateMethods = new HashSet<>();
<ide> private Set<Method> defaultMethods = new HashSet<>();
<add> private Set<Method> unimplementedMethods = new HashSet<>();
<ide>
<ide> public ExtensionConfiguration(Class<C> baseClass, Class<E> extensionInterface) {
<ide> this.baseClass = baseClass;
<ide> private void categorizeMethod(Method method) {
<ide> if (isInBaseClass(method)) {
<ide> delegateMethods.add(method);
<add> } else if (method.isDefault()) {
<add> defaultMethods.add(method);
<ide> } else {
<del> defaultMethods.add(method);
<add> unimplementedMethods.add(method);
<add> }
<add> }
<add>
<add> private boolean isInBaseClass(Method m) {
<add> return m.getDeclaringClass().isAssignableFrom(baseClass);
<add> }
<add>
<add> private void validate() {
<add> if (!extensionInterface.isInterface()) {
<add> throw new ExtensionClassNotAnInterfaceException(baseClass, extensionInterface);
<add> }
<add> if (!unimplementedMethods.isEmpty()) {
<add> throw new UnimplementedExtensionMethodException(baseClass, extensionInterface, unimplementedMethods);
<ide> }
<ide> }
<ide>
<ide> return extensionInterface;
<ide> }
<ide>
<del> private void validate() {
<del> if (!extensionInterface.isInterface()) {
<del> throw new ExtensionClassNotAnInterfaceException(baseClass, extensionInterface);
<del> }
<del>
<del> List<Method> unimplementedMethods = Arrays.stream(extensionInterface.getMethods())
<del> .filter(m -> !isInBaseClass(m))
<del> .filter(m -> !m.isDefault())
<del> .collect(toList());
<del> if (!unimplementedMethods.isEmpty()) {
<del> throw new UnimplementedExtensionMethodException(baseClass, extensionInterface, unimplementedMethods);
<del> }
<del> }
<del>
<del> private boolean isInBaseClass(Method m) {
<del> return m.getDeclaringClass().isAssignableFrom(baseClass);
<del> }
<del>
<ide> public Set<Method> getDelegateMethods() {
<ide> return delegateMethods;
<ide> } |
|
JavaScript | mit | 62540f38072ddc4cbe20be3019c9be002595e104 | 0 | efog/hurler,efog/hurler |
/**
* Controller Constructor
* @constructor
*/
function ControllerController() {
}
/**
* Directive setup
*
* @param {any} $http $http service
* @returns {undefined}
*/
function urlBar($http) {
/**
* links directive to scope
*
* @param {any} scope directive scope
* @param {any} element html element rendering the directive
* @param {any} attrs attributes of the element
* @returns {undefined}
*/
function link(scope, element, attrs) {
}
// Usage:
// <url-bar></url-bar>
// Creates:
//
var directive = {
'bindToController': true,
'controller': ControllerController,
'controllerAs': 'vm',
'link': link,
'restrict': 'E',
'scope': {
}
};
return directive;
}
urlBar.$inject = ['$http'];
angular
.module('app')
.directive('urlBar', urlBar);
| app/ng-app/directives/url-bar/url-bar.js |
/**
* Controller Constructor
* @constructor
*/
function ControllerController() {
}
/**
* Directive setup
*
* @param {any} $http $http service
* @returns {undefined}
*/
function urlBar($http) {
/**
* links directive to scope
*
* @param {any} scope directive scope
* @param {any} element html element rendering the directive
* @param {any} attrs attributes of the element
* @returns {undefined}
*/
function link(scope, element, attrs) {
}
// Usage:
//
// Creates:
//
var directive = {
'bindToController': true,
'controller': ControllerController,
'controllerAs': 'vm',
'link': link,
'restrict': 'E',
'scope': {
}
};
return directive;
}
urlBar.$inject = ['$http'];
angular
.module('app')
.directive('urlBar', urlBar);
| Quick check
| app/ng-app/directives/url-bar/url-bar.js | Quick check | <ide><path>pp/ng-app/directives/url-bar/url-bar.js
<ide> }
<ide>
<ide> // Usage:
<del> //
<add> // <url-bar></url-bar>
<ide> // Creates:
<ide> //
<ide> var directive = { |
|
Java | apache-2.0 | 929bf937b54d6bf196843ae3393d4b09f2cfd99b | 0 | Sellegit/j2objc,Sellegit/j2objc,Sellegit/j2objc,Sellegit/j2objc,Sellegit/j2objc | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc.gen;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.ast.Annotation;
import com.google.devtools.j2objc.ast.AnonymousClassDeclaration;
import com.google.devtools.j2objc.ast.ArrayAccess;
import com.google.devtools.j2objc.ast.ArrayCreation;
import com.google.devtools.j2objc.ast.ArrayInitializer;
import com.google.devtools.j2objc.ast.ArrayType;
import com.google.devtools.j2objc.ast.AssertStatement;
import com.google.devtools.j2objc.ast.Assignment;
import com.google.devtools.j2objc.ast.Block;
import com.google.devtools.j2objc.ast.BooleanLiteral;
import com.google.devtools.j2objc.ast.BreakStatement;
import com.google.devtools.j2objc.ast.CStringLiteral;
import com.google.devtools.j2objc.ast.CastExpression;
import com.google.devtools.j2objc.ast.CatchClause;
import com.google.devtools.j2objc.ast.CharacterLiteral;
import com.google.devtools.j2objc.ast.ClassInstanceCreation;
import com.google.devtools.j2objc.ast.CompilationUnit;
import com.google.devtools.j2objc.ast.ConditionalExpression;
import com.google.devtools.j2objc.ast.ConstructorInvocation;
import com.google.devtools.j2objc.ast.ContinueStatement;
import com.google.devtools.j2objc.ast.DoStatement;
import com.google.devtools.j2objc.ast.EmptyStatement;
import com.google.devtools.j2objc.ast.EnhancedForStatement;
import com.google.devtools.j2objc.ast.Expression;
import com.google.devtools.j2objc.ast.ExpressionStatement;
import com.google.devtools.j2objc.ast.FieldAccess;
import com.google.devtools.j2objc.ast.ForStatement;
import com.google.devtools.j2objc.ast.FunctionInvocation;
import com.google.devtools.j2objc.ast.IfStatement;
import com.google.devtools.j2objc.ast.InfixExpression;
import com.google.devtools.j2objc.ast.Initializer;
import com.google.devtools.j2objc.ast.InstanceofExpression;
import com.google.devtools.j2objc.ast.LabeledStatement;
import com.google.devtools.j2objc.ast.MarkerAnnotation;
import com.google.devtools.j2objc.ast.MemberValuePair;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.MethodInvocation;
import com.google.devtools.j2objc.ast.Name;
import com.google.devtools.j2objc.ast.NativeExpression;
import com.google.devtools.j2objc.ast.NativeStatement;
import com.google.devtools.j2objc.ast.NormalAnnotation;
import com.google.devtools.j2objc.ast.NullLiteral;
import com.google.devtools.j2objc.ast.NumberLiteral;
import com.google.devtools.j2objc.ast.ParenthesizedExpression;
import com.google.devtools.j2objc.ast.PostfixExpression;
import com.google.devtools.j2objc.ast.PrefixExpression;
import com.google.devtools.j2objc.ast.PrimitiveType;
import com.google.devtools.j2objc.ast.QualifiedName;
import com.google.devtools.j2objc.ast.QualifiedType;
import com.google.devtools.j2objc.ast.ReturnStatement;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.SimpleType;
import com.google.devtools.j2objc.ast.SingleMemberAnnotation;
import com.google.devtools.j2objc.ast.SingleVariableDeclaration;
import com.google.devtools.j2objc.ast.Statement;
import com.google.devtools.j2objc.ast.StringLiteral;
import com.google.devtools.j2objc.ast.SuperConstructorInvocation;
import com.google.devtools.j2objc.ast.SuperFieldAccess;
import com.google.devtools.j2objc.ast.SuperMethodInvocation;
import com.google.devtools.j2objc.ast.SwitchCase;
import com.google.devtools.j2objc.ast.SwitchStatement;
import com.google.devtools.j2objc.ast.SynchronizedStatement;
import com.google.devtools.j2objc.ast.ThisExpression;
import com.google.devtools.j2objc.ast.ThrowStatement;
import com.google.devtools.j2objc.ast.TreeNode;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.TreeVisitor;
import com.google.devtools.j2objc.ast.TryStatement;
import com.google.devtools.j2objc.ast.Type;
import com.google.devtools.j2objc.ast.TypeLiteral;
import com.google.devtools.j2objc.ast.UnionType;
import com.google.devtools.j2objc.ast.VariableDeclarationExpression;
import com.google.devtools.j2objc.ast.VariableDeclarationFragment;
import com.google.devtools.j2objc.ast.VariableDeclarationStatement;
import com.google.devtools.j2objc.ast.WhileStatement;
import com.google.devtools.j2objc.translate.Functionizer;
import com.google.devtools.j2objc.types.IOSBlockTypeBinding;
import com.google.devtools.j2objc.types.IOSMethod;
import com.google.devtools.j2objc.types.IOSMethodBinding;
import com.google.devtools.j2objc.types.IOSTypeBinding;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.BindingUtil;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.devtools.j2objc.util.NameTable;
import com.google.devtools.j2objc.util.UnicodeUtils;
import org.eclipse.jdt.core.dom.IAnnotationBinding;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMemberValuePairBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Returns an Objective-C equivalent of a Java AST node.
*
* @author Tom Ball
*/
public class StatementGenerator extends TreeVisitor {
private final CompilationUnit unit;
private final SourceBuilder buffer;
private final boolean asFunction;
private final boolean useReferenceCounting;
private static final Pattern TRIGRAPH_REGEX = Pattern.compile("@\".*\\?\\?[=/'()!<>-].*\"");
public static String generate(TreeNode node, boolean asFunction, int currentLine) {
StatementGenerator generator = new StatementGenerator(node, asFunction, currentLine);
if (node == null) {
throw new NullPointerException("cannot generate a null statement");
}
generator.run(node);
return generator.getResult();
}
private StatementGenerator(TreeNode node, boolean asFunction, int currentLine) {
this.unit = TreeUtil.getCompilationUnit(node);
buffer = new SourceBuilder(Options.emitLineDirectives(), currentLine);
this.asFunction = asFunction;
useReferenceCounting = !Options.useARC();
}
private String getResult() {
return buffer.toString();
}
private void printArgumentExpression(IMethodBinding method, Expression arg, int index) {
if (method != null) {
// wrap @Block argument
IAnnotationBinding blockAnnotation =
BindingUtil.getAnnotation(method.getParameterAnnotations(index), com.google.j2objc.annotations.Block.class);
if (blockAnnotation != null) {
ITypeBinding blockTpe = method.getParameterTypes()[index];
String blockRet = BindingUtil.BlockBridge.returnType(blockAnnotation, blockTpe);
String[] blockParams = BindingUtil.BlockBridge.paramTypes(blockAnnotation, blockTpe);
// TODO: do a proper scope analysis here to prevent accidental name pollution
buffer.append("(^{");
buffer.append(NameTable.getSpecificObjCType(method.getParameterTypes()[index]));
if (buffer.charAt(buffer.length() - 1) != '*') {
buffer.append(" ");
}
String localRunnerId = "___$runner";
buffer.append(localRunnerId + " = ");
arg.accept(this);
buffer.append(";");
buffer.append("return " + localRunnerId + " == nil ? nil : ");
buffer.append(useReferenceCounting ? "[[" : "[");
buffer.append("^" + blockRet + " (");
char argId = 'a';
boolean first = true;
for (String param : blockParams) {
if (first) {
first = false;
} else {
buffer.append(", ");
}
buffer.append(param);
if (!param.endsWith("*")) {
buffer.append(' ');
}
buffer.append("____" + (argId++));
}
buffer.append(") { ");
if (!blockRet.equals("void")) {
buffer.append("return ");
}
buffer.append("[" + localRunnerId + " run");
argId = 'a';
first = true;
for (Object _ : blockParams) {
if (first) {
first = false;
} else {
buffer.append(" param");
}
buffer.append(":____" + (argId++));
}
buffer.append("];}");
buffer.append(" copy]");
if (useReferenceCounting) {
buffer.append(" autorelease]");
}
buffer.append(";})()");
return;
}
}
arg.accept(this);
}
private void printMethodInvocationNameAndArgs(IMethodBinding binding, List<Expression> args) {
String selector = NameTable.getMethodSelector(binding);
String[] selParts = selector.split(":");
if (args.isEmpty()) {
assert selParts.length == 1 && !selector.endsWith(":");
buffer.append(' ');
buffer.append(selector);
} else {
assert selParts.length == args.size();
for (int i = 0; i < args.size(); i++) {
buffer.append(' ');
buffer.append(selParts[i]);
buffer.append(':');
printArgumentExpression(binding, args.get(i), i);
}
}
}
@Override
public boolean preVisit(TreeNode node) {
super.preVisit(node);
if (!(node instanceof Block)) {
buffer.syncLineNumbers(node);
}
return true;
}
@Override
public boolean visit(AnonymousClassDeclaration node) {
// Multi-method anonymous classes should have been converted by the
// InnerClassExtractor.
assert node.getBodyDeclarations().size() == 1;
// Generate an iOS block.
assert false : "not implemented yet";
return true;
}
@Override
public boolean visit(ArrayAccess node) {
throw new AssertionError("ArrayAccess nodes are rewritten by ArrayRewriter.");
}
@Override
public boolean visit(ArrayCreation node) {
throw new AssertionError("ArrayCreation nodes are rewritten by ArrayRewriter.");
}
@Override
public boolean visit(ArrayInitializer node) {
ITypeBinding type = node.getTypeBinding();
assert type.isArray();
ITypeBinding componentType = type.getComponentType();
String componentTypeName = componentType.isPrimitive()
? NameTable.primitiveTypeToObjC(componentType) : "id";
buffer.append(String.format("(%s[]){ ", componentTypeName));
for (Iterator<Expression> it = node.getExpressions().iterator(); it.hasNext(); ) {
it.next().accept(this);
if (it.hasNext()) {
buffer.append(", ");
}
}
buffer.append(" }");
return false;
}
@Override
public boolean visit(ArrayType node) {
ITypeBinding binding = Types.mapType(node.getTypeBinding());
if (binding instanceof IOSTypeBinding) {
buffer.append(binding.getName());
} else {
node.getComponentType().accept(this);
buffer.append("[]");
}
return false;
}
@Override
public boolean visit(AssertStatement node) {
buffer.append(asFunction ? "NSCAssert(" : "NSAssert(");
node.getExpression().accept(this);
buffer.append(", ");
if (node.getMessage() != null) {
Expression expr = node.getMessage();
boolean isString = expr instanceof StringLiteral;
if (!isString) {
buffer.append('[');
}
int start = buffer.length();
expr.accept(this);
int end = buffer.length();
// Commas inside sub-expression of the NSAssert macro will be incorrectly interpreted as
// new argument indicators in the macro. Replace commas with the J2OBJC_COMMA macro.
String substring = buffer.substring(start, end);
substring = substring.replaceAll(",", " J2OBJC_COMMA()");
buffer.replace(start, end, substring);
if (!isString) {
buffer.append(" description]");
}
} else {
int startPos = node.getStartPosition();
String assertStatementString =
unit.getSource().substring(startPos, startPos + node.getLength());
assertStatementString = CharMatcher.WHITESPACE.trimFrom(assertStatementString);
assertStatementString = makeQuotedString(assertStatementString);
// Generates the following string:
// filename.java:456 condition failed: foobar != fish.
buffer.append("@\"" + TreeUtil.getSourceFileName(unit) + ":" + node.getLineNumber()
+ " condition failed: " + assertStatementString + "\"");
}
buffer.append(");\n");
return false;
}
@Override
public boolean visit(Assignment node) {
node.getLeftHandSide().accept(this);
buffer.append(' ');
buffer.append(node.getOperator().toString());
buffer.append(' ');
node.getRightHandSide().accept(this);
return false;
}
@Override
public boolean visit(Block node) {
if (node.hasAutoreleasePool()) {
buffer.append("{\n@autoreleasepool ");
}
buffer.append("{\n");
printStatements(node.getStatements());
buffer.append("}\n");
if (node.hasAutoreleasePool()) {
buffer.append("}\n");
}
return false;
}
private void printStatements(List<?> statements) {
for (Iterator<?> it = statements.iterator(); it.hasNext(); ) {
Statement s = (Statement) it.next();
s.accept(this);
}
}
@Override
public boolean visit(BooleanLiteral node) {
buffer.append(node.booleanValue() ? "YES" : "NO");
return false;
}
@Override
public boolean visit(BreakStatement node) {
if (node.getLabel() != null) {
// Objective-C doesn't have a labeled break, so use a goto.
buffer.append("goto ");
node.getLabel().accept(this);
} else {
buffer.append("break");
}
buffer.append(";\n");
return false;
}
@Override
public boolean visit(CStringLiteral node) {
buffer.append("\"");
buffer.append(node.getLiteralValue());
buffer.append("\"");
return false;
}
@Override
public boolean visit(CastExpression node) {
ITypeBinding type = node.getType().getTypeBinding();
buffer.append("(");
if (Options.useARC()) {
if (BindingUtil.isObjCType(type) &&
BindingUtil.isCFType(node.getExpression().getTypeBinding())) {
buffer.append("__bridge ");
}
}
buffer.append(NameTable.getSpecificObjCType(type));
buffer.append(") ");
node.getExpression().accept(this);
return false;
}
private void printMultiCatch(CatchClause node, boolean hasResources) {
SingleVariableDeclaration exception = node.getException();
for (Type exceptionType : ((UnionType) exception.getType()).getTypes()) {
buffer.append("@catch (");
exceptionType.accept(this);
// Assume exception is definitely pointer type
buffer.append(" *");
exception.getName().accept(this);
buffer.append(") {\n");
printMainExceptionStore(hasResources, node);
printStatements(node.getBody().getStatements());
buffer.append("}\n");
}
}
@Override
public boolean visit(CharacterLiteral node) {
buffer.append(UnicodeUtils.escapeCharLiteral(node.charValue()));
return false;
}
@Override
public boolean visit(ClassInstanceCreation node) {
IMethodBinding binding = node.getMethodBinding();
if (BindingUtil.isMappedToNative(binding) || Functionizer.isConstructorOfMappedClass(binding)) {
ITypeBinding type = node.getType().getTypeBinding();
boolean addAutorelease = useReferenceCounting && !node.hasRetainedResult();
buffer.append(addAutorelease ? "[[[" : "[[");
buffer.append(NameTable.getFullName(type));
// if the method binding is a mapped constructor, use that instead
IMethodBinding method = node.getMethodBinding();
buffer.append(" alloc]");
List<Expression> arguments = node.getArguments();
printMethodInvocationNameAndArgs(method, arguments);
buffer.append(']');
if (addAutorelease) {
buffer.append(" autorelease]");
}
return false;
} else {
throw new AssertionError(
"ClassInstanceCreation nodes are rewritten by Functionizer. node: " + node);
}
}
@Override
public boolean visit(ConditionalExpression node) {
boolean castNeeded = false;
ITypeBinding thenType = node.getThenExpression().getTypeBinding();
ITypeBinding elseType = node.getElseExpression().getTypeBinding();
if (!thenType.equals(elseType)
&& !(node.getThenExpression() instanceof NullLiteral)
&& !(node.getElseExpression() instanceof NullLiteral)) {
// gcc fails to compile a conditional expression where the two clauses of
// the expression have different type. So cast any interface type down to
// "id" to make the compiler happy. Concrete object types all have a
// common ancestor of NSObject, so they don't need a cast.
castNeeded = true;
}
node.getExpression().accept(this);
buffer.append(" ? ");
if (castNeeded && thenType.isInterface()) {
buffer.append("((id) ");
}
node.getThenExpression().accept(this);
if (castNeeded && thenType.isInterface()) {
buffer.append(')');
}
buffer.append(" : ");
if (castNeeded && elseType.isInterface()) {
buffer.append("((id) ");
}
node.getElseExpression().accept(this);
if (castNeeded && elseType.isInterface()) {
buffer.append(')');
}
return false;
}
@Override
public boolean visit(ConstructorInvocation node) {
return visitConstructorInvocation(node);
}
@Override
public boolean visit(SuperConstructorInvocation node) {
return visitConstructorInvocation(node);
}
private boolean visitConstructorInvocation(Statement node) {
IMethodBinding binding;
List<Expression> args;
String receiver;
if (node instanceof ConstructorInvocation) {
binding = ((ConstructorInvocation) node).getMethodBinding();
args = ((ConstructorInvocation) node).getArguments();
receiver = "self";
} else if (node instanceof SuperConstructorInvocation) {
binding = ((SuperConstructorInvocation) node).getMethodBinding();
args = ((SuperConstructorInvocation) node).getArguments();
receiver = "super";
} else {
throw new AssertionError("Illegal statement type.");
}
if (BindingUtil.isMappedToNative(binding) || Functionizer.isConstructorOfMappedClass(binding)) {
buffer.append("self = [" + receiver);
printMethodInvocationNameAndArgs(binding, args);
buffer.append("];\n");
return false;
} else {
throw new AssertionError("SuperConstructorInvocation nodes are rewritten by Functionizer.");
}
}
@Override
public boolean visit(ContinueStatement node) {
if (node.getLabel() != null) {
// Objective-C doesn't have a labeled continue, so use a goto.
buffer.append("goto ");
node.getLabel().accept(this);
} else {
buffer.append("continue");
}
buffer.append(";\n");
return false;
}
@Override
public boolean visit(DoStatement node) {
buffer.append("do ");
node.getBody().accept(this);
buffer.append(" while (");
node.getExpression().accept(this);
buffer.append(");\n");
return false;
}
@Override
public boolean visit(EmptyStatement node) {
buffer.append(";\n");
return false;
}
@Override
public boolean visit(EnhancedForStatement node) {
buffer.append("for (");
node.getParameter().accept(this);
buffer.append(" in ");
node.getExpression().accept(this);
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(ExpressionStatement node) {
Expression expression = node.getExpression();
ITypeBinding type = expression.getTypeBinding();
if (!type.isPrimitive() && Options.useARC()
&& (expression instanceof MethodInvocation
|| expression instanceof SuperMethodInvocation
|| expression instanceof FunctionInvocation)) {
// Avoid clang warning that the return value is unused.
buffer.append("(void) ");
}
expression.accept(this);
buffer.append(";\n");
return false;
}
@Override
public boolean visit(FieldAccess node) {
final Expression expr = node.getExpression();
final IVariableBinding binding = node.getVariableBinding();
final String dotAccess = BindingUtil.extractDotMappingName(binding);
if (dotAccess != null) {
expr.accept(this);
buffer.append("." + dotAccess);
} else {
// self->static_var is invalid Objective-C.
if (!(expr instanceof ThisExpression && BindingUtil.isStatic(node.getVariableBinding()))) {
expr.accept(this);
buffer.append("->");
}
node.getName().accept(this);
}
return false;
}
@Override
public boolean visit(ForStatement node) {
buffer.append("for (");
for (Iterator<Expression> it = node.getInitializers().iterator(); it.hasNext(); ) {
Expression next = it.next();
next.accept(this);
if (it.hasNext()) {
buffer.append(", ");
}
}
buffer.append("; ");
if (node.getExpression() != null) {
node.getExpression().accept(this);
}
buffer.append("; ");
for (Iterator<Expression> it = node.getUpdaters().iterator(); it.hasNext(); ) {
it.next().accept(this);
if (it.hasNext()) {
buffer.append(", ");
}
}
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(FunctionInvocation node) {
buffer.append(node.getName());
buffer.append('(');
for (Iterator<Expression> iter = node.getArguments().iterator(); iter.hasNext(); ) {
iter.next().accept(this);
if (iter.hasNext()) {
buffer.append(", ");
}
}
buffer.append(')');
return false;
}
@Override
public boolean visit(IfStatement node) {
buffer.append("if (");
node.getExpression().accept(this);
buffer.append(") ");
node.getThenStatement().accept(this);
if (node.getElseStatement() != null) {
buffer.append(" else ");
node.getElseStatement().accept(this);
}
return false;
}
@Override
public boolean visit(InfixExpression node) {
InfixExpression.Operator op = node.getOperator();
Expression lhs = node.getLeftOperand();
Expression rhs = node.getRightOperand();
List<Expression> extendedOperands = node.getExtendedOperands();
if ((op.equals(InfixExpression.Operator.EQUALS)
|| op.equals(InfixExpression.Operator.NOT_EQUALS))
&& (lhs instanceof StringLiteral || rhs instanceof StringLiteral)) {
Expression first = lhs;
Expression second = rhs;
if (!(lhs instanceof StringLiteral)) {
// In case the lhs can't call isEqual.
first = rhs;
second = lhs;
}
buffer.append(op.equals(InfixExpression.Operator.NOT_EQUALS) ? "![" : "[");
first.accept(this);
buffer.append(" isEqual:");
second.accept(this);
buffer.append("]");
} else {
lhs.accept(this);
buffer.append(' ');
buffer.append(op.toString());
buffer.append(' ');
rhs.accept(this);
for (Iterator<Expression> it = extendedOperands.iterator(); it.hasNext(); ) {
buffer.append(' ').append(op.toString()).append(' ');
it.next().accept(this);
}
}
return false;
}
@Override
public boolean visit(InstanceofExpression node) {
ITypeBinding rightBinding = node.getRightOperand().getTypeBinding();
if (rightBinding.isInterface()) {
// Our version of "isInstance" is faster than "conformsToProtocol".
buffer.append(String.format("[%s_class_() isInstance:", NameTable.getFullName(rightBinding)));
node.getLeftOperand().accept(this);
buffer.append(']');
} else {
buffer.append('[');
node.getLeftOperand().accept(this);
buffer.append(" isKindOfClass:[");
node.getRightOperand().accept(this);
buffer.append(" class]]");
}
return false;
}
@Override
public boolean visit(LabeledStatement node) {
node.getLabel().accept(this);
buffer.append(": ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(MarkerAnnotation node) {
printAnnotationCreation(node);
return false;
}
@Override
public boolean visit(MethodInvocation node) {
IMethodBinding binding = node.getMethodBinding();
assert binding != null;
// Object receiving the message, or null if it's a method in this class.
Expression receiver = node.getExpression();
String dotAccess = BindingUtil.extractDotMappingName(binding);
if (dotAccess != null) {
if (receiver != null) {
receiver.accept(this);
} else {
ErrorUtil.error(node, "DotMapped method cannot be called inside the same class");
}
buffer.append("." + dotAccess);
return false;
}
// TODO: move this into a function invocation thing?
String fnName = BindingUtil.extractGlobalFunctionName(binding);
if (fnName != null) {
buffer.append(fnName);
buffer.append('(');
List<Expression> args = node.getArguments();
for (int i = 0; i < args.size(); i++) {
printArgumentExpression(binding, args.get(i), i);
if (i < args.size() - 1) {
buffer.append(", ");
}
}
buffer.append(')');
return false;
}
String constName = BindingUtil.extractGlobalConstantName(binding);
if (constName != null) {
buffer.append(constName);
return false;
}
// Note: we dont move extension method mapping to JavaToIOSMethodTranslator bcuz
// we want to preserve the extension class in source code so that appropriate
// dependency will be picked up by import collector
// TODO: clean this up when there is time
IOSMethod mapped = BindingUtil.getMappedMethod(binding, /* extension */ true);
if (mapped != null) {
List<Expression> args = node.getArguments();
Expression newReceiver = args.remove(0);
receiver = newReceiver;
IOSMethodBinding newBinding =
IOSMethodBinding.newMappedExtensionMethod(mapped.getSelector(), binding);
newBinding.setModifiers(Modifier.PUBLIC); // do away static modifier
binding = newBinding;
}
printMethodInvocation(binding, receiver, node.getArguments());
return false;
}
private void printMethodInvocation(
IMethodBinding binding, Expression receiver, List<Expression> args) {
buffer.append('[');
if (BindingUtil.isStatic(binding)) {
buffer.append(NameTable.getFullName(binding.getDeclaringClass()));
} else if (receiver != null) {
receiver.accept(this);
} else {
buffer.append("self");
}
printMethodInvocationNameAndArgs(binding, args);
buffer.append(']');
}
@Override
public boolean visit(NativeExpression node) {
buffer.append(node.getCode());
return false;
}
@Override
public boolean visit(NativeStatement node) {
buffer.append(node.getCode());
buffer.append('\n');
return false;
}
@Override
public boolean visit(NormalAnnotation node) {
printAnnotationCreation(node);
return false;
}
private void printAnnotationCreation(Annotation node) {
IAnnotationBinding annotation = node.getAnnotationBinding();
buffer.append(useReferenceCounting ? "[[[" : "[[");
buffer.append(NameTable.getFullName(annotation.getAnnotationType()));
buffer.append(" alloc] init");
if (node instanceof NormalAnnotation) {
Map<String, Expression> args = Maps.newHashMap();
for (MemberValuePair pair : ((NormalAnnotation) node).getValues()) {
args.put(pair.getName().getIdentifier(), pair.getValue());
}
IMemberValuePairBinding[] members = BindingUtil.getSortedMemberValuePairs(annotation);
for (int i = 0; i < members.length; i++) {
if (i == 0) {
buffer.append("With");
} else {
buffer.append(" with");
}
IMemberValuePairBinding member = members[i];
String name = NameTable.getAnnotationPropertyName(member.getMethodBinding());
buffer.append(NameTable.capitalize(name));
buffer.append(':');
Expression value = args.get(name);
if (value != null) {
value.accept(this);
}
}
} else if (node instanceof SingleMemberAnnotation) {
SingleMemberAnnotation sma = (SingleMemberAnnotation) node;
buffer.append("With");
IMethodBinding accessorBinding = annotation.getAllMemberValuePairs()[0].getMethodBinding();
String name = NameTable.getAnnotationPropertyName(accessorBinding);
buffer.append(NameTable.capitalize(name));
buffer.append(':');
sma.getValue();
}
buffer.append(']');
if (useReferenceCounting) {
buffer.append(" autorelease]");
}
}
@Override
public boolean visit(NullLiteral node) {
buffer.append("nil");
return false;
}
@Override
public boolean visit(NumberLiteral node) {
String token = node.getToken();
if (token != null) {
buffer.append(LiteralGenerator.fixNumberToken(token, node.getTypeBinding()));
} else {
buffer.append(LiteralGenerator.generate(node.getValue()));
}
return false;
}
@Override
public boolean visit(ParenthesizedExpression node) {
buffer.append("(");
node.getExpression().accept(this);
buffer.append(")");
return false;
}
@Override
public boolean visit(PostfixExpression node) {
node.getOperand().accept(this);
buffer.append(node.getOperator().toString());
return false;
}
@Override
public boolean visit(PrefixExpression node) {
buffer.append(node.getOperator().toString());
node.getOperand().accept(this);
return false;
}
@Override
public boolean visit(PrimitiveType node) {
buffer.append(NameTable.primitiveTypeToObjC(node.getTypeBinding()));
return false;
}
@Override
public boolean visit(QualifiedName node) {
IBinding binding = node.getBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding var = (IVariableBinding) binding;
String constantName = BindingUtil.extractGlobalConstantName(var);
if (constantName != null) {
buffer.append(constantName);
return false;
}
if (BindingUtil.isPrimitiveConstant(var)) {
buffer.append(NameTable.getPrimitiveConstantName(var));
return false;
} else if (BindingUtil.isStatic(var)) {
buffer.append(NameTable.getStaticVarQualifiedName(var));
return false;
}
}
if (binding instanceof ITypeBinding) {
buffer.append(NameTable.getFullName((ITypeBinding) binding));
return false;
}
Name qualifier = node.getQualifier();
qualifier.accept(this);
buffer.append("->");
node.getName().accept(this);
return false;
}
@Override
public boolean visit(QualifiedType node) {
ITypeBinding binding = node.getTypeBinding();
if (binding != null) {
buffer.append(NameTable.getFullName(binding));
return false;
}
return true;
}
@Override
public boolean visit(ReturnStatement node) {
buffer.append("return");
Expression expr = node.getExpression();
MethodDeclaration method = TreeUtil.getOwningMethod(node);
if (expr != null) {
buffer.append(' ');
expr.accept(this);
} else if (method != null && method.getMethodBinding().isConstructor()) {
// A return statement without any expression is allowed in constructors.
buffer.append(" self");
}
buffer.append(";\n");
return false;
}
@Override
public boolean visit(SimpleName node) {
IBinding binding = node.getBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding var = (IVariableBinding) binding;
if (BindingUtil.isPrimitiveConstant(var)) {
buffer.append(NameTable.getPrimitiveConstantName(var));
} else if (BindingUtil.isStatic(var)) {
buffer.append(NameTable.getStaticVarQualifiedName(var));
} else if (var.isField()) {
buffer.append(NameTable.javaFieldToObjC(NameTable.getName(var)));
} else {
buffer.append(NameTable.getName(var));
}
return false;
}
if (binding instanceof ITypeBinding) {
if (binding instanceof IOSTypeBinding) {
buffer.append(binding.getName());
} else {
buffer.append(NameTable.getFullName((ITypeBinding) binding));
}
} else {
buffer.append(node.getIdentifier());
}
return false;
}
@Override
public boolean visit(SimpleType node) {
ITypeBinding binding = node.getTypeBinding();
if (binding != null) {
String name = NameTable.getFullName(binding);
buffer.append(name);
return false;
}
return true;
}
@Override
public boolean visit(SingleMemberAnnotation node) {
printAnnotationCreation(node);
return false;
}
@Override
public boolean visit(SingleVariableDeclaration node) {
buffer.append(NameTable.getSpecificObjCType(node.getVariableBinding()));
if (node.isVarargs()) {
buffer.append("...");
}
if (buffer.charAt(buffer.length() - 1) != '*') {
buffer.append(" ");
}
node.getName().accept(this);
for (int i = 0; i < node.getExtraDimensions(); i++) {
buffer.append("[]");
}
if (node.getInitializer() != null) {
buffer.append(" = ");
node.getInitializer().accept(this);
}
return false;
}
@Override
public boolean visit(StringLiteral node) {
String s = generateStringLiteral(node);
if (TRIGRAPH_REGEX.matcher(s).matches()) {
// Split string between the two '?' chars in the trigraph, so compiler
// will concatenate the string without interpreting the trigraph.
String[] substrings = s.split("\\?\\?");
buffer.append(substrings[0]);
for (int i = 1; i < substrings.length; i++) {
buffer.append("?\" \"?");
buffer.append(substrings[i]);
}
} else {
buffer.append(s);
}
return false;
}
public static String generateStringLiteral(StringLiteral node) {
if (UnicodeUtils.hasValidCppCharacters(node.getLiteralValue())) {
return "@\"" + UnicodeUtils.escapeStringLiteral(node.getLiteralValue()) + "\"";
} else {
return buildStringFromChars(node.getLiteralValue());
}
}
@VisibleForTesting
static String buildStringFromChars(String s) {
int length = s.length();
StringBuilder buffer = new StringBuilder();
buffer.append(
"[NSString stringWithCharacters:(jchar[]) { ");
int i = 0;
while (i < length) {
char c = s.charAt(i);
buffer.append("(int) 0x");
buffer.append(Integer.toHexString(c));
if (++i < length) {
buffer.append(", ");
}
}
buffer.append(" } length:");
String lengthString = Integer.toString(length);
buffer.append(lengthString);
buffer.append(']');
return buffer.toString();
}
@Override
public boolean visit(SuperFieldAccess node) {
buffer.append(NameTable.javaFieldToObjC(NameTable.getName(node.getName().getBinding())));
return false;
}
@Override
public boolean visit(SuperMethodInvocation node) {
IMethodBinding binding = node.getMethodBinding();
assert node.getQualifier() == null
: "Qualifiers expected to be handled by SuperMethodInvocationRewriter.";
assert !BindingUtil.isStatic(binding) : "Static invocations are rewritten by Functionizer.";
buffer.append("[super");
printMethodInvocationNameAndArgs(binding, node.getArguments());
buffer.append(']');
return false;
}
@Override
public boolean visit(SwitchCase node) {
if (node.isDefault()) {
buffer.append(" default:\n");
} else {
buffer.append(" case ");
Expression expr = node.getExpression();
boolean isEnumConstant = expr.getTypeBinding().isEnum();
if (isEnumConstant) {
String typeName = NameTable.getFullName(expr.getTypeBinding());
String bareTypeName = typeName.endsWith("Enum")
? typeName.substring(0, typeName.length() - 4) : typeName;
buffer.append(bareTypeName).append("_");
}
if (isEnumConstant && expr instanceof SimpleName) {
buffer.append(((SimpleName) expr).getIdentifier());
} else if (isEnumConstant && expr instanceof QualifiedName) {
buffer.append(((QualifiedName) expr).getName().getIdentifier());
} else {
expr.accept(this);
}
buffer.append(":\n");
}
return false;
}
@Override
public boolean visit(SwitchStatement node) {
Expression expr = node.getExpression();
ITypeBinding exprType = expr.getTypeBinding();
if (Types.isJavaStringType(exprType)) {
printStringSwitchStatement(node);
return false;
}
buffer.append("switch (");
if (exprType.isEnum()) {
buffer.append('[');
}
expr.accept(this);
if (exprType.isEnum()) {
buffer.append(" ordinal]");
}
buffer.append(") ");
buffer.append("{\n");
List<Statement> stmts = node.getStatements();
for (Statement stmt : stmts) {
stmt.accept(this);
}
if (!stmts.isEmpty() && stmts.get(stmts.size() - 1) instanceof SwitchCase) {
// Last switch case doesn't have an associated statement, so add
// an empty one.
buffer.append(";\n");
}
if (!stmts.isEmpty() && stmts.get(stmts.size() - 1) instanceof SwitchCase) {
// Last switch case doesn't have an associated statement, so add
// an empty one.
buffer.append(";\n");
}
buffer.append("}\n");
return false;
}
private void printStringSwitchStatement(SwitchStatement node) {
buffer.append("{\n");
// Define an array of all the string constant case values.
List<String> caseValues = Lists.newArrayList();
List<Statement> stmts = node.getStatements();
for (Statement stmt : stmts) {
if (stmt instanceof SwitchCase) {
SwitchCase caseStmt = (SwitchCase) stmt;
if (!caseStmt.isDefault()) {
caseValues.add(getStringConstant(caseStmt.getExpression()));
}
}
}
buffer.append("NSArray *__caseValues = [NSArray arrayWithObjects:");
for (String value : caseValues) {
buffer.append("@\"" + UnicodeUtils.escapeStringLiteral(value) + "\", ");
}
buffer.append("nil];\n");
buffer.append("NSUInteger __index = [__caseValues indexOfObject:");
node.getExpression().accept(this);
buffer.append("];\n");
buffer.append("switch (__index) {\n");
for (Statement stmt : stmts) {
if (stmt instanceof SwitchCase) {
SwitchCase caseStmt = (SwitchCase) stmt;
if (caseStmt.isDefault()) {
stmt.accept(this);
} else {
int i = caseValues.indexOf(getStringConstant(caseStmt.getExpression()));
assert i >= 0;
buffer.append("case ");
buffer.append(i);
buffer.append(":\n");
}
} else {
stmt.accept(this);
}
}
buffer.append("}\n}\n");
}
private static String getStringConstant(Expression expr) {
Object constantValue = expr.getConstantValue();
assert constantValue != null && constantValue instanceof String;
return (String) constantValue;
}
@Override
public boolean visit(SynchronizedStatement node) {
buffer.append("@synchronized(");
node.getExpression().accept(this);
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(ThisExpression node) {
buffer.append("self");
return false;
}
@Override
public boolean visit(ThrowStatement node) {
buffer.append("@throw ");
node.getExpression().accept(this);
buffer.append(";\n");
return false;
}
@Override
public boolean visit(TryStatement node) {
List<VariableDeclarationExpression> resources = node.getResources();
boolean hasResources = !resources.isEmpty();
if (hasResources) {
buffer.append("{\n");
buffer.append("JavaLangThrowable *__mainException = nil;\n");
}
for (VariableDeclarationExpression var : resources) {
var.accept(this);
buffer.append(";\n");
}
buffer.append("@try ");
node.getBody().accept(this);
buffer.append(' ');
for (CatchClause cc : node.getCatchClauses()) {
if (cc.getException().getType() instanceof UnionType) {
printMultiCatch(cc, hasResources);
} else {
buffer.append("@catch (");
cc.getException().accept(this);
buffer.append(") {\n");
printMainExceptionStore(hasResources, cc);
printStatements(cc.getBody().getStatements());
buffer.append("}\n");
}
}
if (node.getFinally() != null || resources.size() > 0) {
buffer.append(" @finally {\n");
if (node.getFinally() != null) {
printStatements(node.getFinally().getStatements());
}
for (VariableDeclarationExpression var : resources) {
for (VariableDeclarationFragment frag : var.getFragments()) {
buffer.append("@try {\n[");
buffer.append(frag.getName().getFullyQualifiedName());
buffer.append(" close];\n}\n");
buffer.append("@catch (JavaLangThrowable *e) {\n");
buffer.append("if (__mainException) {\n");
buffer.append("[__mainException addSuppressedWithJavaLangThrowable:e];\n} else {\n");
buffer.append("__mainException = e;\n}\n");
buffer.append("}\n");
}
}
if (hasResources) {
buffer.append("if (__mainException) {\n@throw __mainException;\n}\n");
}
buffer.append("}\n");
}
if (hasResources) {
buffer.append("}\n");
}
return false;
}
private void printMainExceptionStore(boolean hasResources, CatchClause cc) {
if (hasResources) {
buffer.append("__mainException = ");
buffer.append(cc.getException().getName().getFullyQualifiedName());
buffer.append(";\n");
}
}
@Override
public boolean visit(TypeLiteral node) {
ITypeBinding type = node.getType().getTypeBinding();
if (type.isPrimitive()) {
buffer.append(String.format("[IOSClass %sClass]", type.getName()));
} else {
buffer.append(NameTable.getFullName(type));
buffer.append("_class_()");
}
return false;
}
@Override
public boolean visit(VariableDeclarationExpression node) {
String typeString = NameTable.getSpecificObjCType(node.getTypeBinding());
boolean needsAsterisk = typeString.endsWith("*");
buffer.append(typeString);
if (!needsAsterisk) {
buffer.append(' ');
}
for (Iterator<VariableDeclarationFragment> it = node.getFragments().iterator();
it.hasNext(); ) {
VariableDeclarationFragment f = it.next();
f.accept(this);
if (it.hasNext()) {
buffer.append(", ");
if (needsAsterisk) {
buffer.append('*');
}
}
}
return false;
}
@Override
public boolean visit(VariableDeclarationFragment node) {
node.getName().accept(this);
Expression initializer = node.getInitializer();
if (initializer != null) {
buffer.append(" = ");
initializer.accept(this);
}
return false;
}
@Override
public boolean visit(VariableDeclarationStatement node) {
List<VariableDeclarationFragment> vars = node.getFragments();
assert !vars.isEmpty();
IVariableBinding binding = vars.get(0).getVariableBinding();
if (binding.getType() instanceof IOSBlockTypeBinding) {
assert vars.size() == 1 : "TODO: cannot handle multiple fragments for block";
IOSBlockTypeBinding blockBinding = (IOSBlockTypeBinding) binding.getType();
buffer.append(blockBinding.getNamedDeclarationFirstPart());
VariableDeclarationFragment frag = vars.get(0);
frag.getName().accept(this);
buffer.append(blockBinding.getNamedDeclarationLastPart());
Expression initializer = frag.getInitializer();
if (initializer != null) {
buffer.append(" = ");
initializer.accept(this);
}
buffer.append(";\n");
return false;
} else {
String objcType = NameTable.getSpecificObjCType(binding);
String objcTypePointers = " ";
int idx = objcType.indexOf(" *");
if (idx != -1) {
// Split the type at the first pointer. The second part of the type is
// applied to each fragment. (eg. Foo *one, *two)
objcTypePointers = objcType.substring(idx);
objcType = objcType.substring(0, idx);
}
buffer.append(objcType);
for (Iterator<VariableDeclarationFragment> it = vars.iterator(); it.hasNext(); ) {
VariableDeclarationFragment f = it.next();
buffer.append(objcTypePointers);
f.accept(this);
if (it.hasNext()) {
buffer.append(",");
}
}
buffer.append(";\n");
return false;
}
}
@Override
public boolean visit(WhileStatement node) {
buffer.append("while (");
node.getExpression().accept(this);
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(Initializer node) {
// All Initializer nodes should have been converted during initialization
// normalization.
throw new AssertionError("initializer node not converted");
}
// Returns a string where all characters that will interfer in
// a valid Objective-C string are quoted.
private static String makeQuotedString(String originalString) {
int location = 0;
StringBuffer buffer = new StringBuffer(originalString);
while ((location = buffer.indexOf("\\", location)) != -1) {
buffer.replace(location++, location++, "\\\\");
}
location = 0;
while ((location = buffer.indexOf("\"", location)) != -1) {
buffer.replace(location++, location++, "\\\"");
}
location = 0;
while ((location = buffer.indexOf("\n")) != -1) {
buffer.replace(location++, location++, "\\n");
}
return buffer.toString();
}
}
| translator/src/main/java/com/google/devtools/j2objc/gen/StatementGenerator.java | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.j2objc.gen;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.ast.Annotation;
import com.google.devtools.j2objc.ast.AnonymousClassDeclaration;
import com.google.devtools.j2objc.ast.ArrayAccess;
import com.google.devtools.j2objc.ast.ArrayCreation;
import com.google.devtools.j2objc.ast.ArrayInitializer;
import com.google.devtools.j2objc.ast.ArrayType;
import com.google.devtools.j2objc.ast.AssertStatement;
import com.google.devtools.j2objc.ast.Assignment;
import com.google.devtools.j2objc.ast.Block;
import com.google.devtools.j2objc.ast.BooleanLiteral;
import com.google.devtools.j2objc.ast.BreakStatement;
import com.google.devtools.j2objc.ast.CStringLiteral;
import com.google.devtools.j2objc.ast.CastExpression;
import com.google.devtools.j2objc.ast.CatchClause;
import com.google.devtools.j2objc.ast.CharacterLiteral;
import com.google.devtools.j2objc.ast.ClassInstanceCreation;
import com.google.devtools.j2objc.ast.CompilationUnit;
import com.google.devtools.j2objc.ast.ConditionalExpression;
import com.google.devtools.j2objc.ast.ConstructorInvocation;
import com.google.devtools.j2objc.ast.ContinueStatement;
import com.google.devtools.j2objc.ast.DoStatement;
import com.google.devtools.j2objc.ast.EmptyStatement;
import com.google.devtools.j2objc.ast.EnhancedForStatement;
import com.google.devtools.j2objc.ast.Expression;
import com.google.devtools.j2objc.ast.ExpressionStatement;
import com.google.devtools.j2objc.ast.FieldAccess;
import com.google.devtools.j2objc.ast.ForStatement;
import com.google.devtools.j2objc.ast.FunctionInvocation;
import com.google.devtools.j2objc.ast.IfStatement;
import com.google.devtools.j2objc.ast.InfixExpression;
import com.google.devtools.j2objc.ast.Initializer;
import com.google.devtools.j2objc.ast.InstanceofExpression;
import com.google.devtools.j2objc.ast.LabeledStatement;
import com.google.devtools.j2objc.ast.MarkerAnnotation;
import com.google.devtools.j2objc.ast.MemberValuePair;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.MethodInvocation;
import com.google.devtools.j2objc.ast.Name;
import com.google.devtools.j2objc.ast.NativeExpression;
import com.google.devtools.j2objc.ast.NativeStatement;
import com.google.devtools.j2objc.ast.NormalAnnotation;
import com.google.devtools.j2objc.ast.NullLiteral;
import com.google.devtools.j2objc.ast.NumberLiteral;
import com.google.devtools.j2objc.ast.ParenthesizedExpression;
import com.google.devtools.j2objc.ast.PostfixExpression;
import com.google.devtools.j2objc.ast.PrefixExpression;
import com.google.devtools.j2objc.ast.PrimitiveType;
import com.google.devtools.j2objc.ast.QualifiedName;
import com.google.devtools.j2objc.ast.QualifiedType;
import com.google.devtools.j2objc.ast.ReturnStatement;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.SimpleType;
import com.google.devtools.j2objc.ast.SingleMemberAnnotation;
import com.google.devtools.j2objc.ast.SingleVariableDeclaration;
import com.google.devtools.j2objc.ast.Statement;
import com.google.devtools.j2objc.ast.StringLiteral;
import com.google.devtools.j2objc.ast.SuperConstructorInvocation;
import com.google.devtools.j2objc.ast.SuperFieldAccess;
import com.google.devtools.j2objc.ast.SuperMethodInvocation;
import com.google.devtools.j2objc.ast.SwitchCase;
import com.google.devtools.j2objc.ast.SwitchStatement;
import com.google.devtools.j2objc.ast.SynchronizedStatement;
import com.google.devtools.j2objc.ast.ThisExpression;
import com.google.devtools.j2objc.ast.ThrowStatement;
import com.google.devtools.j2objc.ast.TreeNode;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.TreeVisitor;
import com.google.devtools.j2objc.ast.TryStatement;
import com.google.devtools.j2objc.ast.Type;
import com.google.devtools.j2objc.ast.TypeLiteral;
import com.google.devtools.j2objc.ast.UnionType;
import com.google.devtools.j2objc.ast.VariableDeclarationExpression;
import com.google.devtools.j2objc.ast.VariableDeclarationFragment;
import com.google.devtools.j2objc.ast.VariableDeclarationStatement;
import com.google.devtools.j2objc.ast.WhileStatement;
import com.google.devtools.j2objc.translate.Functionizer;
import com.google.devtools.j2objc.types.IOSBlockTypeBinding;
import com.google.devtools.j2objc.types.IOSMethod;
import com.google.devtools.j2objc.types.IOSMethodBinding;
import com.google.devtools.j2objc.types.IOSTypeBinding;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.BindingUtil;
import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.devtools.j2objc.util.NameTable;
import com.google.devtools.j2objc.util.UnicodeUtils;
import org.eclipse.jdt.core.dom.IAnnotationBinding;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMemberValuePairBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Returns an Objective-C equivalent of a Java AST node.
*
* @author Tom Ball
*/
public class StatementGenerator extends TreeVisitor {
private final CompilationUnit unit;
private final SourceBuilder buffer;
private final boolean asFunction;
private final boolean useReferenceCounting;
private static final Pattern TRIGRAPH_REGEX = Pattern.compile("@\".*\\?\\?[=/'()!<>-].*\"");
public static String generate(TreeNode node, boolean asFunction, int currentLine) {
StatementGenerator generator = new StatementGenerator(node, asFunction, currentLine);
if (node == null) {
throw new NullPointerException("cannot generate a null statement");
}
generator.run(node);
return generator.getResult();
}
private StatementGenerator(TreeNode node, boolean asFunction, int currentLine) {
this.unit = TreeUtil.getCompilationUnit(node);
buffer = new SourceBuilder(Options.emitLineDirectives(), currentLine);
this.asFunction = asFunction;
useReferenceCounting = !Options.useARC();
}
private String getResult() {
return buffer.toString();
}
private void printArgumentExpression(IMethodBinding method, Expression arg, int index) {
if (method != null) {
// wrap @Block argument
IAnnotationBinding blockAnnotation =
BindingUtil.getAnnotation(method.getParameterAnnotations(index), com.google.j2objc.annotations.Block.class);
if (blockAnnotation != null) {
ITypeBinding blockTpe = method.getParameterTypes()[index];
String blockRet = BindingUtil.BlockBridge.returnType(blockAnnotation, blockTpe);
String[] blockParams = BindingUtil.BlockBridge.paramTypes(blockAnnotation, blockTpe);
// TODO: do a proper scope analysis here to prevent accidental name pollution
buffer.append("(^{");
buffer.append(NameTable.getSpecificObjCType(method.getParameterTypes()[index]));
if (buffer.charAt(buffer.length() - 1) != '*') {
buffer.append(" ");
}
String localRunnerId = "___$runner";
buffer.append(localRunnerId + " = ");
arg.accept(this);
buffer.append(";");
buffer.append("return " + localRunnerId + " == nil ? nil : ");
buffer.append(useReferenceCounting ? "[[" : "[");
buffer.append("^" + blockRet + " (");
char argId = 'a';
boolean first = true;
for (String param : blockParams) {
if (first) {
first = false;
} else {
buffer.append(", ");
}
buffer.append(param);
if (!param.endsWith("*")) {
buffer.append(' ');
}
buffer.append("____" + (argId++));
}
buffer.append(") { ");
if (!blockRet.equals("void")) {
buffer.append("return ");
}
buffer.append("[" + localRunnerId + " run");
argId = 'a';
first = true;
for (Object _ : blockParams) {
if (first) {
first = false;
} else {
buffer.append(" param");
}
buffer.append(":____" + (argId++));
}
buffer.append("];}");
buffer.append(" copy]");
if (useReferenceCounting) {
buffer.append(" autorelease]");
}
buffer.append(";})()");
return;
}
}
arg.accept(this);
}
private void printMethodInvocationNameAndArgs(IMethodBinding binding, List<Expression> args) {
String selector = NameTable.getMethodSelector(binding);
String[] selParts = selector.split(":");
if (args.isEmpty()) {
assert selParts.length == 1 && !selector.endsWith(":");
buffer.append(' ');
buffer.append(selector);
} else {
assert selParts.length == args.size();
for (int i = 0; i < args.size(); i++) {
buffer.append(' ');
buffer.append(selParts[i]);
buffer.append(':');
printArgumentExpression(binding, args.get(i), i);
}
}
}
@Override
public boolean preVisit(TreeNode node) {
super.preVisit(node);
if (!(node instanceof Block)) {
buffer.syncLineNumbers(node);
}
return true;
}
@Override
public boolean visit(AnonymousClassDeclaration node) {
// Multi-method anonymous classes should have been converted by the
// InnerClassExtractor.
assert node.getBodyDeclarations().size() == 1;
// Generate an iOS block.
assert false : "not implemented yet";
return true;
}
@Override
public boolean visit(ArrayAccess node) {
throw new AssertionError("ArrayAccess nodes are rewritten by ArrayRewriter.");
}
@Override
public boolean visit(ArrayCreation node) {
throw new AssertionError("ArrayCreation nodes are rewritten by ArrayRewriter.");
}
@Override
public boolean visit(ArrayInitializer node) {
ITypeBinding type = node.getTypeBinding();
assert type.isArray();
ITypeBinding componentType = type.getComponentType();
String componentTypeName = componentType.isPrimitive()
? NameTable.primitiveTypeToObjC(componentType) : "id";
buffer.append(String.format("(%s[]){ ", componentTypeName));
for (Iterator<Expression> it = node.getExpressions().iterator(); it.hasNext(); ) {
it.next().accept(this);
if (it.hasNext()) {
buffer.append(", ");
}
}
buffer.append(" }");
return false;
}
@Override
public boolean visit(ArrayType node) {
ITypeBinding binding = Types.mapType(node.getTypeBinding());
if (binding instanceof IOSTypeBinding) {
buffer.append(binding.getName());
} else {
node.getComponentType().accept(this);
buffer.append("[]");
}
return false;
}
@Override
public boolean visit(AssertStatement node) {
buffer.append(asFunction ? "NSCAssert(" : "NSAssert(");
node.getExpression().accept(this);
buffer.append(", ");
if (node.getMessage() != null) {
Expression expr = node.getMessage();
boolean isString = expr instanceof StringLiteral;
if (!isString) {
buffer.append('[');
}
int start = buffer.length();
expr.accept(this);
int end = buffer.length();
// Commas inside sub-expression of the NSAssert macro will be incorrectly interpreted as
// new argument indicators in the macro. Replace commas with the J2OBJC_COMMA macro.
String substring = buffer.substring(start, end);
substring = substring.replaceAll(",", " J2OBJC_COMMA()");
buffer.replace(start, end, substring);
if (!isString) {
buffer.append(" description]");
}
} else {
int startPos = node.getStartPosition();
String assertStatementString =
unit.getSource().substring(startPos, startPos + node.getLength());
assertStatementString = CharMatcher.WHITESPACE.trimFrom(assertStatementString);
assertStatementString = makeQuotedString(assertStatementString);
// Generates the following string:
// filename.java:456 condition failed: foobar != fish.
buffer.append("@\"" + TreeUtil.getSourceFileName(unit) + ":" + node.getLineNumber()
+ " condition failed: " + assertStatementString + "\"");
}
buffer.append(");\n");
return false;
}
@Override
public boolean visit(Assignment node) {
node.getLeftHandSide().accept(this);
buffer.append(' ');
buffer.append(node.getOperator().toString());
buffer.append(' ');
node.getRightHandSide().accept(this);
return false;
}
@Override
public boolean visit(Block node) {
if (node.hasAutoreleasePool()) {
buffer.append("{\n@autoreleasepool ");
}
buffer.append("{\n");
printStatements(node.getStatements());
buffer.append("}\n");
if (node.hasAutoreleasePool()) {
buffer.append("}\n");
}
return false;
}
private void printStatements(List<?> statements) {
for (Iterator<?> it = statements.iterator(); it.hasNext(); ) {
Statement s = (Statement) it.next();
s.accept(this);
}
}
@Override
public boolean visit(BooleanLiteral node) {
buffer.append(node.booleanValue() ? "YES" : "NO");
return false;
}
@Override
public boolean visit(BreakStatement node) {
if (node.getLabel() != null) {
// Objective-C doesn't have a labeled break, so use a goto.
buffer.append("goto ");
node.getLabel().accept(this);
} else {
buffer.append("break");
}
buffer.append(";\n");
return false;
}
@Override
public boolean visit(CStringLiteral node) {
buffer.append("\"");
buffer.append(node.getLiteralValue());
buffer.append("\"");
return false;
}
@Override
public boolean visit(CastExpression node) {
ITypeBinding type = node.getType().getTypeBinding();
buffer.append("(");
if (Options.useARC()) {
if (BindingUtil.isObjCType(type) &&
BindingUtil.isCFType(node.getExpression().getTypeBinding())) {
buffer.append("__bridge ");
}
}
buffer.append(NameTable.getSpecificObjCType(type));
buffer.append(") ");
node.getExpression().accept(this);
return false;
}
private void printMultiCatch(CatchClause node, boolean hasResources) {
SingleVariableDeclaration exception = node.getException();
for (Type exceptionType : ((UnionType) exception.getType()).getTypes()) {
buffer.append("@catch (");
exceptionType.accept(this);
// Assume exception is definitely pointer type
buffer.append(" *");
exception.getName().accept(this);
buffer.append(") {\n");
printMainExceptionStore(hasResources, node);
printStatements(node.getBody().getStatements());
buffer.append("}\n");
}
}
@Override
public boolean visit(CharacterLiteral node) {
buffer.append(UnicodeUtils.escapeCharLiteral(node.charValue()));
return false;
}
@Override
public boolean visit(ClassInstanceCreation node) {
IMethodBinding binding = node.getMethodBinding();
if (BindingUtil.isMappedToNative(binding) || Functionizer.isConstructorOfMappedClass(binding)) {
ITypeBinding type = node.getType().getTypeBinding();
boolean addAutorelease = useReferenceCounting && !node.hasRetainedResult();
buffer.append(addAutorelease ? "[[[" : "[[");
buffer.append(NameTable.getFullName(type));
// if the method binding is a mapped constructor, use that instead
IMethodBinding method = node.getMethodBinding();
buffer.append(" alloc]");
List<Expression> arguments = node.getArguments();
printMethodInvocationNameAndArgs(method, arguments);
buffer.append(']');
if (addAutorelease) {
buffer.append(" autorelease]");
}
return false;
} else {
throw new AssertionError(
"ClassInstanceCreation nodes are rewritten by Functionizer. node: " + node);
}
}
@Override
public boolean visit(ConditionalExpression node) {
boolean castNeeded = false;
ITypeBinding thenType = node.getThenExpression().getTypeBinding();
ITypeBinding elseType = node.getElseExpression().getTypeBinding();
if (!thenType.equals(elseType)
&& !(node.getThenExpression() instanceof NullLiteral)
&& !(node.getElseExpression() instanceof NullLiteral)) {
// gcc fails to compile a conditional expression where the two clauses of
// the expression have different type. So cast any interface type down to
// "id" to make the compiler happy. Concrete object types all have a
// common ancestor of NSObject, so they don't need a cast.
castNeeded = true;
}
node.getExpression().accept(this);
buffer.append(" ? ");
if (castNeeded && thenType.isInterface()) {
buffer.append("((id) ");
}
node.getThenExpression().accept(this);
if (castNeeded && thenType.isInterface()) {
buffer.append(')');
}
buffer.append(" : ");
if (castNeeded && elseType.isInterface()) {
buffer.append("((id) ");
}
node.getElseExpression().accept(this);
if (castNeeded && elseType.isInterface()) {
buffer.append(')');
}
return false;
}
@Override
public boolean visit(ConstructorInvocation node) {
return visitConstructorInvocation(node);
}
@Override
public boolean visit(SuperConstructorInvocation node) {
return visitConstructorInvocation(node);
}
private boolean visitConstructorInvocation(Statement node) {
IMethodBinding binding;
List<Expression> args;
String receiver;
if (node instanceof ConstructorInvocation) {
binding = ((ConstructorInvocation) node).getMethodBinding();
args = ((ConstructorInvocation) node).getArguments();
receiver = "self";
} else if (node instanceof SuperConstructorInvocation) {
binding = ((SuperConstructorInvocation) node).getMethodBinding();
args = ((SuperConstructorInvocation) node).getArguments();
receiver = "super";
} else {
throw new AssertionError("Illegal statement type.");
}
if (BindingUtil.isMappedToNative(binding) || Functionizer.isConstructorOfMappedClass(binding)) {
buffer.append("self = [" + receiver);
printMethodInvocationNameAndArgs(binding, args);
buffer.append("];\n");
return false;
} else {
throw new AssertionError("SuperConstructorInvocation nodes are rewritten by Functionizer.");
}
}
@Override
public boolean visit(ContinueStatement node) {
if (node.getLabel() != null) {
// Objective-C doesn't have a labeled continue, so use a goto.
buffer.append("goto ");
node.getLabel().accept(this);
} else {
buffer.append("continue");
}
buffer.append(";\n");
return false;
}
@Override
public boolean visit(DoStatement node) {
buffer.append("do ");
node.getBody().accept(this);
buffer.append(" while (");
node.getExpression().accept(this);
buffer.append(");\n");
return false;
}
@Override
public boolean visit(EmptyStatement node) {
buffer.append(";\n");
return false;
}
@Override
public boolean visit(EnhancedForStatement node) {
buffer.append("for (");
node.getParameter().accept(this);
buffer.append(" in ");
node.getExpression().accept(this);
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(ExpressionStatement node) {
Expression expression = node.getExpression();
ITypeBinding type = expression.getTypeBinding();
if (!type.isPrimitive() && Options.useARC()
&& (expression instanceof MethodInvocation
|| expression instanceof SuperMethodInvocation
|| expression instanceof FunctionInvocation)) {
// Avoid clang warning that the return value is unused.
buffer.append("(void) ");
}
expression.accept(this);
buffer.append(";\n");
return false;
}
@Override
public boolean visit(FieldAccess node) {
final Expression expr = node.getExpression();
final IVariableBinding binding = node.getVariableBinding();
final String dotAccess = BindingUtil.extractDotMappingName(binding);
if (dotAccess != null) {
expr.accept(this);
buffer.append("." + dotAccess);
} else {
// self->static_var is invalid Objective-C.
if (!(expr instanceof ThisExpression && BindingUtil.isStatic(node.getVariableBinding()))) {
expr.accept(this);
buffer.append("->");
}
node.getName().accept(this);
}
return false;
}
@Override
public boolean visit(ForStatement node) {
buffer.append("for (");
for (Iterator<Expression> it = node.getInitializers().iterator(); it.hasNext(); ) {
Expression next = it.next();
next.accept(this);
if (it.hasNext()) {
buffer.append(", ");
}
}
buffer.append("; ");
if (node.getExpression() != null) {
node.getExpression().accept(this);
}
buffer.append("; ");
for (Iterator<Expression> it = node.getUpdaters().iterator(); it.hasNext(); ) {
it.next().accept(this);
if (it.hasNext()) {
buffer.append(", ");
}
}
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(FunctionInvocation node) {
buffer.append(node.getName());
buffer.append('(');
for (Iterator<Expression> iter = node.getArguments().iterator(); iter.hasNext(); ) {
iter.next().accept(this);
if (iter.hasNext()) {
buffer.append(", ");
}
}
buffer.append(')');
return false;
}
@Override
public boolean visit(IfStatement node) {
buffer.append("if (");
node.getExpression().accept(this);
buffer.append(") ");
node.getThenStatement().accept(this);
if (node.getElseStatement() != null) {
buffer.append(" else ");
node.getElseStatement().accept(this);
}
return false;
}
@Override
public boolean visit(InfixExpression node) {
InfixExpression.Operator op = node.getOperator();
Expression lhs = node.getLeftOperand();
Expression rhs = node.getRightOperand();
List<Expression> extendedOperands = node.getExtendedOperands();
if ((op.equals(InfixExpression.Operator.EQUALS)
|| op.equals(InfixExpression.Operator.NOT_EQUALS))
&& (lhs instanceof StringLiteral || rhs instanceof StringLiteral)) {
Expression first = lhs;
Expression second = rhs;
if (!(lhs instanceof StringLiteral)) {
// In case the lhs can't call isEqual.
first = rhs;
second = lhs;
}
buffer.append(op.equals(InfixExpression.Operator.NOT_EQUALS) ? "![" : "[");
first.accept(this);
buffer.append(" isEqual:");
second.accept(this);
buffer.append("]");
} else {
lhs.accept(this);
buffer.append(' ');
buffer.append(op.toString());
buffer.append(' ');
rhs.accept(this);
for (Iterator<Expression> it = extendedOperands.iterator(); it.hasNext(); ) {
buffer.append(' ').append(op.toString()).append(' ');
it.next().accept(this);
}
}
return false;
}
@Override
public boolean visit(InstanceofExpression node) {
ITypeBinding rightBinding = node.getRightOperand().getTypeBinding();
if (rightBinding.isInterface()) {
// Our version of "isInstance" is faster than "conformsToProtocol".
buffer.append(String.format("[%s_class_() isInstance:", NameTable.getFullName(rightBinding)));
node.getLeftOperand().accept(this);
buffer.append(']');
} else {
buffer.append('[');
node.getLeftOperand().accept(this);
buffer.append(" isKindOfClass:[");
node.getRightOperand().accept(this);
buffer.append(" class]]");
}
return false;
}
@Override
public boolean visit(LabeledStatement node) {
node.getLabel().accept(this);
buffer.append(": ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(MarkerAnnotation node) {
printAnnotationCreation(node);
return false;
}
@Override
public boolean visit(MethodInvocation node) {
IMethodBinding binding = node.getMethodBinding();
assert binding != null;
// Object receiving the message, or null if it's a method in this class.
Expression receiver = node.getExpression();
String dotAccess = BindingUtil.extractDotMappingName(binding);
if (dotAccess != null) {
if (receiver != null) {
receiver.accept(this);
} else {
ErrorUtil.error(node, "DotMapped method cannot be called inside the same class");
}
buffer.append("." + dotAccess);
return false;
}
// TODO: move this into a function invocation thing?
String fnName = BindingUtil.extractGlobalFunctionName(binding);
if (fnName != null) {
buffer.append(fnName);
buffer.append('(');
List<Expression> args = node.getArguments();
for (int i = 0; i < args.size(); i++) {
printArgumentExpression(binding, args.get(i), i);
if (i < args.size() - 1) {
buffer.append(", ");
}
}
buffer.append(')');
return false;
}
String constName = BindingUtil.extractGlobalConstantName(binding);
if (constName != null) {
buffer.append(constName);
return false;
}
// Note: we dont move extension method mapping to JavaToIOSMethodTranslator bcuz
// we want to preserve the extension class in source code so that appropriate
// dependency will be picked up by import collector
// TODO: clean this up when there is time
IOSMethod mapped = BindingUtil.getMappedMethod(binding, /* extension */ true);
if (mapped != null) {
List<Expression> args = node.getArguments();
Expression newReceiver = args.remove(0);
receiver = newReceiver;
IOSMethodBinding newBinding =
IOSMethodBinding.newMappedExtensionMethod(mapped.getSelector(), binding);
newBinding.setModifiers(Modifier.PUBLIC); // do away static modifier
binding = newBinding;
}
printMethodInvocation(binding, receiver, node.getArguments());
return false;
}
private void printMethodInvocation(
IMethodBinding binding, Expression receiver, List<Expression> args) {
buffer.append('[');
if (BindingUtil.isStatic(binding)) {
buffer.append(NameTable.getFullName(binding.getDeclaringClass()));
} else if (receiver != null) {
receiver.accept(this);
} else {
buffer.append("self");
}
printMethodInvocationNameAndArgs(binding, args);
buffer.append(']');
}
@Override
public boolean visit(NativeExpression node) {
buffer.append(node.getCode());
return false;
}
@Override
public boolean visit(NativeStatement node) {
buffer.append(node.getCode());
buffer.append('\n');
return false;
}
@Override
public boolean visit(NormalAnnotation node) {
printAnnotationCreation(node);
return false;
}
private void printAnnotationCreation(Annotation node) {
IAnnotationBinding annotation = node.getAnnotationBinding();
buffer.append(useReferenceCounting ? "[[[" : "[[");
buffer.append(NameTable.getFullName(annotation.getAnnotationType()));
buffer.append(" alloc] init");
if (node instanceof NormalAnnotation) {
Map<String, Expression> args = Maps.newHashMap();
for (MemberValuePair pair : ((NormalAnnotation) node).getValues()) {
args.put(pair.getName().getIdentifier(), pair.getValue());
}
IMemberValuePairBinding[] members = BindingUtil.getSortedMemberValuePairs(annotation);
for (int i = 0; i < members.length; i++) {
if (i == 0) {
buffer.append("With");
} else {
buffer.append(" with");
}
IMemberValuePairBinding member = members[i];
String name = NameTable.getAnnotationPropertyName(member.getMethodBinding());
buffer.append(NameTable.capitalize(name));
buffer.append(':');
Expression value = args.get(name);
if (value != null) {
value.accept(this);
}
}
} else if (node instanceof SingleMemberAnnotation) {
SingleMemberAnnotation sma = (SingleMemberAnnotation) node;
buffer.append("With");
IMethodBinding accessorBinding = annotation.getAllMemberValuePairs()[0].getMethodBinding();
String name = NameTable.getAnnotationPropertyName(accessorBinding);
buffer.append(NameTable.capitalize(name));
buffer.append(':');
sma.getValue();
}
buffer.append(']');
if (useReferenceCounting) {
buffer.append(" autorelease]");
}
}
@Override
public boolean visit(NullLiteral node) {
buffer.append("nil");
return false;
}
@Override
public boolean visit(NumberLiteral node) {
String token = node.getToken();
if (token != null) {
buffer.append(LiteralGenerator.fixNumberToken(token, node.getTypeBinding()));
} else {
buffer.append(LiteralGenerator.generate(node.getValue()));
}
return false;
}
@Override
public boolean visit(ParenthesizedExpression node) {
buffer.append("(");
node.getExpression().accept(this);
buffer.append(")");
return false;
}
@Override
public boolean visit(PostfixExpression node) {
node.getOperand().accept(this);
buffer.append(node.getOperator().toString());
return false;
}
@Override
public boolean visit(PrefixExpression node) {
buffer.append(node.getOperator().toString());
node.getOperand().accept(this);
return false;
}
@Override
public boolean visit(PrimitiveType node) {
buffer.append(NameTable.primitiveTypeToObjC(node.getTypeBinding()));
return false;
}
@Override
public boolean visit(QualifiedName node) {
IBinding binding = node.getBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding var = (IVariableBinding) binding;
String constantName = BindingUtil.extractGlobalConstantName(var);
if (constantName != null) {
buffer.append(constantName);
return false;
}
if (BindingUtil.isPrimitiveConstant(var)) {
buffer.append(NameTable.getPrimitiveConstantName(var));
return false;
} else if (BindingUtil.isStatic(var)) {
buffer.append(NameTable.getStaticVarQualifiedName(var));
return false;
}
}
if (binding instanceof ITypeBinding) {
buffer.append(NameTable.getFullName((ITypeBinding) binding));
return false;
}
Name qualifier = node.getQualifier();
qualifier.accept(this);
buffer.append("->");
node.getName().accept(this);
return false;
}
@Override
public boolean visit(QualifiedType node) {
ITypeBinding binding = node.getTypeBinding();
if (binding != null) {
buffer.append(NameTable.getFullName(binding));
return false;
}
return true;
}
@Override
public boolean visit(ReturnStatement node) {
buffer.append("return");
Expression expr = node.getExpression();
MethodDeclaration method = TreeUtil.getOwningMethod(node);
if (expr != null) {
buffer.append(' ');
expr.accept(this);
} else if (method != null && method.getMethodBinding().isConstructor()) {
// A return statement without any expression is allowed in constructors.
buffer.append(" self");
}
buffer.append(";\n");
return false;
}
@Override
public boolean visit(SimpleName node) {
IBinding binding = node.getBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding var = (IVariableBinding) binding;
if (BindingUtil.isPrimitiveConstant(var)) {
buffer.append(NameTable.getPrimitiveConstantName(var));
} else if (BindingUtil.isStatic(var)) {
buffer.append(NameTable.getStaticVarQualifiedName(var));
} else if (var.isField()) {
buffer.append(NameTable.javaFieldToObjC(NameTable.getName(var)));
} else {
buffer.append(NameTable.getName(var));
}
return false;
}
if (binding instanceof ITypeBinding) {
if (binding instanceof IOSTypeBinding) {
buffer.append(binding.getName());
} else {
buffer.append(NameTable.getFullName((ITypeBinding) binding));
}
} else {
buffer.append(node.getIdentifier());
}
return false;
}
@Override
public boolean visit(SimpleType node) {
ITypeBinding binding = node.getTypeBinding();
if (binding != null) {
String name = NameTable.getFullName(binding);
buffer.append(name);
return false;
}
return true;
}
@Override
public boolean visit(SingleMemberAnnotation node) {
printAnnotationCreation(node);
return false;
}
@Override
public boolean visit(SingleVariableDeclaration node) {
buffer.append(NameTable.getSpecificObjCType(node.getVariableBinding()));
if (node.isVarargs()) {
buffer.append("...");
}
if (buffer.charAt(buffer.length() - 1) != '*') {
buffer.append(" ");
}
node.getName().accept(this);
for (int i = 0; i < node.getExtraDimensions(); i++) {
buffer.append("[]");
}
if (node.getInitializer() != null) {
buffer.append(" = ");
node.getInitializer().accept(this);
}
return false;
}
@Override
public boolean visit(StringLiteral node) {
String s = generateStringLiteral(node);
if (TRIGRAPH_REGEX.matcher(s).matches()) {
// Split string between the two '?' chars in the trigraph, so compiler
// will concatenate the string without interpreting the trigraph.
String[] substrings = s.split("\\?\\?");
buffer.append(substrings[0]);
for (int i = 1; i < substrings.length; i++) {
buffer.append("?\" \"?");
buffer.append(substrings[i]);
}
} else {
buffer.append(s);
}
return false;
}
public static String generateStringLiteral(StringLiteral node) {
if (UnicodeUtils.hasValidCppCharacters(node.getLiteralValue())) {
return "@\"" + UnicodeUtils.escapeStringLiteral(node.getLiteralValue()) + "\"";
} else {
return buildStringFromChars(node.getLiteralValue());
}
}
@VisibleForTesting
static String buildStringFromChars(String s) {
int length = s.length();
StringBuilder buffer = new StringBuilder();
buffer.append(
"[NSString stringWithCharacters:(jchar[]) { ");
int i = 0;
while (i < length) {
char c = s.charAt(i);
buffer.append("(int) 0x");
buffer.append(Integer.toHexString(c));
if (++i < length) {
buffer.append(", ");
}
}
buffer.append(" } length:");
String lengthString = Integer.toString(length);
buffer.append(lengthString);
buffer.append(']');
return buffer.toString();
}
@Override
public boolean visit(SuperFieldAccess node) {
buffer.append(NameTable.javaFieldToObjC(NameTable.getName(node.getName().getBinding())));
return false;
}
@Override
public boolean visit(SuperMethodInvocation node) {
IMethodBinding binding = node.getMethodBinding();
assert node.getQualifier() == null
: "Qualifiers expected to be handled by SuperMethodInvocationRewriter.";
assert !BindingUtil.isStatic(binding) : "Static invocations are rewritten by Functionizer.";
buffer.append("[super");
printMethodInvocationNameAndArgs(binding, node.getArguments());
buffer.append(']');
return false;
}
@Override
public boolean visit(SwitchCase node) {
if (node.isDefault()) {
buffer.append(" default:\n");
} else {
buffer.append(" case ");
Expression expr = node.getExpression();
boolean isEnumConstant = expr.getTypeBinding().isEnum();
if (isEnumConstant) {
String typeName = NameTable.getFullName(expr.getTypeBinding());
String bareTypeName = typeName.endsWith("Enum")
? typeName.substring(0, typeName.length() - 4) : typeName;
buffer.append(bareTypeName).append("_");
}
if (isEnumConstant && expr instanceof SimpleName) {
buffer.append(((SimpleName) expr).getIdentifier());
} else if (isEnumConstant && expr instanceof QualifiedName) {
buffer.append(((QualifiedName) expr).getName().getIdentifier());
} else {
expr.accept(this);
}
buffer.append(":\n");
}
return false;
}
@Override
public boolean visit(SwitchStatement node) {
Expression expr = node.getExpression();
ITypeBinding exprType = expr.getTypeBinding();
if (Types.isJavaStringType(exprType)) {
printStringSwitchStatement(node);
return false;
}
buffer.append("switch (");
if (exprType.isEnum()) {
buffer.append('[');
}
expr.accept(this);
if (exprType.isEnum()) {
buffer.append(" ordinal]");
}
buffer.append(") ");
buffer.append("{\n");
List<Statement> stmts = node.getStatements();
for (Statement stmt : stmts) {
stmt.accept(this);
}
if (!stmts.isEmpty() && stmts.get(stmts.size() - 1) instanceof SwitchCase) {
// Last switch case doesn't have an associated statement, so add
// an empty one.
buffer.append(";\n");
}
buffer.append("}\n");
return false;
}
private void printStringSwitchStatement(SwitchStatement node) {
buffer.append("{\n");
// Define an array of all the string constant case values.
List<String> caseValues = Lists.newArrayList();
List<Statement> stmts = node.getStatements();
for (Statement stmt : stmts) {
if (stmt instanceof SwitchCase) {
SwitchCase caseStmt = (SwitchCase) stmt;
if (!caseStmt.isDefault()) {
caseValues.add(getStringConstant(caseStmt.getExpression()));
}
}
}
buffer.append("NSArray *__caseValues = [NSArray arrayWithObjects:");
for (String value : caseValues) {
buffer.append("@\"" + UnicodeUtils.escapeStringLiteral(value) + "\", ");
}
buffer.append("nil];\n");
buffer.append("NSUInteger __index = [__caseValues indexOfObject:");
node.getExpression().accept(this);
buffer.append("];\n");
buffer.append("switch (__index) {\n");
for (Statement stmt : stmts) {
if (stmt instanceof SwitchCase) {
SwitchCase caseStmt = (SwitchCase) stmt;
if (caseStmt.isDefault()) {
stmt.accept(this);
} else {
int i = caseValues.indexOf(getStringConstant(caseStmt.getExpression()));
assert i >= 0;
buffer.append("case ");
buffer.append(i);
buffer.append(":\n");
}
} else {
stmt.accept(this);
}
}
buffer.append("}\n}\n");
}
private static String getStringConstant(Expression expr) {
Object constantValue = expr.getConstantValue();
assert constantValue != null && constantValue instanceof String;
return (String) constantValue;
}
@Override
public boolean visit(SynchronizedStatement node) {
buffer.append("@synchronized(");
node.getExpression().accept(this);
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(ThisExpression node) {
buffer.append("self");
return false;
}
@Override
public boolean visit(ThrowStatement node) {
buffer.append("@throw ");
node.getExpression().accept(this);
buffer.append(";\n");
return false;
}
@Override
public boolean visit(TryStatement node) {
List<VariableDeclarationExpression> resources = node.getResources();
boolean hasResources = !resources.isEmpty();
if (hasResources) {
buffer.append("{\n");
buffer.append("JavaLangThrowable *__mainException = nil;\n");
}
for (VariableDeclarationExpression var : resources) {
var.accept(this);
buffer.append(";\n");
}
buffer.append("@try ");
node.getBody().accept(this);
buffer.append(' ');
for (CatchClause cc : node.getCatchClauses()) {
if (cc.getException().getType() instanceof UnionType) {
printMultiCatch(cc, hasResources);
} else {
buffer.append("@catch (");
cc.getException().accept(this);
buffer.append(") {\n");
printMainExceptionStore(hasResources, cc);
printStatements(cc.getBody().getStatements());
buffer.append("}\n");
}
}
if (node.getFinally() != null || resources.size() > 0) {
buffer.append(" @finally {\n");
if (node.getFinally() != null) {
printStatements(node.getFinally().getStatements());
}
for (VariableDeclarationExpression var : resources) {
for (VariableDeclarationFragment frag : var.getFragments()) {
buffer.append("@try {\n[");
buffer.append(frag.getName().getFullyQualifiedName());
buffer.append(" close];\n}\n");
buffer.append("@catch (JavaLangThrowable *e) {\n");
buffer.append("if (__mainException) {\n");
buffer.append("[__mainException addSuppressedWithJavaLangThrowable:e];\n} else {\n");
buffer.append("__mainException = e;\n}\n");
buffer.append("}\n");
}
}
if (hasResources) {
buffer.append("if (__mainException) {\n@throw __mainException;\n}\n");
}
buffer.append("}\n");
}
if (hasResources) {
buffer.append("}\n");
}
return false;
}
private void printMainExceptionStore(boolean hasResources, CatchClause cc) {
if (hasResources) {
buffer.append("__mainException = ");
buffer.append(cc.getException().getName().getFullyQualifiedName());
buffer.append(";\n");
}
}
@Override
public boolean visit(TypeLiteral node) {
ITypeBinding type = node.getType().getTypeBinding();
if (type.isPrimitive()) {
buffer.append(String.format("[IOSClass %sClass]", type.getName()));
} else {
buffer.append(NameTable.getFullName(type));
buffer.append("_class_()");
}
return false;
}
@Override
public boolean visit(VariableDeclarationExpression node) {
String typeString = NameTable.getSpecificObjCType(node.getTypeBinding());
boolean needsAsterisk = typeString.endsWith("*");
buffer.append(typeString);
if (!needsAsterisk) {
buffer.append(' ');
}
for (Iterator<VariableDeclarationFragment> it = node.getFragments().iterator();
it.hasNext(); ) {
VariableDeclarationFragment f = it.next();
f.accept(this);
if (it.hasNext()) {
buffer.append(", ");
if (needsAsterisk) {
buffer.append('*');
}
}
}
return false;
}
@Override
public boolean visit(VariableDeclarationFragment node) {
node.getName().accept(this);
Expression initializer = node.getInitializer();
if (initializer != null) {
buffer.append(" = ");
initializer.accept(this);
}
return false;
}
@Override
public boolean visit(VariableDeclarationStatement node) {
List<VariableDeclarationFragment> vars = node.getFragments();
assert !vars.isEmpty();
IVariableBinding binding = vars.get(0).getVariableBinding();
if (binding.getType() instanceof IOSBlockTypeBinding) {
assert vars.size() == 1 : "TODO: cannot handle multiple fragments for block";
IOSBlockTypeBinding blockBinding = (IOSBlockTypeBinding) binding.getType();
buffer.append(blockBinding.getNamedDeclarationFirstPart());
VariableDeclarationFragment frag = vars.get(0);
frag.getName().accept(this);
buffer.append(blockBinding.getNamedDeclarationLastPart());
Expression initializer = frag.getInitializer();
if (initializer != null) {
buffer.append(" = ");
initializer.accept(this);
}
buffer.append(";\n");
return false;
} else {
String objcType = NameTable.getSpecificObjCType(binding);
String objcTypePointers = " ";
int idx = objcType.indexOf(" *");
if (idx != -1) {
// Split the type at the first pointer. The second part of the type is
// applied to each fragment. (eg. Foo *one, *two)
objcTypePointers = objcType.substring(idx);
objcType = objcType.substring(0, idx);
}
buffer.append(objcType);
for (Iterator<VariableDeclarationFragment> it = vars.iterator(); it.hasNext(); ) {
VariableDeclarationFragment f = it.next();
buffer.append(objcTypePointers);
f.accept(this);
if (it.hasNext()) {
buffer.append(",");
}
}
buffer.append(";\n");
return false;
}
}
@Override
public boolean visit(WhileStatement node) {
buffer.append("while (");
node.getExpression().accept(this);
buffer.append(") ");
node.getBody().accept(this);
return false;
}
@Override
public boolean visit(Initializer node) {
// All Initializer nodes should have been converted during initialization
// normalization.
throw new AssertionError("initializer node not converted");
}
// Returns a string where all characters that will interfer in
// a valid Objective-C string are quoted.
private static String makeQuotedString(String originalString) {
int location = 0;
StringBuffer buffer = new StringBuffer(originalString);
while ((location = buffer.indexOf("\\", location)) != -1) {
buffer.replace(location++, location++, "\\\\");
}
location = 0;
while ((location = buffer.indexOf("\"", location)) != -1) {
buffer.replace(location++, location++, "\\\"");
}
location = 0;
while ((location = buffer.indexOf("\n")) != -1) {
buffer.replace(location++, location++, "\\n");
}
return buffer.toString();
}
}
| #19, after found switch statment is a string, using another function(printStringSwitchStatement) to convert java continuing, just copy existing code here.
| translator/src/main/java/com/google/devtools/j2objc/gen/StatementGenerator.java | #19, after found switch statment is a string, using another function(printStringSwitchStatement) to convert java continuing, just copy existing code here. | <ide><path>ranslator/src/main/java/com/google/devtools/j2objc/gen/StatementGenerator.java
<ide> // an empty one.
<ide> buffer.append(";\n");
<ide> }
<add> if (!stmts.isEmpty() && stmts.get(stmts.size() - 1) instanceof SwitchCase) {
<add> // Last switch case doesn't have an associated statement, so add
<add> // an empty one.
<add> buffer.append(";\n");
<add> }
<ide> buffer.append("}\n");
<ide> return false;
<ide> } |
|
Java | apache-2.0 | c234a50ed2ef0179d0826ce456e06528a68f9569 | 0 | irccloud/android,irccloud/android,irccloud/android,irccloud/android,irccloud/android | /*
* Copyright (c) 2015 IRCCloud, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irccloud.android.activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.FileProvider;
import android.support.v4.os.BuildCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.irccloud.android.BackgroundTaskService;
import com.irccloud.android.ColorScheme;
import com.irccloud.android.IRCCloudApplication;
import com.irccloud.android.IRCCloudJSONObject;
import com.irccloud.android.NetworkConnection;
import com.irccloud.android.R;
import com.irccloud.android.data.collection.AvatarsList;
import com.irccloud.android.data.collection.EventsList;
import com.irccloud.android.data.model.Server;
import com.irccloud.android.data.collection.ServersList;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.multiwindow.SMultiWindow;
import com.samsung.android.sdk.multiwindow.SMultiWindowActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class BaseActivity extends AppCompatActivity implements NetworkConnection.IRCEventHandler, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
NetworkConnection conn;
private View dialogTextPrompt;
private GoogleApiClient mGoogleApiClient;
private boolean mResolvingError;
private static final int REQUEST_RESOLVE_ERROR = 1001;
private static final int REQUEST_SEND_FEEDBACK = 1002;
private static final String LOG_FILENAME = "log.txt";
private SMultiWindow mMultiWindow = null;
private SMultiWindowActivity mMultiWindowActivity = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean themeChanged = false;
String theme = ColorScheme.getUserTheme();
if(ColorScheme.getInstance().theme == null || !ColorScheme.getInstance().theme.equals(theme)) {
themeChanged = true;
}
setTheme(ColorScheme.getTheme(theme, true));
ColorScheme.getInstance().setThemeFromContext(this, theme);
if(themeChanged) {
EventsList.getInstance().clearCaches();
AvatarsList.getInstance().clear();
}
if (Build.VERSION.SDK_INT >= 21) {
Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
if(cloud != null) {
setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name), cloud, ColorScheme.getInstance().navBarColor));
}
getWindow().setStatusBarColor(ColorScheme.getInstance().statusBarColor);
getWindow().setNavigationBarColor(getResources().getColor(android.R.color.black));
}
if(ColorScheme.getInstance().windowBackgroundDrawable != 0)
getWindow().setBackgroundDrawableResource(ColorScheme.getInstance().windowBackgroundDrawable);
if(Build.VERSION.SDK_INT >= 23) {
if(theme.equals("dawn"))
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
else
getWindow().getDecorView().setSystemUiVisibility(getWindow().getDecorView().getSystemUiVisibility() &~ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.CREDENTIALS_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
conn = NetworkConnection.getInstance();
conn.addHandler(this);
if(ServersList.getInstance().count() == 0)
conn.getInstance().load();
try {
mMultiWindow = new SMultiWindow();
mMultiWindow.initialize(this);
mMultiWindowActivity = new SMultiWindowActivity(this);
} catch (Exception e) {
mMultiWindow = null;
mMultiWindowActivity = null;
} catch (Error e) {
mMultiWindow = null;
mMultiWindowActivity = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (conn != null) {
conn.removeHandler(this);
}
}
public boolean isMultiWindow() {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
return (mMultiWindowActivity != null && !mMultiWindowActivity.isNormalWindow());
else
return isInMultiWindowMode();
}
@Override
protected void onStart() {
super.onStart();
BackgroundTaskService.cancelBacklogSync(this);
if (!mResolvingError) {
mGoogleApiClient.connect();
}
NetworkConnection.getInstance().registerForConnectivity();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("background_sync", true)) {
BackgroundTaskService.scheduleBacklogSync(this);
}
NetworkConnection.getInstance().unregisterForConnectivity();
}
@Override
public void onConnected(Bundle connectionHint) {
}
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
if (GooglePlayServicesUtil.isUserRecoverableError(result.getErrorCode())) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, REQUEST_RESOLVE_ERROR).show();
mResolvingError = true;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
} else if(requestCode == REQUEST_SEND_FEEDBACK) {
if(getFileStreamPath(LOG_FILENAME).exists()) {
android.util.Log.d("IRCCloud", "Removing stale log file");
getFileStreamPath(LOG_FILENAME).delete();
}
}
}
public View getDialogTextPrompt() {
if (dialogTextPrompt == null)
dialogTextPrompt = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog_textprompt, null);
if (dialogTextPrompt.getParent() != null)
((ViewGroup) dialogTextPrompt.getParent()).removeView(dialogTextPrompt);
return dialogTextPrompt;
}
@Override
protected void onPause() {
super.onPause();
IRCCloudApplication.getInstance().onPause(this);
}
@Override
public void onResume() {
super.onResume();
IRCCloudApplication.getInstance().onResume(this);
File f = new File(getFilesDir(), LOG_FILENAME);
if(f.exists()) {
android.util.Log.d("IRCCloud", "Removing stale log file");
f.delete();
}
String session = getSharedPreferences("prefs", 0).getString("session_key", "");
if (session.length() > 0) {
if(conn.notifier) {
android.util.Log.d("IRCCloud", "Upgrading notifier websocket");
conn.upgrade();
}
} else {
Intent i = new Intent(this, LoginActivity.class);
i.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
}
@Override
protected void onPostResume() {
super.onPostResume();
if(conn != null){
if (conn.getState() == NetworkConnection.STATE_DISCONNECTED || conn.getState() == NetworkConnection.STATE_DISCONNECTING)
conn.connect();
}
}
public void onIRCEvent(int what, Object obj) {
String message = "";
final IRCCloudJSONObject o;
switch (what) {
case NetworkConnection.EVENT_BADCHANNELKEY:
o = (IRCCloudJSONObject) obj;
runOnUiThread(new Runnable() {
@Override
public void run() {
Server server = ServersList.getInstance().getServer(o.cid());
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
View view = getDialogTextPrompt();
TextView prompt = (TextView) view.findViewById(R.id.prompt);
final EditText keyinput = (EditText) view.findViewById(R.id.textInput);
keyinput.setText("");
keyinput.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
try {
if (keyinput.getText() != null)
conn.join(o.cid(), o.getString("chan"), keyinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
((AlertDialog) keyinput.getTag()).dismiss();
}
return true;
}
});
try {
prompt.setText("Password for " + o.getString("chan"));
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
builder.setTitle(server.getName() + " (" + server.getHostname() + ":" + (server.getPort()) + ")");
builder.setView(view);
builder.setPositiveButton("Join", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
conn.join(o.cid(), o.getString("chan"), keyinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
keyinput.setTag(dialog);
dialog.setOwnerActivity(BaseActivity.this);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
});
break;
case NetworkConnection.EVENT_INVALIDNICK:
o = (IRCCloudJSONObject) obj;
runOnUiThread(new Runnable() {
@Override
public void run() {
Server server = ServersList.getInstance().getServer(o.cid());
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
View view = getDialogTextPrompt();
TextView prompt = (TextView) view.findViewById(R.id.prompt);
final EditText nickinput = (EditText) view.findViewById(R.id.textInput);
nickinput.setText("");
nickinput.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
try {
conn.say(o.cid(), null, "/nick " + nickinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
((AlertDialog) nickinput.getTag()).dismiss();
}
return true;
}
});
try {
String message = o.getString("invalid_nick") + " is not a valid nickname, try again";
if (server.isupport != null && server.isupport.has("NICKLEN"))
message += "\n(" + server.isupport.get("NICKLEN").asText() + " chars)";
message += ".";
prompt.setText(message);
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
builder.setTitle(server.getName() + " (" + server.getHostname() + ":" + (server.getPort()) + ")");
builder.setView(view);
builder.setPositiveButton("Change Nickname", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
conn.say(o.cid(), null, "/nick " + nickinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
nickinput.setTag(dialog);
dialog.setOwnerActivity(BaseActivity.this);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
});
break;
case NetworkConnection.EVENT_ALERT:
try {
o = (IRCCloudJSONObject) obj;
String type = o.type();
if (type.equalsIgnoreCase("invite_only_chan"))
showAlert(o.cid(), "You need an invitation to join " + o.getString("chan"));
else if (type.equalsIgnoreCase("channel_full"))
showAlert(o.cid(), o.getString("chan") + " isn't allowing any more members to join.");
else if (type.equalsIgnoreCase("banned_from_channel"))
showAlert(o.cid(), "You've been banned from " + o.getString("chan"));
else if (type.equalsIgnoreCase("invalid_nickchange"))
showAlert(o.cid(), o.getString("ban_channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("no_messages_from_non_registered")) {
if (o.has("nick") && o.getString("nick").length() > 0)
showAlert(o.cid(), o.getString("nick") + ": " + o.getString("msg"));
else
showAlert(o.cid(), o.getString("msg"));
} else if (type.equalsIgnoreCase("not_registered")) {
String first = o.getString("first");
if (o.has("rest"))
first += " " + o.getString("rest");
showAlert(o.cid(), first + ": " + o.getString("msg"));
} else if (type.equalsIgnoreCase("too_many_channels"))
showAlert(o.cid(), "Couldn't join " + o.getString("chan") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("too_many_targets"))
showAlert(o.cid(), o.getString("description") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("no_such_server"))
showAlert(o.cid(), o.getString("server") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("unknown_command"))
showAlert(o.cid(), "Unknown command: " + o.getString("command"));
else if (type.equalsIgnoreCase("help_not_found"))
showAlert(o.cid(), o.getString("topic") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("accept_exists"))
showAlert(o.cid(), o.getString("nick") + " " + o.getString("msg"));
else if (type.equalsIgnoreCase("accept_not"))
showAlert(o.cid(), o.getString("nick") + " " + o.getString("msg"));
else if (type.equalsIgnoreCase("nick_collision"))
showAlert(o.cid(), o.getString("collision") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("nick_too_fast"))
showAlert(o.cid(), o.getString("nick") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("save_nick"))
showAlert(o.cid(), o.getString("nick") + ": " + o.getString("msg") + ": " + o.getString("new_nick"));
else if (type.equalsIgnoreCase("unknown_mode"))
showAlert(o.cid(), "Missing mode: " + o.getString("params"));
else if (type.equalsIgnoreCase("user_not_in_channel"))
showAlert(o.cid(), o.getString("nick") + " is not in " + o.getString("channel"));
else if (type.equalsIgnoreCase("need_more_params"))
showAlert(o.cid(), "Missing parameters for command: " + o.getString("command"));
else if (type.equalsIgnoreCase("chan_privs_needed"))
showAlert(o.cid(), o.getString("chan") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("not_on_channel"))
showAlert(o.cid(), o.getString("channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("ban_on_chan"))
showAlert(o.cid(), "You cannot change your nick to " + o.getString("proposed_nick") + " while banned on " + o.getString("channel"));
else if (type.equalsIgnoreCase("cannot_send_to_chan"))
showAlert(o.cid(), o.getString("channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("user_on_channel"))
showAlert(o.cid(), o.getString("nick") + " is already a member of " + o.getString("channel"));
else if (type.equalsIgnoreCase("no_nick_given"))
showAlert(o.cid(), "No nickname given");
else if (type.equalsIgnoreCase("nickname_in_use"))
showAlert(o.cid(), o.getString("nick") + " is already in use");
else if (type.equalsIgnoreCase("silence")) {
String mask = o.getString("usermask");
if (mask.startsWith("-"))
message = mask.substring(1) + " removed from silence list";
else if (mask.startsWith("+"))
message = mask.substring(1) + " added to silence list";
else
message = "Silence list change: " + mask;
showAlert(o.cid(), message);
} else if (type.equalsIgnoreCase("no_channel_topic"))
showAlert(o.cid(), o.getString("channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("time")) {
message = o.getString("time_string");
if (o.has("time_stamp") && o.getString("time_stamp").length() > 0)
message += " (" + o.getString("time_stamp") + ")";
message += " — " + o.getString("time_server");
showAlert(o.cid(), message);
} else
showAlert(o.cid(), o.getString("msg"));
} catch (Exception e1) {
NetworkConnection.printStackTraceToCrashlytics(e1);
}
break;
default:
break;
}
}
@Override
public void onIRCRequestSucceeded(int reqid, IRCCloudJSONObject object) {
}
@Override
public void onIRCRequestFailed(int reqid, IRCCloudJSONObject object) {
}
protected void showAlert(int cid, final String msg) {
final Server server = ServersList.getInstance().getServer(cid);
if (server != null)
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
builder.setTitle(server.getName() + " (" + server.getHostname() + ":" + (server.getPort()) + ")");
builder.setMessage(msg);
builder.setNegativeButton("Ok", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
dialog.dismiss();
} catch (IllegalArgumentException e) {
}
}
});
if(!BaseActivity.this.isFinishing()) {
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(BaseActivity.this);
dialog.show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_base, menu);
setMenuColorFilter(menu);
return super.onCreateOptionsMenu(menu);
}
public void setMenuColorFilter(final Menu menu) {
for(int i = 0; i < menu.size(); i++) {
MenuItem menuItem = menu.getItem(i);
Drawable d = menuItem.getIcon();
if(d != null) {
d.mutate();
d.setColorFilter(ColorScheme.getInstance().navBarSubheadingColor, PorterDuff.Mode.SRC_ATOP);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_logout:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
builder.setTitle("Logout");
builder.setMessage("Would you like to logout of IRCCloud?");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
conn.logout();
if(mGoogleApiClient.isConnected()) {
Auth.CredentialsApi.disableAutoSignIn(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
Intent i = new Intent(BaseActivity.this, LoginActivity.class);
i.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
} else {
Intent i = new Intent(BaseActivity.this, LoginActivity.class);
i.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
break;
case R.id.menu_settings:
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
break;
case R.id.menu_feedback:
try {
String bugReport = "Briefly describe the issue below:\n\n\n\n\n" +
"===========\n" +
"UID: " + NetworkConnection.getInstance().getUserInfo().id + "\n" +
"App version: " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName + " (" + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + ")\n" +
"Device: " + Build.MODEL + "\n" +
"Android version: " + Build.VERSION.RELEASE + "\n" +
"Firmware fingerprint: " + Build.FINGERPRINT + "\n";
File logsDir = new File(getFilesDir(),".Fabric/com.crashlytics.sdk.android.crashlytics-core/log-files/");
File log = null;
File output = null;
if(logsDir.exists()) {
long max = Long.MIN_VALUE;
for (File f : logsDir.listFiles()) {
if (f.lastModified() > max) {
max = f.lastModified();
log = f;
}
}
if (log != null) {
File f = new File(getFilesDir(), "logs");
f.mkdirs();
output = new File(f, LOG_FILENAME);
byte[] b = new byte[1];
FileOutputStream out = new FileOutputStream(output);
FileInputStream is = new FileInputStream(log);
is.skip(5);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
f.setReadable(true, false);
while (is.available() > 0 && is.read(b, 0, 1) > 0) {
if (b[0] == ' ') {
while (is.available() > 0 && is.read(b, 0, 1) > 0) {
out.write(b);
if (b[0] == '\n')
break;
}
}
}
is.close();
out.close();
}
}
Intent email = new Intent(Intent.ACTION_SEND);
email.setData(Uri.parse("mailto:"));
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"IRCCloud Team <[email protected]>"});
email.putExtra(Intent.EXTRA_TEXT, bugReport);
email.putExtra(Intent.EXTRA_SUBJECT, "IRCCloud for Android");
if(log != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + output.getAbsolutePath()));
else
email.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", output));
}
startActivityForResult(Intent.createChooser(email, "Send Feedback:"), 0);
} catch (Exception e) {
Toast.makeText(this, "Unable to generate email report: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Crashlytics.logException(e);
NetworkConnection.printStackTraceToCrashlytics(e);
}
break;
}
return super.onOptionsItemSelected(item);
}
}
| src/com/irccloud/android/activity/BaseActivity.java | /*
* Copyright (c) 2015 IRCCloud, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irccloud.android.activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.FileProvider;
import android.support.v4.os.BuildCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.irccloud.android.BackgroundTaskService;
import com.irccloud.android.ColorScheme;
import com.irccloud.android.IRCCloudApplication;
import com.irccloud.android.IRCCloudJSONObject;
import com.irccloud.android.NetworkConnection;
import com.irccloud.android.R;
import com.irccloud.android.data.collection.AvatarsList;
import com.irccloud.android.data.collection.EventsList;
import com.irccloud.android.data.model.Server;
import com.irccloud.android.data.collection.ServersList;
import com.samsung.android.sdk.SsdkUnsupportedException;
import com.samsung.android.sdk.multiwindow.SMultiWindow;
import com.samsung.android.sdk.multiwindow.SMultiWindowActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class BaseActivity extends AppCompatActivity implements NetworkConnection.IRCEventHandler, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
NetworkConnection conn;
private View dialogTextPrompt;
private GoogleApiClient mGoogleApiClient;
private boolean mResolvingError;
private static final int REQUEST_RESOLVE_ERROR = 1001;
private static final int REQUEST_SEND_FEEDBACK = 1002;
private static final String LOG_FILENAME = "logs/log.txt";
private SMultiWindow mMultiWindow = null;
private SMultiWindowActivity mMultiWindowActivity = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean themeChanged = false;
String theme = ColorScheme.getUserTheme();
if(ColorScheme.getInstance().theme == null || !ColorScheme.getInstance().theme.equals(theme)) {
themeChanged = true;
}
setTheme(ColorScheme.getTheme(theme, true));
ColorScheme.getInstance().setThemeFromContext(this, theme);
if(themeChanged) {
EventsList.getInstance().clearCaches();
AvatarsList.getInstance().clear();
}
if (Build.VERSION.SDK_INT >= 21) {
Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
if(cloud != null) {
setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name), cloud, ColorScheme.getInstance().navBarColor));
}
getWindow().setStatusBarColor(ColorScheme.getInstance().statusBarColor);
getWindow().setNavigationBarColor(getResources().getColor(android.R.color.black));
}
if(ColorScheme.getInstance().windowBackgroundDrawable != 0)
getWindow().setBackgroundDrawableResource(ColorScheme.getInstance().windowBackgroundDrawable);
if(Build.VERSION.SDK_INT >= 23) {
if(theme.equals("dawn"))
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
else
getWindow().getDecorView().setSystemUiVisibility(getWindow().getDecorView().getSystemUiVisibility() &~ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.CREDENTIALS_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
conn = NetworkConnection.getInstance();
conn.addHandler(this);
if(ServersList.getInstance().count() == 0)
conn.getInstance().load();
try {
mMultiWindow = new SMultiWindow();
mMultiWindow.initialize(this);
mMultiWindowActivity = new SMultiWindowActivity(this);
} catch (Exception e) {
mMultiWindow = null;
mMultiWindowActivity = null;
} catch (Error e) {
mMultiWindow = null;
mMultiWindowActivity = null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (conn != null) {
conn.removeHandler(this);
}
}
public boolean isMultiWindow() {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
return (mMultiWindowActivity != null && !mMultiWindowActivity.isNormalWindow());
else
return isInMultiWindowMode();
}
@Override
protected void onStart() {
super.onStart();
BackgroundTaskService.cancelBacklogSync(this);
if (!mResolvingError) {
mGoogleApiClient.connect();
}
NetworkConnection.getInstance().registerForConnectivity();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("background_sync", true)) {
BackgroundTaskService.scheduleBacklogSync(this);
}
NetworkConnection.getInstance().unregisterForConnectivity();
}
@Override
public void onConnected(Bundle connectionHint) {
}
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
if (GooglePlayServicesUtil.isUserRecoverableError(result.getErrorCode())) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, REQUEST_RESOLVE_ERROR).show();
mResolvingError = true;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
} else if(requestCode == REQUEST_SEND_FEEDBACK) {
if(getFileStreamPath(LOG_FILENAME).exists()) {
android.util.Log.d("IRCCloud", "Removing stale log file");
getFileStreamPath(LOG_FILENAME).delete();
}
}
}
public View getDialogTextPrompt() {
if (dialogTextPrompt == null)
dialogTextPrompt = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dialog_textprompt, null);
if (dialogTextPrompt.getParent() != null)
((ViewGroup) dialogTextPrompt.getParent()).removeView(dialogTextPrompt);
return dialogTextPrompt;
}
@Override
protected void onPause() {
super.onPause();
IRCCloudApplication.getInstance().onPause(this);
}
@Override
public void onResume() {
super.onResume();
IRCCloudApplication.getInstance().onResume(this);
File f = new File(getFilesDir(), LOG_FILENAME);
if(f.exists()) {
android.util.Log.d("IRCCloud", "Removing stale log file");
f.delete();
}
String session = getSharedPreferences("prefs", 0).getString("session_key", "");
if (session.length() > 0) {
if(conn.notifier) {
android.util.Log.d("IRCCloud", "Upgrading notifier websocket");
conn.upgrade();
}
} else {
Intent i = new Intent(this, LoginActivity.class);
i.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
}
@Override
protected void onPostResume() {
super.onPostResume();
if(conn != null){
if (conn.getState() == NetworkConnection.STATE_DISCONNECTED || conn.getState() == NetworkConnection.STATE_DISCONNECTING)
conn.connect();
}
}
public void onIRCEvent(int what, Object obj) {
String message = "";
final IRCCloudJSONObject o;
switch (what) {
case NetworkConnection.EVENT_BADCHANNELKEY:
o = (IRCCloudJSONObject) obj;
runOnUiThread(new Runnable() {
@Override
public void run() {
Server server = ServersList.getInstance().getServer(o.cid());
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
View view = getDialogTextPrompt();
TextView prompt = (TextView) view.findViewById(R.id.prompt);
final EditText keyinput = (EditText) view.findViewById(R.id.textInput);
keyinput.setText("");
keyinput.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
try {
if (keyinput.getText() != null)
conn.join(o.cid(), o.getString("chan"), keyinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
((AlertDialog) keyinput.getTag()).dismiss();
}
return true;
}
});
try {
prompt.setText("Password for " + o.getString("chan"));
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
builder.setTitle(server.getName() + " (" + server.getHostname() + ":" + (server.getPort()) + ")");
builder.setView(view);
builder.setPositiveButton("Join", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
conn.join(o.cid(), o.getString("chan"), keyinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
keyinput.setTag(dialog);
dialog.setOwnerActivity(BaseActivity.this);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
});
break;
case NetworkConnection.EVENT_INVALIDNICK:
o = (IRCCloudJSONObject) obj;
runOnUiThread(new Runnable() {
@Override
public void run() {
Server server = ServersList.getInstance().getServer(o.cid());
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
View view = getDialogTextPrompt();
TextView prompt = (TextView) view.findViewById(R.id.prompt);
final EditText nickinput = (EditText) view.findViewById(R.id.textInput);
nickinput.setText("");
nickinput.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) {
try {
conn.say(o.cid(), null, "/nick " + nickinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
((AlertDialog) nickinput.getTag()).dismiss();
}
return true;
}
});
try {
String message = o.getString("invalid_nick") + " is not a valid nickname, try again";
if (server.isupport != null && server.isupport.has("NICKLEN"))
message += "\n(" + server.isupport.get("NICKLEN").asText() + " chars)";
message += ".";
prompt.setText(message);
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
builder.setTitle(server.getName() + " (" + server.getHostname() + ":" + (server.getPort()) + ")");
builder.setView(view);
builder.setPositiveButton("Change Nickname", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
conn.say(o.cid(), null, "/nick " + nickinput.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
NetworkConnection.printStackTraceToCrashlytics(e);
}
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
nickinput.setTag(dialog);
dialog.setOwnerActivity(BaseActivity.this);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
}
});
break;
case NetworkConnection.EVENT_ALERT:
try {
o = (IRCCloudJSONObject) obj;
String type = o.type();
if (type.equalsIgnoreCase("invite_only_chan"))
showAlert(o.cid(), "You need an invitation to join " + o.getString("chan"));
else if (type.equalsIgnoreCase("channel_full"))
showAlert(o.cid(), o.getString("chan") + " isn't allowing any more members to join.");
else if (type.equalsIgnoreCase("banned_from_channel"))
showAlert(o.cid(), "You've been banned from " + o.getString("chan"));
else if (type.equalsIgnoreCase("invalid_nickchange"))
showAlert(o.cid(), o.getString("ban_channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("no_messages_from_non_registered")) {
if (o.has("nick") && o.getString("nick").length() > 0)
showAlert(o.cid(), o.getString("nick") + ": " + o.getString("msg"));
else
showAlert(o.cid(), o.getString("msg"));
} else if (type.equalsIgnoreCase("not_registered")) {
String first = o.getString("first");
if (o.has("rest"))
first += " " + o.getString("rest");
showAlert(o.cid(), first + ": " + o.getString("msg"));
} else if (type.equalsIgnoreCase("too_many_channels"))
showAlert(o.cid(), "Couldn't join " + o.getString("chan") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("too_many_targets"))
showAlert(o.cid(), o.getString("description") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("no_such_server"))
showAlert(o.cid(), o.getString("server") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("unknown_command"))
showAlert(o.cid(), "Unknown command: " + o.getString("command"));
else if (type.equalsIgnoreCase("help_not_found"))
showAlert(o.cid(), o.getString("topic") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("accept_exists"))
showAlert(o.cid(), o.getString("nick") + " " + o.getString("msg"));
else if (type.equalsIgnoreCase("accept_not"))
showAlert(o.cid(), o.getString("nick") + " " + o.getString("msg"));
else if (type.equalsIgnoreCase("nick_collision"))
showAlert(o.cid(), o.getString("collision") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("nick_too_fast"))
showAlert(o.cid(), o.getString("nick") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("save_nick"))
showAlert(o.cid(), o.getString("nick") + ": " + o.getString("msg") + ": " + o.getString("new_nick"));
else if (type.equalsIgnoreCase("unknown_mode"))
showAlert(o.cid(), "Missing mode: " + o.getString("params"));
else if (type.equalsIgnoreCase("user_not_in_channel"))
showAlert(o.cid(), o.getString("nick") + " is not in " + o.getString("channel"));
else if (type.equalsIgnoreCase("need_more_params"))
showAlert(o.cid(), "Missing parameters for command: " + o.getString("command"));
else if (type.equalsIgnoreCase("chan_privs_needed"))
showAlert(o.cid(), o.getString("chan") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("not_on_channel"))
showAlert(o.cid(), o.getString("channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("ban_on_chan"))
showAlert(o.cid(), "You cannot change your nick to " + o.getString("proposed_nick") + " while banned on " + o.getString("channel"));
else if (type.equalsIgnoreCase("cannot_send_to_chan"))
showAlert(o.cid(), o.getString("channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("user_on_channel"))
showAlert(o.cid(), o.getString("nick") + " is already a member of " + o.getString("channel"));
else if (type.equalsIgnoreCase("no_nick_given"))
showAlert(o.cid(), "No nickname given");
else if (type.equalsIgnoreCase("nickname_in_use"))
showAlert(o.cid(), o.getString("nick") + " is already in use");
else if (type.equalsIgnoreCase("silence")) {
String mask = o.getString("usermask");
if (mask.startsWith("-"))
message = mask.substring(1) + " removed from silence list";
else if (mask.startsWith("+"))
message = mask.substring(1) + " added to silence list";
else
message = "Silence list change: " + mask;
showAlert(o.cid(), message);
} else if (type.equalsIgnoreCase("no_channel_topic"))
showAlert(o.cid(), o.getString("channel") + ": " + o.getString("msg"));
else if (type.equalsIgnoreCase("time")) {
message = o.getString("time_string");
if (o.has("time_stamp") && o.getString("time_stamp").length() > 0)
message += " (" + o.getString("time_stamp") + ")";
message += " — " + o.getString("time_server");
showAlert(o.cid(), message);
} else
showAlert(o.cid(), o.getString("msg"));
} catch (Exception e1) {
NetworkConnection.printStackTraceToCrashlytics(e1);
}
break;
default:
break;
}
}
@Override
public void onIRCRequestSucceeded(int reqid, IRCCloudJSONObject object) {
}
@Override
public void onIRCRequestFailed(int reqid, IRCCloudJSONObject object) {
}
protected void showAlert(int cid, final String msg) {
final Server server = ServersList.getInstance().getServer(cid);
if (server != null)
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
builder.setTitle(server.getName() + " (" + server.getHostname() + ":" + (server.getPort()) + ")");
builder.setMessage(msg);
builder.setNegativeButton("Ok", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
dialog.dismiss();
} catch (IllegalArgumentException e) {
}
}
});
if(!BaseActivity.this.isFinishing()) {
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(BaseActivity.this);
dialog.show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_base, menu);
setMenuColorFilter(menu);
return super.onCreateOptionsMenu(menu);
}
public void setMenuColorFilter(final Menu menu) {
for(int i = 0; i < menu.size(); i++) {
MenuItem menuItem = menu.getItem(i);
Drawable d = menuItem.getIcon();
if(d != null) {
d.mutate();
d.setColorFilter(ColorScheme.getInstance().navBarSubheadingColor, PorterDuff.Mode.SRC_ATOP);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_logout:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB);
builder.setTitle("Logout");
builder.setMessage("Would you like to logout of IRCCloud?");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
conn.logout();
if(mGoogleApiClient.isConnected()) {
Auth.CredentialsApi.disableAutoSignIn(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
Intent i = new Intent(BaseActivity.this, LoginActivity.class);
i.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
});
} else {
Intent i = new Intent(BaseActivity.this, LoginActivity.class);
i.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
}
});
AlertDialog dialog = builder.create();
dialog.setOwnerActivity(this);
dialog.show();
break;
case R.id.menu_settings:
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
break;
case R.id.menu_feedback:
try {
String bugReport = "Briefly describe the issue below:\n\n\n\n\n" +
"===========\n" +
"UID: " + NetworkConnection.getInstance().getUserInfo().id + "\n" +
"App version: " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName + " (" + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + ")\n" +
"Device: " + Build.MODEL + "\n" +
"Android version: " + Build.VERSION.RELEASE + "\n" +
"Firmware fingerprint: " + Build.FINGERPRINT + "\n";
File logsDir = new File(getFilesDir(),".Fabric/com.crashlytics.sdk.android.crashlytics-core/log-files/");
File log = null;
File output = null;
if(logsDir.exists()) {
long max = Long.MIN_VALUE;
for (File f : logsDir.listFiles()) {
if (f.lastModified() > max) {
max = f.lastModified();
log = f;
}
}
if (log != null) {
File f = new File(getFilesDir(), "logs");
f.mkdirs();
output = new File(getFilesDir(), LOG_FILENAME);
byte[] b = new byte[1];
FileOutputStream out = new FileOutputStream(output);
FileInputStream is = new FileInputStream(log);
is.skip(5);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
f.setReadable(true, false);
while (is.available() > 0 && is.read(b, 0, 1) > 0) {
if (b[0] == ' ') {
while (is.available() > 0 && is.read(b, 0, 1) > 0) {
out.write(b);
if (b[0] == '\n')
break;
}
}
}
is.close();
out.close();
}
}
Intent email = new Intent(Intent.ACTION_SEND);
email.setData(Uri.parse("mailto:"));
email.setType("message/rfc822");
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"IRCCloud Team <[email protected]>"});
email.putExtra(Intent.EXTRA_TEXT, bugReport);
email.putExtra(Intent.EXTRA_SUBJECT, "IRCCloud for Android");
if(log != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + getFileStreamPath(LOG_FILENAME).getAbsolutePath()));
else
email.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", output));
}
startActivityForResult(Intent.createChooser(email, "Send Feedback:"), 0);
} catch (Exception e) {
Toast.makeText(this, "Unable to generate email report: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Crashlytics.logException(e);
NetworkConnection.printStackTraceToCrashlytics(e);
}
break;
}
return super.onOptionsItemSelected(item);
}
}
| Fix 'Send Feedback' on older versions of Android
| src/com/irccloud/android/activity/BaseActivity.java | Fix 'Send Feedback' on older versions of Android | <ide><path>rc/com/irccloud/android/activity/BaseActivity.java
<ide> private boolean mResolvingError;
<ide> private static final int REQUEST_RESOLVE_ERROR = 1001;
<ide> private static final int REQUEST_SEND_FEEDBACK = 1002;
<del> private static final String LOG_FILENAME = "logs/log.txt";
<add> private static final String LOG_FILENAME = "log.txt";
<ide>
<ide> private SMultiWindow mMultiWindow = null;
<ide> private SMultiWindowActivity mMultiWindowActivity = null;
<ide> if (log != null) {
<ide> File f = new File(getFilesDir(), "logs");
<ide> f.mkdirs();
<del> output = new File(getFilesDir(), LOG_FILENAME);
<add> output = new File(f, LOG_FILENAME);
<ide> byte[] b = new byte[1];
<ide>
<ide> FileOutputStream out = new FileOutputStream(output);
<ide> email.putExtra(Intent.EXTRA_SUBJECT, "IRCCloud for Android");
<ide> if(log != null) {
<ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
<del> email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + getFileStreamPath(LOG_FILENAME).getAbsolutePath()));
<add> email.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + output.getAbsolutePath()));
<ide> else
<ide> email.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", output));
<ide> } |
|
Java | apache-2.0 | 37f569ec5f0a1d282ed4ddf55a7adb3fdf525d24 | 0 | ST-DDT/CrazyCore | package de.st_ddt.crazyutil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/**
* This class is based on an example from: <br>
* <a href=https://github.com/h31ix/ServerModsAPI-Example/blob/master/Update.java> ServerModsAPI-Example / Update.java by h31ix</a>
*/
public class UpdateChecker
{
// An optional API key to use, will be null if not submitted
private static String apiKey;
// Keys for extracting file information from JSON response
private static final String API_NAME_VALUE = "name";
private static final String API_LINK_VALUE = "downloadUrl";
private static final String API_RELEASE_TYPE_VALUE = "releaseType";
// private static final String API_FILE_NAME_VALUE = "fileName";
private static final String API_GAME_VERSION_VALUE = "gameVersion";
// Static information for querying the API
private static final String API_QUERY = "/servermods/files?projectIds=";
private static final String API_HOST = "https://api.curseforge.com";
// Project
private final String projectName;
private final String projectVersion;
private final int projectID;
// Latest
private String latestTitle;
private String latestLink;
private String latestType;
// private String latestFileName;
private String latestVersion;
private String latestGameVersion;
// Update
private boolean hasUpdate;
private boolean queried = false;
/**
* Check for updates
*
* @param projectID
* The BukkitDev Project ID, found in the "Facts" panel on the right-side of your project page.
*/
public UpdateChecker(final String projectName, final String projectVersion, final int projectID)
{
super();
this.projectName = projectName;
this.projectVersion = projectVersion;
this.projectID = projectID;
}
/**
* Query the API to find the latest approved file's details.
*/
public boolean query()
{
queried = true;
URL url = null;
try
{
// Create the URL to query using the project's ID
url = new URL(API_HOST + API_QUERY + projectID);
}
catch (final MalformedURLException e)
{
// There was an error creating the URL
e.printStackTrace();
return hasUpdate;
}
try
{
// Open a connection and query the project
final URLConnection conn = url.openConnection();
if (apiKey != null)
// Add the API key to the request if present
conn.addRequestProperty("X-API-Key", apiKey);
// Add the user-agent to identify the program
conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)");
// Read the response of the query
// The response will be in a JSON format, so only reading one line is necessary.
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
// Parse the array of files from the query's response
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.size() > 0)
{
// Get the newest file's details
final JSONObject latest = (JSONObject) array.get(array.size() - 1);
// Get the version's title
latestTitle = (String) latest.get(API_NAME_VALUE);
// Get the version's link
latestLink = (String) latest.get(API_LINK_VALUE);
// Get the version's release type
latestType = (String) latest.get(API_RELEASE_TYPE_VALUE);
// Get the version's file name
// latestFileName = (String) latest.get(API_FILE_NAME_VALUE);
// Get the version's game version
latestGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);
latestVersion = latestTitle.substring(projectName.length() + 2);
hasUpdate = VersionComparator.compareVersions(projectVersion, latestVersion) == -1;
}
}
catch (final Exception e)
{
// There was an error reading the query
// e.printStackTrace();
}
return hasUpdate;
}
/**
* @return The Server dependend API-Key, found at <a href=>https://dev.bukkit.org/home/servermods-apikey/</a>
*/
public final static String getApiKey()
{
return apiKey;
}
/**
* @param apiKey
* The Server dependend API-Key, found at <a href=>https://dev.bukkit.org/home/servermods-apikey/</a>
*/
public final static void setApiKey(final String apiKey)
{
UpdateChecker.apiKey = apiKey;
}
/**
* @return The title of the latest version.
*/
public String getLatestTitle()
{
return latestTitle;
}
/**
* @return The link where you can download the latest version.
*/
public final String getLatestLink()
{
return latestLink;
}
/**
* @return The type of the update. Ex: Release
*/
public final String getLatestType()
{
return latestType;
}
/**
* @return The latest version available.
*/
public String getLatestVersion()
{
return latestVersion;
}
/**
* @return The game version this update is designed for.
*/
public final String getLatestGameVersion()
{
return latestGameVersion;
}
/**
* @return True, if an update is available.
*/
public final boolean hasUpdate()
{
return hasUpdate;
}
/**
* @return True, if it has already checked for updates once, False otherwise.
*/
public final boolean wasQueried()
{
return queried;
}
}
| src/de/st_ddt/crazyutil/UpdateChecker.java | package de.st_ddt.crazyutil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/**
* This class is based on an example from: <br>
* <a href=https://github.com/h31ix/ServerModsAPI-Example/blob/master/Update.java> ServerModsAPI-Example / Update.java by h31ix</a>
*/
public class UpdateChecker
{
// An optional API key to use, will be null if not submitted
private static String apiKey;
// Keys for extracting file information from JSON response
private static final String API_NAME_VALUE = "name";
private static final String API_LINK_VALUE = "downloadUrl";
private static final String API_RELEASE_TYPE_VALUE = "releaseType";
// private static final String API_FILE_NAME_VALUE = "fileName";
private static final String API_GAME_VERSION_VALUE = "gameVersion";
// Static information for querying the API
private static final String API_QUERY = "/servermods/files?projectIds=";
private static final String API_HOST = "https://api.curseforge.com";
// Project
private final String projectName;
private final String projectVersion;
private final int projectID;
// Latest
private String latestTitle;
private String latestLink;
private String latestType;
// private String latestFileName;
private String latestVersion;
private String latestGameVersion;
// Update
private boolean hasUpdate;
private boolean queried = false;
/**
* Check for updates
*
* @param projectID
* The BukkitDev Project ID, found in the "Facts" panel on the right-side of your project page.
*/
public UpdateChecker(final String projectName, final String projectVersion, final int projectID)
{
super();
this.projectName = projectName;
this.projectVersion = projectVersion;
this.projectID = projectID;
}
/**
* Query the API to find the latest approved file's details.
*/
public boolean query()
{
queried = true;
URL url = null;
try
{
// Create the URL to query using the project's ID
url = new URL(API_HOST + API_QUERY + projectID);
}
catch (final MalformedURLException e)
{
// There was an error creating the URL
e.printStackTrace();
return hasUpdate;
}
try
{
// Open a connection and query the project
final URLConnection conn = url.openConnection();
if (apiKey != null)
// Add the API key to the request if present
conn.addRequestProperty("X-API-Key", apiKey);
// Add the user-agent to identify the program
conn.addRequestProperty("User-Agent", "ServerModsAPI-Example (by Gravity)");
// Read the response of the query
// The response will be in a JSON format, so only reading one line is necessary.
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
// Parse the array of files from the query's response
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.size() > 0)
{
// Get the newest file's details
final JSONObject latest = (JSONObject) array.get(array.size() - 1);
// Get the version's title
latestTitle = (String) latest.get(API_NAME_VALUE);
// Get the version's link
latestLink = (String) latest.get(API_LINK_VALUE);
// Get the version's release type
latestType = (String) latest.get(API_RELEASE_TYPE_VALUE);
// Get the version's file name
// latestFileName = (String) latest.get(API_FILE_NAME_VALUE);
// Get the version's game version
latestGameVersion = (String) latest.get(API_GAME_VERSION_VALUE);
latestVersion = latestTitle.substring(projectName.length() + 2);
hasUpdate = VersionComparator.compareVersions(projectVersion, latestVersion) == -1;
}
}
catch (final IOException e)
{
// There was an error reading the query
e.printStackTrace();
}
return hasUpdate;
}
/**
* @return The Server dependend API-Key, found at <a href=>https://dev.bukkit.org/home/servermods-apikey/</a>
*/
public final static String getApiKey()
{
return apiKey;
}
/**
* @param apiKey
* The Server dependend API-Key, found at <a href=>https://dev.bukkit.org/home/servermods-apikey/</a>
*/
public final static void setApiKey(final String apiKey)
{
UpdateChecker.apiKey = apiKey;
}
/**
* @return The title of the latest version.
*/
public String getLatestTitle()
{
return latestTitle;
}
/**
* @return The link where you can download the latest version.
*/
public final String getLatestLink()
{
return latestLink;
}
/**
* @return The type of the update. Ex: Release
*/
public final String getLatestType()
{
return latestType;
}
/**
* @return The latest version available.
*/
public String getLatestVersion()
{
return latestVersion;
}
/**
* @return The game version this update is designed for.
*/
public final String getLatestGameVersion()
{
return latestGameVersion;
}
/**
* @return True, if an update is available.
*/
public final boolean hasUpdate()
{
return hasUpdate;
}
/**
* @return True, if it has already checked for updates once, False otherwise.
*/
public final boolean wasQueried()
{
return queried;
}
}
| Fixed Issues with UpdateChecker if api is offline. | src/de/st_ddt/crazyutil/UpdateChecker.java | Fixed Issues with UpdateChecker if api is offline. | <ide><path>rc/de/st_ddt/crazyutil/UpdateChecker.java
<ide> package de.st_ddt.crazyutil;
<ide>
<ide> import java.io.BufferedReader;
<del>import java.io.IOException;
<ide> import java.io.InputStreamReader;
<ide> import java.net.MalformedURLException;
<ide> import java.net.URL;
<ide> hasUpdate = VersionComparator.compareVersions(projectVersion, latestVersion) == -1;
<ide> }
<ide> }
<del> catch (final IOException e)
<add> catch (final Exception e)
<ide> {
<ide> // There was an error reading the query
<del> e.printStackTrace();
<add> // e.printStackTrace();
<ide> }
<ide> return hasUpdate;
<ide> } |
|
JavaScript | unlicense | acd645928a5f73e34db0ade525c39a654001cebb | 0 | naconner/lamassu-server,lamassu/lamassu-server,naconner/lamassu-server,naconner/lamassu-server,lamassu/lamassu-server,lamassu/lamassu-server | const _ = require('lodash/fp')
const db = require('./db')
const configManager = require('./config-manager')
const logger = require('./logger')
const schema = require('../lamassu-schema.json')
const REMOVED_FIELDS = ['crossRefVerificationActive', 'crossRefVerificationThreshold']
function allScopes (cryptoScopes, machineScopes) {
const scopes = []
cryptoScopes.forEach(c => {
machineScopes.forEach(m => scopes.push([c, m]))
})
return scopes
}
function allCryptoScopes (cryptos, cryptoScope) {
const cryptoScopes = []
if (cryptoScope === 'global' || cryptoScope === 'both') cryptoScopes.push('global')
if (cryptoScope === 'specific' || cryptoScope === 'both') cryptos.forEach(r => cryptoScopes.push(r))
return cryptoScopes
}
function allMachineScopes (machineList, machineScope) {
const machineScopes = []
if (machineScope === 'global' || machineScope === 'both') machineScopes.push('global')
if (machineScope === 'specific' || machineScope === 'both') machineList.forEach(r => machineScopes.push(r))
return machineScopes
}
function satisfiesRequire (config, cryptos, machineList, field, anyFields, allFields) {
const fieldCode = field.code
const scopes = allScopes(
allCryptoScopes(cryptos, field.cryptoScope),
allMachineScopes(machineList, field.machineScope)
)
return scopes.every(scope => {
const isAnyEnabled = () => _.some(refField => {
return isScopeEnabled(config, cryptos, machineList, refField, scope)
}, anyFields)
const areAllEnabled = () => _.every(refField => {
return isScopeEnabled(config, cryptos, machineList, refField, scope)
}, allFields)
const isBlank = _.isNil(configManager.scopedValue(scope[0], scope[1], fieldCode, config))
const isRequired = (_.isEmpty(anyFields) || isAnyEnabled()) &&
(_.isEmpty(allFields) || areAllEnabled())
const hasDefault = !_.isNil(_.get('default', field))
const isValid = !isRequired || !isBlank || hasDefault
return isValid
})
}
function isScopeEnabled (config, cryptos, machineList, refField, scope) {
const [cryptoScope, machineScope] = scope
const candidateCryptoScopes = cryptoScope === 'global'
? allCryptoScopes(cryptos, refField.cryptoScope)
: [cryptoScope]
const candidateMachineScopes = machineScope === 'global'
? allMachineScopes(machineList, refField.machineScope)
: [ machineScope ]
const allRefCandidateScopes = allScopes(candidateCryptoScopes, candidateMachineScopes)
const getFallbackValue = scope => configManager.scopedValue(scope[0], scope[1], refField.code, config)
const values = allRefCandidateScopes.map(getFallbackValue)
return values.some(r => r)
}
function getCryptos (config, machineList) {
const scopes = allScopes(['global'], allMachineScopes(machineList, 'both'))
const scoped = scope => configManager.scopedValue(scope[0], scope[1], 'cryptoCurrencies', config)
return scopes.reduce((acc, scope) => _.union(acc, scoped(scope)), [])
}
function getGroup (fieldCode) {
return _.find(group => _.includes(fieldCode, group.fields), schema.groups)
}
function getField (fieldCode) {
const group = getGroup(fieldCode)
return getGroupField(group, fieldCode)
}
function getGroupField (group, fieldCode) {
const field = _.find(_.matchesProperty('code', fieldCode), schema.fields)
return _.merge(_.pick(['cryptoScope', 'machineScope'], group), field)
}
// Note: We can't use machine-loader because it relies on settings-loader,
// which relies on this
function getMachines () {
return db.any('select device_id from devices')
}
function fetchMachines () {
return getMachines()
.then(machineList => machineList.map(r => r.device_id))
}
function validateFieldParameter (value, validator) {
switch (validator.code) {
case 'required':
return true // We don't validate this here
case 'min':
return value >= validator.min
case 'max':
return value <= validator.max
default:
throw new Error('Unknown validation type: ' + validator.code)
}
}
function ensureConstraints (config) {
const pickField = fieldCode => schema.fields.find(r => r.code === fieldCode)
return Promise.resolve()
.then(() => {
config.every(fieldInstance => {
const fieldCode = fieldInstance.fieldLocator.code
if (_.includes(fieldCode, REMOVED_FIELDS)) return
const field = pickField(fieldCode)
if (!field) {
logger.warn('No such field: %s, %j', fieldCode, fieldInstance.fieldLocator.fieldScope)
return
}
const fieldValue = fieldInstance.fieldValue
const isValid = field.fieldValidation
.every(validator => validateFieldParameter(fieldValue.value, validator))
if (isValid) return true
throw new Error('Invalid config value')
})
})
}
function validateRequires (config) {
return fetchMachines()
.then(machineList => {
const cryptos = getCryptos(config, machineList)
return schema.groups.filter(group => {
return group.fields.some(fieldCode => {
const field = getGroupField(group, fieldCode)
if (!field.fieldValidation.find(r => r.code === 'required')) return false
const refFieldsAny = _.map(_.partial(getField, group), field.enabledIfAny)
const refFieldsAll = _.map(_.partial(getField, group), field.enabledIfAll)
const isInvalid = !satisfiesRequire(config, cryptos, machineList, field, refFieldsAny, refFieldsAll)
return isInvalid
})
})
})
.then(arr => arr.map(r => r.code))
}
function validate (config) {
return Promise.resolve()
.then(() => ensureConstraints(config))
.then(() => validateRequires(config))
.then(arr => {
if (arr.length === 0) return config
throw new Error('Invalid configuration:' + arr)
})
}
module.exports = {validate, ensureConstraints, validateRequires}
| lib/config-validate.js | const _ = require('lodash/fp')
const db = require('./db')
const configManager = require('./config-manager')
const logger = require('./logger')
const schema = require('../lamassu-schema.json')
function allScopes (cryptoScopes, machineScopes) {
const scopes = []
cryptoScopes.forEach(c => {
machineScopes.forEach(m => scopes.push([c, m]))
})
return scopes
}
function allCryptoScopes (cryptos, cryptoScope) {
const cryptoScopes = []
if (cryptoScope === 'global' || cryptoScope === 'both') cryptoScopes.push('global')
if (cryptoScope === 'specific' || cryptoScope === 'both') cryptos.forEach(r => cryptoScopes.push(r))
return cryptoScopes
}
function allMachineScopes (machineList, machineScope) {
const machineScopes = []
if (machineScope === 'global' || machineScope === 'both') machineScopes.push('global')
if (machineScope === 'specific' || machineScope === 'both') machineList.forEach(r => machineScopes.push(r))
return machineScopes
}
function satisfiesRequire (config, cryptos, machineList, field, anyFields, allFields) {
const fieldCode = field.code
const scopes = allScopes(
allCryptoScopes(cryptos, field.cryptoScope),
allMachineScopes(machineList, field.machineScope)
)
return scopes.every(scope => {
const isAnyEnabled = () => _.some(refField => {
return isScopeEnabled(config, cryptos, machineList, refField, scope)
}, anyFields)
const areAllEnabled = () => _.every(refField => {
return isScopeEnabled(config, cryptos, machineList, refField, scope)
}, allFields)
const isBlank = _.isNil(configManager.scopedValue(scope[0], scope[1], fieldCode, config))
const isRequired = (_.isEmpty(anyFields) || isAnyEnabled()) &&
(_.isEmpty(allFields) || areAllEnabled())
const hasDefault = !_.isNil(_.get('default', field))
const isValid = !isRequired || !isBlank || hasDefault
return isValid
})
}
function isScopeEnabled (config, cryptos, machineList, refField, scope) {
const [cryptoScope, machineScope] = scope
const candidateCryptoScopes = cryptoScope === 'global'
? allCryptoScopes(cryptos, refField.cryptoScope)
: [cryptoScope]
const candidateMachineScopes = machineScope === 'global'
? allMachineScopes(machineList, refField.machineScope)
: [ machineScope ]
const allRefCandidateScopes = allScopes(candidateCryptoScopes, candidateMachineScopes)
const getFallbackValue = scope => configManager.scopedValue(scope[0], scope[1], refField.code, config)
const values = allRefCandidateScopes.map(getFallbackValue)
return values.some(r => r)
}
function getCryptos (config, machineList) {
const scopes = allScopes(['global'], allMachineScopes(machineList, 'both'))
const scoped = scope => configManager.scopedValue(scope[0], scope[1], 'cryptoCurrencies', config)
return scopes.reduce((acc, scope) => _.union(acc, scoped(scope)), [])
}
function getGroup (fieldCode) {
return _.find(group => _.includes(fieldCode, group.fields), schema.groups)
}
function getField (fieldCode) {
const group = getGroup(fieldCode)
return getGroupField(group, fieldCode)
}
function getGroupField (group, fieldCode) {
const field = _.find(_.matchesProperty('code', fieldCode), schema.fields)
return _.merge(_.pick(['cryptoScope', 'machineScope'], group), field)
}
// Note: We can't use machine-loader because it relies on settings-loader,
// which relies on this
function getMachines () {
return db.any('select device_id from devices')
}
function fetchMachines () {
return getMachines()
.then(machineList => machineList.map(r => r.device_id))
}
function validateFieldParameter (value, validator) {
switch (validator.code) {
case 'required':
return true // We don't validate this here
case 'min':
return value >= validator.min
case 'max':
return value <= validator.max
default:
throw new Error('Unknown validation type: ' + validator.code)
}
}
function ensureConstraints (config) {
const pickField = fieldCode => schema.fields.find(r => r.code === fieldCode)
return Promise.resolve()
.then(() => {
config.every(fieldInstance => {
const fieldCode = fieldInstance.fieldLocator.code
const field = pickField(fieldCode)
if (!field) {
logger.warn('No such field: %s, %j', fieldCode, fieldInstance.fieldLocator.fieldScope)
return
}
const fieldValue = fieldInstance.fieldValue
const isValid = field.fieldValidation
.every(validator => validateFieldParameter(fieldValue.value, validator))
if (isValid) return true
throw new Error('Invalid config value')
})
})
}
function validateRequires (config) {
return fetchMachines()
.then(machineList => {
const cryptos = getCryptos(config, machineList)
return schema.groups.filter(group => {
return group.fields.some(fieldCode => {
const field = getGroupField(group, fieldCode)
if (!field.fieldValidation.find(r => r.code === 'required')) return false
const refFieldsAny = _.map(_.partial(getField, group), field.enabledIfAny)
const refFieldsAll = _.map(_.partial(getField, group), field.enabledIfAll)
const isInvalid = !satisfiesRequire(config, cryptos, machineList, field, refFieldsAny, refFieldsAll)
return isInvalid
})
})
})
.then(arr => arr.map(r => r.code))
}
function validate (config) {
return Promise.resolve()
.then(() => ensureConstraints(config))
.then(() => validateRequires(config))
.then(arr => {
if (arr.length === 0) return config
throw new Error('Invalid configuration:' + arr)
})
}
module.exports = {validate, ensureConstraints, validateRequires}
| Handle spammy logs for removed l-a-s options
| lib/config-validate.js | Handle spammy logs for removed l-a-s options | <ide><path>ib/config-validate.js
<ide> const configManager = require('./config-manager')
<ide> const logger = require('./logger')
<ide> const schema = require('../lamassu-schema.json')
<add>
<add>const REMOVED_FIELDS = ['crossRefVerificationActive', 'crossRefVerificationThreshold']
<ide>
<ide> function allScopes (cryptoScopes, machineScopes) {
<ide> const scopes = []
<ide> .then(() => {
<ide> config.every(fieldInstance => {
<ide> const fieldCode = fieldInstance.fieldLocator.code
<add> if (_.includes(fieldCode, REMOVED_FIELDS)) return
<add>
<ide> const field = pickField(fieldCode)
<ide> if (!field) {
<ide> logger.warn('No such field: %s, %j', fieldCode, fieldInstance.fieldLocator.fieldScope) |
|
JavaScript | mit | a5ab2666fb65087b820fec736045711d7b1f8516 | 0 | netiam/netiam,netiam/netiam | import _ from 'lodash'
import roles from './roles'
export default function acl(spec) {
const WILDCARD = '*'
const ALLOW = 'ALLOW'
const DENY = 'DENY'
const {settings} = spec
let o = {}
if (!settings) {
throw new Error('You must provide an ACL "settings" option')
}
/**
* Get all keys from resource and settings
* @returns {[String]}
*/
function keys(resource) {
let fields = []
if (settings.fields && _.isObject(settings.fields)) {
fields = fields.concat(settings.fields)
}
if (_.isFunction(resource.toObject)) {
resource = resource.toObject()
}
return Object
.keys(resource)
.concat(fields)
.sort()
}
/**
* Get all keys which a possible population
* @returns {Object}
*/
function refs() {
const paths = {}
if (settings.fields) {
_.forEach(settings.fields, function(field, key) {
if (field.ref) {
paths[key] = field.ref
}
})
}
return paths
}
/**
* Check path for allowed keys, can also handle wildcard entries
* @param {[String]} allKeys
* @param {String} modelPath
* @param {String} type
* @param {Object} role
* @param {String} role.name
* @param {String} privilege
* @returns {[String]}
*/
function path(allKeys, modelPath, type, role, privilege) {
if (settings.fields.hasOwnProperty(modelPath)) {
if (settings.fields[modelPath].hasOwnProperty(type)) {
if (settings.fields[modelPath][type][role.name] &&
settings.fields[modelPath][type][role.name].indexOf(privilege) !== -1
) {
if (modelPath === WILDCARD) {
return allKeys
}
return [modelPath]
}
}
}
return []
}
/**
* Get hierarchy for current role
* @param {Object} role
* @returns {[Object]}
*/
function hierarchy(role) {
if (!role) {
return []
}
if (!role.parent) {
return [roles.get(role)]
}
return [roles.get(role)].concat(hierarchy(role.parent))
}
/**
* Get allowed keys for a specific role
* @param {Document} user
* @param {Object} resource
* @param {Object} role
* @param {Boolean} role.superuser
* @param {String} [privilege='R']
* @param {Array} [asserts=[]]
* @returns {[String]} A list of allowed keys for given collection
*/
function allowedForRole(user, resource, role, privilege, asserts) {
role = roles.get(role)
const allKeys = keys(resource)
let allowedKeys = []
let deniedKeys = []
// return all keys for superuser
if (role.superuser === true) {
return allKeys
}
// ALLOW wildcard
allowedKeys = allowedKeys.concat(
path(allKeys, WILDCARD, ALLOW, role, privilege)
)
// ALLOW statements
allKeys.forEach(function(key) {
allowedKeys = allowedKeys.concat(
path(allKeys, key, ALLOW, role, privilege)
)
})
// asserts
asserts.forEach(function(assert) {
allowedKeys = allowedKeys.concat(
assert(user, o, resource, role, privilege)
)
})
// ALLOW wildcard
deniedKeys = deniedKeys.concat(
path(allKeys, WILDCARD, DENY, role, privilege)
)
// DENY statements
allKeys.forEach(function(key) {
deniedKeys = deniedKeys.concat(
path(allKeys, key, DENY, role, privilege)
)
})
return _.uniq(
_.difference(allowedKeys, deniedKeys)
)
}
/**
* Get allowed keys for given resource
* @param {Document} user
* @param {Document} resource
* @param {String|Object} role
* @param {String} [privilege='R']
* @param {Array} [asserts=[]]
* @returns {[String]} A list of allowed keys for given collection
*/
function allowed(user, resource, role, privilege = 'R', asserts = []) {
role = roles.get(role)
const roleHierarchy = hierarchy(role).reverse()
let allowedKeys = []
if (!_.isArray(asserts)) {
asserts = [asserts]
}
asserts.forEach(function(assert) {
allowedKeys = allowedKeys.concat(
assert(user, o, resource, role, privilege))
})
roleHierarchy.forEach(function(r) {
allowedKeys = allowedKeys.concat(
allowedForRole(user, resource, r, privilege, asserts))
})
return allowedKeys
}
function isObjectID(obj) {
return _.isObject(obj) && obj.constructor.name === 'ObjectID'
}
/**
* Filters a resource object by ACL
* @param {Document} user
* @param {Document} resource
* @param {Document} role
* @param {String} [privilege='R']
* @param {Array} [asserts=[]]
* @returns {Object}
*/
function filter(user, resource, role, privilege = 'R', asserts = []) {
const data = _.pick(
resource,
allowed(
user,
resource,
role,
privilege,
asserts
)
)
// filter in populated paths
const allRefs = refs()
_.forEach(allRefs, function(ref, path) {
const subacl = acl({settings: ref})
if (_.isArray(data[path]) && data[path].length > 0) {
data[path] = data[path].map(function(nestedResource) {
// HACK Check for ObjectID objects -> lean does not convert them to String
if (isObjectID(nestedResource)) {
return nestedResource.toHexString()
}
if (_.isObject(nestedResource)) {
return subacl.filter(user, nestedResource, role, privilege, asserts)
}
return nestedResource
})
return
}
// HACK Check for ObjectID objects -> lean does not convert them to String
if (isObjectID(data[path])) {
data[path] = data[path].toHexString()
return
}
if (_.isObject(data[path])) {
data[path] = subacl.filter(user, data[path], role, privilege, asserts)
}
})
return data
}
/**
* Is role with privilege allowed to access resource
* @param {User} user
* @param {Object} role
* @param {String} [privilege='R']
* @returns {Boolean} True if allowed, otherwise false
*/
function resource(user, role, privilege = 'R') {
if (!settings.resource) {
return false
}
if (!settings.resource[ALLOW]) {
return false
}
let isAllowed = false
role = roles.get(role)
// wildcard allow
if (settings.resource[ALLOW] && settings.resource[ALLOW][WILDCARD]) {
if (settings.resource[ALLOW][WILDCARD].indexOf(privilege) !== -1) {
isAllowed = true
}
}
// allow
if (settings.resource[ALLOW] && settings.resource[ALLOW][role.name]) {
if (settings.resource[ALLOW][role.name].indexOf(privilege) !== -1) {
isAllowed = true
}
}
// wildcard deny
if (settings.resource[DENY] && settings.resource[DENY][WILDCARD]) {
if (settings.resource[DENY][WILDCARD].indexOf(privilege) !== -1) {
isAllowed = false
}
}
// deny
if (settings.resource[DENY] && settings.resource[DENY][role.name]) {
if (settings.resource[DENY][role.name].indexOf(privilege) !== -1) {
isAllowed = false
}
}
return isAllowed
}
o.settings = settings
o.allowed = allowed
o.filter = filter
o.resource = resource
return Object.freeze(o)
}
| src/rest/acl.js | import _ from 'lodash'
import roles from './roles'
export default function acl(spec) {
const WILDCARD = '*'
const ALLOW = 'ALLOW'
const DENY = 'DENY'
const {settings} = spec
let o = {}
if (!settings) {
throw new Error('You must provide an ACL "settings" option')
}
/**
* Get all keys from resource and settings
* @returns {[String]}
*/
function keys(resource) {
let fields = []
if (settings.fields && _.isObject(settings.fields)) {
fields = fields.concat(settings.fields)
}
if (_.isFunction(resource.toObject)) {
resource = resource.toObject()
}
return Object
.keys(resource)
.concat(fields)
.sort()
}
/**
* Get all keys which a possible population
* @returns {Object}
*/
function refs() {
const paths = {}
if (settings.fields) {
_.forEach(settings.fields, function(field, key) {
if (field.ref) {
paths[key] = field.ref
}
})
}
return paths
}
/**
* Check path for allowed keys, can also handle wildcard entries
* @param {[String]} allKeys
* @param {String} modelPath
* @param {String} type
* @param {Object} role
* @param {String} role.name
* @param {String} privilege
* @returns {[String]}
*/
function path(allKeys, modelPath, type, role, privilege) {
if (settings.fields.hasOwnProperty(modelPath)) {
if (settings.fields[modelPath].hasOwnProperty(type)) {
if (settings.fields[modelPath][type][role.name] &&
settings.fields[modelPath][type][role.name].indexOf(privilege) !== -1
) {
if (modelPath === WILDCARD) {
return allKeys
}
return [modelPath]
}
}
}
return []
}
/**
* Get hierarchy for current role
* @param {Object} role
* @returns {[Object]}
*/
function hierarchy(role) {
if (!role) {
return []
}
if (!role.parent) {
return [roles.get(role)]
}
return [roles.get(role)].concat(hierarchy(role.parent))
}
/**
* Get allowed keys for a specific role
* @param {Document} user
* @param {Object} resource
* @param {Object} role
* @param {Boolean} role.superuser
* @param {String} [privilege='R']
* @param {Array} [asserts=[]]
* @returns {[String]} A list of allowed keys for given collection
*/
function allowedForRole(user, resource, role, privilege, asserts) {
role = roles.get(role)
const allKeys = keys(resource)
let allowedKeys = []
let deniedKeys = []
// return all keys for superuser
if (role.superuser === true) {
return allKeys
}
// ALLOW wildcard
allowedKeys = allowedKeys.concat(
path(allKeys, WILDCARD, ALLOW, role, privilege)
)
// ALLOW statements
allKeys.forEach(function(key) {
allowedKeys = allowedKeys.concat(
path(allKeys, key, ALLOW, role, privilege)
)
})
// asserts
asserts.forEach(function(assert) {
allowedKeys = allowedKeys.concat(
assert(user, o, resource, role, privilege)
)
})
// ALLOW wildcard
deniedKeys = deniedKeys.concat(
path(allKeys, WILDCARD, DENY, role, privilege)
)
// DENY statements
allKeys.forEach(function(key) {
deniedKeys = deniedKeys.concat(
path(allKeys, key, DENY, role, privilege)
)
})
return _.uniq(
_.difference(allowedKeys, deniedKeys)
)
}
/**
* Get allowed keys for given resource
* @param {Document} user
* @param {Document} resource
* @param {String|Object} role
* @param {String} [privilege='R']
* @param {Array} [asserts=[]]
* @returns {[String]} A list of allowed keys for given collection
*/
function allowed(user, resource, role, privilege = 'R', asserts = []) {
role = roles.get(role)
const roleHierarchy = hierarchy(role).reverse()
let allowedKeys = []
if (!_.isArray(asserts)) {
asserts = [asserts]
}
asserts.forEach(function(assert) {
allowedKeys = allowedKeys.concat(
assert(user, o, resource, role, privilege))
})
roleHierarchy.forEach(function(r) {
allowedKeys = allowedKeys.concat(
allowedForRole(user, resource, r, privilege, asserts))
})
return allowedKeys
}
function isObjectID(obj) {
return _.isObject(obj) && obj.constructor.name === 'ObjectID'
}
/**
* Filters a resource object by ACL
* @param {Document} user
* @param {Document} resource
* @param {Document} role
* @param {String} [privilege='R']
* @param {Array} [asserts=[]]
* @returns {Object}
*/
function filter(user, resource, role, privilege = 'R', asserts = []) {
const data = _.pick(
resource,
allowed(
user,
resource,
role,
privilege,
asserts
)
)
// filter in populated paths
const allRefs = refs()
_.forEach(allRefs, function(ref, path) {
const subacl = acl({settings: ref})
if (_.isArray(data[path]) && data[path].length > 0) {
data[path] = data[path].map(function(nestedResource) {
// HACK Check for ObjectID objects -> lean does not convert them to String
if (isObjectID(nestedResource)) {
console.log(nestedResource.toHexString())
return nestedResource.toHexString()
}
if (_.isObject(nestedResource)) {
return subacl.filter(user, nestedResource, role, privilege, asserts)
}
return nestedResource
})
return
}
// HACK Check for ObjectID objects -> lean does not convert them to String
if (isObjectID(data[path])) {
data[path] = data[path].toHexString()
return
}
if (_.isObject(data[path])) {
data[path] = subacl.filter(user, data[path], role, privilege, asserts)
}
})
return data
}
/**
* Is role with privilege allowed to access resource
* @param {User} user
* @param {Object} role
* @param {String} [privilege='R']
* @returns {Boolean} True if allowed, otherwise false
*/
function resource(user, role, privilege = 'R') {
if (!settings.resource) {
return false
}
if (!settings.resource[ALLOW]) {
return false
}
let isAllowed = false
role = roles.get(role)
// wildcard allow
if (settings.resource[ALLOW] && settings.resource[ALLOW][WILDCARD]) {
if (settings.resource[ALLOW][WILDCARD].indexOf(privilege) !== -1) {
isAllowed = true
}
}
// allow
if (settings.resource[ALLOW] && settings.resource[ALLOW][role.name]) {
if (settings.resource[ALLOW][role.name].indexOf(privilege) !== -1) {
isAllowed = true
}
}
// wildcard deny
if (settings.resource[DENY] && settings.resource[DENY][WILDCARD]) {
if (settings.resource[DENY][WILDCARD].indexOf(privilege) !== -1) {
isAllowed = false
}
}
// deny
if (settings.resource[DENY] && settings.resource[DENY][role.name]) {
if (settings.resource[DENY][role.name].indexOf(privilege) !== -1) {
isAllowed = false
}
}
return isAllowed
}
o.settings = settings
o.allowed = allowed
o.filter = filter
o.resource = resource
return Object.freeze(o)
}
| refactor: remove log statement
| src/rest/acl.js | refactor: remove log statement | <ide><path>rc/rest/acl.js
<ide> data[path] = data[path].map(function(nestedResource) {
<ide> // HACK Check for ObjectID objects -> lean does not convert them to String
<ide> if (isObjectID(nestedResource)) {
<del> console.log(nestedResource.toHexString())
<ide> return nestedResource.toHexString()
<ide> }
<ide> |
|
Java | apache-2.0 | 61125a6b1b454454bd67feb412abb8bfca3da7d1 | 0 | freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification,freshplanet/ANE-Push-Notification | /**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirPushNotification;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
public class PingUrlTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... urls) {
String trackingUrl = urls[0];
Extension.log("start tracking "+trackingUrl);
try {
URL url = new URL(trackingUrl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestMethod("GET");
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setDoInput(true);
urlc.setConnectTimeout(1000 * 10);
urlc.connect();
// DO NOT REMOVE THIS CODE BLOCK, IF YOU DO TRACKING WONT WORK
///////////////////////////////////////////////////////////////
switch (urlc.getResponseCode()) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
Extension.log("Notification tracking response: " + sb.toString());
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
///////////////////////////////////////////////////////////////
return null;
}
@Override
protected void onPostExecute(Boolean downloadSuccess)
{
Extension.log("tracking complete");
}
}
| android/lib/src/main/java/com/freshplanet/ane/AirPushNotification/PingUrlTask.java | /**
* Copyright 2017 FreshPlanet
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshplanet.ane.AirPushNotification;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.os.AsyncTask;
public class PingUrlTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... urls) {
String trackingUrl = urls[0];
Extension.log("start tracking "+trackingUrl);
try {
URL url = new URL(trackingUrl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestMethod("GET");
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setDoInput(true);
urlc.setConnectTimeout(1000 * 10);
urlc.connect();
switch (urlc.getResponseCode()) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
Extension.log("Notification tracking response: " + sb.toString());
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Boolean downloadSuccess)
{
Extension.log("tracking complete");
}
}
| adding comment for safety
| android/lib/src/main/java/com/freshplanet/ane/AirPushNotification/PingUrlTask.java | adding comment for safety | <ide><path>ndroid/lib/src/main/java/com/freshplanet/ane/AirPushNotification/PingUrlTask.java
<ide> urlc.setConnectTimeout(1000 * 10);
<ide> urlc.connect();
<ide>
<add> // DO NOT REMOVE THIS CODE BLOCK, IF YOU DO TRACKING WONT WORK
<add> ///////////////////////////////////////////////////////////////
<ide> switch (urlc.getResponseCode()) {
<ide> case 200:
<ide> case 201:
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> }
<del>
<add> ///////////////////////////////////////////////////////////////
<ide> return null;
<ide> }
<ide> |
|
JavaScript | apache-2.0 | 2763dc400463aeb42fc17d7d6af3a8b5fa83451a | 0 | darrylwest/node-file-utils | #!/usr/bin/env node
// example of an events only walker; use this to walk huge trees and operate on each file one at a time; not as
// good as streams, but close
var TreeWalker = require('../lib/TreeWalker'),
log = require('simple-node-logger').createSimpleLogger(),
walker = new TreeWalker({ log:log }),
hugeFolder = 'YOUR-HUGE-FILE-SYSTEM';
walker.onFile(function(file) {
log.info( file );
});
walker.walk( hugeFolder, { eventsOnly:true }, function(err, count) {
if (err) throw err;
log.info( 'walk list size: ', count );
});
| examples/huge-tree-walker.js | #!/usr/bin/env node
// example of an events only walker; use this to walk huge trees and operate on each file one at a time; not as
// good as streams, but close
var TreeWalker = require('../lib/TreeWalker'),
log = require('simple-node-logger').createSimpleLogger(),
walker = new TreeWalker({ log:log }),
hugeFolder = '/Volumes/dpw-2012/gimp';
walker.onFile(function(file) {
log.info( file );
});
walker.walk( hugeFolder, { eventsOnly:true }, function(err, count) {
if (err) throw err;
log.info( 'walk list size: ', count );
});
| added example
| examples/huge-tree-walker.js | added example | <ide><path>xamples/huge-tree-walker.js
<ide> var TreeWalker = require('../lib/TreeWalker'),
<ide> log = require('simple-node-logger').createSimpleLogger(),
<ide> walker = new TreeWalker({ log:log }),
<del> hugeFolder = '/Volumes/dpw-2012/gimp';
<add> hugeFolder = 'YOUR-HUGE-FILE-SYSTEM';
<ide>
<ide> walker.onFile(function(file) {
<ide> log.info( file ); |
|
Java | apache-2.0 | 54f54550800858691a3438f92c6e26960a2a6a6c | 0 | d0k1/jmeter,DoctorQ/jmeter,liwangbest/jmeter,irfanah/jmeter,vherilier/jmeter,hemikak/jmeter,thomsonreuters/jmeter,thomsonreuters/jmeter,kyroskoh/jmeter,ubikloadpack/jmeter,irfanah/jmeter,hemikak/jmeter,kschroeder/jmeter,kschroeder/jmeter,ThiagoGarciaAlves/jmeter,max3163/jmeter,d0k1/jmeter,hemikak/jmeter,tuanhq/jmeter,vherilier/jmeter,hizhangqi/jmeter-1,fj11/jmeter,etnetera/jmeter,tuanhq/jmeter,etnetera/jmeter,max3163/jmeter,ubikloadpack/jmeter,ThiagoGarciaAlves/jmeter,thomsonreuters/jmeter,liwangbest/jmeter,ubikloadpack/jmeter,fj11/jmeter,etnetera/jmeter,irfanah/jmeter,max3163/jmeter,ra0077/jmeter,ubikfsabbe/jmeter,hizhangqi/jmeter-1,etnetera/jmeter,ra0077/jmeter,kschroeder/jmeter,ubikfsabbe/jmeter,d0k1/jmeter,d0k1/jmeter,ubikfsabbe/jmeter,ubikfsabbe/jmeter,kyroskoh/jmeter,max3163/jmeter,tuanhq/jmeter,etnetera/jmeter,hemikak/jmeter,hizhangqi/jmeter-1,kyroskoh/jmeter,ra0077/jmeter,liwangbest/jmeter,DoctorQ/jmeter,vherilier/jmeter,vherilier/jmeter,ra0077/jmeter,ubikloadpack/jmeter,fj11/jmeter,DoctorQ/jmeter,ThiagoGarciaAlves/jmeter | /*
* Copyright 2001-2004,2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jorphan.logging;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Properties;
import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.jorphan.util.ClassContext;
import org.apache.log.Hierarchy;
import org.apache.log.LogTarget;
import org.apache.log.Logger;
import org.apache.log.Priority;
import org.apache.log.format.PatternFormatter;
import org.apache.log.output.NullOutputLogTarget;
import org.apache.log.output.io.WriterTarget;
import org.xml.sax.SAXException;
/**
* @version $Revision$ on $Date$
*/
public final class LoggingManager {
// N.B time pattern is passed to java.text.SimpleDateFormat
/*
* Predefined format patterns, selected by the property log_format_type (see
* jmeter.properties) The new-line is added later
*/
private static final String DEFAULT_PATTERN = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} - "
+ "%{category}: %{message} %{throwable}";
private static final String PATTERN_THREAD_PREFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} "
+ "%12{thread} %{category}: %{message} %{throwable}";
private static final String PATTERN_THREAD_SUFFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} "
+ "%{category}[%{thread}]: %{message} %{throwable}";
private static PatternFormatter format = null;
/** Used to hold the default logging target. */
private static LogTarget target;
// Hack to detect when System.out has been set as the target, to avoid
// closing it
private static boolean isTargetSystemOut = false;// Is the target
// System.out?
private static boolean isWriterSystemOut = false;// Is the Writer
// System.out?
public final static String LOG_FILE = "log_file";
public final static String LOG_PRIORITY = "log_level";
private static LoggingManager logManager = null;
private LoggingManager() {
// ensure that target is valid initially
target = new NullOutputLogTarget();
}
public static LoggingManager getLogManager() {
return logManager;
}
/**
* Initialise the logging system from the Jmeter properties. Logkit loggers
* inherit from their parents.
*
* Normally the jmeter properties file defines a single log file, so set
* this as the default from "log_file", default "jmeter.log" The default
* priority is set from "log_level", with a default of INFO
*
*/
public static void initializeLogging(Properties properties) {
if (logManager == null) {
logManager = new LoggingManager();
}
setFormat(properties);
// Set the top-level defaults
setTarget(makeWriter(properties.getProperty(LOG_FILE, "jmeter.log"), LOG_FILE));
setPriority(properties.getProperty(LOG_PRIORITY, "INFO"));
setLoggingLevels(properties);
// now set the individual categories (if any)
setConfig(properties);// Further configuration
}
private static void setFormat(Properties properties) {
String pattern = DEFAULT_PATTERN;
String type = properties.getProperty("log_format_type", "");
if (type.length() == 0) {
pattern = properties.getProperty("log_format", DEFAULT_PATTERN);
} else {
if (type.equalsIgnoreCase("thread_suffix")) {
pattern = PATTERN_THREAD_SUFFIX;
} else if (type.equalsIgnoreCase("thread_prefix")) {
pattern = PATTERN_THREAD_PREFIX;
} else {
pattern = DEFAULT_PATTERN;
}
}
format = new PatternFormatter(pattern + "\n");
}
private static void setConfig(Properties p) {
String cfg = p.getProperty("log_config");
if (cfg == null)
return;
// Make sure same hierarchy is used
Hierarchy hier = Hierarchy.getDefaultHierarchy();
LogKitLoggerManager manager = new LogKitLoggerManager(null, hier, null, null);
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration c = builder.buildFromFile(cfg);
Context ctx = new DefaultContext();
manager.contextualize(ctx);
manager.configure(c);
} catch (IllegalArgumentException e) {
// This happens if the default log-target id-ref specifies a
// non-existent target
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (NullPointerException e) {
// This can happen if a log-target id-ref specifies a non-existent
// target
System.out.println("Error processing logging config " + cfg);
System.out.println("Perhaps a log target is missing?");
} catch (ConfigurationException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (SAXException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (IOException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (ContextException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
}
}
/*
* Helper method to ensure that format is initialised if initializeLogging()
* has not yet been called.
*/
private static PatternFormatter getFormat() {
if (format == null) {
format = new PatternFormatter(DEFAULT_PATTERN + "\n");
}
return format;
}
/*
* Helper method to handle log target creation. If there is an error
* creating the file, then it uses System.out.
*/
private static Writer makeWriter(String logFile, String propName) {
Writer wt;
isWriterSystemOut = false;
try {
wt = new FileWriter(logFile);
} catch (Exception e) {
System.out.println(propName + "=" + logFile + " " + e.toString());
System.out.println("[" + propName + "-> System.out]");
isWriterSystemOut = true;
wt = new PrintWriter(System.out);
}
return wt;
}
/**
* Handle LOG_PRIORITY.category=priority and LOG_FILE.category=file_name
* properties. If the prefix is detected, then remove it to get the
* category.
*/
public static void setLoggingLevels(Properties appProperties) {
Iterator props = appProperties.keySet().iterator();
while (props.hasNext()) {
String prop = (String) props.next();
if (prop.startsWith(LOG_PRIORITY + "."))
// don't match the empty category
{
String category = prop.substring(LOG_PRIORITY.length() + 1);
setPriority(appProperties.getProperty(prop), category);
}
if (prop.startsWith(LOG_FILE + ".")) {
String category = prop.substring(LOG_FILE.length() + 1);
String file = appProperties.getProperty(prop);
setTarget(new WriterTarget(makeWriter(file, prop), getFormat()), category);
}
}
}
private final static String PACKAGE_PREFIX = "org.apache.";
/*
* Stack contains the follow when the context is obtained: 0 -
* getCallerClassNameAt() 1 - this method 2 - getLoggerForClass
*
*/
private static String getCallerClassName() {
String name = ClassContext.getCallerClassNameAt(3);
return name;
}
public static String removePrefix(String name){
if (name.startsWith(PACKAGE_PREFIX)) { // remove the package prefix
name = name.substring(PACKAGE_PREFIX.length());
}
return name;
}
/**
* Get the Logger for a class - no argument needed because the calling class
* name is derived automatically from the call stack.
*
* @return Logger
*/
public static Logger getLoggerForClass() {
String className = getCallerClassName();
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(className));
}
public static Logger getLoggerFor(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(category);
}
public static Logger getLoggerForShortName(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(category));
}
public static void setPriority(String p, String category) {
setPriority(Priority.getPriorityForName(p), category);
}
/**
*
* @param p - priority, e.g. DEBUG, INFO
* @param fullName - e.g. org.apache.jmeter.etc
*/
public static void setPriorityFullName(String p, String fullName) {
setPriority(Priority.getPriorityForName(p), removePrefix(fullName));
}
public static void setPriority(Priority p, String category) {
Hierarchy.getDefaultHierarchy().getLoggerFor(category).setPriority(p);
}
public static void setPriority(String p) {
setPriority(Priority.getPriorityForName(p));
}
public static void setPriority(Priority p) {
Hierarchy.getDefaultHierarchy().setDefaultPriority(p);
}
public static void setTarget(LogTarget target, String category) {
Logger logger = Hierarchy.getDefaultHierarchy().getLoggerFor(category);
logger.setLogTargets(new LogTarget[] { target });
}
/**
* Sets the default log target from the parameter. The existing target is
* first closed if necessary.
*
* @param targetFile
* (Writer)
*/
public static void setTarget(Writer targetFile) {
if (target == null) {
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
} else {
if (!isTargetSystemOut && target instanceof WriterTarget) {
((WriterTarget) target).close();
}
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
}
Hierarchy.getDefaultHierarchy().setDefaultLogTarget(target);
}
private static LogTarget getTarget(Writer targetFile, PatternFormatter fmt) {
return new WriterTarget(targetFile, fmt);
}
}
| src/jorphan/org/apache/jorphan/logging/LoggingManager.java | // $Header$
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jorphan.logging;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Iterator;
import java.util.Properties;
import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.DefaultContext;
import org.apache.jorphan.util.ClassContext;
import org.apache.log.Hierarchy;
import org.apache.log.LogTarget;
import org.apache.log.Logger;
import org.apache.log.Priority;
import org.apache.log.format.PatternFormatter;
import org.apache.log.output.NullOutputLogTarget;
import org.apache.log.output.io.WriterTarget;
import org.xml.sax.SAXException;
/**
* @version $Revision$ on $Date$
*/
public final class LoggingManager {
// N.B time pattern is passed to java.text.SimpleDateFormat
/*
* Predefined format patterns, selected by the property log_format_type (see
* jmeter.properties) The new-line is added later
*/
private static final String DEFAULT_PATTERN = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} - "
+ "%{category}: %{message} %{throwable}";
private static final String PATTERN_THREAD_PREFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} "
+ "%12{thread} %{category}: %{message} %{throwable}";
private static final String PATTERN_THREAD_SUFFIX = "%{time:yyyy/MM/dd HH:mm:ss} %5.5{priority} "
+ "%{category}[%{thread}]: %{message} %{throwable}";
private static PatternFormatter format = null;
/** Used to hold the default logging target. */
private static LogTarget target;
// Hack to detect when System.out has been set as the target, to avoid
// closing it
private static boolean isTargetSystemOut = false;// Is the target
// System.out?
private static boolean isWriterSystemOut = false;// Is the Writer
// System.out?
public final static String LOG_FILE = "log_file";
public final static String LOG_PRIORITY = "log_level";
private static LoggingManager logManager = null;
private LoggingManager() {
// ensure that target is valid initially
target = new NullOutputLogTarget();
}
public static LoggingManager getLogManager() {
return logManager;
}
/**
* Initialise the logging system from the Jmeter properties. Logkit loggers
* inherit from their parents.
*
* Normally the jmeter properties file defines a single log file, so set
* this as the default from "log_file", default "jmeter.log" The default
* priority is set from "log_level", with a default of INFO
*
*/
public static void initializeLogging(Properties properties) {
if (logManager == null) {
logManager = new LoggingManager();
}
setFormat(properties);
// Set the top-level defaults
setTarget(makeWriter(properties.getProperty(LOG_FILE, "jmeter.log"), LOG_FILE));
setPriority(properties.getProperty(LOG_PRIORITY, "INFO"));
setLoggingLevels(properties);
// now set the individual categories (if any)
setConfig(properties);// Further configuration
}
private static void setFormat(Properties properties) {
String pattern = DEFAULT_PATTERN;
String type = properties.getProperty("log_format_type", "");
if (type.length() == 0) {
pattern = properties.getProperty("log_format", DEFAULT_PATTERN);
} else {
if (type.equalsIgnoreCase("thread_suffix")) {
pattern = PATTERN_THREAD_SUFFIX;
} else if (type.equalsIgnoreCase("thread_prefix")) {
pattern = PATTERN_THREAD_PREFIX;
} else {
pattern = DEFAULT_PATTERN;
}
}
format = new PatternFormatter(pattern + "\n");
}
private static void setConfig(Properties p) {
String cfg = p.getProperty("log_config");
if (cfg == null)
return;
// Make sure same hierarchy is used
Hierarchy hier = Hierarchy.getDefaultHierarchy();
LogKitLoggerManager manager = new LogKitLoggerManager(null, hier, null, null);
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration c = builder.buildFromFile(cfg);
Context ctx = new DefaultContext();
manager.contextualize(ctx);
manager.configure(c);
} catch (IllegalArgumentException e) {
// This happens if the default log-target id-ref specifies a
// non-existent target
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (NullPointerException e) {
// This can happen if a log-target id-ref specifies a non-existent
// target
System.out.println("Error processing logging config " + cfg);
System.out.println("Perhaps a log target is missing?");
} catch (ConfigurationException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (SAXException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (IOException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
} catch (ContextException e) {
System.out.println("Error processing logging config " + cfg);
System.out.println(e.toString());
}
}
/*
* Helper method to ensure that format is initialised if initializeLogging()
* has not yet been called.
*/
private static PatternFormatter getFormat() {
if (format == null) {
format = new PatternFormatter(DEFAULT_PATTERN + "\n");
}
return format;
}
/*
* Helper method to handle log target creation. If there is an error
* creating the file, then it uses System.out.
*/
private static Writer makeWriter(String logFile, String propName) {
Writer wt;
isWriterSystemOut = false;
try {
wt = new FileWriter(logFile);
} catch (Exception e) {
System.out.println(propName + "=" + logFile + " " + e.toString());
System.out.println("[" + propName + "-> System.out]");
isWriterSystemOut = true;
wt = new PrintWriter(System.out);
}
return wt;
}
/*
* Handle LOG_PRIORITY.category=priority and LOG_FILE.category=file_name
* properties. If the prefix is detected, then remove it to get the
* category.
*/
private static void setLoggingLevels(Properties appProperties) {
Iterator props = appProperties.keySet().iterator();
while (props.hasNext()) {
String prop = (String) props.next();
if (prop.startsWith(LOG_PRIORITY + "."))
// don't match the empty category
{
String category = prop.substring(LOG_PRIORITY.length() + 1);
setPriority(appProperties.getProperty(prop), category);
}
if (prop.startsWith(LOG_FILE + ".")) {
String category = prop.substring(LOG_FILE.length() + 1);
String file = appProperties.getProperty(prop);
setTarget(new WriterTarget(makeWriter(file, prop), getFormat()), category);
}
}
}
private final static String PACKAGE_PREFIX = "org.apache.";
/*
* Stack contains the follow when the context is obtained: 0 -
* getCallerClassNameAt() 1 - this method 2 - getLoggerForClass
*
*/
private static String getCallerClassName() {
String name = ClassContext.getCallerClassNameAt(3);
return name;
}
public static String removePrefix(String name){
if (name.startsWith(PACKAGE_PREFIX)) { // remove the package prefix
name = name.substring(PACKAGE_PREFIX.length());
}
return name;
}
/**
* Get the Logger for a class - no argument needed because the calling class
* name is derived automatically from the call stack.
*
* @return Logger
*/
public static Logger getLoggerForClass() {
String className = getCallerClassName();
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(className));
}
public static Logger getLoggerFor(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(category);
}
public static Logger getLoggerForShortName(String category) {
return Hierarchy.getDefaultHierarchy().getLoggerFor(removePrefix(category));
}
public static void setPriority(String p, String category) {
setPriority(Priority.getPriorityForName(p), category);
}
/**
*
* @param p - priority, e.g. DEBUG, INFO
* @param fullName - e.g. org.apache.jmeter.etc
*/
public static void setPriorityFullName(String p, String fullName) {
setPriority(Priority.getPriorityForName(p), removePrefix(fullName));
}
public static void setPriority(Priority p, String category) {
Hierarchy.getDefaultHierarchy().getLoggerFor(category).setPriority(p);
}
public static void setPriority(String p) {
setPriority(Priority.getPriorityForName(p));
}
public static void setPriority(Priority p) {
Hierarchy.getDefaultHierarchy().setDefaultPriority(p);
}
public static void setTarget(LogTarget target, String category) {
Logger logger = Hierarchy.getDefaultHierarchy().getLoggerFor(category);
logger.setLogTargets(new LogTarget[] { target });
}
/**
* Sets the default log target from the parameter. The existing target is
* first closed if necessary.
*
* @param targetFile
* (Writer)
*/
public static void setTarget(Writer targetFile) {
if (target == null) {
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
} else {
if (!isTargetSystemOut && target instanceof WriterTarget) {
((WriterTarget) target).close();
}
target = getTarget(targetFile, getFormat());
isTargetSystemOut = isWriterSystemOut;
}
Hierarchy.getDefaultHierarchy().setDefaultLogTarget(target);
}
private static LogTarget getTarget(Writer targetFile, PatternFormatter fmt) {
return new WriterTarget(targetFile, fmt);
}
}
| Make setLoggingLevels() public
git-svn-id: 52ad764cdf1b64a6e804f4e5ad13917d3c4b2253@410904 13f79535-47bb-0310-9956-ffa450edef68
| src/jorphan/org/apache/jorphan/logging/LoggingManager.java | Make setLoggingLevels() public | <ide><path>rc/jorphan/org/apache/jorphan/logging/LoggingManager.java
<del>// $Header$
<ide> /*
<del> * Copyright 2001-2004 The Apache Software Foundation.
<add> * Copyright 2001-2004,2006 The Apache Software Foundation.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> return wt;
<ide> }
<ide>
<del> /*
<add> /**
<ide> * Handle LOG_PRIORITY.category=priority and LOG_FILE.category=file_name
<ide> * properties. If the prefix is detected, then remove it to get the
<ide> * category.
<ide> */
<del> private static void setLoggingLevels(Properties appProperties) {
<add> public static void setLoggingLevels(Properties appProperties) {
<ide> Iterator props = appProperties.keySet().iterator();
<ide> while (props.hasNext()) {
<ide> String prop = (String) props.next(); |
|
Java | apache-2.0 | d195c066860b25cf734c61c8da57863135e9194a | 0 | kool79/intellij-community,dslomov/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,signed/intellij-community,robovm/robovm-studio,fitermay/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,jexp/idea2,samthor/intellij-community,slisson/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,samthor/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,signed/intellij-community,signed/intellij-community,asedunov/intellij-community,slisson/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,jexp/idea2,alphafoobar/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,dslomov/intellij-community,signed/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,consulo/consulo,ibinti/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,supersven/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,samthor/intellij-community,caot/intellij-community,dslomov/intellij-community,fitermay/intellij-community,holmes/intellij-community,jagguli/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,supersven/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,kdwink/intellij-community,xfournet/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,caot/intellij-community,jexp/idea2,hurricup/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ryano144/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,kdwink/intellij-community,ibinti/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,kool79/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,consulo/consulo,robovm/robovm-studio,holmes/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,petteyg/intellij-community,diorcety/intellij-community,semonte/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,joewalnes/idea-community,signed/intellij-community,da1z/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,da1z/intellij-community,samthor/intellij-community,clumsy/intellij-community,amith01994/intellij-community,caot/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,fnouama/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,amith01994/intellij-community,allotria/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,da1z/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,jagguli/intellij-community,caot/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,amith01994/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,vladmm/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,adedayo/intellij-community,xfournet/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,fnouama/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,consulo/consulo,michaelgallacher/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,jexp/idea2,kool79/intellij-community,dslomov/intellij-community,apixandru/intellij-community,allotria/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,dslomov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ibinti/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,holmes/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,jexp/idea2,xfournet/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,jexp/idea2,lucafavatella/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,caot/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ernestp/consulo,consulo/consulo,youdonghai/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,izonder/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,slisson/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,robovm/robovm-studio,jagguli/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,ibinti/intellij-community,samthor/intellij-community,allotria/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,caot/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,diorcety/intellij-community,clumsy/intellij-community,slisson/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,da1z/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,asedunov/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,caot/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,vladmm/intellij-community,da1z/intellij-community,kool79/intellij-community,adedayo/intellij-community,izonder/intellij-community,gnuhub/intellij-community,allotria/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,diorcety/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,ernestp/consulo,ernestp/consulo,youdonghai/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,amith01994/intellij-community,ryano144/intellij-community,izonder/intellij-community,holmes/intellij-community,signed/intellij-community,supersven/intellij-community,samthor/intellij-community,holmes/intellij-community,ibinti/intellij-community,fitermay/intellij-community,FHannes/intellij-community,signed/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ryano144/intellij-community,gnuhub/intellij-community,caot/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,ernestp/consulo,ahb0327/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,allotria/intellij-community,dslomov/intellij-community,joewalnes/idea-community,dslomov/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,nicolargo/intellij-community,semonte/intellij-community,supersven/intellij-community,da1z/intellij-community,FHannes/intellij-community,joewalnes/idea-community,vladmm/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,adedayo/intellij-community,FHannes/intellij-community,ibinti/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,retomerz/intellij-community,semonte/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,blademainer/intellij-community,hurricup/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,caot/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,samthor/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,semonte/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,caot/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,slisson/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ibinti/intellij-community,blademainer/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,consulo/consulo,FHannes/intellij-community,caot/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,holmes/intellij-community,amith01994/intellij-community,robovm/robovm-studio,izonder/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,jexp/idea2,apixandru/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,da1z/intellij-community,ernestp/consulo,jexp/idea2,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,allotria/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,izonder/intellij-community,supersven/intellij-community,adedayo/intellij-community,supersven/intellij-community,holmes/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,samthor/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,hurricup/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,petteyg/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,apixandru/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,adedayo/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,diorcety/intellij-community,signed/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,signed/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,consulo/consulo,xfournet/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,da1z/intellij-community,semonte/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,slisson/intellij-community,blademainer/intellij-community,allotria/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community | /*
* Copyright 2003-2006 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.controlflow;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.StatementInspection;
import com.siyeh.ig.psiutils.BoolUtils;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
public class ConstantIfStatementInspection extends StatementInspection {
public String getDisplayName() {
return InspectionGadgetsBundle.message(
"constant.if.statement.display.name");
}
public String getGroupDisplayName() {
return GroupNames.CONTROL_FLOW_GROUP_NAME;
}
public boolean isEnabledByDefault() {
return true;
}
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"constant.if.statement.problem.descriptor");
}
public BaseInspectionVisitor buildVisitor() {
return new ConstantIfStatementVisitor();
}
public InspectionGadgetsFix buildFix(PsiElement location) {
//if (PsiUtil.isInJspFile(location)) {
// return null;
//}
return new ConstantIfStatementFix();
}
private static class ConstantIfStatementFix extends InspectionGadgetsFix {
@NotNull
public String getName() {
return InspectionGadgetsBundle.message(
"constant.conditional.expression.simplify.quickfix");
}
public void doFix(Project project, ProblemDescriptor descriptor)
throws IncorrectOperationException {
final PsiElement ifKeyword = descriptor.getPsiElement();
final PsiIfStatement statement =
(PsiIfStatement)ifKeyword.getParent();
assert statement != null;
final PsiStatement thenBranch = statement.getThenBranch();
final PsiStatement elseBranch = statement.getElseBranch();
final PsiExpression condition = statement.getCondition();
if (BoolUtils.isFalse(condition)) {
if (elseBranch != null) {
replaceStatementWithUnwrapping(elseBranch, statement);
} else {
deleteElement(statement);
}
} else {
replaceStatementWithUnwrapping(thenBranch, statement);
}
}
private static void replaceStatementWithUnwrapping(
PsiStatement branch, PsiIfStatement statement)
throws IncorrectOperationException {
if (branch instanceof PsiBlockStatement &&
!(statement.getParent() instanceof PsiIfStatement)) {
final PsiCodeBlock parentBlock =
PsiTreeUtil.getParentOfType(branch, PsiCodeBlock.class);
if (parentBlock == null) {
final String elseText = branch.getText();
replaceStatement(statement, elseText);
return;
}
final PsiCodeBlock block =
((PsiBlockStatement)branch).getCodeBlock();
final boolean hasConflicts =
containsConflictingDeclarations(block, parentBlock);
if (hasConflicts) {
final String elseText = branch.getText();
replaceStatement(statement, elseText);
} else {
final PsiElement containingElement = statement.getParent();
final PsiElement[] children = block.getChildren();
if (children.length > 2) {
assert containingElement != null;
final PsiElement added =
containingElement.addRangeBefore(children[1],
children[children.length - 2],
statement);
final PsiManager manager = statement.getManager();
final Project project = manager.getProject();
final CodeStyleManager codeStyleManager =
CodeStyleManager.getInstance(project);
codeStyleManager.reformat(added);
statement.delete();
}
}
} else {
final String elseText = branch.getText();
replaceStatement(statement, elseText);
}
}
private static boolean containsConflictingDeclarations(
PsiCodeBlock block, PsiCodeBlock parentBlock) {
final PsiStatement[] statements = block.getStatements();
final Set<PsiElement> declaredVars = new HashSet<PsiElement>();
for (final PsiStatement statement : statements) {
if (statement instanceof PsiDeclarationStatement) {
final PsiDeclarationStatement declaration =
(PsiDeclarationStatement)statement;
final PsiElement[] vars = declaration.getDeclaredElements();
for (PsiElement var : vars) {
if (var instanceof PsiLocalVariable) {
declaredVars.add(var);
}
}
}
}
for (Object declaredVar : declaredVars) {
final PsiLocalVariable variable =
(PsiLocalVariable)declaredVar;
final String variableName = variable.getName();
if (conflictingDeclarationExists(variableName, parentBlock,
block)) {
return true;
}
}
return false;
}
private static boolean conflictingDeclarationExists(
String name, PsiCodeBlock parentBlock,
PsiCodeBlock exceptBlock) {
final ConflictingDeclarationVisitor visitor =
new ConflictingDeclarationVisitor(name, exceptBlock);
parentBlock.accept(visitor);
return visitor.hasConflictingDeclaration();
}
}
private static class ConstantIfStatementVisitor
extends BaseInspectionVisitor {
public void visitIfStatement(PsiIfStatement statement) {
super.visitIfStatement(statement);
final PsiExpression condition = statement.getCondition();
if (condition == null) {
return;
}
final PsiStatement thenBranch = statement.getThenBranch();
if (thenBranch == null) {
return;
}
if (BoolUtils.isTrue(condition) || BoolUtils.isFalse(condition)) {
registerStatementError(statement);
}
}
}
private static class ConflictingDeclarationVisitor
extends PsiRecursiveElementVisitor {
private final String variableName;
private final PsiCodeBlock exceptBlock;
private boolean hasConflictingDeclaration = false;
ConflictingDeclarationVisitor(String variableName,
PsiCodeBlock exceptBlock) {
super();
this.variableName = variableName;
this.exceptBlock = exceptBlock;
}
public void visitElement(@NotNull PsiElement element) {
if (!hasConflictingDeclaration) {
super.visitElement(element);
}
}
public void visitCodeBlock(PsiCodeBlock block) {
if (hasConflictingDeclaration) {
return;
}
if (block.equals(exceptBlock)) {
return;
}
super.visitCodeBlock(block);
}
public void visitVariable(PsiVariable variable) {
if (hasConflictingDeclaration) {
return;
}
super.visitVariable(variable);
final String name = variable.getName();
if (name != null && name.equals(variableName)) {
hasConflictingDeclaration = true;
}
}
public boolean hasConflictingDeclaration() {
return hasConflictingDeclaration;
}
}
} | plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/ConstantIfStatementInspection.java | /*
* Copyright 2003-2006 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.controlflow;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.StatementInspection;
import com.siyeh.ig.psiutils.BoolUtils;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
public class ConstantIfStatementInspection extends StatementInspection {
public String getDisplayName() {
return InspectionGadgetsBundle.message(
"constant.if.statement.display.name");
}
public String getGroupDisplayName() {
return GroupNames.CONTROL_FLOW_GROUP_NAME;
}
public boolean isEnabledByDefault() {
return true;
}
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message(
"constant.if.statement.problem.descriptor");
}
public BaseInspectionVisitor buildVisitor() {
return new ConstantIfStatementVisitor();
}
public InspectionGadgetsFix buildFix(PsiElement location) {
//if (PsiUtil.isInJspFile(location)) {
// return null;
//}
return new ConstantIfStatementFix();
}
private static class ConstantIfStatementFix extends InspectionGadgetsFix {
public String getName() {
return InspectionGadgetsBundle.message(
"constant.conditional.expression.simplify.quickfix");
}
public void doFix(Project project, ProblemDescriptor descriptor)
throws IncorrectOperationException {
final PsiElement ifKeyword = descriptor.getPsiElement();
final PsiIfStatement statement =
(PsiIfStatement)ifKeyword.getParent();
assert statement != null;
final PsiStatement thenBranch = statement.getThenBranch();
final PsiStatement elseBranch = statement.getElseBranch();
final PsiExpression condition = statement.getCondition();
if (BoolUtils.isFalse(condition)) {
if (elseBranch != null) {
replaceStatementWithUnwrapping(elseBranch, statement);
} else {
deleteElement(statement);
}
} else {
replaceStatementWithUnwrapping(thenBranch, statement);
}
}
private static void replaceStatementWithUnwrapping(
PsiStatement branch, PsiIfStatement statement)
throws IncorrectOperationException {
if (branch instanceof PsiBlockStatement) {
final PsiCodeBlock parentBlock =
PsiTreeUtil.getParentOfType(branch, PsiCodeBlock.class);
if (parentBlock == null) {
final String elseText = branch.getText();
replaceStatement(statement, elseText);
return;
}
final PsiCodeBlock block =
((PsiBlockStatement)branch).getCodeBlock();
final boolean hasConflicts =
containsConflictingDeclarations(block, parentBlock);
if (hasConflicts) {
final String elseText = branch.getText();
replaceStatement(statement, elseText);
} else {
final PsiElement containingElement = statement.getParent();
final PsiElement[] children = block.getChildren();
if (children.length > 2) {
assert containingElement != null;
final PsiElement added =
containingElement.addRangeBefore(children[1],
children[children .length - 2],
statement);
final PsiManager manager = statement.getManager();
final Project project = manager.getProject();
final CodeStyleManager codeStyleManager =
CodeStyleManager.getInstance(project);
codeStyleManager.reformat(added);
statement.delete();
}
}
} else {
final String elseText = branch.getText();
replaceStatement(statement, elseText);
}
}
private static boolean containsConflictingDeclarations(
PsiCodeBlock block, PsiCodeBlock parentBlock) {
final PsiStatement[] statements = block.getStatements();
final Set<PsiElement> declaredVars = new HashSet<PsiElement>();
for (final PsiStatement statement : statements) {
if (statement instanceof PsiDeclarationStatement) {
final PsiDeclarationStatement declaration =
(PsiDeclarationStatement)statement;
final PsiElement[] vars = declaration.getDeclaredElements();
for (PsiElement var : vars) {
if (var instanceof PsiLocalVariable) {
declaredVars.add(var);
}
}
}
}
for (Object declaredVar : declaredVars) {
final PsiLocalVariable variable =
(PsiLocalVariable)declaredVar;
final String variableName = variable.getName();
if (conflictingDeclarationExists(variableName, parentBlock,
block)) {
return true;
}
}
return false;
}
private static boolean conflictingDeclarationExists(
String name, PsiCodeBlock parentBlock,
PsiCodeBlock exceptBlock) {
final ConflictingDeclarationVisitor visitor =
new ConflictingDeclarationVisitor(name, exceptBlock);
parentBlock.accept(visitor);
return visitor.hasConflictingDeclaration();
}
}
private static class ConstantIfStatementVisitor
extends BaseInspectionVisitor {
public void visitIfStatement(PsiIfStatement statement) {
super.visitIfStatement(statement);
final PsiExpression condition = statement.getCondition();
if (condition == null) {
return;
}
final PsiStatement thenBranch = statement.getThenBranch();
if (thenBranch == null) {
return;
}
if (BoolUtils.isTrue(condition) || BoolUtils.isFalse(condition)) {
registerStatementError(statement);
}
}
}
private static class ConflictingDeclarationVisitor
extends PsiRecursiveElementVisitor {
private final String variableName;
private final PsiCodeBlock exceptBlock;
private boolean hasConflictingDeclaration = false;
ConflictingDeclarationVisitor(String variableName,
PsiCodeBlock exceptBlock) {
super();
this.variableName = variableName;
this.exceptBlock = exceptBlock;
}
public void visitElement(@NotNull PsiElement element) {
if (!hasConflictingDeclaration) {
super.visitElement(element);
}
}
public void visitCodeBlock(PsiCodeBlock block) {
if (hasConflictingDeclaration) {
return;
}
if (block.equals(exceptBlock)) {
return;
}
super.visitCodeBlock(block);
}
public void visitVariable(PsiVariable variable) {
if (hasConflictingDeclaration) {
return;
}
super.visitVariable(variable);
final String name = variable.getName();
if (name != null && name.equals(variableName)) {
hasConflictingDeclaration = true;
}
}
public boolean hasConflictingDeclaration() {
return hasConflictingDeclaration;
}
}
} | IDEADEV-6232 | plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/ConstantIfStatementInspection.java | IDEADEV-6232 | <ide><path>lugins/InspectionGadgets/src/com/siyeh/ig/controlflow/ConstantIfStatementInspection.java
<ide> import com.intellij.openapi.project.Project;
<ide> import com.intellij.psi.*;
<ide> import com.intellij.psi.codeStyle.CodeStyleManager;
<del>import com.intellij.psi.jsp.JspFile;
<ide> import com.intellij.psi.util.PsiTreeUtil;
<del>import com.intellij.psi.util.PsiUtil;
<ide> import com.intellij.util.IncorrectOperationException;
<ide> import com.siyeh.InspectionGadgetsBundle;
<ide> import com.siyeh.ig.BaseInspectionVisitor;
<ide>
<ide> private static class ConstantIfStatementFix extends InspectionGadgetsFix {
<ide>
<add> @NotNull
<ide> public String getName() {
<ide> return InspectionGadgetsBundle.message(
<ide> "constant.conditional.expression.simplify.quickfix");
<ide> private static void replaceStatementWithUnwrapping(
<ide> PsiStatement branch, PsiIfStatement statement)
<ide> throws IncorrectOperationException {
<del> if (branch instanceof PsiBlockStatement) {
<add> if (branch instanceof PsiBlockStatement &&
<add> !(statement.getParent() instanceof PsiIfStatement)) {
<ide> final PsiCodeBlock parentBlock =
<ide> PsiTreeUtil.getParentOfType(branch, PsiCodeBlock.class);
<ide> if (parentBlock == null) {
<ide> assert containingElement != null;
<ide> final PsiElement added =
<ide> containingElement.addRangeBefore(children[1],
<del> children[children .length - 2],
<add> children[children.length - 2],
<ide> statement);
<ide> final PsiManager manager = statement.getManager();
<ide> final Project project = manager.getProject(); |
|
Java | apache-2.0 | c9921175b50d56d932c6b721edb780aa9b566756 | 0 | flipkart-incubator/Lego | /*
* Copyright 2015 Flipkart Internet, pvt ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flipkart.lego;
import flipkart.lego.api.entities.*;
import flipkart.lego.api.exceptions.*;
import flipkart.lego.engine.Lego;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.testng.Assert.assertTrue;
public class LegoTest {
Request request;
Response response;
Buildable buildable;
LegoSet legoSet;
Lego lego;
Map<String, DataSource> dataSourceMap;
DataSource dataSource;
ExecutorService executorService = Executors.newCachedThreadPool();
class DummyDT implements DataType {
@Override
public String getShortDescription() {
return null;
}
public String getResponse() {
return "Some ds response";
}
@Override
public String getDescription() {
return null;
}
}
DataType dataType = new DummyDT();
Filter sleepingFilter = new Filter() {
@Override
public String getShortDescription() {
return null;
}
@Override
public String getDescription() {
return null;
}
@Override
public void filterRequest(Request request, Response response1) throws InternalErrorException, BadRequestException {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
throw new InternalErrorException(e);
}
}
@Override
public void filterResponse(Request request, Response response) throws InternalErrorException, BadRequestException, ProcessingException {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
throw new InternalErrorException(e);
}
}
@Override
public String getId() throws UnsupportedOperationException {
return null;
}
@Override
public String getName() throws UnsupportedOperationException {
return null;
}
@Override
public List<Integer> getVersion() throws UnsupportedOperationException {
return null;
}
};
@BeforeMethod
public void setUp() {
legoSet = Mockito.mock(LegoSet.class);
buildable = Mockito.mock(Buildable.class);
lego = new Lego(legoSet, executorService, executorService);
dataSourceMap = new HashMap<>();
dataSource = Mockito.mock(DataSource.class);
dataSourceMap.put("sample", dataSource);
}
//this tests the buildResponse function and it's response to LegoSet.getBuildable
@Test(groups = "a")
public void testGetBuildableElement() throws Exception {
LegoSet legoSetWithoutElements = Mockito.mock(LegoSet.class);
LegoSet legoSetFaulty = Mockito.mock(LegoSet.class);
boolean elementNotFoundExceptionThrown = false;
boolean internalErrorExceptionThrown = false;
//First setup the case where everything is supposed to work fine.
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getTimeout()).thenReturn(300l);
Lego lego = new Lego(legoSet, executorService, executorService);
lego.buildResponse(request, response);
Mockito.verify(buildable).getRequiredDataSources(request);
//Next test the case where element is not found
Mockito.when(legoSetWithoutElements.getBuildable(request)).thenThrow(new ElementNotFoundException());
lego = new Lego(legoSetWithoutElements, executorService, executorService);
try {
lego.buildResponse(request, response);
} catch (ElementNotFoundException exception) {
elementNotFoundExceptionThrown = true;
}
assert elementNotFoundExceptionThrown;
Mockito.verify(buildable, Mockito.atMost(1)).getRequiredDataSources(request);
//Next test the case where legoSet screws up or is faulty
Mockito.when(legoSetFaulty.getBuildable(request)).thenThrow(new LegoSetException());
lego = new Lego(legoSetFaulty, executorService, executorService);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert internalErrorExceptionThrown;
Mockito.verify(buildable, Mockito.atMost(1)).getRequiredDataSources(request);
}
//this tests the buildResponse function and it's response to LegoSet.getRequiredDataSources
@Test(groups = "a")
public void testGetRequiredDataSources() throws Exception {
Lego lego = new Lego(legoSet, executorService, executorService);
boolean internalErrorExceptionThrown = false;
//Setting up the case where getRequireDataSources returns valid data
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getTimeout()).thenReturn(300l);
Mockito.when(buildable.getRequiredDataSources(request)).thenReturn(dataSourceMap);
try {
lego.buildResponse(request, response);
} catch (Exception e) {
}
Mockito.verify(buildable).getOptionalDataSources(request);
//Setting up the case where getRequiredDataSources throws and internalErrorException
Mockito.when(buildable.getRequiredDataSources(request)).thenThrow(new InternalErrorException());
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert internalErrorExceptionThrown;
}
//this tests the buildResponse function and it's response to LegoSet.getOptionalDataSources
@Test(groups = "a")
public void testGetOptionalDataSources() throws Exception {
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getRequiredDataSources(request)).thenReturn(dataSourceMap);
boolean legoExceptionThrown = false;
//Setting up the case where optional data sources are given without issue
Mockito.when(buildable.getOptionalDataSources(request)).thenReturn(dataSourceMap);
try {
lego.buildResponse(request, response);
} catch (Exception e) {
}
Mockito.verify(buildable, Mockito.atLeastOnce()).getTimeout();
//Setting up the case where optional data sources throws exception
Mockito.when(buildable.getOptionalDataSources(request)).thenThrow(new LegoException());
try {
lego.buildResponse(request, response);
} catch (Exception e) {
}
Mockito.verify(buildable, Mockito.atLeast(2)).getTimeout();
}
//this tests the buildResponse function and it's dispatch data sources function
@Test(groups = "a")
public void testDispatchDataSources() throws Exception {
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getTimeout()).thenReturn(200l);
Mockito.when(buildable.getRequiredDataSources(request)).thenReturn(dataSourceMap);
Mockito.when(buildable.getOptionalDataSources(request)).thenReturn(dataSourceMap);
Mockito.when(buildable.getFilters(request)).thenReturn(new LinkedHashSet<Filter>());
Mockito.when(dataSource.call()).thenReturn(dataType);
Map<String, Object> stringMap = new HashMap<>();
stringMap.put("sample", dataType);
try {
lego.buildResponse(request, response);
} catch (Exception e) {
System.out.println(e);
}
Mockito.verify(buildable, Mockito.atLeastOnce()).build(request, response, stringMap);
}
//Testing whether buildResponse function times out appropriately and throws internal server exception
@Test(groups = "b", dependsOnGroups = "a")
public void testDataSourceTimeout() throws Exception {
class SampleDataSource implements DataSource {
public DataType call() {
try {
Thread.sleep(3000);
} catch (Exception e) {
}
return dataType;
}
@Override
public String getId() throws UnsupportedOperationException {
return null;
}
@Override
public String getName() throws UnsupportedOperationException {
return null;
}
@Override
public List<Integer> getVersion() throws UnsupportedOperationException {
return null;
}
@Override
public String getShortDescription() {
return null;
}
@Override
public String getDescription() {
return null;
}
}
boolean internalErrorExceptionThrown = false;
DataSource dataSource1 = new SampleDataSource();
Map<String, DataSource> dataSourceMap1 = new HashMap<>();
dataSourceMap1.put("sample", dataSource1);
LegoSet legoSet1 = Mockito.mock(LegoSet.class);
Buildable buildable1 = Mockito.mock(Buildable.class);
lego = new Lego(legoSet1, executorService, executorService);
Mockito.when(legoSet1.getBuildable(request)).thenReturn(buildable1);
Mockito.when(buildable1.getRequiredDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getOptionalDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getTimeout()).thenReturn(5000l);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert !internalErrorExceptionThrown;
Mockito.when(buildable1.getTimeout()).thenReturn(1000l);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert internalErrorExceptionThrown;
Mockito.verify(buildable1, Mockito.atLeastOnce()).getRequiredDataSources(request);
Mockito.verify(buildable1, Mockito.atLeastOnce()).getOptionalDataSources(request);
internalErrorExceptionThrown = false;
Mockito.reset(buildable1);
LinkedHashSet<Filter> filters = new LinkedHashSet<>();
filters.add(sleepingFilter);
Mockito.when(buildable1.getRequiredDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getOptionalDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getTimeout()).thenReturn(1000l);
Mockito.when(buildable1.getFilters(request)).thenReturn(filters);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assertTrue(internalErrorExceptionThrown);
Mockito.verify(buildable1, Mockito.never()).getRequiredDataSources(request);
}
}
| src/test/java/flipkart/lego/LegoTest.java | /*
* Copyright 2015 Flipkart Internet, pvt ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flipkart.lego;
import flipkart.lego.api.entities.*;
import flipkart.lego.api.exceptions.*;
import flipkart.lego.engine.Lego;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.testng.Assert.assertTrue;
public class LegoTest {
Request request;
Response response;
Buildable buildable;
LegoSet legoSet;
Lego lego;
Map<String, DataSource> dataSourceMap;
DataSource dataSource;
ExecutorService executorService = Executors.newCachedThreadPool();
class DummyDT implements DataType {
@Override
public String getShortDescription() {
return null;
}
public String getResponse() {
return "Some ds response";
}
@Override
public String getDescription() {
return null;
}
@Override
public String getId() throws UnsupportedOperationException {
return null;
}
@Override
public String getName() throws UnsupportedOperationException {
return null;
}
@Override
public List<Integer> getVersion() {
return null;
}
}
DataType dataType = new DummyDT();
Filter sleepingFilter = new Filter() {
@Override
public String getShortDescription() {
return null;
}
@Override
public String getDescription() {
return null;
}
@Override
public void filterRequest(Request request, Response response1) throws InternalErrorException, BadRequestException {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
throw new InternalErrorException(e);
}
}
@Override
public void filterResponse(Request request, Response response) throws InternalErrorException, BadRequestException, ProcessingException {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
throw new InternalErrorException(e);
}
}
@Override
public String getId() throws UnsupportedOperationException {
return null;
}
@Override
public String getName() throws UnsupportedOperationException {
return null;
}
@Override
public List<Integer> getVersion() throws UnsupportedOperationException {
return null;
}
};
@BeforeMethod
public void setUp() {
legoSet = Mockito.mock(LegoSet.class);
buildable = Mockito.mock(Buildable.class);
lego = new Lego(legoSet, executorService, executorService);
dataSourceMap = new HashMap<>();
dataSource = Mockito.mock(DataSource.class);
dataSourceMap.put("sample", dataSource);
}
//this tests the buildResponse function and it's response to LegoSet.getBuildable
@Test(groups = "a")
public void testGetBuildableElement() throws Exception {
LegoSet legoSetWithoutElements = Mockito.mock(LegoSet.class);
LegoSet legoSetFaulty = Mockito.mock(LegoSet.class);
boolean elementNotFoundExceptionThrown = false;
boolean internalErrorExceptionThrown = false;
//First setup the case where everything is supposed to work fine.
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getTimeout()).thenReturn(300l);
Lego lego = new Lego(legoSet, executorService, executorService);
lego.buildResponse(request, response);
Mockito.verify(buildable).getRequiredDataSources(request);
//Next test the case where element is not found
Mockito.when(legoSetWithoutElements.getBuildable(request)).thenThrow(new ElementNotFoundException());
lego = new Lego(legoSetWithoutElements, executorService, executorService);
try {
lego.buildResponse(request, response);
} catch (ElementNotFoundException exception) {
elementNotFoundExceptionThrown = true;
}
assert elementNotFoundExceptionThrown;
Mockito.verify(buildable, Mockito.atMost(1)).getRequiredDataSources(request);
//Next test the case where legoSet screws up or is faulty
Mockito.when(legoSetFaulty.getBuildable(request)).thenThrow(new LegoSetException());
lego = new Lego(legoSetFaulty, executorService, executorService);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert internalErrorExceptionThrown;
Mockito.verify(buildable, Mockito.atMost(1)).getRequiredDataSources(request);
}
//this tests the buildResponse function and it's response to LegoSet.getRequiredDataSources
@Test(groups = "a")
public void testGetRequiredDataSources() throws Exception {
Lego lego = new Lego(legoSet, executorService, executorService);
boolean internalErrorExceptionThrown = false;
//Setting up the case where getRequireDataSources returns valid data
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getTimeout()).thenReturn(300l);
Mockito.when(buildable.getRequiredDataSources(request)).thenReturn(dataSourceMap);
try {
lego.buildResponse(request, response);
} catch (Exception e) {
}
Mockito.verify(buildable).getOptionalDataSources(request);
//Setting up the case where getRequiredDataSources throws and internalErrorException
Mockito.when(buildable.getRequiredDataSources(request)).thenThrow(new InternalErrorException());
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert internalErrorExceptionThrown;
}
//this tests the buildResponse function and it's response to LegoSet.getOptionalDataSources
@Test(groups = "a")
public void testGetOptionalDataSources() throws Exception {
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getRequiredDataSources(request)).thenReturn(dataSourceMap);
boolean legoExceptionThrown = false;
//Setting up the case where optional data sources are given without issue
Mockito.when(buildable.getOptionalDataSources(request)).thenReturn(dataSourceMap);
try {
lego.buildResponse(request, response);
} catch (Exception e) {
}
Mockito.verify(buildable, Mockito.atLeastOnce()).getTimeout();
//Setting up the case where optional data sources throws exception
Mockito.when(buildable.getOptionalDataSources(request)).thenThrow(new LegoException());
try {
lego.buildResponse(request, response);
} catch (Exception e) {
}
Mockito.verify(buildable, Mockito.atLeast(2)).getTimeout();
}
//this tests the buildResponse function and it's dispatch data sources function
@Test(groups = "a")
public void testDispatchDataSources() throws Exception {
Mockito.when(legoSet.getBuildable(request)).thenReturn(buildable);
Mockito.when(buildable.getTimeout()).thenReturn(200l);
Mockito.when(buildable.getRequiredDataSources(request)).thenReturn(dataSourceMap);
Mockito.when(buildable.getOptionalDataSources(request)).thenReturn(dataSourceMap);
Mockito.when(buildable.getFilters(request)).thenReturn(new LinkedHashSet<Filter>());
Mockito.when(dataSource.call()).thenReturn(dataType);
Map<String, Object> stringMap = new HashMap<>();
stringMap.put("sample", dataType);
try {
lego.buildResponse(request, response);
} catch (Exception e) {
System.out.println(e);
}
Mockito.verify(buildable, Mockito.atLeastOnce()).build(request, response, stringMap);
}
//Testing whether buildResponse function times out appropriately and throws internal server exception
@Test(groups = "b", dependsOnGroups = "a")
public void testDataSourceTimeout() throws Exception {
class SampleDataSource implements DataSource {
public DataType call() {
try {
Thread.sleep(3000);
} catch (Exception e) {
}
return dataType;
}
@Override
public String getId() throws UnsupportedOperationException {
return null;
}
@Override
public String getName() throws UnsupportedOperationException {
return null;
}
@Override
public List<Integer> getVersion() throws UnsupportedOperationException {
return null;
}
@Override
public String getShortDescription() {
return null;
}
@Override
public String getDescription() {
return null;
}
}
boolean internalErrorExceptionThrown = false;
DataSource dataSource1 = new SampleDataSource();
Map<String, DataSource> dataSourceMap1 = new HashMap<>();
dataSourceMap1.put("sample", dataSource1);
LegoSet legoSet1 = Mockito.mock(LegoSet.class);
Buildable buildable1 = Mockito.mock(Buildable.class);
lego = new Lego(legoSet1, executorService, executorService);
Mockito.when(legoSet1.getBuildable(request)).thenReturn(buildable1);
Mockito.when(buildable1.getRequiredDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getOptionalDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getTimeout()).thenReturn(5000l);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert !internalErrorExceptionThrown;
Mockito.when(buildable1.getTimeout()).thenReturn(1000l);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assert internalErrorExceptionThrown;
Mockito.verify(buildable1, Mockito.atLeastOnce()).getRequiredDataSources(request);
Mockito.verify(buildable1, Mockito.atLeastOnce()).getOptionalDataSources(request);
internalErrorExceptionThrown = false;
Mockito.reset(buildable1);
LinkedHashSet<Filter> filters = new LinkedHashSet<>();
filters.add(sleepingFilter);
Mockito.when(buildable1.getRequiredDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getOptionalDataSources(request)).thenReturn(dataSourceMap1);
Mockito.when(buildable1.getTimeout()).thenReturn(1000l);
Mockito.when(buildable1.getFilters(request)).thenReturn(filters);
try {
lego.buildResponse(request, response);
} catch (InternalErrorException exception) {
internalErrorExceptionThrown = true;
}
assertTrue(internalErrorExceptionThrown);
Mockito.verify(buildable1, Mockito.never()).getRequiredDataSources(request);
}
}
| removing overrides methods from test
| src/test/java/flipkart/lego/LegoTest.java | removing overrides methods from test | <ide><path>rc/test/java/flipkart/lego/LegoTest.java
<ide> public String getDescription() {
<ide> return null;
<ide> }
<del>
<del> @Override
<del> public String getId() throws UnsupportedOperationException {
<del> return null;
<del> }
<del>
<del> @Override
<del> public String getName() throws UnsupportedOperationException {
<del> return null;
<del> }
<del>
<del> @Override
<del> public List<Integer> getVersion() {
<del> return null;
<del> }
<ide> }
<ide>
<ide> DataType dataType = new DummyDT(); |
|
JavaScript | apache-2.0 | 252831a6354d723023d5563f19ffe5e81c5618e6 | 0 | ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas | //
// Copyright 2016 Ilkka Oksanen <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const TYPES = {
mas: 'm',
irc: 'i'
};
module.exports = class UserGId {
static create(params = {}) {
let options = {};
if (typeof(params) === 'string') {
options = {
id: parseInt(params.substring(1)),
type: Object.keys(TYPES).find(validType => TYPES[validType] === params[0])
};
} else if (typeof(params) === 'object') {
options = params;
}
const userGId = new this(options);
return userGId.valid ? userGId : null;
}
constructor({ id, type }) {
this.id = id;
this.type = type;
this.valid = !!(id >= 0 && TYPES[type]);
}
isMASUser() {
return this.type === 'mas';
}
isIrcUser() {
return this.type === 'irc';
}
toString() {
return `${TYPES[this.type]}${this.id}`;
}
equals(otherUserGId) {
return this.id === otherUserGId.id && this.type === otherUserGId.type;
}
};
| server/models/userGId.js | //
// Copyright 2016 Ilkka Oksanen <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const TYPES = {
mas: 'm',
irc: 'i'
};
module.exports = class UserGId {
static create(params = {}) {
let options = {};
if (typeof(params) === 'string') {
options = {
id: parseInt(params.substring(1)),
type: Object.keys(TYPES).find(validType => TYPES[validType] === params[0])
};
} else if (typeof(params) === 'object') {
options = params;
}
const userGId = new this(options);
return userGId.valid ? userGId : null;
}
constructor({ id, type }) {
this.id = id;
this.type = type;
this.valid = id >= 0 && TYPES[type];
}
isMASUser() {
return this.type === 'mas';
}
isIrcUser() {
return this.type === 'irc';
}
toString() {
return `${TYPES[this.type]}${this.id}`;
}
equals(otherUserGId) {
return this.id === otherUserGId.id && this.type === otherUserGId.type;
}
};
| userGId.valid should be boolean
| server/models/userGId.js | userGId.valid should be boolean | <ide><path>erver/models/userGId.js
<ide> constructor({ id, type }) {
<ide> this.id = id;
<ide> this.type = type;
<del> this.valid = id >= 0 && TYPES[type];
<add> this.valid = !!(id >= 0 && TYPES[type]);
<ide> }
<ide>
<ide> isMASUser() { |
|
Java | apache-2.0 | ccd8ab424e9faadaf1d5f8d76986816b250d5e2a | 0 | alien4cloud/alien4cloud,alien4cloud/alien4cloud,alien4cloud/alien4cloud,alien4cloud/alien4cloud | package alien4cloud.purge;
import alien4cloud.dao.ESGenericSearchDAO;
import alien4cloud.dao.ESIndexMapper;
import alien4cloud.dao.ElasticSearchDAO;
import alien4cloud.dao.MonitorESDAO;
import alien4cloud.dao.model.GetMultipleDataResult;
import alien4cloud.events.DeploymentUndeployedEvent;
import alien4cloud.model.deployment.Deployment;
import alien4cloud.model.deployment.DeploymentTopology;
import alien4cloud.model.deployment.DeploymentUnprocessedTopology;
import alien4cloud.model.runtime.Execution;
import alien4cloud.model.runtime.Task;
import alien4cloud.model.runtime.WorkflowStepInstance;
import alien4cloud.paas.model.*;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.apache.lucene.util.NamedThreadFactory;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@Slf4j
@Component
public class PurgeService {
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("a4c-purge-service"));
@Inject
ElasticSearchDAO commonDao;
@Inject
MonitorESDAO monitorDao;
/**
* In hours, time to wait between the end of an execution and the start of the next execution.
*/
@Value("${purge.period:24}")
private Integer period;
/**
* Maximum number of deployments to purge at each purge execution.
*/
@Value("${purge.threshold:1000}")
private Integer threshold;
/**
* TTL in hours : the TTL since the endDate of the deployment (when endDate is defined).
*/
@Value("${purge.ttl:240}")
private Integer ttl;
/**
* The maximum number of IDs to delete a each bulk delete request.
*/
@Value("${purge.batch:1000}")
private Integer batch;
@PostConstruct
private void init() {
long periodInSeconds = (period * 60 * 60) + 1; //(+1 just to avoid 0 since delay can not == 0)
log.info("Purge job will be executed with a period of {} seconds (delay between end of execution and start of next execution)", periodInSeconds);
executorService.scheduleWithFixedDelay(this::run, 30, periodInSeconds, TimeUnit.SECONDS);
}
@PreDestroy
private void destroy() {
executorService.shutdown();
try {
executorService.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
}
}
private class PurgeContext {
private final BiConsumer<Class<?>,Collection<String>> callback;
private final MultiValuedMap<Class<?>,String> map = new HashSetValuedHashMap<>();
private Map<Class<?>, Integer> stats = Maps.newHashMap();
protected PurgeContext(BiConsumer<Class<?>,Collection<String>> callback) {
this.callback = callback;
}
public <T> void add(Class<T> clazz, String id) {
map.put(clazz,id);
Collection<String> ids = map.get(clazz);
if (ids.size() == batch) {
callback.accept(clazz,ids);
addStat(clazz, ids.size());
map.remove(clazz);
}
}
public void flush() {
for (Class<?> clazz : map.keySet()) {
Collection<String> ids = map.get(clazz);
callback.accept(clazz, ids);
addStat(clazz, ids.size());
}
map.clear();
}
public void addStat(Class<?> clazz, int nbOfItems) {
Integer count = stats.get(clazz);
if (count == null) {
stats.put(clazz, nbOfItems);
} else {
stats.put(clazz, count + nbOfItems);
}
}
public void logStats() {
stats.forEach((aClass, count) -> {
ESGenericSearchDAO dao = getDaoFor(aClass);
String[] indexName = dao.getIndexForType(aClass);
log.info("=> Purge has deleted {} entries in index {}", count, indexName);
});
}
}
private void run() {
try {
PurgeContext context = new PurgeContext(this::bulkDelete);
long date = Calendar.getInstance().getTime().getTime() - (ttl * 60 * 60 * 1000);
log.info("=> Start of deployments purge : TTL is {} (expiration date for this run : {}), considering {} deployments at each run, bulk delete batch size is {}", ttl, new Date(date), threshold, batch);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.existsQuery("endDate"))
.must(QueryBuilders.rangeQuery("endDate").lte(date));
GetMultipleDataResult<Deployment> deployments = commonDao.search(Deployment.class, null, null, queryBuilder, null, 0, threshold);
if (log.isDebugEnabled()) {
log.debug("=> {} deployments candidates for purge", deployments.getData().length);
}
if (deployments.getData().length >0) {
for (Deployment d : deployments.getData()) {
fullPurge(context, d.getId());
}
// Flush pending deletes
context.flush();
// Delete deployments
Collection<String> ids = Arrays.stream(deployments.getData()).map(Deployment::getId).collect(Collectors.toList());
bulkDelete(Deployment.class,ids);
context.addStat(Deployment.class, ids.size());
if (log.isDebugEnabled()) {
log.debug("=> End of deployments purge");
}
context.logStats();
}
} catch(RuntimeException e) {
log.error("Exception during purge:",e);
}
}
private void fullPurge(PurgeContext context,String id) {
if (log.isTraceEnabled()) {
log.trace("=> Purging Deployment {}", id);
}
context.add(DeploymentTopology.class,id);
purge(context, id, WorkflowStepInstance.class);
purge(context,id,TaskFailedEvent.class);
purge(context,id,TaskSentEvent.class);
purge(context,id,TaskStartedEvent.class);
purge(context,id,TaskCancelledEvent.class);
purge(context,id,TaskSucceededEvent.class);
purge(context,id, WorkflowStepStartedEvent.class);
purge(context,id, WorkflowStepCompletedEvent.class);
purge(context,id, PaaSWorkflowSucceededEvent.class);
purge(context,id, PaaSWorkflowStartedEvent.class);
purge(context,id, PaaSWorkflowCancelledEvent.class);
purge(context,id, PaaSWorkflowFailedEvent.class);
purge(context,id,PaaSDeploymentStatusMonitorEvent.class);
purge(context,id, PaaSInstanceStateMonitorEvent.class);
purge(context,id,Task.class);
purge(context,id,Execution.class);
purge(context,id,PaaSDeploymentLog.class);
purge(context,id,DeploymentUnprocessedTopology.class);
}
private void purge(PurgeContext context, String id) {
purge(context, id, WorkflowStepInstance.class);
purge(context,id,TaskFailedEvent.class);
purge(context,id,TaskSentEvent.class);
purge(context,id,TaskStartedEvent.class);
purge(context,id,TaskCancelledEvent.class);
purge(context,id,TaskSucceededEvent.class);
purge(context,id, WorkflowStepStartedEvent.class);
purge(context,id, WorkflowStepCompletedEvent.class);
purge(context,id, PaaSWorkflowSucceededEvent.class);
purge(context,id, PaaSWorkflowStartedEvent.class);
purge(context,id, PaaSWorkflowCancelledEvent.class);
purge(context,id, PaaSWorkflowFailedEvent.class);
purge(context,id,PaaSDeploymentStatusMonitorEvent.class);
purge(context,id, PaaSInstanceStateMonitorEvent.class);
// Index : DeploymentMonitorEvent
// ------------------------------
// PaaSWorkflowMonitorEvent
// PaaSInstancePersistentResourceMonitorEvent
// PaaSWorkflowStepMonitorEvent
// PaaSMessageMonitorEvent
}
private <T> void purge(PurgeContext context, String id, Class<T> clazz) {
ESGenericSearchDAO dao = getDaoFor(clazz);
String[] indexNames = dao.getIndexForType(clazz);
// Get Id of documents owned by our deployment
SearchRequestBuilder searchRequestBuilder = dao.getClient()
.prepareSearch(indexNames)
.setTypes(ESIndexMapper.TYPE_NAME)
.setQuery(QueryBuilders.termQuery("deploymentId",id))
.setFetchSource(false)
.setFrom(0).setSize(batch);
for (;;) {
SearchResponse response = searchRequestBuilder.execute().actionGet();
if (response.getHits() == null || response.getHits().getHits() == null) break;
for (int i = 0; i < response.getHits().getHits().length; i++) {
context.add(clazz, response.getHits().getHits()[i].getId());
}
// Redo the query if we hit the batch
if (response.getHits().getHits().length < batch) break;
}
}
private <T> ESGenericSearchDAO getDaoFor(Class<T> clazz) {
if (AbstractMonitorEvent.class.isAssignableFrom(clazz)
|| DeploymentTopology.class.isAssignableFrom(clazz)
|| DeploymentUnprocessedTopology.class.isAssignableFrom(clazz)
|| PaaSDeploymentLog.class.isAssignableFrom(clazz)
) {
return monitorDao;
} else {
return commonDao;
}
}
private <T> void bulkDelete(Class<T> clazz,Collection<String> ids) {
ESGenericSearchDAO dao = getDaoFor(clazz);
BulkRequestBuilder bulkRequestBuilder = dao.getClient().prepareBulk().setRefreshPolicy(WriteRequest.RefreshPolicy.NONE);
String[] indexNames = dao.getIndexForType(clazz);
for (String indexName: indexNames) {
if (log.isDebugEnabled()) {
log.debug("BULK DELETE ON {} -> {} items", indexName, ids.size());
}
for (String id : ids) {
DeleteRequestBuilder deleteRequestBuilder = dao.getClient().prepareDelete().setIndex(indexName).setType(ESIndexMapper.TYPE_NAME).setId(id);
bulkRequestBuilder.add(deleteRequestBuilder.request());
}
}
bulkRequestBuilder.execute().actionGet();
}
@EventListener
private void onDeploymentUndeployed(DeploymentUndeployedEvent event) {
PurgeContext context = new PurgeContext(this::bulkDelete);
if (log.isDebugEnabled()) {
log.debug("Cleaning Deployment {}", event.getDeploymentId());
}
purge(context,event.getDeploymentId());
// Flush pending deletes
context.flush();
}
}
| alien4cloud-core/src/main/java/alien4cloud/purge/PurgeService.java | package alien4cloud.purge;
import alien4cloud.dao.ESGenericSearchDAO;
import alien4cloud.dao.ESIndexMapper;
import alien4cloud.dao.ElasticSearchDAO;
import alien4cloud.dao.MonitorESDAO;
import alien4cloud.dao.model.GetMultipleDataResult;
import alien4cloud.events.DeploymentUndeployedEvent;
import alien4cloud.model.deployment.Deployment;
import alien4cloud.model.deployment.DeploymentTopology;
import alien4cloud.model.deployment.DeploymentUnprocessedTopology;
import alien4cloud.model.runtime.Execution;
import alien4cloud.model.runtime.Task;
import alien4cloud.model.runtime.WorkflowStepInstance;
import alien4cloud.paas.model.*;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.apache.lucene.util.NamedThreadFactory;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@Slf4j
@Component
public class PurgeService {
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("a4c-purge-service"));
@Inject
ElasticSearchDAO commonDao;
@Inject
MonitorESDAO monitorDao;
/**
* In hours, time to wait between the end of an execution and the start of the next execution.
*/
@Value("${purge.period:24}")
private Integer period;
/**
* Maximum number of deployments to purge at each purge execution.
*/
@Value("${purge.threshold:1000}")
private Integer threshold;
/**
* TTL in hours : the TTL since the endDate of the deployment (when endDate is defined).
*/
@Value("${purge.ttl:240}")
private Integer ttl;
/**
* The maximum number of IDs to delete a each bulk delete request.
*/
@Value("${purge.batch:1000}")
private Integer batch;
@PostConstruct
private void init() {
long periodInSeconds = (period * 60 * 60) + 1; //(+1 just to avoid 0 since delay can not == 0)
log.info("Purge job will be executed with a period of {} seconds (delay between end of execution and start of next execution)", periodInSeconds);
executorService.scheduleWithFixedDelay(this::run, 30, periodInSeconds, TimeUnit.SECONDS);
}
@PreDestroy
private void destroy() {
executorService.shutdown();
try {
executorService.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException e) {
}
}
private class PurgeContext {
private final BiConsumer<Class<?>,Collection<String>> callback;
private final MultiValuedMap<Class<?>,String> map = new HashSetValuedHashMap<>();
private Map<Class<?>, Integer> stats = Maps.newHashMap();
protected PurgeContext(BiConsumer<Class<?>,Collection<String>> callback) {
this.callback = callback;
}
public <T> void add(Class<T> clazz, String id) {
map.put(clazz,id);
Collection<String> ids = map.get(clazz);
if (ids.size() == batch) {
callback.accept(clazz,ids);
addStat(clazz, ids.size());
map.remove(clazz);
}
}
public void flush() {
for (Class<?> clazz : map.keySet()) {
Collection<String> ids = map.get(clazz);
callback.accept(clazz, ids);
addStat(clazz, ids.size());
}
map.clear();
}
public void addStat(Class<?> clazz, int nbOfItems) {
Integer count = stats.get(clazz);
if (count == null) {
stats.put(clazz, nbOfItems);
} else {
stats.put(clazz, count + nbOfItems);
}
}
public void logStats() {
stats.forEach((aClass, count) -> {
ESGenericSearchDAO dao = getDaoFor(aClass);
String[] indexName = dao.getIndexForType(aClass);
log.info("=> Purge has deleted {} entries in index {}", count, indexName);
});
}
}
private void run() {
try {
PurgeContext context = new PurgeContext(this::bulkDelete);
long date = Calendar.getInstance().getTime().getTime() - (ttl * 60 * 60 * 1000);
log.info("=> Start of deployments purge : TTL is {} (expiration date for this run : {}), considering {} deployments at each run, bulk delete batch size is {}", ttl, new Date(date), threshold, batch);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.existsQuery("endDate"))
.must(QueryBuilders.rangeQuery("endDate").lte(date));
GetMultipleDataResult<Deployment> deployments = commonDao.search(Deployment.class, null, null, queryBuilder, null, 0, threshold);
if (log.isDebugEnabled()) {
log.debug("=> {} deployments candidates for purge", deployments.getData().length);
}
if (deployments.getData().length >0) {
for (Deployment d : deployments.getData()) {
fullPurge(context, d.getId());
}
// Flush pending deletes
context.flush();
// Delete deployments
Collection<String> ids = Arrays.stream(deployments.getData()).map(Deployment::getId).collect(Collectors.toList());
bulkDelete(Deployment.class,ids);
context.addStat(Deployment.class, ids.size());
if (log.isDebugEnabled()) {
log.debug("=> End of deployments purge");
}
context.logStats();
}
} catch(RuntimeException e) {
log.error("Exception during purge:",e);
}
}
private void fullPurge(PurgeContext context,String id) {
if (log.isTraceEnabled()) {
log.trace("=> Purging Deployment {}", id);
}
purge(context,id);
purge(context,id,Task.class);
purge(context,id,Execution.class);
purge(context,id,PaaSDeploymentLog.class);
purge(context,id,DeploymentUnprocessedTopology.class);
}
private void purge(PurgeContext context, String id) {
context.add(DeploymentTopology.class,id);
purge(context, id, WorkflowStepInstance.class);
purge(context,id,TaskFailedEvent.class);
purge(context,id,TaskSentEvent.class);
purge(context,id,TaskStartedEvent.class);
purge(context,id,TaskCancelledEvent.class);
purge(context,id,TaskSucceededEvent.class);
purge(context,id, WorkflowStepStartedEvent.class);
purge(context,id, WorkflowStepCompletedEvent.class);
purge(context,id, PaaSWorkflowSucceededEvent.class);
purge(context,id, PaaSWorkflowStartedEvent.class);
purge(context,id, PaaSWorkflowCancelledEvent.class);
purge(context,id, PaaSWorkflowFailedEvent.class);
purge(context,id,PaaSDeploymentStatusMonitorEvent.class);
purge(context,id, PaaSInstanceStateMonitorEvent.class);
// Index : DeploymentMonitorEvent
// ------------------------------
// PaaSWorkflowMonitorEvent
// PaaSInstancePersistentResourceMonitorEvent
// PaaSWorkflowStepMonitorEvent
// PaaSMessageMonitorEvent
}
private <T> void purge(PurgeContext context, String id, Class<T> clazz) {
ESGenericSearchDAO dao = getDaoFor(clazz);
String[] indexNames = dao.getIndexForType(clazz);
// Get Id of documents owned by our deployment
SearchRequestBuilder searchRequestBuilder = dao.getClient()
.prepareSearch(indexNames)
.setTypes(ESIndexMapper.TYPE_NAME)
.setQuery(QueryBuilders.termQuery("deploymentId",id))
.setFetchSource(false)
.setFrom(0).setSize(batch);
for (;;) {
SearchResponse response = searchRequestBuilder.execute().actionGet();
if (response.getHits() == null || response.getHits().getHits() == null) break;
for (int i = 0; i < response.getHits().getHits().length; i++) {
context.add(clazz, response.getHits().getHits()[i].getId());
}
// Redo the query if we hit the batch
if (response.getHits().getHits().length < batch) break;
}
}
private <T> ESGenericSearchDAO getDaoFor(Class<T> clazz) {
if (AbstractMonitorEvent.class.isAssignableFrom(clazz)
|| DeploymentTopology.class.isAssignableFrom(clazz)
|| DeploymentUnprocessedTopology.class.isAssignableFrom(clazz)
|| PaaSDeploymentLog.class.isAssignableFrom(clazz)
) {
return monitorDao;
} else {
return commonDao;
}
}
private <T> void bulkDelete(Class<T> clazz,Collection<String> ids) {
ESGenericSearchDAO dao = getDaoFor(clazz);
BulkRequestBuilder bulkRequestBuilder = dao.getClient().prepareBulk().setRefreshPolicy(WriteRequest.RefreshPolicy.NONE);
String[] indexNames = dao.getIndexForType(clazz);
for (String indexName: indexNames) {
if (log.isDebugEnabled()) {
log.debug("BULK DELETE ON {} -> {} items", indexName, ids.size());
}
for (String id : ids) {
DeleteRequestBuilder deleteRequestBuilder = dao.getClient().prepareDelete().setIndex(indexName).setType(ESIndexMapper.TYPE_NAME).setId(id);
bulkRequestBuilder.add(deleteRequestBuilder.request());
}
}
bulkRequestBuilder.execute().actionGet();
}
@EventListener
private void onDeploymentUndeployed(DeploymentUndeployedEvent event) {
PurgeContext context = new PurgeContext(this::bulkDelete);
if (log.isDebugEnabled()) {
log.debug("Cleaning Deployment {}", event.getDeploymentId());
}
purge(context,event.getDeploymentId());
// Flush pending deletes
context.flush();
}
}
| [ALIEN-3394] Delay purge of deployedtopology
| alien4cloud-core/src/main/java/alien4cloud/purge/PurgeService.java | [ALIEN-3394] Delay purge of deployedtopology | <ide><path>lien4cloud-core/src/main/java/alien4cloud/purge/PurgeService.java
<ide> import org.elasticsearch.index.query.*;
<ide> import org.springframework.beans.factory.annotation.Value;
<ide> import org.springframework.context.event.EventListener;
<add>import org.springframework.core.Ordered;
<add>import org.springframework.core.annotation.Order;
<ide> import org.springframework.stereotype.Component;
<ide>
<ide> import javax.annotation.PostConstruct;
<ide> log.trace("=> Purging Deployment {}", id);
<ide> }
<ide>
<del> purge(context,id);
<add> context.add(DeploymentTopology.class,id);
<add>
<add> purge(context, id, WorkflowStepInstance.class);
<add> purge(context,id,TaskFailedEvent.class);
<add> purge(context,id,TaskSentEvent.class);
<add> purge(context,id,TaskStartedEvent.class);
<add> purge(context,id,TaskCancelledEvent.class);
<add> purge(context,id,TaskSucceededEvent.class);
<add>
<add> purge(context,id, WorkflowStepStartedEvent.class);
<add> purge(context,id, WorkflowStepCompletedEvent.class);
<add>
<add> purge(context,id, PaaSWorkflowSucceededEvent.class);
<add> purge(context,id, PaaSWorkflowStartedEvent.class);
<add> purge(context,id, PaaSWorkflowCancelledEvent.class);
<add> purge(context,id, PaaSWorkflowFailedEvent.class);
<add>
<add> purge(context,id,PaaSDeploymentStatusMonitorEvent.class);
<add>
<add> purge(context,id, PaaSInstanceStateMonitorEvent.class);
<ide>
<ide> purge(context,id,Task.class);
<ide> purge(context,id,Execution.class);
<ide> }
<ide>
<ide> private void purge(PurgeContext context, String id) {
<del> context.add(DeploymentTopology.class,id);
<del>
<ide> purge(context, id, WorkflowStepInstance.class);
<ide> purge(context,id,TaskFailedEvent.class);
<ide> purge(context,id,TaskSentEvent.class); |
|
Java | apache-2.0 | 53ea57f8d6be80a4cdaaa586213ae98a15a27111 | 0 | DataSketches/memory,ApacheInfra/incubator-datasketches-memory,DataSketches/memory | package com.yahoo.memory;
import static com.yahoo.memory.UnsafeUtil.checkBounds;
import static com.yahoo.memory.UnsafeUtil.unsafe;
import static java.lang.Character.isSurrogate;
import static java.lang.Character.isSurrogatePair;
import static java.lang.Character.toCodePoint;
import java.io.IOException;
import java.nio.BufferOverflowException;
import java.nio.CharBuffer;
/**
* Encoding and decoding implementations of {@link WritableMemory#putCharsToUtf8} and {@link
* Memory#getCharsFromUtf8}.
*
* This is specifically designed to reduce the production of intermediate objects (garbage),
* thus significantly reducing pressure on the JVM Garbage Collector.
*
* <p>UTF-8 encoding/decoding is based on
* https://github.com/google/protobuf/blob/3e944aec9ebdf5043780fba751d604c0a55511f2/
* java/core/src/main/java/com/google/protobuf/Utf8.java
*
* <p>Copyright 2008 Google Inc. All rights reserved.
* https://developers.google.com/protocol-buffers/
*
* @author Lee Rhodes
* @author Roman Leventov
*/
// NOTE: If you touch this class you need to enable the exhaustive Utf8Test.testThreeBytes()
// method.
final class Utf8 {
//Decode
static final void getCharsFromUtf8(final long offsetBytes, final int utf8LengthBytes,
final Appendable dst, final ResourceState state)
throws IOException, Utf8CodingException {
assert state.isValid();
checkBounds(offsetBytes, utf8LengthBytes, state.getCapacity());
final long cumBaseOffset = state.getCumBaseOffset();
long address = cumBaseOffset + offsetBytes;
final Object unsafeObj = state.getUnsafeObject();
if ((dst instanceof CharBuffer) && ((CharBuffer) dst).hasArray()) {
getCharsFromUtf8CharBuffer(offsetBytes, ((CharBuffer) dst), utf8LengthBytes, cumBaseOffset,
state);
return;
}
int i = 0;
// Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
// This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
// Need to keep this loop int-indexed, because it's faster for Hotspot JIT, it doesn't insert
// savepoint polls on each iteration.
for (; i < utf8LengthBytes; i++) {
final byte b = unsafe.getByte(unsafeObj, address + i);
if (!DecodeUtil.isOneByte(b)) {
break;
}
dst.append((char) b);
}
if (i == utf8LengthBytes) {
return;
}
getCharsFromUtf8NonAscii(dst, address + i, address + utf8LengthBytes, unsafeObj, cumBaseOffset);
}
/**
* Optimize for heap CharBuffer manually, because Hotspot JIT doesn't itself unfold this
* abstraction well (doesn't hoist array bound checks, etc.)
*/
private static void getCharsFromUtf8CharBuffer(final long offsetBytes, final CharBuffer cb,
final int utf8LengthBytes, final long cumBaseOffset, final ResourceState state) {
char[] ca = cb.array();
int cp = cb.position() + cb.arrayOffset();
int cl = cb.arrayOffset() + cb.limit();
long address = state.getCumBaseOffset() + offsetBytes;
int i = 0;
final Object unsafeObj = state.getUnsafeObject();
// Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
// This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
int cbNoCheckLimit = Math.min(utf8LengthBytes, cl - cp);
// Need to keep this loop int-indexed, because it's faster for Hotspot JIT, it doesn't insert
// savepoint polls on each iteration.
for (; i < cbNoCheckLimit; i++) {
final byte b = unsafe.getByte(unsafeObj, address + i);
if (!DecodeUtil.isOneByte(b)) {
break;
}
// Not checking CharBuffer bounds!
ca[cp++] = (char) b;
}
for (; i < utf8LengthBytes; i++) {
final byte b = unsafe.getByte(unsafeObj, address + i);
if (!DecodeUtil.isOneByte(b)) {
break;
}
checkCharBufferPos(cb, cp, cl);
ca[cp++] = (char) b;
}
if (i == utf8LengthBytes) {
cb.position(cp - cb.arrayOffset());
return;
}
getCharsFromUtf8NonAsciiCharBuffer(cb, ca, cp, cl, address + i, address + utf8LengthBytes,
unsafeObj, cumBaseOffset);
}
private static void checkCharBufferPos(final CharBuffer cb, final int cp, final int cl) {
if (cp == cl) {
cb.position(cp - cb.arrayOffset());
throw new BufferOverflowException();
}
}
private static void getCharsFromUtf8NonAscii(final Appendable dst, long address,
final long addressLimit, final Object unsafeObj, final long cumBaseOffset)
throws IOException {
while (address < addressLimit) {
final byte byte1 = unsafe.getByte(unsafeObj, address++);
if (DecodeUtil.isOneByte(byte1)) {
dst.append((char) byte1);
// It's common for there to be multiple ASCII characters in a run mixed in, so add an
// extra optimized loop to take care of these runs.
while (address < addressLimit) {
final byte b = unsafe.getByte(unsafeObj, address);
if (!DecodeUtil.isOneByte(b)) {
break;
}
address++;
dst.append((char) b);
}
}
else if (DecodeUtil.isTwoBytes(byte1)) {
if (address >= addressLimit) {
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 2);
}
DecodeUtil.handleTwoBytes(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
dst);
}
else if (DecodeUtil.isThreeBytes(byte1)) {
if (address >= (addressLimit - 1)) {
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 3);
}
DecodeUtil.handleThreeBytes(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
dst);
}
else {
if (address >= (addressLimit - 2)) {
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 4);
}
DecodeUtil.handleFourBytes(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
/* byte4 */ unsafe.getByte(unsafeObj, address++),
dst);
}
}
}
private static void getCharsFromUtf8NonAsciiCharBuffer(final CharBuffer cb, final char[] ca,
int cp, final int cl, long address, final long addressLimit, final Object unsafeObj,
final long cumBaseOffset) {
while (address < addressLimit) {
final byte byte1 = unsafe.getByte(unsafeObj, address++);
if (DecodeUtil.isOneByte(byte1)) {
checkCharBufferPos(cb, cp, cl);
ca[cp++] = (char) byte1;
// It's common for there to be multiple ASCII characters in a run mixed in, so add an
// extra optimized loop to take care of these runs.
while (address < addressLimit) {
final byte b = unsafe.getByte(unsafeObj, address);
if (!DecodeUtil.isOneByte(b)) {
break;
}
address++;
checkCharBufferPos(cb, cp, cl);
ca[cp++] = (char) b;
}
}
else if (DecodeUtil.isTwoBytes(byte1)) {
if (address >= addressLimit) {
cb.position(cp - cb.arrayOffset());
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 2);
}
checkCharBufferPos(cb, cp, cl);
DecodeUtil.handleTwoBytesCharBuffer(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
cb, ca, cp);
cp++;
}
else if (DecodeUtil.isThreeBytes(byte1)) {
if (address >= (addressLimit - 1)) {
cb.position(cp - cb.arrayOffset());
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 3);
}
checkCharBufferPos(cb, cp, cl);
DecodeUtil.handleThreeBytesCharBuffer(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
cb, ca, cp);
cp++;
}
else {
if (address >= (addressLimit - 2)) {
cb.position(cp - cb.arrayOffset());
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 4);
}
if (cp >= (cl - 1)) {
cb.position(cp - cb.arrayOffset());
throw new BufferOverflowException();
}
DecodeUtil.handleFourBytesCharBuffer(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
/* byte4 */ unsafe.getByte(unsafeObj, address++),
cb, ca, cp);
cp += 2;
}
}
cb.position(cp - cb.arrayOffset());
}
//Encode
static long putCharsToUtf8(final long offsetBytes, final CharSequence src,
final ResourceState state) {
assert state.isValid();
final Object unsafeObj = state.getUnsafeObject();
final long cumBaseOffset = state.getCumBaseOffset();
long j = cumBaseOffset + offsetBytes; //used in unsafe for the index
int i = 0; //src character index
final long byteLimit = cumBaseOffset + state.getCapacity(); //unsafe index limit
final int utf16Length = src.length();
//Quickly dispatch an ASCII sequence
for (char c; (i < utf16Length) && ((i + j) < byteLimit) && ((c = src.charAt(i)) < 0x80); i++) {
unsafe.putByte(unsafeObj, j + i, (byte) c);
}
if (i == utf16Length) { //done, return next relative byte index in memory
return (j + utf16Length) - cumBaseOffset;
}
j += i;
for (char c; i < utf16Length; i++) {
c = src.charAt(i);
if ((c < 0x80) && (j < byteLimit)) {
//Encode ASCII, 0 through 0x007F.
unsafe.putByte(unsafeObj, j++, (byte) c);
}
else
//c MUST BE >= 0x0080 || j >= byteLimit
if ((c < 0x800) && (j < (byteLimit - 1))) {
//Encode 0x80 through 0x7FF.
//This is for almost all Latin-script alphabets plus Greek, Cyrillic, Hebrew, Arabic, etc.
//We must have target space for at least 2 Utf8 bytes.
unsafe.putByte(unsafeObj, j++, (byte) ((0xF << 6) | (c >>> 6)));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & c)));
}
else
//c > 0x800 || j >= byteLimit - 1 || j >= byteLimit
if ( !isSurrogate(c) && (j < (byteLimit - 2)) ) {
//Encode the remainder of the BMP that are not surrogates:
// 0x0800 thru 0xD7FF; 0xE000 thru 0xFFFF, the max single-char code point
//We must have target space for at least 3 Utf8 bytes.
unsafe.putByte(unsafeObj, j++, (byte) ((0xF << 5) | (c >>> 12)));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & (c >>> 6))));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & c)));
}
else {
//c is a surrogate || j >= byteLimit - 2 || j >= byteLimit - 1 || j >= byteLimit
//At this point we are either:
// 1) Attempting to encode Code Points outside the BMP.
//
// The only way to properly encode code points outside the BMP into Utf8 bytes is to use
// High/Low pairs of surrogate characters. Therefore, we must have at least 2 source
// characters remaining, at least 4 bytes of memory space remaining, and the next 2
// characters must be a valid surrogate pair.
//
// 2) There is insufficient Memory space to encode the current character from one of the
// ifs above.
//
// We proceed assuming (1). If the following test fails, we move to an exception.
final char low;
if ( (i <= (utf16Length - 2))
&& (j <= (byteLimit - 4))
&& isSurrogatePair(c, low = src.charAt(i + 1)) ) { //we are good
i++; //skip over low surrogate
final int codePoint = toCodePoint(c, low);
unsafe.putByte(unsafeObj, j++, (byte) ((0xF << 4) | (codePoint >>> 18)));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & (codePoint >>> 12))));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & (codePoint >>> 6))));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & codePoint)));
}
else {
//We are going to throw an exception. So we have time to figure out
// what was wrong and hopefully throw an intelligent message!
//check the BMP code point cases and their required memory limits
if ( ((c < 0X0080) && (j >= byteLimit))
|| ((c < 0x0800) && (j >= (byteLimit - 1)))
|| ((c < 0xFFFF) && (j >= (byteLimit - 2))) ) {
throw Utf8CodingException.outOfMemory();
}
if (i > (utf16Length - 2)) { //the last char is an unpaired surrogate
throw Utf8CodingException.unpairedSurrogate(c);
}
if (j > (byteLimit - 4)) {
//4 Memory bytes required to encode a surrogate pair.
final int remaining = (int) ((j - byteLimit) + 4L);
throw Utf8CodingException.shortUtf8EncodeByteLength(remaining);
}
if (!isSurrogatePair(c, src.charAt(i + 1)) ) {
//Not a surrogate pair.
throw Utf8CodingException.illegalSurrogatePair(c, src.charAt(i + 1));
}
//This should not happen :)
throw new IllegalArgumentException("Unknown Utf8 encoding exception");
}
}
}
final long localOffsetBytes = j - cumBaseOffset;
return localOffsetBytes;
}
/**
* Utility methods for decoding UTF-8 bytes into {@link String}. Callers are responsible for
* extracting bytes (possibly using Unsafe methods), and checking remaining bytes. All other
* UTF-8 validity checks and codepoint conversions happen in this class.
*
* @see <a href="https://en.wikipedia.org/wiki/UTF-8">Wikipedia: UTF-8</a>
*/
private static class DecodeUtil {
/**
* Returns whether this is a single-byte UTF-8 encoding.
* This is for ASCII.
*
* <p>Code Plane 0, Code Point range U+0000 to U+007F.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '0xxxxxxx'<li>
* </ul>
* @param b the byte being tested
* @return true if this is a single-byte UTF-8 encoding, i.e., b is ≥ 0.
*/
private static boolean isOneByte(final byte b) {
return b >= 0;
}
/**
* Returns whether this is the start of a two-byte UTF-8 encoding. One-byte encoding must
* already be excluded.
* This is for almost all Latin-script alphabets plus Greek, Cyrillic, Hebrew, Arabic, etc.
*
* <p>Code Plane 0, Code Point range U+0080 to U+07FF.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '110xxxxx'</li>
* <li>Byte 2: '10xxxxxx'</li>
* </ul>
*
* All bytes must be < 0xE0.
*
* @param b the byte being tested
* @return true if this is the start of a two-byte UTF-8 encoding.
*/
private static boolean isTwoBytes(final byte b) {
return b < (byte) 0xE0;
}
/**
* Returns whether this is the start of a three-byte UTF-8 encoding. Two-byte encoding must
* already be excluded.
* This is for the rest of the BMP, which includes most common Chinese, Japanese and Korean
* characters.
*
* <p>Code Plane 0, Code Point range U+0800 to U+FFFF.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '1110xxxx'</li>
* <li>Byte 2: '10xxxxxx'</li>
* <li>Byte 3: '10xxxxxx'</li>
* </ul>
* All bytes must be less than 0xF0.
*
* @param b the byte being tested
* @return true if this is the start of a three-byte UTF-8 encoding, i.e., b ≥ 0XF0.
*/
private static boolean isThreeBytes(final byte b) {
return b < (byte) 0xF0;
}
/*
* Note that if three-byte UTF-8 coding has been excluded and if the current byte is
* ≥ 0XF0, it must be the start of a four-byte UTF-8 encoding.
* This is for the less common CJKV characters, historic scripts, math symbols, emoji, etc.
*
* <p>Code Plane1 1 through 16, Code Point range U+10000 to U+10FFFF.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '11110xxx'</li>
* <li>Byte 2: '10xxxxxx'</li>
* <li>Byte 3: '10xxxxxx'</li>
* <li>Byte 4: '10xxxxxx'</li>
* </ul>
*/
private static void handleTwoBytes(final byte byte1, final byte byte2, final Appendable dst)
throws IOException, Utf8CodingException {
// Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
// overlong 2-byte, '11000001'.
if ((byte1 < (byte) 0xC2)
|| isNotTrailingByte(byte2)) {
byte[] out = new byte[] {byte1, byte2};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
dst.append((char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)));
}
private static void handleTwoBytesCharBuffer(final byte byte1, final byte byte2, final CharBuffer cb, char[] ca, int cp)
throws Utf8CodingException {
// Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
// overlong 2-byte, '11000001'.
if ((byte1 < (byte) 0xC2)
|| isNotTrailingByte(byte2)) {
byte[] out = new byte[] {byte1, byte2};
cb.position(cp - cb.arrayOffset());
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
ca[cp] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2));
}
private static void handleThreeBytes(final byte byte1, final byte byte2, final byte byte3,
final Appendable dst) throws IOException, Utf8CodingException {
if (isNotTrailingByte(byte2)
// overlong? 5 most significant bits must not all be zero
|| ((byte1 == (byte) 0xE0) && (byte2 < (byte) 0xA0))
// check for illegal surrogate codepoints
|| ((byte1 == (byte) 0xED) && (byte2 >= (byte) 0xA0))
|| isNotTrailingByte(byte3)) {
byte[] out = new byte[] {byte1, byte2, byte3};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
dst.append((char)
(((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)));
}
private static void handleThreeBytesCharBuffer(final byte byte1, final byte byte2, final byte byte3,
final CharBuffer cb, char[] ca, int cp) throws Utf8CodingException {
if (isNotTrailingByte(byte2)
// overlong? 5 most significant bits must not all be zero
|| ((byte1 == (byte) 0xE0) && (byte2 < (byte) 0xA0))
// check for illegal surrogate codepoints
|| ((byte1 == (byte) 0xED) && (byte2 >= (byte) 0xA0))
|| isNotTrailingByte(byte3)) {
cb.position(cp - cb.arrayOffset());
byte[] out = new byte[] {byte1, byte2, byte3};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
ca[cp] = (char)
(((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3));
}
private static void handleFourBytes(
final byte byte1, final byte byte2, final byte byte3, final byte byte4,
final Appendable dst) throws IOException, Utf8CodingException {
if (isNotTrailingByte(byte2)
// Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
// if (byte1 > (byte) 0xF4 ||
// overlong? 4 most significant bits must not all be zero
// byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
// codepoint larger than the highest code point (U+10FFFF)?
// byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
|| ((((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0)
|| isNotTrailingByte(byte3)
|| isNotTrailingByte(byte4)) {
byte[] out = new byte[] {byte1, byte2, byte3, byte4};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
final int codepoint = ((byte1 & 0x07) << 18)
| (trailingByteValue(byte2) << 12)
| (trailingByteValue(byte3) << 6)
| trailingByteValue(byte4);
dst.append(DecodeUtil.highSurrogate(codepoint));
dst.append(DecodeUtil.lowSurrogate(codepoint));
}
private static void handleFourBytesCharBuffer(
final byte byte1, final byte byte2, final byte byte3, final byte byte4,
final CharBuffer cb, char[] ca, int cp) throws Utf8CodingException {
if (isNotTrailingByte(byte2)
// Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
// if (byte1 > (byte) 0xF4 ||
// overlong? 4 most significant bits must not all be zero
// byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
// codepoint larger than the highest code point (U+10FFFF)?
// byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
|| ((((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0)
|| isNotTrailingByte(byte3)
|| isNotTrailingByte(byte4)) {
cb.position(cp - cb.arrayOffset());
byte[] out = new byte[] {byte1, byte2, byte3, byte4};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
final int codepoint = ((byte1 & 0x07) << 18)
| (trailingByteValue(byte2) << 12)
| (trailingByteValue(byte3) << 6)
| trailingByteValue(byte4);
ca[cp] = DecodeUtil.highSurrogate(codepoint);
ca[cp + 1] = DecodeUtil.lowSurrogate(codepoint);
}
/**
* Returns whether the byte is not a valid continuation of the form '10XXXXXX'.
*/
private static boolean isNotTrailingByte(final byte b) {
return b > (byte) 0xBF;
}
/**
* Returns the actual value of the trailing byte (removes the prefix '10') for composition.
*/
private static int trailingByteValue(final byte b) {
return b & 0x3F;
}
private static char highSurrogate(final int codePoint) {
return (char) ((Character.MIN_HIGH_SURROGATE
- (Character.MIN_SUPPLEMENTARY_CODE_POINT >>> 10))
+ (codePoint >>> 10));
}
private static char lowSurrogate(final int codePoint) {
return (char) (Character.MIN_LOW_SURROGATE + (codePoint & 0x3ff));
}
}
}
| src/main/java/com/yahoo/memory/Utf8.java | package com.yahoo.memory;
import static com.yahoo.memory.UnsafeUtil.checkBounds;
import static com.yahoo.memory.UnsafeUtil.unsafe;
import static java.lang.Character.isSurrogate;
import static java.lang.Character.isSurrogatePair;
import static java.lang.Character.toCodePoint;
import java.io.IOException;
import java.nio.BufferOverflowException;
import java.nio.CharBuffer;
/**
* Encoding and decoding implementations of {@link WritableMemory#putCharsToUtf8} and {@link
* Memory#getCharsFromUtf8}.
*
* This is specifically designed to reduce the production of intermediate objects (garbage),
* thus significantly reducing pressure on the JVM Garbage Collector.
*
* <p>UTF-8 encoding/decoding is based on
* https://github.com/google/protobuf/blob/3e944aec9ebdf5043780fba751d604c0a55511f2/
* java/core/src/main/java/com/google/protobuf/Utf8.java
*
* <p>Copyright 2008 Google Inc. All rights reserved.
* https://developers.google.com/protocol-buffers/
*
* @author Lee Rhodes
* @author Roman Leventov
*/
// NOTE: If you touch this class you need to enable the exhaustive Utf8Test.testThreeBytes()
// method.
final class Utf8 {
//Decode
static final void getCharsFromUtf8(final long offsetBytes, final int utf8LengthBytes,
final Appendable dst, final ResourceState state)
throws IOException, Utf8CodingException {
assert state.isValid();
checkBounds(offsetBytes, utf8LengthBytes, state.getCapacity());
final long cumBaseOffset = state.getCumBaseOffset();
long address = cumBaseOffset + offsetBytes;
final Object unsafeObj = state.getUnsafeObject();
if ((dst instanceof CharBuffer) && ((CharBuffer) dst).hasArray()) {
getCharsFromUtf8CharBuffer(offsetBytes, ((CharBuffer) dst), utf8LengthBytes, cumBaseOffset,
state);
return;
}
int i = 0;
// Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
// This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
// Need to keep this loop int-indexed, because it's faster for Hotspot JIT, it doesn't insert
// savepoint polls on each iteration.
for (; i < utf8LengthBytes; i++) {
final byte b = unsafe.getByte(unsafeObj, address + i);
if (!DecodeUtil.isOneByte(b)) {
break;
}
dst.append((char) b);
}
if (i == utf8LengthBytes) {
return;
}
getCharsFromUtf8NonAscii(dst, address + i, address + utf8LengthBytes, unsafeObj, cumBaseOffset);
}
/**
* Optimize for heap CharBuffer manually, because Hotspot JIT doesn't itself unfold this
* abstraction well (doesn't hoist array bound checks, etc.)
*/
private static void getCharsFromUtf8CharBuffer(final long offsetBytes, final CharBuffer cb,
final int utf8LengthBytes, final long cumBaseOffset, final ResourceState state) {
char[] ca = cb.array();
int cp = cb.position() + cb.arrayOffset();
int cl = cb.arrayOffset() + cb.limit();
long address = state.getCumBaseOffset() + offsetBytes;
int i = 0;
final Object unsafeObj = state.getUnsafeObject();
// Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this).
// This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII).
int cbNoCheckLimit = Math.min(utf8LengthBytes, cl - cp);
// Need to keep this loop int-indexed, because it's faster for Hotspot JIT, it doesn't insert
// savepoint polls on each iteration.
for (; i < cbNoCheckLimit; i++) {
final byte b = unsafe.getByte(unsafeObj, address + i);
if (!DecodeUtil.isOneByte(b)) {
break;
}
// Not checking CharBuffer bounds!
ca[cp++] = (char) b;
}
for (; i < utf8LengthBytes; i++) {
final byte b = unsafe.getByte(unsafeObj, address + i);
if (!DecodeUtil.isOneByte(b)) {
break;
}
checkCharBufferPos(cb, cp, cl);
ca[cp++] = (char) b;
}
if (i == utf8LengthBytes) {
cb.position(cp - cb.arrayOffset());
return;
}
getCharsFromUtf8NonAsciiCharBuffer(cb, ca, cp, cl, address + i, address + utf8LengthBytes,
unsafeObj, cumBaseOffset);
}
private static void checkCharBufferPos(CharBuffer cb, int cp, int cl) {
if (cp == cl) {
cb.position(cp - cb.arrayOffset());
throw new BufferOverflowException();
}
}
private static void getCharsFromUtf8NonAscii(Appendable dst, long address, long addressLimit,
Object unsafeObj, long cumBaseOffset) throws IOException {
while (address < addressLimit) {
final byte byte1 = unsafe.getByte(unsafeObj, address++);
if (DecodeUtil.isOneByte(byte1)) {
dst.append((char) byte1);
// It's common for there to be multiple ASCII characters in a run mixed in, so add an
// extra optimized loop to take care of these runs.
while (address < addressLimit) {
final byte b = unsafe.getByte(unsafeObj, address);
if (!DecodeUtil.isOneByte(b)) {
break;
}
address++;
dst.append((char) b);
}
}
else if (DecodeUtil.isTwoBytes(byte1)) {
if (address >= addressLimit) {
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 2);
}
DecodeUtil.handleTwoBytes(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
dst);
}
else if (DecodeUtil.isThreeBytes(byte1)) {
if (address >= (addressLimit - 1)) {
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 3);
}
DecodeUtil.handleThreeBytes(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
dst);
}
else {
if (address >= (addressLimit - 2)) {
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 4);
}
DecodeUtil.handleFourBytes(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
/* byte4 */ unsafe.getByte(unsafeObj, address++),
dst);
}
}
}
private static void getCharsFromUtf8NonAsciiCharBuffer(CharBuffer cb, char[] ca, int cp, int cl,
long address, long addressLimit, Object unsafeObj, long cumBaseOffset) {
while (address < addressLimit) {
final byte byte1 = unsafe.getByte(unsafeObj, address++);
if (DecodeUtil.isOneByte(byte1)) {
checkCharBufferPos(cb, cp, cl);
ca[cp++] = (char) byte1;
// It's common for there to be multiple ASCII characters in a run mixed in, so add an
// extra optimized loop to take care of these runs.
while (address < addressLimit) {
final byte b = unsafe.getByte(unsafeObj, address);
if (!DecodeUtil.isOneByte(b)) {
break;
}
address++;
checkCharBufferPos(cb, cp, cl);
ca[cp++] = (char) b;
}
}
else if (DecodeUtil.isTwoBytes(byte1)) {
if (address >= addressLimit) {
cb.position(cp - cb.arrayOffset());
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 2);
}
checkCharBufferPos(cb, cp, cl);
DecodeUtil.handleTwoBytesCharBuffer(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
cb, ca, cp);
cp++;
}
else if (DecodeUtil.isThreeBytes(byte1)) {
if (address >= (addressLimit - 1)) {
cb.position(cp - cb.arrayOffset());
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 3);
}
checkCharBufferPos(cb, cp, cl);
DecodeUtil.handleThreeBytesCharBuffer(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
cb, ca, cp);
cp++;
}
else {
if (address >= (addressLimit - 2)) {
cb.position(cp - cb.arrayOffset());
long off = address - cumBaseOffset;
long limit = addressLimit - cumBaseOffset;
throw Utf8CodingException.shortUtf8DecodeByteSequence(byte1, off, limit, 4);
}
if (cp >= (cl - 1)) {
cb.position(cp - cb.arrayOffset());
throw new BufferOverflowException();
}
DecodeUtil.handleFourBytesCharBuffer(
byte1,
/* byte2 */ unsafe.getByte(unsafeObj, address++),
/* byte3 */ unsafe.getByte(unsafeObj, address++),
/* byte4 */ unsafe.getByte(unsafeObj, address++),
cb, ca, cp);
cp += 2;
}
}
cb.position(cp - cb.arrayOffset());
}
//Encode
static long putCharsToUtf8(final long offsetBytes, final CharSequence src,
final ResourceState state) {
assert state.isValid();
final Object unsafeObj = state.getUnsafeObject();
final long cumBaseOffset = state.getCumBaseOffset();
long j = cumBaseOffset + offsetBytes; //used in unsafe for the index
int i = 0; //src character index
final long byteLimit = cumBaseOffset + state.getCapacity(); //unsafe index limit
final int utf16Length = src.length();
//Quickly dispatch an ASCII sequence
for (char c; (i < utf16Length) && ((i + j) < byteLimit) && ((c = src.charAt(i)) < 0x80); i++) {
unsafe.putByte(unsafeObj, j + i, (byte) c);
}
if (i == utf16Length) { //done, return next relative byte index in memory
return (j + utf16Length) - cumBaseOffset;
}
j += i;
for (char c; i < utf16Length; i++) {
c = src.charAt(i);
if ((c < 0x80) && (j < byteLimit)) {
//Encode ASCII, 0 through 0x007F.
unsafe.putByte(unsafeObj, j++, (byte) c);
}
else
//c MUST BE >= 0x0080 || j >= byteLimit
if ((c < 0x800) && (j < (byteLimit - 1))) {
//Encode 0x80 through 0x7FF.
//This is for almost all Latin-script alphabets plus Greek, Cyrillic, Hebrew, Arabic, etc.
//We must have target space for at least 2 Utf8 bytes.
unsafe.putByte(unsafeObj, j++, (byte) ((0xF << 6) | (c >>> 6)));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & c)));
}
else
//c > 0x800 || j >= byteLimit - 1 || j >= byteLimit
if ( !isSurrogate(c) && (j < (byteLimit - 2)) ) {
//Encode the remainder of the BMP that are not surrogates:
// 0x0800 thru 0xD7FF; 0xE000 thru 0xFFFF, the max single-char code point
//We must have target space for at least 3 Utf8 bytes.
unsafe.putByte(unsafeObj, j++, (byte) ((0xF << 5) | (c >>> 12)));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & (c >>> 6))));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & c)));
}
else {
//c is a surrogate || j >= byteLimit - 2 || j >= byteLimit - 1 || j >= byteLimit
//At this point we are either:
// 1) Attempting to encode Code Points outside the BMP.
//
// The only way to properly encode code points outside the BMP into Utf8 bytes is to use
// High/Low pairs of surrogate characters. Therefore, we must have at least 2 source
// characters remaining, at least 4 bytes of memory space remaining, and the next 2
// characters must be a valid surrogate pair.
//
// 2) There is insufficient Memory space to encode the current character from one of the
// ifs above.
//
// We proceed assuming (1). If the following test fails, we move to an exception.
final char low;
if ( (i <= (utf16Length - 2))
&& (j <= (byteLimit - 4))
&& isSurrogatePair(c, low = src.charAt(i + 1)) ) { //we are good
i++; //skip over low surrogate
final int codePoint = toCodePoint(c, low);
unsafe.putByte(unsafeObj, j++, (byte) ((0xF << 4) | (codePoint >>> 18)));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & (codePoint >>> 12))));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & (codePoint >>> 6))));
unsafe.putByte(unsafeObj, j++, (byte) (0x80 | (0x3F & codePoint)));
}
else {
//We are going to throw an exception. So we have time to figure out
// what was wrong and hopefully throw an intelligent message!
//check the BMP code point cases and their required memory limits
if ( ((c < 0X0080) && (j >= byteLimit))
|| ((c < 0x0800) && (j >= (byteLimit - 1)))
|| ((c < 0xFFFF) && (j >= (byteLimit - 2))) ) {
throw Utf8CodingException.outOfMemory();
}
if (i > (utf16Length - 2)) { //the last char is an unpaired surrogate
throw Utf8CodingException.unpairedSurrogate(c);
}
if (j > (byteLimit - 4)) {
//4 Memory bytes required to encode a surrogate pair.
final int remaining = (int) ((j - byteLimit) + 4L);
throw Utf8CodingException.shortUtf8EncodeByteLength(remaining);
}
if (!isSurrogatePair(c, src.charAt(i + 1)) ) {
//Not a surrogate pair.
throw Utf8CodingException.illegalSurrogatePair(c, src.charAt(i + 1));
}
//This should not happen :)
throw new IllegalArgumentException("Unknown Utf8 encoding exception");
}
}
}
final long localOffsetBytes = j - cumBaseOffset;
return localOffsetBytes;
}
/**
* Utility methods for decoding UTF-8 bytes into {@link String}. Callers are responsible for
* extracting bytes (possibly using Unsafe methods), and checking remaining bytes. All other
* UTF-8 validity checks and codepoint conversions happen in this class.
*
* @see <a href="https://en.wikipedia.org/wiki/UTF-8">Wikipedia: UTF-8</a>
*/
private static class DecodeUtil {
/**
* Returns whether this is a single-byte UTF-8 encoding.
* This is for ASCII.
*
* <p>Code Plane 0, Code Point range U+0000 to U+007F.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '0xxxxxxx'<li>
* </ul>
* @param b the byte being tested
* @return true if this is a single-byte UTF-8 encoding, i.e., b is ≥ 0.
*/
private static boolean isOneByte(final byte b) {
return b >= 0;
}
/**
* Returns whether this is the start of a two-byte UTF-8 encoding. One-byte encoding must
* already be excluded.
* This is for almost all Latin-script alphabets plus Greek, Cyrillic, Hebrew, Arabic, etc.
*
* <p>Code Plane 0, Code Point range U+0080 to U+07FF.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '110xxxxx'</li>
* <li>Byte 2: '10xxxxxx'</li>
* </ul>
*
* All bytes must be < 0xE0.
*
* @param b the byte being tested
* @return true if this is the start of a two-byte UTF-8 encoding.
*/
private static boolean isTwoBytes(final byte b) {
return b < (byte) 0xE0;
}
/**
* Returns whether this is the start of a three-byte UTF-8 encoding. Two-byte encoding must
* already be excluded.
* This is for the rest of the BMP, which includes most common Chinese, Japanese and Korean
* characters.
*
* <p>Code Plane 0, Code Point range U+0800 to U+FFFF.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '1110xxxx'</li>
* <li>Byte 2: '10xxxxxx'</li>
* <li>Byte 3: '10xxxxxx'</li>
* </ul>
* All bytes must be less than 0xF0.
*
* @param b the byte being tested
* @return true if this is the start of a three-byte UTF-8 encoding, i.e., b ≥ 0XF0.
*/
private static boolean isThreeBytes(final byte b) {
return b < (byte) 0xF0;
}
/*
* Note that if three-byte UTF-8 coding has been excluded and if the current byte is
* ≥ 0XF0, it must be the start of a four-byte UTF-8 encoding.
* This is for the less common CJKV characters, historic scripts, math symbols, emoji, etc.
*
* <p>Code Plane1 1 through 16, Code Point range U+10000 to U+10FFFF.
*
* <p>Bit Patterns:
* <ul><li>Byte 1: '11110xxx'</li>
* <li>Byte 2: '10xxxxxx'</li>
* <li>Byte 3: '10xxxxxx'</li>
* <li>Byte 4: '10xxxxxx'</li>
* </ul>
*/
private static void handleTwoBytes(final byte byte1, final byte byte2, final Appendable dst)
throws IOException, Utf8CodingException {
// Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
// overlong 2-byte, '11000001'.
if ((byte1 < (byte) 0xC2)
|| isNotTrailingByte(byte2)) {
byte[] out = new byte[] {byte1, byte2};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
dst.append((char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)));
}
private static void handleTwoBytesCharBuffer(final byte byte1, final byte byte2, final CharBuffer cb, char[] ca, int cp)
throws Utf8CodingException {
// Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and
// overlong 2-byte, '11000001'.
if ((byte1 < (byte) 0xC2)
|| isNotTrailingByte(byte2)) {
byte[] out = new byte[] {byte1, byte2};
cb.position(cp - cb.arrayOffset());
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
ca[cp] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2));
}
private static void handleThreeBytes(final byte byte1, final byte byte2, final byte byte3,
final Appendable dst) throws IOException, Utf8CodingException {
if (isNotTrailingByte(byte2)
// overlong? 5 most significant bits must not all be zero
|| ((byte1 == (byte) 0xE0) && (byte2 < (byte) 0xA0))
// check for illegal surrogate codepoints
|| ((byte1 == (byte) 0xED) && (byte2 >= (byte) 0xA0))
|| isNotTrailingByte(byte3)) {
byte[] out = new byte[] {byte1, byte2, byte3};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
dst.append((char)
(((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)));
}
private static void handleThreeBytesCharBuffer(final byte byte1, final byte byte2, final byte byte3,
final CharBuffer cb, char[] ca, int cp) throws Utf8CodingException {
if (isNotTrailingByte(byte2)
// overlong? 5 most significant bits must not all be zero
|| ((byte1 == (byte) 0xE0) && (byte2 < (byte) 0xA0))
// check for illegal surrogate codepoints
|| ((byte1 == (byte) 0xED) && (byte2 >= (byte) 0xA0))
|| isNotTrailingByte(byte3)) {
cb.position(cp - cb.arrayOffset());
byte[] out = new byte[] {byte1, byte2, byte3};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
ca[cp] = (char)
(((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3));
}
private static void handleFourBytes(
final byte byte1, final byte byte2, final byte byte3, final byte byte4,
final Appendable dst) throws IOException, Utf8CodingException {
if (isNotTrailingByte(byte2)
// Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
// if (byte1 > (byte) 0xF4 ||
// overlong? 4 most significant bits must not all be zero
// byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
// codepoint larger than the highest code point (U+10FFFF)?
// byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
|| ((((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0)
|| isNotTrailingByte(byte3)
|| isNotTrailingByte(byte4)) {
byte[] out = new byte[] {byte1, byte2, byte3, byte4};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
final int codepoint = ((byte1 & 0x07) << 18)
| (trailingByteValue(byte2) << 12)
| (trailingByteValue(byte3) << 6)
| trailingByteValue(byte4);
dst.append(DecodeUtil.highSurrogate(codepoint));
dst.append(DecodeUtil.lowSurrogate(codepoint));
}
private static void handleFourBytesCharBuffer(
final byte byte1, final byte byte2, final byte byte3, final byte byte4,
final CharBuffer cb, char[] ca, int cp) throws Utf8CodingException {
if (isNotTrailingByte(byte2)
// Check that 1 <= plane <= 16. Tricky optimized form of:
// valid 4-byte leading byte?
// if (byte1 > (byte) 0xF4 ||
// overlong? 4 most significant bits must not all be zero
// byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 ||
// codepoint larger than the highest code point (U+10FFFF)?
// byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
|| ((((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0)
|| isNotTrailingByte(byte3)
|| isNotTrailingByte(byte4)) {
cb.position(cp - cb.arrayOffset());
byte[] out = new byte[] {byte1, byte2, byte3, byte4};
throw Utf8CodingException.illegalUtf8DecodeByteSequence(out);
}
final int codepoint = ((byte1 & 0x07) << 18)
| (trailingByteValue(byte2) << 12)
| (trailingByteValue(byte3) << 6)
| trailingByteValue(byte4);
ca[cp] = DecodeUtil.highSurrogate(codepoint);
ca[cp + 1] = DecodeUtil.lowSurrogate(codepoint);
}
/**
* Returns whether the byte is not a valid continuation of the form '10XXXXXX'.
*/
private static boolean isNotTrailingByte(final byte b) {
return b > (byte) 0xBF;
}
/**
* Returns the actual value of the trailing byte (removes the prefix '10') for composition.
*/
private static int trailingByteValue(final byte b) {
return b & 0x3F;
}
private static char highSurrogate(final int codePoint) {
return (char) ((Character.MIN_HIGH_SURROGATE
- (Character.MIN_SUPPLEMENTARY_CODE_POINT >>> 10))
+ (codePoint >>> 10));
}
private static char lowSurrogate(final int codePoint) {
return (char) (Character.MIN_LOW_SURROGATE + (codePoint & 0x3ff));
}
}
}
| Add finals. | src/main/java/com/yahoo/memory/Utf8.java | Add finals. | <ide><path>rc/main/java/com/yahoo/memory/Utf8.java
<ide> unsafeObj, cumBaseOffset);
<ide> }
<ide>
<del> private static void checkCharBufferPos(CharBuffer cb, int cp, int cl) {
<add> private static void checkCharBufferPos(final CharBuffer cb, final int cp, final int cl) {
<ide> if (cp == cl) {
<ide> cb.position(cp - cb.arrayOffset());
<ide> throw new BufferOverflowException();
<ide> }
<ide> }
<ide>
<del> private static void getCharsFromUtf8NonAscii(Appendable dst, long address, long addressLimit,
<del> Object unsafeObj, long cumBaseOffset) throws IOException {
<add> private static void getCharsFromUtf8NonAscii(final Appendable dst, long address,
<add> final long addressLimit, final Object unsafeObj, final long cumBaseOffset)
<add> throws IOException {
<ide> while (address < addressLimit) {
<ide> final byte byte1 = unsafe.getByte(unsafeObj, address++);
<ide> if (DecodeUtil.isOneByte(byte1)) {
<ide> }
<ide> }
<ide>
<del> private static void getCharsFromUtf8NonAsciiCharBuffer(CharBuffer cb, char[] ca, int cp, int cl,
<del> long address, long addressLimit, Object unsafeObj, long cumBaseOffset) {
<add> private static void getCharsFromUtf8NonAsciiCharBuffer(final CharBuffer cb, final char[] ca,
<add> int cp, final int cl, long address, final long addressLimit, final Object unsafeObj,
<add> final long cumBaseOffset) {
<ide> while (address < addressLimit) {
<ide> final byte byte1 = unsafe.getByte(unsafeObj, address++);
<ide> if (DecodeUtil.isOneByte(byte1)) { |
|
Java | mit | 7b301a04dac58d5775a0dc775a897f5bb1be2403 | 0 | CS2103JAN2017-T11-B3/main,CS2103JAN2017-T11-B3/main | package seedu.task.storage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import seedu.task.commons.exceptions.DataConversionException;
import seedu.task.commons.util.FileUtil;
import seedu.task.model.ReadOnlyTaskList;
import seedu.task.model.TaskList;
import seedu.task.model.task.Task;
import seedu.task.testutil.TypicalTestTasks;
public class XmlTaskListStorageTest {
private static final String TEST_DATA_FOLDER = FileUtil.getPath("./src/test/data/XmlTaskListStorageTest/");
@Rule
public ExpectedException thrown = ExpectedException.none();
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Test
public void readTaskListNullFilePathAssertionFailure() throws Exception {
thrown.expect(AssertionError.class);
java.util.Optional<ReadOnlyTaskList> tl = readTaskList(null);
assertNull(tl);
}
private java.util.Optional<ReadOnlyTaskList> readTaskList(String filePath) throws Exception {
return new XmlTaskListStorage(filePath).readTaskList(addToTestDataPathIfNotNull(filePath));
}
private String addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) {
return prefsFileInTestDataFolder != null ? TEST_DATA_FOLDER + prefsFileInTestDataFolder : null;
}
@Test
public void readMissingFileEmptyResult() throws Exception {
assertFalse(readTaskList("NonExistentFile.xml").isPresent());
}
@Test
public void readNotXmlFormatExceptionThrown() throws Exception {
thrown.expect(DataConversionException.class);
readTaskList("NotXmlFormatTaskList.xml");
fail();
// * IMPORTANT: Any code below an exception-throwing line (like the one
// * above) will be ignored. That means you should not have more than one
// * exception test in one method
}
@Test
public void readAndSaveTaskListAllInOrderSuccess() throws Exception {
String filePath = testFolder.getRoot().getPath() + "TempTaskList.xml";
TypicalTestTasks td = new TypicalTestTasks();
TaskList original = td.getTypicalTaskList();
XmlTaskListStorage xmlTaskListStorage = new XmlTaskListStorage(filePath);
// Save in new file and read back
xmlTaskListStorage.saveTaskList(original, filePath);
ReadOnlyTaskList readBack = xmlTaskListStorage.readTaskList(filePath).get();
assertEquals(original, new TaskList(readBack));
// Modify data, overwrite exiting file, and read back
original.addTask(new Task(td.hoon));
original.removeTask(new Task(td.alice));
xmlTaskListStorage.saveTaskList(original, filePath);
readBack = xmlTaskListStorage.readTaskList(filePath).get();
assertEquals(original, new TaskList(readBack));
// Save and read without specifying file path
original.addTask(new Task(td.ida));
xmlTaskListStorage.saveTaskList(original); // file path not specified
readBack = xmlTaskListStorage.readTaskList().get(); // file path not
// specified
assertEquals(original, new TaskList(readBack));
}
@Test
public void saveTaskListNullTaskListAssertionFailure() throws IOException {
thrown.expect(AssertionError.class);
saveTaskList(null, "SomeFile.xml");
fail();
}
private void saveTaskList(ReadOnlyTaskList taskList, String filePath) throws IOException {
new XmlTaskListStorage(filePath).saveTaskList(taskList, addToTestDataPathIfNotNull(filePath));
}
@Test
public void saveTaskListNullFilePathAssertionFailure() throws IOException {
thrown.expect(AssertionError.class);
saveTaskList(new TaskList(), null);
fail();
}
}
| src/test/java/seedu/task/storage/XmlTaskListStorageTest.java | // package seedu.task.storage;
// import static org.junit.Assert.assertEquals;
// import static org.junit.Assert.assertFalse;
// import static org.junit.Assert.assertNull;
// import static org.junit.Assert.fail;
// import java.io.IOException;
// import org.junit.Rule;
// import org.junit.Test;
// import org.junit.rules.ExpectedException;
// import org.junit.rules.TemporaryFolder;
// import seedu.task.commons.exceptions.DataConversionException;
// import seedu.task.commons.util.FileUtil;
// import seedu.task.model.ReadOnlyTaskList;
// import seedu.task.model.TaskList;
// import seedu.task.model.task.Task;
// import seedu.task.testutil.TypicalTestTasks;
// public class XmlTaskListStorageTest {
// private static final String TEST_DATA_FOLDER = FileUtil.getPath("./src/test/data/XmlTaskListStorageTest/");
// @Rule
// public ExpectedException thrown = ExpectedException.none();
// @Rule
// public TemporaryFolder testFolder = new TemporaryFolder();
// @Test
// public void readTaskListNullFilePathAssertionFailure() throws Exception {
// thrown.expect(AssertionError.class);
// java.util.Optional<ReadOnlyTaskList> tl = readTaskList(null);
// assertNull(tl);
// }
// private java.util.Optional<ReadOnlyTaskList> readTaskList(String filePath) throws Exception {
// return new XmlTaskListStorage(filePath).readTaskList(addToTestDataPathIfNotNull(filePath));
// }
// private String addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) {
// return prefsFileInTestDataFolder != null ? TEST_DATA_FOLDER + prefsFileInTestDataFolder : null;
// }
// @Test
// public void readMissingFileEmptyResult() throws Exception {
// assertFalse(readTaskList("NonExistentFile.xml").isPresent());
// }
// @Test
// public void readNotXmlFormatExceptionThrown() throws Exception {
// thrown.expect(DataConversionException.class);
// readTaskList("NotXmlFormatTaskList.xml");
// fail();
// * IMPORTANT: Any code below an exception-throwing line (like the one
// * above) will be ignored. That means you should not have more than one
// * exception test in one method
// }
// @Test
// public void readAndSaveTaskListAllInOrderSuccess() throws Exception {
// String filePath = testFolder.getRoot().getPath() + "TempTaskList.xml";
// TypicalTestTasks td = new TypicalTestTasks();
// TaskList original = td.getTypicalTaskList();
// XmlTaskListStorage xmlTaskListStorage = new XmlTaskListStorage(filePath);
// // Save in new file and read back
// xmlTaskListStorage.saveTaskList(original, filePath);
// ReadOnlyTaskList readBack = xmlTaskListStorage.readTaskList(filePath).get();
// assertEquals(original, new TaskList(readBack));
// // Modify data, overwrite exiting file, and read back
// original.addTask(new Task(td.hoon));
// original.removeTask(new Task(td.alice));
// xmlTaskListStorage.saveTaskList(original, filePath);
// readBack = xmlTaskListStorage.readTaskList(filePath).get();
// assertEquals(original, new TaskList(readBack));
// // Save and read without specifying file path
// original.addTask(new Task(td.ida));
// xmlTaskListStorage.saveTaskList(original); // file path not specified
// readBack = xmlTaskListStorage.readTaskList().get(); // file path not
// // specified
// assertEquals(original, new TaskList(readBack));
// }
// @Test
// public void saveTaskListNullTaskListAssertionFailure() throws IOException {
// thrown.expect(AssertionError.class);
// saveTaskList(null, "SomeFile.xml");
// fail();
// }
// private void saveTaskList(ReadOnlyTaskList taskList, String filePath) throws IOException {
// new XmlTaskListStorage(filePath).saveTaskList(taskList, addToTestDataPathIfNotNull(filePath));
// }
// @Test
// public void saveTaskListNullFilePathAssertionFailure() throws IOException {
// thrown.expect(AssertionError.class);
// saveTaskList(new TaskList(), null);
// fail();
// }
// }
| uncomment XmlTaskListStorageTest.java
| src/test/java/seedu/task/storage/XmlTaskListStorageTest.java | uncomment XmlTaskListStorageTest.java | <ide><path>rc/test/java/seedu/task/storage/XmlTaskListStorageTest.java
<del>// package seedu.task.storage;
<add>package seedu.task.storage;
<ide>
<del>// import static org.junit.Assert.assertEquals;
<del>// import static org.junit.Assert.assertFalse;
<del>// import static org.junit.Assert.assertNull;
<del>// import static org.junit.Assert.fail;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<add>import static org.junit.Assert.assertNull;
<add>import static org.junit.Assert.fail;
<ide>
<del>// import java.io.IOException;
<add>import java.io.IOException;
<ide>
<del>// import org.junit.Rule;
<del>// import org.junit.Test;
<del>// import org.junit.rules.ExpectedException;
<del>// import org.junit.rules.TemporaryFolder;
<add>import org.junit.Rule;
<add>import org.junit.Test;
<add>import org.junit.rules.ExpectedException;
<add>import org.junit.rules.TemporaryFolder;
<ide>
<del>// import seedu.task.commons.exceptions.DataConversionException;
<del>// import seedu.task.commons.util.FileUtil;
<del>// import seedu.task.model.ReadOnlyTaskList;
<del>// import seedu.task.model.TaskList;
<del>// import seedu.task.model.task.Task;
<del>// import seedu.task.testutil.TypicalTestTasks;
<add>import seedu.task.commons.exceptions.DataConversionException;
<add>import seedu.task.commons.util.FileUtil;
<add>import seedu.task.model.ReadOnlyTaskList;
<add>import seedu.task.model.TaskList;
<add>import seedu.task.model.task.Task;
<add>import seedu.task.testutil.TypicalTestTasks;
<ide>
<del>// public class XmlTaskListStorageTest {
<del>// private static final String TEST_DATA_FOLDER = FileUtil.getPath("./src/test/data/XmlTaskListStorageTest/");
<add>public class XmlTaskListStorageTest {
<add> private static final String TEST_DATA_FOLDER = FileUtil.getPath("./src/test/data/XmlTaskListStorageTest/");
<ide>
<del>// @Rule
<del>// public ExpectedException thrown = ExpectedException.none();
<add> @Rule
<add> public ExpectedException thrown = ExpectedException.none();
<ide>
<del>// @Rule
<del>// public TemporaryFolder testFolder = new TemporaryFolder();
<add> @Rule
<add> public TemporaryFolder testFolder = new TemporaryFolder();
<ide>
<del>// @Test
<del>// public void readTaskListNullFilePathAssertionFailure() throws Exception {
<del>// thrown.expect(AssertionError.class);
<del>// java.util.Optional<ReadOnlyTaskList> tl = readTaskList(null);
<del>// assertNull(tl);
<del>// }
<add> @Test
<add> public void readTaskListNullFilePathAssertionFailure() throws Exception {
<add> thrown.expect(AssertionError.class);
<add> java.util.Optional<ReadOnlyTaskList> tl = readTaskList(null);
<add> assertNull(tl);
<add> }
<ide>
<del>// private java.util.Optional<ReadOnlyTaskList> readTaskList(String filePath) throws Exception {
<del>// return new XmlTaskListStorage(filePath).readTaskList(addToTestDataPathIfNotNull(filePath));
<del>// }
<add> private java.util.Optional<ReadOnlyTaskList> readTaskList(String filePath) throws Exception {
<add> return new XmlTaskListStorage(filePath).readTaskList(addToTestDataPathIfNotNull(filePath));
<add> }
<ide>
<del>// private String addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) {
<del>// return prefsFileInTestDataFolder != null ? TEST_DATA_FOLDER + prefsFileInTestDataFolder : null;
<del>// }
<add> private String addToTestDataPathIfNotNull(String prefsFileInTestDataFolder) {
<add> return prefsFileInTestDataFolder != null ? TEST_DATA_FOLDER + prefsFileInTestDataFolder : null;
<add> }
<ide>
<del>// @Test
<del>// public void readMissingFileEmptyResult() throws Exception {
<del>// assertFalse(readTaskList("NonExistentFile.xml").isPresent());
<del>// }
<add> @Test
<add> public void readMissingFileEmptyResult() throws Exception {
<add> assertFalse(readTaskList("NonExistentFile.xml").isPresent());
<add> }
<ide>
<del>// @Test
<del>// public void readNotXmlFormatExceptionThrown() throws Exception {
<add> @Test
<add> public void readNotXmlFormatExceptionThrown() throws Exception {
<ide>
<del>// thrown.expect(DataConversionException.class);
<del>// readTaskList("NotXmlFormatTaskList.xml");
<del>// fail();
<add> thrown.expect(DataConversionException.class);
<add> readTaskList("NotXmlFormatTaskList.xml");
<add> fail();
<ide>
<del>// * IMPORTANT: Any code below an exception-throwing line (like the one
<del>// * above) will be ignored. That means you should not have more than one
<del>// * exception test in one method
<add> // * IMPORTANT: Any code below an exception-throwing line (like the one
<add> // * above) will be ignored. That means you should not have more than one
<add> // * exception test in one method
<ide>
<del>// }
<add> }
<ide>
<del>// @Test
<del>// public void readAndSaveTaskListAllInOrderSuccess() throws Exception {
<del>// String filePath = testFolder.getRoot().getPath() + "TempTaskList.xml";
<del>// TypicalTestTasks td = new TypicalTestTasks();
<del>// TaskList original = td.getTypicalTaskList();
<del>// XmlTaskListStorage xmlTaskListStorage = new XmlTaskListStorage(filePath);
<add> @Test
<add> public void readAndSaveTaskListAllInOrderSuccess() throws Exception {
<add> String filePath = testFolder.getRoot().getPath() + "TempTaskList.xml";
<add> TypicalTestTasks td = new TypicalTestTasks();
<add> TaskList original = td.getTypicalTaskList();
<add> XmlTaskListStorage xmlTaskListStorage = new XmlTaskListStorage(filePath);
<ide>
<del>// // Save in new file and read back
<del>// xmlTaskListStorage.saveTaskList(original, filePath);
<del>// ReadOnlyTaskList readBack = xmlTaskListStorage.readTaskList(filePath).get();
<del>// assertEquals(original, new TaskList(readBack));
<add> // Save in new file and read back
<add> xmlTaskListStorage.saveTaskList(original, filePath);
<add> ReadOnlyTaskList readBack = xmlTaskListStorage.readTaskList(filePath).get();
<add> assertEquals(original, new TaskList(readBack));
<ide>
<del>// // Modify data, overwrite exiting file, and read back
<del>// original.addTask(new Task(td.hoon));
<del>// original.removeTask(new Task(td.alice));
<del>// xmlTaskListStorage.saveTaskList(original, filePath);
<del>// readBack = xmlTaskListStorage.readTaskList(filePath).get();
<del>// assertEquals(original, new TaskList(readBack));
<add> // Modify data, overwrite exiting file, and read back
<add> original.addTask(new Task(td.hoon));
<add> original.removeTask(new Task(td.alice));
<add> xmlTaskListStorage.saveTaskList(original, filePath);
<add> readBack = xmlTaskListStorage.readTaskList(filePath).get();
<add> assertEquals(original, new TaskList(readBack));
<ide>
<del>// // Save and read without specifying file path
<del>// original.addTask(new Task(td.ida));
<del>// xmlTaskListStorage.saveTaskList(original); // file path not specified
<del>// readBack = xmlTaskListStorage.readTaskList().get(); // file path not
<del>// // specified
<del>// assertEquals(original, new TaskList(readBack));
<add> // Save and read without specifying file path
<add> original.addTask(new Task(td.ida));
<add> xmlTaskListStorage.saveTaskList(original); // file path not specified
<add> readBack = xmlTaskListStorage.readTaskList().get(); // file path not
<add> // specified
<add> assertEquals(original, new TaskList(readBack));
<ide>
<del>// }
<add> }
<ide>
<del>// @Test
<del>// public void saveTaskListNullTaskListAssertionFailure() throws IOException {
<del>// thrown.expect(AssertionError.class);
<del>// saveTaskList(null, "SomeFile.xml");
<del>// fail();
<del>// }
<add> @Test
<add> public void saveTaskListNullTaskListAssertionFailure() throws IOException {
<add> thrown.expect(AssertionError.class);
<add> saveTaskList(null, "SomeFile.xml");
<add> fail();
<add> }
<ide>
<del>// private void saveTaskList(ReadOnlyTaskList taskList, String filePath) throws IOException {
<del>// new XmlTaskListStorage(filePath).saveTaskList(taskList, addToTestDataPathIfNotNull(filePath));
<del>// }
<add> private void saveTaskList(ReadOnlyTaskList taskList, String filePath) throws IOException {
<add> new XmlTaskListStorage(filePath).saveTaskList(taskList, addToTestDataPathIfNotNull(filePath));
<add> }
<ide>
<del>// @Test
<del>// public void saveTaskListNullFilePathAssertionFailure() throws IOException {
<del>// thrown.expect(AssertionError.class);
<del>// saveTaskList(new TaskList(), null);
<del>// fail();
<del>// }
<add> @Test
<add> public void saveTaskListNullFilePathAssertionFailure() throws IOException {
<add> thrown.expect(AssertionError.class);
<add> saveTaskList(new TaskList(), null);
<add> fail();
<add> }
<ide>
<del>// }
<add>} |
|
JavaScript | mit | 47fd5df29939a800b6a70ad730d9e7170d9c495f | 0 | palmerhq/backpack | const fs = require('fs')
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const config = require('./paths')
const path = require('path')
const babelPreset = require('../babel')
// This is the Webpack configuration.
// It is focused on developer experience and fast rebuilds.
module.exports = (options) => {
const babelRcPath = path.resolve('.babelrc')
const hasBabelRc = fs.existsSync(babelRcPath)
const mainBabelOptions = {
babelrc: true,
cacheDirectory: true,
presets: []
}
if (hasBabelRc) {
console.log('> Using .babelrc defined in your app root')
} else {
mainBabelOptions.presets.push(require.resolve('../babel'))
}
return {
// Webpack can target multiple environments such as `node`,
// `browser`, and even `electron`. Since Backpack is focused on Node,
// we set the default target accordingly.
target: 'node',
// The benefit of Webpack over just using babel-cli or babel-node
// command is sourcemap support. Although it slows down compilation,
// it makes debugging dramatically easier.
devtool: 'source-map',
// Webpack allows you to define externals - modules that should not be
// bundled. When bundling with Webpack for the backend - you usually
// don't want to bundle its node_modules dependencies. This creates an externals
// function that ignores node_modules when bundling in Webpack.
// @see https://github.com/liady/webpack-node-externals
externals: nodeExternals({
whitelist: [
/\.(eot|woff|woff2|ttf|otf)$/,
/\.(svg|png|jpg|jpeg|gif|ico|webm)$/,
/\.(mp4|mp3|ogg|swf|webp)$/,
/\.(css|scss|sass|less|styl)$/,
]
}),
// As of Webpack 2 beta, Webpack provides performance hints.
// Since we are not targeting a browser, bundle size is not relevant.
// Additionally, the performance hints clutter up our nice error messages.
performance: {
hints: false
},
// Since we are wrapping our own webpack config, we need to properly resolve
// Backpack's and the given user's node_modules without conflict.
resolve: {
extensions: ['.js', '.json'],
modules: [config.userNodeModulesPath, path.resolve(__dirname, '../node_modules')]
},
resolveLoader: {
modules: [config.userNodeModulesPath, path.resolve(__dirname, '../node_modules')]
},
node: {
__filename: true,
__dirname: true
},
entry: {
main: [
`${config.serverSrcPath}/index.js`
],
},
// This sets the default output file path, name, and compile target
// module type. Since we are focused on Node.js, the libraryTarget
// is set to CommonJS2
output: {
path: config.serverBuildPath,
filename: '[name].js',
sourceMapFilename: '[name].map',
publicPath: config.publicPath,
libraryTarget: 'commonjs2'
},
// Define a few default Webpack loaders. Notice the use of the new
// Webpack 2 configuration: module.rules instead of module.loaders
module: {
rules: [
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
{
test: /\.json$/,
loader: 'json-loader'
},
// Process JS with Babel (transpiles ES6 code into ES5 code).
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: [
/node_modules/,
config.buildPath
],
options: mainBabelOptions
}
]
},
plugins: [
// We define some sensible Webpack flags. One for the Node environment,
// and one for dev / production. These become global variables. Note if
// you use something like eslint or standard in your editor, you will
// want to configure __DEV__ as a global variable accordingly.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(options.env),
'__DEV__': options.env === 'development'
}),
// In order to provide sourcemaps, we automagically insert this at the
// top of each file using the BannerPlugin.
new webpack.BannerPlugin({
raw: true,
entryOnly: false,
banner: `require('${
// Is source-map-support installed as project dependency, or linked?
( require.resolve('source-map-support').indexOf(process.cwd()) === 0 )
// If it's resolvable from the project root, it's a project dependency.
? 'source-map-support/register'
// It's not under the project, it's linked via lerna.
: require.resolve('source-map-support/register')
}')`
}),
// The FriendlyErrorsWebpackPlugin (when combined with source-maps)
// gives Backpack its human-readable error messages.
new FriendlyErrorsWebpackPlugin(),
// The NoEmitOnErrorsPlugin plugin prevents Webpack
// from printing out compile time stats to the console.
new webpack.NoEmitOnErrorsPlugin()
]
}
}
| packages/backpack-core/config/webpack.config.js | const fs = require('fs')
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const config = require('./paths')
const path = require('path')
const babelPreset = require('../babel')
// This is the Webpack configuration.
// It is focused on developer experience and fast rebuilds.
module.exports = (options) => {
const babelRcPath = path.resolve('.babelrc')
const hasBabelRc = fs.existsSync(babelRcPath)
const mainBabelOptions = {
babelrc: true,
cacheDirectory: true,
presets: []
}
if (hasBabelRc) {
console.log('> Using .babelrc defined in your app root')
} else {
mainBabelOptions.presets.push(require.resolve('../babel'))
}
return {
// Webpack can target multiple environments such as `node`,
// `browser`, and even `electron`. Since Backpack is focused on Node,
// we set the default target accordingly.
target: 'node',
// The benefit of Webpack over just using babel-cli or babel-node
// command is sourcemap support. Although it slows down compilation,
// it makes debugging dramatically easier.
devtool: 'source-map',
// Webpack allows you to define externals - modules that should not be
// bundled. When bundling with Webpack for the backend - you usually
// don't want to bundle its node_modules dependencies. This creates an externals
// function that ignores node_modules when bundling in Webpack.
// @see https://github.com/liady/webpack-node-externals
externals: nodeExternals({
whitelist: [
/\.(eot|woff|woff2|ttf|otf)$/,
/\.(svg|png|jpg|jpeg|gif|ico|webm)$/,
/\.(mp4|mp3|ogg|swf|webp)$/,
/\.(css|scss|sass|less|styl)$/,
]
}),
// As of Webpack 2 beta, Webpack provides performance hints.
// Since we are not targeting a browser, bundle size is not relevant.
// Additionally, the performance hints clutter up our nice error messages.
performance: {
hints: false
},
// Since we are wrapping our own webpack config, we need to properly resolve
// Backpack's and the given user's node_modules without conflict.
resolve: {
extensions: ['.js', '.json'],
modules: [config.userNodeModulesPath, path.resolve(__dirname, '../node_modules')]
},
resolveLoader: {
modules: [config.userNodeModulesPath, path.resolve(__dirname, '../node_modules')]
},
node: {
__filename: true,
__dirname: true
},
entry: {
main: [
`${config.serverSrcPath}/index.js`
],
},
// This sets the default output file path, name, and compile target
// module type. Since we are focused on Node.js, the libraryTarget
// is set to CommonJS2
output: {
path: config.serverBuildPath,
filename: '[name].js',
sourceMapFilename: '[name].map',
publicPath: config.publicPath,
libraryTarget: 'commonjs2'
},
// Define a few default Webpack loaders. Notice the use of the new
// Webpack 2 configuration: module.rules instead of module.loaders
module: {
rules: [
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
{
test: /\.json$/,
loader: 'json-loader'
},
// Process JS with Babel (transpiles ES6 code into ES5 code).
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: [
/node_modules/,
config.buildPath
],
options: mainBabelOptions
}
]
},
plugins: [
// We define some sensible Webpack flags. One for the Node environment,
// and one for dev / production. These become global variables. Note if
// you use something like eslint or standard in your editor, you will
// want to configure __DEV__ as a global variable accordingly.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(options.env),
'__DEV__': options.env === 'development'
}),
// In order to provide sourcemaps, we automagically insert this at the
// top of each file using the BannerPlugin.
new webpack.BannerPlugin({
raw: true,
entryOnly: false,
banner: `require('${
// Is source-map-support installed as project dependency, or linked?
( require.resolve('source-map-support').indexOf(process.cwd()) === 0 )
// If it's resolvable from the project root, it's a project dependency.
? 'source-map-support/register'
// It's not under the project, it's linked via lerna.
: require.resolve('source-map-support/register')
}')`
}),
// The FriendlyErrorsWebpackPlugin (when combined with source-maps)
// gives Backpack its human-readable error messages.
new FriendlyErrorsWebpackPlugin(),
// This plugin is awkwardly named. Use to be called NoErrorsPlugin.
// It does not actually swallow errors. Instead, it just prevents
// Webpack from printing out compile time stats to the console.
// @todo new webpack.NoEmitOnErrorsPlugin()
new webpack.NoErrorsPlugin()
]
}
}
| Use NoEmitOnErrorsPlugin instead of NoErrorsPlugin (#68)
| packages/backpack-core/config/webpack.config.js | Use NoEmitOnErrorsPlugin instead of NoErrorsPlugin (#68) | <ide><path>ackages/backpack-core/config/webpack.config.js
<ide> // The FriendlyErrorsWebpackPlugin (when combined with source-maps)
<ide> // gives Backpack its human-readable error messages.
<ide> new FriendlyErrorsWebpackPlugin(),
<del> // This plugin is awkwardly named. Use to be called NoErrorsPlugin.
<del> // It does not actually swallow errors. Instead, it just prevents
<del> // Webpack from printing out compile time stats to the console.
<del> // @todo new webpack.NoEmitOnErrorsPlugin()
<del> new webpack.NoErrorsPlugin()
<add> // The NoEmitOnErrorsPlugin plugin prevents Webpack
<add> // from printing out compile time stats to the console.
<add> new webpack.NoEmitOnErrorsPlugin()
<ide> ]
<ide> }
<ide> } |
|
Java | bsd-2-clause | 1b3c5ba863dce0d0b61ae7643fc1694133c96976 | 0 | radai-rosenblatt/li-apache-kafka-clients,radai-rosenblatt/li-apache-kafka-clients | /*
* Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License").
See License in the project root for license information.
*/
package com.linkedin.kafka.clients.consumer;
import com.linkedin.kafka.clients.auditing.NoOpAuditor;
import com.linkedin.kafka.clients.largemessage.DefaultSegmentDeserializer;
import com.linkedin.kafka.clients.largemessage.DefaultSegmentSerializer;
import com.linkedin.kafka.clients.largemessage.MessageSplitter;
import com.linkedin.kafka.clients.largemessage.MessageSplitterImpl;
import com.linkedin.kafka.clients.largemessage.errors.ConsumerRecordsProcessingException;
import com.linkedin.kafka.clients.producer.LiKafkaProducer;
import com.linkedin.kafka.clients.producer.UUIDFactory;
import com.linkedin.kafka.clients.utils.LiKafkaClientsUtils;
import com.linkedin.kafka.clients.utils.tests.AbstractKafkaClientsIntegrationTestHarness;
import com.linkedin.kafka.clients.utils.tests.KafkaTestUtils;
import java.util.Comparator;
import java.util.HashSet;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.NoOffsetForPartitionException;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
import org.apache.kafka.clients.consumer.OffsetCommitCallback;
import org.apache.kafka.clients.consumer.OffsetOutOfRangeException;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.Deserializer;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.testng.Assert.*;
/**
* Integration test for LiKafkaConsumer
*/
public class LiKafkaConsumerIntegrationTest extends AbstractKafkaClientsIntegrationTestHarness {
private final int MESSAGE_COUNT = 1000;
private Random _random;
private final String TOPIC1 = "topic1";
private final String TOPIC2 = "topic2";
private final int NUM_PRODUCER = 2;
private final int THREADS_PER_PRODUCER = 2;
private final int NUM_PARTITIONS = 4;
private final int MAX_SEGMENT_SIZE = 200;
private final int SYNTHETIC_PARTITION_0 = 0;
private final int SYNTHETIC_PARTITION_1 = 1;
private ConcurrentMap<String, String> _messages;
@Override
public Properties overridingProps() {
Properties props = new Properties();
props.setProperty("num.partitions", Integer.toString(NUM_PARTITIONS));
return props;
}
/**
* This test will have a topic with some partitions having interleaved large messages as well as some ordinary
* sized messages. The topic will be used for all the sub-tests.
*/
@BeforeMethod
@Override
public void setUp() {
super.setUp();
}
@AfterMethod
@Override
public void tearDown() {
super.tearDown();
}
@Test
public void testSeek() {
String topic = "testSeek";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testSeek");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
// Now seek to message offset 0
consumer.seek(tp, 0);
verifyMessagesAfterSeek(consumer, Arrays.asList(2L, 4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 1 which is not a message offset and is earlier than the first delivered message.
// in this case, the consumer will seek to the safe offset of the partition.
consumer.seek(tp, 1);
assertEquals(consumer.position(tp), 0L, "The position should be 0 after the seek.");
verifyMessagesAfterSeek(consumer, Arrays.asList(2L, 4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 2
consumer.seek(tp, 2);
verifyMessagesAfterSeek(consumer, Arrays.asList(2L, 4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 3, it is a non message offset. The consumer will actually seek to safe offset
// of 2. m2 should be ignored and m1 should be delivered.
consumer.seek(tp, 3);
verifyMessagesAfterSeek(consumer, Arrays.asList(4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 4, m1 should be delivered but m2 should not be delivered.
consumer.seek(tp, 4);
verifyMessagesAfterSeek(consumer, Arrays.asList(4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 5, m0 should be delivered but m1 and m2 should not be delivered.
consumer.seek(tp, 5);
verifyMessagesAfterSeek(consumer, Arrays.asList(5L, 6L, 7L, 9L));
// Now seek to message offset 6, m3 should be delivered but m2 should not be delivered.
consumer.seek(tp, 6);
assertEquals(consumer.position(tp), 3L);
verifyMessagesAfterSeek(consumer, Arrays.asList(6L, 7L, 9L));
// Now seek to message offset 7, m4 should be delivered but m2 should not be delivered.
consumer.seek(tp, 7);
verifyMessagesAfterSeek(consumer, Arrays.asList(7L, 9L));
// Now seek to message offset 8, m5 should be delivered.
consumer.seek(tp, 8);
verifyMessagesAfterSeek(consumer, Arrays.asList(9L));
// Now seek to message offset 9, m5 should be delivered.
consumer.seek(tp, 9);
verifyMessagesAfterSeek(consumer, Arrays.asList(9L));
}
}
private void verifyMessagesAfterSeek(LiKafkaConsumer<String, String> consumer,
List<Long> expectedOffsets) {
ConsumerRecords<String, String> records;
for (long expectedOffset : expectedOffsets) {
records = null;
while (records == null || records.isEmpty()) {
records = consumer.poll(10);
}
assertEquals(records.count(), 1, "Should return one message");
assertEquals(records.iterator().next().offset(), expectedOffset, "Message offset should be " + expectedOffset);
}
}
@Test
public void testCommit() {
String topic = "testCommit";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommit");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
TopicPartition tp1 = new TopicPartition(topic, SYNTHETIC_PARTITION_1);
consumer.assign(Arrays.asList(tp, tp1));
while (consumer.poll(10).isEmpty()) {
//M2
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(3, ""), "The committed user offset should be 3");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
assertEquals(consumer.position(tp1), 2L, "The position of partition 1 should be 2.");
assertEquals(consumer.committedSafeOffset(tp1).longValue(), 0L, "The committed safe offset for partition 1 should be 0.");
assertEquals(consumer.committed(tp1).offset(), 2L, "The committed offset for partition 1 should be 2.");
while (consumer.poll(10).isEmpty()) {
// M1
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(5, ""), "The committed user offset should be 5");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(4)));
assertEquals(consumer.committed(tp).offset(), 4, "The committed user offset should 4");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
while (consumer.poll(10).isEmpty()) {
// M0
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(6, ""), "The committed user offset should be 6");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 3, "The committed actual offset should be 3");
while (consumer.poll(10).isEmpty()) {
// M3
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(7, ""), "The committed user offset should be 7");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 7, "The committed actual offset should be 7");
while (consumer.poll(10).isEmpty()) {
// M4
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(8, ""), "The committed user offset should be 8");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 8, "The committed actual offset should be 8");
// test commit offset 0
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0)));
assertEquals(consumer.committed(tp), new OffsetAndMetadata(0, ""), "The committed user offset should be 0");
consumer.close();
consumer = createConsumer(props);
consumer.assign(Collections.singleton(tp));
consumer.seekToCommitted(Collections.singleton(tp));
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(8, "new commit")));
assertEquals(consumer.committed(tp), new OffsetAndMetadata(8, "new commit"));
assertEquals(consumer.committedSafeOffset(tp).longValue(), 8);
} finally {
consumer.close();
}
}
@Test
public void testCommitWithOffsetMap() {
String topic = "testCommitWithOffsetMap";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommitWithOffsetMap");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
// First test tracked range from 0 to 9
consumer.seekToBeginning(Collections.singleton(tp));
while (consumer.position(tp) != 10) {
consumer.poll(10L);
}
// test commit first tracked offset.
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0L)));
assertEquals(0L, consumer.committed(tp).offset());
assertEquals(0L, consumer.committedSafeOffset(tp).longValue());
// test last consumed offset + 1
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(10L)));
assertEquals(10L, consumer.committed(tp).offset());
assertEquals(10L, consumer.committedSafeOffset(tp).longValue());
// test a delivered offset (offset of M0 is 5L)
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(6L)));
assertEquals(6L, consumer.committed(tp).offset());
assertEquals(3L, consumer.committedSafeOffset(tp).longValue());
// test a non-message offset,
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(3L)));
assertEquals(3L, consumer.committed(tp).offset());
assertEquals(0L, consumer.committedSafeOffset(tp).longValue());
// Now test tracked range from 2 to 9
consumer.seek(tp, 100L); // clear up internal state.
consumer.seek(tp, 2L);
while (consumer.position(tp) != 10) {
consumer.poll(10L);
}
// test commit an offset smaller than the first tracked offset.
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0L)));
assertEquals(0L, consumer.committed(tp).offset());
assertEquals(0L, consumer.committedSafeOffset(tp).longValue());
// test commit first tracked offset.
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(2L)));
assertEquals(2L, consumer.committed(tp).offset());
assertEquals(2L, consumer.committedSafeOffset(tp).longValue());
// test last consumed offset + 1
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(10L)));
assertEquals(10L, consumer.committed(tp).offset());
assertEquals(4L, consumer.committedSafeOffset(tp).longValue());
// test a delivered offset (offset of M3 is 6L)
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(7L)));
assertEquals(7L, consumer.committed(tp).offset());
assertEquals(4L, consumer.committedSafeOffset(tp).longValue());
// test a non-message offset,
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(3L)));
assertEquals(3L, consumer.committed(tp).offset());
assertEquals(3L, consumer.committedSafeOffset(tp).longValue());
} finally {
consumer.close();
}
}
@Test
public void testSeekToBeginningAndEnd() {
String topic = "testSeekToBeginningAndEnd";
produceSyntheticMessages(topic);
Properties props = new Properties();
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testSeekToBeginningAndEnd");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
LiKafkaConsumer<String, String> tempConsumer = createConsumer(props);
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
// We commit some message to the broker before seek to end. This is to test if the consumer will be affected
// by committed offsets after seek to beginning or end.
tempConsumer.assign(Collections.singleton(tp));
tempConsumer.seek(tp, Long.MAX_VALUE);
tempConsumer.commitSync();
tempConsumer.close();
// Produce a message and ensure it can be consumed.
Properties producerProps = new Properties();
producerProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
LiKafkaProducer<String, String> producer = createProducer(producerProps)) {
consumer.assign(Collections.singleton(tp));
// Seek to beginning, the follow up poll() should ignore the committed high watermark.
consumer.seekToBeginning(Collections.singleton(tp));
ConsumerRecords<String, String> records = consumer.poll(1000L);
assertEquals(records.iterator().next().offset(), 2L, "Should see message offset 2.");
consumer.seekToEnd(Collections.singleton(tp));
consumer.poll(10L);
assertEquals(10L, consumer.position(tp));
producer.send(new ProducerRecord<>(topic, SYNTHETIC_PARTITION_0, null, "test"));
producer.close();
records = consumer.poll(1000L);
assertEquals(records.iterator().next().offset(), 10L, "Should see message offset 10.");
}
}
/**
* This test tests the seekToCommitted() behavior with the following synthetic data:
* 0: M0_SEG0
* 1: M1_SEG0
* 2: M2_SEG0(END)
* 3: M3_SEG0
* 4: M1_SEG1(END)
* 5: M0_SEG1(END)
* 6: M3_SEG1(END)
* 7: M4_SEG0(END)
* 8: M5_SEG0
* 9: M5_SEG1(END)
*/
@Test
public void testSeekToCommitted() {
String topic = "testSeekToCommitted";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testSeekToCommitted");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
ConsumerRecords<String, String> records = waitForData(consumer, 30000); //M2
assertEquals(records.count(), 1, "Should have consumed 1 message");
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(3, ""), "The committed user offset should be 3");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
consumer.close();
consumer = createConsumer(props);
consumer.assign(Collections.singleton(tp));
// This should work the same as seekToCommitted.
consumer.seek(tp, consumer.committed(tp).offset());
assertEquals(consumer.position(tp), 0, "The committed safe offset should be 0");
records = waitForData(consumer, 30000); // M1
assertEquals(records.count(), 1, "There should be only one record.");
assertEquals(records.iterator().next().offset(), 4, "The message offset should be 4");
} finally {
consumer.close();
}
}
private ConsumerRecords<String, String> waitForData(LiKafkaConsumer<String, String> consumer, long timeout) {
long now = System.currentTimeMillis();
long deadline = now + timeout;
while (System.currentTimeMillis() < deadline) {
ConsumerRecords<String, String> records = consumer.poll(1000);
if (records != null && records.count() > 0) {
return records;
}
}
Assert.fail("failed to read any records within time limit");
return null;
}
@Test
public void testOffsetCommitCallback() throws Exception {
String topic = "testOffsetCommitCallback";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testOffsetCommitCallback");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
waitForData(consumer, 30000); // M2
OffsetAndMetadata committed = commitAndRetrieveOffsets(consumer, tp, null);
assertEquals(committed, new OffsetAndMetadata(3, ""), "The committed user offset should be 3, instead was " + committed);
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
offsetMap.put(tp, new OffsetAndMetadata(0));
committed = commitAndRetrieveOffsets(consumer, tp, offsetMap);
assertEquals(committed, new OffsetAndMetadata(0, ""), "The committed user offset should be 0, instead was " + committed);
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
}
}
private OffsetAndMetadata commitAndRetrieveOffsets(
LiKafkaConsumer<String, String> consumer,
TopicPartition tp, Map<TopicPartition,
OffsetAndMetadata> offsetMap) throws Exception {
final AtomicBoolean callbackFired = new AtomicBoolean(false);
final AtomicReference<Exception> offsetCommitIssue = new AtomicReference<>(null);
OffsetAndMetadata committed = null;
long now = System.currentTimeMillis();
long deadline = now + TimeUnit.MINUTES.toMillis(1);
while (System.currentTimeMillis() < deadline) {
//call commitAsync, wait for a NON-NULL return value (see https://issues.apache.org/jira/browse/KAFKA-6183)
OffsetCommitCallback commitCallback = new OffsetCommitCallback() {
@Override
public void onComplete(Map<TopicPartition, OffsetAndMetadata> topicPartitionOffsetAndMetadataMap, Exception e) {
if (e != null) {
offsetCommitIssue.set(e);
}
callbackFired.set(true);
}
};
if (offsetMap != null) {
consumer.commitAsync(offsetMap, commitCallback);
} else {
consumer.commitAsync(commitCallback);
}
while (!callbackFired.get()) {
consumer.poll(20);
}
Assert.assertNull(offsetCommitIssue.get(), "offset commit failed");
committed = consumer.committed(tp);
if (committed != null) {
break;
}
Thread.sleep(100);
}
assertNotNull(committed, "unable to retrieve committed offsets within timeout");
return committed;
}
@Test
public void testCommittedOnOffsetsCommittedByRawConsumer() {
String topic = "testCommittedOnOffsetsCommittedByRawConsumer";
TopicPartition tp = new TopicPartition(topic, 0);
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommittedOnOffsetsCommittedByRawConsumer");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
Consumer<byte[], byte[]> rawConsumer = new KafkaConsumer<>(getConsumerProperties(props))) {
consumer.assign(Collections.singleton(tp));
rawConsumer.assign(Collections.singleton(tp));
// Test commit an offset without metadata
rawConsumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0L)));
OffsetAndMetadata offsetAndMetadata = consumer.committed(tp);
assertEquals(offsetAndMetadata.offset(), 0L);
assertEquals(offsetAndMetadata.metadata(), "");
}
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
Consumer<byte[], byte[]> rawConsumer = new KafkaConsumer<>(getConsumerProperties(props))) {
consumer.assign(Collections.singleton(tp));
rawConsumer.assign(Collections.singleton(tp));
// Test commit an offset with metadata containing no comma
rawConsumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(1L, "test")));
OffsetAndMetadata offsetAndMetadata = consumer.committed(tp);
assertEquals(offsetAndMetadata.offset(), 1L);
assertEquals(offsetAndMetadata.metadata(), "test");
}
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
Consumer<byte[], byte[]> rawConsumer = new KafkaConsumer<>(getConsumerProperties(props))) {
consumer.assign(Collections.singleton(tp));
rawConsumer.assign(Collections.singleton(tp));
// Test commit an offset with metadata containing a comma
rawConsumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(2L, "test,test")));
OffsetAndMetadata offsetAndMetadata = consumer.committed(tp);
assertEquals(offsetAndMetadata.offset(), 2L);
assertEquals(offsetAndMetadata.metadata(), "test,test");
}
}
@Test
public void testSeekAfterAssignmentChange() {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty("group.id", "testSeekAfterAssignmentChange");
// Make sure we start to consume from the beginning
props.setProperty("auto.offset.reset", "earliest");
// Consumer at most 100 messages per poll
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "100");
// Set max fetch size to a small value
props.setProperty(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, "2000");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
TopicPartition tp0 = new TopicPartition(TOPIC1, 0);
TopicPartition tp1 = new TopicPartition(TOPIC1, 1);
consumer.assign(Arrays.asList(tp0, tp1));
// Consume some messages
ConsumerRecords<String, String> records = null;
while (records == null || records.isEmpty()) {
records = consumer.poll(5000);
}
consumer.assign(Collections.singleton(tp1));
records = null;
while (records == null || records.isEmpty()) {
records = consumer.poll(5000);
}
// we should be able to seek on tp 0 after assignment change.
consumer.assign(Arrays.asList(tp0, tp1));
assertEquals(consumer.safeOffset(tp0), null, "The safe offset for " + tp0 + " should be null now.");
// We should be able to seek to 0 freely.
consumer.seek(tp0, 0);
}
@Test
public void testUnsubscribe() {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty("group.id", "testUnsubscribe");
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", "earliest");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
TopicPartition tp = new TopicPartition(TOPIC1, 0);
consumer.subscribe(Collections.singleton(TOPIC1));
try {
ConsumerRecords<String, String> records = null;
while (records == null || !records.isEmpty()) {
records = consumer.poll(5000);
}
// Seek forward should work.
consumer.seek(tp, 100000L);
// After unsubscribe an IllegalStateException should be seen.
consumer.unsubscribe();
try {
consumer.seek(tp, 100000L);
fail();
} catch (IllegalStateException lse) {
// let it go
}
} finally {
consumer.close();
}
}
@Test
public void testPosition() {
String topic = "testSeek";
TopicPartition tp = new TopicPartition(topic, 0);
produceSyntheticMessages(topic);
// Reset to earliest
Properties props = new Properties();
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testPosition1");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
consumer.assign(Collections.singleton(tp));
assertEquals(0, consumer.position(tp));
}
// Reset to latest
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testPosition2");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
consumer.assign(Collections.singleton(tp));
assertEquals(consumer.position(tp), 10);
}
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none");
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testPosition3");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
consumer.assign(Collections.singleton(tp));
consumer.position(tp);
fail("Should have thrown NoOffsetForPartitionException");
} catch (NoOffsetForPartitionException nofpe) {
// let it go.
}
}
/**
* This is an aggressive rebalance test.
* There are two consumers in the same group consuming from two topics.
* The two topics contains mostly large messages.
* The two consumers will change their subscription frequently to trigger rebalances.
* The test makes sure that all the messages are consumed exactly once.
*/
@Test
public void testRebalance() {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testRebalance");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Consumer at most 100 messages per poll
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "100");
// Set max fetch size to a small value
props.setProperty(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, "2000");
// Set heartbeat interval to a small value
props.setProperty(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "10");
// Enable auto offset commit so the offsets will be committed during rebalance.
props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
props.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, "consumer0");
LiKafkaConsumer<String, String> consumer0 = createConsumer(props);
props.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, "consumer1");
LiKafkaConsumer<String, String> consumer1 = createConsumer(props);
final Map<String, String> messageUnseen = new ConcurrentSkipListMap<>(_messages);
Thread thread0 = new RebalanceTestConsumerThread(consumer0, messageUnseen, 0);
Thread thread1 = new RebalanceTestConsumerThread(consumer1, messageUnseen, 1);
thread0.start();
thread1.start();
try {
thread0.join();
thread1.join();
} catch (InterruptedException e) {
// Do nothing
} finally {
consumer0.close();
consumer1.close();
}
assertEquals(messageUnseen.size(), 0, "Messages unseen: " + messageUnseen.keySet());
}
/**
* This test mimics the following sequence:
* 1. User started a consumer to consume
* 2. Consumer commits offset according to the message it receives.
* 3. A consumer die/close at some point
* 4. Another consumer in the same group starts and try to resume from committed offsets.
* The partitions that is consumed should have many interleaved messages. After stopping and resuming consumption,
* the consumers should not miss any message.
* <p>
* This test indirectly tested the following methods:
* <li>{@link LiKafkaConsumer#subscribe(java.util.Collection)}
* <li>{@link LiKafkaConsumer#poll(long)}
* <li>{@link LiKafkaConsumer#commitSync()}
* <li>{@link LiKafkaConsumer#close()}
*
* @throws InterruptedException
*/
@Test
public void testCommitAndResume() throws InterruptedException {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", "earliest");
// All the consumers should have the same group id.
props.setProperty("group.id", "testCommitAndResume");
// Reduce the fetch size for each partition to make sure we will poll() multiple times.
props.setProperty("max.partition.fetch.bytes", "6400");
props.setProperty("enable.auto.commit", "false");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
// Subscribe to the partitions.
consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2));
// Create a new map to record unseen messages which initially contains all the produced _messages.
Map<String, String> messagesUnseen = new ConcurrentSkipListMap<>(new MessageIdComparator());
messagesUnseen.putAll(_messages);
long startTime = System.currentTimeMillis();
int numMessagesConsumed = 0;
int lastCommitAndResume = 0;
int numCommitAndResume = 0;
Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
ConsumerRecords<String, String> records;
while (!messagesUnseen.isEmpty() && startTime + 30000 > System.currentTimeMillis()) {
records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
String messageId = messageId(record.topic(), record.partition(), record.offset());
// We should not see any duplicate message.
String origMessage = messagesUnseen.get(messageId);
assertEquals(record.value(), origMessage, "Message with id \"" + messageId + "\" should be the same.");
messagesUnseen.remove(messageId);
offsetMap.put(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset() + 1));
numMessagesConsumed++;
// We try to stop and recreate a consumer every MESSAGE_COUNT messages and at most stop and resume 4 times.
if (lastCommitAndResume + (NUM_PRODUCER * THREADS_PER_PRODUCER * MESSAGE_COUNT) / 4 < numMessagesConsumed &&
numCommitAndResume < 4 && offsetMap.size() == 2 * NUM_PARTITIONS) {
consumer.commitSync(offsetMap);
consumer.close();
offsetMap.clear();
consumer = createConsumer(props);
consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2));
lastCommitAndResume = numMessagesConsumed;
numCommitAndResume++;
break;
}
}
}
assertEquals(messagesUnseen.size(), 0, "Stop and resumed " + numCommitAndResume + "times, consumed " +
numMessagesConsumed + " messages. ");
} finally {
consumer.close();
}
}
/**
* Test search offset by timestamp
*/
@Test
public void testSearchOffsetByTimestamp() {
Properties props = new Properties();
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", "earliest");
// All the consumers should have the same group id.
props.setProperty("group.id", "testSearchOffsetByTimestamp");
props.setProperty("enable.auto.commit", "false");
produceRecordsWithKafkaProducer();
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
// Consume the messages with largest 10 timestamps.
for (int i = 0; i < NUM_PARTITIONS; i++) {
timestampsToSearch.put(new TopicPartition(TOPIC1, i), (long) MESSAGE_COUNT - 10);
}
consumer.assign(timestampsToSearch.keySet());
Map<TopicPartition, OffsetAndTimestamp> offsets = consumer.offsetsForTimes(timestampsToSearch);
for (Map.Entry<TopicPartition, OffsetAndTimestamp> entry : offsets.entrySet()) {
consumer.seek(entry.getKey(), entry.getValue().offset());
}
int i = 0;
Map<Long, Integer> messageCount = new HashMap<>();
long start = System.currentTimeMillis();
while (i < NUM_PRODUCER * THREADS_PER_PRODUCER * 10 && System.currentTimeMillis() < start + 20000) {
ConsumerRecords<String, String> consumerRecords = consumer.poll(100);
for (ConsumerRecord record : consumerRecords) {
if (record.timestamp() >= MESSAGE_COUNT - 10) {
int count = messageCount.getOrDefault(record.timestamp(), 0);
messageCount.put(record.timestamp(), count + 1);
i++;
}
}
}
assertEquals(i, NUM_PRODUCER * THREADS_PER_PRODUCER * 10);
assertEquals(messageCount.size(), 10, "Should have consumed messages of all 10 timestamps");
int expectedCount = NUM_PRODUCER * THREADS_PER_PRODUCER;
for (Integer count : messageCount.values()) {
assertEquals(count.intValue(), expectedCount, "Each partition should have " + expectedCount + " messages");
}
}
}
@Test
public void testExceptionInProcessing() {
String topic = "testExceptionInProcessing";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommit");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
LiKafkaConsumer<byte[], byte[]> consumer =
new LiKafkaConsumerImpl<byte[], byte[]>(getConsumerProperties(props),
new ByteArrayDeserializer(),
new Deserializer<byte[]>() {
int numMessages = 0;
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
}
@Override
public byte[] deserialize(String topic, byte[] data) {
// Throw exception when deserializing the second message.
numMessages++;
if (numMessages == 2) {
throw new SerializationException();
}
return data;
}
@Override
public void close() {
}
}, new DefaultSegmentDeserializer(), new NoOpAuditor<>());
try {
consumer.subscribe(Collections.singleton(topic));
ConsumerRecords<byte[], byte[]> records = ConsumerRecords.empty();
while (records.isEmpty()) {
records = consumer.poll(1000);
}
assertEquals(records.count(), 1, "Only the first message should be returned");
assertEquals(records.iterator().next().offset(), 2L, "The offset of the first message should be 2.");
assertEquals(consumer.position(new TopicPartition(topic, 0)), 5L, "The position should be 5");
try {
consumer.poll(1000);
fail("Should have thrown exception.");
} catch (ConsumerRecordsProcessingException crpe) {
// let it go
}
assertEquals(consumer.position(new TopicPartition(topic, 0)), 5L, "The position should be 5");
records = ConsumerRecords.empty();
while (records.isEmpty()) {
records = consumer.poll(1000);
}
assertEquals(records.count(), 4, "There should be four messages left.");
assertEquals(records.iterator().next().offset(), 5L, "The first offset should 5");
} finally {
consumer.close();
}
}
@Test
public void testOffsetOutOfRange() {
for (OffsetResetStrategy strategy : OffsetResetStrategy.values()) {
testOffsetOutOfRangeForStrategy(strategy);
}
}
private void testOffsetOutOfRangeForStrategy(OffsetResetStrategy strategy) {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", strategy.name());
// All the consumers should have the same group id.
props.setProperty("group.id", "testOffsetOutOfRange");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
TopicPartition tp = new TopicPartition(TOPIC1, 0);
try {
consumer.assign(Collections.singleton(tp));
ConsumerRecords<String, String> consumerRecords = ConsumerRecords.empty();
consumer.seek(tp, 0);
while (consumerRecords.isEmpty()) {
consumerRecords = consumer.poll(1000);
}
consumer.seek(tp, 100000L);
assertEquals(consumer.position(tp), 100000L);
if (strategy == OffsetResetStrategy.EARLIEST) {
long expectedOffset = consumerRecords.iterator().next().offset();
consumerRecords = ConsumerRecords.empty();
while (consumerRecords.isEmpty()) {
consumerRecords = consumer.poll(1000);
}
assertEquals(consumerRecords.iterator().next().offset(), expectedOffset,
"The offset should have been reset to the earliest offset");
} else if (strategy == OffsetResetStrategy.LATEST) {
consumer.poll(1000);
long expectedOffset = consumer.endOffsets(Collections.singleton(tp)).get(tp);
assertEquals(consumer.position(tp), expectedOffset, "The offset should have been reset to the latest offset");
} else {
consumer.poll(1000);
fail("OffsetOutOfRangeException should have been thrown.");
}
} catch (OffsetOutOfRangeException ooore) {
if (strategy != OffsetResetStrategy.NONE) {
fail("Should not have thrown OffsetOutOfRangeException.");
}
} finally {
consumer.close();
}
}
/**
* This method produce a bunch of messages in an interleaved way.
* @param messages will contain both large message and ordinary messages.
*/
private void produceMessages(ConcurrentMap<String, String> messages, String topic) throws InterruptedException {
Properties props = new Properties();
// Enable large messages.
props.setProperty("large.message.enabled", "true");
// Set segment size to 200 so we have many large messages.
props.setProperty("max.message.segment.size", Integer.toString(MAX_SEGMENT_SIZE));
props.setProperty("client.id", "testProducer");
// Set batch size to 1 to make sure each message is a batch so we have a lot interleave messages.
props.setProperty("batch.size", "1");
// Create a few producers to make sure we have interleaved large messages.
List<LiKafkaProducer<String, String>> producers = new ArrayList<>();
for (int i = 0; i < NUM_PRODUCER; i++) {
producers.add(createProducer(props));
}
// Let each producer have a few user threads sending messages.
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < NUM_PRODUCER; i++) {
for (int j = 0; j < THREADS_PER_PRODUCER; j++) {
threads.add(new ProducerThread(producers.get(i), messages, topic));
}
}
// Start user threads.
for (Thread thread : threads) {
thread.start();
}
// Wait until the user threads finish sending.
for (Thread thread : threads) {
thread.join();
}
// Close producers.
for (LiKafkaProducer<String, String> producer : producers) {
producer.close();
}
}
private static final class MessageIdComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
String[] parts1 = o1.split("-");
String[] parts2 = o2.split("-");
int diff = parts1[0].compareTo(parts2[0]);
if (diff != 0) {
return diff;
}
diff = Integer.parseInt(parts1[1]) - Integer.parseInt(parts2[1]);
if (diff != 0) {
return diff;
}
return Integer.parseInt(parts1[2]) - Integer.parseInt(parts2[2]);
}
}
private class ProducerThread extends Thread {
private final LiKafkaProducer<String, String> _producer;
private final ConcurrentMap<String, String> _messages;
private final String _topic;
public ProducerThread(LiKafkaProducer<String, String> producer,
ConcurrentMap<String, String> messages,
String topic) {
_producer = producer;
_messages = messages;
_topic = topic;
}
@Override
public void run() {
final Set<String> ackedMessages = new HashSet<>();
for (int i = 0; i < MESSAGE_COUNT; i++) {
// The message size is set to 100 - 1124, So we should have most of the messages to be large messages
// while still have some ordinary size messages.
int messageSize = 100 + _random.nextInt(1024);
final String uuid = LiKafkaClientsUtils.randomUUID().toString().replace("-", "");
final String message = uuid + KafkaTestUtils.getRandomString(messageSize);
_producer.send(new ProducerRecord<String, String>(_topic, null, (long) i, null, message),
new Callback() {
@Override
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
// The callback should have been invoked only once.
assertFalse(ackedMessages.contains(uuid));
if (e == null) {
ackedMessages.add(uuid);
} else {
e.printStackTrace();
}
assertNull(e);
String messageId = messageId(recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset());
_messages.put(messageId, message);
}
});
}
}
}
/**
* This is a key we use to check what records have been produced.
*/
private static String messageId(String topic, int partition, long offset) {
return topic + "-" + partition + "-" + offset;
}
private void produceRecordsWithKafkaProducer() {
_messages = new ConcurrentSkipListMap<>();
_random = new Random(23423423);
try {
produceMessages(_messages, TOPIC1);
produceMessages(_messages, TOPIC2);
} catch (InterruptedException e) {
throw new RuntimeException("Message producing phase failed.", e);
}
}
/** Generate the following synthetic messages in order and produce to the same partition.
* <pre>
* partition SYNTHETIC_PARTITION_0
* 0: M0_SEG0 (START)
* 1: M1_SEG0 (START)
* 2: M2_SEG0 (START) (END)
* 3: M3_SEG0 (START)
* 4: M1_SEG1(END)
* 5: M0_SEG1(END)
* 6: M3_SEG1(END)
* 7: M4_SEG0 (START) (END)
* 8: M5_SEG0 (START)
* 9: M5_SEG1 (END)
* </pre>
*/
private void produceSyntheticMessages(String topic) {
MessageSplitter splitter = new MessageSplitterImpl(MAX_SEGMENT_SIZE,
new DefaultSegmentSerializer(),
new UUIDFactory.DefaultUUIDFactory<>());
Producer<byte[], byte[]> producer = createKafkaProducer();
// Prepare messages.
int messageSize = MAX_SEGMENT_SIZE + MAX_SEGMENT_SIZE / 2;
// M0, 2 segments
UUID messageId0 = LiKafkaClientsUtils.randomUUID();
String message0 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m0Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId0, message0.getBytes());
// M1, 2 segments
UUID messageId1 = LiKafkaClientsUtils.randomUUID();
String message1 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m1Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId1, message1.getBytes());
// M2, 1 segment
UUID messageId2 = LiKafkaClientsUtils.randomUUID();
String message2 = KafkaTestUtils.getRandomString(MAX_SEGMENT_SIZE / 2);
List<ProducerRecord<byte[], byte[]>> m2Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId2, message2.getBytes());
// M3, 2 segment
UUID messageId3 = LiKafkaClientsUtils.randomUUID();
String message3 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m3Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId3, message3.getBytes());
// M4, 1 segment
UUID messageId4 = LiKafkaClientsUtils.randomUUID();
String message4 = KafkaTestUtils.getRandomString(MAX_SEGMENT_SIZE / 2);
List<ProducerRecord<byte[], byte[]>> m4Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId4, message4.getBytes());
// M5, 2 segments
UUID messageId5 = LiKafkaClientsUtils.randomUUID();
String message5 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m5Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId5, message5.getBytes());
// Add two more segment to partition SYNTHETIC_PARTITION_1 for corner case test.
List<ProducerRecord<byte[], byte[]>> m0SegsPartition1 = splitter.split(topic, SYNTHETIC_PARTITION_1, LiKafkaClientsUtils.randomUUID(), message0.getBytes());
List<ProducerRecord<byte[], byte[]>> m1SegsPartition1 = splitter.split(topic, SYNTHETIC_PARTITION_1, LiKafkaClientsUtils.randomUUID(), message1.getBytes());
try {
producer.send(m0Segs.get(0)).get();
producer.send(m1Segs.get(0)).get();
producer.send(m2Segs.get(0)).get();
producer.send(m3Segs.get(0)).get();
producer.send(m1Segs.get(1)).get();
producer.send(m0Segs.get(1)).get();
producer.send(m3Segs.get(1)).get();
producer.send(m4Segs.get(0)).get();
producer.send(m5Segs.get(0)).get();
producer.send(m5Segs.get(1)).get();
producer.send(m0SegsPartition1.get(0)).get();
producer.send(m1SegsPartition1.get(0)).get();
} catch (Exception e) {
fail("Produce synthetic data failed.", e);
}
producer.close();
}
//TODO - remove / refactor
private Producer<byte[], byte[]> createKafkaProducer() {
Properties props = new Properties();
props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getCanonicalName());
props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getCanonicalName());
Properties finalProducerProps = getProducerProperties(props);
return new KafkaProducer(finalProducerProps);
}
private class RebalanceTestConsumerThread extends Thread {
private final LiKafkaConsumer<String, String> _consumer;
private final int _id;
private final Map<String, String> _messageUnseen;
private final TestRebalanceListener _listener;
RebalanceTestConsumerThread(LiKafkaConsumer<String, String> consumer,
Map<String, String> messageUnseen,
int id) {
super("consumer-thread-" + id);
_consumer = consumer;
_id = id;
_messageUnseen = messageUnseen;
_listener = new TestRebalanceListener();
}
private void processConsumedRecord(ConsumerRecords<String, String> records) {
for (ConsumerRecord<String, String> record : records) {
String messageId = messageId(record.topic(), record.partition(), record.offset());
String origMessage = _messageUnseen.get(messageId);
assertEquals(record.value(), origMessage, "Message should be the same. partition = " +
record.topic() + "-" + record.partition() + ", offset = " + record.offset());
_messageUnseen.remove(messageId);
}
}
@Override
public void run() {
try {
_consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2), _listener);
long startMs = System.currentTimeMillis();
while (!_messageUnseen.isEmpty() && System.currentTimeMillis() - startMs < 30000) {
int numConsumed = 0;
while (numConsumed < 150 && !_messageUnseen.isEmpty() && System.currentTimeMillis() - startMs < 30000) {
ConsumerRecords<String, String> records = _consumer.poll(10);
numConsumed += records.count();
processConsumedRecord(records);
}
// Let the consumer to change the subscriptions based on the thread id.
if (_id % 2 == 0) {
if (_consumer.subscription().contains(TOPIC2)) {
_consumer.subscribe(Collections.singleton(TOPIC1), _listener);
} else {
_consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2), _listener);
}
} else {
if (_consumer.subscription().contains(TOPIC1)) {
_consumer.subscribe(Collections.singleton(TOPIC2), _listener);
} else {
_consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2), _listener);
}
}
_listener.done = false;
while (!_messageUnseen.isEmpty() && !_listener.done) {
processConsumedRecord(_consumer.poll(10));
}
}
} catch (Throwable t) {
t.printStackTrace();
}
}
private class TestRebalanceListener implements ConsumerRebalanceListener {
public boolean done = false;
@Override
public void onPartitionsRevoked(Collection<TopicPartition> topicPartitions) {
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> topicPartitions) {
done = true;
}
}
}
}
| integration-tests/src/test/java/com/linkedin/kafka/clients/consumer/LiKafkaConsumerIntegrationTest.java | /*
* Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License").
See License in the project root for license information.
*/
package com.linkedin.kafka.clients.consumer;
import com.linkedin.kafka.clients.auditing.NoOpAuditor;
import com.linkedin.kafka.clients.largemessage.DefaultSegmentDeserializer;
import com.linkedin.kafka.clients.largemessage.DefaultSegmentSerializer;
import com.linkedin.kafka.clients.largemessage.MessageSplitter;
import com.linkedin.kafka.clients.largemessage.MessageSplitterImpl;
import com.linkedin.kafka.clients.largemessage.errors.ConsumerRecordsProcessingException;
import com.linkedin.kafka.clients.producer.LiKafkaProducer;
import com.linkedin.kafka.clients.producer.UUIDFactory;
import com.linkedin.kafka.clients.utils.LiKafkaClientsUtils;
import com.linkedin.kafka.clients.utils.tests.AbstractKafkaClientsIntegrationTestHarness;
import com.linkedin.kafka.clients.utils.tests.KafkaTestUtils;
import java.util.Comparator;
import java.util.HashSet;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.NoOffsetForPartitionException;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
import org.apache.kafka.clients.consumer.OffsetCommitCallback;
import org.apache.kafka.clients.consumer.OffsetOutOfRangeException;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.Deserializer;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.fail;
/**
* Integration test for LiKafkaConsumer
*/
public class LiKafkaConsumerIntegrationTest extends AbstractKafkaClientsIntegrationTestHarness {
private final int MESSAGE_COUNT = 1000;
private Random _random;
private final String TOPIC1 = "topic1";
private final String TOPIC2 = "topic2";
private final int NUM_PRODUCER = 2;
private final int THREADS_PER_PRODUCER = 2;
private final int NUM_PARTITIONS = 4;
private final int MAX_SEGMENT_SIZE = 200;
private final int SYNTHETIC_PARTITION_0 = 0;
private final int SYNTHETIC_PARTITION_1 = 1;
private ConcurrentMap<String, String> _messages;
@Override
public Properties overridingProps() {
Properties props = new Properties();
props.setProperty("num.partitions", Integer.toString(NUM_PARTITIONS));
return props;
}
/**
* This test will have a topic with some partitions having interleaved large messages as well as some ordinary
* sized messages. The topic will be used for all the sub-tests.
*/
@BeforeMethod
@Override
public void setUp() {
super.setUp();
}
@AfterMethod
@Override
public void tearDown() {
super.tearDown();
}
@Test
public void testSeek() {
String topic = "testSeek";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testSeek");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
// Now seek to message offset 0
consumer.seek(tp, 0);
verifyMessagesAfterSeek(consumer, Arrays.asList(2L, 4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 1 which is not a message offset and is earlier than the first delivered message.
// in this case, the consumer will seek to the safe offset of the partition.
consumer.seek(tp, 1);
assertEquals(consumer.position(tp), 0L, "The position should be 0 after the seek.");
verifyMessagesAfterSeek(consumer, Arrays.asList(2L, 4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 2
consumer.seek(tp, 2);
verifyMessagesAfterSeek(consumer, Arrays.asList(2L, 4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 3, it is a non message offset. The consumer will actually seek to safe offset
// of 2. m2 should be ignored and m1 should be delivered.
consumer.seek(tp, 3);
verifyMessagesAfterSeek(consumer, Arrays.asList(4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 4, m1 should be delivered but m2 should not be delivered.
consumer.seek(tp, 4);
verifyMessagesAfterSeek(consumer, Arrays.asList(4L, 5L, 6L, 7L, 9L));
// Now seek to message offset 5, m0 should be delivered but m1 and m2 should not be delivered.
consumer.seek(tp, 5);
verifyMessagesAfterSeek(consumer, Arrays.asList(5L, 6L, 7L, 9L));
// Now seek to message offset 6, m3 should be delivered but m2 should not be delivered.
consumer.seek(tp, 6);
assertEquals(consumer.position(tp), 3L);
verifyMessagesAfterSeek(consumer, Arrays.asList(6L, 7L, 9L));
// Now seek to message offset 7, m4 should be delivered but m2 should not be delivered.
consumer.seek(tp, 7);
verifyMessagesAfterSeek(consumer, Arrays.asList(7L, 9L));
// Now seek to message offset 8, m5 should be delivered.
consumer.seek(tp, 8);
verifyMessagesAfterSeek(consumer, Arrays.asList(9L));
// Now seek to message offset 9, m5 should be delivered.
consumer.seek(tp, 9);
verifyMessagesAfterSeek(consumer, Arrays.asList(9L));
}
}
private void verifyMessagesAfterSeek(LiKafkaConsumer<String, String> consumer,
List<Long> expectedOffsets) {
ConsumerRecords<String, String> records;
for (long expectedOffset : expectedOffsets) {
records = null;
while (records == null || records.isEmpty()) {
records = consumer.poll(10);
}
assertEquals(records.count(), 1, "Should return one message");
assertEquals(records.iterator().next().offset(), expectedOffset, "Message offset should be " + expectedOffset);
}
}
@Test
public void testCommit() {
String topic = "testCommit";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommit");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
TopicPartition tp1 = new TopicPartition(topic, SYNTHETIC_PARTITION_1);
consumer.assign(Arrays.asList(tp, tp1));
while (consumer.poll(10).isEmpty()) {
//M2
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(3, ""), "The committed user offset should be 3");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
assertEquals(consumer.position(tp1), 2L, "The position of partition 1 should be 2.");
assertEquals(consumer.committedSafeOffset(tp1).longValue(), 0L, "The committed safe offset for partition 1 should be 0.");
assertEquals(consumer.committed(tp1).offset(), 2L, "The committed offset for partition 1 should be 2.");
while (consumer.poll(10).isEmpty()) {
// M1
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(5, ""), "The committed user offset should be 5");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(4)));
assertEquals(consumer.committed(tp).offset(), 4, "The committed user offset should 4");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
while (consumer.poll(10).isEmpty()) {
// M0
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(6, ""), "The committed user offset should be 6");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 3, "The committed actual offset should be 3");
while (consumer.poll(10).isEmpty()) {
// M3
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(7, ""), "The committed user offset should be 7");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 7, "The committed actual offset should be 7");
while (consumer.poll(10).isEmpty()) {
// M4
}
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(8, ""), "The committed user offset should be 8");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 8, "The committed actual offset should be 8");
// test commit offset 0
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0)));
assertEquals(consumer.committed(tp), new OffsetAndMetadata(0, ""), "The committed user offset should be 0");
consumer.close();
consumer = createConsumer(props);
consumer.assign(Collections.singleton(tp));
consumer.seekToCommitted(Collections.singleton(tp));
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(8, "new commit")));
assertEquals(consumer.committed(tp), new OffsetAndMetadata(8, "new commit"));
assertEquals(consumer.committedSafeOffset(tp).longValue(), 8);
} finally {
consumer.close();
}
}
@Test
public void testCommitWithOffsetMap() {
String topic = "testCommitWithOffsetMap";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommitWithOffsetMap");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
// First test tracked range from 0 to 9
consumer.seekToBeginning(Collections.singleton(tp));
while (consumer.position(tp) != 10) {
consumer.poll(10L);
}
// test commit first tracked offset.
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0L)));
assertEquals(0L, consumer.committed(tp).offset());
assertEquals(0L, consumer.committedSafeOffset(tp).longValue());
// test last consumed offset + 1
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(10L)));
assertEquals(10L, consumer.committed(tp).offset());
assertEquals(10L, consumer.committedSafeOffset(tp).longValue());
// test a delivered offset (offset of M0 is 5L)
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(6L)));
assertEquals(6L, consumer.committed(tp).offset());
assertEquals(3L, consumer.committedSafeOffset(tp).longValue());
// test a non-message offset,
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(3L)));
assertEquals(3L, consumer.committed(tp).offset());
assertEquals(0L, consumer.committedSafeOffset(tp).longValue());
// Now test tracked range from 2 to 9
consumer.seek(tp, 100L); // clear up internal state.
consumer.seek(tp, 2L);
while (consumer.position(tp) != 10) {
consumer.poll(10L);
}
// test commit an offset smaller than the first tracked offset.
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0L)));
assertEquals(0L, consumer.committed(tp).offset());
assertEquals(0L, consumer.committedSafeOffset(tp).longValue());
// test commit first tracked offset.
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(2L)));
assertEquals(2L, consumer.committed(tp).offset());
assertEquals(2L, consumer.committedSafeOffset(tp).longValue());
// test last consumed offset + 1
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(10L)));
assertEquals(10L, consumer.committed(tp).offset());
assertEquals(4L, consumer.committedSafeOffset(tp).longValue());
// test a delivered offset (offset of M3 is 6L)
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(7L)));
assertEquals(7L, consumer.committed(tp).offset());
assertEquals(4L, consumer.committedSafeOffset(tp).longValue());
// test a non-message offset,
consumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(3L)));
assertEquals(3L, consumer.committed(tp).offset());
assertEquals(3L, consumer.committedSafeOffset(tp).longValue());
} finally {
consumer.close();
}
}
@Test
public void testSeekToBeginningAndEnd() {
String topic = "testSeekToBeginningAndEnd";
produceSyntheticMessages(topic);
Properties props = new Properties();
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testSeekToBeginningAndEnd");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
LiKafkaConsumer<String, String> tempConsumer = createConsumer(props);
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
// We commit some message to the broker before seek to end. This is to test if the consumer will be affected
// by committed offsets after seek to beginning or end.
tempConsumer.assign(Collections.singleton(tp));
tempConsumer.seek(tp, Long.MAX_VALUE);
tempConsumer.commitSync();
tempConsumer.close();
// Produce a message and ensure it can be consumed.
Properties producerProps = new Properties();
producerProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers());
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
LiKafkaProducer<String, String> producer = createProducer(producerProps)) {
consumer.assign(Collections.singleton(tp));
// Seek to beginning, the follow up poll() should ignore the committed high watermark.
consumer.seekToBeginning(Collections.singleton(tp));
ConsumerRecords<String, String> records = consumer.poll(1000L);
assertEquals(records.iterator().next().offset(), 2L, "Should see message offset 2.");
consumer.seekToEnd(Collections.singleton(tp));
consumer.poll(10L);
assertEquals(10L, consumer.position(tp));
producer.send(new ProducerRecord<>(topic, SYNTHETIC_PARTITION_0, null, "test"));
producer.close();
records = consumer.poll(1000L);
assertEquals(records.iterator().next().offset(), 10L, "Should see message offset 10.");
}
}
/**
* This test tests the seekToCommitted() behavior with the following synthetic data:
* 0: M0_SEG0
* 1: M1_SEG0
* 2: M2_SEG0(END)
* 3: M3_SEG0
* 4: M1_SEG1(END)
* 5: M0_SEG1(END)
* 6: M3_SEG1(END)
* 7: M4_SEG0(END)
* 8: M5_SEG0
* 9: M5_SEG1(END)
*/
@Test
public void testSeekToCommitted() {
String topic = "testSeekToCommitted";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testSeekToCommitted");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
assertEquals(consumer.poll(5000).count(), 1, "Should have consumed 1 message"); // M2
consumer.commitSync();
assertEquals(consumer.committed(tp), new OffsetAndMetadata(3, ""), "The committed user offset should be 3");
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
consumer.close();
consumer = createConsumer(props);
consumer.assign(Collections.singleton(tp));
// This should work the same as seekToCommitted.
consumer.seek(tp, consumer.committed(tp).offset());
assertEquals(consumer.position(tp), 0, "The committed safe offset should be 0");
ConsumerRecords<String, String> records = consumer.poll(5000); // M1
assertEquals(records.count(), 1, "There should be only one record.");
assertEquals(records.iterator().next().offset(), 4, "The message offset should be 4");
} finally {
consumer.close();
}
}
@Test
public void testOffsetCommitCallback() {
String topic = "testOffsetCommitCallback";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testOffsetCommitCallback");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Only fetch one record at a time.
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
consumer.assign(Collections.singleton(tp));
consumer.poll(5000); // M2
final AtomicBoolean offsetCommitted = new AtomicBoolean(false);
OffsetCommitCallback commitCallback = new OffsetCommitCallback() {
@Override
public void onComplete(Map<TopicPartition, OffsetAndMetadata> topicPartitionOffsetAndMetadataMap, Exception e) {
offsetCommitted.set(true);
}
};
consumer.commitAsync(commitCallback);
while (!offsetCommitted.get()) {
consumer.poll(20);
}
OffsetAndMetadata committed = consumer.committed(tp);
assertEquals(committed, new OffsetAndMetadata(3, ""), "The committed user offset should be 3, instead was " + committed);
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
offsetCommitted.set(false);
Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
offsetMap.put(tp, new OffsetAndMetadata(0));
consumer.commitAsync(offsetMap, commitCallback);
while (!offsetCommitted.get()) {
consumer.poll(20);
}
committed = consumer.committed(tp);
assertEquals(committed, new OffsetAndMetadata(0, ""), "The committed user offset should be 0, instead was " + committed);
assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
}
}
@Test
public void testCommittedOnOffsetsCommittedByRawConsumer() {
String topic = "testCommittedOnOffsetsCommittedByRawConsumer";
TopicPartition tp = new TopicPartition(topic, 0);
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommittedOnOffsetsCommittedByRawConsumer");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
Consumer<byte[], byte[]> rawConsumer = new KafkaConsumer<>(getConsumerProperties(props))) {
consumer.assign(Collections.singleton(tp));
rawConsumer.assign(Collections.singleton(tp));
// Test commit an offset without metadata
rawConsumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(0L)));
OffsetAndMetadata offsetAndMetadata = consumer.committed(tp);
assertEquals(offsetAndMetadata.offset(), 0L);
assertEquals(offsetAndMetadata.metadata(), "");
}
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
Consumer<byte[], byte[]> rawConsumer = new KafkaConsumer<>(getConsumerProperties(props))) {
consumer.assign(Collections.singleton(tp));
rawConsumer.assign(Collections.singleton(tp));
// Test commit an offset with metadata containing no comma
rawConsumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(1L, "test")));
OffsetAndMetadata offsetAndMetadata = consumer.committed(tp);
assertEquals(offsetAndMetadata.offset(), 1L);
assertEquals(offsetAndMetadata.metadata(), "test");
}
try (LiKafkaConsumer<String, String> consumer = createConsumer(props);
Consumer<byte[], byte[]> rawConsumer = new KafkaConsumer<>(getConsumerProperties(props))) {
consumer.assign(Collections.singleton(tp));
rawConsumer.assign(Collections.singleton(tp));
// Test commit an offset with metadata containing a comma
rawConsumer.commitSync(Collections.singletonMap(tp, new OffsetAndMetadata(2L, "test,test")));
OffsetAndMetadata offsetAndMetadata = consumer.committed(tp);
assertEquals(offsetAndMetadata.offset(), 2L);
assertEquals(offsetAndMetadata.metadata(), "test,test");
}
}
@Test
public void testSeekAfterAssignmentChange() {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty("group.id", "testSeekAfterAssignmentChange");
// Make sure we start to consume from the beginning
props.setProperty("auto.offset.reset", "earliest");
// Consumer at most 100 messages per poll
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "100");
// Set max fetch size to a small value
props.setProperty(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, "2000");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
TopicPartition tp0 = new TopicPartition(TOPIC1, 0);
TopicPartition tp1 = new TopicPartition(TOPIC1, 1);
consumer.assign(Arrays.asList(tp0, tp1));
// Consume some messages
ConsumerRecords<String, String> records = null;
while (records == null || records.isEmpty()) {
records = consumer.poll(5000);
}
consumer.assign(Collections.singleton(tp1));
records = null;
while (records == null || records.isEmpty()) {
records = consumer.poll(5000);
}
// we should be able to seek on tp 0 after assignment change.
consumer.assign(Arrays.asList(tp0, tp1));
assertEquals(consumer.safeOffset(tp0), null, "The safe offset for " + tp0 + " should be null now.");
// We should be able to seek to 0 freely.
consumer.seek(tp0, 0);
}
@Test
public void testUnsubscribe() {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty("group.id", "testUnsubscribe");
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", "earliest");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
TopicPartition tp = new TopicPartition(TOPIC1, 0);
consumer.subscribe(Collections.singleton(TOPIC1));
try {
ConsumerRecords<String, String> records = null;
while (records == null || !records.isEmpty()) {
records = consumer.poll(5000);
}
// Seek forward should work.
consumer.seek(tp, 100000L);
// After unsubscribe an IllegalStateException should be seen.
consumer.unsubscribe();
try {
consumer.seek(tp, 100000L);
fail();
} catch (IllegalStateException lse) {
// let it go
}
} finally {
consumer.close();
}
}
@Test
public void testPosition() {
String topic = "testSeek";
TopicPartition tp = new TopicPartition(topic, 0);
produceSyntheticMessages(topic);
// Reset to earliest
Properties props = new Properties();
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testPosition1");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
consumer.assign(Collections.singleton(tp));
assertEquals(0, consumer.position(tp));
}
// Reset to latest
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testPosition2");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
consumer.assign(Collections.singleton(tp));
assertEquals(consumer.position(tp), 10);
}
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none");
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testPosition3");
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
consumer.assign(Collections.singleton(tp));
consumer.position(tp);
fail("Should have thrown NoOffsetForPartitionException");
} catch (NoOffsetForPartitionException nofpe) {
// let it go.
}
}
/**
* This is an aggressive rebalance test.
* There are two consumers in the same group consuming from two topics.
* The two topics contains mostly large messages.
* The two consumers will change their subscription frequently to trigger rebalances.
* The test makes sure that all the messages are consumed exactly once.
*/
@Test
public void testRebalance() {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testRebalance");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Consumer at most 100 messages per poll
props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "100");
// Set max fetch size to a small value
props.setProperty(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, "2000");
// Set heartbeat interval to a small value
props.setProperty(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, "10");
// Enable auto offset commit so the offsets will be committed during rebalance.
props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
props.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, "consumer0");
LiKafkaConsumer<String, String> consumer0 = createConsumer(props);
props.setProperty(ConsumerConfig.CLIENT_ID_CONFIG, "consumer1");
LiKafkaConsumer<String, String> consumer1 = createConsumer(props);
final Map<String, String> messageUnseen = new ConcurrentSkipListMap<>(_messages);
Thread thread0 = new RebalanceTestConsumerThread(consumer0, messageUnseen, 0);
Thread thread1 = new RebalanceTestConsumerThread(consumer1, messageUnseen, 1);
thread0.start();
thread1.start();
try {
thread0.join();
thread1.join();
} catch (InterruptedException e) {
// Do nothing
} finally {
consumer0.close();
consumer1.close();
}
assertEquals(messageUnseen.size(), 0, "Messages unseen: " + messageUnseen.keySet());
}
/**
* This test mimics the following sequence:
* 1. User started a consumer to consume
* 2. Consumer commits offset according to the message it receives.
* 3. A consumer die/close at some point
* 4. Another consumer in the same group starts and try to resume from committed offsets.
* The partitions that is consumed should have many interleaved messages. After stopping and resuming consumption,
* the consumers should not miss any message.
* <p>
* This test indirectly tested the following methods:
* <li>{@link LiKafkaConsumer#subscribe(java.util.Collection)}
* <li>{@link LiKafkaConsumer#poll(long)}
* <li>{@link LiKafkaConsumer#commitSync()}
* <li>{@link LiKafkaConsumer#close()}
*
* @throws InterruptedException
*/
@Test
public void testCommitAndResume() throws InterruptedException {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", "earliest");
// All the consumers should have the same group id.
props.setProperty("group.id", "testCommitAndResume");
// Reduce the fetch size for each partition to make sure we will poll() multiple times.
props.setProperty("max.partition.fetch.bytes", "6400");
props.setProperty("enable.auto.commit", "false");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
try {
// Subscribe to the partitions.
consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2));
// Create a new map to record unseen messages which initially contains all the produced _messages.
Map<String, String> messagesUnseen = new ConcurrentSkipListMap<>(new MessageIdComparator());
messagesUnseen.putAll(_messages);
long startTime = System.currentTimeMillis();
int numMessagesConsumed = 0;
int lastCommitAndResume = 0;
int numCommitAndResume = 0;
Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
ConsumerRecords<String, String> records;
while (!messagesUnseen.isEmpty() && startTime + 30000 > System.currentTimeMillis()) {
records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
String messageId = messageId(record.topic(), record.partition(), record.offset());
// We should not see any duplicate message.
String origMessage = messagesUnseen.get(messageId);
assertEquals(record.value(), origMessage, "Message with id \"" + messageId + "\" should be the same.");
messagesUnseen.remove(messageId);
offsetMap.put(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset() + 1));
numMessagesConsumed++;
// We try to stop and recreate a consumer every MESSAGE_COUNT messages and at most stop and resume 4 times.
if (lastCommitAndResume + (NUM_PRODUCER * THREADS_PER_PRODUCER * MESSAGE_COUNT) / 4 < numMessagesConsumed &&
numCommitAndResume < 4 && offsetMap.size() == 2 * NUM_PARTITIONS) {
consumer.commitSync(offsetMap);
consumer.close();
offsetMap.clear();
consumer = createConsumer(props);
consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2));
lastCommitAndResume = numMessagesConsumed;
numCommitAndResume++;
break;
}
}
}
assertEquals(messagesUnseen.size(), 0, "Stop and resumed " + numCommitAndResume + "times, consumed " +
numMessagesConsumed + " messages. ");
} finally {
consumer.close();
}
}
/**
* Test search offset by timestamp
*/
@Test
public void testSearchOffsetByTimestamp() {
Properties props = new Properties();
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", "earliest");
// All the consumers should have the same group id.
props.setProperty("group.id", "testSearchOffsetByTimestamp");
props.setProperty("enable.auto.commit", "false");
produceRecordsWithKafkaProducer();
try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
Map<TopicPartition, Long> timestampsToSearch = new HashMap<>();
// Consume the messages with largest 10 timestamps.
for (int i = 0; i < NUM_PARTITIONS; i++) {
timestampsToSearch.put(new TopicPartition(TOPIC1, i), (long) MESSAGE_COUNT - 10);
}
consumer.assign(timestampsToSearch.keySet());
Map<TopicPartition, OffsetAndTimestamp> offsets = consumer.offsetsForTimes(timestampsToSearch);
for (Map.Entry<TopicPartition, OffsetAndTimestamp> entry : offsets.entrySet()) {
consumer.seek(entry.getKey(), entry.getValue().offset());
}
int i = 0;
Map<Long, Integer> messageCount = new HashMap<>();
long start = System.currentTimeMillis();
while (i < NUM_PRODUCER * THREADS_PER_PRODUCER * 10 && System.currentTimeMillis() < start + 20000) {
ConsumerRecords<String, String> consumerRecords = consumer.poll(100);
for (ConsumerRecord record : consumerRecords) {
if (record.timestamp() >= MESSAGE_COUNT - 10) {
int count = messageCount.getOrDefault(record.timestamp(), 0);
messageCount.put(record.timestamp(), count + 1);
i++;
}
}
}
assertEquals(i, NUM_PRODUCER * THREADS_PER_PRODUCER * 10);
assertEquals(messageCount.size(), 10, "Should have consumed messages of all 10 timestamps");
int expectedCount = NUM_PRODUCER * THREADS_PER_PRODUCER;
for (Integer count : messageCount.values()) {
assertEquals(count.intValue(), expectedCount, "Each partition should have " + expectedCount + " messages");
}
}
}
@Test
public void testExceptionInProcessing() {
String topic = "testExceptionInProcessing";
produceSyntheticMessages(topic);
Properties props = new Properties();
// All the consumers should have the same group id.
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testCommit");
// Make sure we start to consume from the beginning.
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
LiKafkaConsumer<byte[], byte[]> consumer =
new LiKafkaConsumerImpl<byte[], byte[]>(getConsumerProperties(props),
new ByteArrayDeserializer(),
new Deserializer<byte[]>() {
int numMessages = 0;
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
}
@Override
public byte[] deserialize(String topic, byte[] data) {
// Throw exception when deserializing the second message.
numMessages++;
if (numMessages == 2) {
throw new SerializationException();
}
return data;
}
@Override
public void close() {
}
}, new DefaultSegmentDeserializer(), new NoOpAuditor<>());
try {
consumer.subscribe(Collections.singleton(topic));
ConsumerRecords<byte[], byte[]> records = ConsumerRecords.empty();
while (records.isEmpty()) {
records = consumer.poll(1000);
}
assertEquals(records.count(), 1, "Only the first message should be returned");
assertEquals(records.iterator().next().offset(), 2L, "The offset of the first message should be 2.");
assertEquals(consumer.position(new TopicPartition(topic, 0)), 5L, "The position should be 5");
try {
consumer.poll(1000);
fail("Should have thrown exception.");
} catch (ConsumerRecordsProcessingException crpe) {
// let it go
}
assertEquals(consumer.position(new TopicPartition(topic, 0)), 5L, "The position should be 5");
records = ConsumerRecords.empty();
while (records.isEmpty()) {
records = consumer.poll(1000);
}
assertEquals(records.count(), 4, "There should be four messages left.");
assertEquals(records.iterator().next().offset(), 5L, "The first offset should 5");
} finally {
consumer.close();
}
}
@Test
public void testOffsetOutOfRange() {
for (OffsetResetStrategy strategy : OffsetResetStrategy.values()) {
testOffsetOutOfRangeForStrategy(strategy);
}
}
private void testOffsetOutOfRangeForStrategy(OffsetResetStrategy strategy) {
produceRecordsWithKafkaProducer();
Properties props = new Properties();
// Make sure we start to consume from the beginning.
props.setProperty("auto.offset.reset", strategy.name());
// All the consumers should have the same group id.
props.setProperty("group.id", "testOffsetOutOfRange");
LiKafkaConsumer<String, String> consumer = createConsumer(props);
TopicPartition tp = new TopicPartition(TOPIC1, 0);
try {
consumer.assign(Collections.singleton(tp));
ConsumerRecords<String, String> consumerRecords = ConsumerRecords.empty();
consumer.seek(tp, 0);
while (consumerRecords.isEmpty()) {
consumerRecords = consumer.poll(1000);
}
consumer.seek(tp, 100000L);
assertEquals(consumer.position(tp), 100000L);
if (strategy == OffsetResetStrategy.EARLIEST) {
long expectedOffset = consumerRecords.iterator().next().offset();
consumerRecords = ConsumerRecords.empty();
while (consumerRecords.isEmpty()) {
consumerRecords = consumer.poll(1000);
}
assertEquals(consumerRecords.iterator().next().offset(), expectedOffset,
"The offset should have been reset to the earliest offset");
} else if (strategy == OffsetResetStrategy.LATEST) {
consumer.poll(1000);
long expectedOffset = consumer.endOffsets(Collections.singleton(tp)).get(tp);
assertEquals(consumer.position(tp), expectedOffset, "The offset should have been reset to the latest offset");
} else {
consumer.poll(1000);
fail("OffsetOutOfRangeException should have been thrown.");
}
} catch (OffsetOutOfRangeException ooore) {
if (strategy != OffsetResetStrategy.NONE) {
fail("Should not have thrown OffsetOutOfRangeException.");
}
} finally {
consumer.close();
}
}
/**
* This method produce a bunch of messages in an interleaved way.
* @param messages will contain both large message and ordinary messages.
*/
private void produceMessages(ConcurrentMap<String, String> messages, String topic) throws InterruptedException {
Properties props = new Properties();
// Enable large messages.
props.setProperty("large.message.enabled", "true");
// Set segment size to 200 so we have many large messages.
props.setProperty("max.message.segment.size", Integer.toString(MAX_SEGMENT_SIZE));
props.setProperty("client.id", "testProducer");
// Set batch size to 1 to make sure each message is a batch so we have a lot interleave messages.
props.setProperty("batch.size", "1");
// Create a few producers to make sure we have interleaved large messages.
List<LiKafkaProducer<String, String>> producers = new ArrayList<>();
for (int i = 0; i < NUM_PRODUCER; i++) {
producers.add(createProducer(props));
}
// Let each producer have a few user threads sending messages.
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < NUM_PRODUCER; i++) {
for (int j = 0; j < THREADS_PER_PRODUCER; j++) {
threads.add(new ProducerThread(producers.get(i), messages, topic));
}
}
// Start user threads.
for (Thread thread : threads) {
thread.start();
}
// Wait until the user threads finish sending.
for (Thread thread : threads) {
thread.join();
}
// Close producers.
for (LiKafkaProducer<String, String> producer : producers) {
producer.close();
}
}
private static final class MessageIdComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
String[] parts1 = o1.split("-");
String[] parts2 = o2.split("-");
int diff = parts1[0].compareTo(parts2[0]);
if (diff != 0) {
return diff;
}
diff = Integer.parseInt(parts1[1]) - Integer.parseInt(parts2[1]);
if (diff != 0) {
return diff;
}
return Integer.parseInt(parts1[2]) - Integer.parseInt(parts2[2]);
}
}
private class ProducerThread extends Thread {
private final LiKafkaProducer<String, String> _producer;
private final ConcurrentMap<String, String> _messages;
private final String _topic;
public ProducerThread(LiKafkaProducer<String, String> producer,
ConcurrentMap<String, String> messages,
String topic) {
_producer = producer;
_messages = messages;
_topic = topic;
}
@Override
public void run() {
final Set<String> ackedMessages = new HashSet<>();
for (int i = 0; i < MESSAGE_COUNT; i++) {
// The message size is set to 100 - 1124, So we should have most of the messages to be large messages
// while still have some ordinary size messages.
int messageSize = 100 + _random.nextInt(1024);
final String uuid = LiKafkaClientsUtils.randomUUID().toString().replace("-", "");
final String message = uuid + KafkaTestUtils.getRandomString(messageSize);
_producer.send(new ProducerRecord<String, String>(_topic, null, (long) i, null, message),
new Callback() {
@Override
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
// The callback should have been invoked only once.
assertFalse(ackedMessages.contains(uuid));
if (e == null) {
ackedMessages.add(uuid);
} else {
e.printStackTrace();
}
assertNull(e);
String messageId = messageId(recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset());
_messages.put(messageId, message);
}
});
}
}
}
/**
* This is a key we use to check what records have been produced.
*/
private static String messageId(String topic, int partition, long offset) {
return topic + "-" + partition + "-" + offset;
}
private void produceRecordsWithKafkaProducer() {
_messages = new ConcurrentSkipListMap<>();
_random = new Random(23423423);
try {
produceMessages(_messages, TOPIC1);
produceMessages(_messages, TOPIC2);
} catch (InterruptedException e) {
throw new RuntimeException("Message producing phase failed.", e);
}
}
/** Generate the following synthetic messages in order and produce to the same partition.
* <pre>
* partition SYNTHETIC_PARTITION_0
* 0: M0_SEG0 (START)
* 1: M1_SEG0 (START)
* 2: M2_SEG0 (START) (END)
* 3: M3_SEG0 (START)
* 4: M1_SEG1(END)
* 5: M0_SEG1(END)
* 6: M3_SEG1(END)
* 7: M4_SEG0 (START) (END)
* 8: M5_SEG0 (START)
* 9: M5_SEG1 (END)
* </pre>
*/
private void produceSyntheticMessages(String topic) {
MessageSplitter splitter = new MessageSplitterImpl(MAX_SEGMENT_SIZE,
new DefaultSegmentSerializer(),
new UUIDFactory.DefaultUUIDFactory<>());
Producer<byte[], byte[]> producer = createKafkaProducer();
// Prepare messages.
int messageSize = MAX_SEGMENT_SIZE + MAX_SEGMENT_SIZE / 2;
// M0, 2 segments
UUID messageId0 = LiKafkaClientsUtils.randomUUID();
String message0 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m0Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId0, message0.getBytes());
// M1, 2 segments
UUID messageId1 = LiKafkaClientsUtils.randomUUID();
String message1 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m1Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId1, message1.getBytes());
// M2, 1 segment
UUID messageId2 = LiKafkaClientsUtils.randomUUID();
String message2 = KafkaTestUtils.getRandomString(MAX_SEGMENT_SIZE / 2);
List<ProducerRecord<byte[], byte[]>> m2Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId2, message2.getBytes());
// M3, 2 segment
UUID messageId3 = LiKafkaClientsUtils.randomUUID();
String message3 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m3Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId3, message3.getBytes());
// M4, 1 segment
UUID messageId4 = LiKafkaClientsUtils.randomUUID();
String message4 = KafkaTestUtils.getRandomString(MAX_SEGMENT_SIZE / 2);
List<ProducerRecord<byte[], byte[]>> m4Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId4, message4.getBytes());
// M5, 2 segments
UUID messageId5 = LiKafkaClientsUtils.randomUUID();
String message5 = KafkaTestUtils.getRandomString(messageSize);
List<ProducerRecord<byte[], byte[]>> m5Segs = splitter.split(topic, SYNTHETIC_PARTITION_0, messageId5, message5.getBytes());
// Add two more segment to partition SYNTHETIC_PARTITION_1 for corner case test.
List<ProducerRecord<byte[], byte[]>> m0SegsPartition1 = splitter.split(topic, SYNTHETIC_PARTITION_1, LiKafkaClientsUtils.randomUUID(), message0.getBytes());
List<ProducerRecord<byte[], byte[]>> m1SegsPartition1 = splitter.split(topic, SYNTHETIC_PARTITION_1, LiKafkaClientsUtils.randomUUID(), message1.getBytes());
try {
producer.send(m0Segs.get(0)).get();
producer.send(m1Segs.get(0)).get();
producer.send(m2Segs.get(0)).get();
producer.send(m3Segs.get(0)).get();
producer.send(m1Segs.get(1)).get();
producer.send(m0Segs.get(1)).get();
producer.send(m3Segs.get(1)).get();
producer.send(m4Segs.get(0)).get();
producer.send(m5Segs.get(0)).get();
producer.send(m5Segs.get(1)).get();
producer.send(m0SegsPartition1.get(0)).get();
producer.send(m1SegsPartition1.get(0)).get();
} catch (Exception e) {
fail("Produce synthetic data failed.", e);
}
producer.close();
}
//TODO - remove / refactor
private Producer<byte[], byte[]> createKafkaProducer() {
Properties props = new Properties();
props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getCanonicalName());
props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getCanonicalName());
Properties finalProducerProps = getProducerProperties(props);
return new KafkaProducer(finalProducerProps);
}
private class RebalanceTestConsumerThread extends Thread {
private final LiKafkaConsumer<String, String> _consumer;
private final int _id;
private final Map<String, String> _messageUnseen;
private final TestRebalanceListener _listener;
RebalanceTestConsumerThread(LiKafkaConsumer<String, String> consumer,
Map<String, String> messageUnseen,
int id) {
super("consumer-thread-" + id);
_consumer = consumer;
_id = id;
_messageUnseen = messageUnseen;
_listener = new TestRebalanceListener();
}
private void processConsumedRecord(ConsumerRecords<String, String> records) {
for (ConsumerRecord<String, String> record : records) {
String messageId = messageId(record.topic(), record.partition(), record.offset());
String origMessage = _messageUnseen.get(messageId);
assertEquals(record.value(), origMessage, "Message should be the same. partition = " +
record.topic() + "-" + record.partition() + ", offset = " + record.offset());
_messageUnseen.remove(messageId);
}
}
@Override
public void run() {
try {
_consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2), _listener);
long startMs = System.currentTimeMillis();
while (!_messageUnseen.isEmpty() && System.currentTimeMillis() - startMs < 30000) {
int numConsumed = 0;
while (numConsumed < 150 && !_messageUnseen.isEmpty() && System.currentTimeMillis() - startMs < 30000) {
ConsumerRecords<String, String> records = _consumer.poll(10);
numConsumed += records.count();
processConsumedRecord(records);
}
// Let the consumer to change the subscriptions based on the thread id.
if (_id % 2 == 0) {
if (_consumer.subscription().contains(TOPIC2)) {
_consumer.subscribe(Collections.singleton(TOPIC1), _listener);
} else {
_consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2), _listener);
}
} else {
if (_consumer.subscription().contains(TOPIC1)) {
_consumer.subscribe(Collections.singleton(TOPIC2), _listener);
} else {
_consumer.subscribe(Arrays.asList(TOPIC1, TOPIC2), _listener);
}
}
_listener.done = false;
while (!_messageUnseen.isEmpty() && !_listener.done) {
processConsumedRecord(_consumer.poll(10));
}
}
} catch (Throwable t) {
t.printStackTrace();
}
}
private class TestRebalanceListener implements ConsumerRebalanceListener {
public boolean done = false;
@Override
public void onPartitionsRevoked(Collection<TopicPartition> topicPartitions) {
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> topicPartitions) {
done = true;
}
}
}
}
| fix flaky tests around offset commits (#80)
Signed-off-by: radai-rosenblatt <[email protected]> | integration-tests/src/test/java/com/linkedin/kafka/clients/consumer/LiKafkaConsumerIntegrationTest.java | fix flaky tests around offset commits (#80) | <ide><path>ntegration-tests/src/test/java/com/linkedin/kafka/clients/consumer/LiKafkaConsumerIntegrationTest.java
<ide> import java.util.HashSet;
<ide> import java.util.concurrent.ConcurrentMap;
<ide> import java.util.concurrent.ConcurrentSkipListMap;
<add>import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.atomic.AtomicReference;
<ide> import org.apache.kafka.clients.consumer.Consumer;
<ide> import org.apache.kafka.clients.consumer.ConsumerConfig;
<ide> import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
<ide> import org.apache.kafka.common.serialization.ByteArrayDeserializer;
<ide> import org.apache.kafka.common.serialization.ByteArraySerializer;
<ide> import org.apache.kafka.common.serialization.Deserializer;
<add>import org.testng.Assert;
<ide> import org.testng.annotations.AfterMethod;
<ide> import org.testng.annotations.BeforeMethod;
<ide> import org.testng.annotations.Test;
<ide> import java.util.UUID;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<del>import static org.testng.Assert.assertEquals;
<del>import static org.testng.Assert.assertFalse;
<del>import static org.testng.Assert.assertNull;
<del>import static org.testng.Assert.fail;
<add>import static org.testng.Assert.*;
<ide>
<ide>
<ide> /**
<ide> try {
<ide> TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
<ide> consumer.assign(Collections.singleton(tp));
<del> assertEquals(consumer.poll(5000).count(), 1, "Should have consumed 1 message"); // M2
<add> ConsumerRecords<String, String> records = waitForData(consumer, 30000); //M2
<add> assertEquals(records.count(), 1, "Should have consumed 1 message");
<ide> consumer.commitSync();
<ide> assertEquals(consumer.committed(tp), new OffsetAndMetadata(3, ""), "The committed user offset should be 3");
<ide> assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
<ide> consumer.seek(tp, consumer.committed(tp).offset());
<ide> assertEquals(consumer.position(tp), 0, "The committed safe offset should be 0");
<ide>
<del> ConsumerRecords<String, String> records = consumer.poll(5000); // M1
<add> records = waitForData(consumer, 30000); // M1
<ide>
<ide> assertEquals(records.count(), 1, "There should be only one record.");
<ide> assertEquals(records.iterator().next().offset(), 4, "The message offset should be 4");
<ide> }
<ide> }
<ide>
<del> @Test
<del> public void testOffsetCommitCallback() {
<add> private ConsumerRecords<String, String> waitForData(LiKafkaConsumer<String, String> consumer, long timeout) {
<add> long now = System.currentTimeMillis();
<add> long deadline = now + timeout;
<add> while (System.currentTimeMillis() < deadline) {
<add> ConsumerRecords<String, String> records = consumer.poll(1000);
<add> if (records != null && records.count() > 0) {
<add> return records;
<add> }
<add> }
<add> Assert.fail("failed to read any records within time limit");
<add> return null;
<add> }
<add>
<add> @Test
<add> public void testOffsetCommitCallback() throws Exception {
<ide> String topic = "testOffsetCommitCallback";
<ide> produceSyntheticMessages(topic);
<ide> Properties props = new Properties();
<ide> props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "testOffsetCommitCallback");
<ide> // Make sure we start to consume from the beginning.
<ide> props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
<add> props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
<ide> // Only fetch one record at a time.
<ide> props.setProperty(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "1");
<ide> try (LiKafkaConsumer<String, String> consumer = createConsumer(props)) {
<ide> TopicPartition tp = new TopicPartition(topic, SYNTHETIC_PARTITION_0);
<ide> consumer.assign(Collections.singleton(tp));
<del> consumer.poll(5000); // M2
<del> final AtomicBoolean offsetCommitted = new AtomicBoolean(false);
<add> waitForData(consumer, 30000); // M2
<add> OffsetAndMetadata committed = commitAndRetrieveOffsets(consumer, tp, null);
<add> assertEquals(committed, new OffsetAndMetadata(3, ""), "The committed user offset should be 3, instead was " + committed);
<add> assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
<add> Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
<add> offsetMap.put(tp, new OffsetAndMetadata(0));
<add> committed = commitAndRetrieveOffsets(consumer, tp, offsetMap);
<add> assertEquals(committed, new OffsetAndMetadata(0, ""), "The committed user offset should be 0, instead was " + committed);
<add> assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
<add> }
<add> }
<add>
<add> private OffsetAndMetadata commitAndRetrieveOffsets(
<add> LiKafkaConsumer<String, String> consumer,
<add> TopicPartition tp, Map<TopicPartition,
<add> OffsetAndMetadata> offsetMap) throws Exception {
<add> final AtomicBoolean callbackFired = new AtomicBoolean(false);
<add> final AtomicReference<Exception> offsetCommitIssue = new AtomicReference<>(null);
<add> OffsetAndMetadata committed = null;
<add> long now = System.currentTimeMillis();
<add> long deadline = now + TimeUnit.MINUTES.toMillis(1);
<add> while (System.currentTimeMillis() < deadline) {
<add> //call commitAsync, wait for a NON-NULL return value (see https://issues.apache.org/jira/browse/KAFKA-6183)
<ide> OffsetCommitCallback commitCallback = new OffsetCommitCallback() {
<ide> @Override
<ide> public void onComplete(Map<TopicPartition, OffsetAndMetadata> topicPartitionOffsetAndMetadataMap, Exception e) {
<del> offsetCommitted.set(true);
<add> if (e != null) {
<add> offsetCommitIssue.set(e);
<add> }
<add> callbackFired.set(true);
<ide> }
<ide> };
<del> consumer.commitAsync(commitCallback);
<del> while (!offsetCommitted.get()) {
<add> if (offsetMap != null) {
<add> consumer.commitAsync(offsetMap, commitCallback);
<add> } else {
<add> consumer.commitAsync(commitCallback);
<add> }
<add> while (!callbackFired.get()) {
<ide> consumer.poll(20);
<ide> }
<del> OffsetAndMetadata committed = consumer.committed(tp);
<del> assertEquals(committed, new OffsetAndMetadata(3, ""), "The committed user offset should be 3, instead was " + committed);
<del> assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
<del>
<del> offsetCommitted.set(false);
<del> Map<TopicPartition, OffsetAndMetadata> offsetMap = new HashMap<>();
<del> offsetMap.put(tp, new OffsetAndMetadata(0));
<del> consumer.commitAsync(offsetMap, commitCallback);
<del> while (!offsetCommitted.get()) {
<del> consumer.poll(20);
<del> }
<add> Assert.assertNull(offsetCommitIssue.get(), "offset commit failed");
<ide> committed = consumer.committed(tp);
<del> assertEquals(committed, new OffsetAndMetadata(0, ""), "The committed user offset should be 0, instead was " + committed);
<del> assertEquals(consumer.committedSafeOffset(tp).longValue(), 0, "The committed actual offset should be 0");
<del> }
<add> if (committed != null) {
<add> break;
<add> }
<add> Thread.sleep(100);
<add> }
<add> assertNotNull(committed, "unable to retrieve committed offsets within timeout");
<add> return committed;
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | a3c69294a190680547de9986740e12b305409b71 | 0 | scripthub/CustomCameraPlugin,scripthub/CustomCameraPlugin | package com.example.acedeno.customcamera;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.cordova.PluginResult;
import org.apache.cordova.CordovaInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Build;
import android.widget.Toast;
import android.app.Activity;
import android.util.Log;
import android.content.Context;
import java.io.FileNotFoundException;
import com.itextpdf.text.DocumentException;
import java.util.ArrayList;
public class CustomCameraPlugin extends CordovaPlugin{
private static final String CAMERA = "customCamera";
private static final String IMAGES = "images";
private static final int GET_PICTURES_REQUEST = 1;
private CallbackContext callback;
private boolean running = false;
private ArrayList<String> pagepath;
public CustomCameraPlugin() {}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if(action.equals(CAMERA)){
this.callback = callbackContext;
class Snapshot implements Runnable {
private CallbackContext callback;
private CustomCameraPlugin self;
Snapshot(CallbackContext callbackContext, CustomCameraPlugin self){
this.callback = callbackContext;
this.self = self;
}
public void run(){
Intent intent = new Intent(self.cordova.getActivity(), CustomCameraActivity.class);
if(this.self.cordova != null){
this.self.cordova.startActivityForResult((CordovaPlugin)this.self, intent, GET_PICTURES_REQUEST);
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.cordova.getActivity().runOnUiThread(new Snapshot(callbackContext, this));
}else{
if(!this.running){
this.cordova.getActivity().runOnUiThread(new Snapshot(callbackContext, this));
this.running = true;
}
}
return true;
} else if(action.equals(IMAGES)){
Log.i("XXX", "Pasa por imágenes");
try {
JSONObject js = new JSONObject(args.getString(0));
}catch(Exception e){
Log.i("XXX", "Error");
e.printStackTrace();
}
Log.i("XXX", "data: " + js);
PluginResult r = new PluginResult(PluginResult.Status.OK);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
/*if (jsArr != null){
for(int i = 0; i < jsArr.length(); i ++){
this.pagepath.add(jsArr.getString(i));
}
try{
ImagesManager im = new ImagesManager(this.pagepath);
String pdfPath = im.createPdf();
Log.i("XXX", pdfPath);
PluginResult r = new PluginResult(PluginResult.Status.OK, pdfPath);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
} catch (FileNotFoundException e) {
Log.i("XXX", "FileNotFound");
e.printStackTrace();
} catch (DocumentException e) {
Log.i("XXX", "DocumentException");
e.printStackTrace();
} catch(Exception e){
Log.i("XXX", "Exception");
e.printStackTrace();
}
}*/
return true;
}
return false;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == GET_PICTURES_REQUEST && callback != null) {
this.running = false;
if (resultCode == cordova.getActivity().RESULT_OK) {
Bundle extras = intent.getExtras();
String result = extras.getString("result");
callback.success(result);
} else {
PluginResult r = new PluginResult(PluginResult.Status.OK);
r.setKeepCallback(true);
callback.sendPluginResult(r);
}
}
}
}
| src/android/CustomCameraPlugin.java | package com.example.acedeno.customcamera;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.cordova.PluginResult;
import org.apache.cordova.CordovaInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Build;
import android.widget.Toast;
import android.app.Activity;
import android.util.Log;
import android.content.Context;
import java.io.FileNotFoundException;
import com.itextpdf.text.DocumentException;
import java.util.ArrayList;
public class CustomCameraPlugin extends CordovaPlugin{
private static final String CAMERA = "customCamera";
private static final String IMAGES = "images";
private static final int GET_PICTURES_REQUEST = 1;
private CallbackContext callback;
private boolean running = false;
private ArrayList<String> pagepath;
public CustomCameraPlugin() {}
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if(action.equals(CAMERA)){
this.callback = callbackContext;
class Snapshot implements Runnable {
private CallbackContext callback;
private CustomCameraPlugin self;
Snapshot(CallbackContext callbackContext, CustomCameraPlugin self){
this.callback = callbackContext;
this.self = self;
}
public void run(){
Intent intent = new Intent(self.cordova.getActivity(), CustomCameraActivity.class);
if(this.self.cordova != null){
this.self.cordova.startActivityForResult((CordovaPlugin)this.self, intent, GET_PICTURES_REQUEST);
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.cordova.getActivity().runOnUiThread(new Snapshot(callbackContext, this));
}else{
if(!this.running){
this.cordova.getActivity().runOnUiThread(new Snapshot(callbackContext, this));
this.running = true;
}
}
return true;
} else if(action.equals(IMAGES)){
Log.i("XXX", "Pasa por imágenes");
JSONObject js= new JSONObject(args.getString(0));
Log.i("XXX", "data: " + js);
PluginResult r = new PluginResult(PluginResult.Status.OK);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
/*if (jsArr != null){
for(int i = 0; i < jsArr.length(); i ++){
this.pagepath.add(jsArr.getString(i));
}
try{
ImagesManager im = new ImagesManager(this.pagepath);
String pdfPath = im.createPdf();
Log.i("XXX", pdfPath);
PluginResult r = new PluginResult(PluginResult.Status.OK, pdfPath);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
} catch (FileNotFoundException e) {
Log.i("XXX", "FileNotFound");
e.printStackTrace();
} catch (DocumentException e) {
Log.i("XXX", "DocumentException");
e.printStackTrace();
} catch(Exception e){
Log.i("XXX", "Exception");
e.printStackTrace();
}
}*/
return true;
}
return false;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == GET_PICTURES_REQUEST && callback != null) {
this.running = false;
if (resultCode == cordova.getActivity().RESULT_OK) {
Bundle extras = intent.getExtras();
String result = extras.getString("result");
callback.success(result);
} else {
PluginResult r = new PluginResult(PluginResult.Status.OK);
r.setKeepCallback(true);
callback.sendPluginResult(r);
}
}
}
}
| images action fix
| src/android/CustomCameraPlugin.java | images action fix | <ide><path>rc/android/CustomCameraPlugin.java
<ide> return true;
<ide> } else if(action.equals(IMAGES)){
<ide> Log.i("XXX", "Pasa por imágenes");
<del> JSONObject js= new JSONObject(args.getString(0));
<add> try {
<add> JSONObject js = new JSONObject(args.getString(0));
<add> }catch(Exception e){
<add> Log.i("XXX", "Error");
<add> e.printStackTrace();
<add> }
<add>
<ide> Log.i("XXX", "data: " + js);
<ide>
<ide> |
|
JavaScript | mit | 9df48395d3e390eaeec694735dfb067afbd5a9a7 | 0 | conveyal/datatools-manager,conveyal/datatools-manager,conveyal/datatools-manager,conveyal/datatools-manager | import Icon from '@conveyal/woonerf/components/icon'
import React, { Component, PropTypes } from 'react'
import { Grid, Row, Col, Button, Panel, Checkbox, ListGroup, ListGroupItem, ControlLabel } from 'react-bootstrap'
import { Link } from 'react-router'
import { LinkContainer } from 'react-router-bootstrap'
import EditableTextField from '../../common/components/EditableTextField'
import ManagerPage from '../../common/components/ManagerPage'
import { getConfigProperty, getComponentMessages, getMessage } from '../../common/util/config'
export default class UserAccount extends Component {
static propTypes = {
activeComponent: PropTypes.string,
getUser: PropTypes.func,
resetPassword: PropTypes.func,
unsubscribeAll: PropTypes.func,
user: PropTypes.object
}
componentWillMount () {
this.props.onComponentMount(this.props)
}
_onChangeUserName = (value) => this.props.updateUserName(this.props.user, value)
_onClickGet = () => this.props.getUser(this.props.user.profile.user_id)
_onClickUnsubscribeAll = () => this.props.unsubscribeAll(this.props.user.profile)
_onResetPassword = () => this.props.resetPassword()
render () {
const {user} = this.props
const messages = getComponentMessages('UserAccount')
const removeIconStyle = {cursor: 'pointer'}
const subscriptions = user.profile.app_metadata.datatools.find(dt => dt.client_id === process.env.AUTH0_CLIENT_ID).subscriptions
const ACCOUNT_SECTIONS = [
{
id: 'profile',
component: (
<div>
<Panel header={<h4>Profile information</h4>}>
<ListGroup fill>
<ListGroupItem>
<ControlLabel>Email address</ControlLabel>
<EditableTextField
value={user.profile.email}
onChange={this._onChangeUserName} />
{/*
<Button
onClick={this._onClickGet}>
Get User
</Button>
*/}
</ListGroupItem>
<ListGroupItem>
<p><strong>Avatar</strong></p>
<a href='http://gravatar.com'>
<img
alt='Profile'
className='img-rounded'
height={40}
width={40}
src={user.profile.picture} />
<span style={{marginLeft: '10px'}}>Change on gravatar.com</span>
</a>
</ListGroupItem>
<ListGroupItem>
<p><strong>Password</strong></p>
<Button
onClick={this._onResetPassword}>
Change password
</Button>
</ListGroupItem>
</ListGroup>
</Panel>
</div>
)
},
{
id: 'account',
hidden: !getConfigProperty('modules.enterprise.enabled')
},
{
id: 'organizations',
hidden: !getConfigProperty('modules.enterprise.enabled')
},
{
id: 'notifications',
hidden: !getConfigProperty('application.notifications_enabled'),
component: (
<div>
<Panel
header={<h4>Notification methods</h4>}
>
<ListGroup fill>
<ListGroupItem>
<h4>Watching</h4>
<p>Receive updates to any feed sources or comments you are watching.</p>
<Checkbox inline>Email</Checkbox>{' '}<Checkbox inline>Web</Checkbox>
</ListGroupItem>
</ListGroup>
</Panel>
<Panel
header={
<h4>
<Button
onClick={this._onClickUnsubscribeAll}
className='pull-right'
bsSize='xsmall'>
{getMessage(messages, 'notifications.unsubscribeAll')}
</Button>
{getMessage(messages, 'notifications.subscriptions')}
</h4>
}>
<ul>
{subscriptions && subscriptions.length
? subscriptions.map(sub => {
return (
<SubscriptionListItem
removeIconStyle={removeIconStyle}
subscription={sub}
{...this.props} />
)
})
: <li>No subscriptions.</li>
}
</ul>
</Panel>
</div>
)
},
{
id: 'billing',
hidden: !getConfigProperty('modules.enterprise.enabled')
}
]
const activeSection = ACCOUNT_SECTIONS.find(section => section.id === this.props.activeComponent)
const visibleComponent = activeSection ? activeSection.component : null
return (
<ManagerPage ref='page'>
<Grid fluid>
<Row style={{marginBottom: '20px'}}>
<Col xs={12}>
<h1>
<LinkContainer className='pull-right' to={{ pathname: '/home' }}>
<Button>Back to dashboard</Button>
</LinkContainer>
<Icon type='user' /> My settings
</h1>
</Col>
</Row>
<Row>
<Col xs={3}>
<Panel header={<h4>{getMessage(messages, 'personalSettings')}</h4>}>
<ListGroup fill>
{ACCOUNT_SECTIONS.map(section => {
if (section.hidden) return null
return (
<LinkContainer key={section.id} to={`/settings/${section.id}`}>
<ListGroupItem active={this.props.activeComponent === section.id}>
{getMessage(messages, `${section.id}.title`)}
</ListGroupItem>
</LinkContainer>
)
})}
</ListGroup>
</Panel>
<Panel header={<h4>{getMessage(messages, 'organizationSettings')}</h4>}>
<ListGroup fill>
{this.props.projects && this.props.projects.map(project => {
if (project.hidden) return null
return (
<LinkContainer key={project.id} to={`/project/${project.id}/settings`}>
<ListGroupItem active={this.props.projectId === project.id}>
{project.name}
</ListGroupItem>
</LinkContainer>
)
})}
</ListGroup>
</Panel>
</Col>
<Col xs={1} />
<Col xs={6}>
{visibleComponent}
</Col>
</Row>
</Grid>
</ManagerPage>
)
}
}
class SubscriptionListItem extends Component {
_onClickRemoveSubscriptionType = () => {
const {removeUserSubscription, subscription, user} = this.props
removeUserSubscription(user.profile, subscription.type)
}
render () {
const {removeIconStyle, subscription} = this.props
return (
<li>
{subscription.type.replace('-', ' ')}{' '}
<Icon
type='trash'
className='text-danger'
style={removeIconStyle}
onClick={this._onClickRemoveSubscriptionType} />
<ul>
{subscription.target.length
? subscription.target.map(target => (
<SubscriptionTarget
target={target}
{...this.props} />
))
: <li>No feeds subscribed to.</li>
}
</ul>
</li>
)
}
}
class SubscriptionTarget extends Component {
_onClickRemoveSubscriptionTarget = () => {
const {subscription, target, updateUserSubscription, user} = this.props
updateUserSubscription(user.profile, target, subscription.type)
}
render () {
const {projects, removeIconStyle, target} = this.props
let fs = null // this.props.projects ? this.props.projects.reduce(proj => proj.feedSources.filter(fs => fs.id === target)) : null
if (projects) {
for (var i = 0; i < projects.length; i++) {
const feed = projects[i].feedSources
? projects[i].feedSources.find(fs => fs.id === target)
: null
fs = feed || fs
}
}
const feedLink = fs
? <Link to={fs.isPublic ? `/public/feed/${fs.id}` : `/feed/${fs.id}`}>{fs.name}</Link>
: <span>{target}</span>
return (
<li>
{feedLink}
{' '}
<Icon
type='trash'
className='text-danger'
style={removeIconStyle}
onClick={this._onClickRemoveSubscriptionTarget} />
</li>
)
}
}
| lib/public/components/UserAccount.js | import Icon from '@conveyal/woonerf/components/icon'
import React, { Component, PropTypes } from 'react'
import { Grid, Row, Col, Button, Panel, Checkbox, ListGroup, ListGroupItem, ControlLabel } from 'react-bootstrap'
import { Link } from 'react-router'
import { LinkContainer } from 'react-router-bootstrap'
import EditableTextField from '../../common/components/EditableTextField'
import ManagerPage from '../../common/components/ManagerPage'
import { getConfigProperty, getComponentMessages, getMessage } from '../../common/util/config'
export default class UserAccount extends Component {
static propTypes = {
activeComponent: PropTypes.string,
getUser: PropTypes.func,
resetPassword: PropTypes.func,
unsubscribeAll: PropTypes.func,
user: PropTypes.object
}
componentWillMount () {
this.props.onComponentMount(this.props)
}
_onChangeUserName = (value) => this.props.updateUserName(this.props.user, value)
_onClickGet = () => this.props.getUser(this.props.user.profile.user_id)
_onClickUnsubscribeAll = () => this.props.unsubscribeAll(this.props.user.profile)
_onResetPassword = () => this.props.resetPassword()
render () {
const {user} = this.props
const messages = getComponentMessages('UserAccount')
const removeIconStyle = {cursor: 'pointer'}
const subscriptions = user.profile.app_metadata.datatools.find(dt => dt.client_id === process.env.AUTH0_CLIENT_ID).subscriptions
const ACCOUNT_SECTIONS = [
{
id: 'profile',
component: (
<div>
<Panel header={<h4>Profile information</h4>}>
<ListGroup fill>
<ListGroupItem>
<ControlLabel>Email address</ControlLabel>
<EditableTextField
value={user.profile.email}
onChange={this._onChangeUserName} />
{/*
<Button
onClick={this._onClickGet}>
Get User
</Button>
*/}
</ListGroupItem>
<ListGroupItem>
<p><strong>Avatar</strong></p>
<a href='http://gravatar.com'>
<img
alt='Profile'
className='img-rounded'
height={40}
width={40}
src={user.profile.picture} />
<span style={{marginLeft: '10px'}}>Change on gravatar.com</span>
</a>
</ListGroupItem>
<ListGroupItem>
<p><strong>Password</strong></p>
<Button
onClick={this._onResetPassword}>
Change password
</Button>
</ListGroupItem>
</ListGroup>
</Panel>
</div>
)
},
{
id: 'account',
hidden: !getConfigProperty('modules.enterprise.enabled')
},
{
id: 'organizations',
hidden: !getConfigProperty('modules.enterprise.enabled')
},
{
id: 'notifications',
hidden: !getConfigProperty('application.notifications_enabled'),
component: (
<div>
<Panel
header={<h4>Notification methods</h4>}
>
<ListGroup fill>
<ListGroupItem>
<h4>Watching</h4>
<p>Receive updates to any feed sources or comments you are watching.</p>
<Checkbox inline>Email</Checkbox>{' '}<Checkbox inline>Web</Checkbox>
</ListGroupItem>
</ListGroup>
</Panel>
<Panel
header={
<h4>
<Button
onClick={this._onClickUnsubscribeAll}
className='pull-right'
bsSize='xsmall'>
{getMessage(messages, 'notifications.unsubscribeAll')}
</Button>
{getMessage(messages, 'notifications.subscriptions')}
</h4>
}>
<ul>
{subscriptions && subscriptions.length
? subscriptions.map(sub => {
return (
<SubscriptionListItem
removeIconStyle={removeIconStyle}
subscription={sub}
{...this.props} />
)
})
: <li>No subscriptions.</li>
}
</ul>
</Panel>
</div>
)
},
{
id: 'billing',
hidden: !getConfigProperty('modules.enterprise.enabled')
}
]
const activeSection = ACCOUNT_SECTIONS.find(section => section.id === this.props.activeComponent)
const visibleComponent = activeSection ? activeSection.component : null
return (
<ManagerPage ref='page'>
<Grid fluid>
<Row style={{marginBottom: '20px'}}>
<Col xs={12}>
<h1>
<LinkContainer className='pull-right' to={{ pathname: '/home' }}>
<Button>Back to dashboard</Button>
</LinkContainer>
<Icon type='user' /> My settings
</h1>
</Col>
</Row>
<Row>
<Col xs={3}>
<Panel header={<h4>{getMessage(messages, 'personalSettings')}</h4>}>
<ListGroup fill>
{ACCOUNT_SECTIONS.map(section => {
if (section.hidden) return null
return (
<LinkContainer key={section.id} to={`/settings/${section.id}`}>
<ListGroupItem active={this.props.activeComponent === section.id}>
{getMessage(messages, `${section.id}.title`)}
</ListGroupItem>
</LinkContainer>
)
})}
</ListGroup>
</Panel>
<Panel header={<h4>{getMessage(messages, 'organizationSettings')}</h4>}>
<ListGroup fill>
{this.props.projects && this.props.projects.map(project => {
if (project.hidden) return null
return (
<LinkContainer key={project.id} to={`/project/${project.id}/settings`}>
<ListGroupItem active={this.props.projectId === project.id}>
{project.name}
</ListGroupItem>
</LinkContainer>
)
})}
</ListGroup>
</Panel>
</Col>
<Col xs={1} />
<Col xs={6}>
{visibleComponent}
</Col>
</Row>
</Grid>
</ManagerPage>
)
}
}
class SubscriptionListItem extends Component {
_onClickRemoveSubscriptionType = () => {
const {removeUserSubscription, subscription, user} = this.props
removeUserSubscription(user.profile, subscription.type)
}
render () {
const {removeIconStyle, subscription} = this.props
return (
<li>
{subscription.type.replace('-', ' ')}{' '}
<Icon
type='trash'
className='text-danger'
style={removeIconStyle}
onClick={this._onClickRemoveSubscriptionType} />
<ul>
{subscription.target.length
? subscription.target.map(target => {
<SubscriptionTarget
target={target}
{...this.props} />
})
: <li>No feeds subscribed to.</li>
}
</ul>
</li>
)
}
}
class SubscriptionTarget extends Component {
_onClickRemoveSubscriptionTarget = () => {
const {subscription, target, updateUserSubscription, user} = this.props
updateUserSubscription(user.profile, target, subscription.type)
}
render () {
const {projects, removeIconStyle, target} = this.props
let fs = null // this.props.projects ? this.props.projects.reduce(proj => proj.feedSources.filter(fs => fs.id === target)) : null
if (projects) {
for (var i = 0; i < projects.length; i++) {
const feed = projects[i].feedSources
? projects[i].feedSources.find(fs => fs.id === target)
: null
fs = feed || fs
}
}
const feedLink = fs
? <Link to={fs.isPublic ? `/public/feed/${fs.id}` : `/feed/${fs.id}`}>{fs.name}</Link>
: <span>{target}</span>
return (
<li>
{feedLink}
{' '}
<Icon
type='trash'
className='text-danger'
style={removeIconStyle}
onClick={this._onClickRemoveSubscriptionTarget} />
</li>
)
}
}
| fix(UserAccount): fix map func
| lib/public/components/UserAccount.js | fix(UserAccount): fix map func | <ide><path>ib/public/components/UserAccount.js
<ide> onClick={this._onClickRemoveSubscriptionType} />
<ide> <ul>
<ide> {subscription.target.length
<del> ? subscription.target.map(target => {
<add> ? subscription.target.map(target => (
<ide> <SubscriptionTarget
<ide> target={target}
<ide> {...this.props} />
<del> })
<add> ))
<ide> : <li>No feeds subscribed to.</li>
<ide> }
<ide> </ul> |
|
Java | bsd-3-clause | af640896395d24eb6ac9480d43ce514d7cdb5b27 | 0 | AlexRNL/Commons | package com.alexrnl.commons.arguments;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import com.alexrnl.commons.utils.StringUtils;
import com.alexrnl.commons.utils.object.ReflectUtils;
/**
* Class which allow to parse string arguments and store them in a target object.
* @author Alex
*/
public class Arguments {
/** Logger */
private static Logger lg = Logger.getLogger(Arguments.class.getName());
/** The tab character */
private static final Character TAB = '\t';
/** The number of tabs between the name of the argument and their description */
private static final int NB_TABS_BEFORE_DESCRIPTION = 4;
/** The name of the program. */
private final String programName;
/** The object which holds the target */
private final Object target;
/** The list of parameters in the target */
private final SortedSet<Parameter> parameters;
/**
* Constructor #1.<br />
* @param programName
* the name of the program.
* @param target
* the object which holds the target.
*/
public Arguments (final String programName, final Object target) {
super();
this.programName = programName;
this.target = target;
this.parameters = retrieveParameters(target);
}
/**
* Parse and build a list with the parameters field marked with the {@link Param} annotation in
* the object specified.
* @param obj
* the object to parse for parameters.
* @return the list of parameters associated to this object.
*/
private static SortedSet<Parameter> retrieveParameters (final Object obj) {
final SortedSet<Parameter> params = new TreeSet<>();
for (final Field field : ReflectUtils.retrieveFields(obj.getClass(), Param.class)) {
field.setAccessible(true);
params.add(new Parameter(field, field.getAnnotation(Param.class)));
}
return params;
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final String... arguments) {
parse(Arrays.asList(arguments));
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final Iterable<String> arguments) {
// TODO
}
/**
* Display the parameter's usage on specified output.
* @param out
* the stream to use to display the parameters.
*/
public void usage (final PrintStream out) {
out.println(this);
}
/**
* Display the parameter's usage on the standard output.
*/
public void usage () {
usage(System.out);
}
@Override
public String toString () {
final StringBuilder usage = new StringBuilder(programName).append(" usage as follow:");
for (final Parameter param : parameters) {
usage.append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = NB_TABS_BEFORE_DESCRIPTION;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
}
return usage.toString();
}
}
| src/main/java/com/alexrnl/commons/arguments/Arguments.java | package com.alexrnl.commons.arguments;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import com.alexrnl.commons.utils.StringUtils;
import com.alexrnl.commons.utils.object.ReflectUtils;
/**
* Class which allow to parse string arguments and store them in a target object.
* @author Alex
*/
public class Arguments {
/** Logger */
private static Logger lg = Logger.getLogger(Arguments.class.getName());
/** The tab character */
private static final Character TAB = '\t';
/** The number of tabs between the name of the argument and their description */
private static final int NB_TABS_BEFORE_DESCRIPTION = 4;
/** The name of the program. */
private final String programName;
/** The object which holds the target */
private final Object target;
/** The list of parameters in the target */
private final SortedSet<Parameter> parameters;
/**
* Constructor #1.<br />
* @param programName
* the name of the program.
* @param target
* the object which holds the target.
*/
public Arguments (final String programName, final Object target) {
super();
this.programName = programName;
this.target = target;
this.parameters = retrieveParameters(target);
}
/**
* Parse and build a list with the parameters field marked with the {@link Param} annotation in
* the object specified.
* @param obj
* the object to parse for parameters.
* @return the list of parameters associated to this object.
*/
private static SortedSet<Parameter> retrieveParameters (final Object obj) {
final SortedSet<Parameter> params = new TreeSet<>();
for (final Field field : ReflectUtils.retrieveFields(obj.getClass(), Param.class)) {
field.setAccessible(true);
params.add(new Parameter(field, field.getAnnotation(Param.class)));
}
return params;
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final String... arguments) {
parse(Arrays.asList(arguments));
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final Iterable<String> arguments) {
// TODO
}
/**
* Display the parameter's usage on the standard output.
*/
public void usage () {
System.out.println(this);
}
@Override
public String toString () {
final StringBuilder usage = new StringBuilder(programName).append(" usage as follow:");
for (final Parameter param : parameters) {
usage.append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = NB_TABS_BEFORE_DESCRIPTION;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
}
return usage.toString();
}
}
| Delegate call to System.out
avoid sonar violation.
| src/main/java/com/alexrnl/commons/arguments/Arguments.java | Delegate call to System.out | <ide><path>rc/main/java/com/alexrnl/commons/arguments/Arguments.java
<ide> package com.alexrnl.commons.arguments;
<ide>
<add>import java.io.PrintStream;
<ide> import java.lang.reflect.Field;
<ide> import java.util.Arrays;
<ide> import java.util.SortedSet;
<ide> }
<ide>
<ide> /**
<add> * Display the parameter's usage on specified output.
<add> * @param out
<add> * the stream to use to display the parameters.
<add> */
<add> public void usage (final PrintStream out) {
<add> out.println(this);
<add> }
<add>
<add> /**
<ide> * Display the parameter's usage on the standard output.
<ide> */
<ide> public void usage () {
<del> System.out.println(this);
<add> usage(System.out);
<ide> }
<ide>
<ide> @Override |
|
Java | lgpl-2.1 | 3ecae5400eb944b65385485d3d965201678924ea | 0 | jolie/jolie,jolie/jolie,jolie/jolie | /***************************************************************************
* Copyright (C) 2008-2017 by Fabrizio Montesi <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
***************************************************************************/
package jolie.lang;
import java.util.jar.Attributes;
import jolie.lang.parse.Scanner;
import jolie.util.Range;
/**
* Global constants.
*
* @author Fabrizio Montesi
*/
public final class Constants
{
// Release information
public static final String VERSION = "Jolie 1.6.3";
public static final String COPYRIGHT = "(C) 2006-2018 the Jolie team";
public interface Manifest
{
// Jolie Extensions
public final static Attributes.Name CHANNEL_EXTENSION = new Attributes.Name( "X-JOLIE-ChannelExtension" );
public final static Attributes.Name LISTENER_EXTENSION = new Attributes.Name( "X-JOLIE-ListenerExtension" );
public final static Attributes.Name PROTOCOL_EXTENSION = new Attributes.Name( "X-JOLIE-ProtocolExtension" );
public final static Attributes.Name EMBEDDING_EXTENSION = new Attributes.Name( "X-JOLIE-EmbeddingExtension" );
// JAP Manifest
public final static Attributes.Name MAIN_PROGRAM = new Attributes.Name( "X-JOLIE-Main-Program" );
public final static Attributes.Name OPTIONS = new Attributes.Name( "X-JOLIE-Options" );
//public final static String Libraries = "X-JOLIE-Libraries";
}
static public enum Predefined
{
ATTRIBUTES( "@Attributes", "@Attributes" ),
HTTP_BASIC_AUTHENTICATION( "@HttpBasicAuthentication", "@HttpBasicAuthentication" ),
PI( "PI", java.lang.Math.PI );
private final String id;
private final Scanner.Token token;
public static Predefined get( String id )
{
for ( Predefined p : Predefined.values() ) {
if ( p.id.equals( id ) ) {
return p;
}
}
return null;
}
Predefined( String id, String content )
{
this.id = id;
this.token = new Scanner.Token( Scanner.TokenType.STRING, content );
}
Predefined( String id, Integer content )
{
this.id = id;
this.token = new Scanner.Token( Scanner.TokenType.INT, content.toString() );
}
Predefined( String id, Double content )
{
this.id = id;
this.token = new Scanner.Token( Scanner.TokenType.DOUBLE, content.toString() );
}
public final String id()
{
return id;
}
public final Scanner.Token token()
{
return token;
}
}
public final static Range RANGE_ONE_TO_ONE = new Range( 1, 1 );
public static interface Keywords
{
public static final String DEFAULT_HANDLER_NAME = "default";
}
public static final String TYPE_MISMATCH_FAULT_NAME = "TypeMismatch";
public static final String IO_EXCEPTION_FAULT_NAME = "IOException";
public static final String MONITOR_OUTPUTPORT_NAME = "#Monitor";
public static final String INPUT_PORTS_NODE_NAME = "inputPorts";
public static final String PROTOCOL_NODE_NAME = "protocol";
public static final String LOCATION_NODE_NAME = "location";
public static final String LOCAL_LOCATION_KEYWORD = "local";
public static final String LOCAL_INPUT_PORT_NAME = "LocalInputPort";
//public static String newLineString = System.getProperty( "line.separator" );
public static final String fileSeparator = System.getProperty( "file.separator" );
public static final String pathSeparator = System.getProperty( "path.separator" );
public static final String GLOBAL = "global";
public static final String CSETS = "csets";
public static final String ROOT_RESOURCE_PATH = "/";
public enum EmbeddedServiceType
{
JOLIE("Jolie"), JAVA("Java"), JAVASCRIPT("JavaScript"), INTERNAL("JolieInternal"), UNSUPPORTED("Unsupported");
private final String str;
EmbeddedServiceType( String str )
{
this.str = str;
}
@Override
public String toString()
{
return str;
}
}
public static EmbeddedServiceType stringToEmbeddedServiceType( String str )
{
switch( str.toLowerCase() ) {
case "jolie":
return EmbeddedServiceType.JOLIE;
case "java":
return EmbeddedServiceType.JAVA;
case "javascript":
return EmbeddedServiceType.JAVASCRIPT;
default:
return EmbeddedServiceType.UNSUPPORTED;
}
}
public enum ExecutionMode
{
SINGLE, SEQUENTIAL, CONCURRENT
}
public enum OperationType
{
ONE_WAY,
REQUEST_RESPONSE
}
public enum OperandType
{
ADD, SUBTRACT,
MULTIPLY, DIVIDE,
MODULUS
}
public static long serialVersionUID()
{
return 1L;
}
}
| libjolie/src/jolie/lang/Constants.java | /***************************************************************************
* Copyright (C) 2008-2017 by Fabrizio Montesi <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
***************************************************************************/
package jolie.lang;
import java.util.jar.Attributes;
import jolie.lang.parse.Scanner;
import jolie.util.Range;
/**
* Global constants.
*
* @author Fabrizio Montesi
*/
public final class Constants
{
// Release information
public static final String VERSION = "Jolie 1.6.2";
public static final String COPYRIGHT = "(C) 2006-2017 the Jolie team";
public interface Manifest
{
// Jolie Extensions
public final static Attributes.Name CHANNEL_EXTENSION = new Attributes.Name( "X-JOLIE-ChannelExtension" );
public final static Attributes.Name LISTENER_EXTENSION = new Attributes.Name( "X-JOLIE-ListenerExtension" );
public final static Attributes.Name PROTOCOL_EXTENSION = new Attributes.Name( "X-JOLIE-ProtocolExtension" );
public final static Attributes.Name EMBEDDING_EXTENSION = new Attributes.Name( "X-JOLIE-EmbeddingExtension" );
// JAP Manifest
public final static Attributes.Name MAIN_PROGRAM = new Attributes.Name( "X-JOLIE-Main-Program" );
public final static Attributes.Name OPTIONS = new Attributes.Name( "X-JOLIE-Options" );
//public final static String Libraries = "X-JOLIE-Libraries";
}
static public enum Predefined
{
ATTRIBUTES( "@Attributes", "@Attributes" ),
HTTP_BASIC_AUTHENTICATION( "@HttpBasicAuthentication", "@HttpBasicAuthentication" ),
PI( "PI", java.lang.Math.PI );
private final String id;
private final Scanner.Token token;
public static Predefined get( String id )
{
for ( Predefined p : Predefined.values() ) {
if ( p.id.equals( id ) ) {
return p;
}
}
return null;
}
Predefined( String id, String content )
{
this.id = id;
this.token = new Scanner.Token( Scanner.TokenType.STRING, content );
}
Predefined( String id, Integer content )
{
this.id = id;
this.token = new Scanner.Token( Scanner.TokenType.INT, content.toString() );
}
Predefined( String id, Double content )
{
this.id = id;
this.token = new Scanner.Token( Scanner.TokenType.DOUBLE, content.toString() );
}
public final String id()
{
return id;
}
public final Scanner.Token token()
{
return token;
}
}
public final static Range RANGE_ONE_TO_ONE = new Range( 1, 1 );
public static interface Keywords
{
public static final String DEFAULT_HANDLER_NAME = "default";
}
public static final String TYPE_MISMATCH_FAULT_NAME = "TypeMismatch";
public static final String IO_EXCEPTION_FAULT_NAME = "IOException";
public static final String MONITOR_OUTPUTPORT_NAME = "#Monitor";
public static final String INPUT_PORTS_NODE_NAME = "inputPorts";
public static final String PROTOCOL_NODE_NAME = "protocol";
public static final String LOCATION_NODE_NAME = "location";
public static final String LOCAL_LOCATION_KEYWORD = "local";
public static final String LOCAL_INPUT_PORT_NAME = "LocalInputPort";
//public static String newLineString = System.getProperty( "line.separator" );
public static final String fileSeparator = System.getProperty( "file.separator" );
public static final String pathSeparator = System.getProperty( "path.separator" );
public static final String GLOBAL = "global";
public static final String CSETS = "csets";
public static final String ROOT_RESOURCE_PATH = "/";
public enum EmbeddedServiceType
{
JOLIE("Jolie"), JAVA("Java"), JAVASCRIPT("JavaScript"), INTERNAL("JolieInternal"), UNSUPPORTED("Unsupported");
private final String str;
EmbeddedServiceType( String str )
{
this.str = str;
}
@Override
public String toString()
{
return str;
}
}
public static EmbeddedServiceType stringToEmbeddedServiceType( String str )
{
switch( str.toLowerCase() ) {
case "jolie":
return EmbeddedServiceType.JOLIE;
case "java":
return EmbeddedServiceType.JAVA;
case "javascript":
return EmbeddedServiceType.JAVASCRIPT;
default:
return EmbeddedServiceType.UNSUPPORTED;
}
}
public enum ExecutionMode
{
SINGLE, SEQUENTIAL, CONCURRENT
}
public enum OperationType
{
ONE_WAY,
REQUEST_RESPONSE
}
public enum OperandType
{
ADD, SUBTRACT,
MULTIPLY, DIVIDE,
MODULUS
}
public static long serialVersionUID()
{
return 1L;
}
}
| Version bump
Former-commit-id: 259ff6ee9f35e2c9c356ce01681f08b789d61bd6 | libjolie/src/jolie/lang/Constants.java | Version bump | <ide><path>ibjolie/src/jolie/lang/Constants.java
<ide> public final class Constants
<ide> {
<ide> // Release information
<del> public static final String VERSION = "Jolie 1.6.2";
<del> public static final String COPYRIGHT = "(C) 2006-2017 the Jolie team";
<add> public static final String VERSION = "Jolie 1.6.3";
<add> public static final String COPYRIGHT = "(C) 2006-2018 the Jolie team";
<ide>
<ide> public interface Manifest
<ide> { |
|
JavaScript | apache-2.0 | 4a0d2b7307b52dccf09e5cb1feeda815add3b6fa | 0 | rndsolutions/hawkcd,rndsolutions/hawkcd,rndsolutions/hawkcd,rndsolutions/hawkcd,rndsolutions/hawkcd | /* Copyright (C) 2016 R&D Solutions Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
angular
.module('hawk.pipelinesManagement')
.factory('pipeConfigService', ['jsonHandlerService', 'websocketSenderService', function (jsonHandlerService, websocketSenderService) {
var pipeConfigService = this;
//region Senders
//region /pipeline
pipeConfigService.getAllPipelineDefinitions = function () {
var methodName = "getAll";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.getPipelineDefinitionById = function (id) {
var methodName = "getById";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.getAllPipelineGroupDTOs = function () {
var methodName = "getAllPipelineGroupDTOs";
var className = "PipelineGroupService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.addPipelineDefinition = function (pipelineDefinition) {
var methodName = "add";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.addPipelineDefinitionWithMaterial = function (pipelineDefinition,materialDefinition) {
var methodName = "addWithMaterialDefinition";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}," + "{\"packageName\": \"io.hawkcd.model.MaterialDefinition\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.addPipelineDefinitionWithExistingMaterial = function (pipelineDefinition,materialDefinition) {
var methodName = "addWithMaterialDefinition";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}," + "{\"packageName\": \"java.lang.String\", \"object\": \"" + materialDefinition + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.updatePipelineDefinition = function (pipelineDefinition) {
var methodName = "update";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//TODO: Send Pipeline Definition and Pipeline Group to assign to (and possibly Pipeline Group that is assigned from)
pipeConfigService.assignPipelineDefinition = function (pipelineDefinitionId, pipelineGroupId, pipelineGroupName) {
var methodName = "assignPipelineToGroup";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineDefinitionId + "\"}, " +
"{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineGroupId + "\"}, " +
"{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineGroupName + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//TODO: Send Pipeline Definition to be unassigned
pipeConfigService.unassignPipelineDefinition = function (pipelineDefinitionId) {
var methodName = "unassignPipelineFromGroup";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineDefinitionId + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//TODO: Send Pipeline Definition to be deleted
pipeConfigService.deletePipelineDefinition = function (pipelineDefinition) {
var methodName = "delete";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.createPipeline = function (pipeline, token) {
};
pipeConfigService.deletePipeline = function (pipeName, token) {
};
pipeConfigService.getPipelineDef = function (pipeName, token) {
};
pipeConfigService.updatePipeline = function (pipeName, pipeline, token) {
};
//endregion
//region /pipelines_groups
pipeConfigService.getAllGroups = function (token) {
};
pipeConfigService.createGroup = function (pipeGroup, token) {
};
pipeConfigService.deleteGroup = function (pipeGroupName, token) {
};
pipeConfigService.getGroup = function (pipeGroupName, token) {
};
pipeConfigService.updateGroup = function (pipeGroupName, pipeGroup, token) {
};
//endregion
//region /stages
pipeConfigService.getAllStageDefinitions = function () {
var methodName = "getAll";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.getStageDefinitionById = function (id) {
var methodName = "getById";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.addStageDefinition = function (stageDefinition) {
var methodName = "add";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.StageDefinition\", \"object\": " + JSON.stringify(stageDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.updateStageDefinition = function (stageDefinition) {
var methodName = "update";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.StageDefinition\", \"object\": " + JSON.stringify(stageDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//TODO: Send Stage Definition to be deleted
pipeConfigService.deleteStageDefinition = function (stageDefinition) {
var methodName = "delete";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.StageDefinition\", \"object\": " + JSON.stringify(stageDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//endregion
//region /jobs
pipeConfigService.getAllJobDefinitions = function () {
var methodName = "getAll";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.getJobDefinitionById = function (id) {
var methodName = "getById";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.addJobDefinition = function (jobDefinition) {
var methodName = "add";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.JobDefinition\", \"object\": " + JSON.stringify(jobDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.updateJobDefinition = function (jobDefinition) {
var methodName = "update";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.JobDefinition\", \"object\": " + JSON.stringify(jobDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//TODO: Send Job Definition to be deleted
pipeConfigService.deleteJobDefinition = function (jobDefinition) {
var methodName = "delete";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.JobDefinition\", \"object\": " + JSON.stringify(jobDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//endregion
//region /tasks
pipeConfigService.addTaskDefinition = function (taskDefinition){
var methodName = "add";
var className = "TaskDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.TaskDefinition\", \"object\": " + JSON.stringify(taskDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.updateTaskDefinition = function (taskDefinition) {
var methodName = "update";
var className = "TaskDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.TaskDefinition\", \"object\": " + JSON.stringify(taskDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
//TODO: Send Task Definition to be deleted
pipeConfigService.deleteTaskDefinition = function (taskDefinition) {
var methodName = "delete";
var className = "TaskDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.TaskDefinition\", \"object\": " + JSON.stringify(taskDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.getAllMaterialDefinitions = function () {
var methodName = "getAll";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.getMaterialDefinitionById = function (id) {
var methodName = "getById";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.addGitMaterialDefinition = function (materialDefinition) {
var methodName = "add";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.GitMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.addNugetMaterialDefinition = function (materialDefinition) {
var methodName = "add";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.NugetMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.updateGitMaterialDefinition = function (materialDefinition) {
var methodName = "update";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.GitMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.updateNugetMaterialDefinition = function (materialDefinition) {
var methodName = "update";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.NugetMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.deleteMaterialDefinition = function (materialDefinition) {
var methodName = "delete";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.MaterialDefinition\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
};
pipeConfigService.getAllTasks = function (pipeName, stageName, jobName, token) {
};
pipeConfigService.deleteTask = function (pipeName, stageName, jobName, taskIndex, token) {
};
pipeConfigService.getTask = function (pipeName, stageName, jobName, taskIndex, token) {
};
pipeConfigService.createExecTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.createFetchArtifactTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.createFetchMaterialTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.createUploadArtifactTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.updateExecTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
pipeConfigService.updateFetchArtifactTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
pipeConfigService.updateFetchMaterialTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
pipeConfigService.updateUploadArtifactTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
//endregion
//region /artifacts
pipeConfigService.getAllArtifacts = function (pipeName, stageName, jobName, token) {
};
pipeConfigService.createArtifact = function (pipeName, stageName, jobName, artifactIndex, token) {
};
pipeConfigService.deleteArtifact = function (pipeName, stageName, jobName, artifactIndex, token) {
};
pipeConfigService.getArtifact = function (pipeName, stageName, jobName, artifactIndex, token) {
};
pipeConfigService.updateArtifact = function (pipeName, stageName, jobName, artifactIndex, artifact, token) {
};
//endregion
//region /materials
pipeConfigService.getAllMaterials = function (pipeName, token) {
};
pipeConfigService.getMaterial = function (pipeName, materialName, token) {
};
pipeConfigService.createMaterial = function (pipeName, material, token) {
};
pipeConfigService.deleteMaterial = function (pipeName, materialName, token) {
};
pipeConfigService.updateMaterial = function (pipeName, materialName, material, token) {
};
//endregion
//region /environments
pipeConfigService.getAllEnvironments = function (token) {
};
pipeConfigService.createEnvironment = function (environment, token) {
};
pipeConfigService.deleteEnvironment = function (environmentName, token) {
};
pipeConfigService.getEnvironment = function (environmentName, token) {
};
pipeConfigService.updateEnvironment = function (environmentName, environment, token) {
};
//endregion
pipeConfigService.getAllPipelineVars = function (pipelineName, token) {
};
pipeConfigService.getAllStageVars = function (pipelineName, stageName, token) {
};
pipeConfigService.getAllJobVars = function (pipelineName, stageName, jobName, token) {
};
pipeConfigService.getPipelineVar = function (pipelineName, variable, token) {
};
pipeConfigService.getStageVar = function (pipelineName, stageName, variable, token) {
};
pipeConfigService.getJobVar = function (pipelineName, stageName, jobName, variable, token) {
};
pipeConfigService.createPipelineVar = function (pipelineName, variable, token) {
};
pipeConfigService.createStageVar = function (pipelineName, stageName, variable, token) {
};
pipeConfigService.createJobVar = function (pipelineName, stageName, jobName, variable, token) {
};
pipeConfigService.deletePipelineVar = function (pipelineName, variableName, token) {
};
pipeConfigService.deleteStageVar = function (pipelineName, stageName, variableName, token) {
};
pipeConfigService.deleteJobVar = function (pipelineName, stageName, jobName, variableName, token) {
};
pipeConfigService.updatePipelineVar = function (pipelineName, variableName, variable, token) {
};
pipeConfigService.updateStageVar = function (pipelineName, stageName, variableName, variable, token) {
};
pipeConfigService.updateJobVar = function (pipelineName, stageName, jobName, variableName, variable, token) {
};
pipeConfigService.getLatestCommit = function (token) {
};
//endregion
return pipeConfigService;
}]);
| Server/ui/src/app/pipelines/services/pipelineConfig.service.js | /* Copyright (C) 2016 R&D Solutions Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
angular
.module('hawk.pipelinesManagement')
.factory('pipeConfigService', ['jsonHandlerService', 'websocketSenderService', function (jsonHandlerService, websocketSenderService) {
var pipeConfigService = this;
//region Senders
//region /pipeline
pipeConfigService.getAllPipelineDefinitions = function () {
var methodName = "getAll";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.getPipelineDefinitionById = function (id) {
var methodName = "getById";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.getAllPipelineGroupDTOs = function () {
var methodName = "getAllPipelineGroupDTOs";
var className = "PipelineGroupService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.addPipelineDefinition = function (pipelineDefinition) {
var methodName = "add";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.addPipelineDefinitionWithMaterial = function (pipelineDefinition,materialDefinition) {
var methodName = "addWithMaterialDefinition";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}," + "{\"packageName\": \"io.hawkcd.model.MaterialDefinition\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.addPipelineDefinitionWithExistingMaterial = function (pipelineDefinition,materialDefinition) {
var methodName = "addWithMaterialDefinition";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}," + "{\"packageName\": \"java.lang.String\", \"object\": \"" + materialDefinition + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.updatePipelineDefinition = function (pipelineDefinition) {
var methodName = "update";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//TODO: Send Pipeline Definition and Pipeline Group to assign to (and possibly Pipeline Group that is assigned from)
pipeConfigService.assignPipelineDefinition = function (pipelineDefinitionId, pipelineGroupId, pipelineGroupName) {
var methodName = "assignPipelineToGroup";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineDefinitionId + "\"}, " +
"{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineGroupId + "\"}, " +
"{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineGroupName + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//TODO: Send Pipeline Definition to be unassigned
pipeConfigService.unassignPipelineDefinition = function (pipelineDefinitionId) {
var methodName = "unassignPipelineFromGroup";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + pipelineDefinitionId + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//TODO: Send Pipeline Definition to be deleted
pipeConfigService.deletePipelineDefinition = function (pipelineDefinition) {
var methodName = "delete";
var className = "PipelineDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.PipelineDefinition\", \"object\": " + JSON.stringify(pipelineDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.createPipeline = function (pipeline, token) {
};
pipeConfigService.deletePipeline = function (pipeName, token) {
};
pipeConfigService.getPipelineDef = function (pipeName, token) {
};
pipeConfigService.updatePipeline = function (pipeName, pipeline, token) {
};
//endregion
//region /pipelines_groups
pipeConfigService.getAllGroups = function (token) {
};
pipeConfigService.createGroup = function (pipeGroup, token) {
};
pipeConfigService.deleteGroup = function (pipeGroupName, token) {
};
pipeConfigService.getGroup = function (pipeGroupName, token) {
};
pipeConfigService.updateGroup = function (pipeGroupName, pipeGroup, token) {
};
//endregion
//region /stages
pipeConfigService.getAllStageDefinitions = function () {
var methodName = "getAll";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.getStageDefinitionById = function (id) {
var methodName = "getById";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.addStageDefinition = function (stageDefinition) {
var methodName = "add";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.StageDefinition\", \"object\": " + JSON.stringify(stageDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.updateStageDefinition = function (stageDefinition) {
var methodName = "update";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.StageDefinition\", \"object\": " + JSON.stringify(stageDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//TODO: Send Stage Definition to be deleted
pipeConfigService.deleteStageDefinition = function (stageDefinition) {
var methodName = "delete";
var className = "StageDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.StageDefinition\", \"object\": " + JSON.stringify(stageDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//endregion
//region /jobs
pipeConfigService.getAllJobDefinitions = function () {
var methodName = "getAll";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.getJobDefinitionById = function (id) {
var methodName = "getById";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.addJobDefinition = function (jobDefinition) {
var methodName = "add";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.JobDefinition\", \"object\": " + JSON.stringify(jobDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.updateJobDefinition = function (jobDefinition) {
var methodName = "update";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.JobDefinition\", \"object\": " + JSON.stringify(jobDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//TODO: Send Job Definition to be deleted
pipeConfigService.deleteJobDefinition = function (jobDefinition) {
var methodName = "delete";
var className = "JobDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.JobDefinition\", \"object\": " + JSON.stringify(jobDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//endregion
//region /tasks
pipeConfigService.addTaskDefinition = function (taskDefinition){
var methodName = "add";
var className = "TaskDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.TaskDefinition\", \"object\": " + JSON.stringify(taskDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.updateTaskDefinition = function (taskDefinition) {
var methodName = "update";
var className = "TaskDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.TaskDefinition\", \"object\": " + JSON.stringify(taskDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
//TODO: Send Task Definition to be deleted
pipeConfigService.deleteTaskDefinition = function (taskDefinition) {
var methodName = "delete";
var className = "TaskDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.TaskDefinition\", \"object\": " + JSON.stringify(taskDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.getAllMaterialDefinitions = function () {
var methodName = "getAll";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"\", \"object\": \"\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.getMaterialDefinitionById = function (id) {
var methodName = "getById";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"java.lang.String\", \"object\": \"" + id + "\"}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.addGitMaterialDefinition = function (materialDefinition) {
var methodName = "add";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.GitMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.addNugetMaterialDefinition = function (materialDefinition) {
var methodName = "add";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.NugetMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.updateGitMaterialDefinition = function (materialDefinition) {
var methodName = "update";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.GitMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.updateNugetMaterialDefinition = function (materialDefinition) {
var methodName = "update";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.NugetMaterial\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.deleteMaterialDefinition = function (materialDefinition) {
var methodName = "delete";
var className = "MaterialDefinitionService";
var packageName = "io.hawkcd.services";
var result = "";
var args = ["{\"packageName\": \"io.hawkcd.model.MaterialDefinition\", \"object\": " + JSON.stringify(materialDefinition) + "}"];
var error = "";
var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
websocketSenderService.call(json);
console.log(json);
};
pipeConfigService.getAllTasks = function (pipeName, stageName, jobName, token) {
};
pipeConfigService.deleteTask = function (pipeName, stageName, jobName, taskIndex, token) {
};
pipeConfigService.getTask = function (pipeName, stageName, jobName, taskIndex, token) {
};
pipeConfigService.createExecTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.createFetchArtifactTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.createFetchMaterialTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.createUploadArtifactTask = function (pipeName, stageName, jobName, task, token) {
};
pipeConfigService.updateExecTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
pipeConfigService.updateFetchArtifactTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
pipeConfigService.updateFetchMaterialTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
pipeConfigService.updateUploadArtifactTask = function (pipeName, stageName, jobName, taskIndex, task, token) {
};
//endregion
//region /artifacts
pipeConfigService.getAllArtifacts = function (pipeName, stageName, jobName, token) {
};
pipeConfigService.createArtifact = function (pipeName, stageName, jobName, artifactIndex, token) {
};
pipeConfigService.deleteArtifact = function (pipeName, stageName, jobName, artifactIndex, token) {
};
pipeConfigService.getArtifact = function (pipeName, stageName, jobName, artifactIndex, token) {
};
pipeConfigService.updateArtifact = function (pipeName, stageName, jobName, artifactIndex, artifact, token) {
};
//endregion
//region /materials
pipeConfigService.getAllMaterials = function (pipeName, token) {
};
pipeConfigService.getMaterial = function (pipeName, materialName, token) {
};
pipeConfigService.createMaterial = function (pipeName, material, token) {
};
pipeConfigService.deleteMaterial = function (pipeName, materialName, token) {
};
pipeConfigService.updateMaterial = function (pipeName, materialName, material, token) {
};
//endregion
//region /environments
pipeConfigService.getAllEnvironments = function (token) {
};
pipeConfigService.createEnvironment = function (environment, token) {
};
pipeConfigService.deleteEnvironment = function (environmentName, token) {
};
pipeConfigService.getEnvironment = function (environmentName, token) {
};
pipeConfigService.updateEnvironment = function (environmentName, environment, token) {
};
//endregion
pipeConfigService.getAllPipelineVars = function (pipelineName, token) {
};
pipeConfigService.getAllStageVars = function (pipelineName, stageName, token) {
};
pipeConfigService.getAllJobVars = function (pipelineName, stageName, jobName, token) {
};
pipeConfigService.getPipelineVar = function (pipelineName, variable, token) {
};
pipeConfigService.getStageVar = function (pipelineName, stageName, variable, token) {
};
pipeConfigService.getJobVar = function (pipelineName, stageName, jobName, variable, token) {
};
pipeConfigService.createPipelineVar = function (pipelineName, variable, token) {
};
pipeConfigService.createStageVar = function (pipelineName, stageName, variable, token) {
};
pipeConfigService.createJobVar = function (pipelineName, stageName, jobName, variable, token) {
};
pipeConfigService.deletePipelineVar = function (pipelineName, variableName, token) {
};
pipeConfigService.deleteStageVar = function (pipelineName, stageName, variableName, token) {
};
pipeConfigService.deleteJobVar = function (pipelineName, stageName, jobName, variableName, token) {
};
pipeConfigService.updatePipelineVar = function (pipelineName, variableName, variable, token) {
};
pipeConfigService.updateStageVar = function (pipelineName, stageName, variableName, variable, token) {
};
pipeConfigService.updateJobVar = function (pipelineName, stageName, jobName, variableName, variable, token) {
};
pipeConfigService.getLatestCommit = function (token) {
};
//endregion
return pipeConfigService;
}]);
| Removed console logging from Pipeline Config service #416
| Server/ui/src/app/pipelines/services/pipelineConfig.service.js | Removed console logging from Pipeline Config service #416 | <ide><path>erver/ui/src/app/pipelines/services/pipelineConfig.service.js
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.getPipelineDefinitionById = function (id) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.getAllPipelineGroupDTOs = function () {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.addPipelineDefinition = function (pipelineDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.addPipelineDefinitionWithMaterial = function (pipelineDefinition,materialDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.addPipelineDefinitionWithExistingMaterial = function (pipelineDefinition,materialDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.updatePipelineDefinition = function (pipelineDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> //TODO: Send Pipeline Definition and Pipeline Group to assign to (and possibly Pipeline Group that is assigned from)
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> //TODO: Send Pipeline Definition to be unassigned
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> //TODO: Send Pipeline Definition to be deleted
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.createPipeline = function (pipeline, token) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> pipeConfigService.getStageDefinitionById = function (id) {
<ide> var methodName = "getById";
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> pipeConfigService.addStageDefinition = function (stageDefinition) {
<ide> var methodName = "add";
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> pipeConfigService.updateStageDefinition = function (stageDefinition) {
<ide> var methodName = "update";
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> //TODO: Send Stage Definition to be deleted
<ide> pipeConfigService.deleteStageDefinition = function (stageDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> //endregion
<ide>
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> pipeConfigService.getJobDefinitionById = function (id) {
<ide> var methodName = "getById";
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> pipeConfigService.addJobDefinition = function (jobDefinition) {
<ide> var methodName = "add";
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> pipeConfigService.updateJobDefinition = function (jobDefinition) {
<ide> var methodName = "update";
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> //TODO: Send Job Definition to be deleted
<ide> pipeConfigService.deleteJobDefinition = function (jobDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide> //endregion
<ide>
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.updateTaskDefinition = function (taskDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> //TODO: Send Task Definition to be deleted
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.getAllMaterialDefinitions = function () {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.getMaterialDefinitionById = function (id) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.addGitMaterialDefinition = function (materialDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.addNugetMaterialDefinition = function (materialDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.updateGitMaterialDefinition = function (materialDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.updateNugetMaterialDefinition = function (materialDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.deleteMaterialDefinition = function (materialDefinition) {
<ide> var error = "";
<ide> var json = jsonHandlerService.createJson(className, packageName, methodName, result, error, args);
<ide> websocketSenderService.call(json);
<del> console.log(json);
<ide> };
<ide>
<ide> pipeConfigService.getAllTasks = function (pipeName, stageName, jobName, token) { |
|
Java | mit | 98f3d0b66c6052a88b24c7813b8b9efb6ac76d14 | 0 | CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab | package org.xcolab.service.contest.domain.contestteammember;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.SelectQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.xcolab.model.tables.pojos.ContestTeamMember;
import org.xcolab.model.tables.records.ContestTeamMemberRecord;
import org.xcolab.service.contest.exceptions.NotFoundException;
import java.util.List;
import java.util.Optional;
import static org.xcolab.model.Tables.CONTEST;
import static org.xcolab.model.Tables.CONTEST_TEAM_MEMBER;
@Repository
public class ContestTeamMemberDaoImpl implements ContestTeamMemberDao{
private final DSLContext dslContext;
@Autowired
public ContestTeamMemberDaoImpl(DSLContext dslContext) {
Assert.notNull(dslContext, "DSLContext bean is required");
this.dslContext = dslContext;
}
@Override
public ContestTeamMember create(ContestTeamMember contestTeamMember) {
ContestTeamMemberRecord ret = this.dslContext.insertInto(CONTEST_TEAM_MEMBER)
.set(CONTEST_TEAM_MEMBER.CONTEST_ID, contestTeamMember.getContestId())
.set(CONTEST_TEAM_MEMBER.USER_ID, contestTeamMember.getUserId())
.set(CONTEST_TEAM_MEMBER.ROLE_ID, contestTeamMember.getRoleId())
.returning(CONTEST_TEAM_MEMBER.ID_)
.fetchOne();
if (ret == null) {
throw new IllegalStateException("Could not retrieve inserted id");
}
contestTeamMember.setId_(ret.getValue(CONTEST_TEAM_MEMBER.ID_));
return contestTeamMember;
}
@Override
public Optional<ContestTeamMember> get(Long id_) throws NotFoundException{
final Record record = this.dslContext.selectFrom(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.ID_.eq(id_))
.fetchOne();
if (record == null) {
return Optional.empty();
}
return Optional.of(record.into(ContestTeamMember.class));
}
@Override
public boolean exists(Long id_) {
return dslContext.selectCount()
.from(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.ID_.eq(id_))
.fetchOne().into(Integer.class) > 0;
}
@Override
public ContestTeamMember findOneBy(Long memberId, Long contestId, Long roleId) {
final Record record = this.dslContext.selectFrom(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.USER_ID.eq(memberId))
.and(CONTEST_TEAM_MEMBER.CONTEST_ID.eq(contestId))
.and(CONTEST_TEAM_MEMBER.ROLE_ID.eq(roleId))
.fetchOne();
if (record == null) {
return null;
}
return record.into(ContestTeamMember.class);
}
@Override
public boolean update(ContestTeamMember contestTeamMember) {
return dslContext.update(CONTEST_TEAM_MEMBER)
.set(CONTEST_TEAM_MEMBER.CONTEST_ID, contestTeamMember.getContestId())
.set(CONTEST_TEAM_MEMBER.USER_ID, contestTeamMember.getUserId())
.set(CONTEST_TEAM_MEMBER.ROLE_ID, contestTeamMember.getRoleId())
.where(CONTEST_TEAM_MEMBER.ID_.eq(contestTeamMember.getId_()))
.execute() > 0;
}
@Override
public List<ContestTeamMember> findByGiven(Long memberId, Long contestId, Long roleId) {
final SelectQuery<Record> query = dslContext.select()
.from(CONTEST_TEAM_MEMBER).getQuery();
if (memberId != null) {
query.addConditions(CONTEST_TEAM_MEMBER.USER_ID.eq(memberId));
}
if (contestId != null) {
query.addConditions(CONTEST_TEAM_MEMBER.CONTEST_ID.eq(contestId));
}
if (roleId != null) {
query.addConditions(CONTEST_TEAM_MEMBER.ROLE_ID.eq(roleId));
}
return query.fetchInto(ContestTeamMember.class);
}
@Override
public List<ContestTeamMember> findContestYear(Long categoryId, Long contestYear) {
final SelectQuery<Record> query = dslContext.select()
.from(CONTEST_TEAM_MEMBER).getQuery();
query.addJoin(CONTEST,CONTEST.CONTEST_PK.eq(CONTEST_TEAM_MEMBER.CONTEST_ID));
query.addConditions(CONTEST.CONTEST_YEAR.eq(contestYear));
query.addConditions(CONTEST_TEAM_MEMBER.ROLE_ID.eq(categoryId));
return query.fetchInto(ContestTeamMember.class);
}
@Override
public boolean delete(Long id_) {
return dslContext.deleteFrom(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.ID_.eq(id_))
.execute() > 0;
}
}
| microservices/services/contest-service/src/main/java/org/xcolab/service/contest/domain/contestteammember/ContestTeamMemberDaoImpl.java | package org.xcolab.service.contest.domain.contestteammember;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.SelectQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.xcolab.model.tables.pojos.ContestTeamMember;
import org.xcolab.model.tables.records.ContestTeamMemberRecord;
import org.xcolab.service.contest.exceptions.NotFoundException;
import java.util.List;
import java.util.Optional;
import static org.xcolab.model.Tables.CONTEST;
import static org.xcolab.model.Tables.CONTEST_TEAM_MEMBER;
@Repository
public class ContestTeamMemberDaoImpl implements ContestTeamMemberDao{
private final DSLContext dslContext;
@Autowired
public ContestTeamMemberDaoImpl(DSLContext dslContext) {
Assert.notNull(dslContext, "DSLContext bean is required");
this.dslContext = dslContext;
}
@Override
public ContestTeamMember create(ContestTeamMember contestTeamMember) {
ContestTeamMemberRecord ret = this.dslContext.insertInto(CONTEST_TEAM_MEMBER)
.set(CONTEST_TEAM_MEMBER.CONTEST_ID, contestTeamMember.getContestId())
.set(CONTEST_TEAM_MEMBER.USER_ID, contestTeamMember.getUserId())
.set(CONTEST_TEAM_MEMBER.ROLE_ID, contestTeamMember.getRoleId())
.returning(CONTEST_TEAM_MEMBER.ID_)
.fetchOne();
if (ret == null) {
throw new IllegalStateException("Could not retrieve inserted id");
}
contestTeamMember.setId_(ret.getValue(CONTEST_TEAM_MEMBER.ID_));
return contestTeamMember;
}
@Override
public Optional<ContestTeamMember> get(Long id_) throws NotFoundException{
final Record record = this.dslContext.selectFrom(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.ID_.eq(id_))
.fetchOne();
if (record == null) {
return Optional.empty();
}
return Optional.of(record.into(ContestTeamMember.class));
}
@Override
public boolean exists(Long id_) {
return dslContext.selectCount()
.from(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.ID_.eq(id_))
.fetchOne().into(Integer.class) > 0;
}
@Override
public ContestTeamMember findOneBy(Long memberId, Long contestId, Long roleId) {
final Record record = this.dslContext.selectFrom(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.USER_ID.eq(memberId))
.and(CONTEST_TEAM_MEMBER.CONTEST_ID.eq(contestId))
.and(CONTEST_TEAM_MEMBER.ROLE_ID.eq(roleId))
.fetchOne();
if (record == null) {
return null;
}
return record.into(ContestTeamMember.class);
}
@Override
public boolean update(ContestTeamMember contestTeamMember) {
return dslContext.update(CONTEST_TEAM_MEMBER)
.set(CONTEST_TEAM_MEMBER.CONTEST_ID, contestTeamMember.getContestId())
.set(CONTEST_TEAM_MEMBER.USER_ID, contestTeamMember.getUserId())
.set(CONTEST_TEAM_MEMBER.ROLE_ID, contestTeamMember.getRoleId())
.where(CONTEST_TEAM_MEMBER.ID_.eq(contestTeamMember.getId_()))
.execute() > 0;
}
@Override
public List<ContestTeamMember> findByGiven(Long memberId, Long contestId, Long roleId) {
final SelectQuery<Record> query = dslContext.select()
.from(CONTEST_TEAM_MEMBER).getQuery();
if (memberId != null) {
query.addConditions(CONTEST_TEAM_MEMBER.USER_ID.eq(memberId));
}
if (contestId != null) {
query.addConditions(CONTEST_TEAM_MEMBER.CONTEST_ID.eq(contestId));
}
if (roleId != null) {
query.addConditions(CONTEST_TEAM_MEMBER.ROLE_ID.eq(roleId));
}
return query.fetchInto(ContestTeamMember.class);
}
@Override
public List<ContestTeamMember> findContestYear(Long categoryId, Long contestYear) {
final SelectQuery<Record> query = dslContext.select()
.from(CONTEST_TEAM_MEMBER).getQuery();
query.addJoin(CONTEST,CONTEST.CONTEST_PK.eq(CONTEST_TEAM_MEMBER.CONTEST_ID));
query.addConditions(CONTEST.CONTEST_YEAR.eq(contestYear));
query.addConditions(CONTEST.CONTEST_PRIVATE.eq(false));
query.addConditions(CONTEST_TEAM_MEMBER.ROLE_ID.eq(categoryId));
return query.fetchInto(ContestTeamMember.class);
}
@Override
public boolean delete(Long id_) {
return dslContext.deleteFrom(CONTEST_TEAM_MEMBER)
.where(CONTEST_TEAM_MEMBER.ID_.eq(id_))
.execute() > 0;
}
}
| [COLAB-2371] Include contest team members from private contests in list
| microservices/services/contest-service/src/main/java/org/xcolab/service/contest/domain/contestteammember/ContestTeamMemberDaoImpl.java | [COLAB-2371] Include contest team members from private contests in list | <ide><path>icroservices/services/contest-service/src/main/java/org/xcolab/service/contest/domain/contestteammember/ContestTeamMemberDaoImpl.java
<ide> query.addJoin(CONTEST,CONTEST.CONTEST_PK.eq(CONTEST_TEAM_MEMBER.CONTEST_ID));
<ide>
<ide> query.addConditions(CONTEST.CONTEST_YEAR.eq(contestYear));
<del> query.addConditions(CONTEST.CONTEST_PRIVATE.eq(false));
<ide>
<ide> query.addConditions(CONTEST_TEAM_MEMBER.ROLE_ID.eq(categoryId));
<ide> |
|
Java | agpl-3.0 | c9f4c3a1d023fed0869813ccaef5695a69d38c2d | 0 | cinquin/mutinack,cinquin/mutinack,cinquin/mutinack,cinquin/mutinack,cinquin/mutinack | /**
* Mutinack mutation detection program.
* Copyright (C) 2014-2016 Olivier Cinquin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.org.cinquin.mutinack;
import static uk.org.cinquin.mutinack.misc_util.Util.blueF;
import static uk.org.cinquin.mutinack.misc_util.Util.greenB;
import static uk.org.cinquin.mutinack.misc_util.Util.reset;
import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.TERSE;
import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.VERBOSE;
import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.VERY_VERBOSE;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.Join;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import uk.org.cinquin.final_annotation.Final;
import uk.org.cinquin.mutinack.features.PosByPosNumbersPB.GenomeNumbers.Builder;
import uk.org.cinquin.mutinack.misc_util.Assert;
import uk.org.cinquin.mutinack.misc_util.ComparablePair;
import uk.org.cinquin.mutinack.misc_util.FieldIteration;
import uk.org.cinquin.mutinack.misc_util.SerializablePredicate;
import uk.org.cinquin.mutinack.misc_util.Util;
import uk.org.cinquin.mutinack.misc_util.collections.MutationHistogramMap;
import uk.org.cinquin.mutinack.output.LocationAnalysis;
import uk.org.cinquin.mutinack.qualities.Quality;
import uk.org.cinquin.mutinack.statistics.Actualizable;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocOnly;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocOnlyReportAll;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocation;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocationReportAll;
import uk.org.cinquin.mutinack.statistics.DivideByTwo;
import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter;
import uk.org.cinquin.mutinack.statistics.Histogram;
import uk.org.cinquin.mutinack.statistics.LongAdderFormatter;
import uk.org.cinquin.mutinack.statistics.MultiCounter;
import uk.org.cinquin.mutinack.statistics.PrintInStatus;
import uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel;
import uk.org.cinquin.mutinack.statistics.StatsCollector;
import uk.org.cinquin.mutinack.statistics.SwitchableStats;
import uk.org.cinquin.mutinack.statistics.Traceable;
@PersistenceCapable
public class AnalysisStats implements Serializable, Actualizable {
public @Final @Persistent @NonNull String name;
public OutputLevel outputLevel;
public final MutinackGroup groupSettings;
public @Final @Persistent Set<String> mutinackVersions = new HashSet<>();
public @Final @Persistent Map<@NonNull String, @NonNull String> inputBAMHashes = new HashMap<>();
public @Final @Persistent @NonNull Parameters analysisParameters;
public @Final @Persistent boolean forInsertions;
//Changed to Map instead of ConcurrentMap to please datanucleus
public @Final @Persistent @Join Map<SequenceLocation, LocationAnalysis> detections = new ConcurrentHashMap<>();
public transient PrintStream detectionOutputStream;
public transient OutputStreamWriter annotationOutputStream;
public transient @Nullable OutputStreamWriter topBottomDisagreementWriter, noWtDisagreementWriter,
mutationBEDWriter, coverageBEDWriter;
public boolean canSkipDuplexLoading = false;
public AnalysisStats(@NonNull String name,
@NonNull Parameters param,
boolean forInsertions,
@NonNull MutinackGroup groupSettings,
boolean reportCoverageAtAllPositions) {
this.name = name;
this.analysisParameters = param;
this.forInsertions = forInsertions;
this.groupSettings = groupSettings;
nPosDuplexCandidatesForDisagreementQ2 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexCandidatesForDisagreementQ1 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexQualityQ2OthersQ1Q2 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexTooFewReadsPerStrand1 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexTooFewReadsPerStrand2 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexTooFewReadsAboveQ2Phred = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nRecordsNotInIntersection1 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nRecordsNotInIntersection2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nTooLowMapQIntersect = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplex = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplexBothStrandsPresent = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosIgnoredBecauseTooHighCoverage = new StatsCollector();
nReadMedianPhredBelowThreshold = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
phredAndLigSiteDistance = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, false);
nDuplexesTooMuchClipping = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nDuplexesNoStats = new LongAdder();
nDuplexesWithStats = new LongAdder();
nPosDuplexWithTopBottomDuplexDisagreementNoWT = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplexWithTopBottomDuplexDisagreementNotASub = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
vBarcodeMismatches1M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
vBarcodeMismatches2M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
vBarcodeMismatches3OrMore = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
rawDeletionLengthQ1 = new Histogram(200);
rawInsertionLengthQ1 = new Histogram(200);
rawDeletionLengthQ2 = new Histogram(200);
rawMismatchesQ1 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawDeletionsQ1 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawInsertionsQ1 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawMismatchesQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawDeletionsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawInsertionsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
intraStrandSubstitutions = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
intraStrandDeletions = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
intraStrandInsertions = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomSubstDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, false);
topBottomDelDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomRearDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomIntronDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomInsDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawInsertionLengthQ2 = new Histogram(200);
alleleFrequencies = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
codingStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
templateStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
codingStrandDelQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
templateStrandDelQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
codingStrandInsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
templateStrandInsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
topBottomDisagreementsQ2TooHighCoverage = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null);
nPosDuplexCandidatesForDisagreementQ2TooHighCoverage = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplexWithLackOfStrandConsensus1 = new StatsCollector();
nPosDuplexWithLackOfStrandConsensus2 = new StatsCollector();
nPosDuplexCompletePairOverlap = new StatsCollector();
nPosUncovered = new StatsCollector();
nQ2PromotionsBasedOnFractionReads = new StatsCollector();
nPosQualityPoor = new StatsCollector();
nPosQualityPoorA = new StatsCollector();
nPosQualityPoorT = new StatsCollector();
nPosQualityPoorG = new StatsCollector();
nPosQualityPoorC = new StatsCollector();
nConsensusQ1NotMet = new StatsCollector();
nMedianPhredAtPositionTooLow = new StatsCollector();
nFractionWrongPairsAtPositionTooHigh = new StatsCollector();
nPosQualityQ1 = new StatsCollector();
nPosQualityQ2 = new StatsCollector();
nPosQualityQ2OthersQ1Q2 = new StatsCollector();
nPosDuplexQualityQ2OthersQ1Q2CodingOrTemplate = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosCandidatesForUniqueMutation = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nReadsInPrefetchQueue = new Histogram(1_000);
{ //Force output of fields annotated with AddChromosomeBins to be broken down by
//bins for each contig (bin size as defined by CounterWithSeqLocation.BIN_SIZE, for now)
List<String> contigNamesToProcess = groupSettings.getContigNamesToProcess();
for (Field field : AnalysisStats.class.getDeclaredFields()) {
@Nullable AddChromosomeBins annotation = field.getAnnotation(AddChromosomeBins.class);
if (annotation != null) {
for (final @NonNull String contigName: contigNamesToProcess) {
final int contigIndex = Objects.requireNonNull(
groupSettings.getIndexContigNameReverseMap().get(contigName), () -> "Missing contig index for " + contigName);
for (int c = 0; c < Objects.requireNonNull(groupSettings.getContigSizes().get(contigName),
() -> "Missing contig size for contig " + contigName)
/ groupSettings.BIN_SIZE; c++) {
final int finalBinIndex = c;
try {
MultiCounter <?> counter = ((MultiCounter<?>) field.get(this));
counter.addPredicate(contigName + "_bin_" + String.format("%03d", c),
loc -> {
final int min = groupSettings.BIN_SIZE * finalBinIndex;
final int max = groupSettings.BIN_SIZE * (finalBinIndex + 1);
return loc.contigIndex == contigIndex &&
loc.position >= min &&
loc.position < max;
});
counter.accept(new SequenceLocation(analysisParameters.referenceGenomeShortName, contigName,
groupSettings.getIndexContigNameReverseMap(), c * groupSettings.BIN_SIZE), 0);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
//Force initialization of counters for all possible substitutions:
//it is easier to put the output of multiple samples together if
//unencountered substitutions have a 0-count entry
for (byte mut: Arrays.asList((byte) 'A', (byte) 'T', (byte) 'G', (byte) 'C')) {
for (byte wt: Arrays.asList((byte) 'A', (byte) 'T', (byte) 'G', (byte) 'C')) {
if (wt == mut) {
continue;
}
Mutation wtM = new Mutation(MutationType.WILDTYPE, wt, null, Util.emptyOptional());
Mutation to = new Mutation(MutationType.SUBSTITUTION, wt, new byte [] {mut}, Util.emptyOptional());
ComparablePair<Mutation, Mutation> cpMut = new ComparablePair<>(wtM, to);
DuplexDisagreement disag = new DuplexDisagreement(wtM, to, true, Quality.GOOD);
List<String> contigNames = groupSettings.getContigNames();
for (int contig = 0; contig < contigNames.size(); contig++) {
for (int c = 0; c < Objects.requireNonNull(groupSettings.getContigSizes().get(
contigNames.get(contig))) / groupSettings.BIN_SIZE; c++) {
SequenceLocation location = new SequenceLocation(analysisParameters.referenceGenomeShortName, contig,
Objects.requireNonNull(contigNames.get(contig)), c * groupSettings.BIN_SIZE);
topBottomSubstDisagreementsQ2.accept(location, disag, 0);
codingStrandSubstQ2.accept(location, cpMut, 0);
templateStrandSubstQ2.accept(location, cpMut, 0);
}
}
}
}
//Assert that annotations have not been discarded
//This does not need to be done on every instance, but exceptions are better
//handled in a non-static context
try {
Assert.isNonNull(AnalysisStats.class.getDeclaredField("duplexGroupingDepth").
getAnnotation(PrintInStatus.class));
} catch (NoSuchFieldException | SecurityException e) {
throw new RuntimeException(e);
}
}
public @NonNull String getName() {
return name;
}
private static final long serialVersionUID = -7786797851357308577L;
public double processingThroughput(long timeStartProcessing) {
return (nRecordsProcessed.sum()) /
((System.nanoTime() - timeStartProcessing) / 1_000_000_000d);
//TODO Store start and stop times in AnalysisStats
}
@Retention(RetentionPolicy.RUNTIME)
private @interface AddChromosomeBins {};
@Retention(RetentionPolicy.RUNTIME)
private @interface AddLocationPredicates {};
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized="true")
@Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexGroupingDepth = new Histogram(100);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram minTopCandFreqQ2PosTopAlleleFreqOK = new Histogram(11);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram minTopCandFreqQ2PosTopAlleleFreqKO = new Histogram(11);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexTotalRecords = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rejectedIndelDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rejectedSubstDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtRejectedDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtAcceptedBaseDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram singleAnalyzerQ2CandidateDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram crossAnalyzerQ2CandidateDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
ConcurrentMap<Mutation, Histogram> disagMutConsensus = new MutationHistogramMap();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
ConcurrentMap<Mutation, Histogram> disagWtConsensus = new MutationHistogramMap();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram substDisagDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram insDisagDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram delDisagDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram disagDelSize = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram Q2CandidateDistanceToLigationSiteN = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtQ2CandidateQ1Q2Coverage = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtQ2CandidateQ1Q2CoverageRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtQ2CandidateQ1Q2CoverageNonRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mutantQ2CandidateQ1Q2Coverage = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mutantQ2CandidateQ1Q2DCoverageRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mutantQ2CandidateQ1Q2DCoverageNonRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram uniqueMutantQ2CandidateQ1Q2DCoverage = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram uniqueMutantQ2CandidateQ1Q2DCoverageRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram uniqueMutantQ2CandidateQ1Q2DCoverageNonRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosExcluded = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nRecordsProcessed = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector ignoredUnpairedReads = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nRecordsInFile = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nRecordsUnmapped = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nRecordsBelowMappingQualityThreshold = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mappingQualityKeptRecords = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mappingQualityAllRecords = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram averageReadPhredQuality0 = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram averageReadPhredQuality1 = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
MultiCounter<ComparablePair<Integer, Integer>> phredAndLigSiteDistance;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram medianReadPhredQuality = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram medianPositionPhredQuality = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram averageDuplexReferenceDisagreementRate = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexinsertSize = new Histogram(1000);
@PrintInStatus(outputLevel = VERBOSE)
public @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
double[] approximateReadInsertSize = null;
@PrintInStatus(outputLevel = VERBOSE)
public @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
double[] approximateReadInsertSizeRaw = null;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexAverageNClipped = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexInsert130_180averageNClipped = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexInsert100_130AverageNClipped = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram disagreementOrientationProportions1 = new Histogram(10);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram disagreementOrientationProportions2 = new Histogram(10);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector disagreementMatesSameOrientation = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nComplexDisagreementsQ2 = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nRecordsIgnoredBecauseSecondary = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nRecordsNotInIntersection1;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nRecordsNotInIntersection2;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nTooLowMapQIntersect;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplex;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexBothStrandsPresent;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nReadMedianPhredBelowThreshold;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nDuplexesTooMuchClipping;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent LongAdder nDuplexesNoStats;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent LongAdder nDuplexesWithStats;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsPerStrand1;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsPerStrand2;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsAboveQ2Phred;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nPosIgnoredBecauseTooHighCoverage;
@PrintInStatus(outputLevel = VERY_VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexWithTopBottomDuplexDisagreementNoWT;
@AddLocationPredicates
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexWithTopBottomDuplexDisagreementNotASub;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawMismatchesQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches1M;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches2M;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches3OrMore;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawDeletionsQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawDeletionLengthQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawInsertionsQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawInsertionLengthQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawMismatchesQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") LongAdderFormatter rawMismatchesNReads = new LongAdderFormatter();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawDeletionsQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawDeletionLengthQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawInsertionsQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawInsertionLengthQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
LongAdderFormatter intraStrandAndRawMismatchNPositions = new LongAdderFormatter();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
LongAdderFormatter intraStrandNReads = new LongAdderFormatter();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> intraStrandSubstitutions;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> intraStrandDeletions;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> intraStrandInsertions;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomSubstDisagreementsQ2;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomDelDisagreementsQ2;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomRearDisagreementsQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomIntronDisagreementsQ2;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
public @Final @Persistent(serialized = "true") MultiCounter<List<Integer>> alleleFrequencies;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomInsDisagreementsQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandSubstQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandSubstQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandDelQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandDelQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandInsQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandInsQ2;
@PrintInStatus(outputLevel = VERY_VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomDisagreementsQ2TooHighCoverage;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ1;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ2TooHighCoverage;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosDuplexWithLackOfStrandConsensus1;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosDuplexWithLackOfStrandConsensus2;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosDuplexCompletePairOverlap;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosUncovered;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nQ2PromotionsBasedOnFractionReads;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoor;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorA;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorT;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorG;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorC;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nConsensusQ1NotMet;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nMedianPhredAtPositionTooLow;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nFractionWrongPairsAtPositionTooHigh;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityQ2OthersQ1Q2;
@PrintInStatus(outputLevel = TERSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexQualityQ2OthersQ1Q2;
@PrintInStatus(outputLevel = TERSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexQualityQ2OthersQ1Q2CodingOrTemplate;
@PrintInStatus(color = "greenBackground", outputLevel = TERSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosCandidatesForUniqueMutation;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nReadsAtPosQualityQ2OthersQ1Q2 = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nReadsAtPosWithSomeCandidateForQ2UniqueMutation = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexDistance = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram concurringMutationDuplexDistance = new Histogram(2_000);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram concurringDuplexDistance = new Histogram(2_000);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexLocalGroupSize = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexLocalShiftedGroupSize = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nQ1Q2AtPosQualityQ2OthersQ1Q2 = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nQ1Q2AtPosWithSomeCandidateForQ2UniqueMutation = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE, description = "Q1 or Q2 duplex coverage histogram")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram Q1Q2DuplexCoverage = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE, description = "Q2 duplex coverage histogram")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram Q2DuplexCoverage = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Missing strands for positions that have no usable duplex")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram missingStrandsWhenNoUsableDuplex = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Top/bottom coverage imbalance for positions that have no usable duplex")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram strandCoverageImbalanceWhenNoUsableDuplex = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of copy number for duplex bottom strands")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram copyNumberOfDuplexBottomStrands = new Histogram(500) {
private static final long serialVersionUID = 6597978073262739721L;
private final NumberFormat formatter = new DecimalFormat("0.###E0");
@Override
public String toString() {
final double nPosDuplexf = nPosDuplex.sum();
return stream().map(a -> formatter.format((float) (a.sum() / nPosDuplexf))).
collect(Collectors.toList()).toString();
}
};
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of copy number for duplex top strands")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram copyNumberOfDuplexTopStrands = new Histogram(500) {
private static final long serialVersionUID = -8213283701959613589L;
private final NumberFormat formatter = new DecimalFormat("0.###E0");
@Override
public String toString() {
final double nPosDuplexf = nPosDuplex.sum();
return stream().map(a -> formatter.format((float) (a.sum() / nPosDuplexf))).
collect(Collectors.toList()).toString();
}
};
@PrintInStatus(outputLevel = VERBOSE, description = "Number of duplexes that have both strands represented " +
"(and therefore two or more read pairs)")
public @Final @Persistent StatsCollector nDuplexesTwoOrMoreReadPairsAndBothStrands = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE, description = "Number of duplexes that have two or more read pairs " +
"(for comparison with nDuplexesTwoOrMoreReadPairsAndBothStrands)")
public @Final @Persistent StatsCollector nDuplexesTwoOrMoreReadPairs = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbability = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability at Q2 sites")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityAtQ2 = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability when both strands represented")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityWhen2Strands = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability at disagreement")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityAtDisag = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Average duplex collision probability for duplexes covering genome position of disagreement")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityLocalAvAtDisag = new Histogram(100);
/*
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of variable barcode mapping distance mismatch")
public final Histogram sameBarcodeButPositionMismatch = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE, description = "Candidates with top good coverage")
public final PriorityBlockingQueue<CandidateSequence> topQ2DuplexCoverage = new PriorityBlockingQueue<CandidateSequence>
(100, (c1, c2) -> Integer.compare(c1.getnGoodDuplexes(),c2.getnGoodDuplexes())) {
private static final long serialVersionUID = 8206630026701622788L;
@Override
public String toString() {
return stream().collect(Collectors.toList()).toString();
}
};*/
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nBasesBelowPhredScore = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nConstantBarcodeMissing = new StatsCollector(),
nConstantBarcodeDodgy = new StatsCollector(),
nConstantBarcodeDodgyNStrand = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nReadsConstantBarcodeOK = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsConsidered = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToA = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToT = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToG = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToC = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nNs = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nCandidateInsertions = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nCandidateDeletions = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsAfterLastNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateWildtypeAfterLastNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsBeforeFirstNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateIndelAfterLastNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateIndelBeforeFirstNBases = new StatsCollector();
/*
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeCandidateExaminations = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeLeftEqual = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeRightEqual = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeMateDoesNotMatch = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeMateMatches = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeMatchAfterPositionCheck = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodesCloseMisses = new StatsCollector();*/
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nReadsOpticalDuplicates = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram readDistance = new Histogram(50);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nReadsInsertNoSize = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsPairRF = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsPairTandem = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsInsertSizeAboveMaximum = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsInsertSizeBelowMinimum = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nMateOutOfReach = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nProcessedBases = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
boolean analysisTruncated;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nReadsInPrefetchQueue;
/*
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nProcessedFirst6BasesFirstOfPair = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nProcessedFirst6BasesSecondOfPair = new StatsCollector();*/
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent LongAdder phredSumProcessedbases = new LongAdder();
/*
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final DoubleAdder phredSumFirst6basesFirstOfPair = new DoubleAdder();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final DoubleAdder phredSumFirst6basesSecondOfPair = new DoubleAdder();*/
public @Persistent Map<String, int[]> positionByPositionCoverage;
transient Builder positionByPositionCoverageProtobuilder;
public final StatsCollector nChimericReadsMateWrongContig = new StatsCollector();
public final Histogram inferredRearrangementInsertSizeHistogram = new Histogram(5_000);
public final StatsCollector nChimericReadsMateOK = new StatsCollector();
public final StatsCollector nChimericReadsTooBigInsert = new StatsCollector();
public final StatsCollector nChimericReadsUnmappedMate = new StatsCollector();
public final StatsCollector nNotSingleSupplementary = new StatsCollector();
public final Histogram inferredRearrangementDistanceLogt100Histogram = new Histogram(5_000);
public final StatsCollector nChimericReadsMateWrongSide = new StatsCollector();
@SuppressWarnings("null")
public void print(PrintStream stream, boolean colorize) {
stream.println();
NumberFormat formatter = DoubleAdderFormatter.nf.get();
ConcurrentModificationException cme = null;
for (Field field: AnalysisStats.class.getDeclaredFields()) {
PrintInStatus annotation = field.getAnnotation(PrintInStatus.class);
if ((annotation != null && annotation.outputLevel().compareTo(outputLevel) <= 0) ||
(annotation == null &&
(field.getType().equals(LongAdderFormatter.class) ||
field.getType().equals(StatsCollector.class) ||
field.getType().equals(Histogram.class)))) {
try {
final Object fieldValue = field.get(this);
if (fieldValue == null) {
continue;
}
if (annotation != null && annotation.color().equals("greenBackground")) {
stream.print(greenB(colorize));
}
long divisor;
if (field.getAnnotation(DivideByTwo.class) != null)
divisor = 2;
else
divisor = 1;
boolean hasDescription = annotation != null && !annotation.description().isEmpty();
stream.print(blueF(colorize) + (hasDescription ? annotation.description() : field.getName()) +
": " + reset(colorize));
if (field.getType().equals(LongAdderFormatter.class)) {
stream.println(formatter.format(((Long) longAdderFormatterSum.
invoke(fieldValue)) / divisor));
} else if (field.getType().equals(StatsCollector.class)) {
Function<Long, Long> transformer = l-> l / divisor;
stream.println((String) statsCollectorToString.invoke(fieldValue, transformer));
} else {
stream.println(fieldValue.toString());
}
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
} catch (ConcurrentModificationException e) {
cme = e;
} finally {
if (annotation != null && annotation.color().equals("greenBackground")) {
stream.print(reset(colorize));
}
}
}
}
if (cme != null) {
throw cme;
}
}
private static final Method longAdderFormatterSum, statsCollectorToString, turnOnMethod, turnOffMethod;
static {
try {
longAdderFormatterSum = LongAdder.class.getDeclaredMethod("sum");
statsCollectorToString = StatsCollector.class.getDeclaredMethod("toString", Function.class);
turnOnMethod = SwitchableStats.class.getDeclaredMethod("turnOn");
turnOffMethod = SwitchableStats.class.getDeclaredMethod("turnOff");
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void setOutputLevel(OutputLevel level) {
this.outputLevel = level;
for (Field field : AnalysisStats.class.getDeclaredFields()) {
if (!SwitchableStats.class.isAssignableFrom(field.getType())) {
continue;
}
@Nullable PrintInStatus annotation = field.getAnnotation(PrintInStatus.class);
if (annotation == null) {
continue;
}
try {
if (annotation.outputLevel().compareTo(outputLevel) <= 0) {
turnOnMethod.invoke(field.get(this));
} else {
turnOffMethod.invoke(field.get(this));
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
public void traceField(String fieldName, String prefix) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Object o = this.getClass().getDeclaredField(fieldName).get(this);
if (o instanceof Traceable) {
((Traceable) o).setPrefix(prefix);
} else {
throw new IllegalArgumentException("Field " + fieldName +
" not currently traceable");
}
}
@Override
public void actualize() {
for (Field field: AnalysisStats.class.getDeclaredFields()) {
if (!Actualizable.class.isAssignableFrom(field.getType())) {
continue;
}
try {
if (field.get(this) != null) {
((Actualizable) field.get(this)).actualize();
}
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
};
}
}
public void addLocationPredicate(String filterName, @NonNull SerializablePredicate<SequenceLocation> filter) {
FieldIteration.iterateFields((f, value) -> {
if (f.getAnnotation(AddLocationPredicates.class) != null) {
((MultiCounter<?>) value).addPredicate(filterName, filter);
}
}, this);
}
private static<T> MultiCounter<T> getCounterSecLocOnly(
boolean reportCoverageAtAllPositions,
@NonNull MutinackGroup groupSettings,
boolean sortByValue) {
return reportCoverageAtAllPositions ?
new MultiCounter<>(null, () -> new CounterWithSeqLocOnlyReportAll(sortByValue, groupSettings))
:
new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(sortByValue, groupSettings));
}
private static<T> MultiCounter<T> getCounterTypeSecLoc(
boolean reportCoverageAtAllPositions,
@NonNull MutinackGroup groupSettings, boolean sortByValue) {
return reportCoverageAtAllPositions ?
new MultiCounter<>(() -> new CounterWithSeqLocationReportAll<>(sortByValue, groupSettings), null, true)
:
new MultiCounter<>(() -> new CounterWithSeqLocation<>(sortByValue, groupSettings), null, true);
}
}
| src/uk/org/cinquin/mutinack/AnalysisStats.java | /**
* Mutinack mutation detection program.
* Copyright (C) 2014-2016 Olivier Cinquin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.org.cinquin.mutinack;
import static uk.org.cinquin.mutinack.misc_util.Util.blueF;
import static uk.org.cinquin.mutinack.misc_util.Util.greenB;
import static uk.org.cinquin.mutinack.misc_util.Util.reset;
import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.TERSE;
import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.VERBOSE;
import static uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel.VERY_VERBOSE;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.DoubleAdder;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.Join;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import uk.org.cinquin.final_annotation.Final;
import uk.org.cinquin.mutinack.features.PosByPosNumbersPB.GenomeNumbers.Builder;
import uk.org.cinquin.mutinack.misc_util.Assert;
import uk.org.cinquin.mutinack.misc_util.ComparablePair;
import uk.org.cinquin.mutinack.misc_util.FieldIteration;
import uk.org.cinquin.mutinack.misc_util.SerializablePredicate;
import uk.org.cinquin.mutinack.misc_util.Util;
import uk.org.cinquin.mutinack.misc_util.collections.MutationHistogramMap;
import uk.org.cinquin.mutinack.output.LocationAnalysis;
import uk.org.cinquin.mutinack.qualities.Quality;
import uk.org.cinquin.mutinack.statistics.Actualizable;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocOnly;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocOnlyReportAll;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocation;
import uk.org.cinquin.mutinack.statistics.CounterWithSeqLocationReportAll;
import uk.org.cinquin.mutinack.statistics.DivideByTwo;
import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter;
import uk.org.cinquin.mutinack.statistics.Histogram;
import uk.org.cinquin.mutinack.statistics.LongAdderFormatter;
import uk.org.cinquin.mutinack.statistics.MultiCounter;
import uk.org.cinquin.mutinack.statistics.PrintInStatus;
import uk.org.cinquin.mutinack.statistics.PrintInStatus.OutputLevel;
import uk.org.cinquin.mutinack.statistics.StatsCollector;
import uk.org.cinquin.mutinack.statistics.SwitchableStats;
import uk.org.cinquin.mutinack.statistics.Traceable;
@PersistenceCapable
public class AnalysisStats implements Serializable, Actualizable {
public @Final @Persistent @NonNull String name;
public OutputLevel outputLevel;
public final MutinackGroup groupSettings;
public @Final @Persistent Set<String> mutinackVersions = new HashSet<>();
public @Final @Persistent Map<@NonNull String, @NonNull String> inputBAMHashes = new HashMap<>();
public @Final @Persistent @NonNull Parameters analysisParameters;
public @Final @Persistent boolean forInsertions;
//Changed to Map instead of ConcurrentMap to please datanucleus
public @Final @Persistent @Join Map<SequenceLocation, LocationAnalysis> detections = new ConcurrentHashMap<>();
public transient PrintStream detectionOutputStream;
public transient OutputStreamWriter annotationOutputStream;
public transient @Nullable OutputStreamWriter topBottomDisagreementWriter, noWtDisagreementWriter,
mutationBEDWriter, coverageBEDWriter;
public boolean canSkipDuplexLoading = false;
public AnalysisStats(@NonNull String name,
@NonNull Parameters param,
boolean forInsertions,
@NonNull MutinackGroup groupSettings,
boolean reportCoverageAtAllPositions) {
this.name = name;
this.analysisParameters = param;
this.forInsertions = forInsertions;
this.groupSettings = groupSettings;
nPosDuplexCandidatesForDisagreementQ2 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexCandidatesForDisagreementQ1 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexQualityQ2OthersQ1Q2 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexTooFewReadsPerStrand1 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexTooFewReadsPerStrand2 = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nPosDuplexTooFewReadsAboveQ2Phred = getCounterSecLocOnly(reportCoverageAtAllPositions, groupSettings, false);
nRecordsNotInIntersection1 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nRecordsNotInIntersection2 = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nTooLowMapQIntersect = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplex = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplexBothStrandsPresent = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosIgnoredBecauseTooHighCoverage = new StatsCollector();
nReadMedianPhredBelowThreshold = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
phredAndLigSiteDistance = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, false);
nDuplexesTooMuchClipping = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nDuplexesNoStats = new DoubleAdder();
nPosDuplexWithTopBottomDuplexDisagreementNoWT = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplexWithTopBottomDuplexDisagreementNotASub = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nDuplexesWithStats = new DoubleAdder();
vBarcodeMismatches1M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
vBarcodeMismatches2M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
vBarcodeMismatches3OrMore = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
rawDeletionLengthQ1 = new Histogram(200);
rawInsertionLengthQ1 = new Histogram(200);
rawDeletionLengthQ2 = new Histogram(200);
rawMismatchesQ1 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawDeletionsQ1 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawInsertionsQ1 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawMismatchesQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawDeletionsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawInsertionsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
intraStrandSubstitutions = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
intraStrandDeletions = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
intraStrandInsertions = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomSubstDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, false);
topBottomDelDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomRearDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomIntronDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
topBottomInsDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
rawInsertionLengthQ2 = new Histogram(200);
alleleFrequencies = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
codingStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
templateStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
codingStrandDelQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
templateStrandDelQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
codingStrandInsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
templateStrandInsQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(groupSettings), null);
topBottomDisagreementsQ2TooHighCoverage = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null);
nPosDuplexCandidatesForDisagreementQ2TooHighCoverage = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosDuplexWithLackOfStrandConsensus1 = new StatsCollector();
nPosDuplexWithLackOfStrandConsensus2 = new StatsCollector();
nPosDuplexCompletePairOverlap = new StatsCollector();
nPosUncovered = new StatsCollector();
nQ2PromotionsBasedOnFractionReads = new StatsCollector();
nPosQualityPoor = new StatsCollector();
nPosQualityPoorA = new StatsCollector();
nPosQualityPoorT = new StatsCollector();
nPosQualityPoorG = new StatsCollector();
nPosQualityPoorC = new StatsCollector();
nConsensusQ1NotMet = new StatsCollector();
nMedianPhredAtPositionTooLow = new StatsCollector();
nFractionWrongPairsAtPositionTooHigh = new StatsCollector();
nPosQualityQ1 = new StatsCollector();
nPosQualityQ2 = new StatsCollector();
nPosQualityQ2OthersQ1Q2 = new StatsCollector();
nPosDuplexQualityQ2OthersQ1Q2CodingOrTemplate = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nPosCandidatesForUniqueMutation = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
nReadsInPrefetchQueue = new Histogram(1_000);
{ //Force output of fields annotated with AddChromosomeBins to be broken down by
//bins for each contig (bin size as defined by CounterWithSeqLocation.BIN_SIZE, for now)
List<String> contigNamesToProcess = groupSettings.getContigNamesToProcess();
for (Field field : AnalysisStats.class.getDeclaredFields()) {
@Nullable AddChromosomeBins annotation = field.getAnnotation(AddChromosomeBins.class);
if (annotation != null) {
for (final @NonNull String contigName: contigNamesToProcess) {
final int contigIndex = Objects.requireNonNull(
groupSettings.getIndexContigNameReverseMap().get(contigName), () -> "Missing contig index for " + contigName);
for (int c = 0; c < Objects.requireNonNull(groupSettings.getContigSizes().get(contigName),
() -> "Missing contig size for contig " + contigName)
/ groupSettings.BIN_SIZE; c++) {
final int finalBinIndex = c;
try {
MultiCounter <?> counter = ((MultiCounter<?>) field.get(this));
counter.addPredicate(contigName + "_bin_" + String.format("%03d", c),
loc -> {
final int min = groupSettings.BIN_SIZE * finalBinIndex;
final int max = groupSettings.BIN_SIZE * (finalBinIndex + 1);
return loc.contigIndex == contigIndex &&
loc.position >= min &&
loc.position < max;
});
counter.accept(new SequenceLocation(analysisParameters.referenceGenomeShortName, contigName,
groupSettings.getIndexContigNameReverseMap(), c * groupSettings.BIN_SIZE), 0);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
//Force initialization of counters for all possible substitutions:
//it is easier to put the output of multiple samples together if
//unencountered substitutions have a 0-count entry
for (byte mut: Arrays.asList((byte) 'A', (byte) 'T', (byte) 'G', (byte) 'C')) {
for (byte wt: Arrays.asList((byte) 'A', (byte) 'T', (byte) 'G', (byte) 'C')) {
if (wt == mut) {
continue;
}
Mutation wtM = new Mutation(MutationType.WILDTYPE, wt, null, Util.emptyOptional());
Mutation to = new Mutation(MutationType.SUBSTITUTION, wt, new byte [] {mut}, Util.emptyOptional());
ComparablePair<Mutation, Mutation> cpMut = new ComparablePair<>(wtM, to);
DuplexDisagreement disag = new DuplexDisagreement(wtM, to, true, Quality.GOOD);
List<String> contigNames = groupSettings.getContigNames();
for (int contig = 0; contig < contigNames.size(); contig++) {
for (int c = 0; c < Objects.requireNonNull(groupSettings.getContigSizes().get(
contigNames.get(contig))) / groupSettings.BIN_SIZE; c++) {
SequenceLocation location = new SequenceLocation(analysisParameters.referenceGenomeShortName, contig,
Objects.requireNonNull(contigNames.get(contig)), c * groupSettings.BIN_SIZE);
topBottomSubstDisagreementsQ2.accept(location, disag, 0);
codingStrandSubstQ2.accept(location, cpMut, 0);
templateStrandSubstQ2.accept(location, cpMut, 0);
}
}
}
}
//Assert that annotations have not been discarded
//This does not need to be done on every instance, but exceptions are better
//handled in a non-static context
try {
Assert.isNonNull(AnalysisStats.class.getDeclaredField("duplexGroupingDepth").
getAnnotation(PrintInStatus.class));
} catch (NoSuchFieldException | SecurityException e) {
throw new RuntimeException(e);
}
}
public @NonNull String getName() {
return name;
}
private static final long serialVersionUID = -7786797851357308577L;
public double processingThroughput(long timeStartProcessing) {
return (nRecordsProcessed.sum()) /
((System.nanoTime() - timeStartProcessing) / 1_000_000_000d);
//TODO Store start and stop times in AnalysisStats
}
@Retention(RetentionPolicy.RUNTIME)
private @interface AddChromosomeBins {};
@Retention(RetentionPolicy.RUNTIME)
private @interface AddLocationPredicates {};
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized="true")
@Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexGroupingDepth = new Histogram(100);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram minTopCandFreqQ2PosTopAlleleFreqOK = new Histogram(11);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram minTopCandFreqQ2PosTopAlleleFreqKO = new Histogram(11);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexTotalRecords = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rejectedIndelDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rejectedSubstDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtRejectedDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtAcceptedBaseDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram singleAnalyzerQ2CandidateDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram crossAnalyzerQ2CandidateDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
ConcurrentMap<Mutation, Histogram> disagMutConsensus = new MutationHistogramMap();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
ConcurrentMap<Mutation, Histogram> disagWtConsensus = new MutationHistogramMap();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram substDisagDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram insDisagDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram delDisagDistanceToLigationSite = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram disagDelSize = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram Q2CandidateDistanceToLigationSiteN = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtQ2CandidateQ1Q2Coverage = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtQ2CandidateQ1Q2CoverageRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram wtQ2CandidateQ1Q2CoverageNonRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mutantQ2CandidateQ1Q2Coverage = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mutantQ2CandidateQ1Q2DCoverageRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mutantQ2CandidateQ1Q2DCoverageNonRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram uniqueMutantQ2CandidateQ1Q2DCoverage = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram uniqueMutantQ2CandidateQ1Q2DCoverageRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram uniqueMutantQ2CandidateQ1Q2DCoverageNonRepetitive = new Histogram(200);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosExcluded = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nRecordsProcessed = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector ignoredUnpairedReads = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nRecordsInFile = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nRecordsUnmapped = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nRecordsBelowMappingQualityThreshold = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mappingQualityKeptRecords = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram mappingQualityAllRecords = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram averageReadPhredQuality0 = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram averageReadPhredQuality1 = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
MultiCounter<ComparablePair<Integer, Integer>> phredAndLigSiteDistance;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram medianReadPhredQuality = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram medianPositionPhredQuality = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram averageDuplexReferenceDisagreementRate = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexinsertSize = new Histogram(1000);
@PrintInStatus(outputLevel = VERBOSE)
public @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
double[] approximateReadInsertSize = null;
@PrintInStatus(outputLevel = VERBOSE)
public @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
double[] approximateReadInsertSizeRaw = null;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexAverageNClipped = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexInsert130_180averageNClipped = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexInsert100_130AverageNClipped = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram disagreementOrientationProportions1 = new Histogram(10);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram disagreementOrientationProportions2 = new Histogram(10);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector disagreementMatesSameOrientation = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nComplexDisagreementsQ2 = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nRecordsIgnoredBecauseSecondary = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nRecordsNotInIntersection1;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nRecordsNotInIntersection2;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nTooLowMapQIntersect;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplex;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexBothStrandsPresent;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nReadMedianPhredBelowThreshold;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nDuplexesTooMuchClipping;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent DoubleAdder nDuplexesNoStats;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent DoubleAdder nDuplexesWithStats;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsPerStrand1;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsPerStrand2;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsAboveQ2Phred;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nPosIgnoredBecauseTooHighCoverage;
@PrintInStatus(outputLevel = VERY_VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexWithTopBottomDuplexDisagreementNoWT;
@AddLocationPredicates
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexWithTopBottomDuplexDisagreementNotASub;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawMismatchesQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches1M;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches2M;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> vBarcodeMismatches3OrMore;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawDeletionsQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawDeletionLengthQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawInsertionsQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawInsertionLengthQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawMismatchesQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") LongAdderFormatter rawMismatchesNReads = new LongAdderFormatter();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawDeletionsQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawDeletionLengthQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> rawInsertionsQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram rawInsertionLengthQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
LongAdderFormatter intraStrandAndRawMismatchNPositions = new LongAdderFormatter();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
LongAdderFormatter intraStrandNReads = new LongAdderFormatter();
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> intraStrandSubstitutions;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> intraStrandDeletions;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<String, String>> intraStrandInsertions;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomSubstDisagreementsQ2;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomDelDisagreementsQ2;
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomRearDisagreementsQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomIntronDisagreementsQ2;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
public @Final @Persistent(serialized = "true") MultiCounter<List<Integer>> alleleFrequencies;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomInsDisagreementsQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandSubstQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandSubstQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandDelQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandDelQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> codingStrandInsQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<ComparablePair<Mutation, Mutation>> templateStrandInsQ2;
@PrintInStatus(outputLevel = VERY_VERBOSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<DuplexDisagreement> topBottomDisagreementsQ2TooHighCoverage;
@PrintInStatus(outputLevel = TERSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ2;
@PrintInStatus(outputLevel = VERBOSE)
@AddChromosomeBins
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ1;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexCandidatesForDisagreementQ2TooHighCoverage;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosDuplexWithLackOfStrandConsensus1;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosDuplexWithLackOfStrandConsensus2;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosDuplexCompletePairOverlap;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosUncovered;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nQ2PromotionsBasedOnFractionReads;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoor;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorA;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorT;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorG;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nPosQualityPoorC;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nConsensusQ1NotMet;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nMedianPhredAtPositionTooLow;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nFractionWrongPairsAtPositionTooHigh;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityQ1;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityQ2;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent StatsCollector nPosQualityQ2OthersQ1Q2;
@PrintInStatus(outputLevel = TERSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexQualityQ2OthersQ1Q2;
@PrintInStatus(outputLevel = TERSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexQualityQ2OthersQ1Q2CodingOrTemplate;
@PrintInStatus(color = "greenBackground", outputLevel = TERSE)
@AddLocationPredicates
public @Final @Persistent(serialized = "true") MultiCounter<?> nPosCandidatesForUniqueMutation;
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nReadsAtPosQualityQ2OthersQ1Q2 = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nReadsAtPosWithSomeCandidateForQ2UniqueMutation = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexDistance = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram concurringMutationDuplexDistance = new Histogram(2_000);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram concurringDuplexDistance = new Histogram(2_000);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexLocalGroupSize = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexLocalShiftedGroupSize = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nQ1Q2AtPosQualityQ2OthersQ1Q2 = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nQ1Q2AtPosWithSomeCandidateForQ2UniqueMutation = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE, description = "Q1 or Q2 duplex coverage histogram")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram Q1Q2DuplexCoverage = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE, description = "Q2 duplex coverage histogram")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram Q2DuplexCoverage = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Missing strands for positions that have no usable duplex")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram missingStrandsWhenNoUsableDuplex = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Top/bottom coverage imbalance for positions that have no usable duplex")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram strandCoverageImbalanceWhenNoUsableDuplex = new Histogram(500);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of copy number for duplex bottom strands")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram copyNumberOfDuplexBottomStrands = new Histogram(500) {
private static final long serialVersionUID = 6597978073262739721L;
private final NumberFormat formatter = new DecimalFormat("0.###E0");
@Override
public String toString() {
final double nPosDuplexf = nPosDuplex.sum();
return stream().map(a -> formatter.format((float) (a.sum() / nPosDuplexf))).
collect(Collectors.toList()).toString();
}
};
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of copy number for duplex top strands")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram copyNumberOfDuplexTopStrands = new Histogram(500) {
private static final long serialVersionUID = -8213283701959613589L;
private final NumberFormat formatter = new DecimalFormat("0.###E0");
@Override
public String toString() {
final double nPosDuplexf = nPosDuplex.sum();
return stream().map(a -> formatter.format((float) (a.sum() / nPosDuplexf))).
collect(Collectors.toList()).toString();
}
};
@PrintInStatus(outputLevel = VERBOSE, description = "Number of duplexes that have both strands represented " +
"(and therefore two or more read pairs)")
public @Final @Persistent StatsCollector nDuplexesTwoOrMoreReadPairsAndBothStrands = new StatsCollector();
@PrintInStatus(outputLevel = VERBOSE, description = "Number of duplexes that have two or more read pairs " +
"(for comparison with nDuplexesTwoOrMoreReadPairsAndBothStrands)")
public @Final @Persistent StatsCollector nDuplexesTwoOrMoreReadPairs = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbability = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability at Q2 sites")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityAtQ2 = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability when both strands represented")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityWhen2Strands = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Duplex collision probability at disagreement")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityAtDisag = new Histogram(100);
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Average duplex collision probability for duplexes covering genome position of disagreement")
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram duplexCollisionProbabilityLocalAvAtDisag = new Histogram(100);
/*
@PrintInStatus(outputLevel = VERY_VERBOSE, description = "Histogram of variable barcode mapping distance mismatch")
public final Histogram sameBarcodeButPositionMismatch = new Histogram(500);
@PrintInStatus(outputLevel = VERBOSE, description = "Candidates with top good coverage")
public final PriorityBlockingQueue<CandidateSequence> topQ2DuplexCoverage = new PriorityBlockingQueue<CandidateSequence>
(100, (c1, c2) -> Integer.compare(c1.getnGoodDuplexes(),c2.getnGoodDuplexes())) {
private static final long serialVersionUID = 8206630026701622788L;
@Override
public String toString() {
return stream().collect(Collectors.toList()).toString();
}
};*/
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nBasesBelowPhredScore = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nConstantBarcodeMissing = new StatsCollector(),
nConstantBarcodeDodgy = new StatsCollector(),
nConstantBarcodeDodgyNStrand = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nReadsConstantBarcodeOK = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsConsidered = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToA = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToT = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToG = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsToC = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nNs = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nCandidateInsertions = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nCandidateDeletions = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsAfterLastNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateWildtypeAfterLastNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateSubstitutionsBeforeFirstNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateIndelAfterLastNBases = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nCandidateIndelBeforeFirstNBases = new StatsCollector();
/*
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeCandidateExaminations = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeLeftEqual = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeRightEqual = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeMateDoesNotMatch = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeMateMatches = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodeMatchAfterPositionCheck = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nVariableBarcodesCloseMisses = new StatsCollector();*/
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nReadsOpticalDuplicates = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram readDistance = new Histogram(50);
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nReadsInsertNoSize = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsPairRF = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsPairTandem = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsInsertSizeAboveMaximum = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
@DivideByTwo public @Final @Persistent StatsCollector nReadsInsertSizeBelowMinimum = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent StatsCollector nMateOutOfReach = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
public @Final @Persistent StatsCollector nProcessedBases = new StatsCollector();
@PrintInStatus(outputLevel = TERSE)
boolean analysisTruncated;
@PrintInStatus(outputLevel = VERBOSE)
public @Final @Persistent(serialized = "true") @Extension(vendorName = "datanucleus", key = "is-second-class", value="false")
Histogram nReadsInPrefetchQueue;
/*
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nProcessedFirst6BasesFirstOfPair = new StatsCollector();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final StatsCollector nProcessedFirst6BasesSecondOfPair = new StatsCollector();*/
@PrintInStatus(outputLevel = VERY_VERBOSE)
public @Final @Persistent DoubleAdder phredSumProcessedbases = new DoubleAdder();
/*
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final DoubleAdder phredSumFirst6basesFirstOfPair = new DoubleAdder();
@PrintInStatus(outputLevel = VERY_VERBOSE)
public final DoubleAdder phredSumFirst6basesSecondOfPair = new DoubleAdder();*/
public @Persistent Map<String, int[]> positionByPositionCoverage;
transient Builder positionByPositionCoverageProtobuilder;
public final StatsCollector nChimericReadsMateWrongContig = new StatsCollector();
public final Histogram inferredRearrangementInsertSizeHistogram = new Histogram(5_000);
public final StatsCollector nChimericReadsMateOK = new StatsCollector();
public final StatsCollector nChimericReadsTooBigInsert = new StatsCollector();
public final StatsCollector nChimericReadsUnmappedMate = new StatsCollector();
public final StatsCollector nNotSingleSupplementary = new StatsCollector();
public final Histogram inferredRearrangementDistanceLogt100Histogram = new Histogram(5_000);
public final StatsCollector nChimericReadsMateWrongSide = new StatsCollector();
@SuppressWarnings("null")
public void print(PrintStream stream, boolean colorize) {
stream.println();
NumberFormat formatter = DoubleAdderFormatter.nf.get();
ConcurrentModificationException cme = null;
for (Field field: AnalysisStats.class.getDeclaredFields()) {
PrintInStatus annotation = field.getAnnotation(PrintInStatus.class);
if ((annotation != null && annotation.outputLevel().compareTo(outputLevel) <= 0) ||
(annotation == null &&
(field.getType().equals(LongAdderFormatter.class) ||
field.getType().equals(StatsCollector.class) ||
field.getType().equals(Histogram.class)))) {
try {
final Object fieldValue = field.get(this);
if (fieldValue == null) {
continue;
}
if (annotation != null && annotation.color().equals("greenBackground")) {
stream.print(greenB(colorize));
}
long divisor;
if (field.getAnnotation(DivideByTwo.class) != null)
divisor = 2;
else
divisor = 1;
boolean hasDescription = annotation != null && !annotation.description().isEmpty();
stream.print(blueF(colorize) + (hasDescription ? annotation.description() : field.getName()) +
": " + reset(colorize));
if (field.getType().equals(LongAdderFormatter.class)) {
stream.println(formatter.format(((Long) longAdderFormatterSum.
invoke(fieldValue)) / divisor));
} else if (field.getType().equals(StatsCollector.class)) {
Function<Long, Long> transformer = l-> l / divisor;
stream.println((String) statsCollectorToString.invoke(fieldValue, transformer));
} else {
stream.println(fieldValue.toString());
}
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
} catch (ConcurrentModificationException e) {
cme = e;
} finally {
if (annotation != null && annotation.color().equals("greenBackground")) {
stream.print(reset(colorize));
}
}
}
}
if (cme != null) {
throw cme;
}
}
private static final Method longAdderFormatterSum, statsCollectorToString, turnOnMethod, turnOffMethod;
static {
try {
longAdderFormatterSum = LongAdder.class.getDeclaredMethod("sum");
statsCollectorToString = StatsCollector.class.getDeclaredMethod("toString", Function.class);
turnOnMethod = SwitchableStats.class.getDeclaredMethod("turnOn");
turnOffMethod = SwitchableStats.class.getDeclaredMethod("turnOff");
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void setOutputLevel(OutputLevel level) {
this.outputLevel = level;
for (Field field : AnalysisStats.class.getDeclaredFields()) {
if (!SwitchableStats.class.isAssignableFrom(field.getType())) {
continue;
}
@Nullable PrintInStatus annotation = field.getAnnotation(PrintInStatus.class);
if (annotation == null) {
continue;
}
try {
if (annotation.outputLevel().compareTo(outputLevel) <= 0) {
turnOnMethod.invoke(field.get(this));
} else {
turnOffMethod.invoke(field.get(this));
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
public void traceField(String fieldName, String prefix) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Object o = this.getClass().getDeclaredField(fieldName).get(this);
if (o instanceof Traceable) {
((Traceable) o).setPrefix(prefix);
} else {
throw new IllegalArgumentException("Field " + fieldName +
" not currently traceable");
}
}
@Override
public void actualize() {
for (Field field: AnalysisStats.class.getDeclaredFields()) {
if (!Actualizable.class.isAssignableFrom(field.getType())) {
continue;
}
try {
if (field.get(this) != null) {
((Actualizable) field.get(this)).actualize();
}
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
};
}
}
public void addLocationPredicate(String filterName, @NonNull SerializablePredicate<SequenceLocation> filter) {
FieldIteration.iterateFields((f, value) -> {
if (f.getAnnotation(AddLocationPredicates.class) != null) {
((MultiCounter<?>) value).addPredicate(filterName, filter);
}
}, this);
}
private static<T> MultiCounter<T> getCounterSecLocOnly(
boolean reportCoverageAtAllPositions,
@NonNull MutinackGroup groupSettings,
boolean sortByValue) {
return reportCoverageAtAllPositions ?
new MultiCounter<>(null, () -> new CounterWithSeqLocOnlyReportAll(sortByValue, groupSettings))
:
new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(sortByValue, groupSettings));
}
private static<T> MultiCounter<T> getCounterTypeSecLoc(
boolean reportCoverageAtAllPositions,
@NonNull MutinackGroup groupSettings, boolean sortByValue) {
return reportCoverageAtAllPositions ?
new MultiCounter<>(() -> new CounterWithSeqLocationReportAll<>(sortByValue, groupSettings), null, true)
:
new MultiCounter<>(() -> new CounterWithSeqLocation<>(sortByValue, groupSettings), null, true);
}
}
| Use more appropriate type for counting.
| src/uk/org/cinquin/mutinack/AnalysisStats.java | Use more appropriate type for counting. | <ide><path>rc/uk/org/cinquin/mutinack/AnalysisStats.java
<ide> import java.util.Set;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.ConcurrentMap;
<del>import java.util.concurrent.atomic.DoubleAdder;
<ide> import java.util.concurrent.atomic.LongAdder;
<ide> import java.util.function.Function;
<ide> import java.util.stream.Collectors;
<ide> nReadMedianPhredBelowThreshold = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
<ide> phredAndLigSiteDistance = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, false);
<ide> nDuplexesTooMuchClipping = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
<del> nDuplexesNoStats = new DoubleAdder();
<add> nDuplexesNoStats = new LongAdder();
<add> nDuplexesWithStats = new LongAdder();
<ide> nPosDuplexWithTopBottomDuplexDisagreementNoWT = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
<ide> nPosDuplexWithTopBottomDuplexDisagreementNotASub = new MultiCounter<>(null, () -> new CounterWithSeqLocOnly(false, groupSettings));
<del> nDuplexesWithStats = new DoubleAdder();
<ide> vBarcodeMismatches1M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
<ide> vBarcodeMismatches2M = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
<ide> vBarcodeMismatches3OrMore = new MultiCounter<>(() -> new CounterWithSeqLocation<>(true, groupSettings), null, true);
<ide> topBottomRearDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
<ide> topBottomIntronDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
<ide> topBottomInsDisagreementsQ2 = getCounterTypeSecLoc(reportCoverageAtAllPositions, groupSettings, true);
<add>
<ide> rawInsertionLengthQ2 = new Histogram(200);
<del>
<ide> alleleFrequencies = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
<ide> codingStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
<ide> templateStrandSubstQ2 = new MultiCounter<>(() -> new CounterWithSeqLocation<>(false, groupSettings), null);
<ide> public @Final @Persistent(serialized = "true") MultiCounter<?> nDuplexesTooMuchClipping;
<ide>
<ide> @PrintInStatus(outputLevel = VERY_VERBOSE)
<del> public @Final @Persistent DoubleAdder nDuplexesNoStats;
<del>
<del> @PrintInStatus(outputLevel = VERY_VERBOSE)
<del> public @Final @Persistent DoubleAdder nDuplexesWithStats;
<add> public @Final @Persistent LongAdder nDuplexesNoStats;
<add>
<add> @PrintInStatus(outputLevel = VERY_VERBOSE)
<add> public @Final @Persistent LongAdder nDuplexesWithStats;
<ide>
<ide> @PrintInStatus(outputLevel = TERSE)
<ide> public @Final @Persistent(serialized = "true") MultiCounter<?> nPosDuplexTooFewReadsPerStrand1;
<ide> public final StatsCollector nProcessedFirst6BasesSecondOfPair = new StatsCollector();*/
<ide>
<ide> @PrintInStatus(outputLevel = VERY_VERBOSE)
<del> public @Final @Persistent DoubleAdder phredSumProcessedbases = new DoubleAdder();
<add> public @Final @Persistent LongAdder phredSumProcessedbases = new LongAdder();
<ide>
<ide> /*
<ide> @PrintInStatus(outputLevel = VERY_VERBOSE) |
|
Java | unlicense | ebbe29e6dbd8a2abf682aa8cb8b202af43fe98bd | 0 | EgonOlsen71/basicv2,EgonOlsen71/basicv2 | package com.sixtyfour.cbmnative.mos6502;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.sixtyfour.Basic;
import com.sixtyfour.Loader;
import com.sixtyfour.Logger;
import com.sixtyfour.cbmnative.Generator;
import com.sixtyfour.cbmnative.GeneratorContext;
import com.sixtyfour.cbmnative.PlatformProvider;
import com.sixtyfour.cbmnative.Transformer;
import com.sixtyfour.cbmnative.mos6502.generators.GeneratorList;
import com.sixtyfour.cbmnative.mos6502.util.Converter;
import com.sixtyfour.cbmnative.mos6502.x16.TransformerX16;
import com.sixtyfour.config.CompilerConfig;
import com.sixtyfour.config.MemoryConfig;
import com.sixtyfour.elements.Type;
import com.sixtyfour.elements.Variable;
import com.sixtyfour.extensions.BasicExtension;
import com.sixtyfour.system.DataStore;
import com.sixtyfour.system.Machine;
import com.sixtyfour.util.ConstantExtractor;
import com.sixtyfour.util.VarUtils;
/**
* Transformer base class for Commodore based target platforms.
*
* @author EgonOlsen
*
*/
public abstract class AbstractTransformer implements Transformer {
protected int variableStart = -1;
protected int runtimeStart = -1;
protected int stringMemoryEnd = 0;
protected int startAddress = 0;
protected boolean preferZeropage = true;
public static void addExtensionSubroutines(List<String> addTo, String postFix) {
List<BasicExtension> exts = Basic.getExtensions();
if (exts != null) {
for (BasicExtension ext : exts) {
try {
for (String inc : ext.getAdditionalIncludes()) {
List<String> adds = Arrays.asList(Loader.loadProgram(
AbstractTransformer.class.getResourceAsStream("/ext/" + inc + "." + postFix)));
addTo.addAll(adds);
}
} catch (Exception e) {
// ignore
}
}
}
}
public void addExtensionConstants(List<String> res) {
Map<String, Integer> map = ConstantExtractor.getAllConstantMaps();
for (Entry<String, Integer> entry : map.entrySet()) {
res.add(entry.getKey() + "=" + entry.getValue());
}
}
protected void addLabels(List<String> res, String[] labels) {
for (String label : labels) {
int pos = label.indexOf(";");
if (pos != -1) {
label = label.substring(0, pos);
}
label = label.trim();
res.add(label);
}
}
protected void addBasicBuffer(List<String> res, PlatformProvider platform, MemoryConfig memConfig) {
if (memConfig.getBasicBufferStart() == -1) {
res.add("BASICBUFFER=" + platform.getBasicBufferAddress());
} else {
if (memConfig.getBasicBufferStart() != 0) {
res.add("BASICBUFFER=" + memConfig.getBasicBufferStart());
}
}
}
protected void addInternalBasicBuffer(List<String> res, PlatformProvider platform, MemoryConfig memConfig) {
if (memConfig.getBasicBufferStart() == 0) {
res.add("BASICBUFFER .ARRAY 256");
}
}
protected void addMemoryLocations(List<String> res) {
String[] labels = Loader.loadProgram(TransformerX16.class.getResourceAsStream("/rommap/memloc-c64.map"));
addLabels(res, labels);
}
protected List<String> createDatas(CompilerConfig config, Machine machine) {
DataStore datas = machine.getDataStore();
List<String> ret = new ArrayList<String>();
ret.add(";###############################");
ret.add("; ******** DATA ********");
ret.add("DATAS");
int cnt = 0;
datas.restore();
Object obj = null;
while ((obj = datas.read()) != null) {
Type type = Type.STRING;
if (VarUtils.isInteger(obj)) {
Integer num = (Integer) obj;
if (num < -32768 || num > 32767) {
obj = num.floatValue();
type = Type.REAL;
} else {
type = Type.INTEGER;
}
} else if (VarUtils.isFloat(obj) || VarUtils.isDouble(obj)) {
type = Type.REAL;
}
if (obj.toString().equals("\\0")) {
obj = "";
}
if (type == Type.INTEGER) {
int val = ((Number) obj).intValue();
if (val < 0 || val > 255) {
ret.add(".BYTE 0");
ret.add(".WORD " + obj.toString());
cnt += 3;
} else {
if (val > 3 && val < 255) {
// If larger than the largest type (3) and smaller than the end flag (255),
/// the we can use the type's location as data and skip storing the typ itself.
ret.add(".BYTE " + obj.toString());
cnt += 1;
} else {
ret.add(".BYTE 3");
ret.add(".BYTE " + obj.toString());
cnt += 2;
}
}
} else if (type == Type.REAL) {
ret.add(".BYTE 1");
ret.add(".REAL " + obj.toString());
cnt += 6;
} else {
ret.add(".BYTE 2");
ret.add(".BYTE " + obj.toString().length());
String ds = obj.toString();
if (config.isConvertStringToLower() || config.isFlipCasing()) {
ds = Converter.convertCase(ds, !config.isFlipCasing());
}
ret.add(".STRG \"" + ds + "\"");
cnt += 2 + obj.toString().length();
}
}
ret.add(".BYTE $FF");
ret.add("; ******** DATA END ********");
Logger.log("DATA lines converted, " + cnt + " bytes used!");
return ret;
}
protected List<String> createInitScript(List<String> vars) {
List<String> inits = new ArrayList<String>();
inits.add("; ******* INITVARS ********");
inits.add(";###############################");
inits.add("INITVARS");
inits.add("JSR INITSTRVARS");
inits.add("LDA #0");
for (String var : vars) {
var = var.trim().replace("\t", " ");
if (var.startsWith("VAR_")) {
String[] parts = var.split(" ");
boolean isArray = var.contains("[]");
if (!parts[0].contains("$")) {
if (parts[1].equals(".REAL")) {
// INT and REAL arrays are both marked "ARRAY", so this
// branch can only happen if it a single REAL.
inits.add("STA " + parts[0]);
inits.add("STA " + parts[0] + "+1");
// inits.add("STA " + parts[0] + "+2");
// inits.add("STA " + parts[0] + "+3");
// inits.add("STA " + parts[0] + "+4");
} else {
// INT or ARRAY
if (isArray) {
if (inits.get(inits.size() - 1).equals("LDA #0")) {
// The LDA #0 is obsolete in this case.
inits.remove(inits.size() - 1);
}
inits.add("LDA #<" + parts[0]);
inits.add("LDY #>" + parts[0]);
inits.add("JSR INITSPARAMS"); // This should save A and Y
// inits.add("LDA #<" + parts[0]);
// inits.add("LDY #>" + parts[0]);
inits.add("JSR INITNARRAY");
inits.add("LDA #0");
} else {
inits.add("STA " + parts[0]);
inits.add("STA " + parts[0] + "+1");
}
}
}
}
}
inits.add("RTS");
inits.add(";###############################");
return inits;
}
protected String convertConstantsToReal(String line, PlatformProvider platform) {
if (platform.useLooseTypes()) {
if (line.contains("#") && line.endsWith("{INTEGER}")) {
int val = getConstantValue(line);
if (val < 0 || val > 255) {
line = line.replace("{INTEGER}", "{REAL}");
}
}
}
return line;
}
protected int getConstantValue(String line) {
String sval = line.substring(line.indexOf("#") + 1, line.indexOf("{INTEGER}"));
int val = Integer.parseInt(sval);
return val;
}
protected int extractData(CompilerConfig config, PlatformProvider platform, Machine machine, List<String> consts,
List<String> vars, List<String> strVars, List<String> strArrayVars, Map<String, String> name2label, int cnt,
String line) {
String[] parts = line.split(",", 2);
List<String> tmp = new ArrayList<String>();
for (int p = 0; p < parts.length; p++) {
String part = parts[p];
if (part.contains("{") && part.endsWith("}")) {
int pos = part.lastIndexOf("{");
String name = part.substring(0, pos);
if (name.startsWith("#")) {
Type type = Type.valueOf(part.substring(pos + 1, part.length() - 1));
String keyName = name;
if (type == Type.STRING) {
name = "$" + name.substring(1);
keyName = name;
}
if (!name2label.containsKey(keyName)) {
consts.add("; CONST: " + keyName);
String label = "CONST_" + (cnt++);
name2label.put(keyName, label);
name = name.substring(1);
if (type == Type.INTEGER) {
// Range check...convert to real if needed
int num = Integer.parseInt(name);
if (num < -32768 || num > 32767) {
name += ".0";
type = Type.REAL;
}
}
if (type == Type.INTEGER) {
consts.add(label + "\t" + ".WORD " + name);
if (platform.useLooseTypes()) {
consts.add(label + "R\t" + ".REAL " + name + ".0");
}
} else if (type == Type.REAL) {
consts.add(label + "R");
consts.add(label + "\t" + ".REAL " + name);
} else if (type == Type.STRING) {
consts.add(label + "\t" + ".BYTE " + name.length());
if (config.isConvertStringToLower() || config.isFlipCasing()) {
name = Converter.convertCase(name, !config.isFlipCasing());
}
consts.add("\t" + ".STRG \"" + name + "\"");
}
}
} else {
if (!name2label.containsKey(name)) {
tmp.clear();
tmp.add("; VAR: " + name);
String label = "VAR_" + name;
name2label.put(name, label);
Type type = Type.valueOf(part.substring(pos + 1, part.length() - 1));
if (name.contains("[]")) {
Variable var = machine.getVariable(name);
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>) var.getInternalValue();
if (type == Type.INTEGER) {
tmp.add("\t" + ".BYTE 0");
tmp.add("\t" + ".WORD " + vals.size() * 2);
tmp.add(label + "\t" + ".ARRAY " + vals.size() * 2);
} else if (type == Type.REAL) {
tmp.add("\t" + ".BYTE 1");
tmp.add("\t" + ".WORD " + vals.size() * 5);
tmp.add(label + "\t" + ".ARRAY " + vals.size() * 5);
} else if (type == Type.STRING) {
tmp.add("\t" + ".BYTE 2");
tmp.add("\t" + ".WORD " + vals.size() * 2);
tmp.add(label);
for (int pp = 0; pp < vals.size(); pp = pp + 10) {
StringBuilder sb = new StringBuilder();
sb.append("\t" + ".WORD ");
for (int ppp = pp; ppp < vals.size() && ppp < pp + 10; ppp++) {
sb.append("EMPTYSTR ");
}
tmp.add(sb.toString());
sb.setLength(0);
}
}
} else {
if (type == Type.INTEGER) {
tmp.add(label + "\t" + ".WORD 0");
} else if (type == Type.REAL) {
tmp.add(label + "\t" + ".REAL 0.0");
} else if (type == Type.STRING) {
tmp.add(label + "\t" + ".WORD EMPTYSTR");
}
}
if (name.contains("$")) {
if (name.contains("[]")) {
strArrayVars.addAll(tmp);
} else {
strVars.addAll(tmp);
}
} else {
vars.addAll(tmp);
}
}
}
}
}
return cnt;
}
protected void addStructures(CompilerConfig config, MemoryConfig memConfig, Machine machine, PlatformProvider platform, List<String> code,
List<String> res, List<String> consts, List<String> vars, List<String> mnems, List<String> subs) {
addStructures(config, memConfig, machine, platform, code, res, consts, vars, mnems, subs, null, null);
}
protected void addStructures(CompilerConfig config, MemoryConfig memConfig, Machine machine, PlatformProvider platform, List<String> code,
List<String> res, List<String> consts, List<String> vars, List<String> mnems, List<String> subs,
List<String> addOns, StringAdder adder) {
Map<String, String> name2label = new HashMap<String, String>();
int cnt = 0;
List<String> strVars = new ArrayList<String>();
List<String> strArrayVars = new ArrayList<String>();
GeneratorContext context = new GeneratorContext();
for (String line : code) {
String cmd = line;
line = convertConstantsToReal(line, platform);
// Intermediate code should contain no comments, so this actually
// hurts for Strings like "blah;"
// line = AssemblyParser.truncateComments(line);
String orgLine = line;
int sp = line.indexOf(" ");
if (sp != -1) {
line = line.substring(sp).trim();
}
cnt = extractData(config, platform, machine, consts, vars, strVars, strArrayVars, name2label, cnt, line);
Generator pm = GeneratorList.getGenerator(orgLine);
Generator altPm = platform.getGenerator(orgLine);
if (altPm != null) {
pm = altPm;
}
if (pm != null) {
pm.generateCode(context, orgLine, mnems, subs, name2label);
} else {
if (cmd.endsWith(":") || cmd.startsWith("CONT")) {
mnems.add(cmd);
} else {
mnems.add("; ignored: " + cmd);
}
}
}
if (!mnems.get(mnems.size() - 1).equals("RTS")) {
mnems.add("RTS");
}
List<String> inits = createInitScript(vars);
List<String> datas = createDatas(config, machine);
subs.addAll(inits);
subs.add("; *** SUBROUTINES END ***");
res.addAll(mnems);
res.addAll(subs);
if (addOns != null) {
addOns.add(0, ";###################################");
res.addAll(addOns);
}
res.addAll(consts);
res.addAll(datas);
res.add("CONSTANTS_END");
if (!strVars.contains("; VAR: TI$")) {
strVars.add("; VAR: TI$");
strVars.add("VAR_TI$ .WORD EMPTYSTR");
}
if (adder != null) {
adder.addStringVars(strVars);
}
vars.add("STRINGVARS_START");
vars.addAll(strVars);
vars.add("STRINGVARS_END");
vars.add("STRINGARRAYS_START");
vars.addAll(strArrayVars);
vars.add("STRINGARRAYS_END");
res.addAll(vars);
res.add("VARIABLES_END");
res.add("; *** INTERNAL ***");
res.add("X_REG\t.REAL 0.0");
res.add("Y_REG\t.REAL 0.0");
res.add("C_REG\t.REAL 0.0");
res.add("D_REG\t.REAL 0.0");
res.add("E_REG\t.REAL 0.0");
res.add("F_REG\t.REAL 0.0");
res.add("A_REG\t.WORD 0");
res.add("B_REG\t.WORD 0");
if (!preferZeropage) {
res.add("G_REG\t.WORD 0");
}
res.add("CMD_NUM\t.BYTE 0");
res.add("CHANNEL\t.BYTE 0");
res.add("SP_SAVE\t.BYTE 0");
if (!preferZeropage) {
res.add("TMP_REG\t.WORD 0");
}
res.add("TMP2_REG\t.WORD 0");
res.add("TMP3_REG\t.WORD 0");
res.add("TMP4_REG\t.WORD 0");
res.add("AS_TMP\t.WORD 0");
res.add("BPOINTER_TMP\t.WORD 0");
res.add("BASICTEXTP\t.BYTE 0");
res.add("STORE1\t.WORD 0");
res.add("STORE2\t.WORD 0");
res.add("STORE3\t.WORD 0");
res.add("STORE4\t.WORD 0");
res.add("GCSTART\t.WORD 0");
res.add("GCLEN\t.WORD 0");
res.add("GCWORK\t.WORD 0");
res.add("TMP_FREG\t.REAL 0");
res.add("TMP2_FREG\t.REAL 0");
res.add("TMP_FLAG\t.BYTE 0");
// res.add("JUMP_TARGET\t.WORD 0");
res.add("REAL_CONST_ONE\t.REAL 1.0");
res.add("REAL_CONST_ZERO\t.REAL 0.0");
res.add("REAL_CONST_MINUS_ONE\t.REAL -1.0");
res.add("CHLOCKFLAG\t.BYTE 0");
res.add("EMPTYSTR\t.BYTE 0");
res.add("FPSTACKP\t.WORD FPSTACK");
res.add("FORSTACKP\t.WORD FORSTACK");
res.add("DATASP\t.WORD DATAS");
res.add("LASTVAR\t.WORD 0");
res.add("LASTVARP\t.WORD 0");
res.add("HIGHP\t.WORD STRBUF");
res.add("STRBUFP\t.WORD STRBUF");
res.add("ENDSTRBUF\t.WORD " + this.stringMemoryEnd);
res.add("INPUTQUEUEP\t.BYTE 0");
res.add("PROGRAMEND");
addInternalBasicBuffer(res, platform, memConfig);
res.add("INPUTQUEUE\t.ARRAY $0F");
res.add("FPSTACK .ARRAY " + Math.min(256, platform.getStackSize() * 5));
res.add("FORSTACK .ARRAY " + Math.min(1024, platform.getForStackSize() * 17));
res.add("STRBUF\t.BYTE 0");
}
@Override
public void setVariableStart(int variableStart) {
this.variableStart = variableStart;
}
@Override
public int getVariableStart() {
return variableStart;
}
@Override
public int getStringMemoryEnd() {
return stringMemoryEnd;
}
@Override
public void setStringMemoryEnd(int stringMemoryEnd) {
this.stringMemoryEnd = stringMemoryEnd;
}
@Override
public void setStartAddress(int addr) {
startAddress = addr;
}
@Override
public int getStartAddress() {
return startAddress;
}
@Override
public int getRuntimeStart() {
return runtimeStart;
}
@Override
public void setRuntimeStart(int runtimeStart) {
this.runtimeStart = runtimeStart;
}
@Override
public boolean isOptimizedTempStorage() {
return preferZeropage;
}
@Override
public void setOptimizedTempStorage(boolean optimizedTemp) {
this.preferZeropage = optimizedTemp;
}
@Override
public List<String> createCaller(String calleeName) {
return null;
}
}
| src/main/java/com/sixtyfour/cbmnative/mos6502/AbstractTransformer.java | package com.sixtyfour.cbmnative.mos6502;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.sixtyfour.Basic;
import com.sixtyfour.Loader;
import com.sixtyfour.Logger;
import com.sixtyfour.cbmnative.Generator;
import com.sixtyfour.cbmnative.GeneratorContext;
import com.sixtyfour.cbmnative.PlatformProvider;
import com.sixtyfour.cbmnative.Transformer;
import com.sixtyfour.cbmnative.mos6502.generators.GeneratorList;
import com.sixtyfour.cbmnative.mos6502.util.Converter;
import com.sixtyfour.cbmnative.mos6502.x16.TransformerX16;
import com.sixtyfour.config.CompilerConfig;
import com.sixtyfour.config.MemoryConfig;
import com.sixtyfour.elements.Type;
import com.sixtyfour.elements.Variable;
import com.sixtyfour.extensions.BasicExtension;
import com.sixtyfour.system.DataStore;
import com.sixtyfour.system.Machine;
import com.sixtyfour.util.ConstantExtractor;
import com.sixtyfour.util.VarUtils;
/**
* Transformer base class for Commodore based target platforms.
*
* @author EgonOlsen
*
*/
public abstract class AbstractTransformer implements Transformer {
protected int variableStart = -1;
protected int runtimeStart = -1;
protected int stringMemoryEnd = 0;
protected int startAddress = 0;
protected boolean preferZeropage = true;
public static void addExtensionSubroutines(List<String> addTo, String postFix) {
List<BasicExtension> exts = Basic.getExtensions();
if (exts != null) {
for (BasicExtension ext : exts) {
try {
for (String inc : ext.getAdditionalIncludes()) {
List<String> adds = Arrays.asList(Loader.loadProgram(
AbstractTransformer.class.getResourceAsStream("/ext/" + inc + "." + postFix)));
addTo.addAll(adds);
}
} catch (Exception e) {
// ignore
}
}
}
}
public void addExtensionConstants(List<String> res) {
Map<String, Integer> map = ConstantExtractor.getAllConstantMaps();
for (Entry<String, Integer> entry : map.entrySet()) {
res.add(entry.getKey() + "=" + entry.getValue());
}
}
protected void addLabels(List<String> res, String[] labels) {
for (String label : labels) {
int pos = label.indexOf(";");
if (pos != -1) {
label = label.substring(0, pos);
}
label = label.trim();
res.add(label);
}
}
protected void addBasicBuffer(List<String> res, PlatformProvider platform, MemoryConfig memConfig) {
if (memConfig.getBasicBufferStart() == -1) {
res.add("BASICBUFFER=" + platform.getBasicBufferAddress());
} else {
if (memConfig.getBasicBufferStart() != 0) {
res.add("BASICBUFFER=" + memConfig.getBasicBufferStart());
}
}
}
protected void addInternalBasicBuffer(List<String> res, PlatformProvider platform, MemoryConfig memConfig) {
if (memConfig.getBasicBufferStart() == 0) {
res.add("BASICBUFFER .ARRAY 256");
}
}
protected void addMemoryLocations(List<String> res) {
String[] labels = Loader.loadProgram(TransformerX16.class.getResourceAsStream("/rommap/memloc-c64.map"));
addLabels(res, labels);
}
protected List<String> createDatas(CompilerConfig config, Machine machine) {
DataStore datas = machine.getDataStore();
List<String> ret = new ArrayList<String>();
ret.add(";###############################");
ret.add("; ******** DATA ********");
ret.add("DATAS");
int cnt = 0;
datas.restore();
Object obj = null;
while ((obj = datas.read()) != null) {
Type type = Type.STRING;
if (VarUtils.isInteger(obj)) {
Integer num = (Integer) obj;
if (num < -32768 || num > 32767) {
obj = num.floatValue();
type = Type.REAL;
} else {
type = Type.INTEGER;
}
} else if (VarUtils.isFloat(obj) || VarUtils.isDouble(obj)) {
type = Type.REAL;
}
if (obj.toString().equals("\\0")) {
obj = "";
}
if (type == Type.INTEGER) {
int val = ((Number) obj).intValue();
if (val < 0 || val > 255) {
ret.add(".BYTE 0");
ret.add(".WORD " + obj.toString());
cnt += 3;
} else {
if (val > 3 && val < 255) {
// If larger than the largest type (3) and smaller than the end flag (255),
/// the we can use the type's location as data and skip storing the typ itself.
ret.add(".BYTE " + obj.toString());
cnt += 1;
} else {
ret.add(".BYTE 3");
ret.add(".BYTE " + obj.toString());
cnt += 2;
}
}
} else if (type == Type.REAL) {
ret.add(".BYTE 1");
ret.add(".REAL " + obj.toString());
cnt += 6;
} else {
ret.add(".BYTE 2");
ret.add(".BYTE " + obj.toString().length());
String ds = obj.toString();
if (config.isConvertStringToLower() || config.isFlipCasing()) {
ds = Converter.convertCase(ds, !config.isFlipCasing());
}
ret.add(".STRG \"" + ds + "\"");
cnt += 2 + obj.toString().length();
}
}
ret.add(".BYTE $FF");
ret.add("; ******** DATA END ********");
Logger.log("DATA lines converted, " + cnt + " bytes used!");
return ret;
}
protected List<String> createInitScript(List<String> vars) {
List<String> inits = new ArrayList<String>();
inits.add("; ******* INITVARS ********");
inits.add(";###############################");
inits.add("INITVARS");
inits.add("JSR INITSTRVARS");
inits.add("LDA #0");
for (String var : vars) {
var = var.trim().replace("\t", " ");
if (var.startsWith("VAR_")) {
String[] parts = var.split(" ");
boolean isArray = var.contains("[]");
if (!parts[0].contains("$")) {
if (parts[1].equals(".REAL")) {
// INT and REAL arrays are both marked "ARRAY", so this
// branch can only happen if it a single REAL.
inits.add("STA " + parts[0]);
inits.add("STA " + parts[0] + "+1");
// inits.add("STA " + parts[0] + "+2");
// inits.add("STA " + parts[0] + "+3");
// inits.add("STA " + parts[0] + "+4");
} else {
// INT or ARRAY
if (isArray) {
if (inits.get(inits.size() - 1).equals("LDA #0")) {
// The LDA #0 is obsolete in this case.
inits.remove(inits.size() - 1);
}
inits.add("LDA #<" + parts[0]);
inits.add("LDY #>" + parts[0]);
inits.add("JSR INITSPARAMS"); // This should save A and Y
// inits.add("LDA #<" + parts[0]);
// inits.add("LDY #>" + parts[0]);
inits.add("JSR INITNARRAY");
inits.add("LDA #0");
} else {
inits.add("STA " + parts[0]);
inits.add("STA " + parts[0] + "+1");
}
}
}
}
}
inits.add("RTS");
inits.add(";###############################");
return inits;
}
protected String convertConstantsToReal(String line, PlatformProvider platform) {
if (platform.useLooseTypes()) {
if (line.contains("#") && line.endsWith("{INTEGER}")) {
int val = getConstantValue(line);
if (val < 0 || val > 255) {
line = line.replace("{INTEGER}", "{REAL}");
}
}
}
return line;
}
protected int getConstantValue(String line) {
String sval = line.substring(line.indexOf("#") + 1, line.indexOf("{INTEGER}"));
int val = Integer.parseInt(sval);
return val;
}
protected int extractData(CompilerConfig config, PlatformProvider platform, Machine machine, List<String> consts,
List<String> vars, List<String> strVars, List<String> strArrayVars, Map<String, String> name2label, int cnt,
String line) {
String[] parts = line.split(",", 2);
List<String> tmp = new ArrayList<String>();
for (int p = 0; p < parts.length; p++) {
String part = parts[p];
if (part.contains("{") && part.endsWith("}")) {
int pos = part.lastIndexOf("{");
String name = part.substring(0, pos);
if (name.startsWith("#")) {
Type type = Type.valueOf(part.substring(pos + 1, part.length() - 1));
String keyName = name;
if (type == Type.STRING) {
name = "$" + name.substring(1);
keyName = name;
}
if (!name2label.containsKey(keyName)) {
consts.add("; CONST: " + keyName);
String label = "CONST_" + (cnt++);
name2label.put(keyName, label);
name = name.substring(1);
if (type == Type.INTEGER) {
// Range check...convert to real if needed
int num = Integer.parseInt(name);
if (num < -32768 || num > 32767) {
name += ".0";
type = Type.REAL;
}
}
if (type == Type.INTEGER) {
consts.add(label + "\t" + ".WORD " + name);
if (platform.useLooseTypes()) {
consts.add(label + "R\t" + ".REAL " + name + ".0");
}
} else if (type == Type.REAL) {
consts.add(label + "R");
consts.add(label + "\t" + ".REAL " + name);
} else if (type == Type.STRING) {
consts.add(label + "\t" + ".BYTE " + name.length());
if (config.isConvertStringToLower() || config.isFlipCasing()) {
name = Converter.convertCase(name, !config.isFlipCasing());
}
consts.add("\t" + ".STRG \"" + name + "\"");
}
}
} else {
if (!name2label.containsKey(name)) {
tmp.clear();
tmp.add("; VAR: " + name);
String label = "VAR_" + name;
name2label.put(name, label);
Type type = Type.valueOf(part.substring(pos + 1, part.length() - 1));
if (name.contains("[]")) {
Variable var = machine.getVariable(name);
@SuppressWarnings("unchecked")
List<Object> vals = (List<Object>) var.getInternalValue();
if (type == Type.INTEGER) {
tmp.add("\t" + ".BYTE 0");
tmp.add("\t" + ".WORD " + vals.size() * 2);
tmp.add(label + "\t" + ".ARRAY " + vals.size() * 2);
} else if (type == Type.REAL) {
tmp.add("\t" + ".BYTE 1");
tmp.add("\t" + ".WORD " + vals.size() * 5);
tmp.add(label + "\t" + ".ARRAY " + vals.size() * 5);
} else if (type == Type.STRING) {
tmp.add("\t" + ".BYTE 2");
tmp.add("\t" + ".WORD " + vals.size() * 2);
tmp.add(label);
for (int pp = 0; pp < vals.size(); pp = pp + 10) {
StringBuilder sb = new StringBuilder();
sb.append("\t" + ".WORD ");
for (int ppp = pp; ppp < vals.size() && ppp < pp + 10; ppp++) {
sb.append("EMPTYSTR ");
}
tmp.add(sb.toString());
sb.setLength(0);
}
}
} else {
if (type == Type.INTEGER) {
tmp.add(label + "\t" + ".WORD 0");
} else if (type == Type.REAL) {
tmp.add(label + "\t" + ".REAL 0.0");
} else if (type == Type.STRING) {
tmp.add(label + "\t" + ".WORD EMPTYSTR");
}
}
if (name.contains("$")) {
if (name.contains("[]")) {
strArrayVars.addAll(tmp);
} else {
strVars.addAll(tmp);
}
} else {
vars.addAll(tmp);
}
}
}
}
}
return cnt;
}
protected void addStructures(CompilerConfig config, MemoryConfig memConfig, Machine machine, PlatformProvider platform, List<String> code,
List<String> res, List<String> consts, List<String> vars, List<String> mnems, List<String> subs) {
addStructures(config, memConfig, machine, platform, code, res, consts, vars, mnems, subs, null, null);
}
protected void addStructures(CompilerConfig config, MemoryConfig memConfig, Machine machine, PlatformProvider platform, List<String> code,
List<String> res, List<String> consts, List<String> vars, List<String> mnems, List<String> subs,
List<String> addOns, StringAdder adder) {
Map<String, String> name2label = new HashMap<String, String>();
int cnt = 0;
List<String> strVars = new ArrayList<String>();
List<String> strArrayVars = new ArrayList<String>();
GeneratorContext context = new GeneratorContext();
for (String line : code) {
String cmd = line;
line = convertConstantsToReal(line, platform);
// Intermediate code should contain no comments, so this actually
// hurts for Strings like "blah;"
// line = AssemblyParser.truncateComments(line);
String orgLine = line;
int sp = line.indexOf(" ");
if (sp != -1) {
line = line.substring(sp).trim();
}
cnt = extractData(config, platform, machine, consts, vars, strVars, strArrayVars, name2label, cnt, line);
Generator pm = GeneratorList.getGenerator(orgLine);
Generator altPm = platform.getGenerator(orgLine);
if (altPm != null) {
pm = altPm;
}
if (pm != null) {
pm.generateCode(context, orgLine, mnems, subs, name2label);
} else {
if (cmd.endsWith(":") || cmd.startsWith("CONT")) {
mnems.add(cmd);
} else {
mnems.add("; ignored: " + cmd);
}
}
}
if (!mnems.get(mnems.size() - 1).equals("RTS")) {
mnems.add("RTS");
}
List<String> inits = createInitScript(vars);
List<String> datas = createDatas(config, machine);
subs.addAll(inits);
subs.add("; *** SUBROUTINES END ***");
res.addAll(mnems);
res.addAll(subs);
if (addOns != null) {
addOns.add(0, ";###################################");
res.addAll(addOns);
}
res.addAll(consts);
res.addAll(datas);
res.add("CONSTANTS_END");
if (!strVars.contains("; VAR: TI$")) {
strVars.add("; VAR: TI$");
strVars.add("VAR_TI$ .WORD EMPTYSTR");
}
if (adder != null) {
adder.addStringVars(strVars);
}
vars.add("STRINGVARS_START");
vars.addAll(strVars);
vars.add("STRINGVARS_END");
vars.add("STRINGARRAYS_START");
vars.addAll(strArrayVars);
vars.add("STRINGARRAYS_END");
res.addAll(vars);
res.add("VARIABLES_END");
res.add("; *** INTERNAL ***");
res.add("X_REG\t.REAL 0.0");
res.add("Y_REG\t.REAL 0.0");
res.add("C_REG\t.REAL 0.0");
res.add("D_REG\t.REAL 0.0");
res.add("E_REG\t.REAL 0.0");
res.add("F_REG\t.REAL 0.0");
res.add("A_REG\t.WORD 0");
res.add("B_REG\t.WORD 0");
if (!preferZeropage) {
res.add("G_REG\t.WORD 0");
}
res.add("CMD_NUM\t.BYTE 0");
res.add("CHANNEL\t.BYTE 0");
res.add("SP_SAVE\t.BYTE 0");
if (!preferZeropage) {
res.add("TMP_REG\t.WORD 0");
}
res.add("TMP2_REG\t.WORD 0");
res.add("TMP3_REG\t.WORD 0");
res.add("TMP4_REG\t.WORD 0");
res.add("AS_TMP\t.WORD 0");
res.add("BPOINTER_TMP\t.WORD 0");
res.add("BASICTEXTP\t.BYTE 0");
res.add("STORE1\t.WORD 0");
res.add("STORE2\t.WORD 0");
res.add("STORE3\t.WORD 0");
res.add("STORE4\t.WORD 0");
res.add("GCSTART\t.WORD 0");
res.add("GCLEN\t.WORD 0");
res.add("GCWORK\t.WORD 0");
res.add("TMP_FREG\t.REAL 0");
res.add("TMP2_FREG\t.REAL 0");
res.add("TMP_FLAG\t.BYTE 0");
// res.add("JUMP_TARGET\t.WORD 0");
res.add("REAL_CONST_ONE\t.REAL 1.0");
res.add("REAL_CONST_ZERO\t.REAL 0.0");
res.add("REAL_CONST_MINUS_ONE\t.REAL -1.0");
res.add("EMPTYSTR\t.BYTE 0");
res.add("FPSTACKP\t.WORD FPSTACK");
res.add("FORSTACKP\t.WORD FORSTACK");
res.add("DATASP\t.WORD DATAS");
res.add("LASTVAR\t.WORD 0");
res.add("CHLOCKFLAG\t.BYTE 0");
res.add("LASTVARP\t.WORD 0");
res.add("HIGHP\t.WORD STRBUF");
res.add("STRBUFP\t.WORD STRBUF");
res.add("ENDSTRBUF\t.WORD " + this.stringMemoryEnd);
res.add("INPUTQUEUEP\t.BYTE 0");
res.add("PROGRAMEND");
addInternalBasicBuffer(res, platform, memConfig);
res.add("INPUTQUEUE\t.ARRAY $0F");
res.add("FPSTACK .ARRAY " + Math.min(256, platform.getStackSize() * 5));
res.add("FORSTACK .ARRAY " + Math.min(1024, platform.getForStackSize() * 17));
res.add("STRBUF\t.BYTE 0");
}
@Override
public void setVariableStart(int variableStart) {
this.variableStart = variableStart;
}
@Override
public int getVariableStart() {
return variableStart;
}
@Override
public int getStringMemoryEnd() {
return stringMemoryEnd;
}
@Override
public void setStringMemoryEnd(int stringMemoryEnd) {
this.stringMemoryEnd = stringMemoryEnd;
}
@Override
public void setStartAddress(int addr) {
startAddress = addr;
}
@Override
public int getStartAddress() {
return startAddress;
}
@Override
public int getRuntimeStart() {
return runtimeStart;
}
@Override
public void setRuntimeStart(int runtimeStart) {
this.runtimeStart = runtimeStart;
}
@Override
public boolean isOptimizedTempStorage() {
return preferZeropage;
}
@Override
public void setOptimizedTempStorage(boolean optimizedTemp) {
this.preferZeropage = optimizedTemp;
}
@Override
public List<String> createCaller(String calleeName) {
return null;
}
}
| Moved one byte around | src/main/java/com/sixtyfour/cbmnative/mos6502/AbstractTransformer.java | Moved one byte around | <ide><path>rc/main/java/com/sixtyfour/cbmnative/mos6502/AbstractTransformer.java
<ide> res.add("REAL_CONST_ONE\t.REAL 1.0");
<ide> res.add("REAL_CONST_ZERO\t.REAL 0.0");
<ide> res.add("REAL_CONST_MINUS_ONE\t.REAL -1.0");
<add> res.add("CHLOCKFLAG\t.BYTE 0");
<ide> res.add("EMPTYSTR\t.BYTE 0");
<ide> res.add("FPSTACKP\t.WORD FPSTACK");
<ide> res.add("FORSTACKP\t.WORD FORSTACK");
<ide> res.add("DATASP\t.WORD DATAS");
<ide> res.add("LASTVAR\t.WORD 0");
<del> res.add("CHLOCKFLAG\t.BYTE 0");
<ide> res.add("LASTVARP\t.WORD 0");
<ide> res.add("HIGHP\t.WORD STRBUF");
<ide> res.add("STRBUFP\t.WORD STRBUF"); |
|
Java | agpl-3.0 | 62bb4d640f29676eb0158935b6c680ec22f3e6e5 | 0 | winni67/AndroidAPS,RoumenGeorgiev/AndroidAPS,AdrianLxM/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,LadyViktoria/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,winni67/AndroidAPS,samihusseingit/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,LadyViktoria/AndroidAPS,Heiner1/AndroidAPS,samihusseingit/AndroidAPS,AdrianLxM/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,PoweRGbg/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,RoumenGeorgiev/AndroidAPS,MilosKozak/AndroidAPS | package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResult;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewExtendedBolusDialog;
import info.nightscout.client.data.DbLogger;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil;
public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderFragment.class);
ListView bgsourceListView;
ListView pumpListView;
ListView loopListView;
TextView loopLabel;
ListView treatmentsListView;
ListView tempsListView;
ListView profileListView;
ListView apsListView;
TextView apsLabel;
ListView constraintsListView;
ListView generalListView;
TextView nsclientVerView;
TextView nightscoutVerView;
PluginCustomAdapter bgsourceDataAdapter = null;
PluginCustomAdapter pumpDataAdapter = null;
PluginCustomAdapter loopDataAdapter = null;
PluginCustomAdapter treatmentsDataAdapter = null;
PluginCustomAdapter tempsDataAdapter = null;
PluginCustomAdapter profileDataAdapter = null;
PluginCustomAdapter apsDataAdapter = null;
PluginCustomAdapter constraintsDataAdapter = null;
PluginCustomAdapter generalDataAdapter = null;
BgSourceInterface activeBgSource;
PumpInterface activePump;
ProfileInterface activeProfile;
TreatmentsInterface activeTreatments;
TempBasalsInterface activeTempBasals;
LoopFragment activeLoop;
public String nightscoutVersionName = "";
public Integer nightscoutVersionCode = 0;
public String nsClientVersionName = "";
public Integer nsClientVersionCode = 0;
ArrayList<PluginBase> pluginList;
Date lastDeviceStatusUpload = new Date(0);
// TODO: sorting
// TODO: Toast and sound when command failed
public ConfigBuilderFragment() {
super();
registerBus();
}
public void initialize() {
pluginList = MainApp.getPluginsList();
loadSettings();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
tempsListView = (ListView) view.findViewById(R.id.configbuilder_tempslistview);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
nsclientVerView = (TextView) view.findViewById(R.id.configbuilder_nsclientversion);
nightscoutVerView = (TextView) view.findViewById(R.id.configbuilder_nightscoutversion);
nsclientVerView.setText(nsClientVersionName);
nightscoutVerView.setText(nightscoutVersionName);
if (nsClientVersionCode < 117) nsclientVerView.setTextColor(Color.RED);
if (nightscoutVersionCode < 900) nightscoutVerView.setTextColor(Color.RED);
setViews();
return view;
}
void setViews() {
bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class), PluginBase.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter);
setListViewHeightBasedOnChildren(bgsourceListView);
pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.PUMP), PluginBase.PUMP);
pumpListView.setAdapter(pumpDataAdapter);
setListViewHeightBasedOnChildren(pumpListView);
loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.LOOP), PluginBase.LOOP);
loopListView.setAdapter(loopDataAdapter);
setListViewHeightBasedOnChildren(loopListView);
if (MainApp.getSpecificPluginsList(PluginBase.LOOP).size() == 0)
loopLabel.setVisibility(View.GONE);
treatmentsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TREATMENT), PluginBase.TREATMENT);
treatmentsListView.setAdapter(treatmentsDataAdapter);
setListViewHeightBasedOnChildren(treatmentsListView);
tempsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL), PluginBase.TEMPBASAL);
tempsListView.setAdapter(tempsDataAdapter);
setListViewHeightBasedOnChildren(tempsListView);
profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ProfileInterface.class), PluginBase.PROFILE);
profileListView.setAdapter(profileDataAdapter);
setListViewHeightBasedOnChildren(profileListView);
apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.APS), PluginBase.APS);
apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView);
if (MainApp.getSpecificPluginsList(PluginBase.APS).size() == 0)
apsLabel.setVisibility(View.GONE);
constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class), PluginBase.CONSTRAINTS);
constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView);
generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.GENERAL), PluginBase.GENERAL);
generalListView.setAdapter(generalDataAdapter);
setListViewHeightBasedOnChildren(generalListView);
}
/*
* PluginBase interface
*/
@Override
public int getType() {
return PluginBase.GENERAL;
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.configbuilder);
}
@Override
public boolean isEnabled(int type) {
return true;
}
@Override
public boolean isVisibleInTabs(int type) {
return true;
}
@Override
public boolean canBeHidden(int type) {
return false;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
// Always enabled
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
// Always visible
}
public static ConfigBuilderFragment newInstance() {
return new ConfigBuilderFragment();
}
/*
* Pump interface
*
* Config builder return itself as a pump and check constraints before it passes command to pump driver
*/
@Override
public boolean isTempBasalInProgress() {
return activePump.isTempBasalInProgress();
}
@Override
public boolean isExtendedBoluslInProgress() {
return activePump.isExtendedBoluslInProgress();
}
@Override
public void setNewBasalProfile(NSProfile profile) {
activePump.setNewBasalProfile(profile);
}
@Override
public double getBaseBasalRate() {
return activePump.getBaseBasalRate();
}
@Override
public double getTempBasalAbsoluteRate() {
return activePump.getTempBasalAbsoluteRate();
}
@Override
public double getTempBasalRemainingMinutes() {
return activePump.getTempBasalRemainingMinutes();
}
@Override
public TempBasal getTempBasal(Date time) {
return activePump.getTempBasal(time);
}
@Override
public TempBasal getTempBasal() {
return activePump.getTempBasal();
}
@Override
public TempBasal getExtendedBolus() {
return activePump.getExtendedBolus();
}
/*
{
"_id": {
"$oid": "5789fea07ef0c37deb388240"
},
"boluscalc": {
"profile": "Posunuta snidane",
"eventTime": "2016-07-16T09:30:14.139Z",
"targetBGLow": "5.6",
"targetBGHigh": "5.6",
"isf": "17",
"ic": "26",
"iob": "0.89",
"cob": "0",
"insulincob": "0",
"bg": "3.6",
"insulinbg": "-0.12",
"bgdiff": "-2",
"carbs": "42",
"gi": "2",
"insulincarbs": "1.62",
"othercorrection": "0",
"insulin": "0.6000000000000001",
"roundingcorrection": "-0.009999999999999898",
"carbsneeded": "0"
},
"enteredBy": "",
"eventType": "Bolus Wizard",
"glucose": 3.6,
"glucoseType": "Sensor",
"units": "mmol",
"carbs": 42,
"insulin": 0.6,
"created_at": "2016-07-16T09:30:12.783Z"
}
*/
public PumpEnactResult deliverTreatmentFromBolusWizard(Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatmentFromBolusWizard insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult deliverTreatment(Double insulin, Integer carbs) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
t.sendToNSClient();
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
/**
* apply constraints, set temp based on absolute valus and expecting absolute result
*
* @param absoluteRate
* @param durationInMinutes
* @return
*/
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
Double rateAfterConstraints = applyBasalConstraints(absoluteRate);
PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalAbsolute rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
if (result.isPercent) {
uploadTempBasalStartPercent(result.percent, result.duration);
} else {
uploadTempBasalStartAbsolute(result.absolute, result.duration);
}
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
/**
* apply constraints, set temp based on percent and expecting result in percent
*
* @param percent 0 ... 100 ...
* @param durationInMinutes
* @return result
*/
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
Integer percentAfterConstraints = applyBasalConstraints(percent);
PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalStartPercent(result.percent, result.duration);
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
Double rateAfterConstraints = applyBolusConstraints(insulin);
PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setExtendedBolus rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadExtendedBolus(result.bolusDelivered, result.duration);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult cancelTempBasal() {
PumpEnactResult result = activePump.cancelTempBasal();
if (Config.logCongigBuilderActions)
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalEnd();
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = activePump.cancelExtendedBolus();
if (Config.logCongigBuilderActions)
log.debug("cancelExtendedBolus success: " + result.success + " enacted: " + result.enacted);
return result;
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
*
* @param request
* @return
*/
public PumpEnactResult applyAPSRequest(APSResult request) {
request.rate = applyBasalConstraints(request.rate);
PumpEnactResult result;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString());
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - getBaseBasalRate()) < 0.1) {
if (isTempBasalInProgress()) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()");
result = cancelTempBasal();
} else {
result = new PumpEnactResult();
result.absolute = request.rate;
result.duration = 0;
result.enacted = false;
result.comment = "Basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
}
} else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRate()) < 0.1) {
result = new PumpEnactResult();
result.absolute = getTempBasalAbsoluteRate();
result.duration = activePump.getTempBasal().getPlannedRemainingMinutes();
result.enacted = false;
result.comment = "Temp basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly");
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()");
result = setTempBasalAbsolute(request.rate, request.duration);
}
return result;
}
@Nullable
@Override
public JSONObject getJSONStatus() {
if (activePump != null)
return activePump.getJSONStatus();
else return null;
}
@Override
public String deviceID() {
if (activePump != null)
return activePump.deviceID();
else return "Unknown";
}
/*
* ConfigBuilderFragment code
*/
private class PluginCustomAdapter extends ArrayAdapter<PluginBase> {
private ArrayList<PluginBase> pluginList;
final private int type;
public PluginCustomAdapter(Context context, int textViewResourceId,
ArrayList<PluginBase> pluginList, int type) {
super(context, textViewResourceId, pluginList);
this.pluginList = new ArrayList<PluginBase>();
this.pluginList.addAll(pluginList);
this.type = type;
}
private class PluginViewHolder {
TextView name;
CheckBox checkboxEnabled;
CheckBox checkboxVisible;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PluginViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.configbuilder_simpleitem, null);
holder = new PluginViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.configbuilder_simpleitem_name);
holder.checkboxEnabled = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxenabled);
holder.checkboxVisible = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxvisible);
convertView.setTag(holder);
holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentEnabled(type, cb.isChecked());
plugin.setFragmentVisible(type, cb.isChecked());
onEnabledCategoryChanged(plugin, type);
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
holder.checkboxVisible.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentVisible(type, cb.isChecked());
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
} else {
holder = (PluginViewHolder) convertView.getTag();
}
PluginBase plugin = pluginList.get(position);
holder.name.setText(plugin.getName());
holder.checkboxEnabled.setChecked(plugin.isEnabled(type));
holder.checkboxVisible.setChecked(plugin.isVisibleInTabs(type));
holder.name.setTag(plugin);
holder.checkboxEnabled.setTag(plugin);
holder.checkboxVisible.setTag(plugin);
if (!plugin.canBeHidden(type)) {
holder.checkboxEnabled.setEnabled(false);
holder.checkboxVisible.setEnabled(false);
}
int type = plugin.getType();
// Force enabled if there is only one plugin
if (type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.TEMPBASAL || type == PluginBase.PROFILE)
if (pluginList.size() < 2)
holder.checkboxEnabled.setEnabled(false);
// Constraints cannot be disabled
if (type == PluginBase.CONSTRAINTS)
holder.checkboxEnabled.setEnabled(false);
// Hide disabled profiles by default
if (type == PluginBase.PROFILE) {
if (!plugin.isEnabled(type)) {
holder.checkboxVisible.setEnabled(false);
holder.checkboxVisible.setChecked(false);
} else {
holder.checkboxVisible.setEnabled(true);
}
}
return convertView;
}
}
public BgSourceInterface getActiveBgSource() {
return activeBgSource;
}
public PumpInterface getActivePump() {
return this;
}
@Nullable
public ProfileInterface getActiveProfile() {
return activeProfile;
}
public TreatmentsInterface getActiveTreatments() {
return activeTreatments;
}
public TempBasalsInterface getActiveTempBasals() {
return activeTempBasals;
}
public LoopFragment getActiveLoop() {
return activeLoop;
}
void onEnabledCategoryChanged(PluginBase changedPlugin, int type) {
int category = changedPlugin.getType();
ArrayList<PluginBase> pluginsInCategory = null;
switch (category) {
// Multiple selection allowed
case PluginBase.APS:
case PluginBase.GENERAL:
case PluginBase.CONSTRAINTS:
case PluginBase.LOOP:
break;
// Single selection allowed
case PluginBase.PROFILE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case PluginBase.BGSOURCE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case PluginBase.TEMPBASAL:
case PluginBase.TREATMENT:
case PluginBase.PUMP:
pluginsInCategory = MainApp.getSpecificPluginsList(category);
break;
}
if (pluginsInCategory != null) {
boolean newSelection = changedPlugin.isEnabled(type);
if (newSelection) { // new plugin selected -> disable others
for (PluginBase p : pluginsInCategory) {
if (p.getName().equals(changedPlugin.getName())) {
// this is new selected
} else {
p.setFragmentEnabled(type, false);
p.setFragmentVisible(type, false);
}
}
} else { // enable first plugin in list
pluginsInCategory.get(0).setFragmentEnabled(type, true);
}
setViews();
}
}
private void verifySelectionInCategories() {
ArrayList<PluginBase> pluginsInCategory;
// PluginBase.PROFILE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
activeProfile = (ProfileInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PROFILE);
if (Config.logConfigBuilder)
log.debug("Selected profile interface: " + ((PluginBase) activeProfile).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeProfile).getName())) {
p.setFragmentVisible(PluginBase.PROFILE, false);
}
}
// PluginBase.BGSOURCE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
activeBgSource = (BgSourceInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.BGSOURCE);
if (Config.logConfigBuilder)
log.debug("Selected bgSource interface: " + ((PluginBase) activeBgSource).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeBgSource).getName())) {
p.setFragmentVisible(PluginBase.BGSOURCE, false);
}
}
// PluginBase.PUMP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP);
if (Config.logConfigBuilder)
log.debug("Selected pump interface: " + ((PluginBase) activePump).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activePump).getName())) {
p.setFragmentVisible(PluginBase.PUMP, false);
}
}
// PluginBase.LOOP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.LOOP);
activeLoop = (LoopFragment) getTheOneEnabledInArray(pluginsInCategory, PluginBase.LOOP);
if (activeLoop != null) {
if (Config.logConfigBuilder)
log.debug("Selected loop interface: " + activeLoop.getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(activeLoop.getName())) {
p.setFragmentVisible(PluginBase.LOOP, false);
}
}
}
// PluginBase.TEMPBASAL
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL);
activeTempBasals = (TempBasalsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TEMPBASAL);
if (Config.logConfigBuilder)
log.debug("Selected tempbasal interface: " + ((PluginBase) activeTempBasals).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTempBasals).getName())) {
p.setFragmentVisible(PluginBase.TEMPBASAL, false);
}
}
// PluginBase.TREATMENT
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TREATMENT);
activeTreatments = (TreatmentsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TREATMENT);
if (Config.logConfigBuilder)
log.debug("Selected treatment interface: " + ((PluginBase) activeTreatments).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTreatments).getName())) {
p.setFragmentVisible(PluginBase.TREATMENT, false);
}
}
}
@Nullable
private PluginBase getTheOneEnabledInArray(ArrayList<PluginBase> pluginsInCategory, int type) {
PluginBase found = null;
for (PluginBase p : pluginsInCategory) {
if (p.isEnabled(type) && found == null) {
found = p;
} else if (p.isEnabled(type)) {
// set others disabled
p.setFragmentEnabled(type, false);
}
}
// If none enabled, enable first one
if (found == null && pluginsInCategory.size() > 0)
found = pluginsInCategory.get(0);
return found;
}
private void storeSettings() {
if (pluginList != null) {
if (Config.logPrefsChange)
log.debug("Storing settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
editor.putBoolean(settingEnabled, p.isEnabled(type));
editor.putBoolean(settingVisible, p.isVisibleInTabs(type));
}
}
editor.apply();
verifySelectionInCategories();
}
}
private void loadSettings() {
if (Config.logPrefsChange)
log.debug("Loading stored settings");
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
if (SP.contains(settingEnabled))
p.setFragmentEnabled(type, SP.getBoolean(settingEnabled, true));
if (SP.contains(settingVisible))
p.setFragmentVisible(type, SP.getBoolean(settingVisible, true));
}
}
verifySelectionInCategories();
}
/****
* Method for Setting the Height of the ListView dynamically.
* *** Hack to fix the issue of not showing all the items of the ListView
* *** when placed inside a ScrollView
****/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* Constraints interface
**/
@Override
public boolean isLoopEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isLoopEnabled();
}
return result;
}
@Override
public boolean isClosedModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isClosedModeEnabled();
}
return result;
}
@Override
public boolean isAutosensModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAutosensModeEnabled();
}
return result;
}
@Override
public boolean isAMAModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAMAModeEnabled();
}
return result;
}
@Override
public Double applyBasalConstraints(Double absoluteRate) {
Double rateAfterConstrain = absoluteRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(absoluteRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Integer applyBasalConstraints(Integer percentRate) {
Integer rateAfterConstrain = percentRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(percentRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Double applyBolusConstraints(Double insulin) {
Double insulinAfterConstrain = insulin;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
insulinAfterConstrain = Math.min(constrain.applyBolusConstraints(insulin), insulinAfterConstrain);
}
return insulinAfterConstrain;
}
@Override
public Integer applyCarbsConstraints(Integer carbs) {
Integer carbsAfterConstrain = carbs;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
carbsAfterConstrain = Math.min(constrain.applyCarbsConstraints(carbs), carbsAfterConstrain);
}
return carbsAfterConstrain;
}
@Override
public Double applyMaxIOBConstraints(Double maxIob) {
Double maxIobAfterConstrain = maxIob;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
maxIobAfterConstrain = Math.min(constrain.applyMaxIOBConstraints(maxIob), maxIobAfterConstrain);
}
return maxIobAfterConstrain;
}
@Subscribe
public void onStatusEvent(final EventNewBG ev) {
// Give some time to Loop
try {
Thread.sleep(120 * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
// if status not uploaded, upload pump status only
if (new Date().getTime() - lastDeviceStatusUpload.getTime() > 120 * 1000L) {
uploadDeviceStatus();
}
}
public static void uploadTempBasalStartAbsolute(Double absolute, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("absolute", absolute);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
if (useAbsolute) {
double absolute = MainApp.getConfigBuilder().getActivePump().getBaseBasalRate() * percent / 100d;
uploadTempBasalStartAbsolute(absolute, durationInMinutes);
} else {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("percent", percent - 100);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void uploadTempBasalEnd() {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void uploadExtendedBolus(Double insulin, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Combo Bolus");
data.put("duration", durationInMinutes);
data.put("splitNow", 0);
data.put("splitExt", 100);
data.put("enteredinsulin", insulin);
data.put("relative", insulin);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void uploadDeviceStatus() {
DeviceStatus deviceStatus = new DeviceStatus();
try {
LoopFragment.LastRun lastRun = LoopFragment.lastRun;
if (lastRun != null && lastRun.lastAPSRun.getTime() > new Date().getTime() - 60 * 1000L) {
// do not send if result is older than 1 min
APSResult apsResult = lastRun.request;
apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun));
deviceStatus.suggested = apsResult.json();
if (lastRun.request instanceof DetermineBasalResult) {
DetermineBasalResult result = (DetermineBasalResult) lastRun.request;
deviceStatus.iob = result.iob.json();
deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun));
}
if (lastRun.setByPump != null && lastRun.setByPump.enacted) { // enacted
deviceStatus.enacted = lastRun.request.json();
deviceStatus.enacted.put("rate", lastRun.setByPump.json().get("rate"));
deviceStatus.enacted.put("duration", lastRun.setByPump.json().get("duration"));
deviceStatus.enacted.put("recieved", true);
JSONObject requested = new JSONObject();
requested.put("duration", lastRun.request.duration);
requested.put("rate", lastRun.request.rate);
requested.put("temp", "absolute");
deviceStatus.enacted.put("requested", requested);
}
}
if (getActivePump() != null) {
deviceStatus.device = "openaps://" + getActivePump().deviceID();
deviceStatus.pump = getActivePump().getJSONStatus();
deviceStatus.created_at = DateUtil.toISOString(new Date());
deviceStatus.sendToNSClient();
lastDeviceStatusUpload = new Date();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void uploadBolusWizardRecord(Treatment t, double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
JSONObject data = new JSONObject();
try {
data.put("eventType", "Bolus Wizard");
if (t.insulin != 0d) data.put("insulin", t.insulin);
if (t.carbs != 0d) data.put("carbs", t.carbs.intValue());
data.put("created_at", DateUtil.toISOString(t.created_at));
data.put("timeIndex", t.timeIndex);
if (glucose != 0d) data.put("glucose", glucose);
data.put("glucoseType", glucoseType);
data.put("boluscalc", boluscalc);
if (carbTime != 0) data.put("preBolus", carbTime);
} catch (JSONException e) {
e.printStackTrace();
}
uploadCareportalEntryToNS(data);
}
public static void uploadCareportalEntryToNS(JSONObject data) {
try {
if (data.has("preBolus") && data.has("carbs")) {
JSONObject prebolus = new JSONObject();
prebolus.put("carbs", data.get("carbs"));
data.remove("carbs");
prebolus.put("eventType", data.get("eventType"));
if (data.has("enteredBy")) prebolus.put("enteredBy", data.get("enteredBy"));
if (data.has("notes")) prebolus.put("notes", data.get("notes"));
long mills = DateUtil.fromISODateString(data.getString("created_at")).getTime();
Date preBolusDate = new Date(mills + data.getInt("preBolus") * 60000L);
prebolus.put("created_at", DateUtil.toISOString(preBolusDate));
uploadCareportalEntryToNS(prebolus);
}
Context context = MainApp.instance().getApplicationContext();
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), NewExtendedBolusDialog.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java | package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResult;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewExtendedBolusDialog;
import info.nightscout.client.data.DbLogger;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil;
public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderFragment.class);
ListView bgsourceListView;
ListView pumpListView;
ListView loopListView;
TextView loopLabel;
ListView treatmentsListView;
ListView tempsListView;
ListView profileListView;
ListView apsListView;
TextView apsLabel;
ListView constraintsListView;
ListView generalListView;
TextView nsclientVerView;
TextView nightscoutVerView;
PluginCustomAdapter bgsourceDataAdapter = null;
PluginCustomAdapter pumpDataAdapter = null;
PluginCustomAdapter loopDataAdapter = null;
PluginCustomAdapter treatmentsDataAdapter = null;
PluginCustomAdapter tempsDataAdapter = null;
PluginCustomAdapter profileDataAdapter = null;
PluginCustomAdapter apsDataAdapter = null;
PluginCustomAdapter constraintsDataAdapter = null;
PluginCustomAdapter generalDataAdapter = null;
BgSourceInterface activeBgSource;
PumpInterface activePump;
ProfileInterface activeProfile;
TreatmentsInterface activeTreatments;
TempBasalsInterface activeTempBasals;
LoopFragment activeLoop;
public String nightscoutVersionName = "";
public Integer nightscoutVersionCode = 0;
public String nsClientVersionName = "";
public Integer nsClientVersionCode = 0;
ArrayList<PluginBase> pluginList;
Date lastDeviceStatusUpload = new Date(0);
// TODO: sorting
// TODO: Toast and sound when command failed
public ConfigBuilderFragment() {
super();
registerBus();
}
public void initialize() {
pluginList = MainApp.getPluginsList();
loadSettings();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
tempsListView = (ListView) view.findViewById(R.id.configbuilder_tempslistview);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
nsclientVerView = (TextView) view.findViewById(R.id.configbuilder_nsclientversion);
nightscoutVerView = (TextView) view.findViewById(R.id.configbuilder_nightscoutversion);
nsclientVerView.setText(nsClientVersionName);
nightscoutVerView.setText(nightscoutVersionName);
if (nsClientVersionCode < 117) nsclientVerView.setTextColor(Color.RED);
if (nightscoutVersionCode < 900) nightscoutVerView.setTextColor(Color.RED);
setViews();
return view;
}
void setViews() {
bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class), PluginBase.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter);
setListViewHeightBasedOnChildren(bgsourceListView);
pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.PUMP), PluginBase.PUMP);
pumpListView.setAdapter(pumpDataAdapter);
setListViewHeightBasedOnChildren(pumpListView);
loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.LOOP), PluginBase.LOOP);
loopListView.setAdapter(loopDataAdapter);
setListViewHeightBasedOnChildren(loopListView);
if (MainApp.getSpecificPluginsList(PluginBase.LOOP).size() == 0)
loopLabel.setVisibility(View.GONE);
treatmentsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TREATMENT), PluginBase.TREATMENT);
treatmentsListView.setAdapter(treatmentsDataAdapter);
setListViewHeightBasedOnChildren(treatmentsListView);
tempsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL), PluginBase.TEMPBASAL);
tempsListView.setAdapter(tempsDataAdapter);
setListViewHeightBasedOnChildren(tempsListView);
profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ProfileInterface.class), PluginBase.PROFILE);
profileListView.setAdapter(profileDataAdapter);
setListViewHeightBasedOnChildren(profileListView);
apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.APS), PluginBase.APS);
apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView);
if (MainApp.getSpecificPluginsList(PluginBase.APS).size() == 0)
apsLabel.setVisibility(View.GONE);
constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class), PluginBase.CONSTRAINTS);
constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView);
generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsList(PluginBase.GENERAL), PluginBase.GENERAL);
generalListView.setAdapter(generalDataAdapter);
setListViewHeightBasedOnChildren(generalListView);
}
/*
* PluginBase interface
*/
@Override
public int getType() {
return PluginBase.GENERAL;
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.configbuilder);
}
@Override
public boolean isEnabled(int type) {
return true;
}
@Override
public boolean isVisibleInTabs(int type) {
return true;
}
@Override
public boolean canBeHidden(int type) {
return false;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
// Always enabled
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
// Always visible
}
public static ConfigBuilderFragment newInstance() {
ConfigBuilderFragment fragment = new ConfigBuilderFragment();
return fragment;
}
/*
* Pump interface
*
* Config builder return itself as a pump and check constraints before it passes command to pump driver
*/
@Override
public boolean isTempBasalInProgress() {
return activePump.isTempBasalInProgress();
}
@Override
public boolean isExtendedBoluslInProgress() {
return activePump.isExtendedBoluslInProgress();
}
@Override
public void setNewBasalProfile(NSProfile profile) {
activePump.setNewBasalProfile(profile);
}
@Override
public double getBaseBasalRate() {
return activePump.getBaseBasalRate();
}
@Override
public double getTempBasalAbsoluteRate() {
return activePump.getTempBasalAbsoluteRate();
}
@Override
public double getTempBasalRemainingMinutes() {
return activePump.getTempBasalRemainingMinutes();
}
@Override
public TempBasal getTempBasal(Date time) {
return activePump.getTempBasal(time);
}
@Override
public TempBasal getTempBasal() {
return activePump.getTempBasal();
}
@Override
public TempBasal getExtendedBolus() {
return activePump.getExtendedBolus();
}
/*
{
"_id": {
"$oid": "5789fea07ef0c37deb388240"
},
"boluscalc": {
"profile": "Posunuta snidane",
"eventTime": "2016-07-16T09:30:14.139Z",
"targetBGLow": "5.6",
"targetBGHigh": "5.6",
"isf": "17",
"ic": "26",
"iob": "0.89",
"cob": "0",
"insulincob": "0",
"bg": "3.6",
"insulinbg": "-0.12",
"bgdiff": "-2",
"carbs": "42",
"gi": "2",
"insulincarbs": "1.62",
"othercorrection": "0",
"insulin": "0.6000000000000001",
"roundingcorrection": "-0.009999999999999898",
"carbsneeded": "0"
},
"enteredBy": "",
"eventType": "Bolus Wizard",
"glucose": 3.6,
"glucoseType": "Sensor",
"units": "mmol",
"carbs": 42,
"insulin": 0.6,
"created_at": "2016-07-16T09:30:12.783Z"
}
*/
public PumpEnactResult deliverTreatmentFromBolusWizard(Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatmentFromBolusWizard insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult deliverTreatment(Double insulin, Integer carbs) {
insulin = applyBolusConstraints(insulin);
carbs = applyCarbsConstraints(carbs);
PumpEnactResult result = activePump.deliverTreatment(insulin, carbs);
if (Config.logCongigBuilderActions)
log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered);
if (result.success) {
Treatment t = new Treatment();
t.insulin = result.bolusDelivered;
t.carbs = (double) result.carbsDelivered;
t.created_at = new Date();
try {
MainApp.getDbHelper().getDaoTreatments().create(t);
} catch (SQLException e) {
e.printStackTrace();
}
t.setTimeIndex(t.getTimeIndex());
t.sendToNSClient();
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
/**
* apply constraints, set temp based on absolute valus and expecting absolute result
*
* @param absoluteRate
* @param durationInMinutes
* @return
*/
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
Double rateAfterConstraints = applyBasalConstraints(absoluteRate);
PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalAbsolute rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
if (result.isPercent) {
uploadTempBasalStartPercent(result.percent, result.duration);
} else {
uploadTempBasalStartAbsolute(result.absolute, result.duration);
}
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
/**
* apply constraints, set temp based on percent and expecting result in percent
*
* @param percent 0 ... 100 ...
* @param durationInMinutes
* @return result
*/
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
Integer percentAfterConstraints = applyBasalConstraints(percent);
PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalStartPercent(result.percent, result.duration);
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
Double rateAfterConstraints = applyBolusConstraints(insulin);
PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setExtendedBolus rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadExtendedBolus(result.bolusDelivered, result.duration);
MainApp.bus().post(new EventTreatmentChange());
}
return result;
}
@Override
public PumpEnactResult cancelTempBasal() {
PumpEnactResult result = activePump.cancelTempBasal();
if (Config.logCongigBuilderActions)
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
if (result.enacted && result.success) {
uploadTempBasalEnd();
MainApp.bus().post(new EventTempBasalChange());
}
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = activePump.cancelExtendedBolus();
if (Config.logCongigBuilderActions)
log.debug("cancelExtendedBolus success: " + result.success + " enacted: " + result.enacted);
return result;
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
*
* @param request
* @return
*/
public PumpEnactResult applyAPSRequest(APSResult request) {
request.rate = applyBasalConstraints(request.rate);
PumpEnactResult result;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString());
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - getBaseBasalRate()) < 0.1) {
if (isTempBasalInProgress()) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()");
result = cancelTempBasal();
} else {
result = new PumpEnactResult();
result.absolute = request.rate;
result.duration = 0;
result.enacted = false;
result.comment = "Basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
}
} else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRate()) < 0.1) {
result = new PumpEnactResult();
result.absolute = getTempBasalAbsoluteRate();
result.duration = activePump.getTempBasal().getPlannedRemainingMinutes();
result.enacted = false;
result.comment = "Temp basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly");
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()");
result = setTempBasalAbsolute(request.rate, request.duration);
}
return result;
}
@Nullable
@Override
public JSONObject getJSONStatus() {
if (activePump != null)
return activePump.getJSONStatus();
else return null;
}
@Override
public String deviceID() {
if (activePump != null)
return activePump.deviceID();
else return "Unknown";
}
/*
* ConfigBuilderFragment code
*/
private class PluginCustomAdapter extends ArrayAdapter<PluginBase> {
private ArrayList<PluginBase> pluginList;
final private int type;
public PluginCustomAdapter(Context context, int textViewResourceId,
ArrayList<PluginBase> pluginList, int type) {
super(context, textViewResourceId, pluginList);
this.pluginList = new ArrayList<PluginBase>();
this.pluginList.addAll(pluginList);
this.type = type;
}
private class PluginViewHolder {
TextView name;
CheckBox checkboxEnabled;
CheckBox checkboxVisible;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PluginViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.configbuilder_simpleitem, null);
holder = new PluginViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.configbuilder_simpleitem_name);
holder.checkboxEnabled = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxenabled);
holder.checkboxVisible = (CheckBox) convertView.findViewById(R.id.configbuilder_simpleitem_checkboxvisible);
convertView.setTag(holder);
holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentEnabled(type, cb.isChecked());
plugin.setFragmentVisible(type, cb.isChecked());
onEnabledCategoryChanged(plugin, type);
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
holder.checkboxVisible.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
PluginBase plugin = (PluginBase) cb.getTag();
plugin.setFragmentVisible(type, cb.isChecked());
storeSettings();
MainApp.bus().post(new EventRefreshGui());
}
});
} else {
holder = (PluginViewHolder) convertView.getTag();
}
PluginBase plugin = pluginList.get(position);
holder.name.setText(plugin.getName());
holder.checkboxEnabled.setChecked(plugin.isEnabled(type));
holder.checkboxVisible.setChecked(plugin.isVisibleInTabs(type));
holder.name.setTag(plugin);
holder.checkboxEnabled.setTag(plugin);
holder.checkboxVisible.setTag(plugin);
if (!plugin.canBeHidden(type)) {
holder.checkboxEnabled.setEnabled(false);
holder.checkboxVisible.setEnabled(false);
}
int type = plugin.getType();
// Force enabled if there is only one plugin
if (type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.TEMPBASAL || type == PluginBase.PROFILE)
if (pluginList.size() < 2)
holder.checkboxEnabled.setEnabled(false);
// Constraints cannot be disabled
if (type == PluginBase.CONSTRAINTS)
holder.checkboxEnabled.setEnabled(false);
// Hide disabled profiles by default
if (type == PluginBase.PROFILE) {
if (!plugin.isEnabled(type)) {
holder.checkboxVisible.setEnabled(false);
holder.checkboxVisible.setChecked(false);
} else {
holder.checkboxVisible.setEnabled(true);
}
}
return convertView;
}
}
public BgSourceInterface getActiveBgSource() {
return activeBgSource;
}
public PumpInterface getActivePump() {
return this;
}
@Nullable
public ProfileInterface getActiveProfile() {
return activeProfile;
}
public TreatmentsInterface getActiveTreatments() {
return activeTreatments;
}
public TempBasalsInterface getActiveTempBasals() {
return activeTempBasals;
}
public LoopFragment getActiveLoop() {
return activeLoop;
}
void onEnabledCategoryChanged(PluginBase changedPlugin, int type) {
int category = changedPlugin.getType();
ArrayList<PluginBase> pluginsInCategory = null;
switch (category) {
// Multiple selection allowed
case PluginBase.APS:
case PluginBase.GENERAL:
case PluginBase.CONSTRAINTS:
case PluginBase.LOOP:
break;
// Single selection allowed
case PluginBase.PROFILE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
case PluginBase.BGSOURCE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
case PluginBase.TEMPBASAL:
case PluginBase.TREATMENT:
case PluginBase.PUMP:
pluginsInCategory = MainApp.getSpecificPluginsList(category);
break;
}
if (pluginsInCategory != null) {
boolean newSelection = changedPlugin.isEnabled(type);
if (newSelection) { // new plugin selected -> disable others
for (PluginBase p : pluginsInCategory) {
if (p.getName().equals(changedPlugin.getName())) {
// this is new selected
} else {
p.setFragmentEnabled(type, false);
p.setFragmentVisible(type, false);
}
}
} else { // enable first plugin in list
pluginsInCategory.get(0).setFragmentEnabled(type, true);
}
setViews();
}
}
private void verifySelectionInCategories() {
ArrayList<PluginBase> pluginsInCategory;
// PluginBase.PROFILE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
activeProfile = (ProfileInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PROFILE);
if (Config.logConfigBuilder)
log.debug("Selected profile interface: " + ((PluginBase) activeProfile).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeProfile).getName())) {
p.setFragmentVisible(PluginBase.PROFILE, false);
}
}
// PluginBase.BGSOURCE
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
activeBgSource = (BgSourceInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.BGSOURCE);
if (Config.logConfigBuilder)
log.debug("Selected bgSource interface: " + ((PluginBase) activeBgSource).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeBgSource).getName())) {
p.setFragmentVisible(PluginBase.BGSOURCE, false);
}
}
// PluginBase.PUMP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP);
if (Config.logConfigBuilder)
log.debug("Selected pump interface: " + ((PluginBase) activePump).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activePump).getName())) {
p.setFragmentVisible(PluginBase.PUMP, false);
}
}
// PluginBase.LOOP
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.LOOP);
activeLoop = (LoopFragment) getTheOneEnabledInArray(pluginsInCategory, PluginBase.LOOP);
if (activeLoop != null) {
if (Config.logConfigBuilder)
log.debug("Selected loop interface: " + activeLoop.getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(activeLoop.getName())) {
p.setFragmentVisible(PluginBase.LOOP, false);
}
}
}
// PluginBase.TEMPBASAL
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TEMPBASAL);
activeTempBasals = (TempBasalsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TEMPBASAL);
if (Config.logConfigBuilder)
log.debug("Selected tempbasal interface: " + ((PluginBase) activeTempBasals).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTempBasals).getName())) {
p.setFragmentVisible(PluginBase.TEMPBASAL, false);
}
}
// PluginBase.TREATMENT
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TREATMENT);
activeTreatments = (TreatmentsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TREATMENT);
if (Config.logConfigBuilder)
log.debug("Selected treatment interface: " + ((PluginBase) activeTreatments).getName());
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(((PluginBase) activeTreatments).getName())) {
p.setFragmentVisible(PluginBase.TREATMENT, false);
}
}
}
@Nullable
private PluginBase getTheOneEnabledInArray(ArrayList<PluginBase> pluginsInCategory, int type) {
PluginBase found = null;
for (PluginBase p : pluginsInCategory) {
if (p.isEnabled(type) && found == null) {
found = p;
continue;
} else if (p.isEnabled(type)) {
// set others disabled
p.setFragmentEnabled(type, false);
}
}
// If none enabled, enable first one
if (found == null && pluginsInCategory.size() > 0)
found = pluginsInCategory.get(0);
return found;
}
private void storeSettings() {
if (pluginList != null) {
if (Config.logPrefsChange)
log.debug("Storing settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
editor.putBoolean(settingEnabled, p.isEnabled(type));
editor.putBoolean(settingVisible, p.isVisibleInTabs(type));
}
}
editor.commit();
verifySelectionInCategories();
}
}
private void loadSettings() {
if (Config.logPrefsChange)
log.debug("Loading stored settings");
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
for (int type = 1; type < PluginBase.LAST; type++) {
for (PluginBase p : pluginList) {
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
if (SP.contains(settingEnabled))
p.setFragmentEnabled(type, SP.getBoolean(settingEnabled, true));
if (SP.contains(settingVisible))
p.setFragmentVisible(type, SP.getBoolean(settingVisible, true));
}
}
verifySelectionInCategories();
}
/****
* Method for Setting the Height of the ListView dynamically.
* *** Hack to fix the issue of not showing all the items of the ListView
* *** when placed inside a ScrollView
****/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* Constraints interface
**/
@Override
public boolean isLoopEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isLoopEnabled();
}
return result;
}
@Override
public boolean isClosedModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isClosedModeEnabled();
}
return result;
}
@Override
public boolean isAutosensModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAutosensModeEnabled();
}
return result;
}
@Override
public boolean isAMAModeEnabled() {
boolean result = true;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
result = result && constrain.isAMAModeEnabled();
}
return result;
}
@Override
public Double applyBasalConstraints(Double absoluteRate) {
Double rateAfterConstrain = absoluteRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(absoluteRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Integer applyBasalConstraints(Integer percentRate) {
Integer rateAfterConstrain = percentRate;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
rateAfterConstrain = Math.min(constrain.applyBasalConstraints(percentRate), rateAfterConstrain);
}
return rateAfterConstrain;
}
@Override
public Double applyBolusConstraints(Double insulin) {
Double insulinAfterConstrain = insulin;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
insulinAfterConstrain = Math.min(constrain.applyBolusConstraints(insulin), insulinAfterConstrain);
}
return insulinAfterConstrain;
}
@Override
public Integer applyCarbsConstraints(Integer carbs) {
Integer carbsAfterConstrain = carbs;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
carbsAfterConstrain = Math.min(constrain.applyCarbsConstraints(carbs), carbsAfterConstrain);
}
return carbsAfterConstrain;
}
@Override
public Double applyMaxIOBConstraints(Double maxIob) {
Double maxIobAfterConstrain = maxIob;
ArrayList<PluginBase> constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
maxIobAfterConstrain = Math.min(constrain.applyMaxIOBConstraints(maxIob), maxIobAfterConstrain);
}
return maxIobAfterConstrain;
}
@Subscribe
public void onStatusEvent(final EventNewBG ev) {
// Give some time to Loop
try {
Thread.sleep(120 * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
// if status not uploaded, upload pump status only
if (new Date().getTime() - lastDeviceStatusUpload.getTime() > 120 * 1000L) {
uploadDeviceStatus();
}
}
public static void uploadTempBasalStartAbsolute(Double absolute, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("absolute", absolute);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public static void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false);
if (useAbsolute) {
double absolute = MainApp.getConfigBuilder().getActivePump().getBaseBasalRate() * percent / 100d;
uploadTempBasalStartAbsolute(absolute, durationInMinutes);
} else {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("duration", durationInMinutes);
data.put("percent", percent - 100);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
}
} catch (JSONException e) {
}
}
public static void uploadTempBasalEnd() {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Temp Basal");
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public static void uploadExtendedBolus(Double insulin, double durationInMinutes) {
try {
Context context = MainApp.instance().getApplicationContext();
JSONObject data = new JSONObject();
data.put("eventType", "Combo Bolus");
data.put("duration", durationInMinutes);
data.put("splitNow", 0);
data.put("splitExt", 100);
data.put("enteredinsulin", insulin);
data.put("relative", insulin);
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("enteredBy", MainApp.instance().getString(R.string.app_name));
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
} catch (JSONException e) {
}
}
public void uploadDeviceStatus() {
DeviceStatus deviceStatus = new DeviceStatus();
try {
LoopFragment.LastRun lastRun = LoopFragment.lastRun;
if (lastRun != null && lastRun.lastAPSRun.getTime() > new Date().getTime() - 60 * 1000L) {
// do not send if result is older than 1 min
APSResult apsResult = lastRun.request;
apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun));
deviceStatus.suggested = apsResult.json();
if (lastRun.request instanceof DetermineBasalResult) {
DetermineBasalResult result = (DetermineBasalResult) lastRun.request;
deviceStatus.iob = result.iob.json();
deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun));
}
if (lastRun.setByPump != null && lastRun.setByPump.enacted) { // enacted
deviceStatus.enacted = lastRun.request.json();
deviceStatus.enacted.put("rate", lastRun.setByPump.json().get("rate"));
deviceStatus.enacted.put("duration", lastRun.setByPump.json().get("duration"));
deviceStatus.enacted.put("recieved", true);
JSONObject requested = new JSONObject();
requested.put("duration", lastRun.request.duration);
requested.put("rate", lastRun.request.rate);
requested.put("temp", "absolute");
deviceStatus.enacted.put("requested", requested);
}
}
if (getActivePump() != null) {
deviceStatus.device = "openaps://" + getActivePump().deviceID();
deviceStatus.pump = getActivePump().getJSONStatus();
deviceStatus.created_at = DateUtil.toISOString(new Date());
deviceStatus.sendToNSClient();
lastDeviceStatusUpload = new Date();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void uploadBolusWizardRecord(Treatment t, double glucose, String glucoseType, int carbTime, JSONObject boluscalc) {
JSONObject data = new JSONObject();
try {
data.put("eventType", "Bolus Wizard");
if (t.insulin != 0d) data.put("insulin", t.insulin);
if (t.carbs != 0d) data.put("carbs", t.carbs.intValue());
data.put("created_at", DateUtil.toISOString(t.created_at));
data.put("timeIndex", t.timeIndex);
if (glucose != 0d) data.put("glucose", glucose);
data.put("glucoseType", glucoseType);
data.put("boluscalc", boluscalc);
if (carbTime != 0) data.put("preBolus", carbTime);
} catch (JSONException e) {
e.printStackTrace();
}
uploadCareportalEntryToNS(data);
}
public static void uploadCareportalEntryToNS(JSONObject data) {
try {
if (data.has("preBolus") && data.has("carbs")) {
JSONObject prebolus = new JSONObject();
prebolus.put("carbs", data.get("carbs"));
data.remove("carbs");
prebolus.put("eventType", data.get("eventType"));
if (data.has("enteredBy")) prebolus.put("enteredBy", data.get("enteredBy"));
if (data.has("notes")) prebolus.put("notes", data.get("notes"));
long mills = DateUtil.fromISODateString(data.getString("created_at")).getTime();
Date preBolusDate = new Date(mills + data.getInt("preBolus") * 60000L);
prebolus.put("created_at", DateUtil.toISOString(preBolusDate));
uploadCareportalEntryToNS(prebolus);
}
Context context = MainApp.instance().getApplicationContext();
Bundle bundle = new Bundle();
bundle.putString("action", "dbAdd");
bundle.putString("collection", "treatments");
bundle.putString("data", data.toString());
Intent intent = new Intent(Intents.ACTION_DATABASE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString(), NewExtendedBolusDialog.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| config builder code cleanup
| app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java | config builder code cleanup | <ide><path>pp/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java
<ide> import android.content.Context;
<ide> import android.content.Intent;
<ide> import android.content.SharedPreferences;
<del>import android.content.pm.ResolveInfo;
<ide> import android.graphics.Color;
<ide> import android.os.Bundle;
<ide> import android.preference.PreferenceManager;
<ide>
<ide> import java.sql.SQLException;
<ide> import java.util.ArrayList;
<del>import java.util.Calendar;
<ide> import java.util.Date;
<del>import java.util.List;
<ide>
<ide> import info.nightscout.androidaps.Config;
<del>import info.nightscout.androidaps.MainActivity;
<ide> import info.nightscout.androidaps.MainApp;
<ide> import info.nightscout.androidaps.R;
<ide> import info.nightscout.androidaps.Services.Intents;
<ide> }
<ide>
<ide> public static ConfigBuilderFragment newInstance() {
<del> ConfigBuilderFragment fragment = new ConfigBuilderFragment();
<del> return fragment;
<add> return new ConfigBuilderFragment();
<ide> }
<ide>
<ide>
<ide> for (PluginBase p : pluginsInCategory) {
<ide> if (p.isEnabled(type) && found == null) {
<ide> found = p;
<del> continue;
<ide> } else if (p.isEnabled(type)) {
<ide> // set others disabled
<ide> p.setFragmentEnabled(type, false);
<ide> editor.putBoolean(settingVisible, p.isVisibleInTabs(type));
<ide> }
<ide> }
<del> editor.commit();
<add> editor.apply();
<ide> verifySelectionInCategories();
<ide> }
<ide> }
<ide> context.sendBroadcast(intent);
<ide> DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
<ide> } catch (JSONException e) {
<add> e.printStackTrace();
<ide> }
<ide> }
<ide>
<ide> DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
<ide> }
<ide> } catch (JSONException e) {
<add> e.printStackTrace();
<ide> }
<ide> }
<ide>
<ide> context.sendBroadcast(intent);
<ide> DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
<ide> } catch (JSONException e) {
<add> e.printStackTrace();
<ide> }
<ide> }
<ide>
<ide> context.sendBroadcast(intent);
<ide> DbLogger.dbAdd(intent, data.toString(), ConfigBuilderFragment.class);
<ide> } catch (JSONException e) {
<add> e.printStackTrace();
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | c283af4884c4ac9996e23b4d6c776cd426a66148 | 0 | jdbi/jdbi,hgschmie/jdbi,hgschmie/jdbi,jdbi/jdbi,hgschmie/jdbi,jdbi/jdbi | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jdbi.v3.sqlobject.statement.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.extension.HandleSupplier;
import org.jdbi.v3.core.generic.GenericTypes;
import org.jdbi.v3.core.internal.IterableLike;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.result.ResultIterable;
import org.jdbi.v3.core.result.ResultIterator;
import org.jdbi.v3.core.statement.PreparedBatch;
import org.jdbi.v3.core.statement.StatementContext;
import org.jdbi.v3.core.statement.UnableToCreateStatementException;
import org.jdbi.v3.sqlobject.SingleValue;
import org.jdbi.v3.sqlobject.UnableToCreateSqlObjectException;
import org.jdbi.v3.sqlobject.statement.BatchChunkSize;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlBatch;
import org.jdbi.v3.sqlobject.statement.UseRowMapper;
import org.jdbi.v3.sqlobject.statement.UseRowReducer;
public class SqlBatchHandler extends CustomizingStatementHandler<PreparedBatch> {
private final SqlBatch sqlBatch;
private final SqlBatchHandler.ChunkSizeFunction batchChunkSize;
private final Function<PreparedBatch, ResultIterator<?>> batchIntermediate;
private final ResultReturner magic;
public SqlBatchHandler(Class<?> sqlObjectType, Method method) {
super(sqlObjectType, method);
if (method.isAnnotationPresent(UseRowReducer.class)) {
throw new UnsupportedOperationException("Cannot declare @UseRowReducer on a @SqlUpdate method.");
}
this.sqlBatch = method.getAnnotation(SqlBatch.class);
this.batchChunkSize = determineBatchChunkSize(sqlObjectType, method);
final GetGeneratedKeys getGeneratedKeys = method.getAnnotation(GetGeneratedKeys.class);
if (getGeneratedKeys == null) {
if (!returnTypeIsValid(method.getReturnType())) {
throw new UnableToCreateSqlObjectException(invalidReturnTypeMessage(method));
}
Function<PreparedBatch, ResultIterator<?>> modCounts = PreparedBatch::executeAndGetModCount;
batchIntermediate = method.getReturnType().equals(boolean[].class)
? mapToBoolean(modCounts)
: modCounts;
magic = ResultReturner.forOptionalReturn(sqlObjectType, method);
} else {
String[] columnNames = getGeneratedKeys.value();
magic = ResultReturner.forMethod(sqlObjectType, method);
if (method.isAnnotationPresent(UseRowMapper.class)) {
RowMapper<?> mapper = rowMapperFor(method.getAnnotation(UseRowMapper.class));
batchIntermediate = batch -> batch.executeAndReturnGeneratedKeys(columnNames)
.map(mapper)
.iterator();
} else {
batchIntermediate = batch -> batch.executeAndReturnGeneratedKeys(columnNames)
.mapTo(magic.elementType(batch.getConfig()))
.iterator();
}
}
}
@Override
public void warm(ConfigRegistry config) {
super.warm(config);
magic.warm(config);
}
private Function<PreparedBatch, ResultIterator<?>> mapToBoolean(Function<PreparedBatch, ResultIterator<?>> modCounts) {
return modCounts.andThen(iterator -> new ResultIterator<Boolean>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Boolean next() {
return ((Integer) iterator.next()) > 0;
}
@Override
public void close() {
iterator.close();
}
@Override
public StatementContext getContext() {
return iterator.getContext();
}
});
}
private SqlBatchHandler.ChunkSizeFunction determineBatchChunkSize(Class<?> sqlObjectType, Method method) {
// this next big if chain determines the batch chunk size. It looks from most specific
// scope to least, that is: as an argument, then on the method, then on the class,
// then default to Integer.MAX_VALUE
int batchChunkSizeParameterIndex = indexOfBatchChunkSizeParameter(method);
if (batchChunkSizeParameterIndex >= 0) {
return new ParamBasedChunkSizeFunction(batchChunkSizeParameterIndex);
} else if (method.isAnnotationPresent(BatchChunkSize.class)) {
final int size = method.getAnnotation(BatchChunkSize.class).value();
if (size <= 0) {
throw new IllegalArgumentException("Batch chunk size must be >= 0");
}
return new ConstantChunkSizeFunction(size);
} else if (sqlObjectType.isAnnotationPresent(BatchChunkSize.class)) {
final int size = sqlObjectType.getAnnotation(BatchChunkSize.class).value();
return new ConstantChunkSizeFunction(size);
} else {
return new ConstantChunkSizeFunction(Integer.MAX_VALUE);
}
}
private int indexOfBatchChunkSizeParameter(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
return IntStream.range(0, parameterAnnotations.length)
.filter(i -> Stream.of(parameterAnnotations[i]).anyMatch(BatchChunkSize.class::isInstance))
.findFirst()
.orElse(-1);
}
@Override
PreparedBatch createStatement(Handle handle, String locatedSql) {
return handle.prepareBatch(locatedSql);
}
@Override
void configureReturner(PreparedBatch stmt, SqlObjectStatementConfiguration cfg) {}
@Override
Type getParameterType(Parameter parameter) {
Type type = super.getParameterType(parameter);
if (!parameter.isAnnotationPresent(SingleValue.class)) {
Class<?> erasedType = GenericTypes.getErasedType(type);
if (Iterable.class.isAssignableFrom(erasedType)) {
return GenericTypes.findGenericParameter(type, Iterable.class).get();
} else if (Iterator.class.isAssignableFrom(erasedType)) {
return GenericTypes.findGenericParameter(type, Iterator.class).get();
} else if (GenericTypes.isArray(type)) {
return ((Class<?>) type).getComponentType();
}
}
return type;
}
@Override
@SuppressWarnings("PMD.ExcessiveMethodLength")
public Object invoke(Object target, Object[] args, HandleSupplier h) {
final Handle handle = h.getHandle();
final String sql = locateSql(handle);
final int chunkSize = batchChunkSize.call(args);
final Iterator<Object[]> batchArgs = zipArgs(getMethod(), args);
final class BatchChunkIterator implements ResultIterator<Object> {
private ResultIterator<?> batchResult = null;
private boolean closed = false;
BatchChunkIterator() {
if (batchArgs.hasNext()) {
// if arguments are present, preload the next result chunk
batchResult = loadChunk();
}
}
private ResultIterator<?> loadChunk() {
// execute a single chunk and buffer
List<Object[]> currArgs = new ArrayList<>();
for (int i = 0; i < chunkSize && batchArgs.hasNext(); i++) {
currArgs.add(batchArgs.next());
}
Supplier<PreparedBatch> preparedBatchSupplier = () -> createPreparedBatch(handle, sql, currArgs);
return executeBatch(handle, preparedBatchSupplier);
}
private PreparedBatch createPreparedBatch(Handle handle, String sql, List<Object[]> currArgs) {
PreparedBatch batch = handle.prepareBatch(sql);
for (Object[] currArg : currArgs) {
applyCustomizers(batch, currArg);
batch.add();
}
return batch;
}
@Override
public boolean hasNext() {
if (closed) {
throw new IllegalStateException("closed");
}
// first, any elements already buffered?
if (batchResult != null) {
if (batchResult.hasNext()) {
return true;
}
// no more in this chunk, release resources
batchResult.close();
}
// more chunks?
if (batchArgs.hasNext()) {
// preload the next result chunk
batchResult = loadChunk();
// recurse to ensure we actually got elements
return hasNext();
}
return false;
}
@Override
public Object next() {
if (closed) {
throw new IllegalStateException("closed");
}
if (!hasNext()) {
throw new NoSuchElementException();
}
return batchResult.next();
}
@Override
public StatementContext getContext() {
return batchResult.getContext();
}
@Override
public void close() {
closed = true;
batchResult.close();
}
}
ResultIterator<Object> result;
if (batchArgs.hasNext()) {
result = new BatchChunkIterator();
} else {
// only created to get access to the context.
PreparedBatch dummy = handle.prepareBatch(sql);
result = new ResultIterator<Object>() {
@Override
public void close() {
// no op
}
@Override
public StatementContext getContext() {
return dummy.getContext();
}
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
};
}
ResultIterable<Object> iterable = ResultIterable.of(result);
return magic.mappedResult(iterable, result.getContext());
}
private Iterator<Object[]> zipArgs(Method method, Object[] args) {
boolean foundIterator = false;
List<Iterator<?>> extras = new ArrayList<>();
for (int paramIdx = 0; paramIdx < method.getParameterCount(); paramIdx++) {
final boolean singleValue = method.getParameters()[paramIdx].isAnnotationPresent(SingleValue.class);
final Object arg = args[paramIdx];
if (!singleValue && IterableLike.isIterable(arg)) {
extras.add(IterableLike.of(arg));
foundIterator = true;
} else {
extras.add(Stream.generate(() -> arg).iterator());
}
}
if (!foundIterator) {
throw new UnableToCreateStatementException("@SqlBatch method has no Iterable or array parameters,"
+ " did you mean @SqlQuery?", null, null);
}
return new Iterator<Object[]>() {
@Override
public boolean hasNext() {
for (Iterator<?> extra : extras) {
if (!extra.hasNext()) {
return false;
}
}
return true;
}
@Override
public Object[] next() {
final Object[] argsArray = new Object[args.length];
for (int i = 0; i < extras.size(); i++) {
argsArray[i] = extras.get(i).next();
}
return argsArray;
}
};
}
private ResultIterator<?> executeBatch(final Handle handle, final Supplier<PreparedBatch> preparedBatchSupplier) {
if (!handle.isInTransaction() && sqlBatch.transactional()) {
// it is safe to use same prepared preparedBatchSupplier as the inTransaction passes in the same
// Handle instance.
return handle.inTransaction(c -> batchIntermediate.apply(preparedBatchSupplier.get()));
} else {
return batchIntermediate.apply(preparedBatchSupplier.get());
}
}
private static boolean returnTypeIsValid(Class<?> type) {
if (type.equals(Void.TYPE)) {
return true;
}
if (type.isArray()) {
Class<?> componentType = type.getComponentType();
return componentType.equals(Integer.TYPE) || componentType.equals(Boolean.TYPE);
}
return false;
}
private static String invalidReturnTypeMessage(Method method) {
return method.getDeclaringClass() + "." + method.getName()
+ " method is annotated with @SqlBatch so should return void, int[], or boolean[] but is returning: "
+ method.getReturnType();
}
private interface ChunkSizeFunction {
int call(Object[] args);
}
private static class ConstantChunkSizeFunction implements SqlBatchHandler.ChunkSizeFunction {
private final int value;
ConstantChunkSizeFunction(int value) {
this.value = value;
}
@Override
public int call(Object[] args) {
return value;
}
}
private static class ParamBasedChunkSizeFunction implements SqlBatchHandler.ChunkSizeFunction {
private final int index;
ParamBasedChunkSizeFunction(int index) {
this.index = index;
}
@Override
public int call(Object[] args) {
return (Integer) args[index];
}
}
}
| sqlobject/src/main/java/org/jdbi/v3/sqlobject/statement/internal/SqlBatchHandler.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jdbi.v3.sqlobject.statement.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.extension.HandleSupplier;
import org.jdbi.v3.core.generic.GenericTypes;
import org.jdbi.v3.core.internal.IterableLike;
import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.result.ResultIterable;
import org.jdbi.v3.core.result.ResultIterator;
import org.jdbi.v3.core.statement.PreparedBatch;
import org.jdbi.v3.core.statement.StatementContext;
import org.jdbi.v3.core.statement.UnableToCreateStatementException;
import org.jdbi.v3.sqlobject.SingleValue;
import org.jdbi.v3.sqlobject.UnableToCreateSqlObjectException;
import org.jdbi.v3.sqlobject.statement.BatchChunkSize;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlBatch;
import org.jdbi.v3.sqlobject.statement.UseRowMapper;
import org.jdbi.v3.sqlobject.statement.UseRowReducer;
public class SqlBatchHandler extends CustomizingStatementHandler<PreparedBatch> {
private final SqlBatch sqlBatch;
private final SqlBatchHandler.ChunkSizeFunction batchChunkSize;
private final Function<PreparedBatch, ResultIterator<?>> batchIntermediate;
private final ResultReturner magic;
public SqlBatchHandler(Class<?> sqlObjectType, Method method) {
super(sqlObjectType, method);
if (method.isAnnotationPresent(UseRowReducer.class)) {
throw new UnsupportedOperationException("Cannot declare @UseRowReducer on a @SqlUpdate method.");
}
this.sqlBatch = method.getAnnotation(SqlBatch.class);
this.batchChunkSize = determineBatchChunkSize(sqlObjectType, method);
final GetGeneratedKeys getGeneratedKeys = method.getAnnotation(GetGeneratedKeys.class);
if (getGeneratedKeys == null) {
if (!returnTypeIsValid(method.getReturnType())) {
throw new UnableToCreateSqlObjectException(invalidReturnTypeMessage(method));
}
Function<PreparedBatch, ResultIterator<?>> modCounts = PreparedBatch::executeAndGetModCount;
batchIntermediate = method.getReturnType().equals(boolean[].class)
? mapToBoolean(modCounts)
: modCounts;
magic = ResultReturner.forOptionalReturn(sqlObjectType, method);
} else {
String[] columnNames = getGeneratedKeys.value();
magic = ResultReturner.forMethod(sqlObjectType, method);
if (method.isAnnotationPresent(UseRowMapper.class)) {
RowMapper<?> mapper = rowMapperFor(method.getAnnotation(UseRowMapper.class));
batchIntermediate = batch -> batch.executeAndReturnGeneratedKeys(columnNames)
.map(mapper)
.iterator();
} else {
batchIntermediate = batch -> batch.executeAndReturnGeneratedKeys(columnNames)
.mapTo(magic.elementType(batch.getConfig()))
.iterator();
}
}
}
@Override
public void warm(ConfigRegistry config) {
super.warm(config);
magic.warm(config);
}
private Function<PreparedBatch, ResultIterator<?>> mapToBoolean(Function<PreparedBatch, ResultIterator<?>> modCounts) {
return modCounts.andThen(iterator -> new ResultIterator<Boolean>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Boolean next() {
return ((Integer) iterator.next()) > 0;
}
@Override
public void close() {
iterator.close();
}
@Override
public StatementContext getContext() {
return iterator.getContext();
}
});
}
private SqlBatchHandler.ChunkSizeFunction determineBatchChunkSize(Class<?> sqlObjectType, Method method) {
// this next big if chain determines the batch chunk size. It looks from most specific
// scope to least, that is: as an argument, then on the method, then on the class,
// then default to Integer.MAX_VALUE
int batchChunkSizeParameterIndex = indexOfBatchChunkSizeParameter(method);
if (batchChunkSizeParameterIndex >= 0) {
return new ParamBasedChunkSizeFunction(batchChunkSizeParameterIndex);
} else if (method.isAnnotationPresent(BatchChunkSize.class)) {
final int size = method.getAnnotation(BatchChunkSize.class).value();
if (size <= 0) {
throw new IllegalArgumentException("Batch chunk size must be >= 0");
}
return new ConstantChunkSizeFunction(size);
} else if (sqlObjectType.isAnnotationPresent(BatchChunkSize.class)) {
final int size = sqlObjectType.getAnnotation(BatchChunkSize.class).value();
return new ConstantChunkSizeFunction(size);
} else {
return new ConstantChunkSizeFunction(Integer.MAX_VALUE);
}
}
private int indexOfBatchChunkSizeParameter(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
return IntStream.range(0, parameterAnnotations.length)
.filter(i -> Stream.of(parameterAnnotations[i]).anyMatch(BatchChunkSize.class::isInstance))
.findFirst()
.orElse(-1);
}
@Override
PreparedBatch createStatement(Handle handle, String locatedSql) {
return handle.prepareBatch(locatedSql);
}
@Override
void configureReturner(PreparedBatch stmt, SqlObjectStatementConfiguration cfg) {}
@Override
Type getParameterType(Parameter parameter) {
Type type = super.getParameterType(parameter);
if (!parameter.isAnnotationPresent(SingleValue.class)) {
Class<?> erasedType = GenericTypes.getErasedType(type);
if (Iterable.class.isAssignableFrom(erasedType)) {
return GenericTypes.findGenericParameter(type, Iterable.class).get();
} else if (Iterator.class.isAssignableFrom(erasedType)) {
return GenericTypes.findGenericParameter(type, Iterator.class).get();
} else if (GenericTypes.isArray(type)) {
return ((Class<?>) type).getComponentType();
}
}
return type;
}
@Override
@SuppressWarnings("PMD.ExcessiveMethodLength")
public Object invoke(Object target, Object[] args, HandleSupplier h) {
final Handle handle = h.getHandle();
final String sql = locateSql(handle);
final int chunkSize = batchChunkSize.call(args);
final Iterator<Object[]> batchArgs = zipArgs(getMethod(), args);
final class BatchChunkIterator implements ResultIterator<Object> {
private ResultIterator<?> batchResult = null;
private boolean closed = false;
BatchChunkIterator() {
if (batchArgs.hasNext()) {
// if arguments are present, preload the next result chunk
batchResult = loadChunk();
}
}
private ResultIterator<?> loadChunk() {
// execute a single chunk and buffer
List<Object[]> currArgs = new ArrayList<>();
for (int i = 0; i < chunkSize && batchArgs.hasNext(); i++) {
currArgs.add(batchArgs.next());
}
Supplier<PreparedBatch> preparedBatchSupplier = () -> createPreparedBatch(handle, sql, currArgs);
return executeBatch(handle, preparedBatchSupplier);
}
private PreparedBatch createPreparedBatch(Handle handle, String sql, List<Object[]> currArgs) {
PreparedBatch batch = handle.prepareBatch(sql);
for (Object[] currArg : currArgs) {
applyCustomizers(batch, currArg);
batch.add();
}
return batch;
}
@Override
public boolean hasNext() {
if (closed) {
throw new IllegalStateException("closed");
}
// first, any elements already buffered?
if (batchResult != null) {
if (batchResult.hasNext()) {
return true;
}
// no more in this chunk, release resources
batchResult.close();
}
// more chunks?
if (batchArgs.hasNext()) {
// preload the next result chunk
batchResult = loadChunk();
// recurse to ensure we actually got elements
return hasNext();
}
return false;
}
@Override
public Object next() {
if (closed) {
throw new IllegalStateException("closed");
}
if (!hasNext()) {
throw new NoSuchElementException();
}
return batchResult.next();
}
@Override
public StatementContext getContext() {
return batchResult.getContext();
}
@Override
public void close() {
closed = true;
batchResult.close();
}
}
ResultIterator<Object> result;
if (batchArgs.hasNext()) {
result = new BatchChunkIterator();
} else {
// only created to get access to the context.
PreparedBatch dummy = handle.prepareBatch(sql);
result = new ResultIterator<Object>() {
@Override
public void close() {
// no op
}
@Override
public StatementContext getContext() {
return dummy.getContext();
}
@Override
public boolean hasNext() {
return false;
}
@Override
public Object next() {
throw new NoSuchElementException();
}
};
}
ResultIterable<Object> iterable = ResultIterable.of(result);
return magic.mappedResult(iterable, result.getContext());
}
private Iterator<Object[]> zipArgs(Method method, Object[] args) {
boolean foundIterator = false;
List<Iterator<?>> extras = new ArrayList<>();
for (int paramIdx = 0; paramIdx < method.getParameterCount(); paramIdx++) {
final boolean singleValue = method.getParameters()[paramIdx].isAnnotationPresent(SingleValue.class);
final Object arg = args[paramIdx];
if (!singleValue && IterableLike.isIterable(arg)) {
extras.add(IterableLike.of(arg));
foundIterator = true;
} else {
extras.add(Stream.generate(() -> arg).iterator());
}
}
if (!foundIterator) {
throw new UnableToCreateStatementException("@SqlBatch method has no Iterable or array parameters,"
+ " did you mean @SqlQuery?", null, null);
}
return new Iterator<Object[]>() {
@Override
public boolean hasNext() {
for (Iterator<?> extra : extras) {
if (!extra.hasNext()) {
return false;
}
}
return true;
}
@Override
public Object[] next() {
final Object[] sharedArg = new Object[args.length];
for (int i = 0; i < extras.size(); i++) {
sharedArg[i] = extras.get(i).next();
}
return sharedArg;
}
};
}
private ResultIterator<?> executeBatch(final Handle handle, final Supplier<PreparedBatch> preparedBatchSupplier) {
if (!handle.isInTransaction() && sqlBatch.transactional()) {
// it is safe to use same prepared preparedBatchSupplier as the inTransaction passes in the same
// Handle instance.
return handle.inTransaction(c -> batchIntermediate.apply(preparedBatchSupplier.get()));
} else {
return batchIntermediate.apply(preparedBatchSupplier.get());
}
}
private static boolean returnTypeIsValid(Class<?> type) {
if (type.equals(Void.TYPE)) {
return true;
}
if (type.isArray()) {
Class<?> componentType = type.getComponentType();
return componentType.equals(Integer.TYPE) || componentType.equals(Boolean.TYPE);
}
return false;
}
private static String invalidReturnTypeMessage(Method method) {
return method.getDeclaringClass() + "." + method.getName()
+ " method is annotated with @SqlBatch so should return void, int[], or boolean[] but is returning: "
+ method.getReturnType();
}
private interface ChunkSizeFunction {
int call(Object[] args);
}
private static class ConstantChunkSizeFunction implements SqlBatchHandler.ChunkSizeFunction {
private final int value;
ConstantChunkSizeFunction(int value) {
this.value = value;
}
@Override
public int call(Object[] args) {
return value;
}
}
private static class ParamBasedChunkSizeFunction implements SqlBatchHandler.ChunkSizeFunction {
private final int index;
ParamBasedChunkSizeFunction(int index) {
this.index = index;
}
@Override
public int call(Object[] args) {
return (Integer) args[index];
}
}
}
| Rename sharedArgs to argsArray as it's initialized everytime
| sqlobject/src/main/java/org/jdbi/v3/sqlobject/statement/internal/SqlBatchHandler.java | Rename sharedArgs to argsArray as it's initialized everytime | <ide><path>qlobject/src/main/java/org/jdbi/v3/sqlobject/statement/internal/SqlBatchHandler.java
<ide>
<ide> @Override
<ide> public Object[] next() {
<del> final Object[] sharedArg = new Object[args.length];
<add> final Object[] argsArray = new Object[args.length];
<ide> for (int i = 0; i < extras.size(); i++) {
<del> sharedArg[i] = extras.get(i).next();
<del> }
<del> return sharedArg;
<add> argsArray[i] = extras.get(i).next();
<add> }
<add> return argsArray;
<ide> }
<ide> };
<ide> } |
|
Java | bsd-3-clause | d9e74de5bfdbe41336c007895212adb5cce2b40a | 0 | amesrobotics/2013robot | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.
/*----------------------------------------------------------------------------*/
package edu.ames.frc.robot;
//___
// | |_ o _ o _ _|_|_ _ __ _ o __ _ | _ _ _
// | | | | _> | _> |_| |(/_ |||(_| | | | (_ | (_|_> _>
//The main class is under control of Kolton Yager and Danial Ebling. DO NOT EDIT
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Watchdog;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotProject extends IterativeRobot {
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
protected static MotorControl MC = new MotorControl();
protected static InputManager IM = new InputManager();
protected static ImageProcessor IP = new ImageProcessor();
protected static FrisbeeSimulator FS = new FrisbeeSimulator();
protected static Communication Com = new Communication();
protected static SensorInput SI = new SensorInput();
protected static RobotMap RM = new RobotMap();
protected static Watchdog wd;
double pivotval;
double[] drivemotorvalues;
double[] joystickangleandspeed;
double climbval;
public void robotInit() {
wd = Watchdog.getInstance();
wd.setExpiration(1);
SI.init();
IM.init();
MC.init();
wd.feed();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
//Tarun example
/* double[] example = new double[3];
example[0] = 0;
example[1] = 1;
example[2] = 1;
MC.drive(example);
*/
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
while (isOperatorControl() && isEnabled()) {
wd.feed();
IM.updateAllButtons();
if (!IM.climber.getState()) {
joystickangleandspeed = IM.getPureAxis();
pivotval = IM.getPivot();
drivemotorvalues = MC.convertHeadingToMotorCommands(joystickangleandspeed[0], joystickangleandspeed[1]);
drivemotorvalues = MC.setSpeedCap(drivemotorvalues, IM.speedBoost.getState());
drivemotorvalues = MC.addPivot(drivemotorvalues, pivotval);
wd.feed();
System.out.println("motors: " + drivemotorvalues[0] + ",\t" + drivemotorvalues[1] + ",\t" + drivemotorvalues[2]);
MC.drive(drivemotorvalues);
MC.climb(0);
// this is only temporary, should be moved to second joystick
if (IM.tiltdown.getState()) {
MC.shootertilt(0.5);
}
if (IM.tiltup.getState()) {
MC.shootertilt(-0.5);
}
if (!IM.tiltup.getState() && !IM.tiltdown.getState()) {
MC.shootertilt(0);
}
} else {
climbval = IM.getClimb();
climbval = MC.Climblimit(climbval);
MC.climb(climbval);
}
}
}
}
| src/edu/ames/frc/robot/RobotProject.java | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.
/*----------------------------------------------------------------------------*/
package edu.ames.frc.robot;
//___
// | |_ o _ o _ _|_|_ _ __ _ o __ _ | _ _ _
// | | | | _> | _> |_| |(/_ |||(_| | | | (_ | (_|_> _>
//The main class is under control of Kolton Yager and Danial Ebling. DO NOT EDIT
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Watchdog;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotProject extends IterativeRobot {
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
protected static MotorControl MC = new MotorControl();
protected static InputManager IM = new InputManager();
protected static ImageProcessor IP = new ImageProcessor();
protected static FrisbeeSimulator FS = new FrisbeeSimulator();
protected static Communication Com = new Communication();
protected static SensorInput SI = new SensorInput();
protected static RobotMap RM = new RobotMap();
protected static Watchdog wd;
double pivotval;
double[] drivemotorvalues;
double[] joystickangleandspeed;
double climbval;
public void robotInit() {
wd = Watchdog.getInstance();
wd.setExpiration(1);
SI.init();
IM.init();
MC.init();
wd.feed();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
//Tarun example
/* double[] example = new double[3];
example[0] = 0;
example[1] = 1;
example[2] = 1;
MC.drive(example);
*/
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
while (isOperatorControl() && isEnabled()) {
wd.feed();
IM.updateAllButtons();
if (!IM.climber.getState()) {
joystickangleandspeed = IM.getPureAxis();
pivotval = IM.getPivot();
drivemotorvalues = MC.convertHeadingToMotorCommands(joystickangleandspeed[0], joystickangleandspeed[1]);
drivemotorvalues = MC.setSpeedCap(drivemotorvalues, IM.speedBoost.getState());
drivemotorvalues = MC.addPivot(drivemotorvalues, pivotval);
wd.feed();
System.out.println("motors: " + drivemotorvalues[0] + ",\t" + drivemotorvalues[1] + ",\t" + drivemotorvalues[2]);
MC.drive(drivemotorvalues);
MC.climb(0);
// this is only temporary, should be moved to second joystick
if (IM.tiltdown.getState()) {
MC.shootertilt(1);
}
if (IM.tiltup.getState()) {
MC.shootertilt(-1);
}
if (!IM.tiltup.getState() && !IM.tiltdown.getState()) {
MC.shootertilt(0);
}
} else {
climbval = IM.getClimb();
climbval = MC.Climblimit(climbval);
MC.climb(climbval);
}
}
}
}
| changed the shooter tilting to a jaguar | src/edu/ames/frc/robot/RobotProject.java | changed the shooter tilting to a jaguar | <ide><path>rc/edu/ames/frc/robot/RobotProject.java
<ide> public void teleopPeriodic() {
<ide> while (isOperatorControl() && isEnabled()) {
<ide> wd.feed();
<add>
<ide> IM.updateAllButtons();
<ide> if (!IM.climber.getState()) {
<ide> joystickangleandspeed = IM.getPureAxis();
<ide>
<ide> // this is only temporary, should be moved to second joystick
<ide> if (IM.tiltdown.getState()) {
<del> MC.shootertilt(1);
<add> MC.shootertilt(0.5);
<ide> }
<ide> if (IM.tiltup.getState()) {
<del> MC.shootertilt(-1);
<add> MC.shootertilt(-0.5);
<ide> }
<ide> if (!IM.tiltup.getState() && !IM.tiltdown.getState()) {
<ide> MC.shootertilt(0); |
|
Java | apache-2.0 | 06a48d5de2f003a84bd4f1c0bb765d5cb640851a | 0 | baomidou/mybatis-plus,baomidou/mybatis-plus | /*
* Copyright (c) 2011-2021, baomidou ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baomidou.mybatisplus.extension.plugins.inner;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.toolkit.PropertyMapper;
import lombok.*;
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.update.Update;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
/**
* @author hubin
* @since 3.4.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@SuppressWarnings({"rawtypes"})
public class TenantLineInnerInterceptor extends JsqlParserSupport implements InnerInterceptor {
private TenantLineHandler tenantLineHandler;
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) return;
PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
mpBs.sql(parserSingle(mpBs.sql(), null));
}
@Override
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
MappedStatement ms = mpSh.mappedStatement();
SqlCommandType sct = ms.getSqlCommandType();
if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) return;
PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
mpBs.sql(parserMulti(mpBs.sql(), null));
}
}
@Override
protected void processSelect(Select select, int index, String sql, Object obj) {
processSelectBody(select.getSelectBody());
List<WithItem> withItemsList = select.getWithItemsList();
if (!CollectionUtils.isEmpty(withItemsList)) {
withItemsList.forEach(this::processSelectBody);
}
}
protected void processSelectBody(SelectBody selectBody) {
if (selectBody == null) {
return;
}
if (selectBody instanceof PlainSelect) {
processPlainSelect((PlainSelect) selectBody);
} else if (selectBody instanceof WithItem) {
WithItem withItem = (WithItem) selectBody;
processSelectBody(withItem.getSelectBody());
} else {
SetOperationList operationList = (SetOperationList) selectBody;
List<SelectBody> selectBodys = operationList.getSelects();
if (CollectionUtils.isNotEmpty(selectBodys)) {
selectBodys.forEach(this::processSelectBody);
}
}
}
@Override
protected void processInsert(Insert insert, int index, String sql, Object obj) {
if (tenantLineHandler.ignoreTable(insert.getTable().getName())) {
// 过滤退出执行
return;
}
List<Column> columns = insert.getColumns();
if (CollectionUtils.isEmpty(columns)) {
// 针对不给列名的insert 不处理
return;
}
String tenantIdColumn = tenantLineHandler.getTenantIdColumn();
if (columns.stream().map(Column::getColumnName).anyMatch(i -> i.equals(tenantIdColumn))) {
// 针对已给出租户列的insert 不处理
return;
}
columns.add(new Column(tenantLineHandler.getTenantIdColumn()));
// fixed gitee pulls/141 duplicate update
List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList();
if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) {
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(new StringValue(tenantLineHandler.getTenantIdColumn()));
equalsTo.setRightExpression(tenantLineHandler.getTenantId());
duplicateUpdateColumns.add(equalsTo);
}
Select select = insert.getSelect();
if (select != null) {
this.processInsertSelect(select.getSelectBody());
} else if (insert.getItemsList() != null) {
// fixed github pull/295
ItemsList itemsList = insert.getItemsList();
if (itemsList instanceof MultiExpressionList) {
((MultiExpressionList) itemsList).getExprList().forEach(el -> el.getExpressions().add(tenantLineHandler.getTenantId()));
} else {
((ExpressionList) itemsList).getExpressions().add(tenantLineHandler.getTenantId());
}
} else {
throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId");
}
}
/**
* update 语句处理
*/
@Override
protected void processUpdate(Update update, int index, String sql, Object obj) {
final Table table = update.getTable();
if (tenantLineHandler.ignoreTable(table.getName())) {
// 过滤退出执行
return;
}
update.setWhere(this.andExpression(table, update.getWhere()));
}
/**
* delete 语句处理
*/
@Override
protected void processDelete(Delete delete, int index, String sql, Object obj) {
if (tenantLineHandler.ignoreTable(delete.getTable().getName())) {
// 过滤退出执行
return;
}
delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere()));
}
/**
* delete update 语句 where 处理
*/
protected BinaryExpression andExpression(Table table, Expression where) {
//获得where条件表达式
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(this.getAliasColumn(table));
equalsTo.setRightExpression(tenantLineHandler.getTenantId());
if (null != where) {
if (where instanceof OrExpression) {
return new AndExpression(equalsTo, new Parenthesis(where));
} else {
return new AndExpression(equalsTo, where);
}
}
return equalsTo;
}
/**
* 处理 insert into select
* <p>
* 进入这里表示需要 insert 的表启用了多租户,则 select 的表都启动了
*
* @param selectBody SelectBody
*/
protected void processInsertSelect(SelectBody selectBody) {
PlainSelect plainSelect = (PlainSelect) selectBody;
FromItem fromItem = plainSelect.getFromItem();
if (fromItem instanceof Table) {
// fixed gitee pulls/141 duplicate update
processPlainSelect(plainSelect);
appendSelectItem(plainSelect.getSelectItems());
} else if (fromItem instanceof SubSelect) {
SubSelect subSelect = (SubSelect) fromItem;
appendSelectItem(plainSelect.getSelectItems());
processInsertSelect(subSelect.getSelectBody());
}
}
/**
* 追加 SelectItem
*
* @param selectItems SelectItem
*/
protected void appendSelectItem(List<SelectItem> selectItems) {
if (CollectionUtils.isEmpty(selectItems)) return;
if (selectItems.size() == 1) {
SelectItem item = selectItems.get(0);
if (item instanceof AllColumns || item instanceof AllTableColumns) return;
}
selectItems.add(new SelectExpressionItem(new Column(tenantLineHandler.getTenantIdColumn())));
}
/**
* 处理 PlainSelect
*/
protected void processPlainSelect(PlainSelect plainSelect) {
FromItem fromItem = plainSelect.getFromItem();
Expression where = plainSelect.getWhere();
processWhereSubSelect(where);
if (fromItem instanceof Table) {
Table fromTable = (Table) fromItem;
if (!tenantLineHandler.ignoreTable(fromTable.getName())) {
//#1186 github
plainSelect.setWhere(builderExpression(where, fromTable));
}
} else {
processFromItem(fromItem);
}
//#3087 github
List<SelectItem> selectItems = plainSelect.getSelectItems();
if (CollectionUtils.isNotEmpty(selectItems)) {
selectItems.forEach(this::processSelectItem);
}
List<Join> joins = plainSelect.getJoins();
if (CollectionUtils.isNotEmpty(joins)) {
joins.forEach(j -> {
processJoin(j);
processFromItem(j.getRightItem());
});
}
}
/**
* 处理where条件内的子查询
* <p>
* 支持如下:
* 1. in
* 2. =
* 3. >
* 4. <
* 5. >=
* 6. <=
* 7. <>
* 8. EXISTS
* 9. NOT EXISTS
* <p>
* 前提条件:
* 1. 子查询必须放在小括号中
* 2. 子查询一般放在比较操作符的右边
*
* @param where where 条件
*/
protected void processWhereSubSelect(Expression where) {
if (where == null) {
return;
}
if (where instanceof FromItem) {
processFromItem((FromItem) where);
return;
}
if (where.toString().indexOf("SELECT") > 0) {
// 有子查询
if (where instanceof BinaryExpression) {
// 比较符号 , and , or , 等等
BinaryExpression expression = (BinaryExpression) where;
processWhereSubSelect(expression.getLeftExpression());
processWhereSubSelect(expression.getRightExpression());
} else if (where instanceof InExpression) {
// in
InExpression expression = (InExpression) where;
ItemsList itemsList = expression.getRightItemsList();
if (itemsList instanceof SubSelect) {
processSelectBody(((SubSelect) itemsList).getSelectBody());
}
} else if (where instanceof ExistsExpression) {
// exists
ExistsExpression expression = (ExistsExpression) where;
processWhereSubSelect(expression.getRightExpression());
} else if (where instanceof NotExpression) {
// not exists
NotExpression expression = (NotExpression) where;
processWhereSubSelect(expression.getExpression());
} else if (where instanceof Parenthesis) {
Parenthesis expression = (Parenthesis) where;
processWhereSubSelect(expression.getExpression());
}
}
}
protected void processSelectItem(SelectItem selectItem) {
if (selectItem instanceof SelectExpressionItem) {
SelectExpressionItem selectExpressionItem = (SelectExpressionItem) selectItem;
if (selectExpressionItem.getExpression() instanceof SubSelect) {
processSelectBody(((SubSelect) selectExpressionItem.getExpression()).getSelectBody());
} else if (selectExpressionItem.getExpression() instanceof Function) {
processFunction((Function) selectExpressionItem.getExpression());
}
}
}
/**
* 处理函数
* <p>支持: 1. select fun(args..) 2. select fun1(fun2(args..),args..)<p>
* <p> fixed gitee pulls/141</p>
*
* @param function
*/
protected void processFunction(Function function) {
ExpressionList parameters = function.getParameters();
if (parameters != null) {
parameters.getExpressions().forEach(expression -> {
if (expression instanceof SubSelect) {
processSelectBody(((SubSelect) expression).getSelectBody());
} else if (expression instanceof Function) {
processFunction((Function) expression);
}
});
}
}
/**
* 处理子查询等
*/
protected void processFromItem(FromItem fromItem) {
if (fromItem instanceof SubJoin) {
SubJoin subJoin = (SubJoin) fromItem;
if (subJoin.getJoinList() != null) {
subJoin.getJoinList().forEach(this::processJoin);
}
if (subJoin.getLeft() != null) {
processFromItem(subJoin.getLeft());
}
} else if (fromItem instanceof SubSelect) {
SubSelect subSelect = (SubSelect) fromItem;
if (subSelect.getSelectBody() != null) {
processSelectBody(subSelect.getSelectBody());
}
} else if (fromItem instanceof ValuesList) {
logger.debug("Perform a subquery, if you do not give us feedback");
} else if (fromItem instanceof LateralSubSelect) {
LateralSubSelect lateralSubSelect = (LateralSubSelect) fromItem;
if (lateralSubSelect.getSubSelect() != null) {
SubSelect subSelect = lateralSubSelect.getSubSelect();
if (subSelect.getSelectBody() != null) {
processSelectBody(subSelect.getSelectBody());
}
}
}
}
/**
* 处理联接语句
*/
protected void processJoin(Join join) {
if (join.getRightItem() instanceof Table) {
Table fromTable = (Table) join.getRightItem();
if (tenantLineHandler.ignoreTable(fromTable.getName())) {
// 过滤退出执行
return;
}
join.setOnExpression(builderExpression(join.getOnExpression(), fromTable));
}
}
/**
* 处理条件
*/
protected Expression builderExpression(Expression currentExpression, Table table) {
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(this.getAliasColumn(table));
equalsTo.setRightExpression(tenantLineHandler.getTenantId());
if (currentExpression == null) {
return equalsTo;
}
if (currentExpression instanceof OrExpression) {
return new AndExpression(new Parenthesis(currentExpression), equalsTo);
} else {
return new AndExpression(currentExpression, equalsTo);
}
}
/**
* 租户字段别名设置
* <p>tenantId 或 tableAlias.tenantId</p>
*
* @param table 表对象
* @return 字段
*/
protected Column getAliasColumn(Table table) {
StringBuilder column = new StringBuilder();
if (table.getAlias() != null) {
column.append(table.getAlias().getName()).append(StringPool.DOT);
}
column.append(tenantLineHandler.getTenantIdColumn());
return new Column(column.toString());
}
@Override
public void setProperties(Properties properties) {
PropertyMapper.newInstance(properties)
.whenNotBlack("tenantLineHandler", ClassUtils::newInstance, this::setTenantLineHandler);
}
}
| mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/inner/TenantLineInnerInterceptor.java | /*
* Copyright (c) 2011-2021, baomidou ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baomidou.mybatisplus.extension.plugins.inner;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.toolkit.PropertyMapper;
import lombok.*;
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.update.Update;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
/**
* @author hubin
* @since 3.4.0
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@SuppressWarnings({"rawtypes"})
public class TenantLineInnerInterceptor extends JsqlParserSupport implements InnerInterceptor {
private TenantLineHandler tenantLineHandler;
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) return;
PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
mpBs.sql(parserSingle(mpBs.sql(), null));
}
@Override
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
MappedStatement ms = mpSh.mappedStatement();
SqlCommandType sct = ms.getSqlCommandType();
if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) return;
PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
mpBs.sql(parserMulti(mpBs.sql(), null));
}
}
@Override
protected void processSelect(Select select, int index, String sql, Object obj) {
processSelectBody(select.getSelectBody());
List<WithItem> withItemsList = select.getWithItemsList();
if (!CollectionUtils.isEmpty(withItemsList)) {
withItemsList.forEach(this::processSelectBody);
}
}
protected void processSelectBody(SelectBody selectBody) {
if (selectBody == null) {
return;
}
if (selectBody instanceof PlainSelect) {
processPlainSelect((PlainSelect) selectBody);
} else if (selectBody instanceof WithItem) {
WithItem withItem = (WithItem) selectBody;
processSelectBody(withItem.getSelectBody());
} else {
SetOperationList operationList = (SetOperationList) selectBody;
List<SelectBody> selectBodys = operationList.getSelects();
if (CollectionUtils.isNotEmpty(selectBodys)) {
selectBodys.forEach(this::processSelectBody);
}
}
}
@Override
protected void processInsert(Insert insert, int index, String sql, Object obj) {
if (tenantLineHandler.ignoreTable(insert.getTable().getName())) {
// 过滤退出执行
return;
}
List<Column> columns = insert.getColumns();
if (CollectionUtils.isEmpty(columns)) {
// 针对不给列名的insert 不处理
return;
}
String tenantIdColumn = tenantLineHandler.getTenantIdColumn();
if (columns.stream().map(Column::getColumnName).anyMatch(i -> i.equals(tenantIdColumn))) {
// 针对已给出租户列的insert 不处理
return;
}
columns.add(new Column(tenantLineHandler.getTenantIdColumn()));
// fixed gitee pulls/141 duplicate update
List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList();
if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) {
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(new StringValue(tenantLineHandler.getTenantIdColumn()));
equalsTo.setRightExpression(tenantLineHandler.getTenantId());
duplicateUpdateColumns.add(equalsTo);
}
Select select = insert.getSelect();
if (select != null) {
this.processInsertSelect(select.getSelectBody());
} else if (insert.getItemsList() != null) {
// fixed github pull/295
ItemsList itemsList = insert.getItemsList();
if (itemsList instanceof MultiExpressionList) {
((MultiExpressionList) itemsList).getExprList().forEach(el -> el.getExpressions().add(tenantLineHandler.getTenantId()));
} else {
((ExpressionList) itemsList).getExpressions().add(tenantLineHandler.getTenantId());
}
} else {
throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId");
}
}
/**
* update 语句处理
*/
@Override
protected void processUpdate(Update update, int index, String sql, Object obj) {
final Table table = update.getTable();
if (tenantLineHandler.ignoreTable(table.getName())) {
// 过滤退出执行
return;
}
update.setWhere(this.andExpression(table, update.getWhere()));
}
/**
* delete 语句处理
*/
@Override
protected void processDelete(Delete delete, int index, String sql, Object obj) {
if (tenantLineHandler.ignoreTable(delete.getTable().getName())) {
// 过滤退出执行
return;
}
delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere()));
}
/**
* delete update 语句 where 处理
*/
protected BinaryExpression andExpression(Table table, Expression where) {
//获得where条件表达式
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(this.getAliasColumn(table));
equalsTo.setRightExpression(tenantLineHandler.getTenantId());
if (null != where) {
if (where instanceof OrExpression) {
return new AndExpression(equalsTo, new Parenthesis(where));
} else {
return new AndExpression(equalsTo, where);
}
}
return equalsTo;
}
/**
* 处理 insert into select
* <p>
* 进入这里表示需要 insert 的表启用了多租户,则 select 的表都启动了
*
* @param selectBody SelectBody
*/
protected void processInsertSelect(SelectBody selectBody) {
PlainSelect plainSelect = (PlainSelect) selectBody;
FromItem fromItem = plainSelect.getFromItem();
if (fromItem instanceof Table) {
Table fromTable = (Table) fromItem;
plainSelect.setWhere(builderExpression(plainSelect.getWhere(), fromTable));
appendSelectItem(plainSelect.getSelectItems());
} else if (fromItem instanceof SubSelect) {
SubSelect subSelect = (SubSelect) fromItem;
appendSelectItem(plainSelect.getSelectItems());
processInsertSelect(subSelect.getSelectBody());
}
}
/**
* 追加 SelectItem
*
* @param selectItems SelectItem
*/
protected void appendSelectItem(List<SelectItem> selectItems) {
if (CollectionUtils.isEmpty(selectItems)) return;
if (selectItems.size() == 1) {
SelectItem item = selectItems.get(0);
if (item instanceof AllColumns || item instanceof AllTableColumns) return;
}
selectItems.add(new SelectExpressionItem(new Column(tenantLineHandler.getTenantIdColumn())));
}
/**
* 处理 PlainSelect
*/
protected void processPlainSelect(PlainSelect plainSelect) {
FromItem fromItem = plainSelect.getFromItem();
Expression where = plainSelect.getWhere();
processWhereSubSelect(where);
if (fromItem instanceof Table) {
Table fromTable = (Table) fromItem;
if (!tenantLineHandler.ignoreTable(fromTable.getName())) {
//#1186 github
plainSelect.setWhere(builderExpression(where, fromTable));
}
} else {
processFromItem(fromItem);
}
//#3087 github
List<SelectItem> selectItems = plainSelect.getSelectItems();
if (CollectionUtils.isNotEmpty(selectItems)) {
selectItems.forEach(this::processSelectItem);
}
List<Join> joins = plainSelect.getJoins();
if (CollectionUtils.isNotEmpty(joins)) {
joins.forEach(j -> {
processJoin(j);
processFromItem(j.getRightItem());
});
}
}
/**
* 处理where条件内的子查询
* <p>
* 支持如下:
* 1. in
* 2. =
* 3. >
* 4. <
* 5. >=
* 6. <=
* 7. <>
* 8. EXISTS
* 9. NOT EXISTS
* <p>
* 前提条件:
* 1. 子查询必须放在小括号中
* 2. 子查询一般放在比较操作符的右边
*
* @param where where 条件
*/
protected void processWhereSubSelect(Expression where) {
if (where == null) {
return;
}
if (where instanceof FromItem) {
processFromItem((FromItem) where);
return;
}
if (where.toString().indexOf("SELECT") > 0) {
// 有子查询
if (where instanceof BinaryExpression) {
// 比较符号 , and , or , 等等
BinaryExpression expression = (BinaryExpression) where;
processWhereSubSelect(expression.getLeftExpression());
processWhereSubSelect(expression.getRightExpression());
} else if (where instanceof InExpression) {
// in
InExpression expression = (InExpression) where;
ItemsList itemsList = expression.getRightItemsList();
if (itemsList instanceof SubSelect) {
processSelectBody(((SubSelect) itemsList).getSelectBody());
}
} else if (where instanceof ExistsExpression) {
// exists
ExistsExpression expression = (ExistsExpression) where;
processWhereSubSelect(expression.getRightExpression());
} else if (where instanceof NotExpression) {
// not exists
NotExpression expression = (NotExpression) where;
processWhereSubSelect(expression.getExpression());
} else if (where instanceof Parenthesis) {
Parenthesis expression = (Parenthesis) where;
processWhereSubSelect(expression.getExpression());
}
}
}
protected void processSelectItem(SelectItem selectItem) {
if (selectItem instanceof SelectExpressionItem) {
SelectExpressionItem selectExpressionItem = (SelectExpressionItem) selectItem;
if (selectExpressionItem.getExpression() instanceof SubSelect) {
processSelectBody(((SubSelect) selectExpressionItem.getExpression()).getSelectBody());
} else if (selectExpressionItem.getExpression() instanceof Function) {
processFunction((Function)selectExpressionItem.getExpression());
}
}
}
/**
* 处理函数
* <p>支持: 1. select fun(args..) 2. select fun1(fun2(args..),args..)<p>
* <p> fixed gitee pulls/141</p>
*
* @param function
*/
protected void processFunction(Function function) {
ExpressionList parameters = function.getParameters();
if (parameters != null) {
parameters.getExpressions().forEach(expression -> {
if (expression instanceof SubSelect) {
processSelectBody(((SubSelect)expression).getSelectBody());
} else if (expression instanceof Function) {
processFunction((Function)expression);
}
});
}
}
/**
* 处理子查询等
*/
protected void processFromItem(FromItem fromItem) {
if (fromItem instanceof SubJoin) {
SubJoin subJoin = (SubJoin) fromItem;
if (subJoin.getJoinList() != null) {
subJoin.getJoinList().forEach(this::processJoin);
}
if (subJoin.getLeft() != null) {
processFromItem(subJoin.getLeft());
}
} else if (fromItem instanceof SubSelect) {
SubSelect subSelect = (SubSelect) fromItem;
if (subSelect.getSelectBody() != null) {
processSelectBody(subSelect.getSelectBody());
}
} else if (fromItem instanceof ValuesList) {
logger.debug("Perform a subquery, if you do not give us feedback");
} else if (fromItem instanceof LateralSubSelect) {
LateralSubSelect lateralSubSelect = (LateralSubSelect) fromItem;
if (lateralSubSelect.getSubSelect() != null) {
SubSelect subSelect = lateralSubSelect.getSubSelect();
if (subSelect.getSelectBody() != null) {
processSelectBody(subSelect.getSelectBody());
}
}
}
}
/**
* 处理联接语句
*/
protected void processJoin(Join join) {
if (join.getRightItem() instanceof Table) {
Table fromTable = (Table) join.getRightItem();
if (tenantLineHandler.ignoreTable(fromTable.getName())) {
// 过滤退出执行
return;
}
join.setOnExpression(builderExpression(join.getOnExpression(), fromTable));
}
}
/**
* 处理条件
*/
protected Expression builderExpression(Expression currentExpression, Table table) {
EqualsTo equalsTo = new EqualsTo();
equalsTo.setLeftExpression(this.getAliasColumn(table));
equalsTo.setRightExpression(tenantLineHandler.getTenantId());
if (currentExpression == null) {
return equalsTo;
}
if (currentExpression instanceof OrExpression) {
return new AndExpression(new Parenthesis(currentExpression), equalsTo);
} else {
return new AndExpression(currentExpression, equalsTo);
}
}
/**
* 租户字段别名设置
* <p>tenantId 或 tableAlias.tenantId</p>
*
* @param table 表对象
* @return 字段
*/
protected Column getAliasColumn(Table table) {
StringBuilder column = new StringBuilder();
if (table.getAlias() != null) {
column.append(table.getAlias().getName()).append(StringPool.DOT);
}
column.append(tenantLineHandler.getTenantIdColumn());
return new Column(column.toString());
}
@Override
public void setProperties(Properties properties) {
PropertyMapper.newInstance(properties)
.whenNotBlack("tenantLineHandler", ClassUtils::newInstance, this::setTenantLineHandler);
}
}
| fixed gitee pulls/141
| mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/inner/TenantLineInnerInterceptor.java | fixed gitee pulls/141 | <ide><path>ybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/plugins/inner/TenantLineInnerInterceptor.java
<ide> PlainSelect plainSelect = (PlainSelect) selectBody;
<ide> FromItem fromItem = plainSelect.getFromItem();
<ide> if (fromItem instanceof Table) {
<del> Table fromTable = (Table) fromItem;
<del> plainSelect.setWhere(builderExpression(plainSelect.getWhere(), fromTable));
<add> // fixed gitee pulls/141 duplicate update
<add> processPlainSelect(plainSelect);
<ide> appendSelectItem(plainSelect.getSelectItems());
<ide> } else if (fromItem instanceof SubSelect) {
<ide> SubSelect subSelect = (SubSelect) fromItem;
<ide> if (selectExpressionItem.getExpression() instanceof SubSelect) {
<ide> processSelectBody(((SubSelect) selectExpressionItem.getExpression()).getSelectBody());
<ide> } else if (selectExpressionItem.getExpression() instanceof Function) {
<del> processFunction((Function)selectExpressionItem.getExpression());
<add> processFunction((Function) selectExpressionItem.getExpression());
<ide> }
<ide> }
<ide> }
<ide> if (parameters != null) {
<ide> parameters.getExpressions().forEach(expression -> {
<ide> if (expression instanceof SubSelect) {
<del> processSelectBody(((SubSelect)expression).getSelectBody());
<add> processSelectBody(((SubSelect) expression).getSelectBody());
<ide> } else if (expression instanceof Function) {
<del> processFunction((Function)expression);
<add> processFunction((Function) expression);
<ide> }
<ide> });
<ide> } |
|
Java | lgpl-2.1 | e935417a2899013f86e3e62a39356a48b796f522 | 0 | svn2github/beast-mcmc,armanbilge/BEAST_sandbox,armanbilge/BEAST_sandbox,armanbilge/BEAST_sandbox,armanbilge/BEAST_sandbox,armanbilge/BEAST_sandbox,svn2github/beast-mcmc,svn2github/beast-mcmc,svn2github/beast-mcmc,svn2github/beast-mcmc | /*
* BeastGenerator.java
*
* Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.app.beauti.generator;
import dr.app.beast.BeastVersion;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.options.*;
import dr.app.beauti.options.Parameter;
import dr.app.beauti.priorsPanel.PriorType;
import dr.app.beauti.util.XMLWriter;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.StrictClockBranchRates;
import dr.evomodel.clock.ACLikelihood;
import dr.evomodel.coalescent.CoalescentLikelihood;
import dr.evomodel.coalescent.GMRFFixedGridImportanceSampler;
import dr.evomodel.speciation.SpeciationLikelihood;
import dr.evomodel.speciation.SpeciesTreeBMPrior;
import dr.evomodel.speciation.SpeciesTreeModel;
import dr.evomodel.speciation.TreePartitionCoalescent;
import dr.evomodel.tree.*;
import dr.evomodelxml.*;
import dr.evoxml.*;
import dr.inference.distribution.MixedDistributionLikelihood;
import dr.inference.loggers.Columns;
import dr.inference.model.*;
import dr.inference.operators.SimpleOperatorSchedule;
import dr.inference.xml.LoggerParser;
import dr.inferencexml.PriorParsers;
import dr.util.Attribute;
import dr.util.Version;
import dr.xml.AttributeParser;
import dr.xml.XMLParser;
import java.io.Writer;
import java.util.*;
/**
* This class holds all the data for the current BEAUti Document
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Walter Xie
* @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $
*/
public class BeastGenerator extends Generator {
private final static Version version = new BeastVersion();
private final static String TREE_FILE_LOG = "treeFileLog";
private final static String SUB_TREE_FILE_LOG = "substTreeFileLog";
private final TreePriorGenerator treePriorGenerator;
private final TreeLikelihoodGenerator treeLikelihoodGenerator;
private final SubstitutionModelGenerator substitutionModelGenerator;
private final InitialTreeGenerator initialTreeGenerator;
private final TreeModelGenerator treeModelGenerator;
private final BranchRatesModelGenerator branchRatesModelGenerator;
private final OperatorsGenerator operatorsGenerator;
private final STARBEASTGenerator starEASTGeneratorGenerator;
public BeastGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
substitutionModelGenerator = new SubstitutionModelGenerator(options, components);
treePriorGenerator = new TreePriorGenerator(options, components);
treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components);
initialTreeGenerator = new InitialTreeGenerator(options, components);
treeModelGenerator = new TreeModelGenerator(options, components);
branchRatesModelGenerator = new BranchRatesModelGenerator(options, components);
operatorsGenerator = new OperatorsGenerator(options, components);
starEASTGeneratorGenerator = new STARBEASTGenerator(options, components);
}
/**
* Checks various options to check they are valid. Throws IllegalArgumentExceptions with
* descriptions of the problems.
*
* @throws IllegalArgumentException if there is a problem with the current settings
*/
public void checkOptions() throws IllegalArgumentException {
//++++++++++++++++ Taxon List ++++++++++++++++++
TaxonList taxonList = options.taxonList;
Set<String> ids = new HashSet<String>();
ids.add(TaxaParser.TAXA);
ids.add(AlignmentParser.ALIGNMENT);
if (taxonList != null) {
if (taxonList.getTaxonCount() < 2) {
throw new IllegalArgumentException("BEAST requires at least two taxa to run.");
}
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (ids.contains(taxon.getId())) {
throw new IllegalArgumentException("A taxon has the same id," + taxon.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxon.getId());
}
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
for (Taxa taxa : options.taxonSets) {
if (taxa.getTaxonCount() < 2) {
throw new IllegalArgumentException("Taxon set, " + taxa.getId() + ", should contain\n" +
"at least two taxa.");
}
if (ids.contains(taxa.getId())) {
throw new IllegalArgumentException("A taxon sets has the same id," + taxa.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxa.getId());
}
//++++++++++++++++ Tree Prior ++++++++++++++++++
if (options.shareSameTreePrior) {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePrior.GMRF_SKYRIDE) {
throw new IllegalArgumentException("For GMRF, tree model/tree prior combination not implemented by BEAST yet!" +
"\nPlease uncheck the shareSameTreePrior if using GMRF.");
}
}
}
//++++++++++++++++ clock model/tree model combination ++++++++++++++++++
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// clock model/tree model combination not implemented by BEAST yet
validateClockTreeModelCombination(model);
}
//++++++++++++++++ Species tree ++++++++++++++++++
if (options.isSpeciesAnalysis()) {
// if (!(options.nodeHeightPrior == TreePrior.SPECIES_BIRTH_DEATH || options.nodeHeightPrior == TreePrior.SPECIES_YULE)) {
// //TODO: more species tree model
// throw new IllegalArgumentException("Species analysis requires to define species tree prior in Tree panel.");
// }
}
// add other tests and warnings here
// Speciation model with dated tips
// Sampling rates without dated tips or priors on rate or nodes
}
/**
* Generate a beast xml file from these beast options
*
* @param w the writer
*/
public void generateXML(Writer w) {
XMLWriter writer = new XMLWriter(w);
writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
writer.writeComment("Generated by BEAUTi " + version.getVersionString());
writer.writeComment(" by Alexei J. Drummond and Andrew Rambaut");
writer.writeComment(" Department of Computer Science, University of Auckland and");
writer.writeComment(" Institute of Evolutionary Biology, University of Edinburgh");
writer.writeComment(" http://beast.bio.ed.ac.uk/");
writer.writeOpenTag("beast");
writer.writeText("");
// this gives any added implementations of the 'Component' interface a
// chance to generate XML at this point in the BEAST file.
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
//++++++++++++++++ Taxon List ++++++++++++++++++
writeTaxa(writer, options.taxonList);
List<Taxa> taxonSets = options.taxonSets;
if (taxonSets != null && taxonSets.size() > 0) {
writeTaxonSets(writer, taxonSets); // TODO
}
if (options.allowDifferentTaxa) { // allow diff taxa for multi-gene
writer.writeText("");
writer.writeComment("List all taxons regarding each gene (file) for Multispecies Coalescent function");
// write all taxa in each gene tree regarding each data partition,
for (PartitionData partition : options.dataPartitions) {
// do I need if (!alignments.contains(alignment)) {alignments.add(alignment);} ?
writeDifferentTaxaForMultiGene(partition, writer);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
//++++++++++++++++ Alignments ++++++++++++++++++
List<Alignment> alignments = new ArrayList<Alignment>();
for (PartitionData partition : options.dataPartitions) {
Alignment alignment = partition.getAlignment();
if (!alignments.contains(alignment)) {
alignments.add(alignment);
}
}
if (!options.samplePriorOnly) {
int index = 1;
for (Alignment alignment : alignments) {
if (alignments.size() > 1) {
//if (!options.allowDifferentTaxa) {
alignment.setId(AlignmentParser.ALIGNMENT + index);
//} else { // e.g. alignment_gene1
// alignment.setId("alignment_" + mulitTaxaTagName + index);
//}
} else {
alignment.setId(AlignmentParser.ALIGNMENT);
}
writeAlignment(alignment, writer);
index += 1;
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
//++++++++++++++++ Pattern Lists ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// writePatternList(model, writer);
for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
writePatternList(partition, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
} else {
Alignment alignment = alignments.get(0);
alignment.setId(AlignmentParser.ALIGNMENT);
writeAlignment(alignment, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
}
//++++++++++++++++ Tree Prior Model ++++++++++++++++++
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeTreePriorModel(options.activedSameTreePrior, writer);
// } else { // Different Tree Priors
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // prior.constant
treePriorGenerator.writeTreePriorModel(prior, writer);
writer.writeText("");
}
// }
//++++++++++++++++ Starting Tree ++++++++++++++++++
// if ( options.getPartitionTreeModels().size() == 1 ) { // 1 Partition Tree Model
// initialTreeGenerator.setModelPrefix("");
// initialTreeGenerator.writeStartingTree(options.getPartitionTreeModels().get(0), writer);
// } else { // Different Tree Models
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// initialTreeGenerator.setModelPrefix(model.getPrefix()); // model.startingTree
initialTreeGenerator.writeStartingTree(model, writer);
writer.writeText("");
}
// }
//++++++++++++++++ Tree Model +++++++++++++++++++
// if ( options.getPartitionTreeModels().size() == 1 ) { // 1 Partition Tree Model
// treeModelGenerator.setModelPrefix("");
// treeModelGenerator.writeTreeModel(writer);
// } else { // Different Tree Models
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// treeModelGenerator.setModelPrefix(model.getPrefix()); // treemodel.treeModel
treeModelGenerator.writeTreeModel(model, writer);
writer.writeText("");
}
// }
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
//++++++++++++++++ Tree Prior ++++++++++++++++++
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeTreePrior(options.activedSameTreePrior, writer);
// } else { // no species
// for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // prior.treeModel
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior;
if (options.shareSameTreePrior) {
prior = options.activedSameTreePrior;
} else {
prior = model.getPartitionTreePrior();
}
treePriorGenerator.writePriorLikelihood(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographic(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
//++++++++++++++++ Branch Rates Model ++++++++++++++++++
// if ( options.getPartitionClockModels().size() == 1 ) { // 1 Partition Clock Model
// branchRatesModelGenerator.setModelPrefix("");
// branchRatesModelGenerator.writeBranchRatesModel(writer);
// } else { // Different Tree Models
for (PartitionClockModel model : options.getPartitionClockModels()) {
// branchRatesModelGenerator.setModelPrefix(model.getPrefix()); // model.startingTree
// for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
branchRatesModelGenerator.writeBranchRatesModel(model, writer);
// }
writer.writeText("");
}
// }
//++++++++++++++++ Substitution Model ++++++++++++++++++
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSubstitutionModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
//++++++++++++++++ Site Model ++++++++++++++++++
boolean writeMuParameters = options.hasCodon(); //options.getTotalActivePartitionSubstitutionModelCount() > 1;
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSiteModel(model, writeMuParameters, writer);
writer.writeText("");
}
if (writeMuParameters) {
// allMus is global
writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "allMus")});
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeMuParameterRefs(model, writer);
}
writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
//++++++++++++++++ Tree Likelihood ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// if ( options.isSpeciesAnalysis() ) { // species
// treeLikelihoodGenerator.setModelPrefix(model.getName() + ".");
// } else {
// treeLikelihoodGenerator.setModelPrefix("");
// }
// //TODO: need merge genePrifx and prefix
//// for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
// treeLikelihoodGenerator.writeTreeLikelihood(model, writer);
// writer.writeText("");
// }
for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
treeLikelihoodGenerator.writeTreeLikelihood(partition, writer);
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// treeLikelihoodGenerator.writeTreeLikelihood(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
//++++++++++++++++ Traits ++++++++++++++++++
// traits tag
if (options.selecetedTraits.size() > 0) {
for (String trait : options.selecetedTraits) {
TraitGuesser.TraitType traiType = options.traitTypes.get(trait);
writeTraits(writer, trait, traiType.toString(), options.taxonList);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
}
//++++++++++++++++ ++++++++++++++++++
if (taxonSets != null && taxonSets.size() > 0) {
//TODO: need to suit for multi-gene-tree
writeTMRCAStatistics(writer);
}
//++++++++++++++++ Operators ++++++++++++++++++
List<Operator> operators = options.selectOperators();
operatorsGenerator.writeOperatorSchedule(operators, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
//++++++++++++++++ MCMC ++++++++++++++++++
// XMLWriter writer, List<PartitionSubstitutionModel> models,
writeMCMC(writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
//++++++++++++++++ ++++++++++++++++++
writeTimerReport(writer);
writer.writeText("");
if (options.performTraceAnalysis) {
writeTraceAnalysis(writer);
}
if (options.generateCSV) {
if (options.shareSameTreePrior) { // Share Same Tree Prior
treePriorGenerator.setModelPrefix("");
treePriorGenerator.writeEBSPAnalysisToCSVfile(options.activedSameTreePrior, writer);
} else { // no species
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.setModelPrefix(prior.getName() + "."); // partitionName.constant
treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer);
}
}
}
writer.writeCloseTag("beast");
writer.flush();
}
/**
* Generate a taxa block from these beast options
*
* @param writer the writer
* @param taxonList the taxon list to write
*/
private void writeTaxa(XMLWriter writer, TaxonList taxonList) {
// -1 (single taxa), 0 (1st gene of multi-taxa)
writer.writeComment("The list of taxa analyse (can also include dates/ages).");
writer.writeComment("ntax=" + taxonList.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)});
boolean firstDate = true;
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
boolean hasDate = false;
if (options.maximumTipHeight > 0.0) {
hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE);
}
writer.writeTag(TaxonParser.TAXON, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, taxon.getId())}, !hasDate);
if (hasDate) {
dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
if (firstDate) {
options.units = date.getUnits();
firstDate = false;
} else {
if (options.units != date.getUnits()) {
System.err.println("Error: Units in dates do not match.");
}
}
Attribute[] attributes = {
new Attribute.Default<Double>(ParameterParser.VALUE, date.getTimeValue()),
new Attribute.Default<String>("direction", date.isBackwards() ? "backwards" : "forwards"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
/*,
new Attribute.Default("origin", date.getOrigin()+"")*/
};
writer.writeTag(dr.evolution.util.Date.DATE, attributes, true);
writer.writeCloseTag(TaxonParser.TAXON);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer);
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate additional taxon sets
*
* @param writer the writer
* @param taxonSets a list of taxa to write
*/
private void writeTaxonSets(XMLWriter writer, List<Taxa> taxonSets) {
writer.writeText("");
for (Taxa taxa : taxonSets) {
writer.writeOpenTag(
TaxaParser.TAXA,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, taxa.getId())
}
);
for (int j = 0; j < taxa.getTaxonCount(); j++) {
writer.writeIDref(TaxonParser.TAXON, taxa.getTaxon(j).getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
}
/**
* Determine and return the datatype description for these beast options
* note that the datatype in XML may differ from the actual datatype
*
* @param alignment the alignment to get data type description of
* @return description
*/
private String getAlignmentDataTypeDescription(Alignment alignment) {
String description;
switch (alignment.getDataType().getType()) {
case DataType.TWO_STATES:
case DataType.COVARION:
// TODO make this work
throw new RuntimeException("TO DO!");
//switch (partition.getPartitionSubstitutionModel().binarySubstitutionModel) {
// case ModelOptions.BIN_COVARION:
// description = TwoStateCovarion.DESCRIPTION;
// break;
//
// default:
// description = alignment.getDataType().getDescription();
//}
//break;
default:
description = alignment.getDataType().getDescription();
}
return description;
}
public void writeDifferentTaxaForMultiGene(PartitionData dataPartition, XMLWriter writer) {
String data = dataPartition.getName();
Alignment alignment = dataPartition.getAlignment();
writer.writeComment("gene name = " + data + ", ntax= " + alignment.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, data + "." + TaxaParser.TAXA)});
for (int i = 0; i < alignment.getTaxonCount(); i++) {
final Taxon taxon = alignment.getTaxon(i);
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate an alignment block from these beast options
*
* @param alignment the alignment to write
* @param writer the writer
*/
public void writeAlignment(Alignment alignment, XMLWriter writer) {
writer.writeText("");
writer.writeComment("The sequence alignment (each sequence refers to a taxon above).");
writer.writeComment("ntax=" + alignment.getTaxonCount() + " nchar=" + alignment.getSiteCount());
if (options.samplePriorOnly) {
writer.writeComment("Null sequences generated in order to sample from the prior only.");
}
writer.writeOpenTag(
AlignmentParser.ALIGNMENT,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, alignment.getId()),
new Attribute.Default<String>("dataType", getAlignmentDataTypeDescription(alignment))
}
);
for (int i = 0; i < alignment.getTaxonCount(); i++) {
Taxon taxon = alignment.getTaxon(i);
writer.writeOpenTag("sequence");
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
if (!options.samplePriorOnly) {
writer.writeText(alignment.getAlignedSequenceString(i));
} else {
writer.writeText("N");
}
writer.writeCloseTag("sequence");
}
writer.writeCloseTag(AlignmentParser.ALIGNMENT);
}
/**
* Generate traits block regarding specific trait name (currently only <species>) from options
*
* @param writer
* @param trait
* @param traitType
* @param taxonList
*/
private void writeTraits(XMLWriter writer, String trait, String traitType, TaxonList taxonList) {
writer.writeText("");
if (options.isSpeciesAnalysis()) { // species
writer.writeComment("Species definition: binds taxa, species and gene trees");
}
writer.writeComment("trait = " + trait + " trait_type = " + traitType);
writer.writeOpenTag(trait, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, trait)});
//new Attribute.Default<String>("traitType", traitType)});
// write sub-tags for species
if (options.isSpeciesAnalysis()) { // species
starEASTGeneratorGenerator.writeMultiSpecies(taxonList, writer);
} // end write sub-tags for species
writer.writeCloseTag(trait);
if (options.isSpeciesAnalysis()) { // species
starEASTGeneratorGenerator.writeSTARBEAST(writer);
}
}
/**
* Writes the pattern lists
*
* @param partition the partition data to write the pattern lists for
* @param writer the writer
*/
public void writePatternList(PartitionData partition, XMLWriter writer) {
writer.writeText("");
PartitionSubstitutionModel model = partition.getPartitionSubstitutionModel();
String codonHeteroPattern = model.getCodonHeteroPattern();
int partitionCount = model.getCodonPartitionCount();
if (model.getDataType() == Nucleotides.INSTANCE && codonHeteroPattern != null && partitionCount > 1) {
if (codonHeteroPattern.equals("112")) {
writer.writeComment("The unique patterns for codon positions 1 & 2");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(1) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, 0, 3, writer);
writePatternList(partition, 1, 3, writer);
// }
// }
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
writer.writeComment("The unique patterns for codon positions 3");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(2) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, 2, 3, writer);
// }
// }
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
} else {
// pattern is 123
// write pattern lists for all three codon positions
for (int i = 1; i <= 3; i++) {
writer.writeComment("The unique patterns for codon positions " + i);
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(i) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, i - 1, 3, writer);
// }
// }
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
}
}
} else {
//partitionCount = 1;
// writer.writeComment("The unique patterns site patterns");
// Alignment alignment = partition.getAlignment();
// writer.writeOpenTag(SitePatternsParser.PATTERNS,
// new Attribute[]{
// new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS),
// }
// );
writePatternList(partition, 0, 1, writer);
// writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
// writer.writeCloseTag(SitePatternsParser.PATTERNS);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
// writePatternList(partition, 0, 1, writer);
// }
// }
}
}
/**
* Write a single pattern list
*
* @param partition the partition to write a pattern list for
* @param offset offset by
* @param every skip every
* @param writer the writer
*/
private void writePatternList(PartitionData partition, int offset, int every, XMLWriter writer) {
Alignment alignment = partition.getAlignment();
int from = partition.getFromSite();
int to = partition.getToSite();
int partEvery = partition.getEvery();
if (partEvery > 1 && every > 1) throw new IllegalArgumentException();
if (from < 1) from = 1;
every = Math.max(partEvery, every);
from += offset;
writer.writeComment("The unique patterns from " + from + " to " + (to > 0 ? to : "end") + ((every > 1) ? " every " + every : ""));
// this object is created solely to calculate the number of patterns in the alignment
SitePatterns patterns = new SitePatterns(alignment, from - 1, to - 1, every);
writer.writeComment("npatterns=" + patterns.getPatternCount());
List<Attribute> attributes = new ArrayList<Attribute>();
// no codon, unique patterns site patterns
if (offset == 0 && every == 1) attributes.add(new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS));
attributes.add(new Attribute.Default<String>("from", "" + from));
if (to >= 0) attributes.add(new Attribute.Default<String>("to", "" + to));
if (every > 1) {
attributes.add(new Attribute.Default<String>("every", "" + every));
}
// generate <patterns>
writer.writeOpenTag(SitePatternsParser.PATTERNS, attributes);
writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
writer.writeCloseTag(SitePatternsParser.PATTERNS);
}
/**
* Generate tmrca statistics
*
* @param writer the writer
*/
public void writeTMRCAStatistics(XMLWriter writer) {
writer.writeText("");
for (Taxa taxa : options.taxonSets) {
writer.writeOpenTag(
TMRCAStatistic.TMRCA_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "tmrca(" + taxa.getId() + ")"),
}
);
writer.writeOpenTag(TMRCAStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(TMRCAStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(TMRCAStatistic.TMRCA_STATISTIC);
if (options.taxonSetsMono.get(taxa)) {
writer.writeOpenTag(
MonophylyStatistic.MONOPHYLY_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "monophyly(" + taxa.getId() + ")"),
});
writer.writeOpenTag(MonophylyStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(MonophylyStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(MonophylyStatistic.MONOPHYLY_STATISTIC);
}
}
}
// /**
// * Write the operator schedule XML block.
// *
// * @param operators the list of operators
// * @param writer the writer
// */
// public void writeOperatorSchedule(List<Operator> operators, XMLWriter writer) {
// Attribute[] operatorAttributes;
//// switch (options.coolingSchedule) {
//// case SimpleOperatorSchedule.LOG_SCHEDULE:
// if (options.nodeHeightPrior == TreePrior.GMRF_SKYRIDE) {
// operatorAttributes = new Attribute[2];
// operatorAttributes[1] = new Attribute.Default<String>(SimpleOperatorSchedule.OPTIMIZATION_SCHEDULE, SimpleOperatorSchedule.LOG_STRING);
// } else {
//// break;
//// default:
// operatorAttributes = new Attribute[1];
// }
// operatorAttributes[0] = new Attribute.Default<String>(XMLParser.ID, "operators");
//
// writer.writeOpenTag(
// SimpleOperatorSchedule.OPERATOR_SCHEDULE,
// operatorAttributes
//// new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "operators")}
// );
//
// for (Operator operator : operators) {
// if (operator.weight > 0. && operator.inUse)
// writeOperator(operator, writer);
// }
//
// writer.writeCloseTag(SimpleOperatorSchedule.OPERATOR_SCHEDULE);
// }
// private void writeOperator(Operator operator, XMLWriter writer) {
//
// switch (operator.type) {
//
// case SCALE:
// writeScaleOperator(operator, writer);
// break;
// case RANDOM_WALK:
// writeRandomWalkOperator(operator, writer);
// case RANDOM_WALK_ABSORBING:
// writeRandomWalkOperator(operator, false, writer);
// break;
// case RANDOM_WALK_REFLECTING:
// writeRandomWalkOperator(operator, true, writer);
// break;
// case INTEGER_RANDOM_WALK:
// writeIntegerRandomWalkOperator(operator, writer);
// break;
// case UP_DOWN:
// writeUpDownOperator(operator, writer);
// break;
// case SCALE_ALL:
// writeScaleAllOperator(operator, writer);
// break;
// case SCALE_INDEPENDENTLY:
// writeScaleOperator(operator, writer, true);
// break;
// case CENTERED_SCALE:
// writeCenteredOperator(operator, writer);
// break;
// case DELTA_EXCHANGE:
// writeDeltaOperator(operator, writer);
// break;
// case INTEGER_DELTA_EXCHANGE:
// writeIntegerDeltaOperator(operator, writer);
// break;
// case SWAP:
// writeSwapOperator(operator, writer);
// break;
// case BITFLIP:
// writeBitFlipOperator(operator, writer);
// break;
// case TREE_BIT_MOVE:
// writeTreeBitMoveOperator(operator, writer);
// break;
// case UNIFORM:
// writeUniformOperator(operator, writer);
// break;
// case INTEGER_UNIFORM:
// writeIntegerUniformOperator(operator, writer);
// break;
// case SUBTREE_SLIDE:
// writeSubtreeSlideOperator(operator, writer);
// break;
// case NARROW_EXCHANGE:
// writeNarrowExchangeOperator(operator, writer);
// break;
// case WIDE_EXCHANGE:
// writeWideExchangeOperator(operator, writer);
// break;
// case WILSON_BALDING:
// writeWilsonBaldingOperator(operator, writer);
// break;
// case SAMPLE_NONACTIVE:
// writeSampleNonActiveOperator(operator, writer);
// break;
// case SCALE_WITH_INDICATORS:
// writeScaleWithIndicatorsOperator(operator, writer);
// break;
// case GMRF_GIBBS_OPERATOR:
// writeGMRFGibbsOperator(operator, writer);
// break;
// default:
// throw new IllegalArgumentException("Unknown operator type");
// }
// }
//
// private Attribute getRef(String name) {
// return new Attribute.Default<String>(XMLParser.IDREF, name);
// }
//
// private void writeParameterRefByName(XMLWriter writer, String name) {
// writer.writeTag(ParameterParser.PARAMETER, getRef(name), true);
// }
//
// private void writeParameter1Ref(XMLWriter writer, Operator operator) {
// writeParameterRefByName(writer, operator.parameter1.getName());
// }
//
// private void writeScaleOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeScaleOperator(Operator operator, XMLWriter writer, boolean indepedently) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("scaleAllIndependently", indepedently ? "true" : "false")
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeRandomWalkOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// "randomWalkOperator",
// new Attribute[]{
// new Attribute.Default<Double>("windowSize", operator.tuning),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkOperator");
// }
//
// private void writeRandomWalkOperator(Operator operator, boolean reflecting, XMLWriter writer) {
// writer.writeOpenTag(
// "randomWalkOperator",
// new Attribute[]{
// new Attribute.Default<Double>("windowSize", operator.tuning),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("boundaryCondition",
// (reflecting ? "reflecting" : "absorbing"))
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkOperator");
// }
//
// private void writeIntegerRandomWalkOperator(Operator operator, XMLWriter writer) {
//
// int windowSize = (int) Math.round(operator.tuning);
// if (windowSize < 1) windowSize = 1;
//
// writer.writeOpenTag(
// "randomWalkIntegerOperator",
// new Attribute[]{
// new Attribute.Default<Integer>("windowSize", windowSize),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkIntegerOperator");
// }
//
// private void writeScaleAllOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// new Attribute.Default<String>("scaleAll", "true"),
// getWeightAttribute(operator.weight)
// });
//
// if (operator.parameter2 == null) {
// writeParameter1Ref(writer, operator);
// } else {
// writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER);
// writeParameter1Ref(writer, operator);
// writer.writeIDref(ParameterParser.PARAMETER, operator.parameter2.getName());
// writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
// }
//
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeUpDownOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(UpDownOperator.UP_DOWN_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
//
// writer.writeOpenTag(UpDownOperator.UP);
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(UpDownOperator.UP);
//
// writer.writeOpenTag(UpDownOperator.DOWN);
// writer.writeIDref(ParameterParser.PARAMETER, operator.parameter2.getName());
// writer.writeCloseTag(UpDownOperator.DOWN);
//
// writer.writeCloseTag(UpDownOperator.UP_DOWN_OPERATOR);
// }
//
// private void writeCenteredOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(CenteredScaleOperator.CENTERED_SCALE,
// new Attribute[]{
// new Attribute.Default<Double>(CenteredScaleOperator.SCALE_FACTOR, operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(CenteredScaleOperator.CENTERED_SCALE);
// }
//
// private void writeDeltaOperator(Operator operator, XMLWriter writer) {
//
//
// if (operator.getName().equals("Relative rates")) {
//
// int[] parameterWeights = options.getPartitionWeights();
//
// if (parameterWeights != null && parameterWeights.length > 1) {
// String pw = "" + parameterWeights[0];
// for (int i = 1; i < parameterWeights.length; i++) {
// pw += " " + parameterWeights[i];
// }
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<Double>(DeltaExchangeOperator.DELTA, operator.tuning),
// new Attribute.Default<String>(DeltaExchangeOperator.PARAMETER_WEIGHTS, pw),
// getWeightAttribute(operator.weight)
// }
// );
// }
// } else {
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<Double>(DeltaExchangeOperator.DELTA, operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
// }
//
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(DeltaExchangeOperator.DELTA_EXCHANGE);
// }
//
// private void writeIntegerDeltaOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<String>(DeltaExchangeOperator.DELTA, Integer.toString((int) operator.tuning)),
// new Attribute.Default<String>("integer", "true"),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("autoOptimize", "false")
// }
// );
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(DeltaExchangeOperator.DELTA_EXCHANGE);
// }
//
// private void writeSwapOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SwapOperator.SWAP_OPERATOR,
// new Attribute[]{
// new Attribute.Default<String>("size", Integer.toString((int) operator.tuning)),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("autoOptimize", "false")
// }
// );
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(SwapOperator.SWAP_OPERATOR);
// }
//
// private void writeBitFlipOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(BitFlipOperator.BIT_FLIP_OPERATOR,
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(BitFlipOperator.BIT_FLIP_OPERATOR);
// }
//
// private void writeTreeBitMoveOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(TreeBitMoveOperator.BIT_MOVE_OPERATOR,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(TreeBitMoveOperator.BIT_MOVE_OPERATOR);
// }
//
// private void writeUniformOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag("uniformOperator",
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("uniformOperator");
// }
//
// private void writeIntegerUniformOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag("uniformIntegerOperator",
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("uniformIntegerOperator");
// }
//
// private void writeNarrowExchangeOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(ExchangeOperator.NARROW_EXCHANGE,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(ExchangeOperator.NARROW_EXCHANGE);
// }
//
// private void writeWideExchangeOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(ExchangeOperator.WIDE_EXCHANGE,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(ExchangeOperator.WIDE_EXCHANGE);
// }
//
// private void writeWilsonBaldingOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(WilsonBalding.WILSON_BALDING,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// // not supported anymore. probably never worked. (todo) get it out of GUI too
//// if (options.nodeHeightPrior == TreePrior.CONSTANT) {
//// treePriorGenerator.writeNodeHeightPriorModelRef(writer);
//// }
// writer.writeCloseTag(WilsonBalding.WILSON_BALDING);
// }
//
// private void writeSampleNonActiveOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SampleNonActiveGibbsOperator.SAMPLE_NONACTIVE_GIBBS_OPERATOR,
// getWeightAttribute(operator.weight));
//
// writer.writeOpenTag(SampleNonActiveGibbsOperator.DISTRIBUTION);
// writeParameterRefByName(writer, operator.getName());
// writer.writeCloseTag(SampleNonActiveGibbsOperator.DISTRIBUTION);
//
// writer.writeOpenTag(SampleNonActiveGibbsOperator.DATA_PARAMETER);
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(SampleNonActiveGibbsOperator.DATA_PARAMETER);
//
// writer.writeOpenTag(SampleNonActiveGibbsOperator.INDICATOR_PARAMETER);
// writeParameterRefByName(writer, operator.parameter2.getName());
// writer.writeCloseTag(SampleNonActiveGibbsOperator.INDICATOR_PARAMETER);
//
// writer.writeCloseTag(SampleNonActiveGibbsOperator.SAMPLE_NONACTIVE_GIBBS_OPERATOR);
// }
//
// private void writeGMRFGibbsOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// GMRFSkyrideBlockUpdateOperator.BLOCK_UPDATE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>(GMRFSkyrideBlockUpdateOperator.SCALE_FACTOR, operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
// writer.writeIDref(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD, "skyride");
// writer.writeCloseTag(GMRFSkyrideBlockUpdateOperator.BLOCK_UPDATE_OPERATOR);
// }
//
// private void writeScaleWithIndicatorsOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeOpenTag(ScaleOperator.INDICATORS, new Attribute.Default<String>(ScaleOperator.PICKONEPROB, "1.0"));
// writeParameterRefByName(writer, operator.parameter2.getName());
// writer.writeCloseTag(ScaleOperator.INDICATORS);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeSubtreeSlideOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SubtreeSlideOperator.SUBTREE_SLIDE,
// new Attribute[]{
// new Attribute.Default<Double>("size", operator.tuning),
// new Attribute.Default<String>("gaussian", "true"),
// getWeightAttribute(operator.weight)
// }
// );
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(SubtreeSlideOperator.SUBTREE_SLIDE);
// }
//
// private Attribute getWeightAttribute(double weight) {
// if (weight == (int)weight) {
// return new Attribute.Default<Integer>("weight", (int)weight);
// } else {
// return new Attribute.Default<Double>("weight", weight);
// }
// }
/**
* Write the timer report block.
*
* @param writer the writer
*/
public void writeTimerReport(XMLWriter writer) {
writer.writeOpenTag("report");
writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer"));
writer.writeIDref("mcmc", "mcmc");
writer.writeCloseTag("property");
writer.writeCloseTag("report");
}
/**
* Write the trace analysis block.
*
* @param writer the writer
*/
public void writeTraceAnalysis(XMLWriter writer) {
writer.writeTag(
"traceAnalysis",
new Attribute[]{
new Attribute.Default<String>("fileName", options.logFileName)
},
true
);
}
/**
* Write the MCMC block.
*
* @param writer
*/
public void writeMCMC(XMLWriter writer) {
writer.writeComment("Define MCMC");
writer.writeOpenTag(
"mcmc",
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "mcmc"),
new Attribute.Default<Integer>("chainLength", options.chainLength),
new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false")
});
if (options.hasData()) {
writer.writeOpenTag(CompoundLikelihood.POSTERIOR, new Attribute.Default<String>(XMLParser.ID, "posterior"));
}
// write prior block
writer.writeOpenTag(CompoundLikelihood.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior"));
if (options.isSpeciesAnalysis()) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, TraitGuesser.Traits.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePrior.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// }
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
}
writeParameterPriors(writer);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior;
if (options.shareSameTreePrior) {
prior = options.activedSameTreePrior;
} else {
prior = model.getPartitionTreePrior();
}
treePriorGenerator.writePriorLikelihoodReference(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographicReference(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer);
writer.writeCloseTag(CompoundLikelihood.PRIOR);
if (options.hasData()) {
// write likelihood block
writer.writeOpenTag(CompoundLikelihood.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood"));
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer);
writer.writeCloseTag(CompoundLikelihood.LIKELIHOOD);
writer.writeCloseTag(CompoundLikelihood.POSTERIOR);
}
writer.writeIDref(SimpleOperatorSchedule.OPERATOR_SCHEDULE, "operators");
// write log to screen
writeLogToScreen(writer);
// write log to file
writeLogToFile(writer);
// write tree log to file
writeTreeLogToFile(writer);
writer.writeCloseTag("mcmc");
}
/**
* write log to screen
*
* @param writer
*/
private void writeLogToScreen(XMLWriter writer) {
writer.writeComment("write log to screen");
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "screenLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.echoEvery + "")
});
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Posterior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Prior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
writer.writeCloseTag(Columns.COLUMN);
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Likelihood"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
writer.writeCloseTag(Columns.COLUMN);
}
if (options.isSpeciesAnalysis()) { // species
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "PopMean"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.POP_MEAN);
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Root Height"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
writer.writeCloseTag(Columns.COLUMN);
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Rate"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.STRICT_CLOCK) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + "clock.rate");
} else {
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) { // borrow the method in BeautiOption
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + "meanRate");
}
}
}
writer.writeCloseTag(Columns.COLUMN);
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.RANDOM_LOCAL_CLOCK) {
writeSumStatisticColumn(writer, model.getPrefix() + "rateChanges", "Rate Changes");
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_SCREEN_LOG, writer);
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SCREEN_LOG, writer);
}
/**
* write log to file
*
* @param writer
*/
private void writeLogToFile(XMLWriter writer) {
writer.writeComment("write log to file");
if (options.logFileName == null) {
options.logFileName = options.fileNameStem + ".log";
}
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "fileLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(LoggerParser.FILE_NAME, options.logFileName)
});
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
}
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
}
if (options.isSpeciesAnalysis()) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, TraitGuesser.Traits.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePrior.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// }
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.POP_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, SpeciesTreeModel.SPECIES_TREE + "." + SPLIT_POPS);
if (options.activedSameTreePrior.getNodeHeightPrior() == TreePrior.SPECIES_BIRTH_DEATH) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME);
} else if (options.activedSameTreePrior.getNodeHeightPrior() == TreePrior.SPECIES_YULE) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE);
} else {
throw new IllegalArgumentException("Get wrong species tree prior using *BEAST : " + options.activedSameTreePrior.getNodeHeightPrior().toString());
}
//Species Tree: tmrcaStatistic
writer.writeIDref(TMRCAStatistic.TMRCA_STATISTIC, SpeciesTreeModel.SPECIES_TREE + "." + TreeModelParser.ROOT_HEIGHT);
}
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.STRICT_CLOCK) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + "clock.rate");
} else {
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) { // borrow the method in BeautiOption
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + "meanRate");
}
}
}
for (Taxa taxa : options.taxonSets) {
writer.writeIDref("tmrcaStatistic", "tmrca(" + taxa.getId() + ")");
}
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeParameterLog(options.activedSameTreePrior, writer);
// } else { // no species
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // priorName.treeModel
treePriorGenerator.writeParameterLog(prior, writer);
}
// }
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeLog(writer, model);
}
if (options.hasCodon()) {
writer.writeIDref(ParameterParser.PARAMETER, "allMus");
}
for (PartitionClockModel model : options.getPartitionClockModels()) {
switch (model.getClockType()) {
case STRICT_CLOCK:
break;
case UNCORRELATED_EXPONENTIAL:
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCED_MEAN);
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
case UNCORRELATED_LOGNORMAL:
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_STDEV);
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
case AUTOCORRELATED_LOGNORMAL:
// writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + "branchRates.var");
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + tree.getPrefix() + "branchRates.var");
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + tree.getPrefix() + "treeModel.rootRate");
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
case RANDOM_LOCAL_CLOCK:
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(SumStatistic.SUM_STATISTIC, model.getPrefix() + "rateChanges");
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(SumStatistic.SUM_STATISTIC, model.getPrefix() + tree.getPrefix() + "rateChanges");
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_PARAMETERS, writer);
if (options.hasData()) {
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_LIKELIHOODS, writer);
// coalescentLikelihood
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior;
if (options.shareSameTreePrior) {
prior = options.activedSameTreePrior;
} else {
prior = model.getPartitionTreePrior();
}
treePriorGenerator.writePriorLikelihoodReferenceLog(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePrior.EXTENDED_SKYLINE)
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, prior.getPrefix() + COALESCENT); // only 1 coalescent
}
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_FILE_LOG, writer);
}
/**
* write tree log to file
*
* @param writer
*/
private void writeTreeLogToFile(XMLWriter writer) {
writer.writeComment("write tree log to file");
if (options.isSpeciesAnalysis()) { // species
// species tree log
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, TraitGuesser.Traits.TRAIT_SPECIES + "." + TREE_FILE_LOG), // speciesTreeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + options.SPECIES_TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(SpeciesTreeModel.SPECIES_TREE, SP_TREE);
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
// gene tree log
//TODO make code consistent to MCMCPanel
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
String treeFileName;
if (options.substTreeLog) {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + "(time)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME;
} else {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + GMRFFixedGridImportanceSampler.TREE_FILE_NAME; // stem.partitionName.tree
}
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + TREE_FILE_LOG), // partionName.treeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, treeFileName),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
for (PartitionClockModel model : options.getPartitionClockModels(tree.getAllPartitionData())) {
switch (model.getClockType()) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
} // end For loop
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TREES_LOG, writer);
if (options.substTreeLog) {
if (options.isSpeciesAnalysis()) { // species
//TODO: species sub tree
}
// gene tree
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
// write tree log to file
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + SUB_TREE_FILE_LOG),
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + tree.getPrefix() +
"(subst)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.BRANCH_LENGTHS, TreeLoggerParser.SUBSTITUTIONS)
});
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
for (PartitionClockModel model : options.getPartitionClockModels(tree.getAllPartitionData())) {
switch (model.getClockType()) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREES_LOG, writer);
}
/**
* Write the priors for each parameter
*
* @param writer the writer
*/
private void writeParameterPriors(XMLWriter writer) {
boolean first = true;
for (Map.Entry<Taxa, Boolean> taxaBooleanEntry : options.taxonSetsMono.entrySet()) {
if (taxaBooleanEntry.getValue()) {
if (first) {
writer.writeOpenTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
first = false;
}
final String taxaRef = "monophyly(" + taxaBooleanEntry.getKey().getId() + ")";
writer.writeIDref(MonophylyStatistic.MONOPHYLY_STATISTIC, taxaRef);
}
}
if (!first) {
writer.writeCloseTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
}
ArrayList<Parameter> parameters = options.selectParameters();
for (Parameter parameter : parameters) {
if (parameter.priorType != PriorType.NONE) {
if (parameter.priorType != PriorType.UNIFORM_PRIOR || parameter.isNodeHeight) {
writeParameterPrior(parameter, writer);
}
}
}
}
/**
* Write the priors for each parameter
*
* @param parameter the parameter
* @param writer the writer
*/
private void writeParameterPrior(dr.app.beauti.options.Parameter parameter, XMLWriter writer) {
switch (parameter.priorType) {
case UNIFORM_PRIOR:
writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR);
break;
case EXPONENTIAL_PRIOR:
writer.writeOpenTag(PriorParsers.EXPONENTIAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.exponentialMean),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.exponentialOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.EXPONENTIAL_PRIOR);
break;
case NORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.NORMAL_PRIOR);
break;
case LOGNORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.LOG_NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.logNormalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.logNormalStdev),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.logNormalOffset),
// this is to be implemented...
new Attribute.Default<String>(PriorParsers.MEAN_IN_REAL_SPACE, "false")
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.LOG_NORMAL_PRIOR);
break;
case GAMMA_PRIOR:
writer.writeOpenTag(PriorParsers.GAMMA_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.SHAPE, "" + parameter.gammaAlpha),
new Attribute.Default<String>(PriorParsers.SCALE, "" + parameter.gammaBeta),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.gammaOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.GAMMA_PRIOR);
break;
case JEFFREYS_PRIOR:
writer.writeOpenTag(OneOnXPrior.ONE_ONE_X_PRIOR);
writeParameterIdref(writer, parameter);
writer.writeCloseTag(OneOnXPrior.ONE_ONE_X_PRIOR);
break;
case POISSON_PRIOR:
writer.writeOpenTag(PriorParsers.POISSON_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.poissonMean),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.poissonOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.POISSON_PRIOR);
break;
case TRUNC_NORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR);
writer.writeOpenTag(PriorParsers.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.NORMAL_PRIOR);
break;
default:
throw new IllegalArgumentException("Unknown priorType");
}
}
private void writeParameterIdref(XMLWriter writer, dr.app.beauti.options.Parameter parameter) {
if (parameter.isStatistic) {
writer.writeIDref("statistic", parameter.getName());
} else {
writer.writeIDref(ParameterParser.PARAMETER, parameter.getName());
}
}
}
| src/dr/app/beauti/generator/BeastGenerator.java | /*
* BeastGenerator.java
*
* Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.app.beauti.generator;
import dr.app.beast.BeastVersion;
import dr.app.beauti.components.ComponentFactory;
import dr.app.beauti.options.*;
import dr.app.beauti.options.Parameter;
import dr.app.beauti.priorsPanel.PriorType;
import dr.app.beauti.util.XMLWriter;
import dr.evolution.alignment.Alignment;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.evolution.util.Units;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.StrictClockBranchRates;
import dr.evomodel.clock.ACLikelihood;
import dr.evomodel.coalescent.CoalescentLikelihood;
import dr.evomodel.coalescent.GMRFFixedGridImportanceSampler;
import dr.evomodel.speciation.SpeciationLikelihood;
import dr.evomodel.speciation.SpeciesTreeBMPrior;
import dr.evomodel.speciation.SpeciesTreeModel;
import dr.evomodel.speciation.TreePartitionCoalescent;
import dr.evomodel.tree.*;
import dr.evomodelxml.*;
import dr.evoxml.*;
import dr.inference.distribution.MixedDistributionLikelihood;
import dr.inference.loggers.Columns;
import dr.inference.model.*;
import dr.inference.operators.SimpleOperatorSchedule;
import dr.inference.xml.LoggerParser;
import dr.inferencexml.PriorParsers;
import dr.util.Attribute;
import dr.util.Version;
import dr.xml.AttributeParser;
import dr.xml.XMLParser;
import java.io.Writer;
import java.util.*;
/**
* This class holds all the data for the current BEAUti Document
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Walter Xie
* @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $
*/
public class BeastGenerator extends Generator {
private final static Version version = new BeastVersion();
private final static String TREE_FILE_LOG = "treeFileLog";
private final static String SUB_TREE_FILE_LOG = "substTreeFileLog";
private final TreePriorGenerator treePriorGenerator;
private final TreeLikelihoodGenerator treeLikelihoodGenerator;
private final SubstitutionModelGenerator substitutionModelGenerator;
private final InitialTreeGenerator initialTreeGenerator;
private final TreeModelGenerator treeModelGenerator;
private final BranchRatesModelGenerator branchRatesModelGenerator;
private final OperatorsGenerator operatorsGenerator;
private final STARBEASTGenerator starEASTGeneratorGenerator;
public BeastGenerator(BeautiOptions options, ComponentFactory[] components) {
super(options, components);
substitutionModelGenerator = new SubstitutionModelGenerator(options, components);
treePriorGenerator = new TreePriorGenerator(options, components);
treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components);
initialTreeGenerator = new InitialTreeGenerator(options, components);
treeModelGenerator = new TreeModelGenerator(options, components);
branchRatesModelGenerator = new BranchRatesModelGenerator(options, components);
operatorsGenerator = new OperatorsGenerator(options, components);
starEASTGeneratorGenerator = new STARBEASTGenerator(options, components);
}
/**
* Checks various options to check they are valid. Throws IllegalArgumentExceptions with
* descriptions of the problems.
*
* @throws IllegalArgumentException if there is a problem with the current settings
*/
public void checkOptions() throws IllegalArgumentException {
//++++++++++++++++ Taxon List ++++++++++++++++++
TaxonList taxonList = options.taxonList;
Set<String> ids = new HashSet<String>();
ids.add(TaxaParser.TAXA);
ids.add(AlignmentParser.ALIGNMENT);
if (taxonList != null) {
if (taxonList.getTaxonCount() < 2) {
throw new IllegalArgumentException("BEAST requires at least two taxa to run.");
}
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
if (ids.contains(taxon.getId())) {
throw new IllegalArgumentException("A taxon has the same id," + taxon.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxon.getId());
}
}
//++++++++++++++++ Taxon Sets ++++++++++++++++++
for (Taxa taxa : options.taxonSets) {
if (taxa.getTaxonCount() < 2) {
throw new IllegalArgumentException("Taxon set, " + taxa.getId() + ", should contain\n" +
"at least two taxa.");
}
if (ids.contains(taxa.getId())) {
throw new IllegalArgumentException("A taxon sets has the same id," + taxa.getId() +
"\nas another element (taxon, sequence, taxon set etc.):\nAll ids should be unique.");
}
ids.add(taxa.getId());
}
//++++++++++++++++ Tree Prior ++++++++++++++++++
if (options.shareSameTreePrior) {
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePrior.GMRF_SKYRIDE) {
throw new IllegalArgumentException("For GMRF, tree model/tree prior combination not implemented by BEAST yet!" +
"\nPlease uncheck the shareSameTreePrior if using GMRF.");
}
}
}
//++++++++++++++++ clock model/tree model combination ++++++++++++++++++
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// clock model/tree model combination not implemented by BEAST yet
validateClockTreeModelCombination(model);
}
//++++++++++++++++ Species tree ++++++++++++++++++
if (options.isSpeciesAnalysis()) {
// if (!(options.nodeHeightPrior == TreePrior.SPECIES_BIRTH_DEATH || options.nodeHeightPrior == TreePrior.SPECIES_YULE)) {
// //TODO: more species tree model
// throw new IllegalArgumentException("Species analysis requires to define species tree prior in Tree panel.");
// }
}
// add other tests and warnings here
// Speciation model with dated tips
// Sampling rates without dated tips or priors on rate or nodes
}
/**
* Generate a beast xml file from these beast options
*
* @param w the writer
*/
public void generateXML(Writer w) {
XMLWriter writer = new XMLWriter(w);
writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
writer.writeComment("Generated by BEAUTi " + version.getVersionString());
writer.writeComment(" by Alexei J. Drummond and Andrew Rambaut");
writer.writeComment(" Department of Computer Science, University of Auckland and");
writer.writeComment(" Institute of Evolutionary Biology, University of Edinburgh");
writer.writeComment(" http://beast.bio.ed.ac.uk/");
writer.writeOpenTag("beast");
writer.writeText("");
// this gives any added implementations of the 'Component' interface a
// chance to generate XML at this point in the BEAST file.
generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
//++++++++++++++++ Taxon List ++++++++++++++++++
writeTaxa(writer, options.taxonList);
List<Taxa> taxonSets = options.taxonSets;
if (taxonSets != null && taxonSets.size() > 0) {
writeTaxonSets(writer, taxonSets); // TODO
}
if (options.allowDifferentTaxa) { // allow diff taxa for multi-gene
writer.writeText("");
writer.writeComment("List all taxons regarding each gene (file) for Multispecies Coalescent function");
// write all taxa in each gene tree regarding each data partition,
for (PartitionData partition : options.dataPartitions) {
// do I need if (!alignments.contains(alignment)) {alignments.add(alignment);} ?
writeDifferentTaxaForMultiGene(partition, writer);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
//++++++++++++++++ Alignments ++++++++++++++++++
List<Alignment> alignments = new ArrayList<Alignment>();
for (PartitionData partition : options.dataPartitions) {
Alignment alignment = partition.getAlignment();
if (!alignments.contains(alignment)) {
alignments.add(alignment);
}
}
if (!options.samplePriorOnly) {
int index = 1;
for (Alignment alignment : alignments) {
if (alignments.size() > 1) {
//if (!options.allowDifferentTaxa) {
alignment.setId(AlignmentParser.ALIGNMENT + index);
//} else { // e.g. alignment_gene1
// alignment.setId("alignment_" + mulitTaxaTagName + index);
//}
} else {
alignment.setId(AlignmentParser.ALIGNMENT);
}
writeAlignment(alignment, writer);
index += 1;
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
//++++++++++++++++ Pattern Lists ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// writePatternList(model, writer);
for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
writePatternList(partition, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
} else {
Alignment alignment = alignments.get(0);
alignment.setId(AlignmentParser.ALIGNMENT);
writeAlignment(alignment, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
}
//++++++++++++++++ Tree Prior Model ++++++++++++++++++
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeTreePriorModel(options.activedSameTreePrior, writer);
// } else { // Different Tree Priors
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // prior.constant
treePriorGenerator.writeTreePriorModel(prior, writer);
writer.writeText("");
}
// }
//++++++++++++++++ Starting Tree ++++++++++++++++++
// if ( options.getPartitionTreeModels().size() == 1 ) { // 1 Partition Tree Model
// initialTreeGenerator.setModelPrefix("");
// initialTreeGenerator.writeStartingTree(options.getPartitionTreeModels().get(0), writer);
// } else { // Different Tree Models
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// initialTreeGenerator.setModelPrefix(model.getPrefix()); // model.startingTree
initialTreeGenerator.writeStartingTree(model, writer);
writer.writeText("");
}
// }
//++++++++++++++++ Tree Model +++++++++++++++++++
// if ( options.getPartitionTreeModels().size() == 1 ) { // 1 Partition Tree Model
// treeModelGenerator.setModelPrefix("");
// treeModelGenerator.writeTreeModel(writer);
// } else { // Different Tree Models
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
// treeModelGenerator.setModelPrefix(model.getPrefix()); // treemodel.treeModel
treeModelGenerator.writeTreeModel(model, writer);
writer.writeText("");
}
// }
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
//++++++++++++++++ Tree Prior ++++++++++++++++++
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeTreePrior(options.activedSameTreePrior, writer);
// } else { // no species
// for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // prior.treeModel
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior;
if (options.shareSameTreePrior) {
prior = options.activedSameTreePrior;
} else {
prior = model.getPartitionTreePrior();
}
treePriorGenerator.writePriorLikelihood(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographic(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
//++++++++++++++++ Branch Rates Model ++++++++++++++++++
// if ( options.getPartitionClockModels().size() == 1 ) { // 1 Partition Clock Model
// branchRatesModelGenerator.setModelPrefix("");
// branchRatesModelGenerator.writeBranchRatesModel(writer);
// } else { // Different Tree Models
for (PartitionClockModel model : options.getPartitionClockModels()) {
// branchRatesModelGenerator.setModelPrefix(model.getPrefix()); // model.startingTree
// for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
branchRatesModelGenerator.writeBranchRatesModel(model, writer);
// }
writer.writeText("");
}
// }
//++++++++++++++++ Substitution Model ++++++++++++++++++
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSubstitutionModel(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
//++++++++++++++++ Site Model ++++++++++++++++++
boolean writeMuParameters = options.hasCodon(); //options.getTotalActivePartitionSubstitutionModelCount() > 1;
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeSiteModel(model, writeMuParameters, writer);
writer.writeText("");
}
if (writeMuParameters) {
// allMus is global
writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "allMus")});
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeMuParameterRefs(model, writer);
}
writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
//++++++++++++++++ Tree Likelihood ++++++++++++++++++
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// if ( options.isSpeciesAnalysis() ) { // species
// treeLikelihoodGenerator.setModelPrefix(model.getName() + ".");
// } else {
// treeLikelihoodGenerator.setModelPrefix("");
// }
// //TODO: need merge genePrifx and prefix
//// for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
// treeLikelihoodGenerator.writeTreeLikelihood(model, writer);
// writer.writeText("");
// }
for (PartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
treeLikelihoodGenerator.writeTreeLikelihood(partition, writer);
// for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
// treeLikelihoodGenerator.writeTreeLikelihood(model, writer);
writer.writeText("");
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
//++++++++++++++++ Traits ++++++++++++++++++
// traits tag
if (options.selecetedTraits.size() > 0) {
for (String trait : options.selecetedTraits) {
TraitGuesser.TraitType traiType = options.traitTypes.get(trait);
writeTraits(writer, trait, traiType.toString(), options.taxonList);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
}
//++++++++++++++++ ++++++++++++++++++
if (taxonSets != null && taxonSets.size() > 0) {
//TODO: need to suit for multi-gene-tree
writeTMRCAStatistics(writer);
}
//++++++++++++++++ Operators ++++++++++++++++++
List<Operator> operators = options.selectOperators();
operatorsGenerator.writeOperatorSchedule(operators, writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
//++++++++++++++++ MCMC ++++++++++++++++++
// XMLWriter writer, List<PartitionSubstitutionModel> models,
writeMCMC(writer);
writer.writeText("");
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
//++++++++++++++++ ++++++++++++++++++
writeTimerReport(writer);
writer.writeText("");
if (options.performTraceAnalysis) {
writeTraceAnalysis(writer);
}
if (options.generateCSV) {
if (options.shareSameTreePrior) { // Share Same Tree Prior
treePriorGenerator.setModelPrefix("");
treePriorGenerator.writeEBSPAnalysisToCSVfile(options.activedSameTreePrior, writer);
} else { // no species
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.setModelPrefix(prior.getName() + "."); // partitionName.constant
treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer);
}
}
}
writer.writeCloseTag("beast");
writer.flush();
}
/**
* Generate a taxa block from these beast options
*
* @param writer the writer
* @param taxonList the taxon list to write
*/
private void writeTaxa(XMLWriter writer, TaxonList taxonList) {
// -1 (single taxa), 0 (1st gene of multi-taxa)
writer.writeComment("The list of taxa analyse (can also include dates/ages).");
writer.writeComment("ntax=" + taxonList.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)});
boolean firstDate = true;
for (int i = 0; i < taxonList.getTaxonCount(); i++) {
Taxon taxon = taxonList.getTaxon(i);
boolean hasDate = false;
if (options.maximumTipHeight > 0.0) {
hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE);
}
writer.writeTag(TaxonParser.TAXON, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, taxon.getId())}, !hasDate);
if (hasDate) {
dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
if (firstDate) {
options.units = date.getUnits();
firstDate = false;
} else {
if (options.units != date.getUnits()) {
System.err.println("Error: Units in dates do not match.");
}
}
Attribute[] attributes = {
new Attribute.Default<Double>(ParameterParser.VALUE, date.getTimeValue()),
new Attribute.Default<String>("direction", date.isBackwards() ? "backwards" : "forwards"),
new Attribute.Default<String>("units", Units.Utils.getDefaultUnitName(options.units))
/*,
new Attribute.Default("origin", date.getOrigin()+"")*/
};
writer.writeTag(dr.evolution.util.Date.DATE, attributes, true);
writer.writeCloseTag(TaxonParser.TAXON);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer);
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate additional taxon sets
*
* @param writer the writer
* @param taxonSets a list of taxa to write
*/
private void writeTaxonSets(XMLWriter writer, List<Taxa> taxonSets) {
writer.writeText("");
for (Taxa taxa : taxonSets) {
writer.writeOpenTag(
TaxaParser.TAXA,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, taxa.getId())
}
);
for (int j = 0; j < taxa.getTaxonCount(); j++) {
writer.writeIDref(TaxonParser.TAXON, taxa.getTaxon(j).getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
}
/**
* Determine and return the datatype description for these beast options
* note that the datatype in XML may differ from the actual datatype
*
* @param alignment the alignment to get data type description of
* @return description
*/
private String getAlignmentDataTypeDescription(Alignment alignment) {
String description;
switch (alignment.getDataType().getType()) {
case DataType.TWO_STATES:
case DataType.COVARION:
// TODO make this work
throw new RuntimeException("TO DO!");
//switch (partition.getPartitionSubstitutionModel().binarySubstitutionModel) {
// case ModelOptions.BIN_COVARION:
// description = TwoStateCovarion.DESCRIPTION;
// break;
//
// default:
// description = alignment.getDataType().getDescription();
//}
//break;
default:
description = alignment.getDataType().getDescription();
}
return description;
}
public void writeDifferentTaxaForMultiGene(PartitionData dataPartition, XMLWriter writer) {
String data = dataPartition.getName();
Alignment alignment = dataPartition.getAlignment();
writer.writeComment("gene name = " + data + ", ntax= " + alignment.getTaxonCount());
writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, data + "." + TaxaParser.TAXA)});
for (int i = 0; i < alignment.getTaxonCount(); i++) {
final Taxon taxon = alignment.getTaxon(i);
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
}
writer.writeCloseTag(TaxaParser.TAXA);
}
/**
* Generate an alignment block from these beast options
*
* @param alignment the alignment to write
* @param writer the writer
*/
public void writeAlignment(Alignment alignment, XMLWriter writer) {
writer.writeText("");
writer.writeComment("The sequence alignment (each sequence refers to a taxon above).");
writer.writeComment("ntax=" + alignment.getTaxonCount() + " nchar=" + alignment.getSiteCount());
if (options.samplePriorOnly) {
writer.writeComment("Null sequences generated in order to sample from the prior only.");
}
writer.writeOpenTag(
AlignmentParser.ALIGNMENT,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, alignment.getId()),
new Attribute.Default<String>("dataType", getAlignmentDataTypeDescription(alignment))
}
);
for (int i = 0; i < alignment.getTaxonCount(); i++) {
Taxon taxon = alignment.getTaxon(i);
writer.writeOpenTag("sequence");
writer.writeIDref(TaxonParser.TAXON, taxon.getId());
if (!options.samplePriorOnly) {
writer.writeText(alignment.getAlignedSequenceString(i));
} else {
writer.writeText("N");
}
writer.writeCloseTag("sequence");
}
writer.writeCloseTag(AlignmentParser.ALIGNMENT);
}
/**
* Generate traits block regarding specific trait name (currently only <species>) from options
*
* @param writer
* @param trait
* @param traitType
* @param taxonList
*/
private void writeTraits(XMLWriter writer, String trait, String traitType, TaxonList taxonList) {
writer.writeText("");
if (options.isSpeciesAnalysis()) { // species
writer.writeComment("Species definition: binds taxa, species and gene trees");
}
writer.writeComment("trait = " + trait + " trait_type = " + traitType);
writer.writeOpenTag(trait, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, trait)});
//new Attribute.Default<String>("traitType", traitType)});
// write sub-tags for species
if (options.isSpeciesAnalysis()) { // species
starEASTGeneratorGenerator.writeMultiSpecies(taxonList, writer);
} // end write sub-tags for species
writer.writeCloseTag(trait);
if (options.isSpeciesAnalysis()) { // species
starEASTGeneratorGenerator.writeSTARBEAST(writer);
}
}
/**
* Writes the pattern lists
*
* @param partition the partition data to write the pattern lists for
* @param writer the writer
*/
public void writePatternList(PartitionData partition, XMLWriter writer) {
writer.writeText("");
PartitionSubstitutionModel model = partition.getPartitionSubstitutionModel();
String codonHeteroPattern = model.getCodonHeteroPattern();
int partitionCount = model.getCodonPartitionCount();
if (model.getDataType() == Nucleotides.INSTANCE && codonHeteroPattern != null && partitionCount > 1) {
if (codonHeteroPattern.equals("112")) {
writer.writeComment("The unique patterns for codon positions 1 & 2");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(1) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, 0, 3, writer);
writePatternList(partition, 1, 3, writer);
// }
// }
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
writer.writeComment("The unique patterns for codon positions 3");
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(2) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, 2, 3, writer);
// }
// }
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
} else {
// pattern is 123
// write pattern lists for all three codon positions
for (int i = 1; i <= 3; i++) {
writer.writeComment("The unique patterns for codon positions " + i);
writer.writeOpenTag(MergePatternsParser.MERGE_PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, model.getPrefix(i) + partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
writePatternList(partition, i - 1, 3, writer);
// }
// }
writer.writeCloseTag(MergePatternsParser.MERGE_PATTERNS);
}
}
} else {
//partitionCount = 1;
writer.writeComment("The unique patterns site patterns");
Alignment alignment = partition.getAlignment();
writer.writeOpenTag(SitePatternsParser.PATTERNS,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS),
}
);
writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
writer.writeCloseTag(SitePatternsParser.PATTERNS);
// for (PartitionData partition : options.dataPartitions) {
// if (partition.getPartitionSubstitutionModel() == model) {
// writePatternList(partition, 0, 1, writer);
// }
// }
}
}
/**
* Write a single pattern list
*
* @param partition the partition to write a pattern list for
* @param offset offset by
* @param every skip every
* @param writer the writer
*/
private void writePatternList(PartitionData partition, int offset, int every, XMLWriter writer) {
Alignment alignment = partition.getAlignment();
int from = partition.getFromSite();
int to = partition.getToSite();
int partEvery = partition.getEvery();
if (partEvery > 1 && every > 1) throw new IllegalArgumentException();
if (from < 1) from = 1;
every = Math.max(partEvery, every);
from += offset;
writer.writeComment("The unique patterns from " + from + " to " + (to > 0 ? to : "end") + ((every > 1) ? " every " + every : ""));
// this object is created solely to calculate the number of patterns in the alignment
SitePatterns patterns = new SitePatterns(alignment, from - 1, to - 1, every);
writer.writeComment("npatterns=" + patterns.getPatternCount());
List<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(new Attribute.Default<String>("from", "" + from));
if (to >= 0) attributes.add(new Attribute.Default<String>("to", "" + to));
if (every > 1) {
attributes.add(new Attribute.Default<String>("every", "" + every));
}
writer.writeOpenTag(SitePatternsParser.PATTERNS, attributes);
writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
writer.writeCloseTag(SitePatternsParser.PATTERNS);
}
/**
* Generate tmrca statistics
*
* @param writer the writer
*/
public void writeTMRCAStatistics(XMLWriter writer) {
writer.writeText("");
for (Taxa taxa : options.taxonSets) {
writer.writeOpenTag(
TMRCAStatistic.TMRCA_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "tmrca(" + taxa.getId() + ")"),
}
);
writer.writeOpenTag(TMRCAStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(TMRCAStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(TMRCAStatistic.TMRCA_STATISTIC);
if (options.taxonSetsMono.get(taxa)) {
writer.writeOpenTag(
MonophylyStatistic.MONOPHYLY_STATISTIC,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "monophyly(" + taxa.getId() + ")"),
});
writer.writeOpenTag(MonophylyStatistic.MRCA);
writer.writeIDref(TaxaParser.TAXA, taxa.getId());
writer.writeCloseTag(MonophylyStatistic.MRCA);
writer.writeIDref(TreeModel.TREE_MODEL, TreeModel.TREE_MODEL);
writer.writeCloseTag(MonophylyStatistic.MONOPHYLY_STATISTIC);
}
}
}
// /**
// * Write the operator schedule XML block.
// *
// * @param operators the list of operators
// * @param writer the writer
// */
// public void writeOperatorSchedule(List<Operator> operators, XMLWriter writer) {
// Attribute[] operatorAttributes;
//// switch (options.coolingSchedule) {
//// case SimpleOperatorSchedule.LOG_SCHEDULE:
// if (options.nodeHeightPrior == TreePrior.GMRF_SKYRIDE) {
// operatorAttributes = new Attribute[2];
// operatorAttributes[1] = new Attribute.Default<String>(SimpleOperatorSchedule.OPTIMIZATION_SCHEDULE, SimpleOperatorSchedule.LOG_STRING);
// } else {
//// break;
//// default:
// operatorAttributes = new Attribute[1];
// }
// operatorAttributes[0] = new Attribute.Default<String>(XMLParser.ID, "operators");
//
// writer.writeOpenTag(
// SimpleOperatorSchedule.OPERATOR_SCHEDULE,
// operatorAttributes
//// new Attribute[]{new Attribute.Default<String>(XMLParser.ID, "operators")}
// );
//
// for (Operator operator : operators) {
// if (operator.weight > 0. && operator.inUse)
// writeOperator(operator, writer);
// }
//
// writer.writeCloseTag(SimpleOperatorSchedule.OPERATOR_SCHEDULE);
// }
// private void writeOperator(Operator operator, XMLWriter writer) {
//
// switch (operator.type) {
//
// case SCALE:
// writeScaleOperator(operator, writer);
// break;
// case RANDOM_WALK:
// writeRandomWalkOperator(operator, writer);
// case RANDOM_WALK_ABSORBING:
// writeRandomWalkOperator(operator, false, writer);
// break;
// case RANDOM_WALK_REFLECTING:
// writeRandomWalkOperator(operator, true, writer);
// break;
// case INTEGER_RANDOM_WALK:
// writeIntegerRandomWalkOperator(operator, writer);
// break;
// case UP_DOWN:
// writeUpDownOperator(operator, writer);
// break;
// case SCALE_ALL:
// writeScaleAllOperator(operator, writer);
// break;
// case SCALE_INDEPENDENTLY:
// writeScaleOperator(operator, writer, true);
// break;
// case CENTERED_SCALE:
// writeCenteredOperator(operator, writer);
// break;
// case DELTA_EXCHANGE:
// writeDeltaOperator(operator, writer);
// break;
// case INTEGER_DELTA_EXCHANGE:
// writeIntegerDeltaOperator(operator, writer);
// break;
// case SWAP:
// writeSwapOperator(operator, writer);
// break;
// case BITFLIP:
// writeBitFlipOperator(operator, writer);
// break;
// case TREE_BIT_MOVE:
// writeTreeBitMoveOperator(operator, writer);
// break;
// case UNIFORM:
// writeUniformOperator(operator, writer);
// break;
// case INTEGER_UNIFORM:
// writeIntegerUniformOperator(operator, writer);
// break;
// case SUBTREE_SLIDE:
// writeSubtreeSlideOperator(operator, writer);
// break;
// case NARROW_EXCHANGE:
// writeNarrowExchangeOperator(operator, writer);
// break;
// case WIDE_EXCHANGE:
// writeWideExchangeOperator(operator, writer);
// break;
// case WILSON_BALDING:
// writeWilsonBaldingOperator(operator, writer);
// break;
// case SAMPLE_NONACTIVE:
// writeSampleNonActiveOperator(operator, writer);
// break;
// case SCALE_WITH_INDICATORS:
// writeScaleWithIndicatorsOperator(operator, writer);
// break;
// case GMRF_GIBBS_OPERATOR:
// writeGMRFGibbsOperator(operator, writer);
// break;
// default:
// throw new IllegalArgumentException("Unknown operator type");
// }
// }
//
// private Attribute getRef(String name) {
// return new Attribute.Default<String>(XMLParser.IDREF, name);
// }
//
// private void writeParameterRefByName(XMLWriter writer, String name) {
// writer.writeTag(ParameterParser.PARAMETER, getRef(name), true);
// }
//
// private void writeParameter1Ref(XMLWriter writer, Operator operator) {
// writeParameterRefByName(writer, operator.parameter1.getName());
// }
//
// private void writeScaleOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeScaleOperator(Operator operator, XMLWriter writer, boolean indepedently) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("scaleAllIndependently", indepedently ? "true" : "false")
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeRandomWalkOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// "randomWalkOperator",
// new Attribute[]{
// new Attribute.Default<Double>("windowSize", operator.tuning),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkOperator");
// }
//
// private void writeRandomWalkOperator(Operator operator, boolean reflecting, XMLWriter writer) {
// writer.writeOpenTag(
// "randomWalkOperator",
// new Attribute[]{
// new Attribute.Default<Double>("windowSize", operator.tuning),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("boundaryCondition",
// (reflecting ? "reflecting" : "absorbing"))
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkOperator");
// }
//
// private void writeIntegerRandomWalkOperator(Operator operator, XMLWriter writer) {
//
// int windowSize = (int) Math.round(operator.tuning);
// if (windowSize < 1) windowSize = 1;
//
// writer.writeOpenTag(
// "randomWalkIntegerOperator",
// new Attribute[]{
// new Attribute.Default<Integer>("windowSize", windowSize),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("randomWalkIntegerOperator");
// }
//
// private void writeScaleAllOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// new Attribute.Default<String>("scaleAll", "true"),
// getWeightAttribute(operator.weight)
// });
//
// if (operator.parameter2 == null) {
// writeParameter1Ref(writer, operator);
// } else {
// writer.writeOpenTag(CompoundParameter.COMPOUND_PARAMETER);
// writeParameter1Ref(writer, operator);
// writer.writeIDref(ParameterParser.PARAMETER, operator.parameter2.getName());
// writer.writeCloseTag(CompoundParameter.COMPOUND_PARAMETER);
// }
//
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeUpDownOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(UpDownOperator.UP_DOWN_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
//
// writer.writeOpenTag(UpDownOperator.UP);
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(UpDownOperator.UP);
//
// writer.writeOpenTag(UpDownOperator.DOWN);
// writer.writeIDref(ParameterParser.PARAMETER, operator.parameter2.getName());
// writer.writeCloseTag(UpDownOperator.DOWN);
//
// writer.writeCloseTag(UpDownOperator.UP_DOWN_OPERATOR);
// }
//
// private void writeCenteredOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(CenteredScaleOperator.CENTERED_SCALE,
// new Attribute[]{
// new Attribute.Default<Double>(CenteredScaleOperator.SCALE_FACTOR, operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(CenteredScaleOperator.CENTERED_SCALE);
// }
//
// private void writeDeltaOperator(Operator operator, XMLWriter writer) {
//
//
// if (operator.getName().equals("Relative rates")) {
//
// int[] parameterWeights = options.getPartitionWeights();
//
// if (parameterWeights != null && parameterWeights.length > 1) {
// String pw = "" + parameterWeights[0];
// for (int i = 1; i < parameterWeights.length; i++) {
// pw += " " + parameterWeights[i];
// }
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<Double>(DeltaExchangeOperator.DELTA, operator.tuning),
// new Attribute.Default<String>(DeltaExchangeOperator.PARAMETER_WEIGHTS, pw),
// getWeightAttribute(operator.weight)
// }
// );
// }
// } else {
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<Double>(DeltaExchangeOperator.DELTA, operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
// }
//
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(DeltaExchangeOperator.DELTA_EXCHANGE);
// }
//
// private void writeIntegerDeltaOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(DeltaExchangeOperator.DELTA_EXCHANGE,
// new Attribute[]{
// new Attribute.Default<String>(DeltaExchangeOperator.DELTA, Integer.toString((int) operator.tuning)),
// new Attribute.Default<String>("integer", "true"),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("autoOptimize", "false")
// }
// );
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(DeltaExchangeOperator.DELTA_EXCHANGE);
// }
//
// private void writeSwapOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SwapOperator.SWAP_OPERATOR,
// new Attribute[]{
// new Attribute.Default<String>("size", Integer.toString((int) operator.tuning)),
// getWeightAttribute(operator.weight),
// new Attribute.Default<String>("autoOptimize", "false")
// }
// );
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(SwapOperator.SWAP_OPERATOR);
// }
//
// private void writeBitFlipOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(BitFlipOperator.BIT_FLIP_OPERATOR,
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(BitFlipOperator.BIT_FLIP_OPERATOR);
// }
//
// private void writeTreeBitMoveOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(TreeBitMoveOperator.BIT_MOVE_OPERATOR,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(TreeBitMoveOperator.BIT_MOVE_OPERATOR);
// }
//
// private void writeUniformOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag("uniformOperator",
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("uniformOperator");
// }
//
// private void writeIntegerUniformOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag("uniformIntegerOperator",
// getWeightAttribute(operator.weight));
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag("uniformIntegerOperator");
// }
//
// private void writeNarrowExchangeOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(ExchangeOperator.NARROW_EXCHANGE,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(ExchangeOperator.NARROW_EXCHANGE);
// }
//
// private void writeWideExchangeOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(ExchangeOperator.WIDE_EXCHANGE,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(ExchangeOperator.WIDE_EXCHANGE);
// }
//
// private void writeWilsonBaldingOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(WilsonBalding.WILSON_BALDING,
// getWeightAttribute(operator.weight));
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// // not supported anymore. probably never worked. (todo) get it out of GUI too
//// if (options.nodeHeightPrior == TreePrior.CONSTANT) {
//// treePriorGenerator.writeNodeHeightPriorModelRef(writer);
//// }
// writer.writeCloseTag(WilsonBalding.WILSON_BALDING);
// }
//
// private void writeSampleNonActiveOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SampleNonActiveGibbsOperator.SAMPLE_NONACTIVE_GIBBS_OPERATOR,
// getWeightAttribute(operator.weight));
//
// writer.writeOpenTag(SampleNonActiveGibbsOperator.DISTRIBUTION);
// writeParameterRefByName(writer, operator.getName());
// writer.writeCloseTag(SampleNonActiveGibbsOperator.DISTRIBUTION);
//
// writer.writeOpenTag(SampleNonActiveGibbsOperator.DATA_PARAMETER);
// writeParameter1Ref(writer, operator);
// writer.writeCloseTag(SampleNonActiveGibbsOperator.DATA_PARAMETER);
//
// writer.writeOpenTag(SampleNonActiveGibbsOperator.INDICATOR_PARAMETER);
// writeParameterRefByName(writer, operator.parameter2.getName());
// writer.writeCloseTag(SampleNonActiveGibbsOperator.INDICATOR_PARAMETER);
//
// writer.writeCloseTag(SampleNonActiveGibbsOperator.SAMPLE_NONACTIVE_GIBBS_OPERATOR);
// }
//
// private void writeGMRFGibbsOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// GMRFSkyrideBlockUpdateOperator.BLOCK_UPDATE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>(GMRFSkyrideBlockUpdateOperator.SCALE_FACTOR, operator.tuning),
// getWeightAttribute(operator.weight)
// }
// );
// writer.writeIDref(GMRFSkyrideLikelihood.SKYLINE_LIKELIHOOD, "skyride");
// writer.writeCloseTag(GMRFSkyrideBlockUpdateOperator.BLOCK_UPDATE_OPERATOR);
// }
//
// private void writeScaleWithIndicatorsOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(
// ScaleOperator.SCALE_OPERATOR,
// new Attribute[]{
// new Attribute.Default<Double>("scaleFactor", operator.tuning),
// getWeightAttribute(operator.weight)
// });
// writeParameter1Ref(writer, operator);
// writer.writeOpenTag(ScaleOperator.INDICATORS, new Attribute.Default<String>(ScaleOperator.PICKONEPROB, "1.0"));
// writeParameterRefByName(writer, operator.parameter2.getName());
// writer.writeCloseTag(ScaleOperator.INDICATORS);
// writer.writeCloseTag(ScaleOperator.SCALE_OPERATOR);
// }
//
// private void writeSubtreeSlideOperator(Operator operator, XMLWriter writer) {
// writer.writeOpenTag(SubtreeSlideOperator.SUBTREE_SLIDE,
// new Attribute[]{
// new Attribute.Default<Double>("size", operator.tuning),
// new Attribute.Default<String>("gaussian", "true"),
// getWeightAttribute(operator.weight)
// }
// );
// writer.writeIDref(TreeModel.TREE_MODEL, "treeModel");
// writer.writeCloseTag(SubtreeSlideOperator.SUBTREE_SLIDE);
// }
//
// private Attribute getWeightAttribute(double weight) {
// if (weight == (int)weight) {
// return new Attribute.Default<Integer>("weight", (int)weight);
// } else {
// return new Attribute.Default<Double>("weight", weight);
// }
// }
/**
* Write the timer report block.
*
* @param writer the writer
*/
public void writeTimerReport(XMLWriter writer) {
writer.writeOpenTag("report");
writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer"));
writer.writeIDref("mcmc", "mcmc");
writer.writeCloseTag("property");
writer.writeCloseTag("report");
}
/**
* Write the trace analysis block.
*
* @param writer the writer
*/
public void writeTraceAnalysis(XMLWriter writer) {
writer.writeTag(
"traceAnalysis",
new Attribute[]{
new Attribute.Default<String>("fileName", options.logFileName)
},
true
);
}
/**
* Write the MCMC block.
*
* @param writer
*/
public void writeMCMC(XMLWriter writer) {
writer.writeComment("Define MCMC");
writer.writeOpenTag(
"mcmc",
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "mcmc"),
new Attribute.Default<Integer>("chainLength", options.chainLength),
new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false")
});
if (options.hasData()) {
writer.writeOpenTag(CompoundLikelihood.POSTERIOR, new Attribute.Default<String>(XMLParser.ID, "posterior"));
}
// write prior block
writer.writeOpenTag(CompoundLikelihood.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior"));
if (options.isSpeciesAnalysis()) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, TraitGuesser.Traits.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePrior.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// }
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
}
writeParameterPriors(writer);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior;
if (options.shareSameTreePrior) {
prior = options.activedSameTreePrior;
} else {
prior = model.getPartitionTreePrior();
}
treePriorGenerator.writePriorLikelihoodReference(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
treePriorGenerator.writeEBSPVariableDemographicReference(prior, writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer);
writer.writeCloseTag(CompoundLikelihood.PRIOR);
if (options.hasData()) {
// write likelihood block
writer.writeOpenTag(CompoundLikelihood.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood"));
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer);
writer.writeCloseTag(CompoundLikelihood.LIKELIHOOD);
writer.writeCloseTag(CompoundLikelihood.POSTERIOR);
}
writer.writeIDref(SimpleOperatorSchedule.OPERATOR_SCHEDULE, "operators");
// write log to screen
writeLogToScreen(writer);
// write log to file
writeLogToFile(writer);
// write tree log to file
writeTreeLogToFile(writer);
writer.writeCloseTag("mcmc");
}
/**
* write log to screen
*
* @param writer
*/
private void writeLogToScreen(XMLWriter writer) {
writer.writeComment("write log to screen");
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "screenLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.echoEvery + "")
});
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Posterior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Prior"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
writer.writeCloseTag(Columns.COLUMN);
if (options.hasData()) {
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Likelihood"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
writer.writeCloseTag(Columns.COLUMN);
}
if (options.isSpeciesAnalysis()) { // species
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "PopMean"),
new Attribute.Default<String>(Columns.DECIMAL_PLACES, "4"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.POP_MEAN);
writer.writeCloseTag(Columns.COLUMN);
}
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Root Height"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
writer.writeCloseTag(Columns.COLUMN);
writer.writeOpenTag(Columns.COLUMN,
new Attribute[]{
new Attribute.Default<String>(Columns.LABEL, "Rate"),
new Attribute.Default<String>(Columns.SIGNIFICANT_FIGURES, "6"),
new Attribute.Default<String>(Columns.WIDTH, "12")
}
);
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.STRICT_CLOCK) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + "clock.rate");
} else {
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) { // borrow the method in BeautiOption
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + "meanRate");
}
}
}
writer.writeCloseTag(Columns.COLUMN);
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.RANDOM_LOCAL_CLOCK) {
writeSumStatisticColumn(writer, model.getPrefix() + "rateChanges", "Rate Changes");
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_SCREEN_LOG, writer);
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SCREEN_LOG, writer);
}
/**
* write log to file
*
* @param writer
*/
private void writeLogToFile(XMLWriter writer) {
writer.writeComment("write log to file");
if (options.logFileName == null) {
options.logFileName = options.fileNameStem + ".log";
}
writer.writeOpenTag(LoggerParser.LOG,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, "fileLog"),
new Attribute.Default<String>(LoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(LoggerParser.FILE_NAME, options.logFileName)
});
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.POSTERIOR, "posterior");
}
writer.writeIDref(CompoundLikelihood.PRIOR, "prior");
if (options.hasData()) {
writer.writeIDref(CompoundLikelihood.LIKELIHOOD, "likelihood");
}
if (options.isSpeciesAnalysis()) { // species
// coalescent prior
writer.writeIDref(TreePartitionCoalescent.SPECIES_COALESCENT, TraitGuesser.Traits.TRAIT_SPECIES + "." + COALESCENT);
// prior on population sizes
// if (options.speciesTreePrior == TreePrior.SPECIES_YULE) {
writer.writeIDref(MixedDistributionLikelihood.DISTRIBUTION_LIKELIHOOD, SPOPS);
// } else {
// writer.writeIDref(SpeciesTreeBMPrior.STPRIOR, STP);
// }
// prior on species tree
writer.writeIDref(SpeciationLikelihood.SPECIATION_LIKELIHOOD, SPECIATION_LIKE);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + options.POP_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, SpeciesTreeModel.SPECIES_TREE + "." + SPLIT_POPS);
if (options.activedSameTreePrior.getNodeHeightPrior() == TreePrior.SPECIES_BIRTH_DEATH) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME);
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME);
} else if (options.activedSameTreePrior.getNodeHeightPrior() == TreePrior.SPECIES_YULE) {
writer.writeIDref(ParameterParser.PARAMETER, TraitGuesser.Traits.TRAIT_SPECIES + "." + YuleModelParser.YULE + "." + YuleModelParser.BIRTH_RATE);
} else {
throw new IllegalArgumentException("Get wrong species tree prior using *BEAST : " + options.activedSameTreePrior.getNodeHeightPrior().toString());
}
//Species Tree: tmrcaStatistic
writer.writeIDref(TMRCAStatistic.TMRCA_STATISTIC, SpeciesTreeModel.SPECIES_TREE + "." + TreeModelParser.ROOT_HEIGHT);
}
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + TreeModel.TREE_MODEL + "." + TreeModelParser.ROOT_HEIGHT);
}
for (PartitionClockModel model : options.getPartitionClockModels()) {
if (model.getClockType() == ClockType.STRICT_CLOCK) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + "clock.rate");
} else {
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) { // borrow the method in BeautiOption
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + "meanRate");
}
}
}
for (Taxa taxa : options.taxonSets) {
writer.writeIDref("tmrcaStatistic", "tmrca(" + taxa.getId() + ")");
}
// if ( options.shareSameTreePrior ) { // Share Same Tree Prior
// treePriorGenerator.setModelPrefix("");
// treePriorGenerator.writeParameterLog(options.activedSameTreePrior, writer);
// } else { // no species
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
// treePriorGenerator.setModelPrefix(prior.getPrefix()); // priorName.treeModel
treePriorGenerator.writeParameterLog(prior, writer);
}
// }
for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
substitutionModelGenerator.writeLog(writer, model);
}
if (options.hasCodon()) {
writer.writeIDref(ParameterParser.PARAMETER, "allMus");
}
for (PartitionClockModel model : options.getPartitionClockModels()) {
switch (model.getClockType()) {
case STRICT_CLOCK:
break;
case UNCORRELATED_EXPONENTIAL:
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCED_MEAN);
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
case UNCORRELATED_LOGNORMAL:
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_MEAN);
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + ClockType.UCLD_STDEV);
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
case AUTOCORRELATED_LOGNORMAL:
// writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + "branchRates.var");
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + tree.getPrefix() + "branchRates.var");
writer.writeIDref(ParameterParser.PARAMETER, model.getPrefix() + tree.getPrefix() + "treeModel.rootRate");
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
case RANDOM_LOCAL_CLOCK:
// writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
// writer.writeIDref(SumStatistic.SUM_STATISTIC, model.getPrefix() + "rateChanges");
// writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, "covariance");
for (PartitionTreeModel tree : options.getPartitionTreeModels(model.getAllPartitionData())) {
writer.writeIDref(SumStatistic.SUM_STATISTIC, model.getPrefix() + tree.getPrefix() + "rateChanges");
writer.writeIDref(RateStatistic.RATE_STATISTIC, model.getPrefix() + tree.getPrefix() + RateStatistic.COEFFICIENT_OF_VARIATION);
writer.writeIDref(RateCovarianceStatistic.RATE_COVARIANCE_STATISTIC, model.getPrefix() + tree.getPrefix() + "covariance");
}
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_PARAMETERS, writer);
if (options.hasData()) {
treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_FILE_LOG_LIKELIHOODS, writer);
// coalescentLikelihood
for (PartitionTreeModel model : options.getPartitionTreeModels()) {
PartitionTreePrior prior;
if (options.shareSameTreePrior) {
prior = options.activedSameTreePrior;
} else {
prior = model.getPartitionTreePrior();
}
treePriorGenerator.writePriorLikelihoodReferenceLog(prior, model, writer);
writer.writeText("");
}
for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
if (prior.getNodeHeightPrior() == TreePrior.EXTENDED_SKYLINE)
writer.writeIDref(CoalescentLikelihood.COALESCENT_LIKELIHOOD, prior.getPrefix() + COALESCENT); // only 1 coalescent
}
writer.writeCloseTag(LoggerParser.LOG);
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_FILE_LOG, writer);
}
/**
* write tree log to file
*
* @param writer
*/
private void writeTreeLogToFile(XMLWriter writer) {
writer.writeComment("write tree log to file");
if (options.isSpeciesAnalysis()) { // species
// species tree log
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, TraitGuesser.Traits.TRAIT_SPECIES + "." + TREE_FILE_LOG), // speciesTreeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + options.SPECIES_TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(SpeciesTreeModel.SPECIES_TREE, SP_TREE);
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
// gene tree log
//TODO make code consistent to MCMCPanel
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
String treeFileName;
if (options.substTreeLog) {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + "(time)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME;
} else {
treeFileName = options.fileNameStem + "." + tree.getPrefix() + GMRFFixedGridImportanceSampler.TREE_FILE_NAME; // stem.partitionName.tree
}
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + TREE_FILE_LOG), // partionName.treeFileLog
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, treeFileName),
new Attribute.Default<String>(TreeLoggerParser.SORT_TRANSLATION_TABLE, "true")
});
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
for (PartitionClockModel model : options.getPartitionClockModels(tree.getAllPartitionData())) {
switch (model.getClockType()) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
if (options.hasData()) {
// we have data...
writer.writeIDref("posterior", "posterior");
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
} // end For loop
generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TREES_LOG, writer);
if (options.substTreeLog) {
if (options.isSpeciesAnalysis()) { // species
//TODO: species sub tree
}
// gene tree
for (PartitionTreeModel tree : options.getPartitionTreeModels()) {
// write tree log to file
writer.writeOpenTag(TreeLoggerParser.LOG_TREE,
new Attribute[]{
new Attribute.Default<String>(XMLParser.ID, tree.getPrefix() + SUB_TREE_FILE_LOG),
new Attribute.Default<String>(TreeLoggerParser.LOG_EVERY, options.logEvery + ""),
new Attribute.Default<String>(TreeLoggerParser.NEXUS_FORMAT, "true"),
new Attribute.Default<String>(TreeLoggerParser.FILE_NAME, options.fileNameStem + "." + tree.getPrefix() +
"(subst)." + GMRFFixedGridImportanceSampler.TREE_FILE_NAME),
new Attribute.Default<String>(TreeLoggerParser.BRANCH_LENGTHS, TreeLoggerParser.SUBSTITUTIONS)
});
writer.writeIDref(TreeModel.TREE_MODEL, tree.getPrefix() + TreeModel.TREE_MODEL);
for (PartitionClockModel model : options.getPartitionClockModels(tree.getAllPartitionData())) {
switch (model.getClockType()) {
case STRICT_CLOCK:
writer.writeIDref(StrictClockBranchRates.STRICT_CLOCK_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case UNCORRELATED_EXPONENTIAL:
case UNCORRELATED_LOGNORMAL:
case RANDOM_LOCAL_CLOCK:
writer.writeIDref(DiscretizedBranchRatesParser.DISCRETIZED_BRANCH_RATES, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
case AUTOCORRELATED_LOGNORMAL:
writer.writeIDref(ACLikelihood.AC_LIKELIHOOD, model.getPrefix() + tree.getPrefix() + BranchRateModel.BRANCH_RATES);
break;
default:
throw new IllegalArgumentException("Unknown clock model");
}
}
writer.writeCloseTag(TreeLoggerParser.LOG_TREE);
}
}
generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREES_LOG, writer);
}
/**
* Write the priors for each parameter
*
* @param writer the writer
*/
private void writeParameterPriors(XMLWriter writer) {
boolean first = true;
for (Map.Entry<Taxa, Boolean> taxaBooleanEntry : options.taxonSetsMono.entrySet()) {
if (taxaBooleanEntry.getValue()) {
if (first) {
writer.writeOpenTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
first = false;
}
final String taxaRef = "monophyly(" + taxaBooleanEntry.getKey().getId() + ")";
writer.writeIDref(MonophylyStatistic.MONOPHYLY_STATISTIC, taxaRef);
}
}
if (!first) {
writer.writeCloseTag(BooleanLikelihood.BOOLEAN_LIKELIHOOD);
}
ArrayList<Parameter> parameters = options.selectParameters();
for (Parameter parameter : parameters) {
if (parameter.priorType != PriorType.NONE) {
if (parameter.priorType != PriorType.UNIFORM_PRIOR || parameter.isNodeHeight) {
writeParameterPrior(parameter, writer);
}
}
}
}
/**
* Write the priors for each parameter
*
* @param parameter the parameter
* @param writer the writer
*/
private void writeParameterPrior(dr.app.beauti.options.Parameter parameter, XMLWriter writer) {
switch (parameter.priorType) {
case UNIFORM_PRIOR:
writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR);
break;
case EXPONENTIAL_PRIOR:
writer.writeOpenTag(PriorParsers.EXPONENTIAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.exponentialMean),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.exponentialOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.EXPONENTIAL_PRIOR);
break;
case NORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.NORMAL_PRIOR);
break;
case LOGNORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.LOG_NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.logNormalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.logNormalStdev),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.logNormalOffset),
// this is to be implemented...
new Attribute.Default<String>(PriorParsers.MEAN_IN_REAL_SPACE, "false")
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.LOG_NORMAL_PRIOR);
break;
case GAMMA_PRIOR:
writer.writeOpenTag(PriorParsers.GAMMA_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.SHAPE, "" + parameter.gammaAlpha),
new Attribute.Default<String>(PriorParsers.SCALE, "" + parameter.gammaBeta),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.gammaOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.GAMMA_PRIOR);
break;
case JEFFREYS_PRIOR:
writer.writeOpenTag(OneOnXPrior.ONE_ONE_X_PRIOR);
writeParameterIdref(writer, parameter);
writer.writeCloseTag(OneOnXPrior.ONE_ONE_X_PRIOR);
break;
case POISSON_PRIOR:
writer.writeOpenTag(PriorParsers.POISSON_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.poissonMean),
new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.poissonOffset)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.POISSON_PRIOR);
break;
case TRUNC_NORMAL_PRIOR:
writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.uniformLower),
new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.uniformUpper)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR);
writer.writeOpenTag(PriorParsers.NORMAL_PRIOR,
new Attribute[]{
new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.normalMean),
new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.normalStdev)
});
writeParameterIdref(writer, parameter);
writer.writeCloseTag(PriorParsers.NORMAL_PRIOR);
break;
default:
throw new IllegalArgumentException("Unknown priorType");
}
}
private void writeParameterIdref(XMLWriter writer, dr.app.beauti.options.Parameter parameter) {
if (parameter.isStatistic) {
writer.writeIDref("statistic", parameter.getName());
} else {
writer.writeIDref(ParameterParser.PARAMETER, parameter.getName());
}
}
}
| BEAUTi: fix a critical bug of <patterns> when having multi data parition.
git-svn-id: 67bc77c75b8364e4e9cdff0eb6560f5818674cd8@2035 ca793f91-a31e-0410-b540-2769d408b6a1
| src/dr/app/beauti/generator/BeastGenerator.java | BEAUTi: fix a critical bug of <patterns> when having multi data parition. | <ide><path>rc/dr/app/beauti/generator/BeastGenerator.java
<ide> }
<ide> } else {
<ide> //partitionCount = 1;
<del> writer.writeComment("The unique patterns site patterns");
<del> Alignment alignment = partition.getAlignment();
<del>
<del> writer.writeOpenTag(SitePatternsParser.PATTERNS,
<del> new Attribute[]{
<del> new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS),
<del> }
<del> );
<del>
<del> writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
<del> writer.writeCloseTag(SitePatternsParser.PATTERNS);
<add>// writer.writeComment("The unique patterns site patterns");
<add>// Alignment alignment = partition.getAlignment();
<add>
<add>// writer.writeOpenTag(SitePatternsParser.PATTERNS,
<add>// new Attribute[]{
<add>// new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS),
<add>// }
<add>// );
<add> writePatternList(partition, 0, 1, writer);
<add>// writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
<add>// writer.writeCloseTag(SitePatternsParser.PATTERNS);
<ide>
<ide> // for (PartitionData partition : options.dataPartitions) {
<ide> // if (partition.getPartitionSubstitutionModel() == model) {
<ide> writer.writeComment("npatterns=" + patterns.getPatternCount());
<ide>
<ide> List<Attribute> attributes = new ArrayList<Attribute>();
<add>
<add> // no codon, unique patterns site patterns
<add> if (offset == 0 && every == 1) attributes.add(new Attribute.Default<String>(XMLParser.ID, partition.getName() + "." + SitePatternsParser.PATTERNS));
<add>
<ide> attributes.add(new Attribute.Default<String>("from", "" + from));
<ide> if (to >= 0) attributes.add(new Attribute.Default<String>("to", "" + to));
<ide>
<ide> if (every > 1) {
<ide> attributes.add(new Attribute.Default<String>("every", "" + every));
<ide> }
<add>
<add> // generate <patterns>
<ide> writer.writeOpenTag(SitePatternsParser.PATTERNS, attributes);
<del>
<ide> writer.writeIDref(AlignmentParser.ALIGNMENT, alignment.getId());
<ide> writer.writeCloseTag(SitePatternsParser.PATTERNS);
<ide> } |
|
Java | lgpl-2.1 | error: pathspec 'dom/src/main/java/domainapp/dom/modules/reportes/GenerarReporte.java' did not match any file(s) known to git
| 09c02213b100807026269caf25b66a7a3fef6cd9 | 1 | PlusCel/PlusCel,PlusCel/PlusCel,PlusCel/PlusCel | /*
* This is a software made for highschool management
*
* Copyright (C) 2014, Fourheads
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
*
*
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package domainapp.dom.modules.reportes;
import javax.swing.JOptionPane;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.activation.MimeType;
import javax.inject.Named;
import javax.swing.JFrame;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.ReportContext;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.export.Exporter;
import net.sf.jasperreports.export.ExporterInput;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleXlsExporterConfiguration;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
import net.sf.jasperreports.view.JasperViewer;
import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.value.Blob;
public class GenerarReporte {
public static void generarReporte(String jrxml, List<Object> parametros, E_formato formato, String nombreArchivo) throws JRException{
HashMap<String, Object> map = new HashMap<String, Object>();
//Levanta el jrxml
File file = new File(nombreArchivo,jrxml);
JOptionPane.showMessageDialog(null, "¡Este es el jrxml!" + jrxml);
JOptionPane.showMessageDialog(null, "¡Este es el nombreArchivo!" + nombreArchivo );
JOptionPane.showMessageDialog(null, "¡Este es el file!" + file);
JOptionPane.showMessageDialog(null, "¡Este es el parametro!" + parametros);
//Almacena el array de datos
JRBeanArrayDataSource jArray= new JRBeanArrayDataSource(parametros.toArray());
InputStream input = null;
try{
input = new FileInputStream(file);
JOptionPane.showMessageDialog(null, "¡Entro al input!" + input);
}catch(Exception e){
System.out.println(e.getMessage());
}
//Levanta el modelo del reporte
//Verifico si esta null
if (input == null) {
JOptionPane.showMessageDialog(null, "¡No tiene nada el input!");
} else {
// la otra cosa
JOptionPane.showMessageDialog(null, "¡/Levanta el modelo del reporte!");
}
JasperDesign jd = JRXmlLoader.load(input);
//Compila el reporte
JasperReport reporte = JasperCompileManager.compileReport(jd);
JOptionPane.showMessageDialog(null, "Compila el reporte" + reporte );
//map.put("empleados",jArray.toString());
//Lo llena con los datos del datasource
JasperPrint print = JasperFillManager.fillReport(reporte, map, jArray);
// JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el PRINT" + print.toString() );
// JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el REPORTE" + reporte.toString() );
JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el MAP" + map.toString() );
JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el JARRAY" + jArray.toString() );
//Lo muestra con el jasperviewer
JasperViewer.viewReport(print, false);
// JOptionPane.showMessageDialog(null, "¡Lo muestra con el jasperviewer");
//nombreArchivo = reportes/(calificaciones o asistencia/(nombre)
if(formato == E_formato.HojadeCálculo){
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setExporterInput(new SimpleExporterInput(print));
exporterXLS.setExporterOutput(new SimpleOutputStreamExporterOutput(nombreArchivo + ".xls"));
SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
configuration.setOnePagePerSheet(true);
configuration.setDetectCellType(true);
configuration.setCollapseRowSpan(false);
exporterXLS.setConfiguration(configuration);
exporterXLS.exportReport();
}else{
if(formato == E_formato.PDF){
JasperExportManager.exportReportToPdfFile(print, nombreArchivo + ".pdf" );
JOptionPane.showMessageDialog(null, "¡lo exporta a PDF en :" + "" + print + " " + nombreArchivo);
}
}
//Muestra el reporte en otra ventana
//JasperExportManager.exportReportToHtmlFile(print, "reportemp/nuevo.html");
}
@javax.inject.Inject
public ReportContext reportContext;
@javax.inject.Inject
DomainObjectContainer container;
}
| dom/src/main/java/domainapp/dom/modules/reportes/GenerarReporte.java | Clase que genera el reporte
| dom/src/main/java/domainapp/dom/modules/reportes/GenerarReporte.java | Clase que genera el reporte | <ide><path>om/src/main/java/domainapp/dom/modules/reportes/GenerarReporte.java
<add>/*
<add> * This is a software made for highschool management
<add> *
<add> * Copyright (C) 2014, Fourheads
<add> *
<add> * This program is free software; you can redistribute it and/or
<add> * modify it under the terms of the GNU General Public License
<add> * as published by the Free Software Foundation; either version 2
<add> * of the License, or (at your option) any later version.
<add> *
<add> * This program is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add> * GNU General Public License for more details.
<add> *
<add> * You should have received a copy of the GNU General Public License
<add> * along with this program; if not, write to the Free Software
<add> *
<add> *
<add> * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
<add> */
<add>
<add>
<add>package domainapp.dom.modules.reportes;
<add>
<add>
<add>import javax.swing.JOptionPane;
<add>
<add>
<add>
<add>
<add>
<add>
<add>import java.io.File;
<add>import java.io.FileInputStream;
<add>import java.io.FileNotFoundException;
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.util.ArrayList;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>
<add>import javax.activation.MimeType;
<add>import javax.inject.Named;
<add>import javax.swing.JFrame;
<add>
<add>import net.sf.jasperreports.engine.JREmptyDataSource;
<add>import net.sf.jasperreports.engine.JRException;
<add>import net.sf.jasperreports.engine.JRExporterParameter;
<add>import net.sf.jasperreports.engine.JasperCompileManager;
<add>import net.sf.jasperreports.engine.JasperExportManager;
<add>import net.sf.jasperreports.engine.JasperFillManager;
<add>import net.sf.jasperreports.engine.JasperPrint;
<add>import net.sf.jasperreports.engine.JasperReport;
<add>import net.sf.jasperreports.engine.ReportContext;
<add>import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
<add>import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
<add>import net.sf.jasperreports.engine.design.JasperDesign;
<add>import net.sf.jasperreports.engine.export.JRXlsExporter;
<add>import net.sf.jasperreports.engine.xml.JRXmlLoader;
<add>import net.sf.jasperreports.export.Exporter;
<add>import net.sf.jasperreports.export.ExporterInput;
<add>import net.sf.jasperreports.export.SimpleExporterInput;
<add>import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
<add>import net.sf.jasperreports.export.SimpleXlsExporterConfiguration;
<add>import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
<add>import net.sf.jasperreports.view.JasperViewer;
<add>
<add>import org.apache.isis.applib.DomainObjectContainer;
<add>import org.apache.isis.applib.annotation.DomainService;
<add>import org.apache.isis.applib.value.Blob;
<add>
<add>
<add>
<add>public class GenerarReporte {
<add>
<add> public static void generarReporte(String jrxml, List<Object> parametros, E_formato formato, String nombreArchivo) throws JRException{
<add> HashMap<String, Object> map = new HashMap<String, Object>();
<add>
<add> //Levanta el jrxml
<add> File file = new File(nombreArchivo,jrxml);
<add>
<add>
<add> JOptionPane.showMessageDialog(null, "¡Este es el jrxml!" + jrxml);
<add> JOptionPane.showMessageDialog(null, "¡Este es el nombreArchivo!" + nombreArchivo );
<add> JOptionPane.showMessageDialog(null, "¡Este es el file!" + file);
<add> JOptionPane.showMessageDialog(null, "¡Este es el parametro!" + parametros);
<add>
<add>
<add>
<add> //Almacena el array de datos
<add> JRBeanArrayDataSource jArray= new JRBeanArrayDataSource(parametros.toArray());
<add>
<add> InputStream input = null;
<add> try{
<add> input = new FileInputStream(file);
<add> JOptionPane.showMessageDialog(null, "¡Entro al input!" + input);
<add>
<add> }catch(Exception e){
<add> System.out.println(e.getMessage());
<add> }
<add> //Levanta el modelo del reporte
<add> //Verifico si esta null
<add> if (input == null) {
<add>
<add> JOptionPane.showMessageDialog(null, "¡No tiene nada el input!");
<add>
<add> } else {
<add> // la otra cosa
<add> JOptionPane.showMessageDialog(null, "¡/Levanta el modelo del reporte!");
<add> }
<add>
<add>
<add> JasperDesign jd = JRXmlLoader.load(input);
<add>
<add>
<add>
<add> //Compila el reporte
<add> JasperReport reporte = JasperCompileManager.compileReport(jd);
<add> JOptionPane.showMessageDialog(null, "Compila el reporte" + reporte );
<add>
<add> //map.put("empleados",jArray.toString());
<add> //Lo llena con los datos del datasource
<add> JasperPrint print = JasperFillManager.fillReport(reporte, map, jArray);
<add>// JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el PRINT" + print.toString() );
<add>// JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el REPORTE" + reporte.toString() );
<add> JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el MAP" + map.toString() );
<add> JOptionPane.showMessageDialog(null, "¡Lo llena con los datos del datasource el JARRAY" + jArray.toString() );
<add>
<add> //Lo muestra con el jasperviewer
<add> JasperViewer.viewReport(print, false);
<add>// JOptionPane.showMessageDialog(null, "¡Lo muestra con el jasperviewer");
<add>
<add> //nombreArchivo = reportes/(calificaciones o asistencia/(nombre)
<add>
<add> if(formato == E_formato.HojadeCálculo){
<add>
<add> JRXlsExporter exporterXLS = new JRXlsExporter();
<add>
<add> exporterXLS.setExporterInput(new SimpleExporterInput(print));
<add> exporterXLS.setExporterOutput(new SimpleOutputStreamExporterOutput(nombreArchivo + ".xls"));
<add>
<add> SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
<add> configuration.setOnePagePerSheet(true);
<add> configuration.setDetectCellType(true);
<add> configuration.setCollapseRowSpan(false);
<add>
<add> exporterXLS.setConfiguration(configuration);
<add> exporterXLS.exportReport();
<add>
<add> }else{
<add> if(formato == E_formato.PDF){
<add> JasperExportManager.exportReportToPdfFile(print, nombreArchivo + ".pdf" );
<add> JOptionPane.showMessageDialog(null, "¡lo exporta a PDF en :" + "" + print + " " + nombreArchivo);
<add>
<add> }
<add> }
<add>
<add>
<add> //Muestra el reporte en otra ventana
<add> //JasperExportManager.exportReportToHtmlFile(print, "reportemp/nuevo.html");
<add>
<add>
<add> }
<add>
<add>
<add> @javax.inject.Inject
<add> public ReportContext reportContext;
<add>
<add> @javax.inject.Inject
<add> DomainObjectContainer container;
<add>
<add>} |
|
Java | apache-2.0 | c32568b5f5ef62726a9904e729f94cd206b6314a | 0 | linkhub-sdk/popbill.example.springMVC | /*
* 팝빌 휴폐업조회 API Java SDK SpringMVC Example
*
* - SpringMVC SDK 연동환경 설정방법 안내 : http://blog.linkhub.co.kr/591/
* - 업데이트 일자 : 2016-12-02
* - 연동 기술지원 연락처 : 1600-8536 / 070-4304-2991~2
* - 연동 기술지원 이메일 : [email protected]
*
* Copyright 2006-2014 linkhub.co.kr, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.popbill.example;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.popbill.api.ChargeInfo;
import com.popbill.api.CloseDownService;
import com.popbill.api.CorpState;
import com.popbill.api.PopbillException;
/**
* 팝빌 휴폐업조회 API 예제.
*/
@Controller
@RequestMapping("CloseDownService")
public class ClosedownServiceExample {
@Autowired
private CloseDownService closedownService;
// 팝빌회원 사업자번호
@Value("#{EXAMPLE_CONFIG.TestCorpNum}")
private String testCorpNum;
// 팝빌회원 아이디
@Value("#{EXAMPLE_CONFIG.TestUserID}")
private String testUserID;
@RequestMapping(value = "", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "Closedown/index";
}
@RequestMapping(value = "getUnitCost", method = RequestMethod.GET)
public String getUnitCost( Model m) {
/**
* 휴폐업조회 단가를 확인합니다.
*/
try {
float unitCost = closedownService.getUnitCost(testCorpNum);
m.addAttribute("Result",unitCost);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getChargeInfo", method = RequestMethod.GET)
public String chargeInfo( Model m) {
/**
* 연동회원의 휴폐업조회 API 서비스 과금정보를 확인합니다.
*/
try {
ChargeInfo chrgInfo = closedownService.getChargeInfo(testCorpNum);
m.addAttribute("ChargeInfo",chrgInfo);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "getChargeInfo";
}
@RequestMapping(value="checkCorpNum", method = RequestMethod.GET)
public String checkCorpNum(@RequestParam(required=false) String CorpNum, Model m){
/**
* 1건의 사업자에 대한 휴폐업여부를 조회합니다.
*/
if ( CorpNum != null && CorpNum != "" ) {
try {
CorpState corpState = closedownService.CheckCorpNum(testCorpNum, CorpNum);
m.addAttribute("CorpState", corpState);
} catch(PopbillException e){
m.addAttribute("Exception", e);
return "exception";
}
}else {
}
return "Closedown/checkCorpNum";
}
@RequestMapping(value="checkCorpNums", method = RequestMethod.GET)
public String checkCorpNums(Model m) {
/**
* 다수의 사업자에 대한 휴폐업여부를 조회합니다.
*/
// 조회할 사업자번호 배열, 최대 1000건
String[] CorpNumList = new String[] {"1234567890", "6798700433"};
try {
CorpState[] corpStates = closedownService.CheckCorpNum(testCorpNum, CorpNumList);
m.addAttribute("CorpStates", corpStates);
} catch(PopbillException e){
m.addAttribute("Exception", e);
return "exception";
}
return "Closedown/checkCorpNums";
}
}
| src/main/java/com/popbill/example/ClosedownServiceExample.java | /*
* Copyright 2006-2014 linkhub.co.kr, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.popbill.example;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.popbill.api.ChargeInfo;
import com.popbill.api.CloseDownService;
import com.popbill.api.CorpState;
import com.popbill.api.PopbillException;
/**
* 팝빌 휴폐업조회 API 예제.
*/
@Controller
@RequestMapping("CloseDownService")
public class ClosedownServiceExample {
@Autowired
private CloseDownService closedownService;
@Value("#{EXAMPLE_CONFIG.TestCorpNum}")
private String testCorpNum;
@Value("#{EXAMPLE_CONFIG.TestUserID}")
private String testUserID;
@RequestMapping(value = "", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "Closedown/index";
}
@RequestMapping(value = "getUnitCost", method = RequestMethod.GET)
public String getUnitCost( Model m) {
try {
//조회단가 확인
float unitCost = closedownService.getUnitCost(testCorpNum);
m.addAttribute("Result",unitCost);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "result";
}
@RequestMapping(value = "getChargeInfo", method = RequestMethod.GET)
public String chargeInfo( Model m) {
try {
ChargeInfo chrgInfo = closedownService.getChargeInfo(testCorpNum);
m.addAttribute("ChargeInfo",chrgInfo);
} catch (PopbillException e) {
m.addAttribute("Exception", e);
return "exception";
}
return "getChargeInfo";
}
@RequestMapping(value="checkCorpNum", method = RequestMethod.GET)
public String checkCorpNum(@RequestParam(required=false) String CorpNum, Model m){
if(CorpNum !=null && CorpNum != ""){
try {
// CheckCorpNum(팝빌회원 사업자번호, 조회할 사업자번호)
CorpState corpState = closedownService.CheckCorpNum(testCorpNum, CorpNum);
m.addAttribute("CorpState", corpState);
} catch(PopbillException e){
m.addAttribute("Exception", e);
return "exception";
}
}else {
}
return "Closedown/checkCorpNum";
}
@RequestMapping(value="checkCorpNums", method = RequestMethod.GET)
public String checkCorpNums(Model m) {
//사업자번호 배열, 최대 1000건
String[] CorpNumList = new String[] {"1234567890", "4108600477", "122-31-81200"};
try {
// CheckCorpNum(팝빌회원 사업자번호, 조회할 사업자번호 배열)
CorpState[] corpStates = closedownService.CheckCorpNum(testCorpNum, CorpNumList);
m.addAttribute("CorpStates", corpStates);
} catch(PopbillException e){
m.addAttribute("Exception", e);
return "exception";
}
return "Closedown/checkCorpNums";
}
}
| add Comment for ClosedownService Example | src/main/java/com/popbill/example/ClosedownServiceExample.java | add Comment for ClosedownService Example | <ide><path>rc/main/java/com/popbill/example/ClosedownServiceExample.java
<ide> /*
<add> * 팝빌 휴폐업조회 API Java SDK SpringMVC Example
<add> *
<add> * - SpringMVC SDK 연동환경 설정방법 안내 : http://blog.linkhub.co.kr/591/
<add> * - 업데이트 일자 : 2016-12-02
<add> * - 연동 기술지원 연락처 : 1600-8536 / 070-4304-2991~2
<add> * - 연동 기술지원 이메일 : [email protected]
<add> *
<ide> * Copyright 2006-2014 linkhub.co.kr, Inc. or its affiliates. All Rights Reserved.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License").
<ide> @Autowired
<ide> private CloseDownService closedownService;
<ide>
<add> // 팝빌회원 사업자번호
<ide> @Value("#{EXAMPLE_CONFIG.TestCorpNum}")
<ide> private String testCorpNum;
<add>
<add> // 팝빌회원 아이디
<ide> @Value("#{EXAMPLE_CONFIG.TestUserID}")
<ide> private String testUserID;
<ide>
<ide>
<ide> @RequestMapping(value = "getUnitCost", method = RequestMethod.GET)
<ide> public String getUnitCost( Model m) {
<add> /**
<add> * 휴폐업조회 단가를 확인합니다.
<add> */
<add>
<ide> try {
<del> //조회단가 확인
<add>
<ide> float unitCost = closedownService.getUnitCost(testCorpNum);
<ide>
<ide> m.addAttribute("Result",unitCost);
<ide>
<ide> @RequestMapping(value = "getChargeInfo", method = RequestMethod.GET)
<ide> public String chargeInfo( Model m) {
<add> /**
<add> * 연동회원의 휴폐업조회 API 서비스 과금정보를 확인합니다.
<add> */
<add>
<ide> try {
<ide> ChargeInfo chrgInfo = closedownService.getChargeInfo(testCorpNum);
<ide> m.addAttribute("ChargeInfo",chrgInfo);
<ide>
<ide> @RequestMapping(value="checkCorpNum", method = RequestMethod.GET)
<ide> public String checkCorpNum(@RequestParam(required=false) String CorpNum, Model m){
<add> /**
<add> * 1건의 사업자에 대한 휴폐업여부를 조회합니다.
<add> */
<ide>
<del> if(CorpNum !=null && CorpNum != ""){
<add> if ( CorpNum != null && CorpNum != "" ) {
<ide>
<ide> try {
<del> // CheckCorpNum(팝빌회원 사업자번호, 조회할 사업자번호)
<ide> CorpState corpState = closedownService.CheckCorpNum(testCorpNum, CorpNum);
<ide>
<ide> m.addAttribute("CorpState", corpState);
<ide>
<ide> @RequestMapping(value="checkCorpNums", method = RequestMethod.GET)
<ide> public String checkCorpNums(Model m) {
<add> /**
<add> * 다수의 사업자에 대한 휴폐업여부를 조회합니다.
<add> */
<ide>
<del> //사업자번호 배열, 최대 1000건
<del> String[] CorpNumList = new String[] {"1234567890", "4108600477", "122-31-81200"};
<add> // 조회할 사업자번호 배열, 최대 1000건
<add> String[] CorpNumList = new String[] {"1234567890", "6798700433"};
<ide>
<ide> try {
<ide>
<del> // CheckCorpNum(팝빌회원 사업자번호, 조회할 사업자번호 배열)
<ide> CorpState[] corpStates = closedownService.CheckCorpNum(testCorpNum, CorpNumList);
<ide>
<ide> m.addAttribute("CorpStates", corpStates); |
|
Java | apache-2.0 | 83f58ee9e93ebf4c581bdbfd1b296fb9a30768b9 | 0 | leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.jdbc.orchestration.internal.state.datasource;
import io.shardingsphere.core.exception.ShardingException;
import io.shardingsphere.jdbc.orchestration.internal.OrchestrationProxyConfiguration;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.disabled.JdbcDisabledEventBusEvent;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.disabled.JdbcDisabledEventBusInstance;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.proxy.ProxyEventBusEvent;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.proxy.ProxyEventBusInstance;
import io.shardingsphere.jdbc.orchestration.internal.listener.ListenerManager;
import io.shardingsphere.jdbc.orchestration.internal.state.StateNode;
import io.shardingsphere.jdbc.orchestration.reg.api.RegistryCenter;
import io.shardingsphere.jdbc.orchestration.reg.listener.DataChangedEvent;
import io.shardingsphere.jdbc.orchestration.reg.listener.EventListener;
/**
* Data source listener manager.
*
* @author caohao
* @author panjuan
*/
public final class DataSourceListenerManager implements ListenerManager {
private final StateNode stateNode;
private final RegistryCenter regCenter;
private final DataSourceService dataSourceService;
public DataSourceListenerManager(final String name, final RegistryCenter regCenter) {
stateNode = new StateNode(name);
this.regCenter = regCenter;
dataSourceService = new DataSourceService(name, regCenter);
}
@Override
public void shardingStart() {
regCenter.watch(stateNode.getDataSourcesNodeFullPath(), new EventListener() {
@Override
public void onChange(final DataChangedEvent event) {
if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
JdbcDisabledEventBusInstance.getInstance().post(new JdbcDisabledEventBusEvent(dataSourceService.getDisabledDataSourceNames()));
}
}
});
}
@Override
public void masterSlaveStart() {
regCenter.watch(stateNode.getDataSourcesNodeFullPath(), new EventListener() {
@Override
public void onChange(final DataChangedEvent event) {
if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
JdbcDisabledEventBusInstance.getInstance().post(new JdbcDisabledEventBusEvent(dataSourceService.getDisabledDataSourceNames()));
}
}
});
}
@Override
public void proxyStart() {
regCenter.watch(stateNode.getDataSourcesNodeFullPath(), new EventListener() {
@Override
public void onChange(final DataChangedEvent event) {
if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
OrchestrationProxyConfiguration availableYamlProxyConfiguration = dataSourceService.getAvailableYamlProxyConfiguration();
if (availableYamlProxyConfiguration.getShardingRule().getTables().isEmpty() && availableYamlProxyConfiguration.getMasterSlaveRule().getSlaveDataSourceNames().isEmpty()) {
throw new ShardingException("No available slave datasource, can't apply the configuration!");
}
ProxyEventBusInstance.getInstance().post(new ProxyEventBusEvent(dataSourceService.getAvailableDataSourceParameters(), availableYamlProxyConfiguration));
}
}
});
}
}
| sharding-jdbc-orchestration/src/main/java/io/shardingsphere/jdbc/orchestration/internal/state/datasource/DataSourceListenerManager.java | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.jdbc.orchestration.internal.state.datasource;
import io.shardingsphere.core.exception.ShardingException;
import io.shardingsphere.jdbc.orchestration.internal.OrchestrationProxyConfiguration;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.JdbcStateEventBusEvent;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.JdbcStateEventBusInstance;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.proxy.ProxyEventBusEvent;
import io.shardingsphere.jdbc.orchestration.internal.eventbus.proxy.ProxyEventBusInstance;
import io.shardingsphere.jdbc.orchestration.internal.listener.ListenerManager;
import io.shardingsphere.jdbc.orchestration.internal.state.StateNode;
import io.shardingsphere.jdbc.orchestration.reg.api.RegistryCenter;
import io.shardingsphere.jdbc.orchestration.reg.listener.DataChangedEvent;
import io.shardingsphere.jdbc.orchestration.reg.listener.EventListener;
/**
* Data source listener manager.
*
* @author caohao
* @author panjuan
*/
public final class DataSourceListenerManager implements ListenerManager {
private final StateNode stateNode;
private final RegistryCenter regCenter;
private final DataSourceService dataSourceService;
public DataSourceListenerManager(final String name, final RegistryCenter regCenter) {
stateNode = new StateNode(name);
this.regCenter = regCenter;
dataSourceService = new DataSourceService(name, regCenter);
}
@Override
public void shardingStart() {
regCenter.watch(stateNode.getDataSourcesNodeFullPath(), new EventListener() {
@Override
public void onChange(final DataChangedEvent event) {
if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
JdbcStateEventBusEvent jdbcStateEventBusEvent = new JdbcStateEventBusEvent();
jdbcStateEventBusEvent.getDisabledDataSourceNames().addAll(dataSourceService.getDisabledDataSourceNames());
JdbcStateEventBusInstance.getInstance().post(jdbcStateEventBusEvent);
}
}
});
}
@Override
public void masterSlaveStart() {
regCenter.watch(stateNode.getDataSourcesNodeFullPath(), new EventListener() {
@Override
public void onChange(final DataChangedEvent event) {
if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
JdbcStateEventBusEvent jdbcStateEventBusEvent = new JdbcStateEventBusEvent();
jdbcStateEventBusEvent.getDisabledDataSourceNames().addAll(dataSourceService.getDisabledDataSourceNames());
JdbcStateEventBusInstance.getInstance().post(jdbcStateEventBusEvent);
}
}
});
}
@Override
public void proxyStart() {
regCenter.watch(stateNode.getDataSourcesNodeFullPath(), new EventListener() {
@Override
public void onChange(final DataChangedEvent event) {
if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
OrchestrationProxyConfiguration availableYamlProxyConfiguration = dataSourceService.getAvailableYamlProxyConfiguration();
if (availableYamlProxyConfiguration.getShardingRule().getTables().isEmpty() && availableYamlProxyConfiguration.getMasterSlaveRule().getSlaveDataSourceNames().isEmpty()) {
throw new ShardingException("No available slave datasource, can't apply the configuration!");
}
ProxyEventBusInstance.getInstance().post(new ProxyEventBusEvent(dataSourceService.getAvailableDataSourceParameters(), availableYamlProxyConfiguration));
}
}
});
}
}
| rewrite masterSlaveStart
| sharding-jdbc-orchestration/src/main/java/io/shardingsphere/jdbc/orchestration/internal/state/datasource/DataSourceListenerManager.java | rewrite masterSlaveStart | <ide><path>harding-jdbc-orchestration/src/main/java/io/shardingsphere/jdbc/orchestration/internal/state/datasource/DataSourceListenerManager.java
<ide>
<ide> import io.shardingsphere.core.exception.ShardingException;
<ide> import io.shardingsphere.jdbc.orchestration.internal.OrchestrationProxyConfiguration;
<del>import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.JdbcStateEventBusEvent;
<del>import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.JdbcStateEventBusInstance;
<add>import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.disabled.JdbcDisabledEventBusEvent;
<add>import io.shardingsphere.jdbc.orchestration.internal.eventbus.jdbc.state.disabled.JdbcDisabledEventBusInstance;
<ide> import io.shardingsphere.jdbc.orchestration.internal.eventbus.proxy.ProxyEventBusEvent;
<ide> import io.shardingsphere.jdbc.orchestration.internal.eventbus.proxy.ProxyEventBusInstance;
<ide> import io.shardingsphere.jdbc.orchestration.internal.listener.ListenerManager;
<ide> @Override
<ide> public void onChange(final DataChangedEvent event) {
<ide> if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
<del> JdbcStateEventBusEvent jdbcStateEventBusEvent = new JdbcStateEventBusEvent();
<del> jdbcStateEventBusEvent.getDisabledDataSourceNames().addAll(dataSourceService.getDisabledDataSourceNames());
<del> JdbcStateEventBusInstance.getInstance().post(jdbcStateEventBusEvent);
<add> JdbcDisabledEventBusInstance.getInstance().post(new JdbcDisabledEventBusEvent(dataSourceService.getDisabledDataSourceNames()));
<ide> }
<ide> }
<ide> });
<ide> @Override
<ide> public void onChange(final DataChangedEvent event) {
<ide> if (DataChangedEvent.Type.UPDATED == event.getEventType() || DataChangedEvent.Type.DELETED == event.getEventType()) {
<del> JdbcStateEventBusEvent jdbcStateEventBusEvent = new JdbcStateEventBusEvent();
<del> jdbcStateEventBusEvent.getDisabledDataSourceNames().addAll(dataSourceService.getDisabledDataSourceNames());
<del> JdbcStateEventBusInstance.getInstance().post(jdbcStateEventBusEvent);
<add> JdbcDisabledEventBusInstance.getInstance().post(new JdbcDisabledEventBusEvent(dataSourceService.getDisabledDataSourceNames()));
<ide> }
<ide> }
<ide> }); |
|
Java | mit | 237a8734863360ca89783fde0a4cf20bfd59f0d7 | 0 | olavloite/spanner-jdbc | package nl.topicus.jdbc;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.NClob;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import nl.topicus.jdbc.metadata.AbstractCloudSpannerWrapper;
/**
*
* @author loite
*
*/
public abstract class AbstractCloudSpannerConnection extends AbstractCloudSpannerWrapper implements Connection
{
@Override
public void setCatalog(String catalog) throws SQLException
{
// silently ignore
}
@Override
public String getCatalog() throws SQLException
{
return null;
}
@Override
public SQLWarning getWarnings() throws SQLException
{
return null;
}
@Override
public void clearWarnings() throws SQLException
{
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setHoldability(int holdability) throws SQLException
{
if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT)
throw new SQLFeatureNotSupportedException();
}
@Override
public int getHoldability() throws SQLException
{
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public Savepoint setSavepoint() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void rollback(Savepoint savepoint) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Clob createClob() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Blob createBlob() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public NClob createNClob() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public SQLXML createSQLXML() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException
{
// silently ignore
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException
{
// silently ignore
}
@Override
public String getClientInfo(String name) throws SQLException
{
return null;
}
@Override
public Properties getClientInfo() throws SQLException
{
return new Properties();
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setSchema(String schema) throws SQLException
{
// silently ignore
}
@Override
public String getSchema() throws SQLException
{
return null;
}
@Override
public void abort(Executor executor) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public int getNetworkTimeout() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
}
| src/main/java/nl/topicus/jdbc/AbstractCloudSpannerConnection.java | package nl.topicus.jdbc;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.NClob;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
/**
*
* @author loite
*
*/
public abstract class AbstractCloudSpannerConnection implements Connection
{
@Override
public <T> T unwrap(Class<T> iface) throws SQLException
{
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
return false;
}
@Override
public void setCatalog(String catalog) throws SQLException
{
// silently ignore
}
@Override
public String getCatalog() throws SQLException
{
return null;
}
@Override
public SQLWarning getWarnings() throws SQLException
{
return null;
}
@Override
public void clearWarnings() throws SQLException
{
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setHoldability(int holdability) throws SQLException
{
if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT)
throw new SQLFeatureNotSupportedException();
}
@Override
public int getHoldability() throws SQLException
{
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
@Override
public Savepoint setSavepoint() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void rollback(Savepoint savepoint) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Clob createClob() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public Blob createBlob() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public NClob createNClob() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public SQLXML createSQLXML() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException
{
// silently ignore
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException
{
// silently ignore
}
@Override
public String getClientInfo(String name) throws SQLException
{
return null;
}
@Override
public Properties getClientInfo() throws SQLException
{
return new Properties();
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setSchema(String schema) throws SQLException
{
// silently ignore
}
@Override
public String getSchema() throws SQLException
{
return null;
}
@Override
public void abort(Executor executor) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
@Override
public int getNetworkTimeout() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
}
| changed super class | src/main/java/nl/topicus/jdbc/AbstractCloudSpannerConnection.java | changed super class | <ide><path>rc/main/java/nl/topicus/jdbc/AbstractCloudSpannerConnection.java
<ide> import java.util.Properties;
<ide> import java.util.concurrent.Executor;
<ide>
<add>import nl.topicus.jdbc.metadata.AbstractCloudSpannerWrapper;
<add>
<ide> /**
<ide> *
<ide> * @author loite
<ide> *
<ide> */
<del>public abstract class AbstractCloudSpannerConnection implements Connection
<add>public abstract class AbstractCloudSpannerConnection extends AbstractCloudSpannerWrapper implements Connection
<ide> {
<del>
<del> @Override
<del> public <T> T unwrap(Class<T> iface) throws SQLException
<del> {
<del> return null;
<del> }
<del>
<del> @Override
<del> public boolean isWrapperFor(Class<?> iface) throws SQLException
<del> {
<del> return false;
<del> }
<ide>
<ide> @Override
<ide> public void setCatalog(String catalog) throws SQLException |
|
Java | apache-2.0 | 059a65483a4068ae9b1e313b3fd5fc7933a1a250 | 0 | rajapulau/qiscus-sdk-android,qiscus/qiscus-sdk-android | /*
* Copyright (c) 2016 Qiscus.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qiscus.sdk.data.remote;
import android.support.v4.util.Pair;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.qiscus.sdk.data.model.QiscusAccount;
import com.qiscus.sdk.data.model.QiscusChatRoom;
import com.qiscus.sdk.data.model.QiscusComment;
import com.qiscus.sdk.data.model.QiscusRoomMember;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
/**
* Created on : February 02, 2017
* Author : zetbaitsu
* Name : Zetra
* GitHub : https://github.com/zetbaitsu
*/
final class QiscusApiParser {
private static DateFormat dateFormat;
static {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
static QiscusAccount parseQiscusAccount(JsonElement jsonElement) {
JsonObject jsonAccount = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("user").getAsJsonObject();
QiscusAccount qiscusAccount = new QiscusAccount();
qiscusAccount.setId(jsonAccount.get("id").getAsInt());
qiscusAccount.setUsername(jsonAccount.get("username").getAsString());
qiscusAccount.setEmail(jsonAccount.get("email").getAsString());
qiscusAccount.setToken(jsonAccount.get("token").getAsString());
qiscusAccount.setRtKey(jsonAccount.get("rtKey").getAsString());
qiscusAccount.setAvatar(jsonAccount.get("avatar_url").getAsString());
return qiscusAccount;
}
static QiscusChatRoom parseQiscusChatRoom(JsonElement jsonElement) {
if (jsonElement != null) {
JsonObject jsonChatRoom = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("room").getAsJsonObject();
QiscusChatRoom qiscusChatRoom = new QiscusChatRoom();
qiscusChatRoom.setId(jsonChatRoom.get("id").getAsInt());
//TODO minta server ngasih tau distinctId biar bisa disimpen
//qiscusChatRoom.setDistinctId("default");
qiscusChatRoom.setGroup(!"single".equals(jsonChatRoom.get("chat_type").getAsString()));
if (qiscusChatRoom.isGroup()) {
qiscusChatRoom.setName(jsonChatRoom.get("room_name").getAsString());
qiscusChatRoom.setDistinctId(qiscusChatRoom.getId() + "");
}
qiscusChatRoom.setLastCommentId(jsonChatRoom.get("last_comment_id").getAsInt());
qiscusChatRoom.setLastCommentMessage(jsonChatRoom.get("last_comment_message").getAsString());
qiscusChatRoom.setLastTopicId(jsonChatRoom.get("last_topic_id").getAsInt());
qiscusChatRoom.setOptions(jsonChatRoom.get("options").isJsonNull() ? null : jsonChatRoom.get("options").getAsString());
qiscusChatRoom.setAvatarUrl(jsonChatRoom.get("avatar_url").getAsString());
JsonArray jsonMembers = jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("room").getAsJsonObject().get("participants").getAsJsonArray();
List<QiscusRoomMember> members = new ArrayList<>();
for (JsonElement jsonMember : jsonMembers) {
QiscusRoomMember member = new QiscusRoomMember();
member.setEmail(jsonMember.getAsJsonObject().get("email").getAsString());
member.setAvatar(jsonMember.getAsJsonObject().get("avatar_url").getAsString());
member.setUsername(jsonMember.getAsJsonObject().get("username").getAsString());
if (jsonMember.getAsJsonObject().has("last_comment_received_id")) {
member.setLastDeliveredCommentId(jsonMember.getAsJsonObject().get("last_comment_received_id").getAsInt());
}
if (jsonMember.getAsJsonObject().has("last_comment_read_id")) {
member.setLastReadCommentId(jsonMember.getAsJsonObject().get("last_comment_read_id").getAsInt());
}
members.add(member);
}
qiscusChatRoom.setMember(members);
JsonArray comments = jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray();
if (comments.size() > 0) {
JsonObject lastComment = comments.get(0).getAsJsonObject();
qiscusChatRoom.setLastCommentSender(lastComment.get("username").getAsString());
qiscusChatRoom.setLastCommentSenderEmail(lastComment.get("email").getAsString());
try {
qiscusChatRoom.setLastCommentTime(dateFormat.parse(lastComment.get("timestamp").getAsString()));
} catch (ParseException e) {
e.printStackTrace();
}
}
return qiscusChatRoom;
}
return null;
}
static List<QiscusChatRoom> parseQiscusChatRoomInfo(JsonElement jsonElement) {
if (jsonElement != null) {
JsonArray jsonRoomInfo = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("rooms_info").getAsJsonArray();
List<QiscusChatRoom> qiscusChatRooms = new ArrayList<>();
for (JsonElement jsonMember : jsonRoomInfo) {
QiscusChatRoom qiscusChatRoom = new QiscusChatRoom();
qiscusChatRoom.setLastCommentId(jsonMember.getAsJsonObject().get("last_comment_id").getAsInt());
qiscusChatRoom.setAvatarUrl(jsonMember.getAsJsonObject().get("room_avatar_url").getAsString());
qiscusChatRoom.setId(jsonMember.getAsJsonObject().get("room_id").getAsInt());
qiscusChatRoom.setName(jsonMember.getAsJsonObject().get("room_name").getAsString());
qiscusChatRoom.setLastCommentMessage(jsonMember.getAsJsonObject().get("last_comment_message").getAsString());
qiscusChatRoom.setUnreadCount(jsonMember.getAsJsonObject().get("unread_count").getAsInt());
try {
qiscusChatRoom.setLastCommentTime(dateFormat.parse(jsonMember.getAsJsonObject()
.get("last_comment_timestamp").getAsString()));
} catch (ParseException e) {
e.printStackTrace();
}
qiscusChatRooms.add(qiscusChatRoom);
}
return qiscusChatRooms;
}
return null;
}
static Pair<QiscusChatRoom, List<QiscusComment>> parseQiscusChatRoomWithComments(JsonElement jsonElement) {
if (jsonElement != null) {
QiscusChatRoom qiscusChatRoom = parseQiscusChatRoom(jsonElement);
JsonArray comments = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("comments").getAsJsonArray();
List<QiscusComment> qiscusComments = new ArrayList<>();
for (JsonElement jsonComment : comments) {
qiscusComments.add(parseQiscusComment(jsonComment, qiscusChatRoom.getId(), qiscusChatRoom.getLastTopicId()));
}
return Pair.create(qiscusChatRoom, qiscusComments);
}
return null;
}
static QiscusComment parseQiscusComment(JsonElement jsonElement, int roomId, int topicId) {
QiscusComment qiscusComment = new QiscusComment();
JsonObject jsonComment = jsonElement.getAsJsonObject();
qiscusComment.setTopicId(topicId);
qiscusComment.setRoomId(roomId);
qiscusComment.setId(jsonComment.get("id").getAsInt());
qiscusComment.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt());
qiscusComment.setMessage(jsonComment.get("message").getAsString());
qiscusComment.setSender(jsonComment.get("username").getAsString());
qiscusComment.setSenderEmail(jsonComment.get("email").getAsString());
qiscusComment.setSenderAvatar(jsonComment.get("user_avatar_url").getAsString());
qiscusComment.setState(QiscusComment.STATE_ON_QISCUS);
try {
qiscusComment.setTime(dateFormat.parse(jsonComment.get("timestamp").getAsString()));
} catch (ParseException e) {
e.printStackTrace();
}
if (jsonComment.has("room_name")) {
qiscusComment.setRoomName(jsonComment.get("room_name").getAsString());
}
if (jsonComment.has("chat_type")) {
qiscusComment.setGroupMessage(!"single".equals(jsonComment.get("chat_type").getAsString()));
}
if (jsonComment.has("unique_id")) {
qiscusComment.setUniqueId(jsonComment.get("unique_id").getAsString());
} else if (jsonComment.has("unique_temp_id")) {
qiscusComment.setUniqueId(jsonComment.get("unique_temp_id").getAsString());
} else {
qiscusComment.setUniqueId(String.valueOf(qiscusComment.getId()));
}
if (jsonComment.has("type")) {
qiscusComment.setRawType(jsonComment.get("type").getAsString());
qiscusComment.setExtraPayload(jsonComment.get("payload").toString());
if (qiscusComment.getType() == QiscusComment.Type.BUTTONS
|| qiscusComment.getType() == QiscusComment.Type.REPLY
|| qiscusComment.getType() == QiscusComment.Type.CARD) {
JsonObject payload = jsonComment.get("payload").getAsJsonObject();
if (payload.has("text")) {
String text = payload.get("text").getAsString();
if (text != null && !text.trim().isEmpty()) {
qiscusComment.setMessage(text.trim());
}
}
}
}
return qiscusComment;
}
}
| chat/src/main/java/com/qiscus/sdk/data/remote/QiscusApiParser.java | /*
* Copyright (c) 2016 Qiscus.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qiscus.sdk.data.remote;
import android.support.v4.util.Pair;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.qiscus.sdk.data.model.QiscusAccount;
import com.qiscus.sdk.data.model.QiscusChatRoom;
import com.qiscus.sdk.data.model.QiscusComment;
import com.qiscus.sdk.data.model.QiscusRoomMember;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
/**
* Created on : February 02, 2017
* Author : zetbaitsu
* Name : Zetra
* GitHub : https://github.com/zetbaitsu
*/
final class QiscusApiParser {
private static DateFormat dateFormat;
static {
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
static QiscusAccount parseQiscusAccount(JsonElement jsonElement) {
JsonObject jsonAccount = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("user").getAsJsonObject();
QiscusAccount qiscusAccount = new QiscusAccount();
qiscusAccount.setId(jsonAccount.get("id").getAsInt());
qiscusAccount.setUsername(jsonAccount.get("username").getAsString());
qiscusAccount.setEmail(jsonAccount.get("email").getAsString());
qiscusAccount.setToken(jsonAccount.get("token").getAsString());
qiscusAccount.setRtKey(jsonAccount.get("rtKey").getAsString());
qiscusAccount.setAvatar(jsonAccount.get("avatar_url").getAsString());
return qiscusAccount;
}
static QiscusChatRoom parseQiscusChatRoom(JsonElement jsonElement) {
if (jsonElement != null) {
JsonObject jsonChatRoom = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("room").getAsJsonObject();
QiscusChatRoom qiscusChatRoom = new QiscusChatRoom();
qiscusChatRoom.setId(jsonChatRoom.get("id").getAsInt());
//TODO minta server ngasih tau distinctId biar bisa disimpen
//qiscusChatRoom.setDistinctId("default");
qiscusChatRoom.setGroup(!"single".equals(jsonChatRoom.get("chat_type").getAsString()));
if (qiscusChatRoom.isGroup()) {
qiscusChatRoom.setName(jsonChatRoom.get("room_name").getAsString());
qiscusChatRoom.setDistinctId(qiscusChatRoom.getId() + "");
}
qiscusChatRoom.setLastCommentId(jsonChatRoom.get("last_comment_id").getAsInt());
qiscusChatRoom.setLastCommentMessage(jsonChatRoom.get("last_comment_message").getAsString());
qiscusChatRoom.setLastTopicId(jsonChatRoom.get("last_topic_id").getAsInt());
qiscusChatRoom.setOptions(jsonChatRoom.get("options").isJsonNull() ? null : jsonChatRoom.get("options").getAsString());
qiscusChatRoom.setAvatarUrl(jsonChatRoom.get("avatar_url").getAsString());
JsonArray jsonMembers = jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("room").getAsJsonObject().get("participants").getAsJsonArray();
List<QiscusRoomMember> members = new ArrayList<>();
for (JsonElement jsonMember : jsonMembers) {
QiscusRoomMember member = new QiscusRoomMember();
member.setEmail(jsonMember.getAsJsonObject().get("email").getAsString());
member.setAvatar(jsonMember.getAsJsonObject().get("avatar_url").getAsString());
member.setUsername(jsonMember.getAsJsonObject().get("username").getAsString());
if (jsonMember.getAsJsonObject().has("last_comment_received_id")) {
member.setLastDeliveredCommentId(jsonMember.getAsJsonObject().get("last_comment_received_id").getAsInt());
}
if (jsonMember.getAsJsonObject().has("last_comment_read_id")) {
member.setLastReadCommentId(jsonMember.getAsJsonObject().get("last_comment_read_id").getAsInt());
}
members.add(member);
}
qiscusChatRoom.setMember(members);
JsonArray comments = jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray();
if (comments.size() > 0) {
JsonObject lastComment = comments.get(0).getAsJsonObject();
qiscusChatRoom.setLastCommentSender(lastComment.get("username").getAsString());
qiscusChatRoom.setLastCommentSenderEmail(lastComment.get("email").getAsString());
try {
qiscusChatRoom.setLastCommentTime(dateFormat.parse(lastComment.get("timestamp").getAsString()));
} catch (ParseException e) {
e.printStackTrace();
}
}
return qiscusChatRoom;
}
return null;
}
static List<QiscusChatRoom> parseQiscusChatRoomInfo(JsonElement jsonElement) {
if (jsonElement != null) {
JsonArray jsonRoomInfo = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("rooms_info").getAsJsonArray();
List<QiscusChatRoom> qiscusChatRooms = new ArrayList<>();
for (JsonElement jsonMember : jsonRoomInfo) {
QiscusChatRoom qiscusChatRoom = new QiscusChatRoom();
qiscusChatRoom.setLastCommentId(jsonMember.getAsJsonObject().get("last_comment_id").getAsInt());
qiscusChatRoom.setAvatarUrl(jsonMember.getAsJsonObject().get("room_avatar_url").getAsString());
qiscusChatRoom.setId(jsonMember.getAsJsonObject().get("room_id").getAsInt());
qiscusChatRoom.setName(jsonMember.getAsJsonObject().get("room_name").getAsString());
qiscusChatRoom.setLastCommentMessage(jsonMember.getAsJsonObject().get("last_comment_message").getAsString());
qiscusChatRoom.setUnreadCount(jsonMember.getAsJsonObject().get("unread_count").getAsInt());
try {
qiscusChatRoom.setLastCommentTime(dateFormat.parse(jsonMember.getAsJsonObject().get("last_comment_timestamp").getAsString()));
} catch (ParseException e) {
e.printStackTrace();
}
qiscusChatRooms.add(qiscusChatRoom);
}
return qiscusChatRooms;
}
return null;
}
static Pair<QiscusChatRoom, List<QiscusComment>> parseQiscusChatRoomWithComments(JsonElement jsonElement) {
if (jsonElement != null) {
QiscusChatRoom qiscusChatRoom = parseQiscusChatRoom(jsonElement);
JsonArray comments = jsonElement.getAsJsonObject().get("results").getAsJsonObject().get("comments").getAsJsonArray();
List<QiscusComment> qiscusComments = new ArrayList<>();
for (JsonElement jsonComment : comments) {
qiscusComments.add(parseQiscusComment(jsonComment, qiscusChatRoom.getId(), qiscusChatRoom.getLastTopicId()));
}
return Pair.create(qiscusChatRoom, qiscusComments);
}
return null;
}
static QiscusComment parseQiscusComment(JsonElement jsonElement, int roomId, int topicId) {
QiscusComment qiscusComment = new QiscusComment();
JsonObject jsonComment = jsonElement.getAsJsonObject();
qiscusComment.setTopicId(topicId);
qiscusComment.setRoomId(roomId);
qiscusComment.setId(jsonComment.get("id").getAsInt());
qiscusComment.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt());
qiscusComment.setMessage(jsonComment.get("message").getAsString());
qiscusComment.setSender(jsonComment.get("username").getAsString());
qiscusComment.setSenderEmail(jsonComment.get("email").getAsString());
qiscusComment.setSenderAvatar(jsonComment.get("user_avatar_url").getAsString());
qiscusComment.setState(QiscusComment.STATE_ON_QISCUS);
try {
qiscusComment.setTime(dateFormat.parse(jsonComment.get("timestamp").getAsString()));
} catch (ParseException e) {
e.printStackTrace();
}
if (jsonComment.has("room_name")) {
qiscusComment.setRoomName(jsonComment.get("room_name").getAsString());
}
if (jsonComment.has("chat_type")) {
qiscusComment.setGroupMessage(!"single".equals(jsonComment.get("chat_type").getAsString()));
}
if (jsonComment.has("unique_id")) {
qiscusComment.setUniqueId(jsonComment.get("unique_id").getAsString());
} else if (jsonComment.has("unique_temp_id")) {
qiscusComment.setUniqueId(jsonComment.get("unique_temp_id").getAsString());
} else {
qiscusComment.setUniqueId(String.valueOf(qiscusComment.getId()));
}
if (jsonComment.has("type")) {
qiscusComment.setRawType(jsonComment.get("type").getAsString());
qiscusComment.setExtraPayload(jsonComment.get("payload").toString());
if (qiscusComment.getType() == QiscusComment.Type.BUTTONS
|| qiscusComment.getType() == QiscusComment.Type.REPLY
|| qiscusComment.getType() == QiscusComment.Type.CARD) {
JsonObject payload = jsonComment.get("payload").getAsJsonObject();
if (payload.has("text")) {
String text = payload.get("text").getAsString();
if (text != null && !text.trim().isEmpty()) {
qiscusComment.setMessage(text.trim());
}
}
}
}
return qiscusComment;
}
}
| fix checkstyle travis
| chat/src/main/java/com/qiscus/sdk/data/remote/QiscusApiParser.java | fix checkstyle travis | <ide><path>hat/src/main/java/com/qiscus/sdk/data/remote/QiscusApiParser.java
<ide> qiscusChatRoom.setUnreadCount(jsonMember.getAsJsonObject().get("unread_count").getAsInt());
<ide>
<ide> try {
<del> qiscusChatRoom.setLastCommentTime(dateFormat.parse(jsonMember.getAsJsonObject().get("last_comment_timestamp").getAsString()));
<add> qiscusChatRoom.setLastCommentTime(dateFormat.parse(jsonMember.getAsJsonObject()
<add> .get("last_comment_timestamp").getAsString()));
<ide> } catch (ParseException e) {
<ide> e.printStackTrace();
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/basic/number/MaxProductFromIntegerBreak.java' did not match any file(s) known to git
| 838abccaf4efbc9b5b34aad607dcc4bbc125a23a | 1 | zhou-jg/Algorithm | package basic.number;
import java.util.ArrayList;
import java.util.List;
/**
* Source: https://leetcode.com/problems/integer-break/
*
* <p>Given a positive integer n, break it into the sum of at least
* two positive integers and maximize the product of those integers.
* Return the maximum product you can get.
*
* <p>For example, given n = 2, return 1 (2 = 1 + 1);
* given n = 10, return 36 (10 = 3 + 3 + 4).
* <p>Note: You may assume that n is not less than 2 and not larger than 58.
* <p>Hint:
* There is a simple O(n) solution to this problem. You may check the
* breaking results of n ranging from 7 to 10 to discover the regularities.
*
* @author Jingang Zhou
*
*/
public class MaxProductFromIntegerBreak {
public int integerBreak(int n) {
List<Integer> vals = new ArrayList<>();
if (n == 2){
return 1;
}else if (n ==3){
return 2;
}else if (n == 4){
return 4;
}else{
while (n >= 5){
vals.add(3);
n -= 3;
}
for (int val :vals){
n *= val;
}
return n;
}
}
}
| src/basic/number/MaxProductFromIntegerBreak.java | 从一个整数的和分解中获得最大的乘积数 | src/basic/number/MaxProductFromIntegerBreak.java | 从一个整数的和分解中获得最大的乘积数 | <ide><path>rc/basic/number/MaxProductFromIntegerBreak.java
<add>package basic.number;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>/**
<add> * Source: https://leetcode.com/problems/integer-break/
<add> *
<add> * <p>Given a positive integer n, break it into the sum of at least
<add> * two positive integers and maximize the product of those integers.
<add> * Return the maximum product you can get.
<add> *
<add> * <p>For example, given n = 2, return 1 (2 = 1 + 1);
<add> * given n = 10, return 36 (10 = 3 + 3 + 4).
<add>
<add> * <p>Note: You may assume that n is not less than 2 and not larger than 58.
<add>
<add> * <p>Hint:
<add>
<add> * There is a simple O(n) solution to this problem. You may check the
<add> * breaking results of n ranging from 7 to 10 to discover the regularities.
<add> *
<add> * @author Jingang Zhou
<add> *
<add> */
<add>public class MaxProductFromIntegerBreak {
<add> public int integerBreak(int n) {
<add> List<Integer> vals = new ArrayList<>();
<add> if (n == 2){
<add> return 1;
<add> }else if (n ==3){
<add> return 2;
<add> }else if (n == 4){
<add> return 4;
<add> }else{
<add> while (n >= 5){
<add> vals.add(3);
<add> n -= 3;
<add> }
<add> for (int val :vals){
<add> n *= val;
<add> }
<add> return n;
<add> }
<add> }
<add>} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.